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