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