xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision f1ec7f83)
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 "AArch64ErrataFix.h"
12 #include "CallGraphSort.h"
13 #include "Config.h"
14 #include "Filesystem.h"
15 #include "LinkerScript.h"
16 #include "MapFile.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Strings.h"
25 #include "lld/Common/Threads.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include <climits>
29 
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
35 
36 using namespace lld;
37 using namespace lld::elf;
38 
39 namespace {
40 // The writer writes a SymbolTable result to a file.
41 template <class ELFT> class Writer {
42 public:
43   Writer() : Buffer(errorHandler().OutputBuffer) {}
44   typedef typename ELFT::Shdr Elf_Shdr;
45   typedef typename ELFT::Ehdr Elf_Ehdr;
46   typedef typename ELFT::Phdr Elf_Phdr;
47 
48   void run();
49 
50 private:
51   void copyLocalSymbols();
52   void addSectionSymbols();
53   void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> Fn);
54   void sortSections();
55   void resolveShfLinkOrder();
56   void sortInputSections();
57   void finalizeSections();
58   void setReservedSymbolSections();
59 
60   std::vector<PhdrEntry *> createPhdrs();
61   void removeEmptyPTLoad();
62   void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
63   void assignFileOffsets();
64   void assignFileOffsetsBinary();
65   void setPhdrs();
66   void checkSections();
67   void fixSectionAlignments();
68   void openFile();
69   void writeTrapInstr();
70   void writeHeader();
71   void writeSections();
72   void writeSectionsBinary();
73   void writeBuildId();
74 
75   std::unique_ptr<FileOutputBuffer> &Buffer;
76 
77   void addRelIpltSymbols();
78   void addStartEndSymbols();
79   void addStartStopSymbols(OutputSection *Sec);
80   uint64_t getEntryAddr();
81 
82   std::vector<PhdrEntry *> Phdrs;
83 
84   uint64_t FileSize;
85   uint64_t SectionHeaderOff;
86 };
87 } // anonymous namespace
88 
89 static bool isSectionPrefix(StringRef Prefix, StringRef Name) {
90   return Name.startswith(Prefix) || Name == Prefix.drop_back();
91 }
92 
93 StringRef elf::getOutputSectionName(const InputSectionBase *S) {
94   if (Config->Relocatable)
95     return S->Name;
96 
97   // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
98   // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
99   // technically required, but not doing it is odd). This code guarantees that.
100   if (auto *IS = dyn_cast<InputSection>(S)) {
101     if (InputSectionBase *Rel = IS->getRelocatedSection()) {
102       OutputSection *Out = Rel->getOutputSection();
103       if (S->Type == SHT_RELA)
104         return Saver.save(".rela" + Out->Name);
105       return Saver.save(".rel" + Out->Name);
106     }
107   }
108 
109   // This check is for -z keep-text-section-prefix.  This option separates text
110   // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
111   // ".text.exit".
112   // When enabled, this allows identifying the hot code region (.text.hot) in
113   // the final binary which can be selectively mapped to huge pages or mlocked,
114   // for instance.
115   if (Config->ZKeepTextSectionPrefix)
116     for (StringRef V :
117          {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."}) {
118       if (isSectionPrefix(V, S->Name))
119         return V.drop_back();
120     }
121 
122   for (StringRef V :
123        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
124         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
125         ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
126     if (isSectionPrefix(V, S->Name))
127       return V.drop_back();
128   }
129 
130   // CommonSection is identified as "COMMON" in linker scripts.
131   // By default, it should go to .bss section.
132   if (S->Name == "COMMON")
133     return ".bss";
134 
135   return S->Name;
136 }
137 
138 static bool needsInterpSection() {
139   return !SharedFiles.empty() && !Config->DynamicLinker.empty() &&
140          Script->needsInterpSection();
141 }
142 
143 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
144 
145 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
146   llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
147     if (P->p_type != PT_LOAD)
148       return false;
149     if (!P->FirstSec)
150       return true;
151     uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
152     return Size == 0;
153   });
154 }
155 
156 template <class ELFT> static void combineEhFrameSections() {
157   for (InputSectionBase *&S : InputSections) {
158     EhInputSection *ES = dyn_cast<EhInputSection>(S);
159     if (!ES || !ES->Live)
160       continue;
161 
162     InX::EhFrame->addSection<ELFT>(ES);
163     S = nullptr;
164   }
165 
166   std::vector<InputSectionBase *> &V = InputSections;
167   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
168 }
169 
170 static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec,
171                                    uint64_t Val, uint8_t StOther = STV_HIDDEN,
172                                    uint8_t Binding = STB_GLOBAL) {
173   Symbol *S = Symtab->find(Name);
174   if (!S || S->isDefined())
175     return nullptr;
176   Symbol *Sym = Symtab->addRegular(Name, StOther, STT_NOTYPE, Val,
177                                    /*Size=*/0, Binding, Sec,
178                                    /*File=*/nullptr);
179   return cast<Defined>(Sym);
180 }
181 
182 // The linker is expected to define some symbols depending on
183 // the linking result. This function defines such symbols.
184 void elf::addReservedSymbols() {
185   if (Config->EMachine == EM_MIPS) {
186     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
187     // so that it points to an absolute address which by default is relative
188     // to GOT. Default offset is 0x7ff0.
189     // See "Global Data Symbols" in Chapter 6 in the following document:
190     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
191     ElfSym::MipsGp = Symtab->addAbsolute("_gp", STV_HIDDEN, STB_GLOBAL);
192 
193     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
194     // start of function and 'gp' pointer into GOT.
195     if (Symtab->find("_gp_disp"))
196       ElfSym::MipsGpDisp =
197           Symtab->addAbsolute("_gp_disp", STV_HIDDEN, STB_GLOBAL);
198 
199     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
200     // pointer. This symbol is used in the code generated by .cpload pseudo-op
201     // in case of using -mno-shared option.
202     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
203     if (Symtab->find("__gnu_local_gp"))
204       ElfSym::MipsLocalGp =
205           Symtab->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_GLOBAL);
206   }
207 
208   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
209   // combines the typical ELF GOT with the small data sections. It commonly
210   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
211   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
212   // represent the TOC base which is offset by 0x8000 bytes from the start of
213   // the .got section.
214   ElfSym::GlobalOffsetTable = addOptionalRegular(
215       (Config->EMachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_",
216       Out::ElfHeader, Target->GotBaseSymOff);
217 
218   // __ehdr_start is the location of ELF file headers. Note that we define
219   // this symbol unconditionally even when using a linker script, which
220   // differs from the behavior implemented by GNU linker which only define
221   // this symbol if ELF headers are in the memory mapped segment.
222   addOptionalRegular("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
223 
224   // __executable_start is not documented, but the expectation of at
225   // least the Android libc is that it points to the ELF header.
226   addOptionalRegular("__executable_start", Out::ElfHeader, 0, STV_HIDDEN);
227 
228   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
229   // each DSO. The address of the symbol doesn't matter as long as they are
230   // different in different DSOs, so we chose the start address of the DSO.
231   addOptionalRegular("__dso_handle", Out::ElfHeader, 0, STV_HIDDEN);
232 
233   // If linker script do layout we do not need to create any standart symbols.
234   if (Script->HasSectionsCommand)
235     return;
236 
237   auto Add = [](StringRef S, int64_t Pos) {
238     return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT);
239   };
240 
241   ElfSym::Bss = Add("__bss_start", 0);
242   ElfSym::End1 = Add("end", -1);
243   ElfSym::End2 = Add("_end", -1);
244   ElfSym::Etext1 = Add("etext", -1);
245   ElfSym::Etext2 = Add("_etext", -1);
246   ElfSym::Edata1 = Add("edata", -1);
247   ElfSym::Edata2 = Add("_edata", -1);
248 }
249 
250 static OutputSection *findSection(StringRef Name) {
251   for (BaseCommand *Base : Script->SectionCommands)
252     if (auto *Sec = dyn_cast<OutputSection>(Base))
253       if (Sec->Name == Name)
254         return Sec;
255   return nullptr;
256 }
257 
258 // Initialize Out members.
259 template <class ELFT> static void createSyntheticSections() {
260   // Initialize all pointers with NULL. This is needed because
261   // you can call lld::elf::main more than once as a library.
262   memset(&Out::First, 0, sizeof(Out));
263 
264   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
265 
266   InX::DynStrTab = make<StringTableSection>(".dynstr", true);
267   InX::Dynamic = make<DynamicSection<ELFT>>();
268   if (Config->AndroidPackDynRelocs) {
269     InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
270         Config->IsRela ? ".rela.dyn" : ".rel.dyn");
271   } else {
272     InX::RelaDyn = make<RelocationSection<ELFT>>(
273         Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
274   }
275   InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
276 
277   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
278   Out::ProgramHeaders->Alignment = Config->Wordsize;
279 
280   if (needsInterpSection()) {
281     InX::Interp = createInterpSection();
282     Add(InX::Interp);
283   } else {
284     InX::Interp = nullptr;
285   }
286 
287   if (Config->Strip != StripPolicy::All) {
288     InX::StrTab = make<StringTableSection>(".strtab", false);
289     InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
290     InX::SymTabShndx = make<SymtabShndxSection>();
291   }
292 
293   if (Config->BuildId != BuildIdKind::None) {
294     InX::BuildId = make<BuildIdSection>();
295     Add(InX::BuildId);
296   }
297 
298   InX::Bss = make<BssSection>(".bss", 0, 1);
299   Add(InX::Bss);
300 
301   // If there is a SECTIONS command and a .data.rel.ro section name use name
302   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
303   // This makes sure our relro is contiguous.
304   bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro");
305   InX::BssRelRo =
306       make<BssSection>(HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
307   Add(InX::BssRelRo);
308 
309   // Add MIPS-specific sections.
310   if (Config->EMachine == EM_MIPS) {
311     if (!Config->Shared && Config->HasDynSymTab) {
312       InX::MipsRldMap = make<MipsRldMapSection>();
313       Add(InX::MipsRldMap);
314     }
315     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
316       Add(Sec);
317     if (auto *Sec = MipsOptionsSection<ELFT>::create())
318       Add(Sec);
319     if (auto *Sec = MipsReginfoSection<ELFT>::create())
320       Add(Sec);
321   }
322 
323   if (Config->HasDynSymTab) {
324     InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
325     Add(InX::DynSymTab);
326 
327     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
328     Add(In<ELFT>::VerSym);
329 
330     if (!Config->VersionDefinitions.empty()) {
331       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
332       Add(In<ELFT>::VerDef);
333     }
334 
335     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
336     Add(In<ELFT>::VerNeed);
337 
338     if (Config->GnuHash) {
339       InX::GnuHashTab = make<GnuHashTableSection>();
340       Add(InX::GnuHashTab);
341     }
342 
343     if (Config->SysvHash) {
344       InX::HashTab = make<HashTableSection>();
345       Add(InX::HashTab);
346     }
347 
348     Add(InX::Dynamic);
349     Add(InX::DynStrTab);
350     Add(InX::RelaDyn);
351   }
352 
353   if (Config->RelrPackDynRelocs) {
354     InX::RelrDyn = make<RelrSection<ELFT>>();
355     Add(InX::RelrDyn);
356   }
357 
358   // Add .got. MIPS' .got is so different from the other archs,
359   // it has its own class.
360   if (Config->EMachine == EM_MIPS) {
361     InX::MipsGot = make<MipsGotSection>();
362     Add(InX::MipsGot);
363   } else {
364     InX::Got = make<GotSection>();
365     Add(InX::Got);
366   }
367 
368   InX::GotPlt = make<GotPltSection>();
369   Add(InX::GotPlt);
370   InX::IgotPlt = make<IgotPltSection>();
371   Add(InX::IgotPlt);
372 
373   if (Config->GdbIndex) {
374     InX::GdbIndex = GdbIndexSection::create<ELFT>();
375     Add(InX::GdbIndex);
376   }
377 
378   // We always need to add rel[a].plt to output if it has entries.
379   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
380   InX::RelaPlt = make<RelocationSection<ELFT>>(
381       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
382   Add(InX::RelaPlt);
383 
384   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
385   // that the IRelative relocations are processed last by the dynamic loader.
386   // We cannot place the iplt section in .rel.dyn when Android relocation
387   // packing is enabled because that would cause a section type mismatch.
388   // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
389   // we can get the desired behaviour by placing the iplt section in .rel.plt.
390   InX::RelaIplt = make<RelocationSection<ELFT>>(
391       (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs)
392           ? ".rel.dyn"
393           : InX::RelaPlt->Name,
394       false /*Sort*/);
395   Add(InX::RelaIplt);
396 
397   InX::Plt = make<PltSection>(false);
398   Add(InX::Plt);
399   InX::Iplt = make<PltSection>(true);
400   Add(InX::Iplt);
401 
402   // .note.GNU-stack is always added when we are creating a re-linkable
403   // object file. Other linkers are using the presence of this marker
404   // section to control the executable-ness of the stack area, but that
405   // is irrelevant these days. Stack area should always be non-executable
406   // by default. So we emit this section unconditionally.
407   if (Config->Relocatable)
408     Add(make<GnuStackSection>());
409 
410   if (!Config->Relocatable) {
411     if (Config->EhFrameHdr) {
412       InX::EhFrameHdr = make<EhFrameHeader>();
413       Add(InX::EhFrameHdr);
414     }
415     InX::EhFrame = make<EhFrameSection>();
416     Add(InX::EhFrame);
417   }
418 
419   if (InX::SymTab)
420     Add(InX::SymTab);
421   if (InX::SymTabShndx)
422     Add(InX::SymTabShndx);
423   Add(InX::ShStrTab);
424   if (InX::StrTab)
425     Add(InX::StrTab);
426 
427   if (Config->EMachine == EM_ARM && !Config->Relocatable)
428     // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
429     // to find the exact address range of the last entry.
430     Add(make<ARMExidxSentinelSection>());
431 }
432 
433 // The main function of the writer.
434 template <class ELFT> void Writer<ELFT>::run() {
435   // Create linker-synthesized sections such as .got or .plt.
436   // Such sections are of type input section.
437   createSyntheticSections<ELFT>();
438 
439   if (!Config->Relocatable)
440     combineEhFrameSections<ELFT>();
441 
442   // We want to process linker script commands. When SECTIONS command
443   // is given we let it create sections.
444   Script->processSectionCommands();
445 
446   // Linker scripts controls how input sections are assigned to output sections.
447   // Input sections that were not handled by scripts are called "orphans", and
448   // they are assigned to output sections by the default rule. Process that.
449   Script->addOrphanSections();
450 
451   if (Config->Discard != DiscardPolicy::All)
452     copyLocalSymbols();
453 
454   if (Config->CopyRelocs)
455     addSectionSymbols();
456 
457   // Now that we have a complete set of output sections. This function
458   // completes section contents. For example, we need to add strings
459   // to the string table, and add entries to .got and .plt.
460   // finalizeSections does that.
461   finalizeSections();
462   if (errorCount())
463     return;
464 
465   Script->assignAddresses();
466 
467   // If -compressed-debug-sections is specified, we need to compress
468   // .debug_* sections. Do it right now because it changes the size of
469   // output sections.
470   for (OutputSection *Sec : OutputSections)
471     Sec->maybeCompress<ELFT>();
472 
473   Script->allocateHeaders(Phdrs);
474 
475   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
476   // 0 sized region. This has to be done late since only after assignAddresses
477   // we know the size of the sections.
478   removeEmptyPTLoad();
479 
480   if (!Config->OFormatBinary)
481     assignFileOffsets();
482   else
483     assignFileOffsetsBinary();
484 
485   setPhdrs();
486 
487   if (Config->Relocatable) {
488     for (OutputSection *Sec : OutputSections)
489       Sec->Addr = 0;
490   }
491 
492   if (Config->CheckSections)
493     checkSections();
494 
495   // It does not make sense try to open the file if we have error already.
496   if (errorCount())
497     return;
498   // Write the result down to a file.
499   openFile();
500   if (errorCount())
501     return;
502 
503   if (!Config->OFormatBinary) {
504     writeTrapInstr();
505     writeHeader();
506     writeSections();
507   } else {
508     writeSectionsBinary();
509   }
510 
511   // Backfill .note.gnu.build-id section content. This is done at last
512   // because the content is usually a hash value of the entire output file.
513   writeBuildId();
514   if (errorCount())
515     return;
516 
517   // Handle -Map and -cref options.
518   writeMapFile();
519   writeCrossReferenceTable();
520   if (errorCount())
521     return;
522 
523   if (auto E = Buffer->commit())
524     error("failed to write to the output file: " + toString(std::move(E)));
525 }
526 
527 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
528                                const Symbol &B) {
529   if (B.isSection())
530     return false;
531 
532   if (Config->Discard == DiscardPolicy::None)
533     return true;
534 
535   // In ELF assembly .L symbols are normally discarded by the assembler.
536   // If the assembler fails to do so, the linker discards them if
537   // * --discard-locals is used.
538   // * The symbol is in a SHF_MERGE section, which is normally the reason for
539   //   the assembler keeping the .L symbol.
540   if (!SymName.startswith(".L") && !SymName.empty())
541     return true;
542 
543   if (Config->Discard == DiscardPolicy::Locals)
544     return false;
545 
546   return !Sec || !(Sec->Flags & SHF_MERGE);
547 }
548 
549 static bool includeInSymtab(const Symbol &B) {
550   if (!B.isLocal() && !B.IsUsedInRegularObj)
551     return false;
552 
553   if (auto *D = dyn_cast<Defined>(&B)) {
554     // Always include absolute symbols.
555     SectionBase *Sec = D->Section;
556     if (!Sec)
557       return true;
558     Sec = Sec->Repl;
559     // Exclude symbols pointing to garbage-collected sections.
560     if (isa<InputSectionBase>(Sec) && !Sec->Live)
561       return false;
562     if (auto *S = dyn_cast<MergeInputSection>(Sec))
563       if (!S->getSectionPiece(D->Value)->Live)
564         return false;
565     return true;
566   }
567   return B.Used;
568 }
569 
570 // Local symbols are not in the linker's symbol table. This function scans
571 // each object file's symbol table to copy local symbols to the output.
572 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
573   if (!InX::SymTab)
574     return;
575   for (InputFile *File : ObjectFiles) {
576     ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
577     for (Symbol *B : F->getLocalSymbols()) {
578       if (!B->isLocal())
579         fatal(toString(F) +
580               ": broken object: getLocalSymbols returns a non-local symbol");
581       auto *DR = dyn_cast<Defined>(B);
582 
583       // No reason to keep local undefined symbol in symtab.
584       if (!DR)
585         continue;
586       if (!includeInSymtab(*B))
587         continue;
588 
589       SectionBase *Sec = DR->Section;
590       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
591         continue;
592       InX::SymTab->addSymbol(B);
593     }
594   }
595 }
596 
597 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
598   // Create a section symbol for each output section so that we can represent
599   // relocations that point to the section. If we know that no relocation is
600   // referring to a section (that happens if the section is a synthetic one), we
601   // don't create a section symbol for that section.
602   for (BaseCommand *Base : Script->SectionCommands) {
603     auto *Sec = dyn_cast<OutputSection>(Base);
604     if (!Sec)
605       continue;
606     auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
607       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
608         return !ISD->Sections.empty();
609       return false;
610     });
611     if (I == Sec->SectionCommands.end())
612       continue;
613     InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
614 
615     // Relocations are not using REL[A] section symbols.
616     if (IS->Type == SHT_REL || IS->Type == SHT_RELA)
617       continue;
618 
619     // Unlike other synthetic sections, mergeable output sections contain data
620     // copied from input sections, and there may be a relocation pointing to its
621     // contents if -r or -emit-reloc are given.
622     if (isa<SyntheticSection>(IS) && !(IS->Flags & SHF_MERGE))
623       continue;
624 
625     auto *Sym =
626         make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
627                       /*Value=*/0, /*Size=*/0, IS);
628     InX::SymTab->addSymbol(Sym);
629   }
630 }
631 
632 // Today's loaders have a feature to make segments read-only after
633 // processing dynamic relocations to enhance security. PT_GNU_RELRO
634 // is defined for that.
635 //
636 // This function returns true if a section needs to be put into a
637 // PT_GNU_RELRO segment.
638 static bool isRelroSection(const OutputSection *Sec) {
639   if (!Config->ZRelro)
640     return false;
641 
642   uint64_t Flags = Sec->Flags;
643 
644   // Non-allocatable or non-writable sections don't need RELRO because
645   // they are not writable or not even mapped to memory in the first place.
646   // RELRO is for sections that are essentially read-only but need to
647   // be writable only at process startup to allow dynamic linker to
648   // apply relocations.
649   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
650     return false;
651 
652   // Once initialized, TLS data segments are used as data templates
653   // for a thread-local storage. For each new thread, runtime
654   // allocates memory for a TLS and copy templates there. No thread
655   // are supposed to use templates directly. Thus, it can be in RELRO.
656   if (Flags & SHF_TLS)
657     return true;
658 
659   // .init_array, .preinit_array and .fini_array contain pointers to
660   // functions that are executed on process startup or exit. These
661   // pointers are set by the static linker, and they are not expected
662   // to change at runtime. But if you are an attacker, you could do
663   // interesting things by manipulating pointers in .fini_array, for
664   // example. So they are put into RELRO.
665   uint32_t Type = Sec->Type;
666   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
667       Type == SHT_PREINIT_ARRAY)
668     return true;
669 
670   // .got contains pointers to external symbols. They are resolved by
671   // the dynamic linker when a module is loaded into memory, and after
672   // that they are not expected to change. So, it can be in RELRO.
673   if (InX::Got && Sec == InX::Got->getParent())
674     return true;
675 
676   if (Sec->Name.equals(".toc"))
677     return true;
678 
679   // .got.plt contains pointers to external function symbols. They are
680   // by default resolved lazily, so we usually cannot put it into RELRO.
681   // However, if "-z now" is given, the lazy symbol resolution is
682   // disabled, which enables us to put it into RELRO.
683   if (Sec == InX::GotPlt->getParent())
684     return Config->ZNow;
685 
686   // .dynamic section contains data for the dynamic linker, and
687   // there's no need to write to it at runtime, so it's better to put
688   // it into RELRO.
689   if (Sec == InX::Dynamic->getParent())
690     return true;
691 
692   // Sections with some special names are put into RELRO. This is a
693   // bit unfortunate because section names shouldn't be significant in
694   // ELF in spirit. But in reality many linker features depend on
695   // magic section names.
696   StringRef S = Sec->Name;
697   return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" ||
698          S == ".dtors" || S == ".jcr" || S == ".eh_frame" ||
699          S == ".openbsd.randomdata";
700 }
701 
702 // We compute a rank for each section. The rank indicates where the
703 // section should be placed in the file.  Instead of using simple
704 // numbers (0,1,2...), we use a series of flags. One for each decision
705 // point when placing the section.
706 // Using flags has two key properties:
707 // * It is easy to check if a give branch was taken.
708 // * It is easy two see how similar two ranks are (see getRankProximity).
709 enum RankFlags {
710   RF_NOT_ADDR_SET = 1 << 18,
711   RF_NOT_INTERP = 1 << 17,
712   RF_NOT_ALLOC = 1 << 16,
713   RF_WRITE = 1 << 15,
714   RF_EXEC_WRITE = 1 << 14,
715   RF_EXEC = 1 << 13,
716   RF_RODATA = 1 << 12,
717   RF_NON_TLS_BSS = 1 << 11,
718   RF_NON_TLS_BSS_RO = 1 << 10,
719   RF_NOT_TLS = 1 << 9,
720   RF_BSS = 1 << 8,
721   RF_NOTE = 1 << 7,
722   RF_PPC_NOT_TOCBSS = 1 << 6,
723   RF_PPC_TOCL = 1 << 5,
724   RF_PPC_TOC = 1 << 4,
725   RF_PPC_GOT = 1 << 3,
726   RF_PPC_BRANCH_LT = 1 << 2,
727   RF_MIPS_GPREL = 1 << 1,
728   RF_MIPS_NOT_GOT = 1 << 0
729 };
730 
731 static unsigned getSectionRank(const OutputSection *Sec) {
732   unsigned Rank = 0;
733 
734   // We want to put section specified by -T option first, so we
735   // can start assigning VA starting from them later.
736   if (Config->SectionStartMap.count(Sec->Name))
737     return Rank;
738   Rank |= RF_NOT_ADDR_SET;
739 
740   // Put .interp first because some loaders want to see that section
741   // on the first page of the executable file when loaded into memory.
742   if (Sec->Name == ".interp")
743     return Rank;
744   Rank |= RF_NOT_INTERP;
745 
746   // Allocatable sections go first to reduce the total PT_LOAD size and
747   // so debug info doesn't change addresses in actual code.
748   if (!(Sec->Flags & SHF_ALLOC))
749     return Rank | RF_NOT_ALLOC;
750 
751   // Sort sections based on their access permission in the following
752   // order: R, RX, RWX, RW.  This order is based on the following
753   // considerations:
754   // * Read-only sections come first such that they go in the
755   //   PT_LOAD covering the program headers at the start of the file.
756   // * Read-only, executable sections come next.
757   // * Writable, executable sections follow such that .plt on
758   //   architectures where it needs to be writable will be placed
759   //   between .text and .data.
760   // * Writable sections come last, such that .bss lands at the very
761   //   end of the last PT_LOAD.
762   bool IsExec = Sec->Flags & SHF_EXECINSTR;
763   bool IsWrite = Sec->Flags & SHF_WRITE;
764 
765   if (IsExec) {
766     if (IsWrite)
767       Rank |= RF_EXEC_WRITE;
768     else
769       Rank |= RF_EXEC;
770   } else if (IsWrite) {
771     Rank |= RF_WRITE;
772   } else if (Sec->Type == SHT_PROGBITS) {
773     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
774     // .eh_frame) closer to .text. They likely contain PC or GOT relative
775     // relocations and there could be relocation overflow if other huge sections
776     // (.dynstr .dynsym) were placed in between.
777     Rank |= RF_RODATA;
778   }
779 
780   // If we got here we know that both A and B are in the same PT_LOAD.
781 
782   bool IsTls = Sec->Flags & SHF_TLS;
783   bool IsNoBits = Sec->Type == SHT_NOBITS;
784 
785   // The first requirement we have is to put (non-TLS) nobits sections last. The
786   // reason is that the only thing the dynamic linker will see about them is a
787   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
788   // PT_LOAD, so that has to correspond to the nobits sections.
789   bool IsNonTlsNoBits = IsNoBits && !IsTls;
790   if (IsNonTlsNoBits)
791     Rank |= RF_NON_TLS_BSS;
792 
793   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
794   // sections after r/w ones, so that the RelRo sections are contiguous.
795   bool IsRelRo = isRelroSection(Sec);
796   if (IsNonTlsNoBits && !IsRelRo)
797     Rank |= RF_NON_TLS_BSS_RO;
798   if (!IsNonTlsNoBits && IsRelRo)
799     Rank |= RF_NON_TLS_BSS_RO;
800 
801   // The TLS initialization block needs to be a single contiguous block in a R/W
802   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
803   // sections. The TLS NOBITS sections are placed here as they don't take up
804   // virtual address space in the PT_LOAD.
805   if (!IsTls)
806     Rank |= RF_NOT_TLS;
807 
808   // Within the TLS initialization block, the non-nobits sections need to appear
809   // first.
810   if (IsNoBits)
811     Rank |= RF_BSS;
812 
813   // We create a NOTE segment for contiguous .note sections, so make
814   // them contigous if there are more than one .note section with the
815   // same attributes.
816   if (Sec->Type == SHT_NOTE)
817     Rank |= RF_NOTE;
818 
819   // Some architectures have additional ordering restrictions for sections
820   // within the same PT_LOAD.
821   if (Config->EMachine == EM_PPC64) {
822     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
823     // that we would like to make sure appear is a specific order to maximize
824     // their coverage by a single signed 16-bit offset from the TOC base
825     // pointer. Conversely, the special .tocbss section should be first among
826     // all SHT_NOBITS sections. This will put it next to the loaded special
827     // PPC64 sections (and, thus, within reach of the TOC base pointer).
828     StringRef Name = Sec->Name;
829     if (Name != ".tocbss")
830       Rank |= RF_PPC_NOT_TOCBSS;
831 
832     if (Name == ".toc1")
833       Rank |= RF_PPC_TOCL;
834 
835     if (Name == ".toc")
836       Rank |= RF_PPC_TOC;
837 
838     if (Name == ".got")
839       Rank |= RF_PPC_GOT;
840 
841     if (Name == ".branch_lt")
842       Rank |= RF_PPC_BRANCH_LT;
843   }
844 
845   if (Config->EMachine == EM_MIPS) {
846     // All sections with SHF_MIPS_GPREL flag should be grouped together
847     // because data in these sections is addressable with a gp relative address.
848     if (Sec->Flags & SHF_MIPS_GPREL)
849       Rank |= RF_MIPS_GPREL;
850 
851     if (Sec->Name != ".got")
852       Rank |= RF_MIPS_NOT_GOT;
853   }
854 
855   return Rank;
856 }
857 
858 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
859   const OutputSection *A = cast<OutputSection>(ACmd);
860   const OutputSection *B = cast<OutputSection>(BCmd);
861   if (A->SortRank != B->SortRank)
862     return A->SortRank < B->SortRank;
863   if (!(A->SortRank & RF_NOT_ADDR_SET))
864     return Config->SectionStartMap.lookup(A->Name) <
865            Config->SectionStartMap.lookup(B->Name);
866   return false;
867 }
868 
869 void PhdrEntry::add(OutputSection *Sec) {
870   LastSec = Sec;
871   if (!FirstSec)
872     FirstSec = Sec;
873   p_align = std::max(p_align, Sec->Alignment);
874   if (p_type == PT_LOAD)
875     Sec->PtLoad = this;
876 }
877 
878 // The beginning and the ending of .rel[a].plt section are marked
879 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
880 // executable. The runtime needs these symbols in order to resolve
881 // all IRELATIVE relocs on startup. For dynamic executables, we don't
882 // need these symbols, since IRELATIVE relocs are resolved through GOT
883 // and PLT. For details, see http://www.airs.com/blog/archives/403.
884 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
885   if (needsInterpSection())
886     return;
887   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
888   addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
889 
890   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
891   ElfSym::RelaIpltEnd =
892       addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
893 }
894 
895 template <class ELFT>
896 void Writer<ELFT>::forEachRelSec(
897     llvm::function_ref<void(InputSectionBase &)> Fn) {
898   // Scan all relocations. Each relocation goes through a series
899   // of tests to determine if it needs special treatment, such as
900   // creating GOT, PLT, copy relocations, etc.
901   // Note that relocations for non-alloc sections are directly
902   // processed by InputSection::relocateNonAlloc.
903   for (InputSectionBase *IS : InputSections)
904     if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
905       Fn(*IS);
906   for (EhInputSection *ES : InX::EhFrame->Sections)
907     Fn(*ES);
908 }
909 
910 // This function generates assignments for predefined symbols (e.g. _end or
911 // _etext) and inserts them into the commands sequence to be processed at the
912 // appropriate time. This ensures that the value is going to be correct by the
913 // time any references to these symbols are processed and is equivalent to
914 // defining these symbols explicitly in the linker script.
915 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
916   if (ElfSym::GlobalOffsetTable) {
917     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
918     // to the start of the .got or .got.plt section.
919     InputSection *GotSection = InX::GotPlt;
920     if (!Target->GotBaseSymInGotPlt)
921       GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
922                                 : cast<InputSection>(InX::Got);
923     ElfSym::GlobalOffsetTable->Section = GotSection;
924   }
925 
926   if (ElfSym::RelaIpltEnd)
927     ElfSym::RelaIpltEnd->Value = InX::RelaIplt->getSize();
928 
929   PhdrEntry *Last = nullptr;
930   PhdrEntry *LastRO = nullptr;
931 
932   for (PhdrEntry *P : Phdrs) {
933     if (P->p_type != PT_LOAD)
934       continue;
935     Last = P;
936     if (!(P->p_flags & PF_W))
937       LastRO = P;
938   }
939 
940   if (LastRO) {
941     // _etext is the first location after the last read-only loadable segment.
942     if (ElfSym::Etext1)
943       ElfSym::Etext1->Section = LastRO->LastSec;
944     if (ElfSym::Etext2)
945       ElfSym::Etext2->Section = LastRO->LastSec;
946   }
947 
948   if (Last) {
949     // _edata points to the end of the last mapped initialized section.
950     OutputSection *Edata = nullptr;
951     for (OutputSection *OS : OutputSections) {
952       if (OS->Type != SHT_NOBITS)
953         Edata = OS;
954       if (OS == Last->LastSec)
955         break;
956     }
957 
958     if (ElfSym::Edata1)
959       ElfSym::Edata1->Section = Edata;
960     if (ElfSym::Edata2)
961       ElfSym::Edata2->Section = Edata;
962 
963     // _end is the first location after the uninitialized data region.
964     if (ElfSym::End1)
965       ElfSym::End1->Section = Last->LastSec;
966     if (ElfSym::End2)
967       ElfSym::End2->Section = Last->LastSec;
968   }
969 
970   if (ElfSym::Bss)
971     ElfSym::Bss->Section = findSection(".bss");
972 
973   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
974   // be equal to the _gp symbol's value.
975   if (ElfSym::MipsGp) {
976     // Find GP-relative section with the lowest address
977     // and use this address to calculate default _gp value.
978     for (OutputSection *OS : OutputSections) {
979       if (OS->Flags & SHF_MIPS_GPREL) {
980         ElfSym::MipsGp->Section = OS;
981         ElfSym::MipsGp->Value = 0x7ff0;
982         break;
983       }
984     }
985   }
986 }
987 
988 // We want to find how similar two ranks are.
989 // The more branches in getSectionRank that match, the more similar they are.
990 // Since each branch corresponds to a bit flag, we can just use
991 // countLeadingZeros.
992 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
993   return countLeadingZeros(A->SortRank ^ B->SortRank);
994 }
995 
996 static int getRankProximity(OutputSection *A, BaseCommand *B) {
997   if (auto *Sec = dyn_cast<OutputSection>(B))
998     return getRankProximityAux(A, Sec);
999   return -1;
1000 }
1001 
1002 // When placing orphan sections, we want to place them after symbol assignments
1003 // so that an orphan after
1004 //   begin_foo = .;
1005 //   foo : { *(foo) }
1006 //   end_foo = .;
1007 // doesn't break the intended meaning of the begin/end symbols.
1008 // We don't want to go over sections since findOrphanPos is the
1009 // one in charge of deciding the order of the sections.
1010 // We don't want to go over changes to '.', since doing so in
1011 //  rx_sec : { *(rx_sec) }
1012 //  . = ALIGN(0x1000);
1013 //  /* The RW PT_LOAD starts here*/
1014 //  rw_sec : { *(rw_sec) }
1015 // would mean that the RW PT_LOAD would become unaligned.
1016 static bool shouldSkip(BaseCommand *Cmd) {
1017   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
1018     return Assign->Name != ".";
1019   return false;
1020 }
1021 
1022 // We want to place orphan sections so that they share as much
1023 // characteristics with their neighbors as possible. For example, if
1024 // both are rw, or both are tls.
1025 template <typename ELFT>
1026 static std::vector<BaseCommand *>::iterator
1027 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1028               std::vector<BaseCommand *>::iterator E) {
1029   OutputSection *Sec = cast<OutputSection>(*E);
1030 
1031   // Find the first element that has as close a rank as possible.
1032   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1033     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1034   });
1035   if (I == E)
1036     return E;
1037 
1038   // Consider all existing sections with the same proximity.
1039   int Proximity = getRankProximity(Sec, *I);
1040   for (; I != E; ++I) {
1041     auto *CurSec = dyn_cast<OutputSection>(*I);
1042     if (!CurSec)
1043       continue;
1044     if (getRankProximity(Sec, CurSec) != Proximity ||
1045         Sec->SortRank < CurSec->SortRank)
1046       break;
1047   }
1048 
1049   auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); };
1050   auto J = std::find_if(llvm::make_reverse_iterator(I),
1051                         llvm::make_reverse_iterator(B), IsOutputSec);
1052   I = J.base();
1053 
1054   // As a special case, if the orphan section is the last section, put
1055   // it at the very end, past any other commands.
1056   // This matches bfd's behavior and is convenient when the linker script fully
1057   // specifies the start of the file, but doesn't care about the end (the non
1058   // alloc sections for example).
1059   auto NextSec = std::find_if(I, E, IsOutputSec);
1060   if (NextSec == E)
1061     return E;
1062 
1063   while (I != E && shouldSkip(*I))
1064     ++I;
1065   return I;
1066 }
1067 
1068 // Builds section order for handling --symbol-ordering-file.
1069 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1070   DenseMap<const InputSectionBase *, int> SectionOrder;
1071   // Use the rarely used option -call-graph-ordering-file to sort sections.
1072   if (!Config->CallGraphProfile.empty())
1073     return computeCallGraphProfileOrder();
1074 
1075   if (Config->SymbolOrderingFile.empty())
1076     return SectionOrder;
1077 
1078   struct SymbolOrderEntry {
1079     int Priority;
1080     bool Present;
1081   };
1082 
1083   // Build a map from symbols to their priorities. Symbols that didn't
1084   // appear in the symbol ordering file have the lowest priority 0.
1085   // All explicitly mentioned symbols have negative (higher) priorities.
1086   DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1087   int Priority = -Config->SymbolOrderingFile.size();
1088   for (StringRef S : Config->SymbolOrderingFile)
1089     SymbolOrder.insert({S, {Priority++, false}});
1090 
1091   // Build a map from sections to their priorities.
1092   auto AddSym = [&](Symbol &Sym) {
1093     auto It = SymbolOrder.find(Sym.getName());
1094     if (It == SymbolOrder.end())
1095       return;
1096     SymbolOrderEntry &Ent = It->second;
1097     Ent.Present = true;
1098 
1099     warnUnorderableSymbol(&Sym);
1100 
1101     if (auto *D = dyn_cast<Defined>(&Sym)) {
1102       if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1103         int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1104         Priority = std::min(Priority, Ent.Priority);
1105       }
1106     }
1107   };
1108   // We want both global and local symbols. We get the global ones from the
1109   // symbol table and iterate the object files for the local ones.
1110   for (Symbol *Sym : Symtab->getSymbols())
1111     if (!Sym->isLazy())
1112       AddSym(*Sym);
1113   for (InputFile *File : ObjectFiles)
1114     for (Symbol *Sym : File->getSymbols())
1115       if (Sym->isLocal())
1116         AddSym(*Sym);
1117 
1118   if (Config->WarnSymbolOrdering)
1119     for (auto OrderEntry : SymbolOrder)
1120       if (!OrderEntry.second.Present)
1121         warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1122 
1123   return SectionOrder;
1124 }
1125 
1126 // Sorts the sections in ISD according to the provided section order.
1127 static void
1128 sortISDBySectionOrder(InputSectionDescription *ISD,
1129                       const DenseMap<const InputSectionBase *, int> &Order) {
1130   std::vector<InputSection *> UnorderedSections;
1131   std::vector<std::pair<InputSection *, int>> OrderedSections;
1132   uint64_t UnorderedSize = 0;
1133 
1134   for (InputSection *IS : ISD->Sections) {
1135     auto I = Order.find(IS);
1136     if (I == Order.end()) {
1137       UnorderedSections.push_back(IS);
1138       UnorderedSize += IS->getSize();
1139       continue;
1140     }
1141     OrderedSections.push_back({IS, I->second});
1142   }
1143   llvm::sort(
1144       OrderedSections.begin(), OrderedSections.end(),
1145       [&](std::pair<InputSection *, int> A, std::pair<InputSection *, int> B) {
1146         return A.second < B.second;
1147       });
1148 
1149   // Find an insertion point for the ordered section list in the unordered
1150   // section list. On targets with limited-range branches, this is the mid-point
1151   // of the unordered section list. This decreases the likelihood that a range
1152   // extension thunk will be needed to enter or exit the ordered region. If the
1153   // ordered section list is a list of hot functions, we can generally expect
1154   // the ordered functions to be called more often than the unordered functions,
1155   // making it more likely that any particular call will be within range, and
1156   // therefore reducing the number of thunks required.
1157   //
1158   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1159   // If the layout is:
1160   //
1161   // 8MB hot
1162   // 32MB cold
1163   //
1164   // only the first 8-16MB of the cold code (depending on which hot function it
1165   // is actually calling) can call the hot code without a range extension thunk.
1166   // However, if we use this layout:
1167   //
1168   // 16MB cold
1169   // 8MB hot
1170   // 16MB cold
1171   //
1172   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1173   // of the second block of cold code can call the hot code without a thunk. So
1174   // we effectively double the amount of code that could potentially call into
1175   // the hot code without a thunk.
1176   size_t InsPt = 0;
1177   if (Target->getThunkSectionSpacing() && !OrderedSections.empty()) {
1178     uint64_t UnorderedPos = 0;
1179     for (; InsPt != UnorderedSections.size(); ++InsPt) {
1180       UnorderedPos += UnorderedSections[InsPt]->getSize();
1181       if (UnorderedPos > UnorderedSize / 2)
1182         break;
1183     }
1184   }
1185 
1186   ISD->Sections.clear();
1187   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1188     ISD->Sections.push_back(IS);
1189   for (std::pair<InputSection *, int> P : OrderedSections)
1190     ISD->Sections.push_back(P.first);
1191   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1192     ISD->Sections.push_back(IS);
1193 }
1194 
1195 static void sortSection(OutputSection *Sec,
1196                         const DenseMap<const InputSectionBase *, int> &Order) {
1197   StringRef Name = Sec->Name;
1198 
1199   // Sort input sections by section name suffixes for
1200   // __attribute__((init_priority(N))).
1201   if (Name == ".init_array" || Name == ".fini_array") {
1202     if (!Script->HasSectionsCommand)
1203       Sec->sortInitFini();
1204     return;
1205   }
1206 
1207   // Sort input sections by the special rule for .ctors and .dtors.
1208   if (Name == ".ctors" || Name == ".dtors") {
1209     if (!Script->HasSectionsCommand)
1210       Sec->sortCtorsDtors();
1211     return;
1212   }
1213 
1214   // Never sort these.
1215   if (Name == ".init" || Name == ".fini")
1216     return;
1217 
1218   // Sort input sections by priority using the list provided
1219   // by --symbol-ordering-file.
1220   if (!Order.empty())
1221     for (BaseCommand *B : Sec->SectionCommands)
1222       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1223         sortISDBySectionOrder(ISD, Order);
1224 }
1225 
1226 // If no layout was provided by linker script, we want to apply default
1227 // sorting for special input sections. This also handles --symbol-ordering-file.
1228 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1229   // Build the order once since it is expensive.
1230   DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1231   for (BaseCommand *Base : Script->SectionCommands)
1232     if (auto *Sec = dyn_cast<OutputSection>(Base))
1233       sortSection(Sec, Order);
1234 }
1235 
1236 template <class ELFT> void Writer<ELFT>::sortSections() {
1237   Script->adjustSectionsBeforeSorting();
1238 
1239   // Don't sort if using -r. It is not necessary and we want to preserve the
1240   // relative order for SHF_LINK_ORDER sections.
1241   if (Config->Relocatable)
1242     return;
1243 
1244   sortInputSections();
1245 
1246   for (BaseCommand *Base : Script->SectionCommands) {
1247     auto *OS = dyn_cast<OutputSection>(Base);
1248     if (!OS)
1249       continue;
1250     OS->SortRank = getSectionRank(OS);
1251 
1252     // We want to assign rude approximation values to OutSecOff fields
1253     // to know the relative order of the input sections. We use it for
1254     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1255     uint64_t I = 0;
1256     for (InputSection *Sec : getInputSections(OS))
1257       Sec->OutSecOff = I++;
1258   }
1259 
1260   if (!Script->HasSectionsCommand) {
1261     // We know that all the OutputSections are contiguous in this case.
1262     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1263     std::stable_sort(
1264         llvm::find_if(Script->SectionCommands, IsSection),
1265         llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1266         compareSections);
1267     return;
1268   }
1269 
1270   // Orphan sections are sections present in the input files which are
1271   // not explicitly placed into the output file by the linker script.
1272   //
1273   // The sections in the linker script are already in the correct
1274   // order. We have to figuere out where to insert the orphan
1275   // sections.
1276   //
1277   // The order of the sections in the script is arbitrary and may not agree with
1278   // compareSections. This means that we cannot easily define a strict weak
1279   // ordering. To see why, consider a comparison of a section in the script and
1280   // one not in the script. We have a two simple options:
1281   // * Make them equivalent (a is not less than b, and b is not less than a).
1282   //   The problem is then that equivalence has to be transitive and we can
1283   //   have sections a, b and c with only b in a script and a less than c
1284   //   which breaks this property.
1285   // * Use compareSectionsNonScript. Given that the script order doesn't have
1286   //   to match, we can end up with sections a, b, c, d where b and c are in the
1287   //   script and c is compareSectionsNonScript less than b. In which case d
1288   //   can be equivalent to c, a to b and d < a. As a concrete example:
1289   //   .a (rx) # not in script
1290   //   .b (rx) # in script
1291   //   .c (ro) # in script
1292   //   .d (ro) # not in script
1293   //
1294   // The way we define an order then is:
1295   // *  Sort only the orphan sections. They are in the end right now.
1296   // *  Move each orphan section to its preferred position. We try
1297   //    to put each section in the last position where it can share
1298   //    a PT_LOAD.
1299   //
1300   // There is some ambiguity as to where exactly a new entry should be
1301   // inserted, because Commands contains not only output section
1302   // commands but also other types of commands such as symbol assignment
1303   // expressions. There's no correct answer here due to the lack of the
1304   // formal specification of the linker script. We use heuristics to
1305   // determine whether a new output command should be added before or
1306   // after another commands. For the details, look at shouldSkip
1307   // function.
1308 
1309   auto I = Script->SectionCommands.begin();
1310   auto E = Script->SectionCommands.end();
1311   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1312     if (auto *Sec = dyn_cast<OutputSection>(Base))
1313       return Sec->SectionIndex == UINT32_MAX;
1314     return false;
1315   });
1316 
1317   // Sort the orphan sections.
1318   std::stable_sort(NonScriptI, E, compareSections);
1319 
1320   // As a horrible special case, skip the first . assignment if it is before any
1321   // section. We do this because it is common to set a load address by starting
1322   // the script with ". = 0xabcd" and the expectation is that every section is
1323   // after that.
1324   auto FirstSectionOrDotAssignment =
1325       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1326   if (FirstSectionOrDotAssignment != E &&
1327       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1328     ++FirstSectionOrDotAssignment;
1329   I = FirstSectionOrDotAssignment;
1330 
1331   while (NonScriptI != E) {
1332     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1333     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1334 
1335     // As an optimization, find all sections with the same sort rank
1336     // and insert them with one rotate.
1337     unsigned Rank = Orphan->SortRank;
1338     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1339       return cast<OutputSection>(Cmd)->SortRank != Rank;
1340     });
1341     std::rotate(Pos, NonScriptI, End);
1342     NonScriptI = End;
1343   }
1344 
1345   Script->adjustSectionsAfterSorting();
1346 }
1347 
1348 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1349   // Synthetic, i. e. a sentinel section, should go last.
1350   if (A->kind() == InputSectionBase::Synthetic ||
1351       B->kind() == InputSectionBase::Synthetic)
1352     return A->kind() != InputSectionBase::Synthetic;
1353   InputSection *LA = A->getLinkOrderDep();
1354   InputSection *LB = B->getLinkOrderDep();
1355   OutputSection *AOut = LA->getParent();
1356   OutputSection *BOut = LB->getParent();
1357   if (AOut != BOut)
1358     return AOut->SectionIndex < BOut->SectionIndex;
1359   return LA->OutSecOff < LB->OutSecOff;
1360 }
1361 
1362 // This function is used by the --merge-exidx-entries to detect duplicate
1363 // .ARM.exidx sections. It is Arm only.
1364 //
1365 // The .ARM.exidx section is of the form:
1366 // | PREL31 offset to function | Unwind instructions for function |
1367 // where the unwind instructions are either a small number of unwind
1368 // instructions inlined into the table entry, the special CANT_UNWIND value of
1369 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1370 // instructions.
1371 //
1372 // We return true if all the unwind instructions in the .ARM.exidx entries of
1373 // Cur can be merged into the last entry of Prev.
1374 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1375 
1376   // References to .ARM.Extab Sections have bit 31 clear and are not the
1377   // special EXIDX_CANTUNWIND bit-pattern.
1378   auto IsExtabRef = [](uint32_t Unwind) {
1379     return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1380   };
1381 
1382   struct ExidxEntry {
1383     ulittle32_t Fn;
1384     ulittle32_t Unwind;
1385   };
1386 
1387   // Get the last table Entry from the previous .ARM.exidx section.
1388   const ExidxEntry &PrevEntry = Prev->getDataAs<ExidxEntry>().back();
1389   if (IsExtabRef(PrevEntry.Unwind))
1390     return false;
1391 
1392   // We consider the unwind instructions of an .ARM.exidx table entry
1393   // a duplicate if the previous unwind instructions if:
1394   // - Both are the special EXIDX_CANTUNWIND.
1395   // - Both are the same inline unwind instructions.
1396   // We do not attempt to follow and check links into .ARM.extab tables as
1397   // consecutive identical entries are rare and the effort to check that they
1398   // are identical is high.
1399 
1400   for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>())
1401     if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1402       return false;
1403   // All table entries in this .ARM.exidx Section can be merged into the
1404   // previous Section.
1405   return true;
1406 }
1407 
1408 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1409   for (OutputSection *Sec : OutputSections) {
1410     if (!(Sec->Flags & SHF_LINK_ORDER))
1411       continue;
1412 
1413     // Link order may be distributed across several InputSectionDescriptions
1414     // but sort must consider them all at once.
1415     std::vector<InputSection **> ScriptSections;
1416     std::vector<InputSection *> Sections;
1417     for (BaseCommand *Base : Sec->SectionCommands) {
1418       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1419         for (InputSection *&IS : ISD->Sections) {
1420           ScriptSections.push_back(&IS);
1421           Sections.push_back(IS);
1422         }
1423       }
1424     }
1425     std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1426 
1427     if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1428         Sec->Type == SHT_ARM_EXIDX) {
1429 
1430       if (auto *Sentinel = dyn_cast<ARMExidxSentinelSection>(Sections.back())) {
1431         assert(Sections.size() >= 2 &&
1432                "We should create a sentinel section only if there are "
1433                "alive regular exidx sections.");
1434         // The last executable section is required to fill the sentinel.
1435         // Remember it here so that we don't have to find it again.
1436         Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1437       }
1438 
1439       if (Config->MergeArmExidx) {
1440         // The EHABI for the Arm Architecture permits consecutive identical
1441         // table entries to be merged. We use a simple implementation that
1442         // removes a .ARM.exidx Input Section if it can be merged into the
1443         // previous one. This does not require any rewriting of InputSection
1444         // contents but misses opportunities for fine grained deduplication
1445         // where only a subset of the InputSection contents can be merged.
1446         size_t Prev = 0;
1447         // The last one is a sentinel entry which should not be removed.
1448         for (size_t I = 1; I < Sections.size() - 1; ++I) {
1449           if (isDuplicateArmExidxSec(Sections[Prev], Sections[I]))
1450             Sections[I] = nullptr;
1451           else
1452             Prev = I;
1453         }
1454       }
1455     }
1456 
1457     for (int I = 0, N = Sections.size(); I < N; ++I)
1458       *ScriptSections[I] = Sections[I];
1459 
1460     // Remove the Sections we marked as duplicate earlier.
1461     for (BaseCommand *Base : Sec->SectionCommands)
1462       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1463         llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; });
1464   }
1465 }
1466 
1467 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1468                            llvm::function_ref<void(SyntheticSection *)> Fn) {
1469   for (SyntheticSection *SS : Sections)
1470     if (SS && SS->getParent() && !SS->empty())
1471       Fn(SS);
1472 }
1473 
1474 // In order to allow users to manipulate linker-synthesized sections,
1475 // we had to add synthetic sections to the input section list early,
1476 // even before we make decisions whether they are needed. This allows
1477 // users to write scripts like this: ".mygot : { .got }".
1478 //
1479 // Doing it has an unintended side effects. If it turns out that we
1480 // don't need a .got (for example) at all because there's no
1481 // relocation that needs a .got, we don't want to emit .got.
1482 //
1483 // To deal with the above problem, this function is called after
1484 // scanRelocations is called to remove synthetic sections that turn
1485 // out to be empty.
1486 static void removeUnusedSyntheticSections() {
1487   // All input synthetic sections that can be empty are placed after
1488   // all regular ones. We iterate over them all and exit at first
1489   // non-synthetic.
1490   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1491     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1492     if (!SS)
1493       return;
1494     OutputSection *OS = SS->getParent();
1495     if (!OS || !SS->empty())
1496       continue;
1497 
1498     // If we reach here, then SS is an unused synthetic section and we want to
1499     // remove it from corresponding input section description of output section.
1500     for (BaseCommand *B : OS->SectionCommands)
1501       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1502         llvm::erase_if(ISD->Sections,
1503                        [=](InputSection *IS) { return IS == SS; });
1504   }
1505 }
1506 
1507 // Returns true if a symbol can be replaced at load-time by a symbol
1508 // with the same name defined in other ELF executable or DSO.
1509 static bool computeIsPreemptible(const Symbol &B) {
1510   assert(!B.isLocal());
1511   // Only symbols that appear in dynsym can be preempted.
1512   if (!B.includeInDynsym())
1513     return false;
1514 
1515   // Only default visibility symbols can be preempted.
1516   if (B.Visibility != STV_DEFAULT)
1517     return false;
1518 
1519   // At this point copy relocations have not been created yet, so any
1520   // symbol that is not defined locally is preemptible.
1521   if (!B.isDefined())
1522     return true;
1523 
1524   // If we have a dynamic list it specifies which local symbols are preemptible.
1525   if (Config->HasDynamicList)
1526     return false;
1527 
1528   if (!Config->Shared)
1529     return false;
1530 
1531   // -Bsymbolic means that definitions are not preempted.
1532   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1533     return false;
1534   return true;
1535 }
1536 
1537 // Create output section objects and add them to OutputSections.
1538 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1539   Out::DebugInfo = findSection(".debug_info");
1540   Out::PreinitArray = findSection(".preinit_array");
1541   Out::InitArray = findSection(".init_array");
1542   Out::FiniArray = findSection(".fini_array");
1543 
1544   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1545   // symbols for sections, so that the runtime can get the start and end
1546   // addresses of each section by section name. Add such symbols.
1547   if (!Config->Relocatable) {
1548     addStartEndSymbols();
1549     for (BaseCommand *Base : Script->SectionCommands)
1550       if (auto *Sec = dyn_cast<OutputSection>(Base))
1551         addStartStopSymbols(Sec);
1552   }
1553 
1554   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1555   // It should be okay as no one seems to care about the type.
1556   // Even the author of gold doesn't remember why gold behaves that way.
1557   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1558   if (InX::DynSymTab)
1559     Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1560                        /*Size=*/0, STB_WEAK, InX::Dynamic,
1561                        /*File=*/nullptr);
1562 
1563   // Define __rel[a]_iplt_{start,end} symbols if needed.
1564   addRelIpltSymbols();
1565 
1566   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1567   if (Config->EMachine == EM_RISCV) {
1568     ElfSym::RISCVGlobalPointer =
1569         dyn_cast_or_null<Defined>(Symtab->find("__global_pointer$"));
1570     if (!ElfSym::RISCVGlobalPointer)
1571       ElfSym::RISCVGlobalPointer =
1572           addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800);
1573   }
1574 
1575   // This responsible for splitting up .eh_frame section into
1576   // pieces. The relocation scan uses those pieces, so this has to be
1577   // earlier.
1578   applySynthetic({InX::EhFrame},
1579                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1580 
1581   for (Symbol *S : Symtab->getSymbols())
1582     S->IsPreemptible |= computeIsPreemptible(*S);
1583 
1584   // Scan relocations. This must be done after every symbol is declared so that
1585   // we can correctly decide if a dynamic relocation is needed.
1586   if (!Config->Relocatable)
1587     forEachRelSec(scanRelocations<ELFT>);
1588 
1589   if (InX::Plt && !InX::Plt->empty())
1590     InX::Plt->addSymbols();
1591   if (InX::Iplt && !InX::Iplt->empty())
1592     InX::Iplt->addSymbols();
1593 
1594   // Now that we have defined all possible global symbols including linker-
1595   // synthesized ones. Visit all symbols to give the finishing touches.
1596   for (Symbol *Sym : Symtab->getSymbols()) {
1597     if (!includeInSymtab(*Sym))
1598       continue;
1599     if (InX::SymTab)
1600       InX::SymTab->addSymbol(Sym);
1601 
1602     if (InX::DynSymTab && Sym->includeInDynsym()) {
1603       InX::DynSymTab->addSymbol(Sym);
1604       if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1605         if (File->IsNeeded && !Sym->isUndefined())
1606           In<ELFT>::VerNeed->addSymbol(Sym);
1607     }
1608   }
1609 
1610   // Do not proceed if there was an undefined symbol.
1611   if (errorCount())
1612     return;
1613 
1614   if (InX::MipsGot)
1615     InX::MipsGot->build<ELFT>();
1616 
1617   removeUnusedSyntheticSections();
1618 
1619   sortSections();
1620 
1621   // Now that we have the final list, create a list of all the
1622   // OutputSections for convenience.
1623   for (BaseCommand *Base : Script->SectionCommands)
1624     if (auto *Sec = dyn_cast<OutputSection>(Base))
1625       OutputSections.push_back(Sec);
1626 
1627   // Ensure data sections are not mixed with executable sections when
1628   // -execute-only is used.
1629   if (Config->ExecuteOnly)
1630     for (OutputSection *OS : OutputSections)
1631       if (OS->Flags & SHF_EXECINSTR)
1632         for (InputSection *IS : getInputSections(OS))
1633           if (!(IS->Flags & SHF_EXECINSTR))
1634             error("-execute-only does not support intermingling data and code");
1635 
1636   // Prefer command line supplied address over other constraints.
1637   for (OutputSection *Sec : OutputSections) {
1638     auto I = Config->SectionStartMap.find(Sec->Name);
1639     if (I != Config->SectionStartMap.end())
1640       Sec->AddrExpr = [=] { return I->second; };
1641   }
1642 
1643   // This is a bit of a hack. A value of 0 means undef, so we set it
1644   // to 1 to make __ehdr_start defined. The section number is not
1645   // particularly relevant.
1646   Out::ElfHeader->SectionIndex = 1;
1647 
1648   unsigned I = 1;
1649   for (OutputSection *Sec : OutputSections) {
1650     Sec->SectionIndex = I++;
1651     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1652   }
1653 
1654   // Binary and relocatable output does not have PHDRS.
1655   // The headers have to be created before finalize as that can influence the
1656   // image base and the dynamic section on mips includes the image base.
1657   if (!Config->Relocatable && !Config->OFormatBinary) {
1658     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1659     addPtArmExid(Phdrs);
1660     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1661   }
1662 
1663   // Some symbols are defined in term of program headers. Now that we
1664   // have the headers, we can find out which sections they point to.
1665   setReservedSymbolSections();
1666 
1667   // Dynamic section must be the last one in this list and dynamic
1668   // symbol table section (DynSymTab) must be the first one.
1669   applySynthetic(
1670       {InX::DynSymTab,   InX::Bss,         InX::BssRelRo,     InX::GnuHashTab,
1671        InX::HashTab,     InX::SymTabShndx, InX::ShStrTab,     InX::StrTab,
1672        In<ELFT>::VerDef, InX::DynStrTab,   InX::Got,          InX::MipsGot,
1673        InX::IgotPlt,     InX::GotPlt,      InX::RelaDyn,      InX::RelrDyn,
1674        InX::RelaIplt,    InX::RelaPlt,     InX::Plt,          InX::Iplt,
1675        InX::EhFrameHdr,  In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1676       [](SyntheticSection *SS) { SS->finalizeContents(); });
1677 
1678   if (!Script->HasSectionsCommand && !Config->Relocatable)
1679     fixSectionAlignments();
1680 
1681   // After link order processing .ARM.exidx sections can be deduplicated, which
1682   // needs to be resolved before any other address dependent operation.
1683   resolveShfLinkOrder();
1684 
1685   // Some architectures need to generate content that depends on the address
1686   // of InputSections. For example some architectures use small displacements
1687   // for jump instructions that is the linker's responsibility for creating
1688   // range extension thunks for. As the generation of the content may also
1689   // alter InputSection addresses we must converge to a fixed point.
1690   if (Target->NeedsThunks || Config->AndroidPackDynRelocs ||
1691       Config->RelrPackDynRelocs) {
1692     ThunkCreator TC;
1693     AArch64Err843419Patcher A64P;
1694     bool Changed;
1695     do {
1696       Script->assignAddresses();
1697       Changed = false;
1698       if (Target->NeedsThunks)
1699         Changed |= TC.createThunks(OutputSections);
1700       if (Config->FixCortexA53Errata843419) {
1701         if (Changed)
1702           Script->assignAddresses();
1703         Changed |= A64P.createFixes();
1704       }
1705       if (InX::MipsGot)
1706         InX::MipsGot->updateAllocSize();
1707       Changed |= InX::RelaDyn->updateAllocSize();
1708       if (InX::RelrDyn)
1709         Changed |= InX::RelrDyn->updateAllocSize();
1710     } while (Changed);
1711   }
1712 
1713   // createThunks may have added local symbols to the static symbol table
1714   applySynthetic({InX::SymTab},
1715                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1716 
1717   // Fill other section headers. The dynamic table is finalized
1718   // at the end because some tags like RELSZ depend on result
1719   // of finalizing other sections.
1720   for (OutputSection *Sec : OutputSections)
1721     Sec->finalize<ELFT>();
1722 }
1723 
1724 // The linker is expected to define SECNAME_start and SECNAME_end
1725 // symbols for a few sections. This function defines them.
1726 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1727   // If a section does not exist, there's ambiguity as to how we
1728   // define _start and _end symbols for an init/fini section. Since
1729   // the loader assume that the symbols are always defined, we need to
1730   // always define them. But what value? The loader iterates over all
1731   // pointers between _start and _end to run global ctors/dtors, so if
1732   // the section is empty, their symbol values don't actually matter
1733   // as long as _start and _end point to the same location.
1734   //
1735   // That said, we don't want to set the symbols to 0 (which is
1736   // probably the simplest value) because that could cause some
1737   // program to fail to link due to relocation overflow, if their
1738   // program text is above 2 GiB. We use the address of the .text
1739   // section instead to prevent that failure.
1740   OutputSection *Default = findSection(".text");
1741   if (!Default)
1742     Default = Out::ElfHeader;
1743   auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1744     if (OS) {
1745       addOptionalRegular(Start, OS, 0);
1746       addOptionalRegular(End, OS, -1);
1747     } else {
1748       addOptionalRegular(Start, Default, 0);
1749       addOptionalRegular(End, Default, 0);
1750     }
1751   };
1752 
1753   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1754   Define("__init_array_start", "__init_array_end", Out::InitArray);
1755   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1756 
1757   if (OutputSection *Sec = findSection(".ARM.exidx"))
1758     Define("__exidx_start", "__exidx_end", Sec);
1759 }
1760 
1761 // If a section name is valid as a C identifier (which is rare because of
1762 // the leading '.'), linkers are expected to define __start_<secname> and
1763 // __stop_<secname> symbols. They are at beginning and end of the section,
1764 // respectively. This is not requested by the ELF standard, but GNU ld and
1765 // gold provide the feature, and used by many programs.
1766 template <class ELFT>
1767 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1768   StringRef S = Sec->Name;
1769   if (!isValidCIdentifier(S))
1770     return;
1771   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1772   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1773 }
1774 
1775 static bool needsPtLoad(OutputSection *Sec) {
1776   if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1777     return false;
1778 
1779   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1780   // responsible for allocating space for them, not the PT_LOAD that
1781   // contains the TLS initialization image.
1782   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1783     return false;
1784   return true;
1785 }
1786 
1787 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1788 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1789 // RW. This means that there is no alignment in the RO to RX transition and we
1790 // cannot create a PT_LOAD there.
1791 static uint64_t computeFlags(uint64_t Flags) {
1792   if (Config->Omagic)
1793     return PF_R | PF_W | PF_X;
1794   if (Config->ExecuteOnly && (Flags & PF_X))
1795     return Flags & ~PF_R;
1796   if (Config->SingleRoRx && !(Flags & PF_W))
1797     return Flags | PF_X;
1798   return Flags;
1799 }
1800 
1801 // Decide which program headers to create and which sections to include in each
1802 // one.
1803 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1804   std::vector<PhdrEntry *> Ret;
1805   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1806     Ret.push_back(make<PhdrEntry>(Type, Flags));
1807     return Ret.back();
1808   };
1809 
1810   // The first phdr entry is PT_PHDR which describes the program header itself.
1811   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1812 
1813   // PT_INTERP must be the second entry if exists.
1814   if (OutputSection *Cmd = findSection(".interp"))
1815     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1816 
1817   // Add the first PT_LOAD segment for regular output sections.
1818   uint64_t Flags = computeFlags(PF_R);
1819   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1820 
1821   // Add the headers. We will remove them if they don't fit.
1822   Load->add(Out::ElfHeader);
1823   Load->add(Out::ProgramHeaders);
1824 
1825   for (OutputSection *Sec : OutputSections) {
1826     if (!(Sec->Flags & SHF_ALLOC))
1827       break;
1828     if (!needsPtLoad(Sec))
1829       continue;
1830 
1831     // Segments are contiguous memory regions that has the same attributes
1832     // (e.g. executable or writable). There is one phdr for each segment.
1833     // Therefore, we need to create a new phdr when the next section has
1834     // different flags or is loaded at a discontiguous address or memory
1835     // region using AT or AT> linker script command, respectively. At the same
1836     // time, we don't want to create a separate load segment for the headers,
1837     // even if the first output section has an AT or AT> attribute.
1838     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1839     if (((Sec->LMAExpr ||
1840           (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) &&
1841          Load->LastSec != Out::ProgramHeaders) ||
1842         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1843 
1844       Load = AddHdr(PT_LOAD, NewFlags);
1845       Flags = NewFlags;
1846     }
1847 
1848     Load->add(Sec);
1849   }
1850 
1851   // Add a TLS segment if any.
1852   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1853   for (OutputSection *Sec : OutputSections)
1854     if (Sec->Flags & SHF_TLS)
1855       TlsHdr->add(Sec);
1856   if (TlsHdr->FirstSec)
1857     Ret.push_back(TlsHdr);
1858 
1859   // Add an entry for .dynamic.
1860   if (InX::DynSymTab)
1861     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1862         ->add(InX::Dynamic->getParent());
1863 
1864   // PT_GNU_RELRO includes all sections that should be marked as
1865   // read-only by dynamic linker after proccessing relocations.
1866   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1867   // an error message if more than one PT_GNU_RELRO PHDR is required.
1868   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1869   bool InRelroPhdr = false;
1870   bool IsRelroFinished = false;
1871   for (OutputSection *Sec : OutputSections) {
1872     if (!needsPtLoad(Sec))
1873       continue;
1874     if (isRelroSection(Sec)) {
1875       InRelroPhdr = true;
1876       if (!IsRelroFinished)
1877         RelRo->add(Sec);
1878       else
1879         error("section: " + Sec->Name + " is not contiguous with other relro" +
1880               " sections");
1881     } else if (InRelroPhdr) {
1882       InRelroPhdr = false;
1883       IsRelroFinished = true;
1884     }
1885   }
1886   if (RelRo->FirstSec)
1887     Ret.push_back(RelRo);
1888 
1889   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1890   if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() &&
1891       InX::EhFrameHdr->getParent())
1892     AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags())
1893         ->add(InX::EhFrameHdr->getParent());
1894 
1895   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1896   // the dynamic linker fill the segment with random data.
1897   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1898     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1899 
1900   // PT_GNU_STACK is a special section to tell the loader to make the
1901   // pages for the stack non-executable. If you really want an executable
1902   // stack, you can pass -z execstack, but that's not recommended for
1903   // security reasons.
1904   unsigned Perm = PF_R | PF_W;
1905   if (Config->ZExecstack)
1906     Perm |= PF_X;
1907   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1908 
1909   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1910   // is expected to perform W^X violations, such as calling mprotect(2) or
1911   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1912   // OpenBSD.
1913   if (Config->ZWxneeded)
1914     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1915 
1916   // Create one PT_NOTE per a group of contiguous .note sections.
1917   PhdrEntry *Note = nullptr;
1918   for (OutputSection *Sec : OutputSections) {
1919     if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
1920       if (!Note || Sec->LMAExpr)
1921         Note = AddHdr(PT_NOTE, PF_R);
1922       Note->add(Sec);
1923     } else {
1924       Note = nullptr;
1925     }
1926   }
1927   return Ret;
1928 }
1929 
1930 template <class ELFT>
1931 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
1932   if (Config->EMachine != EM_ARM)
1933     return;
1934   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
1935     return Cmd->Type == SHT_ARM_EXIDX;
1936   });
1937   if (I == OutputSections.end())
1938     return;
1939 
1940   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1941   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
1942   ARMExidx->add(*I);
1943   Phdrs.push_back(ARMExidx);
1944 }
1945 
1946 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1947 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1948 // linker can set the permissions.
1949 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1950   auto PageAlign = [](OutputSection *Cmd) {
1951     if (Cmd && !Cmd->AddrExpr)
1952       Cmd->AddrExpr = [=] {
1953         return alignTo(Script->getDot(), Config->MaxPageSize);
1954       };
1955   };
1956 
1957   for (const PhdrEntry *P : Phdrs)
1958     if (P->p_type == PT_LOAD && P->FirstSec)
1959       PageAlign(P->FirstSec);
1960 
1961   for (const PhdrEntry *P : Phdrs) {
1962     if (P->p_type != PT_GNU_RELRO)
1963       continue;
1964     if (P->FirstSec)
1965       PageAlign(P->FirstSec);
1966     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1967     // have to align it to a page.
1968     auto End = OutputSections.end();
1969     auto I = std::find(OutputSections.begin(), End, P->LastSec);
1970     if (I == End || (I + 1) == End)
1971       continue;
1972     OutputSection *Cmd = (*(I + 1));
1973     if (needsPtLoad(Cmd))
1974       PageAlign(Cmd);
1975   }
1976 }
1977 
1978 // Adjusts the file alignment for a given output section and returns
1979 // its new file offset. The file offset must be the same with its
1980 // virtual address (modulo the page size) so that the loader can load
1981 // executables without any address adjustment.
1982 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) {
1983   OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr;
1984   // The first section in a PT_LOAD has to have congruent offset and address
1985   // module the page size.
1986   if (Cmd == First)
1987     return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize),
1988                    Cmd->Addr);
1989 
1990   // For SHT_NOBITS we don't want the alignment of the section to impact the
1991   // offset of the sections that follow. Since nothing seems to care about the
1992   // sh_offset of the SHT_NOBITS section itself, just ignore it.
1993   if (Cmd->Type == SHT_NOBITS)
1994     return Off;
1995 
1996   // If the section is not in a PT_LOAD, we just have to align it.
1997   if (!Cmd->PtLoad)
1998     return alignTo(Off, Cmd->Alignment);
1999 
2000   // If two sections share the same PT_LOAD the file offset is calculated
2001   // using this formula: Off2 = Off1 + (VA2 - VA1).
2002   return First->Offset + Cmd->Addr - First->Addr;
2003 }
2004 
2005 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) {
2006   Off = getFileAlignment(Off, Cmd);
2007   Cmd->Offset = Off;
2008 
2009   // For SHT_NOBITS we should not count the size.
2010   if (Cmd->Type == SHT_NOBITS)
2011     return Off;
2012 
2013   return Off + Cmd->Size;
2014 }
2015 
2016 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2017   uint64_t Off = 0;
2018   for (OutputSection *Sec : OutputSections)
2019     if (Sec->Flags & SHF_ALLOC)
2020       Off = setOffset(Sec, Off);
2021   FileSize = alignTo(Off, Config->Wordsize);
2022 }
2023 
2024 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
2025   return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
2026 }
2027 
2028 // Assign file offsets to output sections.
2029 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2030   uint64_t Off = 0;
2031   Off = setOffset(Out::ElfHeader, Off);
2032   Off = setOffset(Out::ProgramHeaders, Off);
2033 
2034   PhdrEntry *LastRX = nullptr;
2035   for (PhdrEntry *P : Phdrs)
2036     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2037       LastRX = P;
2038 
2039   for (OutputSection *Sec : OutputSections) {
2040     Off = setOffset(Sec, Off);
2041     if (Script->HasSectionsCommand)
2042       continue;
2043     // If this is a last section of the last executable segment and that
2044     // segment is the last loadable segment, align the offset of the
2045     // following section to avoid loading non-segments parts of the file.
2046     if (LastRX && LastRX->LastSec == Sec)
2047       Off = alignTo(Off, Target->PageSize);
2048   }
2049 
2050   SectionHeaderOff = alignTo(Off, Config->Wordsize);
2051   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2052 
2053   // Our logic assumes that sections have rising VA within the same segment.
2054   // With use of linker scripts it is possible to violate this rule and get file
2055   // offset overlaps or overflows. That should never happen with a valid script
2056   // which does not move the location counter backwards and usually scripts do
2057   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2058   // kernel, which control segment distribution explicitly and move the counter
2059   // backwards, so we have to allow doing that to support linking them. We
2060   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2061   // we want to prevent file size overflows because it would crash the linker.
2062   for (OutputSection *Sec : OutputSections) {
2063     if (Sec->Type == SHT_NOBITS)
2064       continue;
2065     if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2066       error("unable to place section " + Sec->Name + " at file offset " +
2067             rangeToString(Sec->Offset, Sec->Size) +
2068             "; check your linker script for overflows");
2069   }
2070 }
2071 
2072 // Finalize the program headers. We call this function after we assign
2073 // file offsets and VAs to all sections.
2074 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2075   for (PhdrEntry *P : Phdrs) {
2076     OutputSection *First = P->FirstSec;
2077     OutputSection *Last = P->LastSec;
2078     if (First) {
2079       P->p_filesz = Last->Offset - First->Offset;
2080       if (Last->Type != SHT_NOBITS)
2081         P->p_filesz += Last->Size;
2082       P->p_memsz = Last->Addr + Last->Size - First->Addr;
2083       P->p_offset = First->Offset;
2084       P->p_vaddr = First->Addr;
2085       if (!P->HasLMA)
2086         P->p_paddr = First->getLMA();
2087     }
2088     if (P->p_type == PT_LOAD)
2089       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2090     else if (P->p_type == PT_GNU_RELRO) {
2091       P->p_align = 1;
2092       // The glibc dynamic loader rounds the size down, so we need to round up
2093       // to protect the last page. This is a no-op on FreeBSD which always
2094       // rounds up.
2095       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2096     }
2097 
2098     // The TLS pointer goes after PT_TLS. At least glibc will align it,
2099     // so round up the size to make sure the offsets are correct.
2100     if (P->p_type == PT_TLS) {
2101       Out::TlsPhdr = P;
2102       if (P->p_memsz)
2103         P->p_memsz = alignTo(P->p_memsz, P->p_align);
2104     }
2105   }
2106 }
2107 
2108 // A helper struct for checkSectionOverlap.
2109 namespace {
2110 struct SectionOffset {
2111   OutputSection *Sec;
2112   uint64_t Offset;
2113 };
2114 } // namespace
2115 
2116 // Check whether sections overlap for a specific address range (file offsets,
2117 // load and virtual adresses).
2118 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2119                          bool IsVirtualAddr) {
2120   llvm::sort(Sections.begin(), Sections.end(),
2121              [=](const SectionOffset &A, const SectionOffset &B) {
2122                return A.Offset < B.Offset;
2123              });
2124 
2125   // Finding overlap is easy given a vector is sorted by start position.
2126   // If an element starts before the end of the previous element, they overlap.
2127   for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2128     SectionOffset A = Sections[I - 1];
2129     SectionOffset B = Sections[I];
2130     if (B.Offset >= A.Offset + A.Sec->Size)
2131       continue;
2132 
2133     // If both sections are in OVERLAY we allow the overlapping of virtual
2134     // addresses, because it is what OVERLAY was designed for.
2135     if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2136       continue;
2137 
2138     errorOrWarn("section " + A.Sec->Name + " " + Name +
2139                 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2140                 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2141                 B.Sec->Name + " range is " +
2142                 rangeToString(B.Offset, B.Sec->Size));
2143   }
2144 }
2145 
2146 // Check for overlapping sections and address overflows.
2147 //
2148 // In this function we check that none of the output sections have overlapping
2149 // file offsets. For SHF_ALLOC sections we also check that the load address
2150 // ranges and the virtual address ranges don't overlap
2151 template <class ELFT> void Writer<ELFT>::checkSections() {
2152   // First, check that section's VAs fit in available address space for target.
2153   for (OutputSection *OS : OutputSections)
2154     if ((OS->Addr + OS->Size < OS->Addr) ||
2155         (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2156       errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2157                   " of size 0x" + utohexstr(OS->Size) +
2158                   " exceeds available address space");
2159 
2160   // Check for overlapping file offsets. In this case we need to skip any
2161   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2162   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2163   // binary is specified only add SHF_ALLOC sections are added to the output
2164   // file so we skip any non-allocated sections in that case.
2165   std::vector<SectionOffset> FileOffs;
2166   for (OutputSection *Sec : OutputSections)
2167     if (Sec->Size > 0 && Sec->Type != SHT_NOBITS &&
2168         (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2169       FileOffs.push_back({Sec, Sec->Offset});
2170   checkOverlap("file", FileOffs, false);
2171 
2172   // When linking with -r there is no need to check for overlapping virtual/load
2173   // addresses since those addresses will only be assigned when the final
2174   // executable/shared object is created.
2175   if (Config->Relocatable)
2176     return;
2177 
2178   // Checking for overlapping virtual and load addresses only needs to take
2179   // into account SHF_ALLOC sections since others will not be loaded.
2180   // Furthermore, we also need to skip SHF_TLS sections since these will be
2181   // mapped to other addresses at runtime and can therefore have overlapping
2182   // ranges in the file.
2183   std::vector<SectionOffset> VMAs;
2184   for (OutputSection *Sec : OutputSections)
2185     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2186       VMAs.push_back({Sec, Sec->Addr});
2187   checkOverlap("virtual address", VMAs, true);
2188 
2189   // Finally, check that the load addresses don't overlap. This will usually be
2190   // the same as the virtual addresses but can be different when using a linker
2191   // script with AT().
2192   std::vector<SectionOffset> LMAs;
2193   for (OutputSection *Sec : OutputSections)
2194     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2195       LMAs.push_back({Sec, Sec->getLMA()});
2196   checkOverlap("load address", LMAs, false);
2197 }
2198 
2199 // The entry point address is chosen in the following ways.
2200 //
2201 // 1. the '-e' entry command-line option;
2202 // 2. the ENTRY(symbol) command in a linker control script;
2203 // 3. the value of the symbol _start, if present;
2204 // 4. the number represented by the entry symbol, if it is a number;
2205 // 5. the address of the first byte of the .text section, if present;
2206 // 6. the address 0.
2207 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
2208   // Case 1, 2 or 3
2209   if (Symbol *B = Symtab->find(Config->Entry))
2210     return B->getVA();
2211 
2212   // Case 4
2213   uint64_t Addr;
2214   if (to_integer(Config->Entry, Addr))
2215     return Addr;
2216 
2217   // Case 5
2218   if (OutputSection *Sec = findSection(".text")) {
2219     if (Config->WarnMissingEntry)
2220       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2221            utohexstr(Sec->Addr));
2222     return Sec->Addr;
2223   }
2224 
2225   // Case 6
2226   if (Config->WarnMissingEntry)
2227     warn("cannot find entry symbol " + Config->Entry +
2228          "; not setting start address");
2229   return 0;
2230 }
2231 
2232 static uint16_t getELFType() {
2233   if (Config->Pic)
2234     return ET_DYN;
2235   if (Config->Relocatable)
2236     return ET_REL;
2237   return ET_EXEC;
2238 }
2239 
2240 static uint8_t getAbiVersion() {
2241   // MIPS non-PIC executable gets ABI version 1.
2242   if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2243       (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2244     return 1;
2245   return 0;
2246 }
2247 
2248 template <class ELFT> void Writer<ELFT>::writeHeader() {
2249   uint8_t *Buf = Buffer->getBufferStart();
2250   // For executable segments, the trap instructions are written before writing
2251   // the header. Setting Elf header bytes to zero ensures that any unused bytes
2252   // in header are zero-cleared, instead of having trap instructions.
2253   memset(Buf, 0, sizeof(Elf_Ehdr));
2254   memcpy(Buf, "\177ELF", 4);
2255 
2256   // Write the ELF header.
2257   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2258   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2259   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2260   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2261   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2262   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2263   EHdr->e_type = getELFType();
2264   EHdr->e_machine = Config->EMachine;
2265   EHdr->e_version = EV_CURRENT;
2266   EHdr->e_entry = getEntryAddr();
2267   EHdr->e_shoff = SectionHeaderOff;
2268   EHdr->e_flags = Config->EFlags;
2269   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2270   EHdr->e_phnum = Phdrs.size();
2271   EHdr->e_shentsize = sizeof(Elf_Shdr);
2272 
2273   if (!Config->Relocatable) {
2274     EHdr->e_phoff = sizeof(Elf_Ehdr);
2275     EHdr->e_phentsize = sizeof(Elf_Phdr);
2276   }
2277 
2278   // Write the program header table.
2279   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2280   for (PhdrEntry *P : Phdrs) {
2281     HBuf->p_type = P->p_type;
2282     HBuf->p_flags = P->p_flags;
2283     HBuf->p_offset = P->p_offset;
2284     HBuf->p_vaddr = P->p_vaddr;
2285     HBuf->p_paddr = P->p_paddr;
2286     HBuf->p_filesz = P->p_filesz;
2287     HBuf->p_memsz = P->p_memsz;
2288     HBuf->p_align = P->p_align;
2289     ++HBuf;
2290   }
2291 
2292   // Write the section header table.
2293   //
2294   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2295   // and e_shstrndx fields. When the value of one of these fields exceeds
2296   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2297   // use fields in the section header at index 0 to store
2298   // the value. The sentinel values and fields are:
2299   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2300   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2301   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2302   size_t Num = OutputSections.size() + 1;
2303   if (Num >= SHN_LORESERVE)
2304     SHdrs->sh_size = Num;
2305   else
2306     EHdr->e_shnum = Num;
2307 
2308   uint32_t StrTabIndex = InX::ShStrTab->getParent()->SectionIndex;
2309   if (StrTabIndex >= SHN_LORESERVE) {
2310     SHdrs->sh_link = StrTabIndex;
2311     EHdr->e_shstrndx = SHN_XINDEX;
2312   } else {
2313     EHdr->e_shstrndx = StrTabIndex;
2314   }
2315 
2316   for (OutputSection *Sec : OutputSections)
2317     Sec->writeHeaderTo<ELFT>(++SHdrs);
2318 }
2319 
2320 // Open a result file.
2321 template <class ELFT> void Writer<ELFT>::openFile() {
2322   if (!Config->Is64 && FileSize > UINT32_MAX) {
2323     error("output file too large: " + Twine(FileSize) + " bytes");
2324     return;
2325   }
2326 
2327   unlinkAsync(Config->OutputFile);
2328   unsigned Flags = 0;
2329   if (!Config->Relocatable)
2330     Flags = FileOutputBuffer::F_executable;
2331   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2332       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2333 
2334   if (!BufferOrErr)
2335     error("failed to open " + Config->OutputFile + ": " +
2336           llvm::toString(BufferOrErr.takeError()));
2337   else
2338     Buffer = std::move(*BufferOrErr);
2339 }
2340 
2341 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2342   uint8_t *Buf = Buffer->getBufferStart();
2343   for (OutputSection *Sec : OutputSections)
2344     if (Sec->Flags & SHF_ALLOC)
2345       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2346 }
2347 
2348 static void fillTrap(uint8_t *I, uint8_t *End) {
2349   for (; I + 4 <= End; I += 4)
2350     memcpy(I, &Target->TrapInstr, 4);
2351 }
2352 
2353 // Fill the last page of executable segments with trap instructions
2354 // instead of leaving them as zero. Even though it is not required by any
2355 // standard, it is in general a good thing to do for security reasons.
2356 //
2357 // We'll leave other pages in segments as-is because the rest will be
2358 // overwritten by output sections.
2359 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2360   if (Script->HasSectionsCommand)
2361     return;
2362 
2363   // Fill the last page.
2364   uint8_t *Buf = Buffer->getBufferStart();
2365   for (PhdrEntry *P : Phdrs)
2366     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2367       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2368                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2369 
2370   // Round up the file size of the last segment to the page boundary iff it is
2371   // an executable segment to ensure that other tools don't accidentally
2372   // trim the instruction padding (e.g. when stripping the file).
2373   PhdrEntry *Last = nullptr;
2374   for (PhdrEntry *P : Phdrs)
2375     if (P->p_type == PT_LOAD)
2376       Last = P;
2377 
2378   if (Last && (Last->p_flags & PF_X))
2379     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2380 }
2381 
2382 // Write section contents to a mmap'ed file.
2383 template <class ELFT> void Writer<ELFT>::writeSections() {
2384   uint8_t *Buf = Buffer->getBufferStart();
2385 
2386   OutputSection *EhFrameHdr = nullptr;
2387   if (InX::EhFrameHdr && !InX::EhFrameHdr->empty())
2388     EhFrameHdr = InX::EhFrameHdr->getParent();
2389 
2390   // In -r or -emit-relocs mode, write the relocation sections first as in
2391   // ELf_Rel targets we might find out that we need to modify the relocated
2392   // section while doing it.
2393   for (OutputSection *Sec : OutputSections)
2394     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2395       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2396 
2397   for (OutputSection *Sec : OutputSections)
2398     if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2399       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2400 
2401   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2402   // it should be written after .eh_frame is written.
2403   if (EhFrameHdr)
2404     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2405 }
2406 
2407 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2408   if (!InX::BuildId || !InX::BuildId->getParent())
2409     return;
2410 
2411   // Compute a hash of all sections of the output file.
2412   uint8_t *Start = Buffer->getBufferStart();
2413   uint8_t *End = Start + FileSize;
2414   InX::BuildId->writeBuildId({Start, End});
2415 }
2416 
2417 template void elf::writeResult<ELF32LE>();
2418 template void elf::writeResult<ELF32BE>();
2419 template void elf::writeResult<ELF64LE>();
2420 template void elf::writeResult<ELF64BE>();
2421