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