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