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