]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Writer.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302418, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Writer.cpp
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Writer.h"
11 #include "Config.h"
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
14 #include "MapFile.h"
15 #include "Memory.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "Strings.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "Threads.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <climits>
28
29 using namespace llvm;
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
34
35 using namespace lld;
36 using namespace lld::elf;
37
38 namespace {
39 // The writer writes a SymbolTable result to a file.
40 template <class ELFT> class Writer {
41 public:
42   typedef typename ELFT::Shdr Elf_Shdr;
43   typedef typename ELFT::Ehdr Elf_Ehdr;
44   typedef typename ELFT::Phdr Elf_Phdr;
45
46   void run();
47
48 private:
49   void createSyntheticSections();
50   void copyLocalSymbols();
51   void addSectionSymbols();
52   void addReservedSymbols();
53   void createSections();
54   void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
55   void sortSections();
56   void finalizeSections();
57   void addPredefinedSections();
58
59   std::vector<PhdrEntry> createPhdrs();
60   void removeEmptyPTLoad();
61   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
62   void assignFileOffsets();
63   void assignFileOffsetsBinary();
64   void setPhdrs();
65   void fixSectionAlignments();
66   void fixPredefinedSymbols();
67   void openFile();
68   void writeHeader();
69   void writeSections();
70   void writeSectionsBinary();
71   void writeBuildId();
72
73   std::unique_ptr<FileOutputBuffer> Buffer;
74
75   std::vector<OutputSection *> OutputSections;
76   OutputSectionFactory Factory{OutputSections};
77
78   void addRelIpltSymbols();
79   void addStartEndSymbols();
80   void addStartStopSymbols(OutputSection *Sec);
81   uint64_t getEntryAddr();
82   OutputSection *findSection(StringRef Name);
83
84   std::vector<PhdrEntry> Phdrs;
85
86   uint64_t FileSize;
87   uint64_t SectionHeaderOff;
88 };
89 } // anonymous namespace
90
91 StringRef elf::getOutputSectionName(StringRef Name) {
92   if (Config->Relocatable)
93     return Name;
94
95   // If -emit-relocs is given (which is rare), we need to copy
96   // relocation sections to the output. If input section .foo is
97   // output as .bar, we want to rename .rel.foo .rel.bar as well.
98   if (Config->EmitRelocs) {
99     for (StringRef V : {".rel.", ".rela."}) {
100       if (Name.startswith(V)) {
101         StringRef Inner = getOutputSectionName(Name.substr(V.size() - 1));
102         return Saver.save(V.drop_back() + Inner);
103       }
104     }
105   }
106
107   for (StringRef V :
108        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
109         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
110         ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
111     StringRef Prefix = V.drop_back();
112     if (Name.startswith(V) || Name == Prefix)
113       return Prefix;
114   }
115
116   // CommonSection is identified as "COMMON" in linker scripts.
117   // By default, it should go to .bss section.
118   if (Name == "COMMON")
119     return ".bss";
120
121   // ".zdebug_" is a prefix for ZLIB-compressed sections.
122   // Because we decompressed input sections, we want to remove 'z'.
123   if (Name.startswith(".zdebug_"))
124     return Saver.save("." + Name.substr(2));
125   return Name;
126 }
127
128 template <class ELFT> static bool needsInterpSection() {
129   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
130          !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
131 }
132
133 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
134
135 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
136   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
137     if (P.p_type != PT_LOAD)
138       return false;
139     if (!P.First)
140       return true;
141     uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
142     return Size == 0;
143   });
144   Phdrs.erase(I, Phdrs.end());
145 }
146
147 // This function scans over the input sections and creates mergeable
148 // synthetic sections. It removes MergeInputSections from array and
149 // adds new synthetic ones. Each synthetic section is added to the
150 // location of the first input section it replaces.
151 static void combineMergableSections() {
152   std::vector<MergeSyntheticSection *> MergeSections;
153   for (InputSectionBase *&S : InputSections) {
154     MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
155     if (!MS)
156       continue;
157
158     // We do not want to handle sections that are not alive, so just remove
159     // them instead of trying to merge.
160     if (!MS->Live)
161       continue;
162
163     StringRef OutsecName = getOutputSectionName(MS->Name);
164     uint64_t Flags = MS->Flags & ~(uint64_t)(SHF_GROUP | SHF_COMPRESSED);
165     uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
166
167     auto I =
168         llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
169           return Sec->Name == OutsecName && Sec->Flags == Flags &&
170                  Sec->Alignment == Alignment;
171         });
172     if (I == MergeSections.end()) {
173       MergeSyntheticSection *Syn =
174           make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
175       MergeSections.push_back(Syn);
176       I = std::prev(MergeSections.end());
177       S = Syn;
178     } else {
179       S = nullptr;
180     }
181     (*I)->addSection(MS);
182   }
183
184   std::vector<InputSectionBase *> &V = InputSections;
185   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
186 }
187
188 template <class ELFT> static void combineEhFrameSections() {
189   for (InputSectionBase *&S : InputSections) {
190     EhInputSection *ES = dyn_cast<EhInputSection>(S);
191     if (!ES || !ES->Live)
192       continue;
193
194     In<ELFT>::EhFrame->addSection(ES);
195     S = nullptr;
196   }
197
198   std::vector<InputSectionBase *> &V = InputSections;
199   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
200 }
201
202 // The main function of the writer.
203 template <class ELFT> void Writer<ELFT>::run() {
204   // Create linker-synthesized sections such as .got or .plt.
205   // Such sections are of type input section.
206   createSyntheticSections();
207   combineMergableSections();
208
209   if (!Config->Relocatable)
210     combineEhFrameSections<ELFT>();
211
212   // We need to create some reserved symbols such as _end. Create them.
213   if (!Config->Relocatable)
214     addReservedSymbols();
215
216   // Create output sections.
217   Script->OutputSections = &OutputSections;
218   if (Script->Opt.HasSections) {
219     // If linker script contains SECTIONS commands, let it create sections.
220     Script->processCommands(Factory);
221
222     // Linker scripts may have left some input sections unassigned.
223     // Assign such sections using the default rule.
224     Script->addOrphanSections(Factory);
225   } else {
226     // If linker script does not contain SECTIONS commands, create
227     // output sections by default rules. We still need to give the
228     // linker script a chance to run, because it might contain
229     // non-SECTIONS commands such as ASSERT.
230     createSections();
231     Script->processCommands(Factory);
232   }
233
234   if (Config->Discard != DiscardPolicy::All)
235     copyLocalSymbols();
236
237   if (Config->CopyRelocs)
238     addSectionSymbols();
239
240   // Now that we have a complete set of output sections. This function
241   // completes section contents. For example, we need to add strings
242   // to the string table, and add entries to .got and .plt.
243   // finalizeSections does that.
244   finalizeSections();
245   if (ErrorCount)
246     return;
247
248   if (Config->Relocatable) {
249     assignFileOffsets();
250   } else {
251     if (!Script->Opt.HasSections) {
252       fixSectionAlignments();
253       Script->fabricateDefaultCommands();
254     }
255     Script->synchronize();
256     Script->assignAddresses(Phdrs);
257
258     // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
259     // 0 sized region. This has to be done late since only after assignAddresses
260     // we know the size of the sections.
261     removeEmptyPTLoad();
262
263     if (!Config->OFormatBinary)
264       assignFileOffsets();
265     else
266       assignFileOffsetsBinary();
267
268     setPhdrs();
269     fixPredefinedSymbols();
270   }
271
272   // It does not make sense try to open the file if we have error already.
273   if (ErrorCount)
274     return;
275   // Write the result down to a file.
276   openFile();
277   if (ErrorCount)
278     return;
279   if (!Config->OFormatBinary) {
280     writeHeader();
281     writeSections();
282   } else {
283     writeSectionsBinary();
284   }
285
286   // Backfill .note.gnu.build-id section content. This is done at last
287   // because the content is usually a hash value of the entire output file.
288   writeBuildId();
289   if (ErrorCount)
290     return;
291
292   // Handle -Map option.
293   writeMapFile<ELFT>(OutputSections);
294   if (ErrorCount)
295     return;
296
297   if (auto EC = Buffer->commit())
298     error("failed to write to the output file: " + EC.message());
299
300   // Flush the output streams and exit immediately. A full shutdown
301   // is a good test that we are keeping track of all allocated memory,
302   // but actually freeing it is a waste of time in a regular linker run.
303   if (Config->ExitEarly)
304     exitLld(0);
305 }
306
307 // Initialize Out members.
308 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
309   // Initialize all pointers with NULL. This is needed because
310   // you can call lld::elf::main more than once as a library.
311   memset(&Out::First, 0, sizeof(Out));
312
313   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
314
315   In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true);
316   In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
317   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
318       Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
319   In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false);
320
321   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
322   Out::ElfHeader->Size = sizeof(Elf_Ehdr);
323   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
324   Out::ProgramHeaders->updateAlignment(Config->Wordsize);
325
326   if (needsInterpSection<ELFT>()) {
327     In<ELFT>::Interp = createInterpSection();
328     Add(In<ELFT>::Interp);
329   } else {
330     In<ELFT>::Interp = nullptr;
331   }
332
333   if (!Config->Relocatable)
334     Add(createCommentSection<ELFT>());
335
336   if (Config->Strip != StripPolicy::All) {
337     In<ELFT>::StrTab = make<StringTableSection>(".strtab", false);
338     In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
339   }
340
341   if (Config->BuildId != BuildIdKind::None) {
342     In<ELFT>::BuildId = make<BuildIdSection>();
343     Add(In<ELFT>::BuildId);
344   }
345
346   In<ELFT>::Common = createCommonSection<ELFT>();
347   if (In<ELFT>::Common)
348     Add(InX::Common);
349
350   In<ELFT>::Bss = make<BssSection>(".bss");
351   Add(In<ELFT>::Bss);
352   In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro");
353   Add(In<ELFT>::BssRelRo);
354
355   // Add MIPS-specific sections.
356   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
357                       Config->Pic || Config->ExportDynamic;
358   if (Config->EMachine == EM_MIPS) {
359     if (!Config->Shared && HasDynSymTab) {
360       In<ELFT>::MipsRldMap = make<MipsRldMapSection>();
361       Add(In<ELFT>::MipsRldMap);
362     }
363     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
364       Add(Sec);
365     if (auto *Sec = MipsOptionsSection<ELFT>::create())
366       Add(Sec);
367     if (auto *Sec = MipsReginfoSection<ELFT>::create())
368       Add(Sec);
369   }
370
371   if (HasDynSymTab) {
372     In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
373     Add(In<ELFT>::DynSymTab);
374
375     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
376     Add(In<ELFT>::VerSym);
377
378     if (!Config->VersionDefinitions.empty()) {
379       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
380       Add(In<ELFT>::VerDef);
381     }
382
383     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
384     Add(In<ELFT>::VerNeed);
385
386     if (Config->GnuHash) {
387       In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
388       Add(In<ELFT>::GnuHashTab);
389     }
390
391     if (Config->SysvHash) {
392       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
393       Add(In<ELFT>::HashTab);
394     }
395
396     Add(In<ELFT>::Dynamic);
397     Add(In<ELFT>::DynStrTab);
398     Add(In<ELFT>::RelaDyn);
399   }
400
401   // Add .got. MIPS' .got is so different from the other archs,
402   // it has its own class.
403   if (Config->EMachine == EM_MIPS) {
404     In<ELFT>::MipsGot = make<MipsGotSection>();
405     Add(In<ELFT>::MipsGot);
406   } else {
407     In<ELFT>::Got = make<GotSection<ELFT>>();
408     Add(In<ELFT>::Got);
409   }
410
411   In<ELFT>::GotPlt = make<GotPltSection>();
412   Add(In<ELFT>::GotPlt);
413   In<ELFT>::IgotPlt = make<IgotPltSection>();
414   Add(In<ELFT>::IgotPlt);
415
416   if (Config->GdbIndex) {
417     In<ELFT>::GdbIndex = make<GdbIndexSection>();
418     Add(In<ELFT>::GdbIndex);
419   }
420
421   // We always need to add rel[a].plt to output if it has entries.
422   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
423   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
424       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
425   Add(In<ELFT>::RelaPlt);
426
427   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
428   // that the IRelative relocations are processed last by the dynamic loader
429   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
430       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
431       false /*Sort*/);
432   Add(In<ELFT>::RelaIplt);
433
434   In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize);
435   Add(In<ELFT>::Plt);
436   In<ELFT>::Iplt = make<PltSection>(0);
437   Add(In<ELFT>::Iplt);
438
439   if (!Config->Relocatable) {
440     if (Config->EhFrameHdr) {
441       In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
442       Add(In<ELFT>::EhFrameHdr);
443     }
444     In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
445     Add(In<ELFT>::EhFrame);
446   }
447
448   if (In<ELFT>::SymTab)
449     Add(In<ELFT>::SymTab);
450   Add(In<ELFT>::ShStrTab);
451   if (In<ELFT>::StrTab)
452     Add(In<ELFT>::StrTab);
453 }
454
455 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
456                                const SymbolBody &B) {
457   if (B.isFile() || B.isSection())
458     return false;
459
460   // If sym references a section in a discarded group, don't keep it.
461   if (Sec == &InputSection::Discarded)
462     return false;
463
464   if (Config->Discard == DiscardPolicy::None)
465     return true;
466
467   // In ELF assembly .L symbols are normally discarded by the assembler.
468   // If the assembler fails to do so, the linker discards them if
469   // * --discard-locals is used.
470   // * The symbol is in a SHF_MERGE section, which is normally the reason for
471   //   the assembler keeping the .L symbol.
472   if (!SymName.startswith(".L") && !SymName.empty())
473     return true;
474
475   if (Config->Discard == DiscardPolicy::Locals)
476     return false;
477
478   return !Sec || !(Sec->Flags & SHF_MERGE);
479 }
480
481 static bool includeInSymtab(const SymbolBody &B) {
482   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
483     return false;
484
485   if (auto *D = dyn_cast<DefinedRegular>(&B)) {
486     // Always include absolute symbols.
487     SectionBase *Sec = D->Section;
488     if (!Sec)
489       return true;
490     if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
491       Sec = IS->Repl;
492       IS = cast<InputSectionBase>(Sec);
493       // Exclude symbols pointing to garbage-collected sections.
494       if (!IS->Live)
495         return false;
496     }
497     if (auto *S = dyn_cast<MergeInputSection>(Sec))
498       if (!S->getSectionPiece(D->Value)->Live)
499         return false;
500   }
501   return true;
502 }
503
504 // Local symbols are not in the linker's symbol table. This function scans
505 // each object file's symbol table to copy local symbols to the output.
506 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
507   if (!In<ELFT>::SymTab)
508     return;
509   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
510     for (SymbolBody *B : F->getLocalSymbols()) {
511       if (!B->IsLocal)
512         fatal(toString(F) +
513               ": broken object: getLocalSymbols returns a non-local symbol");
514       auto *DR = dyn_cast<DefinedRegular>(B);
515
516       // No reason to keep local undefined symbol in symtab.
517       if (!DR)
518         continue;
519       if (!includeInSymtab(*B))
520         continue;
521
522       SectionBase *Sec = DR->Section;
523       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
524         continue;
525       In<ELFT>::SymTab->addSymbol(B);
526     }
527   }
528 }
529
530 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
531   // Create one STT_SECTION symbol for each output section we might
532   // have a relocation with.
533   for (OutputSection *Sec : OutputSections) {
534     if (Sec->Sections.empty())
535       continue;
536
537     InputSection *IS = Sec->Sections[0];
538     if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
539         IS->Type == SHT_RELA)
540       continue;
541
542     auto *Sym =
543         make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
544                              /*Value=*/0, /*Size=*/0, IS, nullptr);
545     In<ELFT>::SymTab->addSymbol(Sym);
546   }
547 }
548
549 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
550 // we would like to make sure appear is a specific order to maximize their
551 // coverage by a single signed 16-bit offset from the TOC base pointer.
552 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
553 // sections. This will put it next to the loaded special PPC64 sections (and,
554 // thus, within reach of the TOC base pointer).
555 static int getPPC64SectionRank(StringRef SectionName) {
556   return StringSwitch<int>(SectionName)
557       .Case(".tocbss", 0)
558       .Case(".branch_lt", 2)
559       .Case(".toc", 3)
560       .Case(".toc1", 4)
561       .Case(".opd", 5)
562       .Default(1);
563 }
564
565 // All sections with SHF_MIPS_GPREL flag should be grouped together
566 // because data in these sections is addressable with a gp relative address.
567 static int getMipsSectionRank(const OutputSection *S) {
568   if ((S->Flags & SHF_MIPS_GPREL) == 0)
569     return 0;
570   if (S->Name == ".got")
571     return 1;
572   return 2;
573 }
574
575 // Today's loaders have a feature to make segments read-only after
576 // processing dynamic relocations to enhance security. PT_GNU_RELRO
577 // is defined for that.
578 //
579 // This function returns true if a section needs to be put into a
580 // PT_GNU_RELRO segment.
581 template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) {
582   if (!Config->ZRelro)
583     return false;
584
585   uint64_t Flags = Sec->Flags;
586
587   // Non-allocatable or non-writable sections don't need RELRO because
588   // they are not writable or not even mapped to memory in the first place.
589   // RELRO is for sections that are essentially read-only but need to
590   // be writable only at process startup to allow dynamic linker to
591   // apply relocations.
592   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
593     return false;
594
595   // Once initialized, TLS data segments are used as data templates
596   // for a thread-local storage. For each new thread, runtime
597   // allocates memory for a TLS and copy templates there. No thread
598   // are supposed to use templates directly. Thus, it can be in RELRO.
599   if (Flags & SHF_TLS)
600     return true;
601
602   // .init_array, .preinit_array and .fini_array contain pointers to
603   // functions that are executed on process startup or exit. These
604   // pointers are set by the static linker, and they are not expected
605   // to change at runtime. But if you are an attacker, you could do
606   // interesting things by manipulating pointers in .fini_array, for
607   // example. So they are put into RELRO.
608   uint32_t Type = Sec->Type;
609   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
610       Type == SHT_PREINIT_ARRAY)
611     return true;
612
613   // .got contains pointers to external symbols. They are resolved by
614   // the dynamic linker when a module is loaded into memory, and after
615   // that they are not expected to change. So, it can be in RELRO.
616   if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
617     return true;
618
619   // .got.plt contains pointers to external function symbols. They are
620   // by default resolved lazily, so we usually cannot put it into RELRO.
621   // However, if "-z now" is given, the lazy symbol resolution is
622   // disabled, which enables us to put it into RELRO.
623   if (Sec == In<ELFT>::GotPlt->OutSec)
624     return Config->ZNow;
625
626   // .dynamic section contains data for the dynamic linker, and
627   // there's no need to write to it at runtime, so it's better to put
628   // it into RELRO.
629   if (Sec == In<ELFT>::Dynamic->OutSec)
630     return true;
631
632   // .bss.rel.ro is used for copy relocations for read-only symbols.
633   // Since the dynamic linker needs to process copy relocations, the
634   // section cannot be read-only, but once initialized, they shouldn't
635   // change.
636   if (Sec == In<ELFT>::BssRelRo->OutSec)
637     return true;
638
639   // Sections with some special names are put into RELRO. This is a
640   // bit unfortunate because section names shouldn't be significant in
641   // ELF in spirit. But in reality many linker features depend on
642   // magic section names.
643   StringRef S = Sec->Name;
644   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
645          S == ".eh_frame" || S == ".openbsd.randomdata";
646 }
647
648 template <class ELFT>
649 static bool compareSectionsNonScript(const OutputSection *A,
650                                      const OutputSection *B) {
651   // Put .interp first because some loaders want to see that section
652   // on the first page of the executable file when loaded into memory.
653   bool AIsInterp = A->Name == ".interp";
654   bool BIsInterp = B->Name == ".interp";
655   if (AIsInterp != BIsInterp)
656     return AIsInterp;
657
658   // Allocatable sections go first to reduce the total PT_LOAD size and
659   // so debug info doesn't change addresses in actual code.
660   bool AIsAlloc = A->Flags & SHF_ALLOC;
661   bool BIsAlloc = B->Flags & SHF_ALLOC;
662   if (AIsAlloc != BIsAlloc)
663     return AIsAlloc;
664
665   // We don't have any special requirements for the relative order of two non
666   // allocatable sections.
667   if (!AIsAlloc)
668     return false;
669
670   // We want to put section specified by -T option first, so we
671   // can start assigning VA starting from them later.
672   auto AAddrSetI = Config->SectionStartMap.find(A->Name);
673   auto BAddrSetI = Config->SectionStartMap.find(B->Name);
674   bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
675   bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
676   if (AHasAddrSet != BHasAddrSet)
677     return AHasAddrSet;
678   if (AHasAddrSet)
679     return AAddrSetI->second < BAddrSetI->second;
680
681   // We want the read only sections first so that they go in the PT_LOAD
682   // covering the program headers at the start of the file.
683   bool AIsWritable = A->Flags & SHF_WRITE;
684   bool BIsWritable = B->Flags & SHF_WRITE;
685   if (AIsWritable != BIsWritable)
686     return BIsWritable;
687
688   if (!Config->SingleRoRx) {
689     // For a corresponding reason, put non exec sections first (the program
690     // header PT_LOAD is not executable).
691     // We only do that if we are not using linker scripts, since with linker
692     // scripts ro and rx sections are in the same PT_LOAD, so their relative
693     // order is not important. The same applies for -no-rosegment.
694     bool AIsExec = A->Flags & SHF_EXECINSTR;
695     bool BIsExec = B->Flags & SHF_EXECINSTR;
696     if (AIsExec != BIsExec)
697       return BIsExec;
698   }
699
700   // If we got here we know that both A and B are in the same PT_LOAD.
701
702   bool AIsTls = A->Flags & SHF_TLS;
703   bool BIsTls = B->Flags & SHF_TLS;
704   bool AIsNoBits = A->Type == SHT_NOBITS;
705   bool BIsNoBits = B->Type == SHT_NOBITS;
706
707   // The first requirement we have is to put (non-TLS) nobits sections last. The
708   // reason is that the only thing the dynamic linker will see about them is a
709   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
710   // PT_LOAD, so that has to correspond to the nobits sections.
711   bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
712   bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
713   if (AIsNonTlsNoBits != BIsNonTlsNoBits)
714     return BIsNonTlsNoBits;
715
716   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
717   // sections after r/w ones, so that the RelRo sections are contiguous.
718   bool AIsRelRo = isRelroSection<ELFT>(A);
719   bool BIsRelRo = isRelroSection<ELFT>(B);
720   if (AIsRelRo != BIsRelRo)
721     return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
722
723   // The TLS initialization block needs to be a single contiguous block in a R/W
724   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
725   // sections. The TLS NOBITS sections are placed here as they don't take up
726   // virtual address space in the PT_LOAD.
727   if (AIsTls != BIsTls)
728     return AIsTls;
729
730   // Within the TLS initialization block, the non-nobits sections need to appear
731   // first.
732   if (AIsNoBits != BIsNoBits)
733     return BIsNoBits;
734
735   // Some architectures have additional ordering restrictions for sections
736   // within the same PT_LOAD.
737   if (Config->EMachine == EM_PPC64)
738     return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name);
739   if (Config->EMachine == EM_MIPS)
740     return getMipsSectionRank(A) < getMipsSectionRank(B);
741
742   return false;
743 }
744
745 // Output section ordering is determined by this function.
746 template <class ELFT>
747 static bool compareSections(const OutputSection *A, const OutputSection *B) {
748   // For now, put sections mentioned in a linker script
749   // first. Sections not on linker script will have a SectionIndex of
750   // INT_MAX.
751   int AIndex = A->SectionIndex;
752   int BIndex = B->SectionIndex;
753   if (AIndex != BIndex)
754     return AIndex < BIndex;
755
756   return compareSectionsNonScript<ELFT>(A, B);
757 }
758
759 // Program header entry
760 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
761   p_type = Type;
762   p_flags = Flags;
763 }
764
765 void PhdrEntry::add(OutputSection *Sec) {
766   Last = Sec;
767   if (!First)
768     First = Sec;
769   p_align = std::max(p_align, Sec->Alignment);
770   if (p_type == PT_LOAD)
771     Sec->FirstInPtLoad = First;
772 }
773
774 template <class ELFT>
775 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
776                           uint8_t StOther = STV_HIDDEN,
777                           uint8_t Binding = STB_WEAK) {
778   // The linker generated symbols are added as STB_WEAK to allow user defined
779   // ones to override them.
780   return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
781                                      /*Size=*/0, Binding, Sec,
782                                      /*File=*/nullptr);
783 }
784
785 template <class ELFT>
786 static DefinedRegular *
787 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
788                    uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
789   SymbolBody *S = Symtab<ELFT>::X->find(Name);
790   if (!S)
791     return nullptr;
792   if (S->isInCurrentDSO())
793     return nullptr;
794   return cast<DefinedRegular>(
795       addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
796 }
797
798 // The beginning and the ending of .rel[a].plt section are marked
799 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
800 // executable. The runtime needs these symbols in order to resolve
801 // all IRELATIVE relocs on startup. For dynamic executables, we don't
802 // need these symbols, since IRELATIVE relocs are resolved through GOT
803 // and PLT. For details, see http://www.airs.com/blog/archives/403.
804 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
805   if (In<ELFT>::DynSymTab)
806     return;
807   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
808   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
809
810   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
811   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
812 }
813
814 // The linker is expected to define some symbols depending on
815 // the linking result. This function defines such symbols.
816 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
817   if (Config->EMachine == EM_MIPS) {
818     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
819     // so that it points to an absolute address which by default is relative
820     // to GOT. Default offset is 0x7ff0.
821     // See "Global Data Symbols" in Chapter 6 in the following document:
822     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
823     ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
824
825     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
826     // start of function and 'gp' pointer into GOT.
827     if (Symtab<ELFT>::X->find("_gp_disp"))
828       ElfSym::MipsGpDisp =
829           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
830
831     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
832     // pointer. This symbol is used in the code generated by .cpload pseudo-op
833     // in case of using -mno-shared option.
834     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
835     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
836       ElfSym::MipsLocalGp =
837           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
838   }
839
840   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
841   // is magical and is used to produce a R_386_GOTPC relocation.
842   // The R_386_GOTPC relocation value doesn't actually depend on the
843   // symbol value, so it could use an index of STN_UNDEF which, according
844   // to the spec, means the symbol value is 0.
845   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
846   // the object file.
847   // The situation is even stranger on x86_64 where the assembly doesn't
848   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
849   // an undefined symbol in the .o files.
850   // Given that the symbol is effectively unused, we just create a dummy
851   // hidden one to avoid the undefined symbol error.
852   Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
853
854   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
855   // static linking the linker is required to optimize away any references to
856   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
857   // to avoid the undefined symbol error.
858   if (!In<ELFT>::DynSymTab)
859     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
860
861   // If linker script do layout we do not need to create any standart symbols.
862   if (Script->Opt.HasSections)
863     return;
864
865   // __ehdr_start is the location of ELF file headers.
866   addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
867
868   auto Add = [](StringRef S) {
869     return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
870   };
871
872   ElfSym::Bss = Add("__bss_start");
873   ElfSym::End1 = Add("end");
874   ElfSym::End2 = Add("_end");
875   ElfSym::Etext1 = Add("etext");
876   ElfSym::Etext2 = Add("_etext");
877   ElfSym::Edata1 = Add("edata");
878   ElfSym::Edata2 = Add("_edata");
879 }
880
881 // Sort input sections by section name suffixes for
882 // __attribute__((init_priority(N))).
883 static void sortInitFini(OutputSection *S) {
884   if (S)
885     reinterpret_cast<OutputSection *>(S)->sortInitFini();
886 }
887
888 // Sort input sections by the special rule for .ctors and .dtors.
889 static void sortCtorsDtors(OutputSection *S) {
890   if (S)
891     reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
892 }
893
894 // Sort input sections using the list provided by --symbol-ordering-file.
895 template <class ELFT>
896 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
897   if (Config->SymbolOrderingFile.empty())
898     return;
899
900   // Build a map from symbols to their priorities. Symbols that didn't
901   // appear in the symbol ordering file have the lowest priority 0.
902   // All explicitly mentioned symbols have negative (higher) priorities.
903   DenseMap<StringRef, int> SymbolOrder;
904   int Priority = -Config->SymbolOrderingFile.size();
905   for (StringRef S : Config->SymbolOrderingFile)
906     SymbolOrder.insert({S, Priority++});
907
908   // Build a map from sections to their priorities.
909   DenseMap<SectionBase *, int> SectionOrder;
910   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
911     for (SymbolBody *Body : File->getSymbols()) {
912       auto *D = dyn_cast<DefinedRegular>(Body);
913       if (!D || !D->Section)
914         continue;
915       int &Priority = SectionOrder[D->Section];
916       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
917     }
918   }
919
920   // Sort sections by priority.
921   for (OutputSection *Base : OutputSections)
922     if (auto *Sec = dyn_cast<OutputSection>(Base))
923       Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
924 }
925
926 template <class ELFT>
927 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
928   for (InputSectionBase *IS : InputSections) {
929     if (!IS->Live)
930       continue;
931     // Scan all relocations. Each relocation goes through a series
932     // of tests to determine if it needs special treatment, such as
933     // creating GOT, PLT, copy relocations, etc.
934     // Note that relocations for non-alloc sections are directly
935     // processed by InputSection::relocateNonAlloc.
936     if (!(IS->Flags & SHF_ALLOC))
937       continue;
938     if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
939       Fn(*IS);
940   }
941
942   if (!Config->Relocatable) {
943     for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
944       Fn(*ES);
945   }
946 }
947
948 template <class ELFT> void Writer<ELFT>::createSections() {
949   for (InputSectionBase *IS : InputSections)
950     if (IS)
951       Factory.addInputSec(IS, getOutputSectionName(IS->Name));
952
953   sortBySymbolsOrder<ELFT>(OutputSections);
954   sortInitFini(findSection(".init_array"));
955   sortInitFini(findSection(".fini_array"));
956   sortCtorsDtors(findSection(".ctors"));
957   sortCtorsDtors(findSection(".dtors"));
958
959   for (OutputSection *Sec : OutputSections)
960     Sec->assignOffsets();
961 }
962
963 static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) {
964   if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
965     return false;
966
967   bool S1IsWrite = S1.Flags & SHF_WRITE;
968   bool S2IsWrite = S2.Flags & SHF_WRITE;
969   if (S1IsWrite != S2IsWrite)
970     return false;
971
972   if (!S1IsWrite)
973     return true; // RO and RX share a PT_LOAD with linker scripts.
974   return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
975 }
976
977 template <class ELFT> void Writer<ELFT>::sortSections() {
978   // Don't sort if using -r. It is not necessary and we want to preserve the
979   // relative order for SHF_LINK_ORDER sections.
980   if (Config->Relocatable)
981     return;
982   if (!Script->Opt.HasSections) {
983     std::stable_sort(OutputSections.begin(), OutputSections.end(),
984                      compareSectionsNonScript<ELFT>);
985     return;
986   }
987   Script->adjustSectionsBeforeSorting();
988
989   // The order of the sections in the script is arbitrary and may not agree with
990   // compareSectionsNonScript. This means that we cannot easily define a
991   // strict weak ordering. To see why, consider a comparison of a section in the
992   // script and one not in the script. We have a two simple options:
993   // * Make them equivalent (a is not less than b, and b is not less than a).
994   //   The problem is then that equivalence has to be transitive and we can
995   //   have sections a, b and c with only b in a script and a less than c
996   //   which breaks this property.
997   // * Use compareSectionsNonScript. Given that the script order doesn't have
998   //   to match, we can end up with sections a, b, c, d where b and c are in the
999   //   script and c is compareSectionsNonScript less than b. In which case d
1000   //   can be equivalent to c, a to b and d < a. As a concrete example:
1001   //   .a (rx) # not in script
1002   //   .b (rx) # in script
1003   //   .c (ro) # in script
1004   //   .d (ro) # not in script
1005   //
1006   // The way we define an order then is:
1007   // *  First put script sections at the start and sort the script and
1008   //    non-script sections independently.
1009   // *  Move each non-script section to its preferred position. We try
1010   //    to put each section in the last position where it it can share
1011   //    a PT_LOAD.
1012
1013   std::stable_sort(OutputSections.begin(), OutputSections.end(),
1014                    compareSections<ELFT>);
1015
1016   auto I = OutputSections.begin();
1017   auto E = OutputSections.end();
1018   auto NonScriptI =
1019       std::find_if(OutputSections.begin(), E,
1020                    [](OutputSection *S) { return S->SectionIndex == INT_MAX; });
1021   while (NonScriptI != E) {
1022     auto BestPos = std::max_element(
1023         I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) {
1024           bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A);
1025           bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B);
1026           if (ACanSharePtLoad != BCanSharePtLoad)
1027             return BCanSharePtLoad;
1028
1029           bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1030           bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1031           if (ACmp != BCmp)
1032             return BCmp; // FIXME: missing test
1033
1034           size_t PosA = &A - &OutputSections[0];
1035           size_t PosB = &B - &OutputSections[0];
1036           return ACmp ? PosA > PosB : PosA < PosB;
1037         });
1038
1039     // max_element only returns NonScriptI if the range is empty. If the range
1040     // is not empty we should consider moving the the element forward one
1041     // position.
1042     if (BestPos != NonScriptI &&
1043         !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1044       ++BestPos;
1045     std::rotate(BestPos, NonScriptI, NonScriptI + 1);
1046     ++NonScriptI;
1047   }
1048
1049   Script->adjustSectionsAfterSorting();
1050 }
1051
1052 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1053                            std::function<void(SyntheticSection *)> Fn) {
1054   for (SyntheticSection *SS : Sections)
1055     if (SS && SS->OutSec && !SS->empty()) {
1056       Fn(SS);
1057       SS->OutSec->assignOffsets();
1058     }
1059 }
1060
1061 // We need to add input synthetic sections early in createSyntheticSections()
1062 // to make them visible from linkescript side. But not all sections are always
1063 // required to be in output. For example we don't need dynamic section content
1064 // sometimes. This function filters out such unused sections from the output.
1065 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1066   // All input synthetic sections that can be empty are placed after
1067   // all regular ones. We iterate over them all and exit at first
1068   // non-synthetic.
1069   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1070     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1071     if (!SS)
1072       return;
1073     if (!SS->empty() || !SS->OutSec)
1074       continue;
1075
1076     SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1077                                          SS->OutSec->Sections.end(), SS));
1078     SS->Live = false;
1079     // If there are no other sections in the output section, remove it from the
1080     // output.
1081     if (SS->OutSec->Sections.empty())
1082       V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1083   }
1084 }
1085
1086 // Create output section objects and add them to OutputSections.
1087 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1088   Out::DebugInfo = findSection(".debug_info");
1089   Out::PreinitArray = findSection(".preinit_array");
1090   Out::InitArray = findSection(".init_array");
1091   Out::FiniArray = findSection(".fini_array");
1092
1093   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1094   // symbols for sections, so that the runtime can get the start and end
1095   // addresses of each section by section name. Add such symbols.
1096   if (!Config->Relocatable) {
1097     addStartEndSymbols();
1098     for (OutputSection *Sec : OutputSections)
1099       addStartStopSymbols(Sec);
1100   }
1101
1102   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1103   // It should be okay as no one seems to care about the type.
1104   // Even the author of gold doesn't remember why gold behaves that way.
1105   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1106   if (In<ELFT>::DynSymTab)
1107     addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0);
1108
1109   // Define __rel[a]_iplt_{start,end} symbols if needed.
1110   addRelIpltSymbols();
1111
1112   // This responsible for splitting up .eh_frame section into
1113   // pieces. The relocation scan uses those pieces, so this has to be
1114   // earlier.
1115   applySynthetic({In<ELFT>::EhFrame},
1116                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1117
1118   // Scan relocations. This must be done after every symbol is declared so that
1119   // we can correctly decide if a dynamic relocation is needed.
1120   forEachRelSec(scanRelocations<ELFT>);
1121
1122   if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1123     In<ELFT>::Plt->addSymbols();
1124   if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1125     In<ELFT>::Iplt->addSymbols();
1126
1127   // Now that we have defined all possible global symbols including linker-
1128   // synthesized ones. Visit all symbols to give the finishing touches.
1129   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1130     SymbolBody *Body = S->body();
1131
1132     if (!includeInSymtab(*Body))
1133       continue;
1134     if (In<ELFT>::SymTab)
1135       In<ELFT>::SymTab->addSymbol(Body);
1136
1137     if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1138       In<ELFT>::DynSymTab->addSymbol(Body);
1139       if (auto *SS = dyn_cast<SharedSymbol>(Body))
1140         if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1141           In<ELFT>::VerNeed->addSymbol(SS);
1142     }
1143   }
1144
1145   // Do not proceed if there was an undefined symbol.
1146   if (ErrorCount)
1147     return;
1148
1149   // So far we have added sections from input object files.
1150   // This function adds linker-created Out::* sections.
1151   addPredefinedSections();
1152   removeUnusedSyntheticSections(OutputSections);
1153
1154   sortSections();
1155
1156   // This is a bit of a hack. A value of 0 means undef, so we set it
1157   // to 1 t make __ehdr_start defined. The section number is not
1158   // particularly relevant.
1159   Out::ElfHeader->SectionIndex = 1;
1160
1161   unsigned I = 1;
1162   for (OutputSection *Sec : OutputSections) {
1163     Sec->SectionIndex = I++;
1164     Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name);
1165   }
1166
1167   // Binary and relocatable output does not have PHDRS.
1168   // The headers have to be created before finalize as that can influence the
1169   // image base and the dynamic section on mips includes the image base.
1170   if (!Config->Relocatable && !Config->OFormatBinary) {
1171     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1172     addPtArmExid(Phdrs);
1173     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1174   }
1175
1176   // Dynamic section must be the last one in this list and dynamic
1177   // symbol table section (DynSymTab) must be the first one.
1178   applySynthetic({In<ELFT>::DynSymTab,  In<ELFT>::Bss,      In<ELFT>::BssRelRo,
1179                   In<ELFT>::GnuHashTab, In<ELFT>::HashTab,  In<ELFT>::SymTab,
1180                   In<ELFT>::ShStrTab,   In<ELFT>::StrTab,   In<ELFT>::VerDef,
1181                   In<ELFT>::DynStrTab,  In<ELFT>::GdbIndex, In<ELFT>::Got,
1182                   In<ELFT>::MipsGot,    In<ELFT>::IgotPlt,  In<ELFT>::GotPlt,
1183                   In<ELFT>::RelaDyn,    In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1184                   In<ELFT>::Plt,        In<ELFT>::Iplt,     In<ELFT>::Plt,
1185                   In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,   In<ELFT>::VerNeed,
1186                   In<ELFT>::Dynamic},
1187                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1188
1189   // Some architectures use small displacements for jump instructions.
1190   // It is linker's responsibility to create thunks containing long
1191   // jump instructions if jump targets are too far. Create thunks.
1192   if (Target->NeedsThunks) {
1193     // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1194     // these
1195     // do not require address information. To support range extension Thunks
1196     // we need to assign addresses so that we can tell if jump instructions
1197     // are out of range. This will need to turn into a loop that converges
1198     // when no more Thunks are added
1199     ThunkCreator<ELFT> TC;
1200     if (TC.createThunks(OutputSections))
1201       applySynthetic({In<ELFT>::MipsGot},
1202                      [](SyntheticSection *SS) { SS->updateAllocSize(); });
1203   }
1204   // Fill other section headers. The dynamic table is finalized
1205   // at the end because some tags like RELSZ depend on result
1206   // of finalizing other sections.
1207   for (OutputSection *Sec : OutputSections)
1208     Sec->finalize<ELFT>();
1209
1210   // If -compressed-debug-sections is specified, we need to compress
1211   // .debug_* sections. Do it right now because it changes the size of
1212   // output sections.
1213   parallelForEach(OutputSections.begin(), OutputSections.end(),
1214                   [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1215
1216   // createThunks may have added local symbols to the static symbol table
1217   applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab},
1218                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1219 }
1220
1221 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1222   // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1223   // We have the terminater synthetic section class. Add that at the end.
1224   auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1225   if (OS && !OS->Sections.empty() && !Config->Relocatable)
1226     OS->addSection(make<ARMExidxSentinelSection>());
1227 }
1228
1229 // The linker is expected to define SECNAME_start and SECNAME_end
1230 // symbols for a few sections. This function defines them.
1231 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1232   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1233     // These symbols resolve to the image base if the section does not exist.
1234     // A special value -1 indicates end of the section.
1235     if (OS) {
1236       addOptionalRegular<ELFT>(Start, OS, 0);
1237       addOptionalRegular<ELFT>(End, OS, -1);
1238     } else {
1239       if (Config->Pic)
1240         OS = Out::ElfHeader;
1241       addOptionalRegular<ELFT>(Start, OS, 0);
1242       addOptionalRegular<ELFT>(End, OS, 0);
1243     }
1244   };
1245
1246   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1247   Define("__init_array_start", "__init_array_end", Out::InitArray);
1248   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1249
1250   if (OutputSection *Sec = findSection(".ARM.exidx"))
1251     Define("__exidx_start", "__exidx_end", Sec);
1252 }
1253
1254 // If a section name is valid as a C identifier (which is rare because of
1255 // the leading '.'), linkers are expected to define __start_<secname> and
1256 // __stop_<secname> symbols. They are at beginning and end of the section,
1257 // respectively. This is not requested by the ELF standard, but GNU ld and
1258 // gold provide the feature, and used by many programs.
1259 template <class ELFT>
1260 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1261   StringRef S = Sec->Name;
1262   if (!isValidCIdentifier(S))
1263     return;
1264   addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1265   addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1266 }
1267
1268 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1269   for (OutputSection *Sec : OutputSections)
1270     if (Sec->Name == Name)
1271       return Sec;
1272   return nullptr;
1273 }
1274
1275 static bool needsPtLoad(OutputSection *Sec) {
1276   if (!(Sec->Flags & SHF_ALLOC))
1277     return false;
1278
1279   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1280   // responsible for allocating space for them, not the PT_LOAD that
1281   // contains the TLS initialization image.
1282   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1283     return false;
1284   return true;
1285 }
1286
1287 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1288 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1289 // RW. This means that there is no alignment in the RO to RX transition and we
1290 // cannot create a PT_LOAD there.
1291 static uint64_t computeFlags(uint64_t Flags) {
1292   if (Config->Omagic)
1293     return PF_R | PF_W | PF_X;
1294   if (Config->SingleRoRx && !(Flags & PF_W))
1295     return Flags | PF_X;
1296   return Flags;
1297 }
1298
1299 // Decide which program headers to create and which sections to include in each
1300 // one.
1301 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1302   std::vector<PhdrEntry> Ret;
1303   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1304     Ret.emplace_back(Type, Flags);
1305     return &Ret.back();
1306   };
1307
1308   // The first phdr entry is PT_PHDR which describes the program header itself.
1309   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1310
1311   // PT_INTERP must be the second entry if exists.
1312   if (OutputSection *Sec = findSection(".interp"))
1313     AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1314
1315   // Add the first PT_LOAD segment for regular output sections.
1316   uint64_t Flags = computeFlags(PF_R);
1317   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1318
1319   // Add the headers. We will remove them if they don't fit.
1320   Load->add(Out::ElfHeader);
1321   Load->add(Out::ProgramHeaders);
1322
1323   for (OutputSection *Sec : OutputSections) {
1324     if (!(Sec->Flags & SHF_ALLOC))
1325       break;
1326     if (!needsPtLoad(Sec))
1327       continue;
1328
1329     // Segments are contiguous memory regions that has the same attributes
1330     // (e.g. executable or writable). There is one phdr for each segment.
1331     // Therefore, we need to create a new phdr when the next section has
1332     // different flags or is loaded at a discontiguous address using AT linker
1333     // script command.
1334     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1335     if (Script->hasLMA(Sec->Name) || Flags != NewFlags) {
1336       Load = AddHdr(PT_LOAD, NewFlags);
1337       Flags = NewFlags;
1338     }
1339
1340     Load->add(Sec);
1341   }
1342
1343   // Add a TLS segment if any.
1344   PhdrEntry TlsHdr(PT_TLS, PF_R);
1345   for (OutputSection *Sec : OutputSections)
1346     if (Sec->Flags & SHF_TLS)
1347       TlsHdr.add(Sec);
1348   if (TlsHdr.First)
1349     Ret.push_back(std::move(TlsHdr));
1350
1351   // Add an entry for .dynamic.
1352   if (In<ELFT>::DynSymTab)
1353     AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1354         ->add(In<ELFT>::Dynamic->OutSec);
1355
1356   // PT_GNU_RELRO includes all sections that should be marked as
1357   // read-only by dynamic linker after proccessing relocations.
1358   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1359   for (OutputSection *Sec : OutputSections)
1360     if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec))
1361       RelRo.add(Sec);
1362   if (RelRo.First)
1363     Ret.push_back(std::move(RelRo));
1364
1365   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1366   if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1367       In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1368     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1369         ->add(In<ELFT>::EhFrameHdr->OutSec);
1370
1371   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1372   // the dynamic linker fill the segment with random data.
1373   if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1374     AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1375
1376   // PT_GNU_STACK is a special section to tell the loader to make the
1377   // pages for the stack non-executable. If you really want an executable
1378   // stack, you can pass -z execstack, but that's not recommended for
1379   // security reasons.
1380   unsigned Perm;
1381   if (Config->ZExecstack)
1382     Perm = PF_R | PF_W | PF_X;
1383   else
1384     Perm = PF_R | PF_W;
1385   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1386
1387   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1388   // is expected to perform W^X violations, such as calling mprotect(2) or
1389   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1390   // OpenBSD.
1391   if (Config->ZWxneeded)
1392     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1393
1394   // Create one PT_NOTE per a group of contiguous .note sections.
1395   PhdrEntry *Note = nullptr;
1396   for (OutputSection *Sec : OutputSections) {
1397     if (Sec->Type == SHT_NOTE) {
1398       if (!Note || Script->hasLMA(Sec->Name))
1399         Note = AddHdr(PT_NOTE, PF_R);
1400       Note->add(Sec);
1401     } else {
1402       Note = nullptr;
1403     }
1404   }
1405   return Ret;
1406 }
1407
1408 template <class ELFT>
1409 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1410   if (Config->EMachine != EM_ARM)
1411     return;
1412   auto I = std::find_if(
1413       OutputSections.begin(), OutputSections.end(),
1414       [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1415   if (I == OutputSections.end())
1416     return;
1417
1418   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1419   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1420   ARMExidx.add(*I);
1421   Phdrs.push_back(ARMExidx);
1422 }
1423
1424 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1425 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1426 // linker can set the permissions.
1427 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1428   for (const PhdrEntry &P : Phdrs)
1429     if (P.p_type == PT_LOAD && P.First)
1430       P.First->PageAlign = true;
1431
1432   for (const PhdrEntry &P : Phdrs) {
1433     if (P.p_type != PT_GNU_RELRO)
1434       continue;
1435     if (P.First)
1436       P.First->PageAlign = true;
1437     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1438     // have to align it to a page.
1439     auto End = OutputSections.end();
1440     auto I = std::find(OutputSections.begin(), End, P.Last);
1441     if (I == End || (I + 1) == End)
1442       continue;
1443     OutputSection *Sec = *(I + 1);
1444     if (needsPtLoad(Sec))
1445       Sec->PageAlign = true;
1446   }
1447 }
1448
1449 // Adjusts the file alignment for a given output section and returns
1450 // its new file offset. The file offset must be the same with its
1451 // virtual address (modulo the page size) so that the loader can load
1452 // executables without any address adjustment.
1453 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1454   OutputSection *First = Sec->FirstInPtLoad;
1455   // If the section is not in a PT_LOAD, we just have to align it.
1456   if (!First)
1457     return alignTo(Off, Sec->Alignment);
1458
1459   // The first section in a PT_LOAD has to have congruent offset and address
1460   // module the page size.
1461   if (Sec == First)
1462     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1463
1464   // If two sections share the same PT_LOAD the file offset is calculated
1465   // using this formula: Off2 = Off1 + (VA2 - VA1).
1466   return First->Offset + Sec->Addr - First->Addr;
1467 }
1468
1469 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1470   if (Sec->Type == SHT_NOBITS) {
1471     Sec->Offset = Off;
1472     return Off;
1473   }
1474
1475   Off = getFileAlignment(Off, Sec);
1476   Sec->Offset = Off;
1477   return Off + Sec->Size;
1478 }
1479
1480 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1481   uint64_t Off = 0;
1482   for (OutputSection *Sec : OutputSections)
1483     if (Sec->Flags & SHF_ALLOC)
1484       Off = setOffset(Sec, Off);
1485   FileSize = alignTo(Off, Config->Wordsize);
1486 }
1487
1488 // Assign file offsets to output sections.
1489 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1490   uint64_t Off = 0;
1491   Off = setOffset(Out::ElfHeader, Off);
1492   Off = setOffset(Out::ProgramHeaders, Off);
1493
1494   for (OutputSection *Sec : OutputSections)
1495     Off = setOffset(Sec, Off);
1496
1497   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1498   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1499 }
1500
1501 // Finalize the program headers. We call this function after we assign
1502 // file offsets and VAs to all sections.
1503 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1504   for (PhdrEntry &P : Phdrs) {
1505     OutputSection *First = P.First;
1506     OutputSection *Last = P.Last;
1507     if (First) {
1508       P.p_filesz = Last->Offset - First->Offset;
1509       if (Last->Type != SHT_NOBITS)
1510         P.p_filesz += Last->Size;
1511       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1512       P.p_offset = First->Offset;
1513       P.p_vaddr = First->Addr;
1514       if (!P.HasLMA)
1515         P.p_paddr = First->getLMA();
1516     }
1517     if (P.p_type == PT_LOAD)
1518       P.p_align = Config->MaxPageSize;
1519     else if (P.p_type == PT_GNU_RELRO)
1520       P.p_align = 1;
1521
1522     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1523     // so round up the size to make sure the offsets are correct.
1524     if (P.p_type == PT_TLS) {
1525       Out::TlsPhdr = &P;
1526       if (P.p_memsz)
1527         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1528     }
1529   }
1530 }
1531
1532 // The entry point address is chosen in the following ways.
1533 //
1534 // 1. the '-e' entry command-line option;
1535 // 2. the ENTRY(symbol) command in a linker control script;
1536 // 3. the value of the symbol start, if present;
1537 // 4. the address of the first byte of the .text section, if present;
1538 // 5. the address 0.
1539 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1540   // Case 1, 2 or 3. As a special case, if the symbol is actually
1541   // a number, we'll use that number as an address.
1542   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1543     return B->getVA();
1544   uint64_t Addr;
1545   if (!Config->Entry.getAsInteger(0, Addr))
1546     return Addr;
1547
1548   // Case 4
1549   if (OutputSection *Sec = findSection(".text")) {
1550     if (Config->WarnMissingEntry)
1551       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1552            utohexstr(Sec->Addr));
1553     return Sec->Addr;
1554   }
1555
1556   // Case 5
1557   if (Config->WarnMissingEntry)
1558     warn("cannot find entry symbol " + Config->Entry +
1559          "; not setting start address");
1560   return 0;
1561 }
1562
1563 static uint16_t getELFType() {
1564   if (Config->Pic)
1565     return ET_DYN;
1566   if (Config->Relocatable)
1567     return ET_REL;
1568   return ET_EXEC;
1569 }
1570
1571 // This function is called after we have assigned address and size
1572 // to each section. This function fixes some predefined
1573 // symbol values that depend on section address and size.
1574 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1575   auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1576                 uint64_t Value) {
1577     if (S1) {
1578       S1->Section = Sec;
1579       S1->Value = Value;
1580     }
1581     if (S2) {
1582       S2->Section = Sec;
1583       S2->Value = Value;
1584     }
1585   };
1586
1587   // _etext is the first location after the last read-only loadable segment.
1588   // _edata is the first location after the last read-write loadable segment.
1589   // _end is the first location after the uninitialized data region.
1590   PhdrEntry *Last = nullptr;
1591   PhdrEntry *LastRO = nullptr;
1592   PhdrEntry *LastRW = nullptr;
1593   for (PhdrEntry &P : Phdrs) {
1594     if (P.p_type != PT_LOAD)
1595       continue;
1596     Last = &P;
1597     if (P.p_flags & PF_W)
1598       LastRW = &P;
1599     else
1600       LastRO = &P;
1601   }
1602   if (Last)
1603     Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1604   if (LastRO)
1605     Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1606   if (LastRW)
1607     Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1608
1609   if (ElfSym::Bss)
1610     ElfSym::Bss->Section = findSection(".bss");
1611
1612   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1613   // be equal to the _gp symbol's value.
1614   if (Config->EMachine == EM_MIPS) {
1615     if (!ElfSym::MipsGp->Value) {
1616       // Find GP-relative section with the lowest address
1617       // and use this address to calculate default _gp value.
1618       uint64_t Gp = -1;
1619       for (const OutputSection *OS : OutputSections)
1620         if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1621           Gp = OS->Addr;
1622       if (Gp != (uint64_t)-1)
1623         ElfSym::MipsGp->Value = Gp + 0x7ff0;
1624     }
1625   }
1626 }
1627
1628 template <class ELFT> void Writer<ELFT>::writeHeader() {
1629   uint8_t *Buf = Buffer->getBufferStart();
1630   memcpy(Buf, "\177ELF", 4);
1631
1632   // Write the ELF header.
1633   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1634   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1635   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1636   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1637   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1638   EHdr->e_type = getELFType();
1639   EHdr->e_machine = Config->EMachine;
1640   EHdr->e_version = EV_CURRENT;
1641   EHdr->e_entry = getEntryAddr();
1642   EHdr->e_shoff = SectionHeaderOff;
1643   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1644   EHdr->e_phnum = Phdrs.size();
1645   EHdr->e_shentsize = sizeof(Elf_Shdr);
1646   EHdr->e_shnum = OutputSections.size() + 1;
1647   EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1648
1649   if (Config->EMachine == EM_ARM)
1650     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1651     // but we don't have any firm guarantees of conformance. Linux AArch64
1652     // kernels (as of 2016) require an EABI version to be set.
1653     EHdr->e_flags = EF_ARM_EABI_VER5;
1654   else if (Config->EMachine == EM_MIPS)
1655     EHdr->e_flags = getMipsEFlags<ELFT>();
1656
1657   if (!Config->Relocatable) {
1658     EHdr->e_phoff = sizeof(Elf_Ehdr);
1659     EHdr->e_phentsize = sizeof(Elf_Phdr);
1660   }
1661
1662   // Write the program header table.
1663   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1664   for (PhdrEntry &P : Phdrs) {
1665     HBuf->p_type = P.p_type;
1666     HBuf->p_flags = P.p_flags;
1667     HBuf->p_offset = P.p_offset;
1668     HBuf->p_vaddr = P.p_vaddr;
1669     HBuf->p_paddr = P.p_paddr;
1670     HBuf->p_filesz = P.p_filesz;
1671     HBuf->p_memsz = P.p_memsz;
1672     HBuf->p_align = P.p_align;
1673     ++HBuf;
1674   }
1675
1676   // Write the section header table. Note that the first table entry is null.
1677   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1678   for (OutputSection *Sec : OutputSections)
1679     Sec->writeHeaderTo<ELFT>(++SHdrs);
1680 }
1681
1682 // Open a result file.
1683 template <class ELFT> void Writer<ELFT>::openFile() {
1684   if (!Config->Is64 && FileSize > UINT32_MAX) {
1685     error("output file too large: " + Twine(FileSize) + " bytes");
1686     return;
1687   }
1688
1689   unlinkAsync(Config->OutputFile);
1690   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1691       FileOutputBuffer::create(Config->OutputFile, FileSize,
1692                                FileOutputBuffer::F_executable);
1693
1694   if (auto EC = BufferOrErr.getError())
1695     error("failed to open " + Config->OutputFile + ": " + EC.message());
1696   else
1697     Buffer = std::move(*BufferOrErr);
1698 }
1699
1700 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1701   uint8_t *Buf = Buffer->getBufferStart();
1702   for (OutputSection *Sec : OutputSections)
1703     if (Sec->Flags & SHF_ALLOC)
1704       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1705 }
1706
1707 // Write section contents to a mmap'ed file.
1708 template <class ELFT> void Writer<ELFT>::writeSections() {
1709   uint8_t *Buf = Buffer->getBufferStart();
1710
1711   // PPC64 needs to process relocations in the .opd section
1712   // before processing relocations in code-containing sections.
1713   Out::Opd = findSection(".opd");
1714   if (Out::Opd) {
1715     Out::OpdBuf = Buf + Out::Opd->Offset;
1716     Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1717   }
1718
1719   OutputSection *EhFrameHdr =
1720       In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1721
1722   // In -r or -emit-relocs mode, write the relocation sections first as in
1723   // ELf_Rel targets we might find out that we need to modify the relocated
1724   // section while doing it.
1725   for (OutputSection *Sec : OutputSections)
1726     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1727       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1728
1729   for (OutputSection *Sec : OutputSections)
1730     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1731         Sec->Type != SHT_RELA)
1732       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1733
1734   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1735   // it should be written after .eh_frame is written.
1736   if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1737     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1738 }
1739
1740 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1741   if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1742     return;
1743
1744   // Compute a hash of all sections of the output file.
1745   uint8_t *Start = Buffer->getBufferStart();
1746   uint8_t *End = Start + FileSize;
1747   In<ELFT>::BuildId->writeBuildId({Start, End});
1748 }
1749
1750 template void elf::writeResult<ELF32LE>();
1751 template void elf::writeResult<ELF32BE>();
1752 template void elf::writeResult<ELF64LE>();
1753 template void elf::writeResult<ELF64BE>();
1754
1755 template bool elf::isRelroSection<ELF32LE>(const OutputSection *);
1756 template bool elf::isRelroSection<ELF32BE>(const OutputSection *);
1757 template bool elf::isRelroSection<ELF64LE>(const OutputSection *);
1758 template bool elf::isRelroSection<ELF64BE>(const OutputSection *);