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