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