xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision f489e2bf)
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 << 13,
701   RF_EXEC = 1 << 12,
702   RF_NON_TLS_BSS = 1 << 11,
703   RF_NON_TLS_BSS_RO = 1 << 10,
704   RF_NOT_TLS = 1 << 9,
705   RF_BSS = 1 << 8,
706   RF_NOTE = 1 << 7,
707   RF_PPC_NOT_TOCBSS = 1 << 6,
708   RF_PPC_TOCL = 1 << 4,
709   RF_PPC_TOC = 1 << 3,
710   RF_PPC_BRANCH_LT = 1 << 2,
711   RF_MIPS_GPREL = 1 << 1,
712   RF_MIPS_NOT_GOT = 1 << 0
713 };
714 
715 static unsigned getSectionRank(const OutputSection *Sec) {
716   unsigned Rank = 0;
717 
718   // We want to put section specified by -T option first, so we
719   // can start assigning VA starting from them later.
720   if (Config->SectionStartMap.count(Sec->Name))
721     return Rank;
722   Rank |= RF_NOT_ADDR_SET;
723 
724   // Put .interp first because some loaders want to see that section
725   // on the first page of the executable file when loaded into memory.
726   if (Sec->Name == ".interp")
727     return Rank;
728   Rank |= RF_NOT_INTERP;
729 
730   // Allocatable sections go first to reduce the total PT_LOAD size and
731   // so debug info doesn't change addresses in actual code.
732   if (!(Sec->Flags & SHF_ALLOC))
733     return Rank | RF_NOT_ALLOC;
734 
735   // Sort sections based on their access permission in the following
736   // order: R, RX, RWX, RW.  This order is based on the following
737   // considerations:
738   // * Read-only sections come first such that they go in the
739   //   PT_LOAD covering the program headers at the start of the file.
740   // * Read-only, executable sections come next, unless the
741   //   -no-rosegment option is used.
742   // * Writable, executable sections follow such that .plt on
743   //   architectures where it needs to be writable will be placed
744   //   between .text and .data.
745   // * Writable sections come last, such that .bss lands at the very
746   //   end of the last PT_LOAD.
747   bool IsExec = Sec->Flags & SHF_EXECINSTR;
748   bool IsWrite = Sec->Flags & SHF_WRITE;
749 
750   if (IsExec) {
751     if (IsWrite)
752       Rank |= RF_EXEC_WRITE;
753     else if (!Config->SingleRoRx)
754       Rank |= RF_EXEC;
755   } else {
756     if (IsWrite)
757       Rank |= RF_WRITE;
758   }
759 
760   // If we got here we know that both A and B are in the same PT_LOAD.
761 
762   bool IsTls = Sec->Flags & SHF_TLS;
763   bool IsNoBits = Sec->Type == SHT_NOBITS;
764 
765   // The first requirement we have is to put (non-TLS) nobits sections last. The
766   // reason is that the only thing the dynamic linker will see about them is a
767   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
768   // PT_LOAD, so that has to correspond to the nobits sections.
769   bool IsNonTlsNoBits = IsNoBits && !IsTls;
770   if (IsNonTlsNoBits)
771     Rank |= RF_NON_TLS_BSS;
772 
773   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
774   // sections after r/w ones, so that the RelRo sections are contiguous.
775   bool IsRelRo = isRelroSection(Sec);
776   if (IsNonTlsNoBits && !IsRelRo)
777     Rank |= RF_NON_TLS_BSS_RO;
778   if (!IsNonTlsNoBits && IsRelRo)
779     Rank |= RF_NON_TLS_BSS_RO;
780 
781   // The TLS initialization block needs to be a single contiguous block in a R/W
782   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
783   // sections. The TLS NOBITS sections are placed here as they don't take up
784   // virtual address space in the PT_LOAD.
785   if (!IsTls)
786     Rank |= RF_NOT_TLS;
787 
788   // Within the TLS initialization block, the non-nobits sections need to appear
789   // first.
790   if (IsNoBits)
791     Rank |= RF_BSS;
792 
793   // We create a NOTE segment for contiguous .note sections, so make
794   // them contigous if there are more than one .note section with the
795   // same attributes.
796   if (Sec->Type == SHT_NOTE)
797     Rank |= RF_NOTE;
798 
799   // Some architectures have additional ordering restrictions for sections
800   // within the same PT_LOAD.
801   if (Config->EMachine == EM_PPC64) {
802     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
803     // that we would like to make sure appear is a specific order to maximize
804     // their coverage by a single signed 16-bit offset from the TOC base
805     // pointer. Conversely, the special .tocbss section should be first among
806     // all SHT_NOBITS sections. This will put it next to the loaded special
807     // PPC64 sections (and, thus, within reach of the TOC base pointer).
808     StringRef Name = Sec->Name;
809     if (Name != ".tocbss")
810       Rank |= RF_PPC_NOT_TOCBSS;
811 
812     if (Name == ".toc1")
813       Rank |= RF_PPC_TOCL;
814 
815     if (Name == ".toc")
816       Rank |= RF_PPC_TOC;
817 
818     if (Name == ".branch_lt")
819       Rank |= RF_PPC_BRANCH_LT;
820   }
821 
822   if (Config->EMachine == EM_MIPS) {
823     // All sections with SHF_MIPS_GPREL flag should be grouped together
824     // because data in these sections is addressable with a gp relative address.
825     if (Sec->Flags & SHF_MIPS_GPREL)
826       Rank |= RF_MIPS_GPREL;
827 
828     if (Sec->Name != ".got")
829       Rank |= RF_MIPS_NOT_GOT;
830   }
831 
832   return Rank;
833 }
834 
835 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
836   const OutputSection *A = cast<OutputSection>(ACmd);
837   const OutputSection *B = cast<OutputSection>(BCmd);
838   if (A->SortRank != B->SortRank)
839     return A->SortRank < B->SortRank;
840   if (!(A->SortRank & RF_NOT_ADDR_SET))
841     return Config->SectionStartMap.lookup(A->Name) <
842            Config->SectionStartMap.lookup(B->Name);
843   return false;
844 }
845 
846 void PhdrEntry::add(OutputSection *Sec) {
847   LastSec = Sec;
848   if (!FirstSec)
849     FirstSec = Sec;
850   p_align = std::max(p_align, Sec->Alignment);
851   if (p_type == PT_LOAD)
852     Sec->PtLoad = this;
853 }
854 
855 // The beginning and the ending of .rel[a].plt section are marked
856 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
857 // executable. The runtime needs these symbols in order to resolve
858 // all IRELATIVE relocs on startup. For dynamic executables, we don't
859 // need these symbols, since IRELATIVE relocs are resolved through GOT
860 // and PLT. For details, see http://www.airs.com/blog/archives/403.
861 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
862   if (needsInterpSection())
863     return;
864   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
865   addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
866 
867   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
868   ElfSym::RelaIpltEnd =
869       addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
870 }
871 
872 template <class ELFT>
873 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
874   // Scan all relocations. Each relocation goes through a series
875   // of tests to determine if it needs special treatment, such as
876   // creating GOT, PLT, copy relocations, etc.
877   // Note that relocations for non-alloc sections are directly
878   // processed by InputSection::relocateNonAlloc.
879   for (InputSectionBase *IS : InputSections)
880     if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
881       Fn(*IS);
882   for (EhInputSection *ES : InX::EhFrame->Sections)
883     Fn(*ES);
884 }
885 
886 // This function generates assignments for predefined symbols (e.g. _end or
887 // _etext) and inserts them into the commands sequence to be processed at the
888 // appropriate time. This ensures that the value is going to be correct by the
889 // time any references to these symbols are processed and is equivalent to
890 // defining these symbols explicitly in the linker script.
891 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
892   if (ElfSym::GlobalOffsetTable) {
893     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
894     // to the start of the .got or .got.plt section.
895     InputSection *GotSection = InX::GotPlt;
896     if (!Target->GotBaseSymInGotPlt)
897       GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
898                                 : cast<InputSection>(InX::Got);
899     ElfSym::GlobalOffsetTable->Section = GotSection;
900   }
901 
902   if (ElfSym::RelaIpltEnd)
903     ElfSym::RelaIpltEnd->Value = InX::RelaIplt->getSize();
904 
905   PhdrEntry *Last = nullptr;
906   PhdrEntry *LastRO = nullptr;
907 
908   for (PhdrEntry *P : Phdrs) {
909     if (P->p_type != PT_LOAD)
910       continue;
911     Last = P;
912     if (!(P->p_flags & PF_W))
913       LastRO = P;
914   }
915 
916   if (LastRO) {
917     // _etext is the first location after the last read-only loadable segment.
918     if (ElfSym::Etext1)
919       ElfSym::Etext1->Section = LastRO->LastSec;
920     if (ElfSym::Etext2)
921       ElfSym::Etext2->Section = LastRO->LastSec;
922   }
923 
924   if (Last) {
925     // _edata points to the end of the last mapped initialized section.
926     OutputSection *Edata = nullptr;
927     for (OutputSection *OS : OutputSections) {
928       if (OS->Type != SHT_NOBITS)
929         Edata = OS;
930       if (OS == Last->LastSec)
931         break;
932     }
933 
934     if (ElfSym::Edata1)
935       ElfSym::Edata1->Section = Edata;
936     if (ElfSym::Edata2)
937       ElfSym::Edata2->Section = Edata;
938 
939     // _end is the first location after the uninitialized data region.
940     if (ElfSym::End1)
941       ElfSym::End1->Section = Last->LastSec;
942     if (ElfSym::End2)
943       ElfSym::End2->Section = Last->LastSec;
944   }
945 
946   if (ElfSym::Bss)
947     ElfSym::Bss->Section = findSection(".bss");
948 
949   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
950   // be equal to the _gp symbol's value.
951   if (ElfSym::MipsGp) {
952     // Find GP-relative section with the lowest address
953     // and use this address to calculate default _gp value.
954     for (OutputSection *OS : OutputSections) {
955       if (OS->Flags & SHF_MIPS_GPREL) {
956         ElfSym::MipsGp->Section = OS;
957         ElfSym::MipsGp->Value = 0x7ff0;
958         break;
959       }
960     }
961   }
962 }
963 
964 // We want to find how similar two ranks are.
965 // The more branches in getSectionRank that match, the more similar they are.
966 // Since each branch corresponds to a bit flag, we can just use
967 // countLeadingZeros.
968 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
969   return countLeadingZeros(A->SortRank ^ B->SortRank);
970 }
971 
972 static int getRankProximity(OutputSection *A, BaseCommand *B) {
973   if (auto *Sec = dyn_cast<OutputSection>(B))
974     return getRankProximityAux(A, Sec);
975   return -1;
976 }
977 
978 // When placing orphan sections, we want to place them after symbol assignments
979 // so that an orphan after
980 //   begin_foo = .;
981 //   foo : { *(foo) }
982 //   end_foo = .;
983 // doesn't break the intended meaning of the begin/end symbols.
984 // We don't want to go over sections since findOrphanPos is the
985 // one in charge of deciding the order of the sections.
986 // We don't want to go over changes to '.', since doing so in
987 //  rx_sec : { *(rx_sec) }
988 //  . = ALIGN(0x1000);
989 //  /* The RW PT_LOAD starts here*/
990 //  rw_sec : { *(rw_sec) }
991 // would mean that the RW PT_LOAD would become unaligned.
992 static bool shouldSkip(BaseCommand *Cmd) {
993   if (isa<OutputSection>(Cmd))
994     return false;
995   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
996     return Assign->Name != ".";
997   return true;
998 }
999 
1000 // We want to place orphan sections so that they share as much
1001 // characteristics with their neighbors as possible. For example, if
1002 // both are rw, or both are tls.
1003 template <typename ELFT>
1004 static std::vector<BaseCommand *>::iterator
1005 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1006               std::vector<BaseCommand *>::iterator E) {
1007   OutputSection *Sec = cast<OutputSection>(*E);
1008 
1009   // Find the first element that has as close a rank as possible.
1010   auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1011     return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1012   });
1013   if (I == E)
1014     return E;
1015 
1016   // Consider all existing sections with the same proximity.
1017   int Proximity = getRankProximity(Sec, *I);
1018   for (; I != E; ++I) {
1019     auto *CurSec = dyn_cast<OutputSection>(*I);
1020     if (!CurSec)
1021       continue;
1022     if (getRankProximity(Sec, CurSec) != Proximity ||
1023         Sec->SortRank < CurSec->SortRank)
1024       break;
1025   }
1026 
1027   auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); };
1028   auto J = std::find_if(llvm::make_reverse_iterator(I),
1029                         llvm::make_reverse_iterator(B), IsOutputSec);
1030   I = J.base();
1031 
1032   // As a special case, if the orphan section is the last section, put
1033   // it at the very end, past any other commands.
1034   // This matches bfd's behavior and is convenient when the linker script fully
1035   // specifies the start of the file, but doesn't care about the end (the non
1036   // alloc sections for example).
1037   auto NextSec = std::find_if(I, E, IsOutputSec);
1038   if (NextSec == E)
1039     return E;
1040 
1041   while (I != E && shouldSkip(*I))
1042     ++I;
1043   return I;
1044 }
1045 
1046 // Builds section order for handling --symbol-ordering-file.
1047 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1048   DenseMap<const InputSectionBase *, int> SectionOrder;
1049   // Use the rarely used option -call-graph-ordering-file to sort sections.
1050   if (!Config->CallGraphProfile.empty())
1051     return computeCallGraphProfileOrder();
1052 
1053   if (Config->SymbolOrderingFile.empty())
1054     return SectionOrder;
1055 
1056   struct SymbolOrderEntry {
1057     int Priority;
1058     bool Present;
1059   };
1060 
1061   // Build a map from symbols to their priorities. Symbols that didn't
1062   // appear in the symbol ordering file have the lowest priority 0.
1063   // All explicitly mentioned symbols have negative (higher) priorities.
1064   DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1065   int Priority = -Config->SymbolOrderingFile.size();
1066   for (StringRef S : Config->SymbolOrderingFile)
1067     SymbolOrder.insert({S, {Priority++, false}});
1068 
1069   // Build a map from sections to their priorities.
1070   auto AddSym = [&](Symbol &Sym) {
1071     auto It = SymbolOrder.find(Sym.getName());
1072     if (It == SymbolOrder.end())
1073       return;
1074     SymbolOrderEntry &Ent = It->second;
1075     Ent.Present = true;
1076 
1077     warnUnorderableSymbol(&Sym);
1078 
1079     if (auto *D = dyn_cast<Defined>(&Sym)) {
1080       if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1081         int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1082         Priority = std::min(Priority, Ent.Priority);
1083       }
1084     }
1085   };
1086   // We want both global and local symbols. We get the global ones from the
1087   // symbol table and iterate the object files for the local ones.
1088   for (Symbol *Sym : Symtab->getSymbols())
1089     if (!Sym->isLazy())
1090       AddSym(*Sym);
1091   for (InputFile *File : ObjectFiles)
1092     for (Symbol *Sym : File->getSymbols())
1093       if (Sym->isLocal())
1094         AddSym(*Sym);
1095 
1096   if (Config->WarnSymbolOrdering)
1097     for (auto OrderEntry : SymbolOrder)
1098       if (!OrderEntry.second.Present)
1099         warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1100 
1101   return SectionOrder;
1102 }
1103 
1104 // Sorts the sections in ISD according to the provided section order.
1105 static void
1106 sortISDBySectionOrder(InputSectionDescription *ISD,
1107                       const DenseMap<const InputSectionBase *, int> &Order) {
1108   std::vector<InputSection *> UnorderedSections;
1109   std::vector<std::pair<InputSection *, int>> OrderedSections;
1110   uint64_t UnorderedSize = 0;
1111 
1112   for (InputSection *IS : ISD->Sections) {
1113     auto I = Order.find(IS);
1114     if (I == Order.end()) {
1115       UnorderedSections.push_back(IS);
1116       UnorderedSize += IS->getSize();
1117       continue;
1118     }
1119     OrderedSections.push_back({IS, I->second});
1120   }
1121   llvm::sort(
1122       OrderedSections.begin(), OrderedSections.end(),
1123       [&](std::pair<InputSection *, int> A, std::pair<InputSection *, int> B) {
1124         return A.second < B.second;
1125       });
1126 
1127   // Find an insertion point for the ordered section list in the unordered
1128   // section list. On targets with limited-range branches, this is the mid-point
1129   // of the unordered section list. This decreases the likelihood that a range
1130   // extension thunk will be needed to enter or exit the ordered region. If the
1131   // ordered section list is a list of hot functions, we can generally expect
1132   // the ordered functions to be called more often than the unordered functions,
1133   // making it more likely that any particular call will be within range, and
1134   // therefore reducing the number of thunks required.
1135   //
1136   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1137   // If the layout is:
1138   //
1139   // 8MB hot
1140   // 32MB cold
1141   //
1142   // only the first 8-16MB of the cold code (depending on which hot function it
1143   // is actually calling) can call the hot code without a range extension thunk.
1144   // However, if we use this layout:
1145   //
1146   // 16MB cold
1147   // 8MB hot
1148   // 16MB cold
1149   //
1150   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1151   // of the second block of cold code can call the hot code without a thunk. So
1152   // we effectively double the amount of code that could potentially call into
1153   // the hot code without a thunk.
1154   size_t InsPt = 0;
1155   if (Target->ThunkSectionSpacing && !OrderedSections.empty()) {
1156     uint64_t UnorderedPos = 0;
1157     for (; InsPt != UnorderedSections.size(); ++InsPt) {
1158       UnorderedPos += UnorderedSections[InsPt]->getSize();
1159       if (UnorderedPos > UnorderedSize / 2)
1160         break;
1161     }
1162   }
1163 
1164   ISD->Sections.clear();
1165   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1166     ISD->Sections.push_back(IS);
1167   for (std::pair<InputSection *, int> P : OrderedSections)
1168     ISD->Sections.push_back(P.first);
1169   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1170     ISD->Sections.push_back(IS);
1171 }
1172 
1173 static void sortSection(OutputSection *Sec,
1174                         const DenseMap<const InputSectionBase *, int> &Order) {
1175   StringRef Name = Sec->Name;
1176 
1177   // Sort input sections by section name suffixes for
1178   // __attribute__((init_priority(N))).
1179   if (Name == ".init_array" || Name == ".fini_array") {
1180     if (!Script->HasSectionsCommand)
1181       Sec->sortInitFini();
1182     return;
1183   }
1184 
1185   // Sort input sections by the special rule for .ctors and .dtors.
1186   if (Name == ".ctors" || Name == ".dtors") {
1187     if (!Script->HasSectionsCommand)
1188       Sec->sortCtorsDtors();
1189     return;
1190   }
1191 
1192   // Never sort these.
1193   if (Name == ".init" || Name == ".fini")
1194     return;
1195 
1196   // Sort input sections by priority using the list provided
1197   // by --symbol-ordering-file.
1198   if (!Order.empty())
1199     for (BaseCommand *B : Sec->SectionCommands)
1200       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1201         sortISDBySectionOrder(ISD, Order);
1202 }
1203 
1204 // If no layout was provided by linker script, we want to apply default
1205 // sorting for special input sections. This also handles --symbol-ordering-file.
1206 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1207   // Build the order once since it is expensive.
1208   DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1209   for (BaseCommand *Base : Script->SectionCommands)
1210     if (auto *Sec = dyn_cast<OutputSection>(Base))
1211       sortSection(Sec, Order);
1212 }
1213 
1214 template <class ELFT> void Writer<ELFT>::sortSections() {
1215   Script->adjustSectionsBeforeSorting();
1216 
1217   // Don't sort if using -r. It is not necessary and we want to preserve the
1218   // relative order for SHF_LINK_ORDER sections.
1219   if (Config->Relocatable)
1220     return;
1221 
1222   sortInputSections();
1223 
1224   for (BaseCommand *Base : Script->SectionCommands) {
1225     auto *OS = dyn_cast<OutputSection>(Base);
1226     if (!OS)
1227       continue;
1228     OS->SortRank = getSectionRank(OS);
1229 
1230     // We want to assign rude approximation values to OutSecOff fields
1231     // to know the relative order of the input sections. We use it for
1232     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1233     uint64_t I = 0;
1234     for (InputSection *Sec : getInputSections(OS))
1235       Sec->OutSecOff = I++;
1236   }
1237 
1238   if (!Script->HasSectionsCommand) {
1239     // We know that all the OutputSections are contiguous in this case.
1240     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1241     std::stable_sort(
1242         llvm::find_if(Script->SectionCommands, IsSection),
1243         llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1244         compareSections);
1245     return;
1246   }
1247 
1248   // Orphan sections are sections present in the input files which are
1249   // not explicitly placed into the output file by the linker script.
1250   //
1251   // The sections in the linker script are already in the correct
1252   // order. We have to figuere out where to insert the orphan
1253   // sections.
1254   //
1255   // The order of the sections in the script is arbitrary and may not agree with
1256   // compareSections. This means that we cannot easily define a strict weak
1257   // ordering. To see why, consider a comparison of a section in the script and
1258   // one not in the script. We have a two simple options:
1259   // * Make them equivalent (a is not less than b, and b is not less than a).
1260   //   The problem is then that equivalence has to be transitive and we can
1261   //   have sections a, b and c with only b in a script and a less than c
1262   //   which breaks this property.
1263   // * Use compareSectionsNonScript. Given that the script order doesn't have
1264   //   to match, we can end up with sections a, b, c, d where b and c are in the
1265   //   script and c is compareSectionsNonScript less than b. In which case d
1266   //   can be equivalent to c, a to b and d < a. As a concrete example:
1267   //   .a (rx) # not in script
1268   //   .b (rx) # in script
1269   //   .c (ro) # in script
1270   //   .d (ro) # not in script
1271   //
1272   // The way we define an order then is:
1273   // *  Sort only the orphan sections. They are in the end right now.
1274   // *  Move each orphan section to its preferred position. We try
1275   //    to put each section in the last position where it can share
1276   //    a PT_LOAD.
1277   //
1278   // There is some ambiguity as to where exactly a new entry should be
1279   // inserted, because Commands contains not only output section
1280   // commands but also other types of commands such as symbol assignment
1281   // expressions. There's no correct answer here due to the lack of the
1282   // formal specification of the linker script. We use heuristics to
1283   // determine whether a new output command should be added before or
1284   // after another commands. For the details, look at shouldSkip
1285   // function.
1286 
1287   auto I = Script->SectionCommands.begin();
1288   auto E = Script->SectionCommands.end();
1289   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1290     if (auto *Sec = dyn_cast<OutputSection>(Base))
1291       return Sec->SectionIndex == UINT32_MAX;
1292     return false;
1293   });
1294 
1295   // Sort the orphan sections.
1296   std::stable_sort(NonScriptI, E, compareSections);
1297 
1298   // As a horrible special case, skip the first . assignment if it is before any
1299   // section. We do this because it is common to set a load address by starting
1300   // the script with ". = 0xabcd" and the expectation is that every section is
1301   // after that.
1302   auto FirstSectionOrDotAssignment =
1303       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1304   if (FirstSectionOrDotAssignment != E &&
1305       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1306     ++FirstSectionOrDotAssignment;
1307   I = FirstSectionOrDotAssignment;
1308 
1309   while (NonScriptI != E) {
1310     auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1311     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1312 
1313     // As an optimization, find all sections with the same sort rank
1314     // and insert them with one rotate.
1315     unsigned Rank = Orphan->SortRank;
1316     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1317       return cast<OutputSection>(Cmd)->SortRank != Rank;
1318     });
1319     std::rotate(Pos, NonScriptI, End);
1320     NonScriptI = End;
1321   }
1322 
1323   Script->adjustSectionsAfterSorting();
1324 }
1325 
1326 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1327   // Synthetic, i. e. a sentinel section, should go last.
1328   if (A->kind() == InputSectionBase::Synthetic ||
1329       B->kind() == InputSectionBase::Synthetic)
1330     return A->kind() != InputSectionBase::Synthetic;
1331   InputSection *LA = A->getLinkOrderDep();
1332   InputSection *LB = B->getLinkOrderDep();
1333   OutputSection *AOut = LA->getParent();
1334   OutputSection *BOut = LB->getParent();
1335   if (AOut != BOut)
1336     return AOut->SectionIndex < BOut->SectionIndex;
1337   return LA->OutSecOff < LB->OutSecOff;
1338 }
1339 
1340 // This function is used by the --merge-exidx-entries to detect duplicate
1341 // .ARM.exidx sections. It is Arm only.
1342 //
1343 // The .ARM.exidx section is of the form:
1344 // | PREL31 offset to function | Unwind instructions for function |
1345 // where the unwind instructions are either a small number of unwind
1346 // instructions inlined into the table entry, the special CANT_UNWIND value of
1347 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1348 // instructions.
1349 //
1350 // We return true if all the unwind instructions in the .ARM.exidx entries of
1351 // Cur can be merged into the last entry of Prev.
1352 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1353 
1354   // References to .ARM.Extab Sections have bit 31 clear and are not the
1355   // special EXIDX_CANTUNWIND bit-pattern.
1356   auto IsExtabRef = [](uint32_t Unwind) {
1357     return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1358   };
1359 
1360   struct ExidxEntry {
1361     ulittle32_t Fn;
1362     ulittle32_t Unwind;
1363   };
1364 
1365   // Get the last table Entry from the previous .ARM.exidx section.
1366   const ExidxEntry &PrevEntry = *reinterpret_cast<const ExidxEntry *>(
1367       Prev->Data.data() + Prev->getSize() - sizeof(ExidxEntry));
1368   if (IsExtabRef(PrevEntry.Unwind))
1369     return false;
1370 
1371   // We consider the unwind instructions of an .ARM.exidx table entry
1372   // a duplicate if the previous unwind instructions if:
1373   // - Both are the special EXIDX_CANTUNWIND.
1374   // - Both are the same inline unwind instructions.
1375   // We do not attempt to follow and check links into .ARM.extab tables as
1376   // consecutive identical entries are rare and the effort to check that they
1377   // are identical is high.
1378 
1379   if (isa<SyntheticSection>(Cur))
1380     // Exidx sentinel section has implicit EXIDX_CANTUNWIND;
1381     return PrevEntry.Unwind == 0x1;
1382 
1383   ArrayRef<const ExidxEntry> Entries(
1384       reinterpret_cast<const ExidxEntry *>(Cur->Data.data()),
1385       Cur->getSize() / sizeof(ExidxEntry));
1386   for (const ExidxEntry &Entry : Entries)
1387     if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1388       return false;
1389   // All table entries in this .ARM.exidx Section can be merged into the
1390   // previous Section.
1391   return true;
1392 }
1393 
1394 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1395   for (OutputSection *Sec : OutputSections) {
1396     if (!(Sec->Flags & SHF_LINK_ORDER))
1397       continue;
1398 
1399     // Link order may be distributed across several InputSectionDescriptions
1400     // but sort must consider them all at once.
1401     std::vector<InputSection **> ScriptSections;
1402     std::vector<InputSection *> Sections;
1403     for (BaseCommand *Base : Sec->SectionCommands) {
1404       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1405         for (InputSection *&IS : ISD->Sections) {
1406           ScriptSections.push_back(&IS);
1407           Sections.push_back(IS);
1408         }
1409       }
1410     }
1411     std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1412 
1413     if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1414         Sec->Type == SHT_ARM_EXIDX) {
1415 
1416       if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1417         assert(Sections.size() >= 2 &&
1418                "We should create a sentinel section only if there are "
1419                "alive regular exidx sections.");
1420         // The last executable section is required to fill the sentinel.
1421         // Remember it here so that we don't have to find it again.
1422         auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1423         Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1424       }
1425 
1426       if (Config->MergeArmExidx) {
1427         // The EHABI for the Arm Architecture permits consecutive identical
1428         // table entries to be merged. We use a simple implementation that
1429         // removes a .ARM.exidx Input Section if it can be merged into the
1430         // previous one. This does not require any rewriting of InputSection
1431         // contents but misses opportunities for fine grained deduplication
1432         // where only a subset of the InputSection contents can be merged.
1433         int Cur = 1;
1434         int Prev = 0;
1435         // The last one is a sentinel entry which should not be removed.
1436         int N = Sections.size() - 1;
1437         while (Cur < N) {
1438           if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1439             Sections[Cur] = nullptr;
1440           else
1441             Prev = Cur;
1442           ++Cur;
1443         }
1444       }
1445     }
1446 
1447     for (int I = 0, N = Sections.size(); I < N; ++I)
1448       *ScriptSections[I] = Sections[I];
1449 
1450     // Remove the Sections we marked as duplicate earlier.
1451     for (BaseCommand *Base : Sec->SectionCommands)
1452       if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1453         llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; });
1454   }
1455 }
1456 
1457 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1458                            std::function<void(SyntheticSection *)> Fn) {
1459   for (SyntheticSection *SS : Sections)
1460     if (SS && SS->getParent() && !SS->empty())
1461       Fn(SS);
1462 }
1463 
1464 // In order to allow users to manipulate linker-synthesized sections,
1465 // we had to add synthetic sections to the input section list early,
1466 // even before we make decisions whether they are needed. This allows
1467 // users to write scripts like this: ".mygot : { .got }".
1468 //
1469 // Doing it has an unintended side effects. If it turns out that we
1470 // don't need a .got (for example) at all because there's no
1471 // relocation that needs a .got, we don't want to emit .got.
1472 //
1473 // To deal with the above problem, this function is called after
1474 // scanRelocations is called to remove synthetic sections that turn
1475 // out to be empty.
1476 static void removeUnusedSyntheticSections() {
1477   // All input synthetic sections that can be empty are placed after
1478   // all regular ones. We iterate over them all and exit at first
1479   // non-synthetic.
1480   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1481     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1482     if (!SS)
1483       return;
1484     OutputSection *OS = SS->getParent();
1485     if (!OS || !SS->empty())
1486       continue;
1487 
1488     // If we reach here, then SS is an unused synthetic section and we want to
1489     // remove it from corresponding input section description of output section.
1490     for (BaseCommand *B : OS->SectionCommands)
1491       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1492         llvm::erase_if(ISD->Sections,
1493                        [=](InputSection *IS) { return IS == SS; });
1494   }
1495 }
1496 
1497 // Returns true if a symbol can be replaced at load-time by a symbol
1498 // with the same name defined in other ELF executable or DSO.
1499 static bool computeIsPreemptible(const Symbol &B) {
1500   assert(!B.isLocal());
1501   // Only symbols that appear in dynsym can be preempted.
1502   if (!B.includeInDynsym())
1503     return false;
1504 
1505   // Only default visibility symbols can be preempted.
1506   if (B.Visibility != STV_DEFAULT)
1507     return false;
1508 
1509   // At this point copy relocations have not been created yet, so any
1510   // symbol that is not defined locally is preemptible.
1511   if (!B.isDefined())
1512     return true;
1513 
1514   // If we have a dynamic list it specifies which local symbols are preemptible.
1515   if (Config->HasDynamicList)
1516     return false;
1517 
1518   if (!Config->Shared)
1519     return false;
1520 
1521   // -Bsymbolic means that definitions are not preempted.
1522   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1523     return false;
1524   return true;
1525 }
1526 
1527 // Create output section objects and add them to OutputSections.
1528 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1529   Out::DebugInfo = findSection(".debug_info");
1530   Out::PreinitArray = findSection(".preinit_array");
1531   Out::InitArray = findSection(".init_array");
1532   Out::FiniArray = findSection(".fini_array");
1533 
1534   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1535   // symbols for sections, so that the runtime can get the start and end
1536   // addresses of each section by section name. Add such symbols.
1537   if (!Config->Relocatable) {
1538     addStartEndSymbols();
1539     for (BaseCommand *Base : Script->SectionCommands)
1540       if (auto *Sec = dyn_cast<OutputSection>(Base))
1541         addStartStopSymbols(Sec);
1542   }
1543 
1544   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1545   // It should be okay as no one seems to care about the type.
1546   // Even the author of gold doesn't remember why gold behaves that way.
1547   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1548   if (InX::DynSymTab)
1549     Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1550                        /*Size=*/0, STB_WEAK, InX::Dynamic,
1551                        /*File=*/nullptr);
1552 
1553   // Define __rel[a]_iplt_{start,end} symbols if needed.
1554   addRelIpltSymbols();
1555 
1556   // This responsible for splitting up .eh_frame section into
1557   // pieces. The relocation scan uses those pieces, so this has to be
1558   // earlier.
1559   applySynthetic({InX::EhFrame},
1560                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1561 
1562   for (Symbol *S : Symtab->getSymbols())
1563     S->IsPreemptible |= computeIsPreemptible(*S);
1564 
1565   // Scan relocations. This must be done after every symbol is declared so that
1566   // we can correctly decide if a dynamic relocation is needed.
1567   if (!Config->Relocatable)
1568     forEachRelSec(scanRelocations<ELFT>);
1569 
1570   if (InX::Plt && !InX::Plt->empty())
1571     InX::Plt->addSymbols();
1572   if (InX::Iplt && !InX::Iplt->empty())
1573     InX::Iplt->addSymbols();
1574 
1575   // Now that we have defined all possible global symbols including linker-
1576   // synthesized ones. Visit all symbols to give the finishing touches.
1577   for (Symbol *Sym : Symtab->getSymbols()) {
1578     if (!includeInSymtab(*Sym))
1579       continue;
1580     if (InX::SymTab)
1581       InX::SymTab->addSymbol(Sym);
1582 
1583     if (InX::DynSymTab && Sym->includeInDynsym()) {
1584       InX::DynSymTab->addSymbol(Sym);
1585       if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1586         if (File->IsNeeded && !Sym->isUndefined())
1587           In<ELFT>::VerNeed->addSymbol(Sym);
1588     }
1589   }
1590 
1591   // Do not proceed if there was an undefined symbol.
1592   if (errorCount())
1593     return;
1594 
1595   removeUnusedSyntheticSections();
1596 
1597   sortSections();
1598 
1599   // Now that we have the final list, create a list of all the
1600   // OutputSections for convenience.
1601   for (BaseCommand *Base : Script->SectionCommands)
1602     if (auto *Sec = dyn_cast<OutputSection>(Base))
1603       OutputSections.push_back(Sec);
1604 
1605   // Prefer command line supplied address over other constraints.
1606   for (OutputSection *Sec : OutputSections) {
1607     auto I = Config->SectionStartMap.find(Sec->Name);
1608     if (I != Config->SectionStartMap.end())
1609       Sec->AddrExpr = [=] { return I->second; };
1610   }
1611 
1612   // This is a bit of a hack. A value of 0 means undef, so we set it
1613   // to 1 to make __ehdr_start defined. The section number is not
1614   // particularly relevant.
1615   Out::ElfHeader->SectionIndex = 1;
1616 
1617   unsigned I = 1;
1618   for (OutputSection *Sec : OutputSections) {
1619     Sec->SectionIndex = I++;
1620     Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1621   }
1622 
1623   // Binary and relocatable output does not have PHDRS.
1624   // The headers have to be created before finalize as that can influence the
1625   // image base and the dynamic section on mips includes the image base.
1626   if (!Config->Relocatable && !Config->OFormatBinary) {
1627     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1628     addPtArmExid(Phdrs);
1629     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1630   }
1631 
1632   // Some symbols are defined in term of program headers. Now that we
1633   // have the headers, we can find out which sections they point to.
1634   setReservedSymbolSections();
1635 
1636   // Dynamic section must be the last one in this list and dynamic
1637   // symbol table section (DynSymTab) must be the first one.
1638   applySynthetic(
1639       {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1640        InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1641        In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1642        InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1643        InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1644        In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1645       [](SyntheticSection *SS) { SS->finalizeContents(); });
1646 
1647   if (!Script->HasSectionsCommand && !Config->Relocatable)
1648     fixSectionAlignments();
1649 
1650   // After link order processing .ARM.exidx sections can be deduplicated, which
1651   // needs to be resolved before any other address dependent operation.
1652   resolveShfLinkOrder();
1653 
1654   // Some architectures need to generate content that depends on the address
1655   // of InputSections. For example some architectures use small displacements
1656   // for jump instructions that is the linker's responsibility for creating
1657   // range extension thunks for. As the generation of the content may also
1658   // alter InputSection addresses we must converge to a fixed point.
1659   if (Target->NeedsThunks || Config->AndroidPackDynRelocs) {
1660     ThunkCreator TC;
1661     AArch64Err843419Patcher A64P;
1662     bool Changed;
1663     do {
1664       Script->assignAddresses();
1665       Changed = false;
1666       if (Target->NeedsThunks)
1667         Changed |= TC.createThunks(OutputSections);
1668       if (Config->FixCortexA53Errata843419) {
1669         if (Changed)
1670           Script->assignAddresses();
1671         Changed |= A64P.createFixes();
1672       }
1673       if (InX::MipsGot)
1674         InX::MipsGot->updateAllocSize();
1675       Changed |= InX::RelaDyn->updateAllocSize();
1676     } while (Changed);
1677   }
1678 
1679   // createThunks may have added local symbols to the static symbol table
1680   applySynthetic({InX::SymTab},
1681                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1682 
1683   // Fill other section headers. The dynamic table is finalized
1684   // at the end because some tags like RELSZ depend on result
1685   // of finalizing other sections.
1686   for (OutputSection *Sec : OutputSections)
1687     Sec->finalize<ELFT>();
1688 }
1689 
1690 // The linker is expected to define SECNAME_start and SECNAME_end
1691 // symbols for a few sections. This function defines them.
1692 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1693   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1694     // These symbols resolve to the image base if the section does not exist.
1695     // A special value -1 indicates end of the section.
1696     if (OS) {
1697       addOptionalRegular(Start, OS, 0);
1698       addOptionalRegular(End, OS, -1);
1699     } else {
1700       if (Config->Pic)
1701         OS = Out::ElfHeader;
1702       addOptionalRegular(Start, OS, 0);
1703       addOptionalRegular(End, OS, 0);
1704     }
1705   };
1706 
1707   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1708   Define("__init_array_start", "__init_array_end", Out::InitArray);
1709   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1710 
1711   if (OutputSection *Sec = findSection(".ARM.exidx"))
1712     Define("__exidx_start", "__exidx_end", Sec);
1713 }
1714 
1715 // If a section name is valid as a C identifier (which is rare because of
1716 // the leading '.'), linkers are expected to define __start_<secname> and
1717 // __stop_<secname> symbols. They are at beginning and end of the section,
1718 // respectively. This is not requested by the ELF standard, but GNU ld and
1719 // gold provide the feature, and used by many programs.
1720 template <class ELFT>
1721 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1722   StringRef S = Sec->Name;
1723   if (!isValidCIdentifier(S))
1724     return;
1725   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1726   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1727 }
1728 
1729 static bool needsPtLoad(OutputSection *Sec) {
1730   if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1731     return false;
1732 
1733   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1734   // responsible for allocating space for them, not the PT_LOAD that
1735   // contains the TLS initialization image.
1736   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1737     return false;
1738   return true;
1739 }
1740 
1741 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1742 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1743 // RW. This means that there is no alignment in the RO to RX transition and we
1744 // cannot create a PT_LOAD there.
1745 static uint64_t computeFlags(uint64_t Flags) {
1746   if (Config->Omagic)
1747     return PF_R | PF_W | PF_X;
1748   if (Config->SingleRoRx && !(Flags & PF_W))
1749     return Flags | PF_X;
1750   return Flags;
1751 }
1752 
1753 // Decide which program headers to create and which sections to include in each
1754 // one.
1755 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1756   std::vector<PhdrEntry *> Ret;
1757   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1758     Ret.push_back(make<PhdrEntry>(Type, Flags));
1759     return Ret.back();
1760   };
1761 
1762   // The first phdr entry is PT_PHDR which describes the program header itself.
1763   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1764 
1765   // PT_INTERP must be the second entry if exists.
1766   if (OutputSection *Cmd = findSection(".interp"))
1767     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1768 
1769   // Add the first PT_LOAD segment for regular output sections.
1770   uint64_t Flags = computeFlags(PF_R);
1771   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1772 
1773   // Add the headers. We will remove them if they don't fit.
1774   Load->add(Out::ElfHeader);
1775   Load->add(Out::ProgramHeaders);
1776 
1777   for (OutputSection *Sec : OutputSections) {
1778     if (!(Sec->Flags & SHF_ALLOC))
1779       break;
1780     if (!needsPtLoad(Sec))
1781       continue;
1782 
1783     // Segments are contiguous memory regions that has the same attributes
1784     // (e.g. executable or writable). There is one phdr for each segment.
1785     // Therefore, we need to create a new phdr when the next section has
1786     // different flags or is loaded at a discontiguous address using AT linker
1787     // script command. At the same time, we don't want to create a separate
1788     // load segment for the headers, even if the first output section has
1789     // an AT attribute.
1790     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1791     if ((Sec->LMAExpr && Load->LastSec != Out::ProgramHeaders) ||
1792         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1793 
1794       Load = AddHdr(PT_LOAD, NewFlags);
1795       Flags = NewFlags;
1796     }
1797 
1798     Load->add(Sec);
1799   }
1800 
1801   // Add a TLS segment if any.
1802   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1803   for (OutputSection *Sec : OutputSections)
1804     if (Sec->Flags & SHF_TLS)
1805       TlsHdr->add(Sec);
1806   if (TlsHdr->FirstSec)
1807     Ret.push_back(TlsHdr);
1808 
1809   // Add an entry for .dynamic.
1810   if (InX::DynSymTab)
1811     AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags())
1812         ->add(InX::Dynamic->getParent());
1813 
1814   // PT_GNU_RELRO includes all sections that should be marked as
1815   // read-only by dynamic linker after proccessing relocations.
1816   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1817   // an error message if more than one PT_GNU_RELRO PHDR is required.
1818   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1819   bool InRelroPhdr = false;
1820   bool IsRelroFinished = false;
1821   for (OutputSection *Sec : OutputSections) {
1822     if (!needsPtLoad(Sec))
1823       continue;
1824     if (isRelroSection(Sec)) {
1825       InRelroPhdr = true;
1826       if (!IsRelroFinished)
1827         RelRo->add(Sec);
1828       else
1829         error("section: " + Sec->Name + " is not contiguous with other relro" +
1830               " sections");
1831     } else if (InRelroPhdr) {
1832       InRelroPhdr = false;
1833       IsRelroFinished = true;
1834     }
1835   }
1836   if (RelRo->FirstSec)
1837     Ret.push_back(RelRo);
1838 
1839   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1840   if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() &&
1841       InX::EhFrameHdr->getParent())
1842     AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags())
1843         ->add(InX::EhFrameHdr->getParent());
1844 
1845   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1846   // the dynamic linker fill the segment with random data.
1847   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1848     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1849 
1850   // PT_GNU_STACK is a special section to tell the loader to make the
1851   // pages for the stack non-executable. If you really want an executable
1852   // stack, you can pass -z execstack, but that's not recommended for
1853   // security reasons.
1854   unsigned Perm = PF_R | PF_W;
1855   if (Config->ZExecstack)
1856     Perm |= PF_X;
1857   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1858 
1859   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1860   // is expected to perform W^X violations, such as calling mprotect(2) or
1861   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1862   // OpenBSD.
1863   if (Config->ZWxneeded)
1864     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1865 
1866   // Create one PT_NOTE per a group of contiguous .note sections.
1867   PhdrEntry *Note = nullptr;
1868   for (OutputSection *Sec : OutputSections) {
1869     if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
1870       if (!Note || Sec->LMAExpr)
1871         Note = AddHdr(PT_NOTE, PF_R);
1872       Note->add(Sec);
1873     } else {
1874       Note = nullptr;
1875     }
1876   }
1877   return Ret;
1878 }
1879 
1880 template <class ELFT>
1881 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
1882   if (Config->EMachine != EM_ARM)
1883     return;
1884   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
1885     return Cmd->Type == SHT_ARM_EXIDX;
1886   });
1887   if (I == OutputSections.end())
1888     return;
1889 
1890   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1891   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
1892   ARMExidx->add(*I);
1893   Phdrs.push_back(ARMExidx);
1894 }
1895 
1896 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1897 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1898 // linker can set the permissions.
1899 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1900   auto PageAlign = [](OutputSection *Cmd) {
1901     if (Cmd && !Cmd->AddrExpr)
1902       Cmd->AddrExpr = [=] {
1903         return alignTo(Script->getDot(), Config->MaxPageSize);
1904       };
1905   };
1906 
1907   for (const PhdrEntry *P : Phdrs)
1908     if (P->p_type == PT_LOAD && P->FirstSec)
1909       PageAlign(P->FirstSec);
1910 
1911   for (const PhdrEntry *P : Phdrs) {
1912     if (P->p_type != PT_GNU_RELRO)
1913       continue;
1914     if (P->FirstSec)
1915       PageAlign(P->FirstSec);
1916     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1917     // have to align it to a page.
1918     auto End = OutputSections.end();
1919     auto I = std::find(OutputSections.begin(), End, P->LastSec);
1920     if (I == End || (I + 1) == End)
1921       continue;
1922     OutputSection *Cmd = (*(I + 1));
1923     if (needsPtLoad(Cmd))
1924       PageAlign(Cmd);
1925   }
1926 }
1927 
1928 // Adjusts the file alignment for a given output section and returns
1929 // its new file offset. The file offset must be the same with its
1930 // virtual address (modulo the page size) so that the loader can load
1931 // executables without any address adjustment.
1932 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) {
1933   OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr;
1934   // The first section in a PT_LOAD has to have congruent offset and address
1935   // module the page size.
1936   if (Cmd == First)
1937     return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize),
1938                    Cmd->Addr);
1939 
1940   // For SHT_NOBITS we don't want the alignment of the section to impact the
1941   // offset of the sections that follow. Since nothing seems to care about the
1942   // sh_offset of the SHT_NOBITS section itself, just ignore it.
1943   if (Cmd->Type == SHT_NOBITS)
1944     return Off;
1945 
1946   // If the section is not in a PT_LOAD, we just have to align it.
1947   if (!Cmd->PtLoad)
1948     return alignTo(Off, Cmd->Alignment);
1949 
1950   // If two sections share the same PT_LOAD the file offset is calculated
1951   // using this formula: Off2 = Off1 + (VA2 - VA1).
1952   return First->Offset + Cmd->Addr - First->Addr;
1953 }
1954 
1955 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) {
1956   Off = getFileAlignment(Off, Cmd);
1957   Cmd->Offset = Off;
1958 
1959   // For SHT_NOBITS we should not count the size.
1960   if (Cmd->Type == SHT_NOBITS)
1961     return Off;
1962 
1963   return Off + Cmd->Size;
1964 }
1965 
1966 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1967   uint64_t Off = 0;
1968   for (OutputSection *Sec : OutputSections)
1969     if (Sec->Flags & SHF_ALLOC)
1970       Off = setOffset(Sec, Off);
1971   FileSize = alignTo(Off, Config->Wordsize);
1972 }
1973 
1974 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
1975   if (Len == 0)
1976     return "<empty range at 0x" + utohexstr(Addr) + ">";
1977   return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
1978 }
1979 
1980 // Assign file offsets to output sections.
1981 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1982   uint64_t Off = 0;
1983   Off = setOffset(Out::ElfHeader, Off);
1984   Off = setOffset(Out::ProgramHeaders, Off);
1985 
1986   PhdrEntry *LastRX = nullptr;
1987   for (PhdrEntry *P : Phdrs)
1988     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
1989       LastRX = P;
1990 
1991   for (OutputSection *Sec : OutputSections) {
1992     Off = setOffset(Sec, Off);
1993     if (Script->HasSectionsCommand)
1994       continue;
1995     // If this is a last section of the last executable segment and that
1996     // segment is the last loadable segment, align the offset of the
1997     // following section to avoid loading non-segments parts of the file.
1998     if (LastRX && LastRX->LastSec == Sec)
1999       Off = alignTo(Off, Target->PageSize);
2000   }
2001 
2002   SectionHeaderOff = alignTo(Off, Config->Wordsize);
2003   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2004 
2005   // Our logic assumes that sections have rising VA within the same segment.
2006   // With use of linker scripts it is possible to violate this rule and get file
2007   // offset overlaps or overflows. That should never happen with a valid script
2008   // which does not move the location counter backwards and usually scripts do
2009   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2010   // kernel, which control segment distribution explicitly and move the counter
2011   // backwards, so we have to allow doing that to support linking them. We
2012   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2013   // we want to prevent file size overflows because it would crash the linker.
2014   for (OutputSection *Sec : OutputSections) {
2015     if (Sec->Type == SHT_NOBITS)
2016       continue;
2017     if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2018       error("unable to place section " + Sec->Name + " at file offset " +
2019             rangeToString(Sec->Offset, Sec->Offset + Sec->Size) +
2020             "; check your linker script for overflows");
2021   }
2022 }
2023 
2024 // Finalize the program headers. We call this function after we assign
2025 // file offsets and VAs to all sections.
2026 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2027   for (PhdrEntry *P : Phdrs) {
2028     OutputSection *First = P->FirstSec;
2029     OutputSection *Last = P->LastSec;
2030     if (First) {
2031       P->p_filesz = Last->Offset - First->Offset;
2032       if (Last->Type != SHT_NOBITS)
2033         P->p_filesz += Last->Size;
2034       P->p_memsz = Last->Addr + Last->Size - First->Addr;
2035       P->p_offset = First->Offset;
2036       P->p_vaddr = First->Addr;
2037       if (!P->HasLMA)
2038         P->p_paddr = First->getLMA();
2039     }
2040     if (P->p_type == PT_LOAD)
2041       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2042     else if (P->p_type == PT_GNU_RELRO) {
2043       P->p_align = 1;
2044       // The glibc dynamic loader rounds the size down, so we need to round up
2045       // to protect the last page. This is a no-op on FreeBSD which always
2046       // rounds up.
2047       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2048     }
2049 
2050     // The TLS pointer goes after PT_TLS. At least glibc will align it,
2051     // so round up the size to make sure the offsets are correct.
2052     if (P->p_type == PT_TLS) {
2053       Out::TlsPhdr = P;
2054       if (P->p_memsz)
2055         P->p_memsz = alignTo(P->p_memsz, P->p_align);
2056     }
2057   }
2058 }
2059 
2060 // A helper struct for checkSectionOverlap.
2061 namespace {
2062 struct SectionOffset {
2063   OutputSection *Sec;
2064   uint64_t Offset;
2065 };
2066 } // namespace
2067 
2068 // Check whether sections overlap for a specific address range (file offsets,
2069 // load and virtual adresses).
2070 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections) {
2071   llvm::sort(Sections.begin(), Sections.end(),
2072              [=](const SectionOffset &A, const SectionOffset &B) {
2073                return A.Offset < B.Offset;
2074              });
2075 
2076   // Finding overlap is easy given a vector is sorted by start position.
2077   // If an element starts before the end of the previous element, they overlap.
2078   for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2079     SectionOffset A = Sections[I - 1];
2080     SectionOffset B = Sections[I];
2081     if (B.Offset < A.Offset + A.Sec->Size)
2082       errorOrWarn(
2083           "section " + A.Sec->Name + " " + Name + " range overlaps with " +
2084           B.Sec->Name + "\n>>> " + A.Sec->Name + " range is " +
2085           rangeToString(A.Offset, A.Sec->Size) + "\n>>> " + B.Sec->Name +
2086           " range is " + rangeToString(B.Offset, B.Sec->Size));
2087   }
2088 }
2089 
2090 // Check for overlapping sections and address overflows.
2091 //
2092 // In this function we check that none of the output sections have overlapping
2093 // file offsets. For SHF_ALLOC sections we also check that the load address
2094 // ranges and the virtual address ranges don't overlap
2095 template <class ELFT> void Writer<ELFT>::checkSections() {
2096   // First, check that section's VAs fit in available address space for target.
2097   for (OutputSection *OS : OutputSections)
2098     if ((OS->Addr + OS->Size < OS->Addr) ||
2099         (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2100       errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2101                   " of size 0x" + utohexstr(OS->Size) +
2102                   " exceeds available address space");
2103 
2104   // Check for overlapping file offsets. In this case we need to skip any
2105   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2106   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2107   // binary is specified only add SHF_ALLOC sections are added to the output
2108   // file so we skip any non-allocated sections in that case.
2109   std::vector<SectionOffset> FileOffs;
2110   for (OutputSection *Sec : OutputSections)
2111     if (0 < Sec->Size && Sec->Type != SHT_NOBITS &&
2112         (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2113       FileOffs.push_back({Sec, Sec->Offset});
2114   checkOverlap("file", FileOffs);
2115 
2116   // When linking with -r there is no need to check for overlapping virtual/load
2117   // addresses since those addresses will only be assigned when the final
2118   // executable/shared object is created.
2119   if (Config->Relocatable)
2120     return;
2121 
2122   // Checking for overlapping virtual and load addresses only needs to take
2123   // into account SHF_ALLOC sections since others will not be loaded.
2124   // Furthermore, we also need to skip SHF_TLS sections since these will be
2125   // mapped to other addresses at runtime and can therefore have overlapping
2126   // ranges in the file.
2127   std::vector<SectionOffset> VMAs;
2128   for (OutputSection *Sec : OutputSections)
2129     if (0 < Sec->Size && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2130       VMAs.push_back({Sec, Sec->Addr});
2131   checkOverlap("virtual address", VMAs);
2132 
2133   // Finally, check that the load addresses don't overlap. This will usually be
2134   // the same as the virtual addresses but can be different when using a linker
2135   // script with AT().
2136   std::vector<SectionOffset> LMAs;
2137   for (OutputSection *Sec : OutputSections)
2138     if (0 < Sec->Size && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2139       LMAs.push_back({Sec, Sec->getLMA()});
2140   checkOverlap("load address", LMAs);
2141 }
2142 
2143 // The entry point address is chosen in the following ways.
2144 //
2145 // 1. the '-e' entry command-line option;
2146 // 2. the ENTRY(symbol) command in a linker control script;
2147 // 3. the value of the symbol _start, if present;
2148 // 4. the number represented by the entry symbol, if it is a number;
2149 // 5. the address of the first byte of the .text section, if present;
2150 // 6. the address 0.
2151 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
2152   // Case 1, 2 or 3
2153   if (Symbol *B = Symtab->find(Config->Entry))
2154     return B->getVA();
2155 
2156   // Case 4
2157   uint64_t Addr;
2158   if (to_integer(Config->Entry, Addr))
2159     return Addr;
2160 
2161   // Case 5
2162   if (OutputSection *Sec = findSection(".text")) {
2163     if (Config->WarnMissingEntry)
2164       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2165            utohexstr(Sec->Addr));
2166     return Sec->Addr;
2167   }
2168 
2169   // Case 6
2170   if (Config->WarnMissingEntry)
2171     warn("cannot find entry symbol " + Config->Entry +
2172          "; not setting start address");
2173   return 0;
2174 }
2175 
2176 static uint16_t getELFType() {
2177   if (Config->Pic)
2178     return ET_DYN;
2179   if (Config->Relocatable)
2180     return ET_REL;
2181   return ET_EXEC;
2182 }
2183 
2184 static uint8_t getAbiVersion() {
2185   // MIPS non-PIC executable gets ABI version 1.
2186   if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2187       (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2188     return 1;
2189   return 0;
2190 }
2191 
2192 template <class ELFT> void Writer<ELFT>::writeHeader() {
2193   uint8_t *Buf = Buffer->getBufferStart();
2194   // For executable segments, the trap instructions are written before writing
2195   // the header. Setting Elf header bytes to zero ensures that any unused bytes
2196   // in header are zero-cleared, instead of having trap instructions.
2197   memset(Buf, 0, sizeof(Elf_Ehdr));
2198   memcpy(Buf, "\177ELF", 4);
2199 
2200   // Write the ELF header.
2201   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2202   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2203   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2204   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2205   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2206   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2207   EHdr->e_type = getELFType();
2208   EHdr->e_machine = Config->EMachine;
2209   EHdr->e_version = EV_CURRENT;
2210   EHdr->e_entry = getEntryAddr();
2211   EHdr->e_shoff = SectionHeaderOff;
2212   EHdr->e_flags = Config->EFlags;
2213   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2214   EHdr->e_phnum = Phdrs.size();
2215   EHdr->e_shentsize = sizeof(Elf_Shdr);
2216   EHdr->e_shnum = OutputSections.size() + 1;
2217   EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex;
2218 
2219   if (!Config->Relocatable) {
2220     EHdr->e_phoff = sizeof(Elf_Ehdr);
2221     EHdr->e_phentsize = sizeof(Elf_Phdr);
2222   }
2223 
2224   // Write the program header table.
2225   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2226   for (PhdrEntry *P : Phdrs) {
2227     HBuf->p_type = P->p_type;
2228     HBuf->p_flags = P->p_flags;
2229     HBuf->p_offset = P->p_offset;
2230     HBuf->p_vaddr = P->p_vaddr;
2231     HBuf->p_paddr = P->p_paddr;
2232     HBuf->p_filesz = P->p_filesz;
2233     HBuf->p_memsz = P->p_memsz;
2234     HBuf->p_align = P->p_align;
2235     ++HBuf;
2236   }
2237 
2238   // Write the section header table. Note that the first table entry is null.
2239   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2240   for (OutputSection *Sec : OutputSections)
2241     Sec->writeHeaderTo<ELFT>(++SHdrs);
2242 }
2243 
2244 // Open a result file.
2245 template <class ELFT> void Writer<ELFT>::openFile() {
2246   if (!Config->Is64 && FileSize > UINT32_MAX) {
2247     error("output file too large: " + Twine(FileSize) + " bytes");
2248     return;
2249   }
2250 
2251   unlinkAsync(Config->OutputFile);
2252   unsigned Flags = 0;
2253   if (!Config->Relocatable)
2254     Flags = FileOutputBuffer::F_executable;
2255   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2256       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2257 
2258   if (!BufferOrErr)
2259     error("failed to open " + Config->OutputFile + ": " +
2260           llvm::toString(BufferOrErr.takeError()));
2261   else
2262     Buffer = std::move(*BufferOrErr);
2263 }
2264 
2265 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2266   uint8_t *Buf = Buffer->getBufferStart();
2267   for (OutputSection *Sec : OutputSections)
2268     if (Sec->Flags & SHF_ALLOC)
2269       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2270 }
2271 
2272 static void fillTrap(uint8_t *I, uint8_t *End) {
2273   for (; I + 4 <= End; I += 4)
2274     memcpy(I, &Target->TrapInstr, 4);
2275 }
2276 
2277 // Fill the last page of executable segments with trap instructions
2278 // instead of leaving them as zero. Even though it is not required by any
2279 // standard, it is in general a good thing to do for security reasons.
2280 //
2281 // We'll leave other pages in segments as-is because the rest will be
2282 // overwritten by output sections.
2283 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2284   if (Script->HasSectionsCommand)
2285     return;
2286 
2287   // Fill the last page.
2288   uint8_t *Buf = Buffer->getBufferStart();
2289   for (PhdrEntry *P : Phdrs)
2290     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2291       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2292                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2293 
2294   // Round up the file size of the last segment to the page boundary iff it is
2295   // an executable segment to ensure that other tools don't accidentally
2296   // trim the instruction padding (e.g. when stripping the file).
2297   PhdrEntry *Last = nullptr;
2298   for (PhdrEntry *P : Phdrs)
2299     if (P->p_type == PT_LOAD)
2300       Last = P;
2301 
2302   if (Last && (Last->p_flags & PF_X))
2303     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2304 }
2305 
2306 // Write section contents to a mmap'ed file.
2307 template <class ELFT> void Writer<ELFT>::writeSections() {
2308   uint8_t *Buf = Buffer->getBufferStart();
2309 
2310   OutputSection *EhFrameHdr = nullptr;
2311   if (InX::EhFrameHdr && !InX::EhFrameHdr->empty())
2312     EhFrameHdr = InX::EhFrameHdr->getParent();
2313 
2314   // In -r or -emit-relocs mode, write the relocation sections first as in
2315   // ELf_Rel targets we might find out that we need to modify the relocated
2316   // section while doing it.
2317   for (OutputSection *Sec : OutputSections)
2318     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2319       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2320 
2321   for (OutputSection *Sec : OutputSections)
2322     if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2323       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2324 
2325   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2326   // it should be written after .eh_frame is written.
2327   if (EhFrameHdr)
2328     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2329 }
2330 
2331 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2332   if (!InX::BuildId || !InX::BuildId->getParent())
2333     return;
2334 
2335   // Compute a hash of all sections of the output file.
2336   uint8_t *Start = Buffer->getBufferStart();
2337   uint8_t *End = Start + FileSize;
2338   InX::BuildId->writeBuildId({Start, End});
2339 }
2340 
2341 template void elf::writeResult<ELF32LE>();
2342 template void elf::writeResult<ELF32BE>();
2343 template void elf::writeResult<ELF64LE>();
2344 template void elf::writeResult<ELF64BE>();
2345