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