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