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