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