xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 059e52c4)
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 "OutputSections.h"
13 #include "SymbolTable.h"
14 #include "Target.h"
15 
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/Support/FileOutputBuffer.h"
18 #include "llvm/Support/StringSaver.h"
19 
20 using namespace llvm;
21 using namespace llvm::ELF;
22 using namespace llvm::object;
23 
24 using namespace lld;
25 using namespace lld::elf2;
26 
27 namespace {
28 // The writer writes a SymbolTable result to a file.
29 template <class ELFT> class Writer {
30 public:
31   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
32   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
33   typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
34   typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
35   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
36   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
37   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
38   Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
39   void run();
40 
41 private:
42   void copyLocalSymbols();
43   void createSections();
44   template <bool isRela>
45   void scanRelocs(const InputSection<ELFT> &C,
46                   iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
47   void scanRelocs(const InputSection<ELFT> &C);
48   void assignAddresses();
49   void openFile(StringRef OutputPath);
50   void writeHeader();
51   void writeSections();
52   bool needsInterpSection() const {
53     return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
54   }
55   bool isOutputDynamic() const {
56     return !Symtab.getSharedFiles().empty() || Config->Shared;
57   }
58   uintX_t getVAStart() const { return Config->Shared ? 0 : Target->getVAStart(); }
59   uintX_t getEntryAddr() const;
60   int getPhdrsNum() const;
61 
62   OutputSection<ELFT> *getBSS();
63   void addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms);
64   void addSharedCopySymbols(std::vector<SharedSymbol<ELFT> *> &Syms);
65 
66   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
67 
68   SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc;
69   SpecificBumpPtrAllocator<MergeOutputSection<ELFT>> MSecAlloc;
70   BumpPtrAllocator Alloc;
71   std::vector<OutputSectionBase<ELFT> *> OutputSections;
72   unsigned getNumSections() const { return OutputSections.size() + 1; }
73 
74   void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
75   void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff,
76                uintX_t VA, uintX_t Size, uintX_t Align);
77   void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From);
78 
79   SymbolTable<ELFT> &Symtab;
80   std::vector<Elf_Phdr> Phdrs;
81 
82   uintX_t FileSize;
83   uintX_t SectionHeaderOff;
84 };
85 } // anonymous namespace
86 
87 template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) {
88   // Initialize output sections that are handled by Writer specially.
89   // Don't reorder because the order of initialization matters.
90   InterpSection<ELFT> Interp;
91   Out<ELFT>::Interp = &Interp;
92   StringTableSection<ELFT> ShStrTab(".shstrtab", false);
93   Out<ELFT>::ShStrTab = &ShStrTab;
94   StringTableSection<ELFT> StrTab(".strtab", false);
95   if (!Config->StripAll)
96     Out<ELFT>::StrTab = &StrTab;
97   StringTableSection<ELFT> DynStrTab(".dynstr", true);
98   Out<ELFT>::DynStrTab = &DynStrTab;
99   GotSection<ELFT> Got;
100   Out<ELFT>::Got = &Got;
101   GotPltSection<ELFT> GotPlt;
102   if (Target->supportsLazyRelocations())
103     Out<ELFT>::GotPlt = &GotPlt;
104   PltSection<ELFT> Plt;
105   Out<ELFT>::Plt = &Plt;
106   std::unique_ptr<SymbolTableSection<ELFT>> SymTab;
107   if (!Config->StripAll) {
108     SymTab.reset(new SymbolTableSection<ELFT>(*Symtab, *Out<ELFT>::StrTab));
109     Out<ELFT>::SymTab = SymTab.get();
110   }
111   SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab);
112   Out<ELFT>::DynSymTab = &DynSymTab;
113   HashTableSection<ELFT> HashTab;
114   if (Config->SysvHash)
115     Out<ELFT>::HashTab = &HashTab;
116   GnuHashTableSection<ELFT> GnuHashTab;
117   if (Config->GnuHash)
118     Out<ELFT>::GnuHashTab = &GnuHashTab;
119   bool IsRela = Symtab->shouldUseRela();
120   RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela);
121   Out<ELFT>::RelaDyn = &RelaDyn;
122   RelocationSection<ELFT> RelaPlt(IsRela ? ".rela.plt" : ".rel.plt", IsRela);
123   if (Target->supportsLazyRelocations())
124     Out<ELFT>::RelaPlt = &RelaPlt;
125   DynamicSection<ELFT> Dynamic(*Symtab);
126   Out<ELFT>::Dynamic = &Dynamic;
127 
128   Writer<ELFT>(*Symtab).run();
129 }
130 
131 // The main function of the writer.
132 template <class ELFT> void Writer<ELFT>::run() {
133   if (!Config->DiscardAll)
134     copyLocalSymbols();
135   createSections();
136   assignAddresses();
137   openFile(Config->OutputFile);
138   writeHeader();
139   writeSections();
140   error(Buffer->commit());
141 }
142 
143 namespace {
144 template <bool Is64Bits> struct SectionKey {
145   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
146   StringRef Name;
147   uint32_t Type;
148   uintX_t Flags;
149   uintX_t EntSize;
150 };
151 }
152 namespace llvm {
153 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
154   static SectionKey<Is64Bits> getEmptyKey() {
155     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
156                                 0};
157   }
158   static SectionKey<Is64Bits> getTombstoneKey() {
159     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
160                                 0, 0};
161   }
162   static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
163     return hash_combine(Val.Name, Val.Type, Val.Flags, Val.EntSize);
164   }
165   static bool isEqual(const SectionKey<Is64Bits> &LHS,
166                       const SectionKey<Is64Bits> &RHS) {
167     return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
168            LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
169            LHS.EntSize == RHS.EntSize;
170   }
171 };
172 }
173 
174 // The reason we have to do this early scan is as follows
175 // * To mmap the output file, we need to know the size
176 // * For that, we need to know how many dynamic relocs we will have.
177 // It might be possible to avoid this by outputting the file with write:
178 // * Write the allocated output sections, computing addresses.
179 // * Apply relocations, recording which ones require a dynamic reloc.
180 // * Write the dynamic relocations.
181 // * Write the rest of the file.
182 template <class ELFT>
183 template <bool isRela>
184 void Writer<ELFT>::scanRelocs(
185     const InputSection<ELFT> &C,
186     iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
187   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
188   const ObjectFile<ELFT> &File = *C.getFile();
189   for (const RelType &RI : Rels) {
190     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
191     SymbolBody *Body = File.getSymbolBody(SymIndex);
192     uint32_t Type = RI.getType(Config->Mips64EL);
193 
194     // Set "used" bit for --as-needed.
195     if (Body && Body->isUndefined() && !Body->isWeak())
196       if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl()))
197         S->File->IsUsed = true;
198 
199     if (Body)
200       Body = Body->repl();
201     bool NeedsGot = false;
202     bool NeedsPlt = false;
203     if (Body) {
204       if (auto *E = dyn_cast<SharedSymbol<ELFT>>(Body)) {
205         if (E->needsCopy())
206           continue;
207         if (Target->relocNeedsCopy(Type, *Body))
208           E->OffsetInBSS = 0;
209       }
210       NeedsPlt = Target->relocNeedsPlt(Type, *Body);
211       if (NeedsPlt) {
212         if (Body->isInPlt())
213           continue;
214         Out<ELFT>::Plt->addEntry(Body);
215       }
216       NeedsGot = Target->relocNeedsGot(Type, *Body);
217       if (NeedsGot) {
218         if (NeedsPlt && Target->supportsLazyRelocations()) {
219           Out<ELFT>::GotPlt->addEntry(Body);
220         } else {
221           if (Body->isInGot())
222             continue;
223           Out<ELFT>::Got->addEntry(Body);
224         }
225       }
226     }
227 
228     if (Config->EMachine == EM_MIPS && NeedsGot) {
229       // MIPS ABI has special rules to process GOT entries
230       // and doesn't require relocation entries for them.
231       // See "Global Offset Table" in Chapter 5 in the following document
232       // for detailed description:
233       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
234       Body->setUsedInDynamicReloc();
235       continue;
236     }
237     bool CBP = canBePreempted(Body, NeedsGot);
238     if (!CBP && (!Config->Shared || Target->isRelRelative(Type)))
239       continue;
240     if (CBP)
241       Body->setUsedInDynamicReloc();
242     if (NeedsPlt && Target->supportsLazyRelocations())
243       Out<ELFT>::RelaPlt->addReloc({C, RI});
244     else
245       Out<ELFT>::RelaDyn->addReloc({C, RI});
246   }
247 }
248 
249 template <class ELFT>
250 void Writer<ELFT>::scanRelocs(const InputSection<ELFT> &C) {
251   ObjectFile<ELFT> *File = C.getFile();
252   ELFFile<ELFT> &EObj = File->getObj();
253 
254   if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
255     return;
256 
257   for (const Elf_Shdr *RelSec : C.RelocSections) {
258     if (RelSec->sh_type == SHT_RELA)
259       scanRelocs(C, EObj.relas(RelSec));
260     else
261       scanRelocs(C, EObj.rels(RelSec));
262   }
263 }
264 
265 template <class ELFT>
266 static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) {
267   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
268   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
269 
270   if (Config->Shared && !Config->NoUndefined)
271     return;
272 
273   const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym;
274   ELFFileBase<ELFT> *SymFile = nullptr;
275 
276   for (const std::unique_ptr<ObjectFile<ELFT>> &File : S.getObjectFiles()) {
277     Elf_Sym_Range Syms = File->getObj().symbols(File->getSymbolTable());
278     if (&SymE > Syms.begin() && &SymE < Syms.end())
279       SymFile = File.get();
280   }
281 
282   std::string Message = "undefined symbol: " + Sym.getName().str();
283   if (SymFile)
284     Message += " in " + SymFile->getName().str();
285   if (Config->NoInhibitExec)
286     warning(Message);
287   else
288     error(Message);
289 }
290 
291 // Local symbols are not in the linker's symbol table. This function scans
292 // each object file's symbol table to copy local symbols to the output.
293 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
294   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
295     for (const Elf_Sym &Sym : F->getLocalSymbols()) {
296       ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable());
297       error(SymNameOrErr);
298       StringRef SymName = *SymNameOrErr;
299       if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym))
300         continue;
301       if (Out<ELFT>::SymTab)
302         Out<ELFT>::SymTab->addLocalSymbol(SymName);
303     }
304   }
305 }
306 
307 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
308 // we would like to make sure appear is a specific order to maximize their
309 // coverage by a single signed 16-bit offset from the TOC base pointer.
310 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
311 // sections. This will put it next to the loaded special PPC64 sections (and,
312 // thus, within reach of the TOC base pointer).
313 static int getPPC64SectionRank(StringRef SectionName) {
314   return StringSwitch<int>(SectionName)
315            .Case(".tocbss", 0)
316            .Case(".branch_lt", 2)
317            .Case(".toc", 3)
318            .Case(".toc1", 4)
319            .Case(".opd", 5)
320            .Default(1);
321 }
322 
323 // Output section ordering is determined by this function.
324 template <class ELFT>
325 static bool compareOutputSections(OutputSectionBase<ELFT> *A,
326                                   OutputSectionBase<ELFT> *B) {
327   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
328 
329   uintX_t AFlags = A->getFlags();
330   uintX_t BFlags = B->getFlags();
331 
332   // Allocatable sections go first to reduce the total PT_LOAD size and
333   // so debug info doesn't change addresses in actual code.
334   bool AIsAlloc = AFlags & SHF_ALLOC;
335   bool BIsAlloc = BFlags & SHF_ALLOC;
336   if (AIsAlloc != BIsAlloc)
337     return AIsAlloc;
338 
339   // We don't have any special requirements for the relative order of
340   // two non allocatable sections.
341   if (!AIsAlloc)
342     return false;
343 
344   // We want the read only sections first so that they go in the PT_LOAD
345   // covering the program headers at the start of the file.
346   bool AIsWritable = AFlags & SHF_WRITE;
347   bool BIsWritable = BFlags & SHF_WRITE;
348   if (AIsWritable != BIsWritable)
349     return BIsWritable;
350 
351   // For a corresponding reason, put non exec sections first (the program
352   // header PT_LOAD is not executable).
353   bool AIsExec = AFlags & SHF_EXECINSTR;
354   bool BIsExec = BFlags & SHF_EXECINSTR;
355   if (AIsExec != BIsExec)
356     return BIsExec;
357 
358   // If we got here we know that both A and B are in the same PT_LOAD.
359 
360   // The TLS initialization block needs to be a single contiguous block in a R/W
361   // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
362   // sections are placed here as they don't take up virtual address space in the
363   // PT_LOAD.
364   bool AIsTLS = AFlags & SHF_TLS;
365   bool BIsTLS = BFlags & SHF_TLS;
366   if (AIsTLS != BIsTLS)
367     return AIsTLS;
368 
369   // The next requirement we have is to put nobits sections last. The
370   // reason is that the only thing the dynamic linker will see about
371   // them is a p_memsz that is larger than p_filesz. Seeing that it
372   // zeros the end of the PT_LOAD, so that has to correspond to the
373   // nobits sections.
374   bool AIsNoBits = A->getType() == SHT_NOBITS;
375   bool BIsNoBits = B->getType() == SHT_NOBITS;
376   if (AIsNoBits != BIsNoBits)
377     return BIsNoBits;
378 
379   // Some architectures have additional ordering restrictions for sections
380   // within the same PT_LOAD.
381   if (Config->EMachine == EM_PPC64)
382     return getPPC64SectionRank(A->getName()) <
383            getPPC64SectionRank(B->getName());
384 
385   return false;
386 }
387 
388 template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBSS() {
389   if (!Out<ELFT>::Bss) {
390     Out<ELFT>::Bss = new (SecAlloc.Allocate())
391         OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
392     OutputSections.push_back(Out<ELFT>::Bss);
393   }
394   return Out<ELFT>::Bss;
395 }
396 
397 // Until this function is called, common symbols do not belong to any section.
398 // This function adds them to end of BSS section.
399 template <class ELFT>
400 void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms) {
401   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
402   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
403 
404   if (Syms.empty())
405     return;
406 
407   // Sort the common symbols by alignment as an heuristic to pack them better.
408   std::stable_sort(
409     Syms.begin(), Syms.end(),
410     [](const DefinedCommon<ELFT> *A, const DefinedCommon<ELFT> *B) {
411       return A->MaxAlignment > B->MaxAlignment;
412     });
413 
414   uintX_t Off = getBSS()->getSize();
415   for (DefinedCommon<ELFT> *C : Syms) {
416     const Elf_Sym &Sym = C->Sym;
417     uintX_t Align = C->MaxAlignment;
418     Off = RoundUpToAlignment(Off, Align);
419     C->OffsetInBSS = Off;
420     Off += Sym.st_size;
421   }
422 
423   Out<ELFT>::Bss->setSize(Off);
424 }
425 
426 template <class ELFT>
427 void Writer<ELFT>::addSharedCopySymbols(
428     std::vector<SharedSymbol<ELFT> *> &Syms) {
429   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
430   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
431   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
432 
433   if (Syms.empty())
434     return;
435 
436   uintX_t Off = getBSS()->getSize();
437   for (SharedSymbol<ELFT> *C : Syms) {
438     const Elf_Sym &Sym = C->Sym;
439     const Elf_Shdr *Sec = C->File->getSection(Sym);
440     uintX_t SecAlign = Sec->sh_addralign;
441     uintX_t Align = Sym.st_value % SecAlign;
442     if (Align == 0)
443       Align = SecAlign;
444     Out<ELFT>::Bss->updateAlign(Align);
445     Off = RoundUpToAlignment(Off, Align);
446     C->OffsetInBSS = Off;
447     Off += Sym.st_size;
448   }
449   Out<ELFT>::Bss->setSize(Off);
450 }
451 
452 static StringRef getOutputName(StringRef S) {
453   if (S.startswith(".text."))
454     return ".text";
455   if (S.startswith(".rodata."))
456     return ".rodata";
457   if (S.startswith(".data."))
458     return ".data";
459   if (S.startswith(".bss."))
460     return ".bss";
461   return S;
462 }
463 
464 // Create output section objects and add them to OutputSections.
465 template <class ELFT> void Writer<ELFT>::createSections() {
466   // .interp needs to be on the first page in the output file.
467   if (needsInterpSection())
468     OutputSections.push_back(Out<ELFT>::Interp);
469 
470   SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
471 
472   std::vector<OutputSectionBase<ELFT> *> RegularSections;
473 
474   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
475     for (InputSectionBase<ELFT> *C : F->getSections()) {
476       if (!C || !C->isLive() || C == &InputSection<ELFT>::Discarded)
477         continue;
478       const Elf_Shdr *H = C->getSectionHdr();
479       uintX_t OutFlags = H->sh_flags & ~SHF_GROUP;
480       // For SHF_MERGE we create different output sections for each sh_entsize.
481       // This makes each output section simple and keeps a single level
482       // mapping from input to output.
483       auto *IS = dyn_cast<InputSection<ELFT>>(C);
484       uintX_t EntSize = IS ? 0 : H->sh_entsize;
485       SectionKey<ELFT::Is64Bits> Key{getOutputName(C->getSectionName()),
486                                      H->sh_type, OutFlags, EntSize};
487       OutputSectionBase<ELFT> *&Sec = Map[Key];
488       if (!Sec) {
489         if (IS)
490           Sec = new (SecAlloc.Allocate())
491               OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
492         else
493           Sec = new (MSecAlloc.Allocate())
494               MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
495         OutputSections.push_back(Sec);
496         RegularSections.push_back(Sec);
497       }
498       if (IS)
499         static_cast<OutputSection<ELFT> *>(Sec)->addSection(IS);
500       else
501         static_cast<MergeOutputSection<ELFT> *>(Sec)
502             ->addSection(cast<MergeInputSection<ELFT>>(C));
503     }
504   }
505 
506   Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
507       Map[{".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE, 0}]);
508 
509   Out<ELFT>::Dynamic->PreInitArraySec = Map.lookup(
510       {".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
511   Out<ELFT>::Dynamic->InitArraySec =
512       Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
513   Out<ELFT>::Dynamic->FiniArraySec =
514       Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
515 
516   auto AddStartEnd = [&](StringRef Start, StringRef End,
517                          OutputSectionBase<ELFT> *OS) {
518     if (OS) {
519       Symtab.addSyntheticSym(Start, *OS, 0);
520       Symtab.addSyntheticSym(End, *OS, OS->getSize());
521     } else {
522       Symtab.addIgnoredSym(Start);
523       Symtab.addIgnoredSym(End);
524     }
525   };
526 
527   AddStartEnd("__preinit_array_start", "__preinit_array_end",
528               Out<ELFT>::Dynamic->PreInitArraySec);
529   AddStartEnd("__init_array_start", "__init_array_end",
530               Out<ELFT>::Dynamic->InitArraySec);
531   AddStartEnd("__fini_array_start", "__fini_array_end",
532               Out<ELFT>::Dynamic->FiniArraySec);
533 
534   for (OutputSectionBase<ELFT> *Sec : RegularSections)
535     addStartStopSymbols(Sec);
536 
537   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
538   // static linking the linker is required to optimize away any references to
539   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
540   // to avoid the undefined symbol error.
541   if (!isOutputDynamic())
542     Symtab.addIgnoredSym("__tls_get_addr");
543 
544   // Scan relocations. This must be done after every symbol is declared so that
545   // we can correctly decide if a dynamic relocation is needed.
546   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles())
547     for (InputSectionBase<ELFT> *B : F->getSections())
548       if (auto *S = dyn_cast_or_null<InputSection<ELFT>>(B))
549         if (S != &InputSection<ELFT>::Discarded)
550           if (S->isLive())
551             scanRelocs(*S);
552 
553   std::vector<DefinedCommon<ELFT> *> CommonSymbols;
554   std::vector<SharedSymbol<ELFT> *> SharedCopySymbols;
555   for (auto &P : Symtab.getSymbols()) {
556     SymbolBody *Body = P.second->Body;
557     if (auto *U = dyn_cast<Undefined<ELFT>>(Body))
558       if (!U->isWeak() && !U->canKeepUndefined())
559         reportUndefined<ELFT>(Symtab, *Body);
560 
561     if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
562       CommonSymbols.push_back(C);
563     if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body))
564       if (SC->needsCopy())
565         SharedCopySymbols.push_back(SC);
566 
567     if (!includeInSymtab<ELFT>(*Body))
568       continue;
569     if (Out<ELFT>::SymTab)
570       Out<ELFT>::SymTab->addSymbol(Body);
571 
572     if (isOutputDynamic() && includeInDynamicSymtab(*Body))
573       Out<ELFT>::DynSymTab->addSymbol(Body);
574   }
575   addCommonSymbols(CommonSymbols);
576   addSharedCopySymbols(SharedCopySymbols);
577 
578   // This order is not the same as the final output order
579   // because we sort the sections using their attributes below.
580   if (Out<ELFT>::SymTab)
581     OutputSections.push_back(Out<ELFT>::SymTab);
582   OutputSections.push_back(Out<ELFT>::ShStrTab);
583   if (Out<ELFT>::StrTab)
584     OutputSections.push_back(Out<ELFT>::StrTab);
585   if (isOutputDynamic()) {
586     OutputSections.push_back(Out<ELFT>::DynSymTab);
587     if (Out<ELFT>::GnuHashTab)
588       OutputSections.push_back(Out<ELFT>::GnuHashTab);
589     if (Out<ELFT>::HashTab)
590       OutputSections.push_back(Out<ELFT>::HashTab);
591     OutputSections.push_back(Out<ELFT>::Dynamic);
592     OutputSections.push_back(Out<ELFT>::DynStrTab);
593     if (Out<ELFT>::RelaDyn->hasRelocs())
594       OutputSections.push_back(Out<ELFT>::RelaDyn);
595     if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs())
596       OutputSections.push_back(Out<ELFT>::RelaPlt);
597   }
598   if (!Out<ELFT>::Got->empty())
599     OutputSections.push_back(Out<ELFT>::Got);
600   if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
601     OutputSections.push_back(Out<ELFT>::GotPlt);
602   if (!Out<ELFT>::Plt->empty())
603     OutputSections.push_back(Out<ELFT>::Plt);
604 
605   std::stable_sort(OutputSections.begin(), OutputSections.end(),
606                    compareOutputSections<ELFT>);
607 
608   for (unsigned I = 0, N = OutputSections.size(); I < N; ++I)
609     OutputSections[I]->SectionIndex = I + 1;
610 
611   for (OutputSectionBase<ELFT> *Sec : OutputSections)
612     Out<ELFT>::ShStrTab->add(Sec->getName());
613 
614   // Finalizers fix each section's size.
615   // .dynamic section's finalizer may add strings to .dynstr,
616   // so finalize that early.
617   // Likewise, .dynsym is finalized early since that may fill up .gnu.hash.
618   Out<ELFT>::Dynamic->finalize();
619   if (isOutputDynamic())
620     Out<ELFT>::DynSymTab->finalize();
621 
622   // Fill other section headers.
623   for (OutputSectionBase<ELFT> *Sec : OutputSections)
624     Sec->finalize();
625 
626   // If we have a .opd section (used under PPC64 for function descriptors),
627   // store a pointer to it here so that we can use it later when processing
628   // relocations.
629   Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC, 0});
630 }
631 
632 static bool isAlpha(char C) {
633   return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
634 }
635 
636 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
637 
638 // Returns true if S is valid as a C language identifier.
639 static bool isValidCIdentifier(StringRef S) {
640   if (S.empty() || !isAlpha(S[0]))
641     return false;
642   return std::all_of(S.begin() + 1, S.end(), isAlnum);
643 }
644 
645 // If a section name is valid as a C identifier (which is rare because of
646 // the leading '.'), linkers are expected to define __start_<secname> and
647 // __stop_<secname> symbols. They are at beginning and end of the section,
648 // respectively. This is not requested by the ELF standard, but GNU ld and
649 // gold provide the feature, and used by many programs.
650 template <class ELFT>
651 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
652   StringRef S = Sec->getName();
653   if (!isValidCIdentifier(S))
654     return;
655   StringSaver Saver(Alloc);
656   StringRef Start = Saver.save("__start_" + S);
657   StringRef Stop = Saver.save("__stop_" + S);
658   if (Symtab.isUndefined(Start))
659     Symtab.addSyntheticSym(Start, *Sec, 0);
660   if (Symtab.isUndefined(Stop))
661     Symtab.addSyntheticSym(Stop, *Sec, Sec->getSize());
662 }
663 
664 template <class ELFT> static bool needsPhdr(OutputSectionBase<ELFT> *Sec) {
665   return Sec->getFlags() & SHF_ALLOC;
666 }
667 
668 static uint32_t toPhdrFlags(uint64_t Flags) {
669   uint32_t Ret = PF_R;
670   if (Flags & SHF_WRITE)
671     Ret |= PF_W;
672   if (Flags & SHF_EXECINSTR)
673     Ret |= PF_X;
674   return Ret;
675 }
676 
677 // Visits all sections to create PHDRs and to assign incremental,
678 // non-overlapping addresses to output sections.
679 template <class ELFT> void Writer<ELFT>::assignAddresses() {
680   uintX_t VA = getVAStart() + sizeof(Elf_Ehdr);
681   uintX_t FileOff = sizeof(Elf_Ehdr);
682 
683   // Calculate and reserve the space for the program header first so that
684   // the first section can start right after the program header.
685   Phdrs.resize(getPhdrsNum());
686   size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size();
687 
688   // The first phdr entry is PT_PHDR which describes the program header itself.
689   setPhdr(&Phdrs[0], PT_PHDR, PF_R, FileOff, VA, PhdrSize, /*Align=*/8);
690   FileOff += PhdrSize;
691   VA += PhdrSize;
692 
693   // PT_INTERP must be the second entry if exists.
694   int PhdrIdx = 0;
695   Elf_Phdr *Interp = nullptr;
696   if (needsInterpSection())
697     Interp = &Phdrs[++PhdrIdx];
698 
699   // Add the first PT_LOAD segment for regular output sections.
700   setPhdr(&Phdrs[++PhdrIdx], PT_LOAD, PF_R, 0, getVAStart(), FileOff,
701           Target->getPageSize());
702 
703   Elf_Phdr TlsPhdr{};
704   uintX_t ThreadBSSOffset = 0;
705   // Create phdrs as we assign VAs and file offsets to all output sections.
706   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
707     if (needsPhdr<ELFT>(Sec)) {
708       uintX_t Flags = toPhdrFlags(Sec->getFlags());
709       if (Phdrs[PhdrIdx].p_flags != Flags) {
710         // Flags changed. Create a new PT_LOAD.
711         VA = RoundUpToAlignment(VA, Target->getPageSize());
712         FileOff = RoundUpToAlignment(FileOff, Target->getPageSize());
713         Elf_Phdr *PH = &Phdrs[++PhdrIdx];
714         setPhdr(PH, PT_LOAD, Flags, FileOff, VA, 0, Target->getPageSize());
715       }
716 
717       if (Sec->getFlags() & SHF_TLS) {
718         if (!TlsPhdr.p_vaddr) {
719           setPhdr(&TlsPhdr, PT_TLS, PF_R, FileOff, VA, 0, Sec->getAlign());
720           Out<ELFT>::TlsInitImageVA = VA;
721         }
722         if (Sec->getType() != SHT_NOBITS)
723           VA = RoundUpToAlignment(VA, Sec->getAlign());
724         uintX_t TVA = RoundUpToAlignment(VA + ThreadBSSOffset, Sec->getAlign());
725         Sec->setVA(TVA);
726         TlsPhdr.p_memsz += Sec->getSize();
727         if (Sec->getType() == SHT_NOBITS) {
728           ThreadBSSOffset = TVA - VA + Sec->getSize();
729         } else {
730           TlsPhdr.p_filesz += Sec->getSize();
731           VA += Sec->getSize();
732         }
733         TlsPhdr.p_align = std::max<uintX_t>(TlsPhdr.p_align, Sec->getAlign());
734       } else {
735         VA = RoundUpToAlignment(VA, Sec->getAlign());
736         Sec->setVA(VA);
737         VA += Sec->getSize();
738       }
739     }
740 
741     FileOff = RoundUpToAlignment(FileOff, Sec->getAlign());
742     Sec->setFileOffset(FileOff);
743     if (Sec->getType() != SHT_NOBITS)
744       FileOff += Sec->getSize();
745     if (needsPhdr<ELFT>(Sec)) {
746       Elf_Phdr *Cur = &Phdrs[PhdrIdx];
747       Cur->p_filesz = FileOff - Cur->p_offset;
748       Cur->p_memsz = VA - Cur->p_vaddr;
749     }
750   }
751 
752   if (TlsPhdr.p_vaddr) {
753     Phdrs[++PhdrIdx] = TlsPhdr;
754     Out<ELFT>::TlsInitImageAlignedSize =
755         RoundUpToAlignment(TlsPhdr.p_memsz, TlsPhdr.p_align);
756   }
757 
758   // Add an entry for .dynamic.
759   if (isOutputDynamic()) {
760     Elf_Phdr *PH = &Phdrs[++PhdrIdx];
761     PH->p_type = PT_DYNAMIC;
762     copyPhdr(PH, Out<ELFT>::Dynamic);
763   }
764 
765   // Fix up PT_INTERP as we now know the address of .interp section.
766   if (Interp) {
767     Interp->p_type = PT_INTERP;
768     copyPhdr(Interp, Out<ELFT>::Interp);
769   }
770 
771   // Add space for section headers.
772   SectionHeaderOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4);
773   FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr);
774 
775   // Update MIPS _gp absolute symbol so that it points to the static data.
776   if (Config->EMachine == EM_MIPS)
777     DefinedAbsolute<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>();
778 }
779 
780 // Returns the number of PHDR entries.
781 template <class ELFT> int Writer<ELFT>::getPhdrsNum() const {
782   bool Tls = false;
783   int I = 2; // 2 for PT_PHDR and the first PT_LOAD
784   if (needsInterpSection())
785     ++I;
786   if (isOutputDynamic())
787     ++I;
788   uintX_t Last = PF_R;
789   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
790     if (!needsPhdr<ELFT>(Sec))
791       continue;
792     if (Sec->getFlags() & SHF_TLS)
793       Tls = true;
794     uintX_t Flags = toPhdrFlags(Sec->getFlags());
795     if (Last != Flags) {
796       Last = Flags;
797       ++I;
798     }
799   }
800   if (Tls)
801     ++I;
802   return I;
803 }
804 
805 template <class ELFT> void Writer<ELFT>::writeHeader() {
806   uint8_t *Buf = Buffer->getBufferStart();
807   memcpy(Buf, "\177ELF", 4);
808 
809   // Write the ELF header.
810   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
811   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
812   EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little
813                                ? ELFDATA2LSB
814                                : ELFDATA2MSB;
815   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
816 
817   auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
818   EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
819 
820   EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC;
821   EHdr->e_machine = FirstObj.getEMachine();
822   EHdr->e_version = EV_CURRENT;
823   EHdr->e_entry = getEntryAddr();
824   EHdr->e_phoff = sizeof(Elf_Ehdr);
825   EHdr->e_shoff = SectionHeaderOff;
826   EHdr->e_ehsize = sizeof(Elf_Ehdr);
827   EHdr->e_phentsize = sizeof(Elf_Phdr);
828   EHdr->e_phnum = Phdrs.size();
829   EHdr->e_shentsize = sizeof(Elf_Shdr);
830   EHdr->e_shnum = getNumSections();
831   EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
832 
833   // Write the program header table.
834   memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0]));
835 
836   // Write the section header table. Note that the first table entry is null.
837   auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
838   for (OutputSectionBase<ELFT> *Sec : OutputSections)
839     Sec->writeHeaderTo(++SHdrs);
840 }
841 
842 template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) {
843   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
844       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable);
845   error(BufferOrErr, Twine("failed to open ") + Path);
846   Buffer = std::move(*BufferOrErr);
847 }
848 
849 // Write section contents to a mmap'ed file.
850 template <class ELFT> void Writer<ELFT>::writeSections() {
851   uint8_t *Buf = Buffer->getBufferStart();
852 
853   // PPC64 needs to process relocations in the .opd section before processing
854   // relocations in code-containing sections.
855   if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
856     Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
857     Sec->writeTo(Buf + Sec->getFileOff());
858   }
859 
860   for (OutputSectionBase<ELFT> *Sec : OutputSections)
861     if (Sec != Out<ELFT>::Opd)
862       Sec->writeTo(Buf + Sec->getFileOff());
863 }
864 
865 template <class ELFT>
866 typename ELFFile<ELFT>::uintX_t Writer<ELFT>::getEntryAddr() const {
867   if (Config->EntrySym) {
868     if (auto *E = dyn_cast<ELFSymbolBody<ELFT>>(Config->EntrySym->repl()))
869       return getSymVA<ELFT>(*E);
870     return 0;
871   }
872   if (Config->EntryAddr != uint64_t(-1))
873     return Config->EntryAddr;
874   return 0;
875 }
876 
877 template <class ELFT>
878 void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags,
879                            uintX_t FileOff, uintX_t VA, uintX_t Size,
880                            uintX_t Align) {
881   PH->p_type = Type;
882   PH->p_flags = Flags;
883   PH->p_offset = FileOff;
884   PH->p_vaddr = VA;
885   PH->p_paddr = VA;
886   PH->p_filesz = Size;
887   PH->p_memsz = Size;
888   PH->p_align = Align;
889 }
890 
891 template <class ELFT>
892 void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From) {
893   PH->p_flags = toPhdrFlags(From->getFlags());
894   PH->p_offset = From->getFileOff();
895   PH->p_vaddr = From->getVA();
896   PH->p_paddr = From->getVA();
897   PH->p_filesz = From->getSize();
898   PH->p_memsz = From->getSize();
899   PH->p_align = From->getAlign();
900 }
901 
902 template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
903 template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
904 template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
905 template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);
906