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