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