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