xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 796ac80b)
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->PPC64SmallCodeModelRelocs &&
1266                               !B->File->PPC64SmallCodeModelRelocs;
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   if (In.Plt && !In.Plt->empty())
1681     In.Plt->addSymbols();
1682   if (In.Iplt && !In.Iplt->empty())
1683     In.Iplt->addSymbols();
1684 
1685   if (!Config->AllowShlibUndefined) {
1686     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1687     // entires are seen. These cases would otherwise lead to runtime errors
1688     // reported by the dynamic linker.
1689     //
1690     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1691     // catch more cases. That is too much for us. Our approach resembles the one
1692     // used in ld.gold, achieves a good balance to be useful but not too smart.
1693     for (InputFile *File : SharedFiles) {
1694       SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1695       F->AllNeededIsKnown = llvm::all_of(F->DtNeeded, [&](StringRef Needed) {
1696         return Symtab->SoNames.count(Needed);
1697       });
1698     }
1699     for (Symbol *Sym : Symtab->getSymbols())
1700       if (Sym->isUndefined() && !Sym->isWeak())
1701         if (auto *F = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1702           if (F->AllNeededIsKnown)
1703             error(toString(F) + ": undefined reference to " + toString(*Sym));
1704   }
1705 
1706   // Now that we have defined all possible global symbols including linker-
1707   // synthesized ones. Visit all symbols to give the finishing touches.
1708   for (Symbol *Sym : Symtab->getSymbols()) {
1709     if (!includeInSymtab(*Sym))
1710       continue;
1711     if (In.SymTab)
1712       In.SymTab->addSymbol(Sym);
1713 
1714     if (Sym->includeInDynsym()) {
1715       In.DynSymTab->addSymbol(Sym);
1716       if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1717         if (File->IsNeeded && !Sym->isUndefined())
1718           InX<ELFT>::VerNeed->addSymbol(Sym);
1719     }
1720   }
1721 
1722   // Do not proceed if there was an undefined symbol.
1723   if (errorCount())
1724     return;
1725 
1726   if (In.MipsGot)
1727     In.MipsGot->build<ELFT>();
1728 
1729   removeUnusedSyntheticSections();
1730 
1731   sortSections();
1732 
1733   // Now that we have the final list, create a list of all the
1734   // OutputSections for convenience.
1735   for (BaseCommand *Base : Script->SectionCommands)
1736     if (auto *Sec = dyn_cast<OutputSection>(Base))
1737       OutputSections.push_back(Sec);
1738 
1739   // Prefer command line supplied address over other constraints.
1740   for (OutputSection *Sec : OutputSections) {
1741     auto I = Config->SectionStartMap.find(Sec->Name);
1742     if (I != Config->SectionStartMap.end())
1743       Sec->AddrExpr = [=] { return I->second; };
1744   }
1745 
1746   // This is a bit of a hack. A value of 0 means undef, so we set it
1747   // to 1 to make __ehdr_start defined. The section number is not
1748   // particularly relevant.
1749   Out::ElfHeader->SectionIndex = 1;
1750 
1751   for (size_t I = 0, E = OutputSections.size(); I != E; ++I) {
1752     OutputSection *Sec = OutputSections[I];
1753     Sec->SectionIndex = I + 1;
1754     Sec->ShName = In.ShStrTab->addString(Sec->Name);
1755   }
1756 
1757   // Binary and relocatable output does not have PHDRS.
1758   // The headers have to be created before finalize as that can influence the
1759   // image base and the dynamic section on mips includes the image base.
1760   if (!Config->Relocatable && !Config->OFormatBinary) {
1761     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1762     addPtArmExid(Phdrs);
1763     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1764 
1765     // Find the TLS segment. This happens before the section layout loop so that
1766     // Android relocation packing can look up TLS symbol addresses.
1767     for (PhdrEntry *P : Phdrs)
1768       if (P->p_type == PT_TLS)
1769         Out::TlsPhdr = P;
1770   }
1771 
1772   // Some symbols are defined in term of program headers. Now that we
1773   // have the headers, we can find out which sections they point to.
1774   setReservedSymbolSections();
1775 
1776   // Dynamic section must be the last one in this list and dynamic
1777   // symbol table section (DynSymTab) must be the first one.
1778   finalizeSynthetic(In.DynSymTab);
1779   finalizeSynthetic(In.Bss);
1780   finalizeSynthetic(In.BssRelRo);
1781   finalizeSynthetic(In.GnuHashTab);
1782   finalizeSynthetic(In.HashTab);
1783   finalizeSynthetic(In.SymTabShndx);
1784   finalizeSynthetic(In.ShStrTab);
1785   finalizeSynthetic(In.StrTab);
1786   finalizeSynthetic(In.VerDef);
1787   finalizeSynthetic(In.DynStrTab);
1788   finalizeSynthetic(In.Got);
1789   finalizeSynthetic(In.MipsGot);
1790   finalizeSynthetic(In.IgotPlt);
1791   finalizeSynthetic(In.GotPlt);
1792   finalizeSynthetic(In.RelaDyn);
1793   finalizeSynthetic(In.RelrDyn);
1794   finalizeSynthetic(In.RelaIplt);
1795   finalizeSynthetic(In.RelaPlt);
1796   finalizeSynthetic(In.Plt);
1797   finalizeSynthetic(In.Iplt);
1798   finalizeSynthetic(In.EhFrameHdr);
1799   finalizeSynthetic(InX<ELFT>::VerSym);
1800   finalizeSynthetic(InX<ELFT>::VerNeed);
1801   finalizeSynthetic(In.Dynamic);
1802 
1803   if (!Script->HasSectionsCommand && !Config->Relocatable)
1804     fixSectionAlignments();
1805 
1806   // After link order processing .ARM.exidx sections can be deduplicated, which
1807   // needs to be resolved before any other address dependent operation.
1808   resolveShfLinkOrder();
1809 
1810   // Jump instructions in many ISAs have small displacements, and therefore they
1811   // cannot jump to arbitrary addresses in memory. For example, RISC-V JAL
1812   // instruction can target only +-1 MiB from PC. It is a linker's
1813   // responsibility to create and insert small pieces of code between sections
1814   // to extend the ranges if jump targets are out of range. Such code pieces are
1815   // called "thunks".
1816   //
1817   // We add thunks at this stage. We couldn't do this before this point because
1818   // this is the earliest point where we know sizes of sections and their
1819   // layouts (that are needed to determine if jump targets are in range).
1820   maybeAddThunks();
1821 
1822   // maybeAddThunks may have added local symbols to the static symbol table.
1823   finalizeSynthetic(In.SymTab);
1824   finalizeSynthetic(In.PPC64LongBranchTarget);
1825 
1826   // Fill other section headers. The dynamic table is finalized
1827   // at the end because some tags like RELSZ depend on result
1828   // of finalizing other sections.
1829   for (OutputSection *Sec : OutputSections)
1830     Sec->finalize<ELFT>();
1831 }
1832 
1833 // Ensure data sections are not mixed with executable sections when
1834 // -execute-only is used. -execute-only is a feature to make pages executable
1835 // but not readable, and the feature is currently supported only on AArch64.
1836 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1837   if (!Config->ExecuteOnly)
1838     return;
1839 
1840   for (OutputSection *OS : OutputSections)
1841     if (OS->Flags & SHF_EXECINSTR)
1842       for (InputSection *IS : getInputSections(OS))
1843         if (!(IS->Flags & SHF_EXECINSTR))
1844           error("cannot place " + toString(IS) + " into " + toString(OS->Name) +
1845                 ": -execute-only does not support intermingling data and code");
1846 }
1847 
1848 // The linker is expected to define SECNAME_start and SECNAME_end
1849 // symbols for a few sections. This function defines them.
1850 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1851   // If a section does not exist, there's ambiguity as to how we
1852   // define _start and _end symbols for an init/fini section. Since
1853   // the loader assume that the symbols are always defined, we need to
1854   // always define them. But what value? The loader iterates over all
1855   // pointers between _start and _end to run global ctors/dtors, so if
1856   // the section is empty, their symbol values don't actually matter
1857   // as long as _start and _end point to the same location.
1858   //
1859   // That said, we don't want to set the symbols to 0 (which is
1860   // probably the simplest value) because that could cause some
1861   // program to fail to link due to relocation overflow, if their
1862   // program text is above 2 GiB. We use the address of the .text
1863   // section instead to prevent that failure.
1864   //
1865   // In a rare sitaution, .text section may not exist. If that's the
1866   // case, use the image base address as a last resort.
1867   OutputSection *Default = findSection(".text");
1868   if (!Default)
1869     Default = Out::ElfHeader;
1870 
1871   auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1872     if (OS) {
1873       addOptionalRegular(Start, OS, 0);
1874       addOptionalRegular(End, OS, -1);
1875     } else {
1876       addOptionalRegular(Start, Default, 0);
1877       addOptionalRegular(End, Default, 0);
1878     }
1879   };
1880 
1881   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1882   Define("__init_array_start", "__init_array_end", Out::InitArray);
1883   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1884 
1885   if (OutputSection *Sec = findSection(".ARM.exidx"))
1886     Define("__exidx_start", "__exidx_end", Sec);
1887 }
1888 
1889 // If a section name is valid as a C identifier (which is rare because of
1890 // the leading '.'), linkers are expected to define __start_<secname> and
1891 // __stop_<secname> symbols. They are at beginning and end of the section,
1892 // respectively. This is not requested by the ELF standard, but GNU ld and
1893 // gold provide the feature, and used by many programs.
1894 template <class ELFT>
1895 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1896   StringRef S = Sec->Name;
1897   if (!isValidCIdentifier(S))
1898     return;
1899   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1900   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1901 }
1902 
1903 static bool needsPtLoad(OutputSection *Sec) {
1904   if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1905     return false;
1906 
1907   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1908   // responsible for allocating space for them, not the PT_LOAD that
1909   // contains the TLS initialization image.
1910   if ((Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS)
1911     return false;
1912   return true;
1913 }
1914 
1915 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1916 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1917 // RW. This means that there is no alignment in the RO to RX transition and we
1918 // cannot create a PT_LOAD there.
1919 static uint64_t computeFlags(uint64_t Flags) {
1920   if (Config->Omagic)
1921     return PF_R | PF_W | PF_X;
1922   if (Config->ExecuteOnly && (Flags & PF_X))
1923     return Flags & ~PF_R;
1924   if (Config->SingleRoRx && !(Flags & PF_W))
1925     return Flags | PF_X;
1926   return Flags;
1927 }
1928 
1929 // Decide which program headers to create and which sections to include in each
1930 // one.
1931 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1932   std::vector<PhdrEntry *> Ret;
1933   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1934     Ret.push_back(make<PhdrEntry>(Type, Flags));
1935     return Ret.back();
1936   };
1937 
1938   // The first phdr entry is PT_PHDR which describes the program header itself.
1939   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1940 
1941   // PT_INTERP must be the second entry if exists.
1942   if (OutputSection *Cmd = findSection(".interp"))
1943     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1944 
1945   // Add the first PT_LOAD segment for regular output sections.
1946   uint64_t Flags = computeFlags(PF_R);
1947   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1948 
1949   // Add the headers. We will remove them if they don't fit.
1950   Load->add(Out::ElfHeader);
1951   Load->add(Out::ProgramHeaders);
1952 
1953   for (OutputSection *Sec : OutputSections) {
1954     if (!(Sec->Flags & SHF_ALLOC))
1955       break;
1956     if (!needsPtLoad(Sec))
1957       continue;
1958 
1959     // Segments are contiguous memory regions that has the same attributes
1960     // (e.g. executable or writable). There is one phdr for each segment.
1961     // Therefore, we need to create a new phdr when the next section has
1962     // different flags or is loaded at a discontiguous address or memory
1963     // region using AT or AT> linker script command, respectively. At the same
1964     // time, we don't want to create a separate load segment for the headers,
1965     // even if the first output section has an AT or AT> attribute.
1966     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1967     if (((Sec->LMAExpr ||
1968           (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) &&
1969          Load->LastSec != Out::ProgramHeaders) ||
1970         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1971 
1972       Load = AddHdr(PT_LOAD, NewFlags);
1973       Flags = NewFlags;
1974     }
1975 
1976     Load->add(Sec);
1977   }
1978 
1979   // Add a TLS segment if any.
1980   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1981   for (OutputSection *Sec : OutputSections)
1982     if (Sec->Flags & SHF_TLS)
1983       TlsHdr->add(Sec);
1984   if (TlsHdr->FirstSec)
1985     Ret.push_back(TlsHdr);
1986 
1987   // Add an entry for .dynamic.
1988   if (OutputSection *Sec = In.Dynamic->getParent())
1989     AddHdr(PT_DYNAMIC, Sec->getPhdrFlags())->add(Sec);
1990 
1991   // PT_GNU_RELRO includes all sections that should be marked as
1992   // read-only by dynamic linker after proccessing relocations.
1993   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1994   // an error message if more than one PT_GNU_RELRO PHDR is required.
1995   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1996   bool InRelroPhdr = false;
1997   bool IsRelroFinished = false;
1998   for (OutputSection *Sec : OutputSections) {
1999     if (!needsPtLoad(Sec))
2000       continue;
2001     if (isRelroSection(Sec)) {
2002       InRelroPhdr = true;
2003       if (!IsRelroFinished)
2004         RelRo->add(Sec);
2005       else
2006         error("section: " + Sec->Name + " is not contiguous with other relro" +
2007               " sections");
2008     } else if (InRelroPhdr) {
2009       InRelroPhdr = false;
2010       IsRelroFinished = true;
2011     }
2012   }
2013   if (RelRo->FirstSec)
2014     Ret.push_back(RelRo);
2015 
2016   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2017   if (!In.EhFrame->empty() && In.EhFrameHdr && In.EhFrame->getParent() &&
2018       In.EhFrameHdr->getParent())
2019     AddHdr(PT_GNU_EH_FRAME, In.EhFrameHdr->getParent()->getPhdrFlags())
2020         ->add(In.EhFrameHdr->getParent());
2021 
2022   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2023   // the dynamic linker fill the segment with random data.
2024   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
2025     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
2026 
2027   // PT_GNU_STACK is a special section to tell the loader to make the
2028   // pages for the stack non-executable. If you really want an executable
2029   // stack, you can pass -z execstack, but that's not recommended for
2030   // security reasons.
2031   unsigned Perm = PF_R | PF_W;
2032   if (Config->ZExecstack)
2033     Perm |= PF_X;
2034   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
2035 
2036   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2037   // is expected to perform W^X violations, such as calling mprotect(2) or
2038   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2039   // OpenBSD.
2040   if (Config->ZWxneeded)
2041     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
2042 
2043   // Create one PT_NOTE per a group of contiguous .note sections.
2044   PhdrEntry *Note = nullptr;
2045   for (OutputSection *Sec : OutputSections) {
2046     if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
2047       if (!Note || Sec->LMAExpr)
2048         Note = AddHdr(PT_NOTE, PF_R);
2049       Note->add(Sec);
2050     } else {
2051       Note = nullptr;
2052     }
2053   }
2054   return Ret;
2055 }
2056 
2057 template <class ELFT>
2058 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
2059   if (Config->EMachine != EM_ARM)
2060     return;
2061   auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
2062     return Cmd->Type == SHT_ARM_EXIDX;
2063   });
2064   if (I == OutputSections.end())
2065     return;
2066 
2067   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2068   PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
2069   ARMExidx->add(*I);
2070   Phdrs.push_back(ARMExidx);
2071 }
2072 
2073 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2074 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2075 // linker can set the permissions.
2076 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2077   auto PageAlign = [](OutputSection *Cmd) {
2078     if (Cmd && !Cmd->AddrExpr)
2079       Cmd->AddrExpr = [=] {
2080         return alignTo(Script->getDot(), Config->MaxPageSize);
2081       };
2082   };
2083 
2084   for (const PhdrEntry *P : Phdrs)
2085     if (P->p_type == PT_LOAD && P->FirstSec)
2086       PageAlign(P->FirstSec);
2087 
2088   for (const PhdrEntry *P : Phdrs) {
2089     if (P->p_type != PT_GNU_RELRO)
2090       continue;
2091 
2092     if (P->FirstSec)
2093       PageAlign(P->FirstSec);
2094 
2095     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
2096     // have to align it to a page.
2097     auto End = OutputSections.end();
2098     auto I = std::find(OutputSections.begin(), End, P->LastSec);
2099     if (I == End || (I + 1) == End)
2100       continue;
2101 
2102     OutputSection *Cmd = (*(I + 1));
2103     if (needsPtLoad(Cmd))
2104       PageAlign(Cmd);
2105   }
2106 }
2107 
2108 // Compute an in-file position for a given section. The file offset must be the
2109 // same with its virtual address modulo the page size, so that the loader can
2110 // load executables without any address adjustment.
2111 static uint64_t computeFileOffset(OutputSection *OS, uint64_t Off) {
2112   // File offsets are not significant for .bss sections. By convention, we keep
2113   // section offsets monotonically increasing rather than setting to zero.
2114   if (OS->Type == SHT_NOBITS)
2115     return Off;
2116 
2117   // If the section is not in a PT_LOAD, we just have to align it.
2118   if (!OS->PtLoad)
2119     return alignTo(Off, OS->Alignment);
2120 
2121   // The first section in a PT_LOAD has to have congruent offset and address
2122   // module the page size.
2123   OutputSection *First = OS->PtLoad->FirstSec;
2124   if (OS == First) {
2125     uint64_t Alignment = std::max<uint64_t>(OS->Alignment, Config->MaxPageSize);
2126     return alignTo(Off, Alignment, OS->Addr);
2127   }
2128 
2129   // If two sections share the same PT_LOAD the file offset is calculated
2130   // using this formula: Off2 = Off1 + (VA2 - VA1).
2131   return First->Offset + OS->Addr - First->Addr;
2132 }
2133 
2134 // Set an in-file position to a given section and returns the end position of
2135 // the section.
2136 static uint64_t setFileOffset(OutputSection *OS, uint64_t Off) {
2137   Off = computeFileOffset(OS, Off);
2138   OS->Offset = Off;
2139 
2140   if (OS->Type == SHT_NOBITS)
2141     return Off;
2142   return Off + OS->Size;
2143 }
2144 
2145 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2146   uint64_t Off = 0;
2147   for (OutputSection *Sec : OutputSections)
2148     if (Sec->Flags & SHF_ALLOC)
2149       Off = setFileOffset(Sec, Off);
2150   FileSize = alignTo(Off, Config->Wordsize);
2151 }
2152 
2153 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
2154   return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
2155 }
2156 
2157 // Assign file offsets to output sections.
2158 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2159   uint64_t Off = 0;
2160   Off = setFileOffset(Out::ElfHeader, Off);
2161   Off = setFileOffset(Out::ProgramHeaders, Off);
2162 
2163   PhdrEntry *LastRX = nullptr;
2164   for (PhdrEntry *P : Phdrs)
2165     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2166       LastRX = P;
2167 
2168   for (OutputSection *Sec : OutputSections) {
2169     Off = setFileOffset(Sec, Off);
2170     if (Script->HasSectionsCommand)
2171       continue;
2172 
2173     // If this is a last section of the last executable segment and that
2174     // segment is the last loadable segment, align the offset of the
2175     // following section to avoid loading non-segments parts of the file.
2176     if (LastRX && LastRX->LastSec == Sec)
2177       Off = alignTo(Off, Target->PageSize);
2178   }
2179 
2180   SectionHeaderOff = alignTo(Off, Config->Wordsize);
2181   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2182 
2183   // Our logic assumes that sections have rising VA within the same segment.
2184   // With use of linker scripts it is possible to violate this rule and get file
2185   // offset overlaps or overflows. That should never happen with a valid script
2186   // which does not move the location counter backwards and usually scripts do
2187   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2188   // kernel, which control segment distribution explicitly and move the counter
2189   // backwards, so we have to allow doing that to support linking them. We
2190   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2191   // we want to prevent file size overflows because it would crash the linker.
2192   for (OutputSection *Sec : OutputSections) {
2193     if (Sec->Type == SHT_NOBITS)
2194       continue;
2195     if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2196       error("unable to place section " + Sec->Name + " at file offset " +
2197             rangeToString(Sec->Offset, Sec->Size) +
2198             "; check your linker script for overflows");
2199   }
2200 }
2201 
2202 // Finalize the program headers. We call this function after we assign
2203 // file offsets and VAs to all sections.
2204 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2205   for (PhdrEntry *P : Phdrs) {
2206     OutputSection *First = P->FirstSec;
2207     OutputSection *Last = P->LastSec;
2208 
2209     if (First) {
2210       P->p_filesz = Last->Offset - First->Offset;
2211       if (Last->Type != SHT_NOBITS)
2212         P->p_filesz += Last->Size;
2213 
2214       P->p_memsz = Last->Addr + Last->Size - First->Addr;
2215       P->p_offset = First->Offset;
2216       P->p_vaddr = First->Addr;
2217 
2218       if (!P->HasLMA)
2219         P->p_paddr = First->getLMA();
2220     }
2221 
2222     if (P->p_type == PT_LOAD) {
2223       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2224     } else if (P->p_type == PT_GNU_RELRO) {
2225       P->p_align = 1;
2226       // The glibc dynamic loader rounds the size down, so we need to round up
2227       // to protect the last page. This is a no-op on FreeBSD which always
2228       // rounds up.
2229       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2230     }
2231 
2232     if (P->p_type == PT_TLS && P->p_memsz) {
2233       if (!Config->Shared &&
2234           (Config->EMachine == EM_ARM || Config->EMachine == EM_AARCH64)) {
2235         // On ARM/AArch64, reserve extra space (8 words) between the thread
2236         // pointer and an executable's TLS segment by overaligning the segment.
2237         // This reservation is needed for backwards compatibility with Android's
2238         // TCB, which allocates several slots after the thread pointer (e.g.
2239         // TLS_SLOT_STACK_GUARD==5). For simplicity, this overalignment is also
2240         // done on other operating systems.
2241         P->p_align = std::max<uint64_t>(P->p_align, Config->Wordsize * 8);
2242       }
2243 
2244       // The TLS pointer goes after PT_TLS for variant 2 targets. At least glibc
2245       // will align it, so round up the size to make sure the offsets are
2246       // correct.
2247       P->p_memsz = alignTo(P->p_memsz, P->p_align);
2248     }
2249   }
2250 }
2251 
2252 // A helper struct for checkSectionOverlap.
2253 namespace {
2254 struct SectionOffset {
2255   OutputSection *Sec;
2256   uint64_t Offset;
2257 };
2258 } // namespace
2259 
2260 // Check whether sections overlap for a specific address range (file offsets,
2261 // load and virtual adresses).
2262 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2263                          bool IsVirtualAddr) {
2264   llvm::sort(Sections, [=](const SectionOffset &A, const SectionOffset &B) {
2265     return A.Offset < B.Offset;
2266   });
2267 
2268   // Finding overlap is easy given a vector is sorted by start position.
2269   // If an element starts before the end of the previous element, they overlap.
2270   for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2271     SectionOffset A = Sections[I - 1];
2272     SectionOffset B = Sections[I];
2273     if (B.Offset >= A.Offset + A.Sec->Size)
2274       continue;
2275 
2276     // If both sections are in OVERLAY we allow the overlapping of virtual
2277     // addresses, because it is what OVERLAY was designed for.
2278     if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2279       continue;
2280 
2281     errorOrWarn("section " + A.Sec->Name + " " + Name +
2282                 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2283                 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2284                 B.Sec->Name + " range is " +
2285                 rangeToString(B.Offset, B.Sec->Size));
2286   }
2287 }
2288 
2289 // Check for overlapping sections and address overflows.
2290 //
2291 // In this function we check that none of the output sections have overlapping
2292 // file offsets. For SHF_ALLOC sections we also check that the load address
2293 // ranges and the virtual address ranges don't overlap
2294 template <class ELFT> void Writer<ELFT>::checkSections() {
2295   // First, check that section's VAs fit in available address space for target.
2296   for (OutputSection *OS : OutputSections)
2297     if ((OS->Addr + OS->Size < OS->Addr) ||
2298         (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2299       errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2300                   " of size 0x" + utohexstr(OS->Size) +
2301                   " exceeds available address space");
2302 
2303   // Check for overlapping file offsets. In this case we need to skip any
2304   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2305   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2306   // binary is specified only add SHF_ALLOC sections are added to the output
2307   // file so we skip any non-allocated sections in that case.
2308   std::vector<SectionOffset> FileOffs;
2309   for (OutputSection *Sec : OutputSections)
2310     if (Sec->Size > 0 && Sec->Type != SHT_NOBITS &&
2311         (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2312       FileOffs.push_back({Sec, Sec->Offset});
2313   checkOverlap("file", FileOffs, false);
2314 
2315   // When linking with -r there is no need to check for overlapping virtual/load
2316   // addresses since those addresses will only be assigned when the final
2317   // executable/shared object is created.
2318   if (Config->Relocatable)
2319     return;
2320 
2321   // Checking for overlapping virtual and load addresses only needs to take
2322   // into account SHF_ALLOC sections since others will not be loaded.
2323   // Furthermore, we also need to skip SHF_TLS sections since these will be
2324   // mapped to other addresses at runtime and can therefore have overlapping
2325   // ranges in the file.
2326   std::vector<SectionOffset> VMAs;
2327   for (OutputSection *Sec : OutputSections)
2328     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2329       VMAs.push_back({Sec, Sec->Addr});
2330   checkOverlap("virtual address", VMAs, true);
2331 
2332   // Finally, check that the load addresses don't overlap. This will usually be
2333   // the same as the virtual addresses but can be different when using a linker
2334   // script with AT().
2335   std::vector<SectionOffset> LMAs;
2336   for (OutputSection *Sec : OutputSections)
2337     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2338       LMAs.push_back({Sec, Sec->getLMA()});
2339   checkOverlap("load address", LMAs, false);
2340 }
2341 
2342 // The entry point address is chosen in the following ways.
2343 //
2344 // 1. the '-e' entry command-line option;
2345 // 2. the ENTRY(symbol) command in a linker control script;
2346 // 3. the value of the symbol _start, if present;
2347 // 4. the number represented by the entry symbol, if it is a number;
2348 // 5. the address of the first byte of the .text section, if present;
2349 // 6. the address 0.
2350 static uint64_t getEntryAddr() {
2351   // Case 1, 2 or 3
2352   if (Symbol *B = Symtab->find(Config->Entry))
2353     return B->getVA();
2354 
2355   // Case 4
2356   uint64_t Addr;
2357   if (to_integer(Config->Entry, Addr))
2358     return Addr;
2359 
2360   // Case 5
2361   if (OutputSection *Sec = findSection(".text")) {
2362     if (Config->WarnMissingEntry)
2363       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2364            utohexstr(Sec->Addr));
2365     return Sec->Addr;
2366   }
2367 
2368   // Case 6
2369   if (Config->WarnMissingEntry)
2370     warn("cannot find entry symbol " + Config->Entry +
2371          "; not setting start address");
2372   return 0;
2373 }
2374 
2375 static uint16_t getELFType() {
2376   if (Config->Pic)
2377     return ET_DYN;
2378   if (Config->Relocatable)
2379     return ET_REL;
2380   return ET_EXEC;
2381 }
2382 
2383 static uint8_t getAbiVersion() {
2384   // MIPS non-PIC executable gets ABI version 1.
2385   if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2386       (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2387     return 1;
2388   return 0;
2389 }
2390 
2391 template <class ELFT> void Writer<ELFT>::writeHeader() {
2392   uint8_t *Buf = Buffer->getBufferStart();
2393 
2394   // For executable segments, the trap instructions are written before writing
2395   // the header. Setting Elf header bytes to zero ensures that any unused bytes
2396   // in header are zero-cleared, instead of having trap instructions.
2397   memset(Buf, 0, sizeof(Elf_Ehdr));
2398   memcpy(Buf, "\177ELF", 4);
2399 
2400   // Write the ELF header.
2401   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2402   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2403   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2404   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2405   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2406   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2407   EHdr->e_type = getELFType();
2408   EHdr->e_machine = Config->EMachine;
2409   EHdr->e_version = EV_CURRENT;
2410   EHdr->e_entry = getEntryAddr();
2411   EHdr->e_shoff = SectionHeaderOff;
2412   EHdr->e_flags = Config->EFlags;
2413   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2414   EHdr->e_phnum = Phdrs.size();
2415   EHdr->e_shentsize = sizeof(Elf_Shdr);
2416 
2417   if (!Config->Relocatable) {
2418     EHdr->e_phoff = sizeof(Elf_Ehdr);
2419     EHdr->e_phentsize = sizeof(Elf_Phdr);
2420   }
2421 
2422   // Write the program header table.
2423   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2424   for (PhdrEntry *P : Phdrs) {
2425     HBuf->p_type = P->p_type;
2426     HBuf->p_flags = P->p_flags;
2427     HBuf->p_offset = P->p_offset;
2428     HBuf->p_vaddr = P->p_vaddr;
2429     HBuf->p_paddr = P->p_paddr;
2430     HBuf->p_filesz = P->p_filesz;
2431     HBuf->p_memsz = P->p_memsz;
2432     HBuf->p_align = P->p_align;
2433     ++HBuf;
2434   }
2435 
2436   // Write the section header table.
2437   //
2438   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2439   // and e_shstrndx fields. When the value of one of these fields exceeds
2440   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2441   // use fields in the section header at index 0 to store
2442   // the value. The sentinel values and fields are:
2443   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2444   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2445   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2446   size_t Num = OutputSections.size() + 1;
2447   if (Num >= SHN_LORESERVE)
2448     SHdrs->sh_size = Num;
2449   else
2450     EHdr->e_shnum = Num;
2451 
2452   uint32_t StrTabIndex = In.ShStrTab->getParent()->SectionIndex;
2453   if (StrTabIndex >= SHN_LORESERVE) {
2454     SHdrs->sh_link = StrTabIndex;
2455     EHdr->e_shstrndx = SHN_XINDEX;
2456   } else {
2457     EHdr->e_shstrndx = StrTabIndex;
2458   }
2459 
2460   for (OutputSection *Sec : OutputSections)
2461     Sec->writeHeaderTo<ELFT>(++SHdrs);
2462 }
2463 
2464 // Open a result file.
2465 template <class ELFT> void Writer<ELFT>::openFile() {
2466   uint64_t MaxSize = Config->Is64 ? INT64_MAX : UINT32_MAX;
2467   if (MaxSize < FileSize) {
2468     error("output file too large: " + Twine(FileSize) + " bytes");
2469     return;
2470   }
2471 
2472   unlinkAsync(Config->OutputFile);
2473   unsigned Flags = 0;
2474   if (!Config->Relocatable)
2475     Flags = FileOutputBuffer::F_executable;
2476   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2477       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2478 
2479   if (!BufferOrErr)
2480     error("failed to open " + Config->OutputFile + ": " +
2481           llvm::toString(BufferOrErr.takeError()));
2482   else
2483     Buffer = std::move(*BufferOrErr);
2484 }
2485 
2486 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2487   uint8_t *Buf = Buffer->getBufferStart();
2488   for (OutputSection *Sec : OutputSections)
2489     if (Sec->Flags & SHF_ALLOC)
2490       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2491 }
2492 
2493 static void fillTrap(uint8_t *I, uint8_t *End) {
2494   for (; I + 4 <= End; I += 4)
2495     memcpy(I, &Target->TrapInstr, 4);
2496 }
2497 
2498 // Fill the last page of executable segments with trap instructions
2499 // instead of leaving them as zero. Even though it is not required by any
2500 // standard, it is in general a good thing to do for security reasons.
2501 //
2502 // We'll leave other pages in segments as-is because the rest will be
2503 // overwritten by output sections.
2504 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2505   if (Script->HasSectionsCommand)
2506     return;
2507 
2508   // Fill the last page.
2509   uint8_t *Buf = Buffer->getBufferStart();
2510   for (PhdrEntry *P : Phdrs)
2511     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2512       fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2513                Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2514 
2515   // Round up the file size of the last segment to the page boundary iff it is
2516   // an executable segment to ensure that other tools don't accidentally
2517   // trim the instruction padding (e.g. when stripping the file).
2518   PhdrEntry *Last = nullptr;
2519   for (PhdrEntry *P : Phdrs)
2520     if (P->p_type == PT_LOAD)
2521       Last = P;
2522 
2523   if (Last && (Last->p_flags & PF_X))
2524     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2525 }
2526 
2527 // Write section contents to a mmap'ed file.
2528 template <class ELFT> void Writer<ELFT>::writeSections() {
2529   uint8_t *Buf = Buffer->getBufferStart();
2530 
2531   OutputSection *EhFrameHdr = nullptr;
2532   if (In.EhFrameHdr && !In.EhFrameHdr->empty())
2533     EhFrameHdr = In.EhFrameHdr->getParent();
2534 
2535   // In -r or -emit-relocs mode, write the relocation sections first as in
2536   // ELf_Rel targets we might find out that we need to modify the relocated
2537   // section while doing it.
2538   for (OutputSection *Sec : OutputSections)
2539     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2540       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2541 
2542   for (OutputSection *Sec : OutputSections)
2543     if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2544       Sec->writeTo<ELFT>(Buf + Sec->Offset);
2545 
2546   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2547   // it should be written after .eh_frame is written.
2548   if (EhFrameHdr)
2549     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2550 }
2551 
2552 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2553   if (!In.BuildId || !In.BuildId->getParent())
2554     return;
2555 
2556   // Compute a hash of all sections of the output file.
2557   uint8_t *Start = Buffer->getBufferStart();
2558   uint8_t *End = Start + FileSize;
2559   In.BuildId->writeBuildId({Start, End});
2560 }
2561 
2562 template void elf::writeResult<ELF32LE>();
2563 template void elf::writeResult<ELF32BE>();
2564 template void elf::writeResult<ELF64LE>();
2565 template void elf::writeResult<ELF64BE>();
2566