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