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