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