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