xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision ed98e8d0)
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 "MapFile.h"
14 #include "Memory.h"
15 #include "OutputSections.h"
16 #include "Relocations.h"
17 #include "Strings.h"
18 #include "SymbolTable.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/FileOutputBuffer.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <climits>
27 #include <thread>
28 
29 using namespace llvm;
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
34 
35 using namespace lld;
36 using namespace lld::elf;
37 
38 namespace {
39 // The writer writes a SymbolTable result to a file.
40 template <class ELFT> class Writer {
41 public:
42   typedef typename ELFT::uint uintX_t;
43   typedef typename ELFT::Shdr Elf_Shdr;
44   typedef typename ELFT::Ehdr Elf_Ehdr;
45   typedef typename ELFT::Phdr Elf_Phdr;
46   typedef typename ELFT::Sym Elf_Sym;
47   typedef typename ELFT::SymRange Elf_Sym_Range;
48   typedef typename ELFT::Rela Elf_Rela;
49   void run();
50 
51 private:
52   void createSyntheticSections();
53   void copyLocalSymbols();
54   void addSectionSymbols();
55   void addReservedSymbols();
56   void addInputSec(InputSectionBase<ELFT> *S);
57   void createSections();
58   void forEachRelSec(std::function<void(InputSectionBase<ELFT> &)> Fn);
59   void sortSections();
60   void finalizeSections();
61   void addPredefinedSections();
62 
63   std::vector<PhdrEntry> createPhdrs();
64   void removeEmptyPTLoad();
65   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
66   void assignAddresses();
67   void assignFileOffsets();
68   void assignFileOffsetsBinary();
69   void setPhdrs();
70   void fixHeaders();
71   void fixSectionAlignments();
72   void fixPredefinedSymbols();
73   void openFile();
74   void writeHeader();
75   void writeSections();
76   void writeSectionsBinary();
77   void writeBuildId();
78 
79   std::unique_ptr<FileOutputBuffer> Buffer;
80 
81   std::vector<OutputSectionBase *> OutputSections;
82   OutputSectionFactory<ELFT> Factory;
83 
84   void addRelIpltSymbols();
85   void addStartEndSymbols();
86   void addStartStopSymbols(OutputSectionBase *Sec);
87   uintX_t getEntryAddr();
88   OutputSectionBase *findSection(StringRef Name);
89 
90   std::vector<PhdrEntry> Phdrs;
91 
92   uintX_t FileSize;
93   uintX_t SectionHeaderOff;
94   bool AllocateHeader = true;
95 };
96 } // anonymous namespace
97 
98 StringRef elf::getOutputSectionName(StringRef Name) {
99   if (Config->Relocatable)
100     return Name;
101 
102   for (StringRef V :
103        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
104         ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
105         ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
106     StringRef Prefix = V.drop_back();
107     if (Name.startswith(V) || Name == Prefix)
108       return Prefix;
109   }
110 
111   // CommonSection is identified as "COMMON" in linker scripts.
112   // By default, it should go to .bss section.
113   if (Name == "COMMON")
114     return ".bss";
115 
116   // ".zdebug_" is a prefix for ZLIB-compressed sections.
117   // Because we decompressed input sections, we want to remove 'z'.
118   if (Name.startswith(".zdebug_"))
119     return Saver.save(Twine(".") + Name.substr(2));
120   return Name;
121 }
122 
123 template <class ELFT> void elf::reportDiscarded(InputSectionBase<ELFT> *IS) {
124   if (IS == In<ELFT>::ShStrTab)
125     error("discarding .shstrtab section is not allowed");
126   if (!Config->PrintGcSections)
127     return;
128   errs() << "removing unused section from '" << IS->Name << "' in file '"
129          << IS->getFile()->getName() << "'\n";
130 }
131 
132 template <class ELFT> static bool needsInterpSection() {
133   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
134          !Config->DynamicLinker.empty() &&
135          !Script<ELFT>::X->ignoreInterpSection();
136 }
137 
138 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
139 
140 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
141   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
142     if (P.p_type != PT_LOAD)
143       return false;
144     if (!P.First)
145       return true;
146     uintX_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
147     return Size == 0;
148   });
149   Phdrs.erase(I, Phdrs.end());
150 }
151 
152 template <class ELFT>
153 static typename ELFT::uint getOutFlags(InputSectionBase<ELFT> *S) {
154   return S->Flags & ~(typename ELFT::uint)(SHF_GROUP | SHF_COMPRESSED);
155 }
156 
157 // This function scans over the input sections and creates mergeable
158 // synthetic sections. It removes MergeInputSections from array and
159 // adds new synthetic ones. Each synthetic section is added to the
160 // location of the first input section it replaces.
161 template <class ELFT> static void combineMergableSections() {
162   typedef typename ELFT::uint uintX_t;
163 
164   std::vector<MergeSyntheticSection<ELFT> *> MergeSections;
165   for (InputSectionBase<ELFT> *&S : Symtab<ELFT>::X->Sections) {
166     MergeInputSection<ELFT> *MS = dyn_cast<MergeInputSection<ELFT>>(S);
167     if (!MS)
168       continue;
169 
170     // We do not want to handle sections that are not alive, so just remove
171     // them instead of trying to merge.
172     if (!MS->Live)
173       continue;
174 
175     StringRef OutsecName = getOutputSectionName(MS->Name);
176     uintX_t Flags = getOutFlags(MS);
177     uintX_t Alignment = std::max<uintX_t>(MS->Alignment, MS->Entsize);
178 
179     auto I =
180         llvm::find_if(MergeSections, [=](MergeSyntheticSection<ELFT> *Sec) {
181           return Sec->Name == OutsecName && Sec->Flags == Flags &&
182                  Sec->Alignment == Alignment;
183         });
184     if (I == MergeSections.end()) {
185       MergeSyntheticSection<ELFT> *Syn = make<MergeSyntheticSection<ELFT>>(
186           OutsecName, MS->Type, Flags, Alignment);
187       MergeSections.push_back(Syn);
188       I = std::prev(MergeSections.end());
189       S = Syn;
190     } else {
191       S = nullptr;
192     }
193     (*I)->addSection(MS);
194   }
195 
196   std::vector<InputSectionBase<ELFT> *> &V = Symtab<ELFT>::X->Sections;
197   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
198 }
199 
200 // The main function of the writer.
201 template <class ELFT> void Writer<ELFT>::run() {
202   // Create linker-synthesized sections such as .got or .plt.
203   // Such sections are of type input section.
204   createSyntheticSections();
205   combineMergableSections<ELFT>();
206 
207   // We need to create some reserved symbols such as _end. Create them.
208   if (!Config->Relocatable)
209     addReservedSymbols();
210 
211   // Create output sections.
212   Script<ELFT>::X->OutputSections = &OutputSections;
213   if (ScriptConfig->HasSections) {
214     // If linker script contains SECTIONS commands, let it create sections.
215     Script<ELFT>::X->processCommands(Factory);
216 
217     // Linker scripts may have left some input sections unassigned.
218     // Assign such sections using the default rule.
219     Script<ELFT>::X->addOrphanSections(Factory);
220   } else {
221     // If linker script does not contain SECTIONS commands, create
222     // output sections by default rules. We still need to give the
223     // linker script a chance to run, because it might contain
224     // non-SECTIONS commands such as ASSERT.
225     createSections();
226     Script<ELFT>::X->processCommands(Factory);
227   }
228 
229   if (Config->Discard != DiscardPolicy::All)
230     copyLocalSymbols();
231 
232   if (Config->copyRelocs())
233     addSectionSymbols();
234 
235   // Now that we have a complete set of output sections. This function
236   // completes section contents. For example, we need to add strings
237   // to the string table, and add entries to .got and .plt.
238   // finalizeSections does that.
239   finalizeSections();
240   if (ErrorCount)
241     return;
242 
243   if (Config->Relocatable) {
244     assignFileOffsets();
245   } else {
246     if (ScriptConfig->HasSections) {
247       Script<ELFT>::X->assignAddresses(Phdrs);
248     } else {
249       fixSectionAlignments();
250       assignAddresses();
251     }
252 
253     // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
254     // 0 sized region. This has to be done late since only after assignAddresses
255     // we know the size of the sections.
256     removeEmptyPTLoad();
257 
258     if (!Config->OFormatBinary)
259       assignFileOffsets();
260     else
261       assignFileOffsetsBinary();
262 
263     setPhdrs();
264     fixPredefinedSymbols();
265   }
266 
267   // It does not make sense try to open the file if we have error already.
268   if (ErrorCount)
269     return;
270   // Write the result down to a file.
271   openFile();
272   if (ErrorCount)
273     return;
274   if (!Config->OFormatBinary) {
275     writeHeader();
276     writeSections();
277   } else {
278     writeSectionsBinary();
279   }
280 
281   // Backfill .note.gnu.build-id section content. This is done at last
282   // because the content is usually a hash value of the entire output file.
283   writeBuildId();
284   if (ErrorCount)
285     return;
286 
287   // Handle -Map option.
288   writeMapFile<ELFT>(OutputSections);
289   if (ErrorCount)
290     return;
291 
292   if (auto EC = Buffer->commit())
293     error("failed to write to the output file: " + EC.message());
294 
295   // Flush the output streams and exit immediately. A full shutdown
296   // is a good test that we are keeping track of all allocated memory,
297   // but actually freeing it is a waste of time in a regular linker run.
298   if (Config->ExitEarly)
299     exitLld(0);
300 }
301 
302 // Initialize Out<ELFT> members.
303 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
304   // Initialize all pointers with NULL. This is needed because
305   // you can call lld::elf::main more than once as a library.
306   memset(&Out<ELFT>::First, 0, sizeof(Out<ELFT>));
307 
308   auto Add = [](InputSectionBase<ELFT> *Sec) {
309     Symtab<ELFT>::X->Sections.push_back(Sec);
310   };
311 
312   // Create singleton output sections.
313   Out<ELFT>::Bss =
314       make<OutputSection<ELFT>>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
315   Out<ELFT>::BssRelRo = make<OutputSection<ELFT>>(".bss.rel.ro", SHT_NOBITS,
316                                                   SHF_ALLOC | SHF_WRITE);
317   In<ELFT>::DynStrTab = make<StringTableSection<ELFT>>(".dynstr", true);
318   In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
319   Out<ELFT>::EhFrame = make<EhOutputSection<ELFT>>();
320   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
321       Config->Rela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
322   In<ELFT>::ShStrTab = make<StringTableSection<ELFT>>(".shstrtab", false);
323 
324   Out<ELFT>::ElfHeader = make<OutputSectionBase>("", 0, SHF_ALLOC);
325   Out<ELFT>::ElfHeader->Size = sizeof(Elf_Ehdr);
326   Out<ELFT>::ProgramHeaders = make<OutputSectionBase>("", 0, SHF_ALLOC);
327   Out<ELFT>::ProgramHeaders->updateAlignment(sizeof(uintX_t));
328 
329   if (needsInterpSection<ELFT>()) {
330     In<ELFT>::Interp = createInterpSection<ELFT>();
331     Add(In<ELFT>::Interp);
332   } else {
333     In<ELFT>::Interp = nullptr;
334   }
335 
336   if (!Config->Relocatable)
337     Add(createCommentSection<ELFT>());
338 
339   if (Config->Strip != StripPolicy::All) {
340     In<ELFT>::StrTab = make<StringTableSection<ELFT>>(".strtab", false);
341     In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
342   }
343 
344   if (Config->BuildId != BuildIdKind::None) {
345     In<ELFT>::BuildId = make<BuildIdSection<ELFT>>();
346     Add(In<ELFT>::BuildId);
347   }
348 
349   InputSection<ELFT> *Common = createCommonSection<ELFT>();
350   if (!Common->Data.empty()) {
351     In<ELFT>::Common = Common;
352     Add(Common);
353   }
354 
355   // Add MIPS-specific sections.
356   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() || Config->Pic;
357   if (Config->EMachine == EM_MIPS) {
358     if (!Config->Shared && HasDynSymTab) {
359       In<ELFT>::MipsRldMap = make<MipsRldMapSection<ELFT>>();
360       Add(In<ELFT>::MipsRldMap);
361     }
362     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
363       Add(Sec);
364     if (auto *Sec = MipsOptionsSection<ELFT>::create())
365       Add(Sec);
366     if (auto *Sec = MipsReginfoSection<ELFT>::create())
367       Add(Sec);
368   }
369 
370   if (HasDynSymTab) {
371     In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
372     Add(In<ELFT>::DynSymTab);
373 
374     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
375     Add(In<ELFT>::VerSym);
376 
377     if (!Config->VersionDefinitions.empty()) {
378       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
379       Add(In<ELFT>::VerDef);
380     }
381 
382     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
383     Add(In<ELFT>::VerNeed);
384 
385     if (Config->GnuHash) {
386       In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
387       Add(In<ELFT>::GnuHashTab);
388     }
389 
390     if (Config->SysvHash) {
391       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
392       Add(In<ELFT>::HashTab);
393     }
394 
395     Add(In<ELFT>::Dynamic);
396     Add(In<ELFT>::DynStrTab);
397     Add(In<ELFT>::RelaDyn);
398   }
399 
400   // Add .got. MIPS' .got is so different from the other archs,
401   // it has its own class.
402   if (Config->EMachine == EM_MIPS) {
403     In<ELFT>::MipsGot = make<MipsGotSection<ELFT>>();
404     Add(In<ELFT>::MipsGot);
405   } else {
406     In<ELFT>::Got = make<GotSection<ELFT>>();
407     Add(In<ELFT>::Got);
408   }
409 
410   In<ELFT>::GotPlt = make<GotPltSection<ELFT>>();
411   Add(In<ELFT>::GotPlt);
412   In<ELFT>::IgotPlt = make<IgotPltSection<ELFT>>();
413   Add(In<ELFT>::IgotPlt);
414 
415   if (Config->GdbIndex) {
416     In<ELFT>::GdbIndex = make<GdbIndexSection<ELFT>>();
417     Add(In<ELFT>::GdbIndex);
418   }
419 
420   // We always need to add rel[a].plt to output if it has entries.
421   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
422   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
423       Config->Rela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
424   Add(In<ELFT>::RelaPlt);
425 
426   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
427   // that the IRelative relocations are processed last by the dynamic loader
428   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
429       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
430       false /*Sort*/);
431   Add(In<ELFT>::RelaIplt);
432 
433   In<ELFT>::Plt = make<PltSection<ELFT>>(Target->PltHeaderSize);
434   Add(In<ELFT>::Plt);
435   In<ELFT>::Iplt = make<PltSection<ELFT>>(0);
436   Add(In<ELFT>::Iplt);
437 
438   if (Config->EhFrameHdr) {
439     In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
440     Add(In<ELFT>::EhFrameHdr);
441   }
442 
443   if (In<ELFT>::SymTab)
444     Add(In<ELFT>::SymTab);
445   Add(In<ELFT>::ShStrTab);
446   if (In<ELFT>::StrTab)
447     Add(In<ELFT>::StrTab);
448 }
449 
450 template <class ELFT>
451 static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
452                                const SymbolBody &B) {
453   if (B.isFile() || B.isSection())
454     return false;
455 
456   // If sym references a section in a discarded group, don't keep it.
457   if (Sec == &InputSection<ELFT>::Discarded)
458     return false;
459 
460   if (Config->Discard == DiscardPolicy::None)
461     return true;
462 
463   // In ELF assembly .L symbols are normally discarded by the assembler.
464   // If the assembler fails to do so, the linker discards them if
465   // * --discard-locals is used.
466   // * The symbol is in a SHF_MERGE section, which is normally the reason for
467   //   the assembler keeping the .L symbol.
468   if (!SymName.startswith(".L") && !SymName.empty())
469     return true;
470 
471   if (Config->Discard == DiscardPolicy::Locals)
472     return false;
473 
474   return !Sec || !(Sec->Flags & SHF_MERGE);
475 }
476 
477 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
478   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
479     return false;
480 
481   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
482     // Always include absolute symbols.
483     if (!D->Section)
484       return true;
485     // Exclude symbols pointing to garbage-collected sections.
486     if (!D->Section->Live)
487       return false;
488     if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
489       if (!S->getSectionPiece(D->Value)->Live)
490         return false;
491   }
492   return true;
493 }
494 
495 // Local symbols are not in the linker's symbol table. This function scans
496 // each object file's symbol table to copy local symbols to the output.
497 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
498   if (!In<ELFT>::SymTab)
499     return;
500   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
501     for (SymbolBody *B : F->getLocalSymbols()) {
502       if (!B->IsLocal)
503         fatal(toString(F) +
504               ": broken object: getLocalSymbols returns a non-local symbol");
505       auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
506 
507       // No reason to keep local undefined symbol in symtab.
508       if (!DR)
509         continue;
510       if (!includeInSymtab<ELFT>(*B))
511         continue;
512 
513       InputSectionBase<ELFT> *Sec = DR->Section;
514       if (!shouldKeepInSymtab<ELFT>(Sec, B->getName(), *B))
515         continue;
516       In<ELFT>::SymTab->addLocal(B);
517     }
518   }
519 }
520 
521 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
522   // Create one STT_SECTION symbol for each output section we might
523   // have a relocation with.
524   for (OutputSectionBase *Sec : OutputSections) {
525     InputSectionData *First = nullptr;
526     Sec->forEachInputSection([&](InputSectionData *D) {
527       if (!First)
528         First = D;
529     });
530     auto *IS = dyn_cast_or_null<InputSection<ELFT>>(First);
531     if (!IS || isa<SyntheticSection<ELFT>>(IS) || IS->Type == SHT_REL ||
532         IS->Type == SHT_RELA)
533       continue;
534     auto *B = new (BAlloc)
535         DefinedRegular<ELFT>("", /*IsLocal=*/true, /*StOther*/ 0, STT_SECTION,
536                              /*Value*/ 0, /*Size*/ 0, IS, nullptr);
537 
538     In<ELFT>::SymTab->addLocal(B);
539   }
540 }
541 
542 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
543 // we would like to make sure appear is a specific order to maximize their
544 // coverage by a single signed 16-bit offset from the TOC base pointer.
545 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
546 // sections. This will put it next to the loaded special PPC64 sections (and,
547 // thus, within reach of the TOC base pointer).
548 static int getPPC64SectionRank(StringRef SectionName) {
549   return StringSwitch<int>(SectionName)
550       .Case(".tocbss", 0)
551       .Case(".branch_lt", 2)
552       .Case(".toc", 3)
553       .Case(".toc1", 4)
554       .Case(".opd", 5)
555       .Default(1);
556 }
557 
558 // All sections with SHF_MIPS_GPREL flag should be grouped together
559 // because data in these sections is addressable with a gp relative address.
560 static int getMipsSectionRank(const OutputSectionBase *S) {
561   if ((S->Flags & SHF_MIPS_GPREL) == 0)
562     return 0;
563   if (S->getName() == ".got")
564     return 1;
565   return 2;
566 }
567 
568 template <class ELFT> bool elf::isRelroSection(const OutputSectionBase *Sec) {
569   if (!Config->ZRelro)
570     return false;
571   uint64_t Flags = Sec->Flags;
572   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
573     return false;
574   if (Flags & SHF_TLS)
575     return true;
576   uint32_t Type = Sec->Type;
577   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
578       Type == SHT_PREINIT_ARRAY)
579     return true;
580   if (Sec == In<ELFT>::GotPlt->OutSec)
581     return Config->ZNow;
582   if (Sec == In<ELFT>::Dynamic->OutSec)
583     return true;
584   if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
585     return true;
586   if (Sec == Out<ELFT>::BssRelRo)
587     return true;
588   StringRef S = Sec->getName();
589   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
590          S == ".eh_frame" || S == ".openbsd.randomdata";
591 }
592 
593 template <class ELFT>
594 static bool compareSectionsNonScript(const OutputSectionBase *A,
595                                      const OutputSectionBase *B) {
596   // Put .interp first because some loaders want to see that section
597   // on the first page of the executable file when loaded into memory.
598   bool AIsInterp = A->getName() == ".interp";
599   bool BIsInterp = B->getName() == ".interp";
600   if (AIsInterp != BIsInterp)
601     return AIsInterp;
602 
603   // Allocatable sections go first to reduce the total PT_LOAD size and
604   // so debug info doesn't change addresses in actual code.
605   bool AIsAlloc = A->Flags & SHF_ALLOC;
606   bool BIsAlloc = B->Flags & SHF_ALLOC;
607   if (AIsAlloc != BIsAlloc)
608     return AIsAlloc;
609 
610   // We don't have any special requirements for the relative order of two non
611   // allocatable sections.
612   if (!AIsAlloc)
613     return false;
614 
615   // We want to put section specified by -T option first, so we
616   // can start assigning VA starting from them later.
617   auto AAddrSetI = Config->SectionStartMap.find(A->getName());
618   auto BAddrSetI = Config->SectionStartMap.find(B->getName());
619   bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
620   bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
621   if (AHasAddrSet != BHasAddrSet)
622     return AHasAddrSet;
623   if (AHasAddrSet)
624     return AAddrSetI->second < BAddrSetI->second;
625 
626   // We want the read only sections first so that they go in the PT_LOAD
627   // covering the program headers at the start of the file.
628   bool AIsWritable = A->Flags & SHF_WRITE;
629   bool BIsWritable = B->Flags & SHF_WRITE;
630   if (AIsWritable != BIsWritable)
631     return BIsWritable;
632 
633   if (!Config->SingleRoRx) {
634     // For a corresponding reason, put non exec sections first (the program
635     // header PT_LOAD is not executable).
636     // We only do that if we are not using linker scripts, since with linker
637     // scripts ro and rx sections are in the same PT_LOAD, so their relative
638     // order is not important. The same applies for -no-rosegment.
639     bool AIsExec = A->Flags & SHF_EXECINSTR;
640     bool BIsExec = B->Flags & SHF_EXECINSTR;
641     if (AIsExec != BIsExec)
642       return BIsExec;
643   }
644 
645   // If we got here we know that both A and B are in the same PT_LOAD.
646 
647   bool AIsTls = A->Flags & SHF_TLS;
648   bool BIsTls = B->Flags & SHF_TLS;
649   bool AIsNoBits = A->Type == SHT_NOBITS;
650   bool BIsNoBits = B->Type == SHT_NOBITS;
651 
652   // The first requirement we have is to put (non-TLS) nobits sections last. The
653   // reason is that the only thing the dynamic linker will see about them is a
654   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
655   // PT_LOAD, so that has to correspond to the nobits sections.
656   bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
657   bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
658   if (AIsNonTlsNoBits != BIsNonTlsNoBits)
659     return BIsNonTlsNoBits;
660 
661   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
662   // sections after r/w ones, so that the RelRo sections are contiguous.
663   bool AIsRelRo = isRelroSection<ELFT>(A);
664   bool BIsRelRo = isRelroSection<ELFT>(B);
665   if (AIsRelRo != BIsRelRo)
666     return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
667 
668   // The TLS initialization block needs to be a single contiguous block in a R/W
669   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
670   // sections. The TLS NOBITS sections are placed here as they don't take up
671   // virtual address space in the PT_LOAD.
672   if (AIsTls != BIsTls)
673     return AIsTls;
674 
675   // Within the TLS initialization block, the non-nobits sections need to appear
676   // first.
677   if (AIsNoBits != BIsNoBits)
678     return BIsNoBits;
679 
680   // Some architectures have additional ordering restrictions for sections
681   // within the same PT_LOAD.
682   if (Config->EMachine == EM_PPC64)
683     return getPPC64SectionRank(A->getName()) <
684            getPPC64SectionRank(B->getName());
685   if (Config->EMachine == EM_MIPS)
686     return getMipsSectionRank(A) < getMipsSectionRank(B);
687 
688   return false;
689 }
690 
691 // Output section ordering is determined by this function.
692 template <class ELFT>
693 static bool compareSections(const OutputSectionBase *A,
694                             const OutputSectionBase *B) {
695   // For now, put sections mentioned in a linker script first.
696   int AIndex = Script<ELFT>::X->getSectionIndex(A->getName());
697   int BIndex = Script<ELFT>::X->getSectionIndex(B->getName());
698   bool AInScript = AIndex != INT_MAX;
699   bool BInScript = BIndex != INT_MAX;
700   if (AInScript != BInScript)
701     return AInScript;
702   // If both are in the script, use that order.
703   if (AInScript)
704     return AIndex < BIndex;
705 
706   return compareSectionsNonScript<ELFT>(A, B);
707 }
708 
709 // Program header entry
710 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
711   p_type = Type;
712   p_flags = Flags;
713 }
714 
715 void PhdrEntry::add(OutputSectionBase *Sec) {
716   Last = Sec;
717   if (!First)
718     First = Sec;
719   p_align = std::max(p_align, Sec->Addralign);
720   if (p_type == PT_LOAD)
721     Sec->FirstInPtLoad = First;
722 }
723 
724 template <class ELFT>
725 static DefinedSynthetic *
726 addOptionalSynthetic(StringRef Name, OutputSectionBase *Sec,
727                      typename ELFT::uint Val, uint8_t StOther = STV_HIDDEN) {
728   if (SymbolBody *S = Symtab<ELFT>::X->find(Name))
729     if (!S->isInCurrentDSO())
730       return cast<DefinedSynthetic>(
731           Symtab<ELFT>::X->addSynthetic(Name, Sec, Val, StOther)->body());
732   return nullptr;
733 }
734 
735 template <class ELFT>
736 static Symbol *addRegular(StringRef Name, InputSectionBase<ELFT> *Sec,
737                           typename ELFT::uint Value) {
738   // The linker generated symbols are added as STB_WEAK to allow user defined
739   // ones to override them.
740   return Symtab<ELFT>::X->addRegular(Name, STV_HIDDEN, STT_NOTYPE, Value,
741                                      /*Size=*/0, STB_WEAK, Sec,
742                                      /*File=*/nullptr);
743 }
744 
745 template <class ELFT>
746 static Symbol *addOptionalRegular(StringRef Name, InputSectionBase<ELFT> *IS,
747                                   typename ELFT::uint Value) {
748   SymbolBody *S = Symtab<ELFT>::X->find(Name);
749   if (!S)
750     return nullptr;
751   if (S->isInCurrentDSO())
752     return S->symbol();
753   return addRegular(Name, IS, Value);
754 }
755 
756 // The beginning and the ending of .rel[a].plt section are marked
757 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
758 // executable. The runtime needs these symbols in order to resolve
759 // all IRELATIVE relocs on startup. For dynamic executables, we don't
760 // need these symbols, since IRELATIVE relocs are resolved through GOT
761 // and PLT. For details, see http://www.airs.com/blog/archives/403.
762 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
763   if (In<ELFT>::DynSymTab)
764     return;
765   StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
766   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0);
767 
768   S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
769   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1);
770 }
771 
772 // The linker is expected to define some symbols depending on
773 // the linking result. This function defines such symbols.
774 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
775   if (Config->EMachine == EM_MIPS) {
776     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
777     // so that it points to an absolute address which by default is relative
778     // to GOT. Default offset is 0x7ff0.
779     // See "Global Data Symbols" in Chapter 6 in the following document:
780     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
781     ElfSym<ELFT>::MipsGp =
782         Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
783 
784     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
785     // start of function and 'gp' pointer into GOT. To simplify relocation
786     // calculation we assign _gp value to it and calculate corresponding
787     // relocations as relative to this value.
788     if (Symtab<ELFT>::X->find("_gp_disp"))
789       ElfSym<ELFT>::MipsGpDisp =
790           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
791 
792     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
793     // pointer. This symbol is used in the code generated by .cpload pseudo-op
794     // in case of using -mno-shared option.
795     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
796     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
797       ElfSym<ELFT>::MipsLocalGp =
798           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
799   }
800 
801   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
802   // is magical and is used to produce a R_386_GOTPC relocation.
803   // The R_386_GOTPC relocation value doesn't actually depend on the
804   // symbol value, so it could use an index of STN_UNDEF which, according
805   // to the spec, means the symbol value is 0.
806   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
807   // the object file.
808   // The situation is even stranger on x86_64 where the assembly doesn't
809   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
810   // an undefined symbol in the .o files.
811   // Given that the symbol is effectively unused, we just create a dummy
812   // hidden one to avoid the undefined symbol error.
813   Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
814 
815   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816   // static linking the linker is required to optimize away any references to
817   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818   // to avoid the undefined symbol error. As usual special cases are ARM and
819   // MIPS - the libc for these targets defines __tls_get_addr itself because
820   // there are no TLS optimizations for these targets.
821   if (!In<ELFT>::DynSymTab &&
822       (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
823     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
824 
825   // If linker script do layout we do not need to create any standart symbols.
826   if (ScriptConfig->HasSections)
827     return;
828 
829   // __ehdr_start is the location of program headers.
830   ElfSym<ELFT>::EhdrStart =
831       addOptionalSynthetic<ELFT>("__ehdr_start", Out<ELFT>::ProgramHeaders, 0);
832 
833   auto Define = [](StringRef S, DefinedSynthetic *&Sym1,
834                    DefinedSynthetic *&Sym2) {
835     Sym1 = addOptionalSynthetic<ELFT>(S, nullptr, 0, STV_DEFAULT);
836     assert(S.startswith("_"));
837     S = S.substr(1);
838     Sym2 = addOptionalSynthetic<ELFT>(S, nullptr, 0, STV_DEFAULT);
839   };
840 
841   Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
842   Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
843   Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
844 }
845 
846 // Sort input sections by section name suffixes for
847 // __attribute__((init_priority(N))).
848 template <class ELFT> static void sortInitFini(OutputSectionBase *S) {
849   if (S)
850     reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
851 }
852 
853 // Sort input sections by the special rule for .ctors and .dtors.
854 template <class ELFT> static void sortCtorsDtors(OutputSectionBase *S) {
855   if (S)
856     reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
857 }
858 
859 // Sort input sections using the list provided by --symbol-ordering-file.
860 template <class ELFT>
861 static void sortBySymbolsOrder(ArrayRef<OutputSectionBase *> OutputSections) {
862   if (Config->SymbolOrderingFile.empty())
863     return;
864 
865   // Build a map from symbols to their priorities. Symbols that didn't
866   // appear in the symbol ordering file have the lowest priority 0.
867   // All explicitly mentioned symbols have negative (higher) priorities.
868   DenseMap<StringRef, int> SymbolOrder;
869   int Priority = -Config->SymbolOrderingFile.size();
870   for (StringRef S : Config->SymbolOrderingFile)
871     SymbolOrder.insert({S, Priority++});
872 
873   // Build a map from sections to their priorities.
874   DenseMap<InputSectionBase<ELFT> *, int> SectionOrder;
875   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
876     for (SymbolBody *Body : File->getSymbols()) {
877       auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
878       if (!D || !D->Section)
879         continue;
880       int &Priority = SectionOrder[D->Section];
881       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
882     }
883   }
884 
885   // Sort sections by priority.
886   for (OutputSectionBase *Base : OutputSections)
887     if (auto *Sec = dyn_cast<OutputSection<ELFT>>(Base))
888       Sec->sort([&](InputSection<ELFT> *S) { return SectionOrder.lookup(S); });
889 }
890 
891 template <class ELFT>
892 void Writer<ELFT>::forEachRelSec(
893     std::function<void(InputSectionBase<ELFT> &)> Fn) {
894   for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections) {
895     if (!IS->Live)
896       continue;
897     // Scan all relocations. Each relocation goes through a series
898     // of tests to determine if it needs special treatment, such as
899     // creating GOT, PLT, copy relocations, etc.
900     // Note that relocations for non-alloc sections are directly
901     // processed by InputSection::relocateNonAlloc.
902     if (!(IS->Flags & SHF_ALLOC))
903       continue;
904     if (isa<InputSection<ELFT>>(IS) || isa<EhInputSection<ELFT>>(IS))
905       Fn(*IS);
906   }
907 }
908 
909 template <class ELFT>
910 void Writer<ELFT>::addInputSec(InputSectionBase<ELFT> *IS) {
911   if (!IS)
912     return;
913 
914   if (!IS->Live) {
915     reportDiscarded(IS);
916     return;
917   }
918   OutputSectionBase *Sec;
919   bool IsNew;
920   StringRef OutsecName = getOutputSectionName(IS->Name);
921   std::tie(Sec, IsNew) = Factory.create(IS, OutsecName);
922   if (IsNew)
923     OutputSections.push_back(Sec);
924   Sec->addSection(IS);
925 }
926 
927 template <class ELFT> void Writer<ELFT>::createSections() {
928   for (InputSectionBase<ELFT> *IS : Symtab<ELFT>::X->Sections)
929     addInputSec(IS);
930 
931   sortBySymbolsOrder<ELFT>(OutputSections);
932   sortInitFini<ELFT>(findSection(".init_array"));
933   sortInitFini<ELFT>(findSection(".fini_array"));
934   sortCtorsDtors<ELFT>(findSection(".ctors"));
935   sortCtorsDtors<ELFT>(findSection(".dtors"));
936 
937   for (OutputSectionBase *Sec : OutputSections)
938     Sec->assignOffsets();
939 }
940 
941 template <class ELFT>
942 static bool canSharePtLoad(const OutputSectionBase &S1,
943                            const OutputSectionBase &S2) {
944   if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
945     return false;
946 
947   bool S1IsWrite = S1.Flags & SHF_WRITE;
948   bool S2IsWrite = S2.Flags & SHF_WRITE;
949   if (S1IsWrite != S2IsWrite)
950     return false;
951 
952   if (!S1IsWrite)
953     return true; // RO and RX share a PT_LOAD with linker scripts.
954   return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
955 }
956 
957 template <class ELFT> void Writer<ELFT>::sortSections() {
958   // Don't sort if using -r. It is not necessary and we want to preserve the
959   // relative order for SHF_LINK_ORDER sections.
960   if (Config->Relocatable)
961     return;
962   if (!ScriptConfig->HasSections) {
963     std::stable_sort(OutputSections.begin(), OutputSections.end(),
964                      compareSectionsNonScript<ELFT>);
965     return;
966   }
967   Script<ELFT>::X->adjustSectionsBeforeSorting();
968 
969   // The order of the sections in the script is arbitrary and may not agree with
970   // compareSectionsNonScript. This means that we cannot easily define a
971   // strict weak ordering. To see why, consider a comparison of a section in the
972   // script and one not in the script. We have a two simple options:
973   // * Make them equivalent (a is not less than b, and b is not less than a).
974   //   The problem is then that equivalence has to be transitive and we can
975   //   have sections a, b and c with only b in a script and a less than c
976   //   which breaks this property.
977   // * Use compareSectionsNonScript. Given that the script order doesn't have
978   //   to match, we can end up with sections a, b, c, d where b and c are in the
979   //   script and c is compareSectionsNonScript less than b. In which case d
980   //   can be equivalent to c, a to b and d < a. As a concrete example:
981   //   .a (rx) # not in script
982   //   .b (rx) # in script
983   //   .c (ro) # in script
984   //   .d (ro) # not in script
985   //
986   // The way we define an order then is:
987   // *  First put script sections at the start and sort the script and
988   //    non-script sections independently.
989   // *  Move each non-script section to its preferred position. We try
990   //    to put each section in the last position where it it can share
991   //    a PT_LOAD.
992 
993   std::stable_sort(OutputSections.begin(), OutputSections.end(),
994                    compareSections<ELFT>);
995 
996   auto I = OutputSections.begin();
997   auto E = OutputSections.end();
998   auto NonScriptI =
999       std::find_if(OutputSections.begin(), E, [](OutputSectionBase *S) {
1000         return Script<ELFT>::X->getSectionIndex(S->getName()) == INT_MAX;
1001       });
1002   while (NonScriptI != E) {
1003     auto BestPos = std::max_element(
1004         I, NonScriptI, [&](OutputSectionBase *&A, OutputSectionBase *&B) {
1005           bool ACanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *A);
1006           bool BCanSharePtLoad = canSharePtLoad<ELFT>(**NonScriptI, *B);
1007           if (ACanSharePtLoad != BCanSharePtLoad)
1008             return BCanSharePtLoad;
1009 
1010           bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1011           bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1012           if (ACmp != BCmp)
1013             return BCmp; // FIXME: missing test
1014 
1015           size_t PosA = &A - &OutputSections[0];
1016           size_t PosB = &B - &OutputSections[0];
1017           return ACmp ? PosA > PosB : PosA < PosB;
1018         });
1019 
1020     // max_element only returns NonScriptI if the range is empty. If the range
1021     // is not empty we should consider moving the the element forward one
1022     // position.
1023     if (BestPos != NonScriptI &&
1024         !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1025       ++BestPos;
1026     std::rotate(BestPos, NonScriptI, NonScriptI + 1);
1027     ++NonScriptI;
1028   }
1029 
1030   Script<ELFT>::X->adjustSectionsAfterSorting();
1031 }
1032 
1033 template <class ELFT>
1034 static void
1035 finalizeSynthetic(const std::vector<SyntheticSection<ELFT> *> &Sections) {
1036   for (SyntheticSection<ELFT> *SS : Sections)
1037     if (SS && SS->OutSec && !SS->empty()) {
1038       SS->finalize();
1039       SS->OutSec->Size = 0;
1040       SS->OutSec->assignOffsets();
1041     }
1042 }
1043 
1044 // We need to add input synthetic sections early in createSyntheticSections()
1045 // to make them visible from linkescript side. But not all sections are always
1046 // required to be in output. For example we don't need dynamic section content
1047 // sometimes. This function filters out such unused sections from output.
1048 template <class ELFT>
1049 static void removeUnusedSyntheticSections(std::vector<OutputSectionBase *> &V) {
1050   // All input synthetic sections that can be empty are placed after
1051   // all regular ones. We iterate over them all and exit at first
1052   // non-synthetic.
1053   for (InputSectionBase<ELFT> *S : llvm::reverse(Symtab<ELFT>::X->Sections)) {
1054     SyntheticSection<ELFT> *SS = dyn_cast<SyntheticSection<ELFT>>(S);
1055     if (!SS)
1056       return;
1057     if (!SS->empty() || !SS->OutSec)
1058       continue;
1059 
1060     OutputSection<ELFT> *OutSec = cast<OutputSection<ELFT>>(SS->OutSec);
1061     OutSec->Sections.erase(
1062         std::find(OutSec->Sections.begin(), OutSec->Sections.end(), SS));
1063     // If there is no other sections in output section, remove it from output.
1064     if (OutSec->Sections.empty())
1065       V.erase(std::find(V.begin(), V.end(), OutSec));
1066   }
1067 }
1068 
1069 // Create output section objects and add them to OutputSections.
1070 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1071   Out<ELFT>::DebugInfo = findSection(".debug_info");
1072   Out<ELFT>::PreinitArray = findSection(".preinit_array");
1073   Out<ELFT>::InitArray = findSection(".init_array");
1074   Out<ELFT>::FiniArray = findSection(".fini_array");
1075 
1076   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1077   // symbols for sections, so that the runtime can get the start and end
1078   // addresses of each section by section name. Add such symbols.
1079   if (!Config->Relocatable) {
1080     addStartEndSymbols();
1081     for (OutputSectionBase *Sec : OutputSections)
1082       addStartStopSymbols(Sec);
1083   }
1084 
1085   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1086   // It should be okay as no one seems to care about the type.
1087   // Even the author of gold doesn't remember why gold behaves that way.
1088   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1089   if (In<ELFT>::DynSymTab)
1090     addRegular("_DYNAMIC", In<ELFT>::Dynamic, 0);
1091 
1092   // Define __rel[a]_iplt_{start,end} symbols if needed.
1093   addRelIpltSymbols();
1094 
1095   if (!Out<ELFT>::EhFrame->empty()) {
1096     OutputSections.push_back(Out<ELFT>::EhFrame);
1097     Out<ELFT>::EhFrame->finalize();
1098   }
1099 
1100   // Scan relocations. This must be done after every symbol is declared so that
1101   // we can correctly decide if a dynamic relocation is needed.
1102   forEachRelSec(scanRelocations<ELFT>);
1103 
1104   if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1105     In<ELFT>::Plt->addSymbols();
1106   if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1107     In<ELFT>::Iplt->addSymbols();
1108 
1109   // Some architectures use small displacements for jump instructions.
1110   // It is linker's responsibility to create thunks containing long
1111   // jump instructions if jump targets are too far. Create thunks.
1112   if (Target->NeedsThunks)
1113     createThunks<ELFT>(OutputSections);
1114 
1115   // Now that we have defined all possible symbols including linker-
1116   // synthesized ones. Visit all symbols to give the finishing touches.
1117   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1118     SymbolBody *Body = S->body();
1119 
1120     if (!includeInSymtab<ELFT>(*Body))
1121       continue;
1122     if (In<ELFT>::SymTab)
1123       In<ELFT>::SymTab->addGlobal(Body);
1124 
1125     if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1126       In<ELFT>::DynSymTab->addGlobal(Body);
1127       if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1128         if (SS->file()->isNeeded())
1129           In<ELFT>::VerNeed->addSymbol(SS);
1130     }
1131   }
1132 
1133   // Do not proceed if there was an undefined symbol.
1134   if (ErrorCount)
1135     return;
1136 
1137   // So far we have added sections from input object files.
1138   // This function adds linker-created Out<ELFT>::* sections.
1139   addPredefinedSections();
1140   removeUnusedSyntheticSections<ELFT>(OutputSections);
1141 
1142   sortSections();
1143 
1144   // This is a bit of a hack. A value of 0 means undef, so we set it
1145   // to 1 t make __ehdr_start defined. The section number is not
1146   // particularly relevant.
1147   Out<ELFT>::ProgramHeaders->SectionIndex = 1;
1148 
1149   unsigned I = 1;
1150   for (OutputSectionBase *Sec : OutputSections) {
1151     Sec->SectionIndex = I++;
1152     Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->getName());
1153   }
1154 
1155   // Binary and relocatable output does not have PHDRS.
1156   // The headers have to be created before finalize as that can influence the
1157   // image base and the dynamic section on mips includes the image base.
1158   if (!Config->Relocatable && !Config->OFormatBinary) {
1159     Phdrs = Script<ELFT>::X->hasPhdrsCommands() ? Script<ELFT>::X->createPhdrs()
1160                                                 : createPhdrs();
1161     addPtArmExid(Phdrs);
1162     fixHeaders();
1163   }
1164 
1165   // Fill other section headers. The dynamic table is finalized
1166   // at the end because some tags like RELSZ depend on result
1167   // of finalizing other sections.
1168   for (OutputSectionBase *Sec : OutputSections)
1169     Sec->finalize();
1170 
1171   // Dynamic section must be the last one in this list and dynamic
1172   // symbol table section (DynSymTab) must be the first one.
1173   finalizeSynthetic<ELFT>(
1174       {In<ELFT>::DynSymTab, In<ELFT>::GnuHashTab, In<ELFT>::HashTab,
1175        In<ELFT>::SymTab,    In<ELFT>::ShStrTab,   In<ELFT>::StrTab,
1176        In<ELFT>::VerDef,    In<ELFT>::DynStrTab,  In<ELFT>::GdbIndex,
1177        In<ELFT>::Got,       In<ELFT>::MipsGot,    In<ELFT>::IgotPlt,
1178        In<ELFT>::GotPlt,    In<ELFT>::RelaDyn,    In<ELFT>::RelaIplt,
1179        In<ELFT>::RelaPlt,   In<ELFT>::Plt,        In<ELFT>::Iplt,
1180        In<ELFT>::Plt,       In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,
1181        In<ELFT>::VerNeed,   In<ELFT>::Dynamic});
1182 }
1183 
1184 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1185   if (Out<ELFT>::Bss->Size > 0)
1186     OutputSections.push_back(Out<ELFT>::Bss);
1187   if (Out<ELFT>::BssRelRo->Size > 0)
1188     OutputSections.push_back(Out<ELFT>::BssRelRo);
1189 
1190   auto OS = dyn_cast_or_null<OutputSection<ELFT>>(findSection(".ARM.exidx"));
1191   if (OS && !OS->Sections.empty() && !Config->Relocatable)
1192     OS->addSection(make<ARMExidxSentinelSection<ELFT>>());
1193 }
1194 
1195 // The linker is expected to define SECNAME_start and SECNAME_end
1196 // symbols for a few sections. This function defines them.
1197 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1198   auto Define = [&](StringRef Start, StringRef End, OutputSectionBase *OS) {
1199     // These symbols resolve to the image base if the section does not exist.
1200     // A special value -1 indicates end of the section.
1201     addOptionalSynthetic<ELFT>(Start, OS, 0);
1202     addOptionalSynthetic<ELFT>(End, OS, OS ? -1 : 0);
1203   };
1204 
1205   Define("__preinit_array_start", "__preinit_array_end",
1206          Out<ELFT>::PreinitArray);
1207   Define("__init_array_start", "__init_array_end", Out<ELFT>::InitArray);
1208   Define("__fini_array_start", "__fini_array_end", Out<ELFT>::FiniArray);
1209 
1210   if (OutputSectionBase *Sec = findSection(".ARM.exidx"))
1211     Define("__exidx_start", "__exidx_end", Sec);
1212 }
1213 
1214 // If a section name is valid as a C identifier (which is rare because of
1215 // the leading '.'), linkers are expected to define __start_<secname> and
1216 // __stop_<secname> symbols. They are at beginning and end of the section,
1217 // respectively. This is not requested by the ELF standard, but GNU ld and
1218 // gold provide the feature, and used by many programs.
1219 template <class ELFT>
1220 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase *Sec) {
1221   StringRef S = Sec->getName();
1222   if (!isValidCIdentifier(S))
1223     return;
1224   addOptionalSynthetic<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1225   addOptionalSynthetic<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1226 }
1227 
1228 template <class ELFT>
1229 OutputSectionBase *Writer<ELFT>::findSection(StringRef Name) {
1230   for (OutputSectionBase *Sec : OutputSections)
1231     if (Sec->getName() == Name)
1232       return Sec;
1233   return nullptr;
1234 }
1235 
1236 template <class ELFT> static bool needsPtLoad(OutputSectionBase *Sec) {
1237   if (!(Sec->Flags & SHF_ALLOC))
1238     return false;
1239 
1240   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1241   // responsible for allocating space for them, not the PT_LOAD that
1242   // contains the TLS initialization image.
1243   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1244     return false;
1245   return true;
1246 }
1247 
1248 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1249 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1250 // RW. This means that there is no alignment in the RO to RX transition and we
1251 // cannot create a PT_LOAD there.
1252 template <class ELFT>
1253 static typename ELFT::uint computeFlags(typename ELFT::uint F) {
1254   if (Config->OMagic)
1255     return PF_R | PF_W | PF_X;
1256   if (Config->SingleRoRx && !(F & PF_W))
1257     return F | PF_X;
1258   return F;
1259 }
1260 
1261 // Decide which program headers to create and which sections to include in each
1262 // one.
1263 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1264   std::vector<PhdrEntry> Ret;
1265   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1266     Ret.emplace_back(Type, Flags);
1267     return &Ret.back();
1268   };
1269 
1270   // The first phdr entry is PT_PHDR which describes the program header itself.
1271   AddHdr(PT_PHDR, PF_R)->add(Out<ELFT>::ProgramHeaders);
1272 
1273   // PT_INTERP must be the second entry if exists.
1274   if (OutputSectionBase *Sec = findSection(".interp"))
1275     AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1276 
1277   // Add the first PT_LOAD segment for regular output sections.
1278   uintX_t Flags = computeFlags<ELFT>(PF_R);
1279   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1280   for (OutputSectionBase *Sec : OutputSections) {
1281     if (!(Sec->Flags & SHF_ALLOC))
1282       break;
1283     if (!needsPtLoad<ELFT>(Sec))
1284       continue;
1285 
1286     // Segments are contiguous memory regions that has the same attributes
1287     // (e.g. executable or writable). There is one phdr for each segment.
1288     // Therefore, we need to create a new phdr when the next section has
1289     // different flags or is loaded at a discontiguous address using AT linker
1290     // script command.
1291     uintX_t NewFlags = computeFlags<ELFT>(Sec->getPhdrFlags());
1292     if (Script<ELFT>::X->hasLMA(Sec->getName()) || Flags != NewFlags) {
1293       Load = AddHdr(PT_LOAD, NewFlags);
1294       Flags = NewFlags;
1295     }
1296 
1297     Load->add(Sec);
1298   }
1299 
1300   // Add a TLS segment if any.
1301   PhdrEntry TlsHdr(PT_TLS, PF_R);
1302   for (OutputSectionBase *Sec : OutputSections)
1303     if (Sec->Flags & SHF_TLS)
1304       TlsHdr.add(Sec);
1305   if (TlsHdr.First)
1306     Ret.push_back(std::move(TlsHdr));
1307 
1308   // Add an entry for .dynamic.
1309   if (In<ELFT>::DynSymTab)
1310     AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1311         ->add(In<ELFT>::Dynamic->OutSec);
1312 
1313   // PT_GNU_RELRO includes all sections that should be marked as
1314   // read-only by dynamic linker after proccessing relocations.
1315   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1316   for (OutputSectionBase *Sec : OutputSections)
1317     if (needsPtLoad<ELFT>(Sec) && isRelroSection<ELFT>(Sec))
1318       RelRo.add(Sec);
1319   if (RelRo.First)
1320     Ret.push_back(std::move(RelRo));
1321 
1322   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1323   if (!Out<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr)
1324     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1325         ->add(In<ELFT>::EhFrameHdr->OutSec);
1326 
1327   // PT_OPENBSD_RANDOMIZE specifies the location and size of a part of the
1328   // memory image of the program that must be filled with random data before any
1329   // code in the object is executed.
1330   if (OutputSectionBase *Sec = findSection(".openbsd.randomdata"))
1331     AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1332 
1333   // PT_GNU_STACK is a special section to tell the loader to make the
1334   // pages for the stack non-executable.
1335   if (!Config->ZExecstack)
1336     AddHdr(PT_GNU_STACK, PF_R | PF_W)->p_memsz = Config->ZStackSize;
1337 
1338   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1339   // is expected to perform W^X violations, such as calling mprotect(2) or
1340   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1341   // OpenBSD.
1342   if (Config->ZWxneeded)
1343     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1344 
1345   // Create one PT_NOTE per a group of contiguous .note sections.
1346   PhdrEntry *Note = nullptr;
1347   for (OutputSectionBase *Sec : OutputSections) {
1348     if (Sec->Type == SHT_NOTE) {
1349       if (!Note || Script<ELFT>::X->hasLMA(Sec->getName()))
1350         Note = AddHdr(PT_NOTE, PF_R);
1351       Note->add(Sec);
1352     } else {
1353       Note = nullptr;
1354     }
1355   }
1356   return Ret;
1357 }
1358 
1359 template <class ELFT>
1360 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1361   if (Config->EMachine != EM_ARM)
1362     return;
1363   auto I = std::find_if(
1364       OutputSections.begin(), OutputSections.end(),
1365       [](OutputSectionBase *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1366   if (I == OutputSections.end())
1367     return;
1368 
1369   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1370   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1371   ARMExidx.add(*I);
1372   Phdrs.push_back(ARMExidx);
1373 }
1374 
1375 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1376 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1377 // linker can set the permissions.
1378 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1379   for (const PhdrEntry &P : Phdrs)
1380     if (P.p_type == PT_LOAD && P.First)
1381       P.First->PageAlign = true;
1382 
1383   for (const PhdrEntry &P : Phdrs) {
1384     if (P.p_type != PT_GNU_RELRO)
1385       continue;
1386     if (P.First)
1387       P.First->PageAlign = true;
1388     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1389     // have to align it to a page.
1390     auto End = OutputSections.end();
1391     auto I = std::find(OutputSections.begin(), End, P.Last);
1392     if (I == End || (I + 1) == End)
1393       continue;
1394     OutputSectionBase *Sec = *(I + 1);
1395     if (needsPtLoad<ELFT>(Sec))
1396       Sec->PageAlign = true;
1397   }
1398 }
1399 
1400 template <class ELFT>
1401 bool elf::allocateHeaders(std::vector<PhdrEntry> &Phdrs,
1402                           ArrayRef<OutputSectionBase *> OutputSections,
1403                           uint64_t Min) {
1404   auto FirstPTLoad =
1405       std::find_if(Phdrs.begin(), Phdrs.end(),
1406                    [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1407   if (FirstPTLoad == Phdrs.end())
1408     return false;
1409 
1410   uint64_t HeaderSize = getHeaderSize<ELFT>();
1411   if (HeaderSize > Min) {
1412     auto PhdrI =
1413         std::find_if(Phdrs.begin(), Phdrs.end(),
1414                      [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
1415     if (PhdrI != Phdrs.end())
1416       Phdrs.erase(PhdrI);
1417     return false;
1418   }
1419   Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1420 
1421   if (!ScriptConfig->HasSections)
1422     Config->ImageBase = Min = std::min(Min, Config->ImageBase);
1423 
1424   Out<ELFT>::ElfHeader->Addr = Min;
1425   Out<ELFT>::ProgramHeaders->Addr = Min + Out<ELFT>::ElfHeader->Size;
1426 
1427   if (Script<ELFT>::X->hasPhdrsCommands())
1428     return true;
1429 
1430   if (FirstPTLoad->First)
1431     for (OutputSectionBase *Sec : OutputSections)
1432       if (Sec->FirstInPtLoad == FirstPTLoad->First)
1433         Sec->FirstInPtLoad = Out<ELFT>::ElfHeader;
1434   FirstPTLoad->First = Out<ELFT>::ElfHeader;
1435   if (!FirstPTLoad->Last)
1436     FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
1437   return true;
1438 }
1439 
1440 // We should set file offsets and VAs for elf header and program headers
1441 // sections. These are special, we do not include them into output sections
1442 // list, but have them to simplify the code.
1443 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1444   Out<ELFT>::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1445   // If the script has SECTIONS, assignAddresses will compute the values.
1446   if (ScriptConfig->HasSections)
1447     return;
1448 
1449   // When -T<section> option is specified, lower the base to make room for those
1450   // sections.
1451   uint64_t Min = -1;
1452   if (!Config->SectionStartMap.empty())
1453     for (const auto &P : Config->SectionStartMap)
1454       Min = std::min(Min, P.second);
1455 
1456   AllocateHeader = allocateHeaders<ELFT>(Phdrs, OutputSections, Min);
1457 }
1458 
1459 // Assign VAs (addresses at run-time) to output sections.
1460 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1461   uintX_t VA = Config->ImageBase;
1462   if (AllocateHeader)
1463     VA += getHeaderSize<ELFT>();
1464   uintX_t ThreadBssOffset = 0;
1465   for (OutputSectionBase *Sec : OutputSections) {
1466     uintX_t Alignment = Sec->Addralign;
1467     if (Sec->PageAlign)
1468       Alignment = std::max<uintX_t>(Alignment, Config->MaxPageSize);
1469 
1470     auto I = Config->SectionStartMap.find(Sec->getName());
1471     if (I != Config->SectionStartMap.end())
1472       VA = I->second;
1473 
1474     // We only assign VAs to allocated sections.
1475     if (needsPtLoad<ELFT>(Sec)) {
1476       VA = alignTo(VA, Alignment);
1477       Sec->Addr = VA;
1478       VA += Sec->Size;
1479     } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
1480       uintX_t TVA = VA + ThreadBssOffset;
1481       TVA = alignTo(TVA, Alignment);
1482       Sec->Addr = TVA;
1483       ThreadBssOffset = TVA - VA + Sec->Size;
1484     }
1485   }
1486 }
1487 
1488 // Adjusts the file alignment for a given output section and returns
1489 // its new file offset. The file offset must be the same with its
1490 // virtual address (modulo the page size) so that the loader can load
1491 // executables without any address adjustment.
1492 template <class ELFT, class uintX_t>
1493 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase *Sec) {
1494   OutputSectionBase *First = Sec->FirstInPtLoad;
1495   // If the section is not in a PT_LOAD, we just have to align it.
1496   if (!First)
1497     return alignTo(Off, Sec->Addralign);
1498 
1499   // The first section in a PT_LOAD has to have congruent offset and address
1500   // module the page size.
1501   if (Sec == First)
1502     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1503 
1504   // If two sections share the same PT_LOAD the file offset is calculated
1505   // using this formula: Off2 = Off1 + (VA2 - VA1).
1506   return First->Offset + Sec->Addr - First->Addr;
1507 }
1508 
1509 template <class ELFT, class uintX_t>
1510 void setOffset(OutputSectionBase *Sec, uintX_t &Off) {
1511   if (Sec->Type == SHT_NOBITS) {
1512     Sec->Offset = Off;
1513     return;
1514   }
1515 
1516   Off = getFileAlignment<ELFT>(Off, Sec);
1517   Sec->Offset = Off;
1518   Off += Sec->Size;
1519 }
1520 
1521 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1522   uintX_t Off = 0;
1523   for (OutputSectionBase *Sec : OutputSections)
1524     if (Sec->Flags & SHF_ALLOC)
1525       setOffset<ELFT>(Sec, Off);
1526   FileSize = alignTo(Off, sizeof(uintX_t));
1527 }
1528 
1529 // Assign file offsets to output sections.
1530 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1531   uintX_t Off = 0;
1532   setOffset<ELFT>(Out<ELFT>::ElfHeader, Off);
1533   setOffset<ELFT>(Out<ELFT>::ProgramHeaders, Off);
1534 
1535   for (OutputSectionBase *Sec : OutputSections)
1536     setOffset<ELFT>(Sec, Off);
1537 
1538   SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1539   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1540 }
1541 
1542 // Finalize the program headers. We call this function after we assign
1543 // file offsets and VAs to all sections.
1544 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1545   for (PhdrEntry &P : Phdrs) {
1546     OutputSectionBase *First = P.First;
1547     OutputSectionBase *Last = P.Last;
1548     if (First) {
1549       P.p_filesz = Last->Offset - First->Offset;
1550       if (Last->Type != SHT_NOBITS)
1551         P.p_filesz += Last->Size;
1552       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1553       P.p_offset = First->Offset;
1554       P.p_vaddr = First->Addr;
1555       if (!P.HasLMA)
1556         P.p_paddr = First->getLMA();
1557     }
1558     if (P.p_type == PT_LOAD)
1559       P.p_align = Config->MaxPageSize;
1560     else if (P.p_type == PT_GNU_RELRO) {
1561       P.p_align = 1;
1562       // The glibc dynamic loader rounds the size down, so we need to round up
1563       // to protect the last page. This is a no-op on FreeBSD which always
1564       // rounds up.
1565       P.p_memsz = alignTo(P.p_memsz, Target->PageSize);
1566     }
1567 
1568     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1569     // so round up the size to make sure the offsets are correct.
1570     if (P.p_type == PT_TLS) {
1571       Out<ELFT>::TlsPhdr = &P;
1572       if (P.p_memsz)
1573         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1574     }
1575   }
1576 }
1577 
1578 // The entry point address is chosen in the following ways.
1579 //
1580 // 1. the '-e' entry command-line option;
1581 // 2. the ENTRY(symbol) command in a linker control script;
1582 // 3. the value of the symbol start, if present;
1583 // 4. the address of the first byte of the .text section, if present;
1584 // 5. the address 0.
1585 template <class ELFT> typename ELFT::uint Writer<ELFT>::getEntryAddr() {
1586   // Case 1, 2 or 3. As a special case, if the symbol is actually
1587   // a number, we'll use that number as an address.
1588   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1589     return B->getVA<ELFT>();
1590   uint64_t Addr;
1591   if (!Config->Entry.getAsInteger(0, Addr))
1592     return Addr;
1593 
1594   // Case 4
1595   if (OutputSectionBase *Sec = findSection(".text")) {
1596     if (Config->WarnMissingEntry)
1597       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1598            utohexstr(Sec->Addr));
1599     return Sec->Addr;
1600   }
1601 
1602   // Case 5
1603   if (Config->WarnMissingEntry)
1604     warn("cannot find entry symbol " + Config->Entry +
1605          "; not setting start address");
1606   return 0;
1607 }
1608 
1609 template <class ELFT> static uint8_t getELFEncoding() {
1610   if (ELFT::TargetEndianness == llvm::support::little)
1611     return ELFDATA2LSB;
1612   return ELFDATA2MSB;
1613 }
1614 
1615 static uint16_t getELFType() {
1616   if (Config->Pic)
1617     return ET_DYN;
1618   if (Config->Relocatable)
1619     return ET_REL;
1620   return ET_EXEC;
1621 }
1622 
1623 // This function is called after we have assigned address and size
1624 // to each section. This function fixes some predefined
1625 // symbol values that depend on section address and size.
1626 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1627   auto Set = [](DefinedSynthetic *S1, DefinedSynthetic *S2,
1628                 OutputSectionBase *Sec, uint64_t Value) {
1629     if (S1) {
1630       S1->Section = Sec;
1631       S1->Value = Value;
1632     }
1633     if (S2) {
1634       S2->Section = Sec;
1635       S2->Value = Value;
1636     }
1637   };
1638 
1639   // _etext is the first location after the last read-only loadable segment.
1640   // _edata is the first location after the last read-write loadable segment.
1641   // _end is the first location after the uninitialized data region.
1642   PhdrEntry *Last = nullptr;
1643   PhdrEntry *LastRO = nullptr;
1644   PhdrEntry *LastRW = nullptr;
1645   for (PhdrEntry &P : Phdrs) {
1646     if (P.p_type != PT_LOAD)
1647       continue;
1648     Last = &P;
1649     if (P.p_flags & PF_W)
1650       LastRW = &P;
1651     else
1652       LastRO = &P;
1653   }
1654   if (Last)
1655     Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, Last->First, Last->p_memsz);
1656   if (LastRO)
1657     Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, LastRO->First,
1658         LastRO->p_filesz);
1659   if (LastRW)
1660     Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, LastRW->First,
1661         LastRW->p_filesz);
1662 
1663   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1664   // be equal to the _gp symbol's value.
1665   if (Config->EMachine == EM_MIPS) {
1666     if (!ElfSym<ELFT>::MipsGp->Value) {
1667       // Find GP-relative section with the lowest address
1668       // and use this address to calculate default _gp value.
1669       uintX_t Gp = -1;
1670       for (const OutputSectionBase * OS : OutputSections)
1671         if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1672           Gp = OS->Addr;
1673       if (Gp != (uintX_t)-1)
1674         ElfSym<ELFT>::MipsGp->Value = Gp + 0x7ff0;
1675     }
1676     if (ElfSym<ELFT>::MipsGpDisp)
1677       ElfSym<ELFT>::MipsGpDisp->Value = ElfSym<ELFT>::MipsGp->Value;
1678     if (ElfSym<ELFT>::MipsLocalGp)
1679       ElfSym<ELFT>::MipsLocalGp->Value = ElfSym<ELFT>::MipsGp->Value;
1680   }
1681 }
1682 
1683 template <class ELFT> void Writer<ELFT>::writeHeader() {
1684   uint8_t *Buf = Buffer->getBufferStart();
1685   memcpy(Buf, "\177ELF", 4);
1686 
1687   // Write the ELF header.
1688   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1689   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1690   EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1691   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1692   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1693   EHdr->e_type = getELFType();
1694   EHdr->e_machine = Config->EMachine;
1695   EHdr->e_version = EV_CURRENT;
1696   EHdr->e_entry = getEntryAddr();
1697   EHdr->e_shoff = SectionHeaderOff;
1698   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1699   EHdr->e_phnum = Phdrs.size();
1700   EHdr->e_shentsize = sizeof(Elf_Shdr);
1701   EHdr->e_shnum = OutputSections.size() + 1;
1702   EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1703 
1704   if (Config->EMachine == EM_ARM)
1705     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1706     // but we don't have any firm guarantees of conformance. Linux AArch64
1707     // kernels (as of 2016) require an EABI version to be set.
1708     EHdr->e_flags = EF_ARM_EABI_VER5;
1709   else if (Config->EMachine == EM_MIPS)
1710     EHdr->e_flags = getMipsEFlags<ELFT>();
1711 
1712   if (!Config->Relocatable) {
1713     EHdr->e_phoff = sizeof(Elf_Ehdr);
1714     EHdr->e_phentsize = sizeof(Elf_Phdr);
1715   }
1716 
1717   // Write the program header table.
1718   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1719   for (PhdrEntry &P : Phdrs) {
1720     HBuf->p_type = P.p_type;
1721     HBuf->p_flags = P.p_flags;
1722     HBuf->p_offset = P.p_offset;
1723     HBuf->p_vaddr = P.p_vaddr;
1724     HBuf->p_paddr = P.p_paddr;
1725     HBuf->p_filesz = P.p_filesz;
1726     HBuf->p_memsz = P.p_memsz;
1727     HBuf->p_align = P.p_align;
1728     ++HBuf;
1729   }
1730 
1731   // Write the section header table. Note that the first table entry is null.
1732   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1733   for (OutputSectionBase *Sec : OutputSections)
1734     Sec->writeHeaderTo<ELFT>(++SHdrs);
1735 }
1736 
1737 // Removes a given file asynchronously. This is a performance hack,
1738 // so remove this when operating systems are improved.
1739 //
1740 // On Linux (and probably on other Unix-like systems), unlink(2) is a
1741 // noticeably slow system call. As of 2016, unlink takes 250
1742 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
1743 //
1744 // To create a new result file, we first remove existing file. So, if
1745 // you repeatedly link a 1 GB program in a regular compile-link-debug
1746 // cycle, every cycle wastes 250 milliseconds only to remove a file.
1747 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
1748 // actually counts.
1749 //
1750 // This function spawns a background thread to call unlink.
1751 // The calling thread returns almost immediately.
1752 static void unlinkAsync(StringRef Path) {
1753   if (!Config->Threads || !sys::fs::exists(Config->OutputFile))
1754     return;
1755 
1756   // First, rename Path to avoid race condition. We cannot remove
1757   // Path from a different thread because we are now going to create
1758   // Path as a new file. If we do that in a different thread, the new
1759   // thread can remove the new file.
1760   SmallString<128> TempPath;
1761   if (sys::fs::createUniqueFile(Path + "tmp%%%%%%%%", TempPath))
1762     return;
1763   if (sys::fs::rename(Path, TempPath)) {
1764     sys::fs::remove(TempPath);
1765     return;
1766   }
1767 
1768   // Remove TempPath in background.
1769   std::thread([=] { ::remove(TempPath.str().str().c_str()); }).detach();
1770 }
1771 
1772 // Open a result file.
1773 template <class ELFT> void Writer<ELFT>::openFile() {
1774   unlinkAsync(Config->OutputFile);
1775   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1776       FileOutputBuffer::create(Config->OutputFile, FileSize,
1777                                FileOutputBuffer::F_executable);
1778 
1779   if (auto EC = BufferOrErr.getError())
1780     error("failed to open " + Config->OutputFile + ": " + EC.message());
1781   else
1782     Buffer = std::move(*BufferOrErr);
1783 }
1784 
1785 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1786   uint8_t *Buf = Buffer->getBufferStart();
1787   for (OutputSectionBase *Sec : OutputSections)
1788     if (Sec->Flags & SHF_ALLOC)
1789       Sec->writeTo(Buf + Sec->Offset);
1790 }
1791 
1792 // Write section contents to a mmap'ed file.
1793 template <class ELFT> void Writer<ELFT>::writeSections() {
1794   uint8_t *Buf = Buffer->getBufferStart();
1795 
1796   // PPC64 needs to process relocations in the .opd section
1797   // before processing relocations in code-containing sections.
1798   Out<ELFT>::Opd = findSection(".opd");
1799   if (Out<ELFT>::Opd) {
1800     Out<ELFT>::OpdBuf = Buf + Out<ELFT>::Opd->Offset;
1801     Out<ELFT>::Opd->writeTo(Buf + Out<ELFT>::Opd->Offset);
1802   }
1803 
1804   OutputSectionBase *EhFrameHdr =
1805       In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1806 
1807   // In -r or -emit-relocs mode, write the relocation sections first as in
1808   // ELf_Rel targets we might find out that we need to modify the relocated
1809   // section while doing it.
1810   for (OutputSectionBase *Sec : OutputSections)
1811     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1812       Sec->writeTo(Buf + Sec->Offset);
1813 
1814   for (OutputSectionBase *Sec : OutputSections)
1815     if (Sec != Out<ELFT>::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1816         Sec->Type != SHT_RELA)
1817       Sec->writeTo(Buf + Sec->Offset);
1818 
1819   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1820   // it should be written after .eh_frame is written.
1821   if (!Out<ELFT>::EhFrame->empty() && EhFrameHdr)
1822     EhFrameHdr->writeTo(Buf + EhFrameHdr->Offset);
1823 }
1824 
1825 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1826   if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1827     return;
1828 
1829   // Compute a hash of all sections of the output file.
1830   uint8_t *Start = Buffer->getBufferStart();
1831   uint8_t *End = Start + FileSize;
1832   In<ELFT>::BuildId->writeBuildId({Start, End});
1833 }
1834 
1835 template void elf::writeResult<ELF32LE>();
1836 template void elf::writeResult<ELF32BE>();
1837 template void elf::writeResult<ELF64LE>();
1838 template void elf::writeResult<ELF64BE>();
1839 
1840 template bool elf::allocateHeaders<ELF32LE>(std::vector<PhdrEntry> &,
1841                                             ArrayRef<OutputSectionBase *>,
1842                                             uint64_t);
1843 template bool elf::allocateHeaders<ELF32BE>(std::vector<PhdrEntry> &,
1844                                             ArrayRef<OutputSectionBase *>,
1845                                             uint64_t);
1846 template bool elf::allocateHeaders<ELF64LE>(std::vector<PhdrEntry> &,
1847                                             ArrayRef<OutputSectionBase *>,
1848                                             uint64_t);
1849 template bool elf::allocateHeaders<ELF64BE>(std::vector<PhdrEntry> &,
1850                                             ArrayRef<OutputSectionBase *>,
1851                                             uint64_t);
1852 
1853 template bool elf::isRelroSection<ELF32LE>(const OutputSectionBase *);
1854 template bool elf::isRelroSection<ELF32BE>(const OutputSectionBase *);
1855 template bool elf::isRelroSection<ELF64LE>(const OutputSectionBase *);
1856 template bool elf::isRelroSection<ELF64BE>(const OutputSectionBase *);
1857 
1858 template void elf::reportDiscarded<ELF32LE>(InputSectionBase<ELF32LE> *);
1859 template void elf::reportDiscarded<ELF32BE>(InputSectionBase<ELF32BE> *);
1860 template void elf::reportDiscarded<ELF64LE>(InputSectionBase<ELF64LE> *);
1861 template void elf::reportDiscarded<ELF64BE>(InputSectionBase<ELF64BE> *);
1862