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