xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 4d75e8d6)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Writer.h"
11 #include "Config.h"
12 #include "LinkerScript.h"
13 #include "OutputSections.h"
14 #include "SymbolTable.h"
15 #include "Target.h"
16 
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Support/FileOutputBuffer.h"
21 #include "llvm/Support/StringSaver.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 using namespace llvm::ELF;
26 using namespace llvm::object;
27 
28 using namespace lld;
29 using namespace lld::elf;
30 
31 namespace {
32 // The writer writes a SymbolTable result to a file.
33 template <class ELFT> class Writer {
34 public:
35   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
36   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
37   typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
38   typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
39   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
40   typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
41   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
42   Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
43   void run();
44 
45 private:
46   // This describes a program header entry.
47   // Each contains type, access flags and range of output sections that will be
48   // placed in it.
49   struct Phdr {
50     Phdr(unsigned Type, unsigned Flags) {
51       H.p_type = Type;
52       H.p_flags = Flags;
53     }
54     Elf_Phdr H = {};
55     OutputSectionBase<ELFT> *First = nullptr;
56     OutputSectionBase<ELFT> *Last = nullptr;
57   };
58 
59   void copyLocalSymbols();
60   void addReservedSymbols();
61   bool createSections();
62   void addPredefinedSections();
63   bool needsGot();
64 
65   template <bool isRela>
66   void scanRelocs(InputSectionBase<ELFT> &C,
67                   iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
68 
69   void scanRelocs(InputSection<ELFT> &C);
70   void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec);
71   void createPhdrs();
72   void assignAddresses();
73   void assignAddressesRelocatable();
74   void fixAbsoluteSymbols();
75   bool openFile();
76   void writeHeader();
77   void writeSections();
78   bool isDiscarded(InputSectionBase<ELFT> *IS) const;
79   StringRef getOutputSectionName(InputSectionBase<ELFT> *S) const;
80   bool needsInterpSection() const {
81     return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
82   }
83   bool isOutputDynamic() const {
84     return !Symtab.getSharedFiles().empty() || Config->Shared;
85   }
86 
87   OutputSection<ELFT> *getBss();
88   void addCommonSymbols(std::vector<DefinedCommon *> &Syms);
89   void addCopyRelSymbols(std::vector<SharedSymbol<ELFT> *> &Syms);
90 
91   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
92 
93   BumpPtrAllocator Alloc;
94   std::vector<OutputSectionBase<ELFT> *> OutputSections;
95   std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> OwningSections;
96 
97   // We create a section for the ELF header and one for the program headers.
98   ArrayRef<OutputSectionBase<ELFT> *> getSections() const {
99     return makeArrayRef(OutputSections).slice(dummySectionsNum());
100   }
101   unsigned getNumSections() const {
102     return OutputSections.size() + 1 - dummySectionsNum();
103   }
104   // Usually there are 2 dummies sections: ELF header and program header.
105   // Relocatable output does not require program headers to be created.
106   unsigned dummySectionsNum() const { return Config->Relocatable ? 1 : 2; }
107 
108   void addRelIpltSymbols();
109   void addStartEndSymbols();
110   void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
111 
112   SymbolTable<ELFT> &Symtab;
113   std::vector<Phdr> Phdrs;
114 
115   uintX_t FileSize;
116   uintX_t SectionHeaderOff;
117 
118   // Flag to force GOT to be in output if we have relocations
119   // that relies on its address.
120   bool HasGotOffRel = false;
121 };
122 } // anonymous namespace
123 
124 template <class ELFT> static bool shouldUseRela() { return ELFT::Is64Bits; }
125 
126 template <class ELFT> void elf::writeResult(SymbolTable<ELFT> *Symtab) {
127   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
128 
129   // Create singleton output sections.
130   bool IsRela = shouldUseRela<ELFT>();
131   DynamicSection<ELFT> Dynamic(*Symtab);
132   EhFrameHeader<ELFT> EhFrameHdr;
133   GotSection<ELFT> Got;
134   InterpSection<ELFT> Interp;
135   PltSection<ELFT> Plt;
136   RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela);
137   StringTableSection<ELFT> DynStrTab(".dynstr", true);
138   StringTableSection<ELFT> ShStrTab(".shstrtab", false);
139   SymbolTableSection<ELFT> DynSymTab(*Symtab, DynStrTab);
140 
141   OutputSectionBase<ELFT> ElfHeader("", 0, SHF_ALLOC);
142   OutputSectionBase<ELFT> ProgramHeaders("", 0, SHF_ALLOC);
143   ProgramHeaders.updateAlign(sizeof(uintX_t));
144 
145   // Instantiate optional output sections if they are needed.
146   std::unique_ptr<GnuHashTableSection<ELFT>> GnuHashTab;
147   std::unique_ptr<GotPltSection<ELFT>> GotPlt;
148   std::unique_ptr<HashTableSection<ELFT>> HashTab;
149   std::unique_ptr<RelocationSection<ELFT>> RelaPlt;
150   std::unique_ptr<StringTableSection<ELFT>> StrTab;
151   std::unique_ptr<SymbolTableSection<ELFT>> SymTabSec;
152   std::unique_ptr<OutputSection<ELFT>> MipsRldMap;
153 
154   if (Config->GnuHash)
155     GnuHashTab.reset(new GnuHashTableSection<ELFT>);
156   if (Config->SysvHash)
157     HashTab.reset(new HashTableSection<ELFT>);
158   if (Target->UseLazyBinding) {
159     StringRef S = IsRela ? ".rela.plt" : ".rel.plt";
160     GotPlt.reset(new GotPltSection<ELFT>);
161     RelaPlt.reset(new RelocationSection<ELFT>(S, IsRela));
162   }
163   if (!Config->StripAll) {
164     StrTab.reset(new StringTableSection<ELFT>(".strtab", false));
165     SymTabSec.reset(new SymbolTableSection<ELFT>(*Symtab, *StrTab));
166   }
167   if (Config->EMachine == EM_MIPS && !Config->Shared) {
168     // This is a MIPS specific section to hold a space within the data segment
169     // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
170     // See "Dynamic section" in Chapter 5 in the following document:
171     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
172     MipsRldMap.reset(new OutputSection<ELFT>(".rld_map", SHT_PROGBITS,
173                                              SHF_ALLOC | SHF_WRITE));
174     MipsRldMap->setSize(sizeof(uintX_t));
175     MipsRldMap->updateAlign(sizeof(uintX_t));
176   }
177 
178   Out<ELFT>::DynStrTab = &DynStrTab;
179   Out<ELFT>::DynSymTab = &DynSymTab;
180   Out<ELFT>::Dynamic = &Dynamic;
181   Out<ELFT>::EhFrameHdr = &EhFrameHdr;
182   Out<ELFT>::GnuHashTab = GnuHashTab.get();
183   Out<ELFT>::Got = &Got;
184   Out<ELFT>::GotPlt = GotPlt.get();
185   Out<ELFT>::HashTab = HashTab.get();
186   Out<ELFT>::Interp = &Interp;
187   Out<ELFT>::Plt = &Plt;
188   Out<ELFT>::RelaDyn = &RelaDyn;
189   Out<ELFT>::RelaPlt = RelaPlt.get();
190   Out<ELFT>::ShStrTab = &ShStrTab;
191   Out<ELFT>::StrTab = StrTab.get();
192   Out<ELFT>::SymTab = SymTabSec.get();
193   Out<ELFT>::Bss = nullptr;
194   Out<ELFT>::MipsRldMap = MipsRldMap.get();
195   Out<ELFT>::Opd = nullptr;
196   Out<ELFT>::OpdBuf = nullptr;
197   Out<ELFT>::TlsPhdr = nullptr;
198   Out<ELFT>::ElfHeader = &ElfHeader;
199   Out<ELFT>::ProgramHeaders = &ProgramHeaders;
200 
201   Writer<ELFT>(*Symtab).run();
202 }
203 
204 // The main function of the writer.
205 template <class ELFT> void Writer<ELFT>::run() {
206   if (!Config->DiscardAll)
207     copyLocalSymbols();
208   addReservedSymbols();
209   if (!createSections())
210     return;
211   if (!Config->Relocatable) {
212     createPhdrs();
213     assignAddresses();
214   } else {
215     assignAddressesRelocatable();
216   }
217   fixAbsoluteSymbols();
218   if (!openFile())
219     return;
220   writeHeader();
221   writeSections();
222   if (HasError)
223     return;
224   fatal(Buffer->commit());
225 }
226 
227 namespace {
228 template <bool Is64Bits> struct SectionKey {
229   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
230   StringRef Name;
231   uint32_t Type;
232   uintX_t Flags;
233   uintX_t Alignment;
234 };
235 }
236 namespace llvm {
237 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
238   static SectionKey<Is64Bits> getEmptyKey() {
239     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
240                                 0};
241   }
242   static SectionKey<Is64Bits> getTombstoneKey() {
243     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
244                                 0, 0};
245   }
246   static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
247     return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
248   }
249   static bool isEqual(const SectionKey<Is64Bits> &LHS,
250                       const SectionKey<Is64Bits> &RHS) {
251     return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
252            LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
253            LHS.Alignment == RHS.Alignment;
254   }
255 };
256 }
257 
258 template <class ELFT, class RelT>
259 static bool handleTlsRelocation(unsigned Type, SymbolBody *Body,
260                                 InputSectionBase<ELFT> &C, RelT &RI) {
261   if (Target->isTlsLocalDynamicRel(Type)) {
262     if (Target->canRelaxTls(Type, nullptr))
263       return true;
264     if (Out<ELFT>::Got->addTlsIndex())
265       Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel,
266                                     DynamicReloc<ELFT>::Off_LTlsIndex,
267                                     nullptr});
268     return true;
269   }
270 
271   if (!Body || !Body->IsTls)
272     return false;
273 
274   if (Target->isTlsGlobalDynamicRel(Type)) {
275     if (!Target->canRelaxTls(Type, Body)) {
276       if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
277         Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel,
278                                       DynamicReloc<ELFT>::Off_GTlsIndex, Body});
279         Out<ELFT>::RelaDyn->addReloc(
280             {Target->TlsOffsetRel, DynamicReloc<ELFT>::Off_GTlsOffset, Body});
281       }
282       return true;
283     }
284     if (!canBePreempted(Body))
285       return true;
286   }
287   return !Target->isTlsDynRel(Type, *Body);
288 }
289 
290 // The reason we have to do this early scan is as follows
291 // * To mmap the output file, we need to know the size
292 // * For that, we need to know how many dynamic relocs we will have.
293 // It might be possible to avoid this by outputting the file with write:
294 // * Write the allocated output sections, computing addresses.
295 // * Apply relocations, recording which ones require a dynamic reloc.
296 // * Write the dynamic relocations.
297 // * Write the rest of the file.
298 // This would have some drawbacks. For example, we would only know if .rela.dyn
299 // is needed after applying relocations. If it is, it will go after rw and rx
300 // sections. Given that it is ro, we will need an extra PT_LOAD. This
301 // complicates things for the dynamic linker and means we would have to reserve
302 // space for the extra PT_LOAD even if we end up not using it.
303 template <class ELFT>
304 template <bool isRela>
305 void Writer<ELFT>::scanRelocs(
306     InputSectionBase<ELFT> &C,
307     iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
308   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
309   const ObjectFile<ELFT> &File = *C.getFile();
310   for (const RelType &RI : Rels) {
311     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
312     SymbolBody *Body = File.getSymbolBody(SymIndex);
313     uint32_t Type = RI.getType(Config->Mips64EL);
314 
315     // Ignore "hint" relocation because it is for optional code optimization.
316     if (Target->isHintRel(Type))
317       continue;
318 
319     if (Target->isGotRelative(Type))
320       HasGotOffRel = true;
321 
322     // Set "used" bit for --as-needed.
323     if (Body && Body->isUndefined() && !Body->isWeak())
324       if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl()))
325         S->File->IsUsed = true;
326 
327     if (Body)
328       Body = Body->repl();
329 
330     bool CBP = canBePreempted(Body);
331     if (handleTlsRelocation<ELFT>(Type, Body, C, RI))
332       continue;
333 
334     if (Target->needsDynRelative(Type))
335       Out<ELFT>::RelaDyn->addReloc({Target->RelativeRel, &C, RI.r_offset, true,
336                                     Body, getAddend<ELFT>(RI)});
337 
338     // MIPS has a special rule to create GOTs for local symbols.
339     if (Config->EMachine == EM_MIPS && !CBP &&
340         (Type == R_MIPS_GOT16 || Type == R_MIPS_CALL16)) {
341       // FIXME (simon): Do not add so many redundant entries.
342       Out<ELFT>::Got->addMipsLocalEntry();
343       continue;
344     }
345 
346     // If a symbol in a DSO is referenced directly instead of through GOT,
347     // we need to create a copy relocation for the symbol.
348     if (auto *B = dyn_cast_or_null<SharedSymbol<ELFT>>(Body)) {
349       if (B->needsCopy())
350         continue;
351       if (Target->needsCopyRel<ELFT>(Type, *B)) {
352         B->NeedsCopyOrPltAddr = true;
353         Out<ELFT>::RelaDyn->addReloc(
354             {Target->CopyRel, DynamicReloc<ELFT>::Off_Bss, B});
355         continue;
356       }
357     }
358 
359     // An STT_GNU_IFUNC symbol always uses a PLT entry, and all references
360     // to the symbol go through the PLT. This is true even for a local
361     // symbol, although local symbols normally do not require PLT entries.
362     if (Body && isGnuIFunc<ELFT>(*Body)) {
363       if (Body->isInPlt())
364         continue;
365       Out<ELFT>::Plt->addEntry(Body);
366       if (Target->UseLazyBinding) {
367         Out<ELFT>::GotPlt->addEntry(Body);
368         Out<ELFT>::RelaPlt->addReloc(
369             {CBP ? Target->PltRel : Target->IRelativeRel,
370              DynamicReloc<ELFT>::Off_GotPlt, !CBP, Body});
371       } else {
372         Out<ELFT>::Got->addEntry(Body);
373         Out<ELFT>::RelaDyn->addReloc(
374             {CBP ? Target->PltRel : Target->IRelativeRel,
375              DynamicReloc<ELFT>::Off_Got, !CBP, Body});
376       }
377       continue;
378     }
379 
380     // If a relocation needs PLT, we create a PLT and a GOT slot
381     // for the symbol.
382     TargetInfo::PltNeed NeedPlt = TargetInfo::Plt_No;
383     if (Body)
384       NeedPlt = Target->needsPlt<ELFT>(Type, *Body);
385     if (NeedPlt) {
386       if (NeedPlt == TargetInfo::Plt_Implicit)
387         Body->NeedsCopyOrPltAddr = true;
388       if (Body->isInPlt())
389         continue;
390       Out<ELFT>::Plt->addEntry(Body);
391 
392       if (Target->UseLazyBinding) {
393         Out<ELFT>::GotPlt->addEntry(Body);
394         Out<ELFT>::RelaPlt->addReloc(
395             {Target->PltRel, DynamicReloc<ELFT>::Off_GotPlt, Body});
396       } else {
397         if (Body->isInGot())
398           continue;
399         Out<ELFT>::Got->addEntry(Body);
400         Out<ELFT>::RelaDyn->addReloc(
401             {Target->GotRel, DynamicReloc<ELFT>::Off_Got, Body});
402       }
403       continue;
404     }
405 
406     // If a relocation needs GOT, we create a GOT slot for the symbol.
407     if (Body && Target->needsGot(Type, *Body)) {
408       if (Body->isInGot())
409         continue;
410       Out<ELFT>::Got->addEntry(Body);
411 
412       if (Config->EMachine == EM_MIPS) {
413         // MIPS ABI has special rules to process GOT entries
414         // and doesn't require relocation entries for them.
415         // See "Global Offset Table" in Chapter 5 in the following document
416         // for detailed description:
417         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
418         Body->MustBeInDynSym = true;
419         continue;
420       }
421 
422       bool Dynrel = Config->Shared && !Target->isRelRelative(Type) &&
423                     !Target->isSizeRel(Type);
424       if (CBP || Dynrel) {
425         uint32_t DynType;
426         if (CBP)
427           DynType = Body->IsTls ? Target->TlsGotRel : Target->GotRel;
428         else
429           DynType = Target->RelativeRel;
430         Out<ELFT>::RelaDyn->addReloc(
431             {DynType, DynamicReloc<ELFT>::Off_Got, !CBP, Body});
432       }
433       continue;
434     }
435 
436     if (Config->EMachine == EM_MIPS) {
437       if (Type == R_MIPS_LO16)
438         // Ignore R_MIPS_LO16 relocation. If it is a pair for R_MIPS_GOT16 we
439         // already completed all required action (GOT entry allocation) when
440         // handle R_MIPS_GOT16a. If it is a pair for R_MIPS_HI16 against
441         // _gp_disp it does not require dynamic relocation. If its a pair for
442         // R_MIPS_HI16 against a regular symbol it does not require dynamic
443         // relocation too because that case is possible for executable file
444         // linking only.
445         continue;
446       if (Body == Config->MipsGpDisp || Body == Config->MipsLocalGp)
447         // MIPS _gp_disp designates offset between start of function and 'gp'
448         // pointer into GOT. __gnu_local_gp is equal to the current value of
449         // the 'gp'. Therefore any relocations against them do not require
450         // dynamic relocation.
451         continue;
452     }
453 
454     if (CBP) {
455       // We don't know anything about the finaly symbol. Just ask the dynamic
456       // linker to handle the relocation for us.
457       Out<ELFT>::RelaDyn->addReloc({Target->getDynRel(Type), &C, RI.r_offset,
458                                     false, Body, getAddend<ELFT>(RI)});
459       continue;
460     }
461 
462     // We know that this is the final symbol. If the program being produced
463     // is position independent, the final value is still not known.
464     // If the relocation depends on the symbol value (not the size or distances
465     // in the output), we still need some help from the dynamic linker.
466     // We can however do better than just copying the incoming relocation. We
467     // can process some of it and and just ask the dynamic linker to add the
468     // load address.
469     if (!Config->Shared || Target->isRelRelative(Type) ||
470         Target->isSizeRel(Type))
471       continue;
472 
473     uintX_t Addend = getAddend<ELFT>(RI);
474     if (Config->EMachine == EM_PPC64 && RI.getType(false) == R_PPC64_TOC) {
475       Out<ELFT>::RelaDyn->addReloc({R_PPC64_RELATIVE, &C, RI.r_offset, false,
476                                     nullptr,
477                                     (uintX_t)getPPC64TocBase() + Addend});
478       continue;
479     }
480     if (Body) {
481       Out<ELFT>::RelaDyn->addReloc(
482           {Target->RelativeRel, &C, RI.r_offset, true, Body, Addend});
483       continue;
484     }
485     const Elf_Sym *Sym =
486         File.getObj().getRelocationSymbol(&RI, File.getSymbolTable());
487     InputSectionBase<ELFT> *Section = File.getSection(*Sym);
488     uintX_t Offset = Sym->st_value;
489     if (Sym->getType() == STT_SECTION) {
490       Offset += Addend;
491       Addend = 0;
492     }
493     Out<ELFT>::RelaDyn->addReloc(
494         {Target->RelativeRel, &C, RI.r_offset, Section, Offset, Addend});
495   }
496 }
497 
498 template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) {
499   if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
500     for (const Elf_Shdr *RelSec : C.RelocSections)
501       scanRelocs(C, *RelSec);
502 }
503 
504 template <class ELFT>
505 void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S,
506                               const Elf_Shdr &RelSec) {
507   ELFFile<ELFT> &EObj = S.getFile()->getObj();
508   if (RelSec.sh_type == SHT_RELA)
509     scanRelocs(S, EObj.relas(&RelSec));
510   else
511     scanRelocs(S, EObj.rels(&RelSec));
512 }
513 
514 template <class ELFT>
515 static void reportUndefined(SymbolTable<ELFT> &Symtab, SymbolBody *Sym) {
516   if ((Config->Relocatable || Config->Shared) && !Config->NoUndefined)
517     return;
518 
519   std::string Msg = "undefined symbol: " + Sym->getName().str();
520   if (InputFile *File = Symtab.findFile(Sym))
521     Msg += " in " + File->getName().str();
522   if (Config->NoInhibitExec)
523     warning(Msg);
524   else
525     error(Msg);
526 }
527 
528 template <class ELFT>
529 static bool shouldKeepInSymtab(const ObjectFile<ELFT> &File, StringRef SymName,
530                                const typename ELFFile<ELFT>::Elf_Sym &Sym) {
531   if (Sym.getType() == STT_SECTION || Sym.getType() == STT_FILE)
532     return false;
533 
534   InputSectionBase<ELFT> *Sec = File.getSection(Sym);
535   // If sym references a section in a discarded group, don't keep it.
536   if (Sec == InputSection<ELFT>::Discarded)
537     return false;
538 
539   if (Config->DiscardNone)
540     return true;
541 
542   // In ELF assembly .L symbols are normally discarded by the assembler.
543   // If the assembler fails to do so, the linker discards them if
544   // * --discard-locals is used.
545   // * The symbol is in a SHF_MERGE section, which is normally the reason for
546   //   the assembler keeping the .L symbol.
547   if (!SymName.startswith(".L") && !SymName.empty())
548     return true;
549 
550   if (Config->DiscardLocals)
551     return false;
552 
553   return !(Sec->getSectionHdr()->sh_flags & SHF_MERGE);
554 }
555 
556 // Local symbols are not in the linker's symbol table. This function scans
557 // each object file's symbol table to copy local symbols to the output.
558 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
559   if (!Out<ELFT>::SymTab)
560     return;
561   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
562     for (const Elf_Sym &Sym : F->getLocalSymbols()) {
563       ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable());
564       fatal(SymNameOrErr);
565       StringRef SymName = *SymNameOrErr;
566       if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym))
567         continue;
568       if (Sym.st_shndx != SHN_ABS) {
569         InputSectionBase<ELFT> *Section = F->getSection(Sym);
570         if (!Section->Live)
571           continue;
572       }
573       ++Out<ELFT>::SymTab->NumLocals;
574       F->KeptLocalSyms.push_back(std::make_pair(
575           &Sym, Out<ELFT>::SymTab->StrTabSec.addString(SymName)));
576     }
577   }
578 }
579 
580 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
581 // we would like to make sure appear is a specific order to maximize their
582 // coverage by a single signed 16-bit offset from the TOC base pointer.
583 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
584 // sections. This will put it next to the loaded special PPC64 sections (and,
585 // thus, within reach of the TOC base pointer).
586 static int getPPC64SectionRank(StringRef SectionName) {
587   return StringSwitch<int>(SectionName)
588            .Case(".tocbss", 0)
589            .Case(".branch_lt", 2)
590            .Case(".toc", 3)
591            .Case(".toc1", 4)
592            .Case(".opd", 5)
593            .Default(1);
594 }
595 
596 template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
597   if (!Config->ZRelro)
598     return false;
599   typename OutputSectionBase<ELFT>::uintX_t Flags = Sec->getFlags();
600   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
601     return false;
602   if (Flags & SHF_TLS)
603     return true;
604   uint32_t Type = Sec->getType();
605   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
606       Type == SHT_PREINIT_ARRAY)
607     return true;
608   if (Sec == Out<ELFT>::GotPlt)
609     return Config->ZNow;
610   if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
611     return true;
612   StringRef S = Sec->getName();
613   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
614          S == ".eh_frame";
615 }
616 
617 // Output section ordering is determined by this function.
618 template <class ELFT>
619 static bool compareSections(OutputSectionBase<ELFT> *A,
620                             OutputSectionBase<ELFT> *B) {
621   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
622 
623   int Comp = Script->compareSections(A->getName(), B->getName());
624   if (Comp != 0)
625     return Comp < 0;
626 
627   uintX_t AFlags = A->getFlags();
628   uintX_t BFlags = B->getFlags();
629 
630   // Allocatable sections go first to reduce the total PT_LOAD size and
631   // so debug info doesn't change addresses in actual code.
632   bool AIsAlloc = AFlags & SHF_ALLOC;
633   bool BIsAlloc = BFlags & SHF_ALLOC;
634   if (AIsAlloc != BIsAlloc)
635     return AIsAlloc;
636 
637   // We don't have any special requirements for the relative order of
638   // two non allocatable sections.
639   if (!AIsAlloc)
640     return false;
641 
642   // We want the read only sections first so that they go in the PT_LOAD
643   // covering the program headers at the start of the file.
644   bool AIsWritable = AFlags & SHF_WRITE;
645   bool BIsWritable = BFlags & SHF_WRITE;
646   if (AIsWritable != BIsWritable)
647     return BIsWritable;
648 
649   // For a corresponding reason, put non exec sections first (the program
650   // header PT_LOAD is not executable).
651   bool AIsExec = AFlags & SHF_EXECINSTR;
652   bool BIsExec = BFlags & SHF_EXECINSTR;
653   if (AIsExec != BIsExec)
654     return BIsExec;
655 
656   // If we got here we know that both A and B are in the same PT_LOAD.
657 
658   // The TLS initialization block needs to be a single contiguous block in a R/W
659   // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
660   // sections are placed here as they don't take up virtual address space in the
661   // PT_LOAD.
662   bool AIsTls = AFlags & SHF_TLS;
663   bool BIsTls = BFlags & SHF_TLS;
664   if (AIsTls != BIsTls)
665     return AIsTls;
666 
667   // The next requirement we have is to put nobits sections last. The
668   // reason is that the only thing the dynamic linker will see about
669   // them is a p_memsz that is larger than p_filesz. Seeing that it
670   // zeros the end of the PT_LOAD, so that has to correspond to the
671   // nobits sections.
672   bool AIsNoBits = A->getType() == SHT_NOBITS;
673   bool BIsNoBits = B->getType() == SHT_NOBITS;
674   if (AIsNoBits != BIsNoBits)
675     return BIsNoBits;
676 
677   // We place RelRo section before plain r/w ones.
678   bool AIsRelRo = isRelroSection(A);
679   bool BIsRelRo = isRelroSection(B);
680   if (AIsRelRo != BIsRelRo)
681     return AIsRelRo;
682 
683   // Some architectures have additional ordering restrictions for sections
684   // within the same PT_LOAD.
685   if (Config->EMachine == EM_PPC64)
686     return getPPC64SectionRank(A->getName()) <
687            getPPC64SectionRank(B->getName());
688 
689   return false;
690 }
691 
692 template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBss() {
693   if (!Out<ELFT>::Bss) {
694     Out<ELFT>::Bss =
695         new OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
696     OwningSections.emplace_back(Out<ELFT>::Bss);
697     OutputSections.push_back(Out<ELFT>::Bss);
698   }
699   return Out<ELFT>::Bss;
700 }
701 
702 // Until this function is called, common symbols do not belong to any section.
703 // This function adds them to end of BSS section.
704 template <class ELFT>
705 void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) {
706   if (Syms.empty())
707     return;
708 
709   // Sort the common symbols by alignment as an heuristic to pack them better.
710   std::stable_sort(Syms.begin(), Syms.end(),
711                    [](const DefinedCommon *A, const DefinedCommon *B) {
712                      return A->MaxAlignment > B->MaxAlignment;
713                    });
714 
715   uintX_t Off = getBss()->getSize();
716   for (DefinedCommon *C : Syms) {
717     Off = alignTo(Off, C->MaxAlignment);
718     C->OffsetInBss = Off;
719     Off += C->Size;
720   }
721 
722   Out<ELFT>::Bss->setSize(Off);
723 }
724 
725 // Reserve space in .bss for copy relocations.
726 template <class ELFT>
727 void Writer<ELFT>::addCopyRelSymbols(std::vector<SharedSymbol<ELFT> *> &Syms) {
728   if (Syms.empty())
729     return;
730   uintX_t Off = getBss()->getSize();
731   for (SharedSymbol<ELFT> *C : Syms) {
732     const Elf_Sym &Sym = C->Sym;
733     const Elf_Shdr *Sec = C->File->getSection(Sym);
734     uintX_t SecAlign = Sec->sh_addralign;
735     unsigned TrailingZeros =
736         std::min(countTrailingZeros(SecAlign),
737                  countTrailingZeros((uintX_t)Sym.st_value));
738     uintX_t Align = 1 << TrailingZeros;
739     Out<ELFT>::Bss->updateAlign(Align);
740     Off = alignTo(Off, Align);
741     C->OffsetInBss = Off;
742     Off += Sym.st_size;
743   }
744   Out<ELFT>::Bss->setSize(Off);
745 }
746 
747 template <class ELFT>
748 StringRef Writer<ELFT>::getOutputSectionName(InputSectionBase<ELFT> *S) const {
749   StringRef Dest = Script->getOutputSection<ELFT>(S);
750   if (!Dest.empty())
751     return Dest;
752 
753   StringRef Name = S->getSectionName();
754   for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
755                       ".init_array.", ".fini_array.", ".ctors.", ".dtors.",
756                       ".tbss.", ".gcc_except_table.", ".tdata."})
757     if (Name.startswith(V))
758       return V.drop_back();
759   return Name;
760 }
761 
762 template <class ELFT>
763 void reportDiscarded(InputSectionBase<ELFT> *IS,
764                      const std::unique_ptr<ObjectFile<ELFT>> &File) {
765   if (!Config->PrintGcSections || !IS || IS->Live)
766     return;
767   llvm::errs() << "removing unused section from '" << IS->getSectionName()
768                << "' in file '" << File->getName() << "'\n";
769 }
770 
771 template <class ELFT>
772 bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) const {
773   return !S || S == InputSection<ELFT>::Discarded || !S->Live ||
774          Script->isDiscarded(S);
775 }
776 
777 // The beginning and the ending of .rel[a].plt section are marked
778 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
779 // executable. The runtime needs these symbols in order to resolve
780 // all IRELATIVE relocs on startup. For dynamic executables, we don't
781 // need these symbols, since IRELATIVE relocs are resolved through GOT
782 // and PLT. For details, see http://www.airs.com/blog/archives/403.
783 template <class ELFT>
784 void Writer<ELFT>::addRelIpltSymbols() {
785   if (isOutputDynamic() || !Out<ELFT>::RelaPlt)
786     return;
787   bool IsRela = shouldUseRela<ELFT>();
788 
789   StringRef S = IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
790   if (Symtab.find(S))
791     Symtab.addAbsolute(S, ElfSym<ELFT>::RelaIpltStart);
792 
793   S = IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
794   if (Symtab.find(S))
795     Symtab.addAbsolute(S, ElfSym<ELFT>::RelaIpltEnd);
796 }
797 
798 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
799   if (!B.isUsedInRegularObj())
800     return false;
801 
802   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
803     // Don't include synthetic symbols like __init_array_start in every output.
804     if (&D->Sym == &ElfSym<ELFT>::Ignored)
805       return false;
806     // Exclude symbols pointing to garbage-collected sections.
807     if (D->Section && !D->Section->Live)
808       return false;
809   }
810   return true;
811 }
812 
813 static bool includeInDynsym(const SymbolBody &B) {
814   uint8_t V = B.getVisibility();
815   if (V != STV_DEFAULT && V != STV_PROTECTED)
816     return false;
817   if (Config->ExportDynamic || Config->Shared)
818     return true;
819   return B.MustBeInDynSym;
820 }
821 
822 // This class knows how to create an output section for a given
823 // input section. Output section type is determined by various
824 // factors, including input section's sh_flags, sh_type and
825 // linker scripts.
826 namespace {
827 template <class ELFT> class OutputSectionFactory {
828   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
829   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
830 
831 public:
832   std::pair<OutputSectionBase<ELFT> *, bool> create(InputSectionBase<ELFT> *C,
833                                                     StringRef OutsecName);
834 
835   OutputSectionBase<ELFT> *lookup(StringRef Name, uint32_t Type, uintX_t Flags);
836 
837 private:
838   SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
839                                        StringRef OutsecName);
840 
841   SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
842 };
843 }
844 
845 template <class ELFT>
846 std::pair<OutputSectionBase<ELFT> *, bool>
847 OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
848                                    StringRef OutsecName) {
849   SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
850   OutputSectionBase<ELFT> *&Sec = Map[Key];
851   if (Sec)
852     return {Sec, false};
853 
854   switch (C->SectionKind) {
855   case InputSectionBase<ELFT>::Regular:
856     Sec = new OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
857     break;
858   case InputSectionBase<ELFT>::EHFrame:
859     Sec = new EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
860     break;
861   case InputSectionBase<ELFT>::Merge:
862     Sec = new MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags,
863                                        Key.Alignment);
864     break;
865   case InputSectionBase<ELFT>::MipsReginfo:
866     Sec = new MipsReginfoOutputSection<ELFT>();
867     break;
868   }
869   return {Sec, true};
870 }
871 
872 template <class ELFT>
873 OutputSectionBase<ELFT> *OutputSectionFactory<ELFT>::lookup(StringRef Name,
874                                                             uint32_t Type,
875                                                             uintX_t Flags) {
876   return Map.lookup({Name, Type, Flags, 0});
877 }
878 
879 template <class ELFT>
880 SectionKey<ELFT::Is64Bits>
881 OutputSectionFactory<ELFT>::createKey(InputSectionBase<ELFT> *C,
882                                       StringRef OutsecName) {
883   const Elf_Shdr *H = C->getSectionHdr();
884   uintX_t Flags = H->sh_flags & ~SHF_GROUP;
885 
886   // For SHF_MERGE we create different output sections for each alignment.
887   // This makes each output section simple and keeps a single level mapping from
888   // input to output.
889   uintX_t Alignment = 0;
890   if (isa<MergeInputSection<ELFT>>(C)) {
891     Alignment = H->sh_addralign;
892     if (H->sh_entsize > Alignment)
893       Alignment = H->sh_entsize;
894   }
895 
896   // GNU as can give .eh_frame secion type SHT_PROGBITS or SHT_X86_64_UNWIND
897   // depending on the construct. We want to canonicalize it so that
898   // there is only one .eh_frame in the end.
899   uint32_t Type = H->sh_type;
900   if (Type == SHT_PROGBITS && Config->EMachine == EM_X86_64 &&
901       isa<EHInputSection<ELFT>>(C))
902     Type = SHT_X86_64_UNWIND;
903 
904   return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
905 }
906 
907 // The linker is expected to define some symbols depending on
908 // the linking result. This function defines such symbols.
909 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
910   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
911   // static linking the linker is required to optimize away any references to
912   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
913   // to avoid the undefined symbol error.
914   if (!isOutputDynamic())
915     Symtab.addIgnored("__tls_get_addr");
916 
917   auto Define = [this](StringRef S, Elf_Sym &Sym) {
918     if (Symtab.find(S))
919       Symtab.addAbsolute(S, Sym);
920 
921     // The name without the underscore is not a reserved name,
922     // so it is defined only when there is a reference against it.
923     assert(S.startswith("_"));
924     S = S.substr(1);
925     if (SymbolBody *B = Symtab.find(S))
926       if (B->isUndefined())
927         Symtab.addAbsolute(S, Sym);
928   };
929 
930   Define("_end", ElfSym<ELFT>::End);
931   Define("_etext", ElfSym<ELFT>::Etext);
932   Define("_edata", ElfSym<ELFT>::Edata);
933 }
934 
935 // Sort input sections by section name suffixes for
936 // __attribute__((init_priority(N))).
937 template <class ELFT> static void sortInitFini(OutputSectionBase<ELFT> *S) {
938   if (S)
939     reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
940 }
941 
942 // Sort input sections by the special rule for .ctors and .dtors.
943 template <class ELFT> static void sortCtorsDtors(OutputSectionBase<ELFT> *S) {
944   if (S)
945     reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
946 }
947 
948 // Create output section objects and add them to OutputSections.
949 template <class ELFT> bool Writer<ELFT>::createSections() {
950   OutputSections.push_back(Out<ELFT>::ElfHeader);
951   if (!Config->Relocatable)
952     OutputSections.push_back(Out<ELFT>::ProgramHeaders);
953 
954   // Add .interp first because some loaders want to see that section
955   // on the first page of the executable file when loaded into memory.
956   if (needsInterpSection())
957     OutputSections.push_back(Out<ELFT>::Interp);
958 
959   // Create output sections for input object file sections.
960   std::vector<OutputSectionBase<ELFT> *> RegularSections;
961   OutputSectionFactory<ELFT> Factory;
962   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
963     for (InputSectionBase<ELFT> *C : F->getSections()) {
964       if (isDiscarded(C)) {
965         reportDiscarded(C, F);
966         continue;
967       }
968       OutputSectionBase<ELFT> *Sec;
969       bool IsNew;
970       std::tie(Sec, IsNew) = Factory.create(C, getOutputSectionName(C));
971       if (IsNew) {
972         OwningSections.emplace_back(Sec);
973         OutputSections.push_back(Sec);
974         RegularSections.push_back(Sec);
975       }
976       Sec->addSection(C);
977     }
978   }
979 
980   Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
981       Factory.lookup(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE));
982 
983   // If we have a .opd section (used under PPC64 for function descriptors),
984   // store a pointer to it here so that we can use it later when processing
985   // relocations.
986   Out<ELFT>::Opd = Factory.lookup(".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC);
987 
988   Out<ELFT>::Dynamic->PreInitArraySec = Factory.lookup(
989       ".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC);
990   Out<ELFT>::Dynamic->InitArraySec =
991       Factory.lookup(".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC);
992   Out<ELFT>::Dynamic->FiniArraySec =
993       Factory.lookup(".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC);
994 
995   // Sort section contents for __attribute__((init_priority(N)).
996   sortInitFini(Out<ELFT>::Dynamic->InitArraySec);
997   sortInitFini(Out<ELFT>::Dynamic->FiniArraySec);
998   sortCtorsDtors(Factory.lookup(".ctors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
999   sortCtorsDtors(Factory.lookup(".dtors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
1000 
1001   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1002   // symbols for sections, so that the runtime can get the start and end
1003   // addresses of each section by section name. Add such symbols.
1004   addStartEndSymbols();
1005   for (OutputSectionBase<ELFT> *Sec : RegularSections)
1006     addStartStopSymbols(Sec);
1007 
1008   // Define __rel[a]_iplt_{start,end} symbols if needed.
1009   addRelIpltSymbols();
1010 
1011   // Scan relocations. This must be done after every symbol is declared so that
1012   // we can correctly decide if a dynamic relocation is needed.
1013   for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
1014     for (InputSectionBase<ELFT> *C : F->getSections()) {
1015       if (isDiscarded(C))
1016         continue;
1017       if (auto *S = dyn_cast<InputSection<ELFT>>(C))
1018         scanRelocs(*S);
1019       else if (auto *S = dyn_cast<EHInputSection<ELFT>>(C))
1020         if (S->RelocSection)
1021           scanRelocs(*S, *S->RelocSection);
1022     }
1023   }
1024 
1025   // Now that we have defined all possible symbols including linker-
1026   // synthesized ones. Visit all symbols to give the finishing touches.
1027   std::vector<DefinedCommon *> CommonSymbols;
1028   std::vector<SharedSymbol<ELFT> *> CopyRelSymbols;
1029   for (auto &P : Symtab.getSymbols()) {
1030     SymbolBody *Body = P.second->Body;
1031     if (auto *U = dyn_cast<Undefined>(Body))
1032       if (!U->isWeak() && !U->canKeepUndefined())
1033         reportUndefined<ELFT>(Symtab, Body);
1034 
1035     if (auto *C = dyn_cast<DefinedCommon>(Body))
1036       CommonSymbols.push_back(C);
1037     if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body))
1038       if (SC->needsCopy())
1039         CopyRelSymbols.push_back(SC);
1040 
1041     if (!includeInSymtab<ELFT>(*Body))
1042       continue;
1043     if (Out<ELFT>::SymTab)
1044       Out<ELFT>::SymTab->addSymbol(Body);
1045 
1046     if (isOutputDynamic() && includeInDynsym(*Body))
1047       Out<ELFT>::DynSymTab->addSymbol(Body);
1048   }
1049 
1050   // Do not proceed if there was an undefined symbol.
1051   if (HasError)
1052     return false;
1053 
1054   addCommonSymbols(CommonSymbols);
1055   addCopyRelSymbols(CopyRelSymbols);
1056 
1057   // So far we have added sections from input object files.
1058   // This function adds linker-created Out<ELFT>::* sections.
1059   addPredefinedSections();
1060 
1061   std::stable_sort(OutputSections.begin(), OutputSections.end(),
1062                    compareSections<ELFT>);
1063 
1064   for (unsigned I = dummySectionsNum(), N = OutputSections.size(); I < N; ++I)
1065     OutputSections[I]->SectionIndex = I + 1 - dummySectionsNum();
1066 
1067   for (OutputSectionBase<ELFT> *Sec : getSections())
1068     Sec->setSHName(Out<ELFT>::ShStrTab->addString(Sec->getName()));
1069 
1070   // Finalizers fix each section's size.
1071   // .dynsym is finalized early since that may fill up .gnu.hash.
1072   if (isOutputDynamic())
1073     Out<ELFT>::DynSymTab->finalize();
1074 
1075   // Fill other section headers. The dynamic table is finalized
1076   // at the end because some tags like RELSZ depend on result
1077   // of finalizing other sections. The dynamic string table is
1078   // finalized once the .dynamic finalizer has added a few last
1079   // strings. See DynamicSection::finalize()
1080   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1081     if (Sec != Out<ELFT>::DynStrTab && Sec != Out<ELFT>::Dynamic)
1082       Sec->finalize();
1083 
1084   if (isOutputDynamic())
1085     Out<ELFT>::Dynamic->finalize();
1086   return true;
1087 }
1088 
1089 template <class ELFT> bool Writer<ELFT>::needsGot() {
1090   if (!Out<ELFT>::Got->empty())
1091     return true;
1092 
1093   // We add the .got section to the result for dynamic MIPS target because
1094   // its address and properties are mentioned in the .dynamic section.
1095   if (Config->EMachine == EM_MIPS && isOutputDynamic())
1096     return true;
1097 
1098   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
1099   // we need to emit a GOT even if it's empty.
1100   return HasGotOffRel;
1101 }
1102 
1103 // This function add Out<ELFT>::* sections to OutputSections.
1104 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1105   auto Add = [&](OutputSectionBase<ELFT> *C) {
1106     if (C)
1107       OutputSections.push_back(C);
1108   };
1109 
1110   // This order is not the same as the final output order
1111   // because we sort the sections using their attributes below.
1112   Add(Out<ELFT>::SymTab);
1113   Add(Out<ELFT>::ShStrTab);
1114   Add(Out<ELFT>::StrTab);
1115   if (isOutputDynamic()) {
1116     Add(Out<ELFT>::DynSymTab);
1117     Add(Out<ELFT>::GnuHashTab);
1118     Add(Out<ELFT>::HashTab);
1119     Add(Out<ELFT>::Dynamic);
1120     Add(Out<ELFT>::DynStrTab);
1121     if (Out<ELFT>::RelaDyn->hasRelocs())
1122       Add(Out<ELFT>::RelaDyn);
1123     Add(Out<ELFT>::MipsRldMap);
1124   }
1125 
1126   // We always need to add rel[a].plt to output if it has entries.
1127   // Even during static linking it can contain R_[*]_IRELATIVE relocations.
1128   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
1129     Add(Out<ELFT>::RelaPlt);
1130     Out<ELFT>::RelaPlt->Static = !isOutputDynamic();
1131   }
1132 
1133   if (needsGot())
1134     Add(Out<ELFT>::Got);
1135   if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
1136     Add(Out<ELFT>::GotPlt);
1137   if (!Out<ELFT>::Plt->empty())
1138     Add(Out<ELFT>::Plt);
1139   if (Out<ELFT>::EhFrameHdr->Live)
1140     Add(Out<ELFT>::EhFrameHdr);
1141 }
1142 
1143 // The linker is expected to define SECNAME_start and SECNAME_end
1144 // symbols for a few sections. This function defines them.
1145 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1146   auto Define = [&](StringRef Start, StringRef End,
1147                     OutputSectionBase<ELFT> *OS) {
1148     if (OS) {
1149       Symtab.addSynthetic(Start, *OS, 0);
1150       Symtab.addSynthetic(End, *OS, OS->getSize());
1151     } else {
1152       Symtab.addIgnored(Start);
1153       Symtab.addIgnored(End);
1154     }
1155   };
1156 
1157   Define("__preinit_array_start", "__preinit_array_end",
1158          Out<ELFT>::Dynamic->PreInitArraySec);
1159   Define("__init_array_start", "__init_array_end",
1160          Out<ELFT>::Dynamic->InitArraySec);
1161   Define("__fini_array_start", "__fini_array_end",
1162          Out<ELFT>::Dynamic->FiniArraySec);
1163 }
1164 
1165 // If a section name is valid as a C identifier (which is rare because of
1166 // the leading '.'), linkers are expected to define __start_<secname> and
1167 // __stop_<secname> symbols. They are at beginning and end of the section,
1168 // respectively. This is not requested by the ELF standard, but GNU ld and
1169 // gold provide the feature, and used by many programs.
1170 template <class ELFT>
1171 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
1172   StringRef S = Sec->getName();
1173   if (!isValidCIdentifier(S))
1174     return;
1175   StringSaver Saver(Alloc);
1176   StringRef Start = Saver.save("__start_" + S);
1177   StringRef Stop = Saver.save("__stop_" + S);
1178   if (SymbolBody *B = Symtab.find(Start))
1179     if (B->isUndefined())
1180       Symtab.addSynthetic(Start, *Sec, 0);
1181   if (SymbolBody *B = Symtab.find(Stop))
1182     if (B->isUndefined())
1183       Symtab.addSynthetic(Stop, *Sec, Sec->getSize());
1184 }
1185 
1186 template <class ELFT> static bool needsPtLoad(OutputSectionBase<ELFT> *Sec) {
1187   if (!(Sec->getFlags() & SHF_ALLOC))
1188     return false;
1189 
1190   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1191   // responsible for allocating space for them, not the PT_LOAD that
1192   // contains the TLS initialization image.
1193   if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS)
1194     return false;
1195   return true;
1196 }
1197 
1198 static uint32_t toPhdrFlags(uint64_t Flags) {
1199   uint32_t Ret = PF_R;
1200   if (Flags & SHF_WRITE)
1201     Ret |= PF_W;
1202   if (Flags & SHF_EXECINSTR)
1203     Ret |= PF_X;
1204   return Ret;
1205 }
1206 
1207 /// For AMDGPU we need to use custom segment kinds in order to specify which
1208 /// address space data should be loaded into.
1209 template <class ELFT>
1210 static uint32_t getAmdgpuPhdr(OutputSectionBase<ELFT> *Sec) {
1211   uint32_t Flags = Sec->getFlags();
1212   if (Flags & SHF_AMDGPU_HSA_CODE)
1213     return PT_AMDGPU_HSA_LOAD_CODE_AGENT;
1214   if ((Flags & SHF_AMDGPU_HSA_GLOBAL) && !(Flags & SHF_AMDGPU_HSA_AGENT))
1215     return PT_AMDGPU_HSA_LOAD_GLOBAL_PROGRAM;
1216   return PT_LOAD;
1217 }
1218 
1219 // Decide which program headers to create and which sections to include in each
1220 // one.
1221 template <class ELFT> void Writer<ELFT>::createPhdrs() {
1222   auto AddHdr = [this](unsigned Type, unsigned Flags) {
1223     return &*Phdrs.emplace(Phdrs.end(), Type, Flags);
1224   };
1225 
1226   auto AddSec = [](Phdr &Hdr, OutputSectionBase<ELFT> *Sec) {
1227     Hdr.Last = Sec;
1228     if (!Hdr.First)
1229       Hdr.First = Sec;
1230     Hdr.H.p_align = std::max<uintX_t>(Hdr.H.p_align, Sec->getAlign());
1231   };
1232 
1233   // The first phdr entry is PT_PHDR which describes the program header itself.
1234   Phdr &Hdr = *AddHdr(PT_PHDR, PF_R);
1235   AddSec(Hdr, Out<ELFT>::ProgramHeaders);
1236 
1237   // PT_INTERP must be the second entry if exists.
1238   if (needsInterpSection()) {
1239     Phdr &Hdr = *AddHdr(PT_INTERP, toPhdrFlags(Out<ELFT>::Interp->getFlags()));
1240     AddSec(Hdr, Out<ELFT>::Interp);
1241   }
1242 
1243   // Add the first PT_LOAD segment for regular output sections.
1244   uintX_t Flags = PF_R;
1245   Phdr *Load = AddHdr(PT_LOAD, Flags);
1246   AddSec(*Load, Out<ELFT>::ElfHeader);
1247 
1248   Phdr TlsHdr(PT_TLS, PF_R);
1249   Phdr RelRo(PT_GNU_RELRO, PF_R);
1250   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1251     if (!(Sec->getFlags() & SHF_ALLOC))
1252       break;
1253 
1254     // If we meet TLS section then we create TLS header
1255     // and put all TLS sections inside for futher use when
1256     // assign addresses.
1257     if (Sec->getFlags() & SHF_TLS)
1258       AddSec(TlsHdr, Sec);
1259 
1260     if (!needsPtLoad<ELFT>(Sec))
1261       continue;
1262 
1263     // If flags changed then we want new load segment.
1264     uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
1265     if (Flags != NewFlags) {
1266       uint32_t LoadType = (Config->EMachine == EM_AMDGPU) ? getAmdgpuPhdr(Sec)
1267                                                           : (uint32_t)PT_LOAD;
1268       Load = AddHdr(LoadType, NewFlags);
1269       Flags = NewFlags;
1270     }
1271 
1272     AddSec(*Load, Sec);
1273 
1274     if (isRelroSection(Sec))
1275       AddSec(RelRo, Sec);
1276   }
1277 
1278   // Add the TLS segment unless it's empty.
1279   if (TlsHdr.First)
1280     Phdrs.push_back(std::move(TlsHdr));
1281 
1282   // Add an entry for .dynamic.
1283   if (isOutputDynamic()) {
1284     Phdr &H = *AddHdr(PT_DYNAMIC, toPhdrFlags(Out<ELFT>::Dynamic->getFlags()));
1285     AddSec(H, Out<ELFT>::Dynamic);
1286   }
1287 
1288   // PT_GNU_RELRO includes all sections that should be marked as
1289   // read-only by dynamic linker after proccessing relocations.
1290   if (RelRo.First)
1291     Phdrs.push_back(std::move(RelRo));
1292 
1293   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1294   if (Out<ELFT>::EhFrameHdr->Live) {
1295     Phdr &Hdr = *AddHdr(PT_GNU_EH_FRAME,
1296                         toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags()));
1297     AddSec(Hdr, Out<ELFT>::EhFrameHdr);
1298   }
1299 
1300   // PT_GNU_STACK is a special section to tell the loader to make the
1301   // pages for the stack non-executable.
1302   if (!Config->ZExecStack)
1303     AddHdr(PT_GNU_STACK, PF_R | PF_W);
1304 }
1305 
1306 // Used for relocatable output (-r). In this case we create only ELF file
1307 // header, do not create program headers. Also assign of section addresses
1308 // is very straightforward: we just put all sections sequentually to the file.
1309 template <class ELFT> void Writer<ELFT>::assignAddressesRelocatable() {
1310   Out<ELFT>::ElfHeader->setSize(sizeof(Elf_Ehdr));
1311   uintX_t FileOff = 0;
1312   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1313     FileOff = alignTo(FileOff, Sec->getAlign());
1314     Sec->setFileOffset(FileOff);
1315     FileOff += Sec->getSize();
1316   }
1317   SectionHeaderOff = alignTo(FileOff, sizeof(uintX_t));
1318   FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr);
1319 }
1320 
1321 // Visits all headers in PhdrTable and assigns the adresses to
1322 // the output sections. Also creates common and special headers.
1323 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1324   Out<ELFT>::ElfHeader->setSize(sizeof(Elf_Ehdr));
1325   size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size();
1326   Out<ELFT>::ProgramHeaders->setSize(PhdrSize);
1327 
1328   // The first section of each PT_LOAD and the first section after PT_GNU_RELRO
1329   // have to be page aligned so that the dynamic linker can set the permissions.
1330   SmallPtrSet<OutputSectionBase<ELFT> *, 4> PageAlign;
1331   for (const Phdr &P : Phdrs) {
1332     if (P.H.p_type == PT_GNU_RELRO) {
1333       // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1334       // have to align it to a page.
1335       auto I = std::find(OutputSections.begin(), OutputSections.end(), P.Last);
1336       ++I;
1337       if (I != OutputSections.end() && needsPtLoad(*I))
1338         PageAlign.insert(*I);
1339     }
1340 
1341     if (P.H.p_type == PT_LOAD)
1342       PageAlign.insert(P.First);
1343   }
1344 
1345   uintX_t ThreadBssOffset = 0;
1346   uintX_t VA = Target->getVAStart();
1347   uintX_t FileOff = 0;
1348 
1349   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1350     uintX_t Align = Sec->getAlign();
1351     if (PageAlign.count(Sec))
1352       Align = std::max<uintX_t>(Align, Target->PageSize);
1353 
1354     if (Sec->getType() != SHT_NOBITS)
1355       FileOff = alignTo(FileOff, Align);
1356     Sec->setFileOffset(FileOff);
1357     if (Sec->getType() != SHT_NOBITS)
1358       FileOff += Sec->getSize();
1359 
1360     // We only assign VAs to allocated sections.
1361     if (needsPtLoad<ELFT>(Sec)) {
1362       VA = alignTo(VA, Align);
1363       Sec->setVA(VA);
1364       VA += Sec->getSize();
1365     } else if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS) {
1366       uintX_t TVA = VA + ThreadBssOffset;
1367       TVA = alignTo(TVA, Align);
1368       Sec->setVA(TVA);
1369       ThreadBssOffset = TVA - VA + Sec->getSize();
1370     }
1371   }
1372 
1373   // Add space for section headers.
1374   SectionHeaderOff = alignTo(FileOff, sizeof(uintX_t));
1375   FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr);
1376 
1377   // Update "_end" and "end" symbols so that they
1378   // point to the end of the data segment.
1379   ElfSym<ELFT>::End.st_value = VA;
1380 
1381   for (Phdr &PHdr : Phdrs) {
1382     Elf_Phdr &H = PHdr.H;
1383     if (PHdr.First) {
1384       OutputSectionBase<ELFT> *Last = PHdr.Last;
1385       H.p_filesz = Last->getFileOff() - PHdr.First->getFileOff();
1386       if (Last->getType() != SHT_NOBITS)
1387         H.p_filesz += Last->getSize();
1388       H.p_memsz = Last->getVA() + Last->getSize() - PHdr.First->getVA();
1389       H.p_offset = PHdr.First->getFileOff();
1390       H.p_vaddr = PHdr.First->getVA();
1391     }
1392     if (PHdr.H.p_type == PT_LOAD)
1393       H.p_align = Target->PageSize;
1394     else if (PHdr.H.p_type == PT_GNU_RELRO)
1395       H.p_align = 1;
1396     H.p_paddr = H.p_vaddr;
1397 
1398     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1399     // so round up the size to make sure the offsets are correct.
1400     if (PHdr.H.p_type == PT_TLS) {
1401       Out<ELFT>::TlsPhdr = &H;
1402       H.p_memsz = alignTo(H.p_memsz, H.p_align);
1403     }
1404   }
1405 }
1406 
1407 static uint32_t getELFFlags() {
1408   if (Config->EMachine != EM_MIPS)
1409     return 0;
1410   // FIXME: In fact ELF flags depends on ELF flags of input object files
1411   // and selected emulation. For now just use hard coded values.
1412   uint32_t V = EF_MIPS_ABI_O32 | EF_MIPS_CPIC | EF_MIPS_ARCH_32R2;
1413   if (Config->Shared)
1414     V |= EF_MIPS_PIC;
1415   return V;
1416 }
1417 
1418 template <class ELFT>
1419 static typename ELFFile<ELFT>::uintX_t getEntryAddr() {
1420   if (Config->EntrySym) {
1421     if (SymbolBody *B = Config->EntrySym->repl())
1422       return B->getVA<ELFT>();
1423     return 0;
1424   }
1425   if (Config->EntryAddr != uint64_t(-1))
1426     return Config->EntryAddr;
1427   return 0;
1428 }
1429 
1430 template <class ELFT> static uint8_t getELFEncoding() {
1431   if (ELFT::TargetEndianness == llvm::support::little)
1432     return ELFDATA2LSB;
1433   return ELFDATA2MSB;
1434 }
1435 
1436 static uint16_t getELFType() {
1437   if (Config->Shared)
1438     return ET_DYN;
1439   if (Config->Relocatable)
1440     return ET_REL;
1441   return ET_EXEC;
1442 }
1443 
1444 // This function is called after we have assigned address and size
1445 // to each section. This function fixes some predefined absolute
1446 // symbol values that depend on section address and size.
1447 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1448   // Update __rel[a]_iplt_{start,end} symbols so that they point
1449   // to beginning or ending of .rela.plt section, respectively.
1450   if (Out<ELFT>::RelaPlt) {
1451     uintX_t Start = Out<ELFT>::RelaPlt->getVA();
1452     ElfSym<ELFT>::RelaIpltStart.st_value = Start;
1453     ElfSym<ELFT>::RelaIpltEnd.st_value = Start + Out<ELFT>::RelaPlt->getSize();
1454   }
1455 
1456   // Update MIPS _gp absolute symbol so that it points to the static data.
1457   if (Config->EMachine == EM_MIPS)
1458     ElfSym<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>();
1459 
1460   // _etext points to location after the last read-only loadable segment.
1461   // _edata points to the end of the last non SHT_NOBITS section.
1462   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1463     if (!(Sec->getFlags() & SHF_ALLOC))
1464       continue;
1465     if (!(Sec->getFlags() & SHF_WRITE))
1466       ElfSym<ELFT>::Etext.st_value = Sec->getVA() + Sec->getSize();
1467     if (Sec->getType() != SHT_NOBITS)
1468       ElfSym<ELFT>::Edata.st_value = Sec->getVA() + Sec->getSize();
1469   }
1470 }
1471 
1472 template <class ELFT> void Writer<ELFT>::writeHeader() {
1473   uint8_t *Buf = Buffer->getBufferStart();
1474   memcpy(Buf, "\177ELF", 4);
1475 
1476   auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
1477 
1478   // Write the ELF header.
1479   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1480   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1481   EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1482   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1483   EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
1484   EHdr->e_type = getELFType();
1485   EHdr->e_machine = FirstObj.getEMachine();
1486   EHdr->e_version = EV_CURRENT;
1487   EHdr->e_entry = getEntryAddr<ELFT>();
1488   EHdr->e_shoff = SectionHeaderOff;
1489   EHdr->e_flags = getELFFlags();
1490   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1491   EHdr->e_phnum = Phdrs.size();
1492   EHdr->e_shentsize = sizeof(Elf_Shdr);
1493   EHdr->e_shnum = getNumSections();
1494   EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
1495 
1496   if (!Config->Relocatable) {
1497     EHdr->e_phoff = sizeof(Elf_Ehdr);
1498     EHdr->e_phentsize = sizeof(Elf_Phdr);
1499   }
1500 
1501   // Write the program header table.
1502   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1503   for (Phdr &P : Phdrs)
1504     *HBuf++ = P.H;
1505 
1506   // Write the section header table. Note that the first table entry is null.
1507   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1508   for (OutputSectionBase<ELFT> *Sec : getSections())
1509     Sec->writeHeaderTo(++SHdrs);
1510 }
1511 
1512 template <class ELFT> bool Writer<ELFT>::openFile() {
1513   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1514       FileOutputBuffer::create(Config->OutputFile, FileSize,
1515                                FileOutputBuffer::F_executable);
1516   if (error(BufferOrErr, "failed to open " + Config->OutputFile))
1517     return false;
1518   Buffer = std::move(*BufferOrErr);
1519   return true;
1520 }
1521 
1522 // Write section contents to a mmap'ed file.
1523 template <class ELFT> void Writer<ELFT>::writeSections() {
1524   uint8_t *Buf = Buffer->getBufferStart();
1525 
1526   // PPC64 needs to process relocations in the .opd section before processing
1527   // relocations in code-containing sections.
1528   if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
1529     Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
1530     Sec->writeTo(Buf + Sec->getFileOff());
1531   }
1532 
1533   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1534     if (Sec != Out<ELFT>::Opd)
1535       Sec->writeTo(Buf + Sec->getFileOff());
1536 }
1537 
1538 template void elf::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
1539 template void elf::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
1540 template void elf::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
1541 template void elf::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);
1542