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