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