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