xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision d3d0ecbf)
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 || !CurSec->Live)
1098       continue;
1099     if (getRankProximity(Sec, CurSec) != Proximity ||
1100         Sec->SortRank < CurSec->SortRank)
1101       break;
1102   }
1103 
1104   auto IsLiveOutputSec = [](BaseCommand *Cmd) {
1105     auto *OS = dyn_cast<OutputSection>(Cmd);
1106     return OS && OS->Live;
1107   };
1108   auto J = std::find_if(llvm::make_reverse_iterator(I),
1109                         llvm::make_reverse_iterator(B), IsLiveOutputSec);
1110   I = J.base();
1111 
1112   // As a special case, if the orphan section is the last section, put
1113   // it at the very end, past any other commands.
1114   // This matches bfd's behavior and is convenient when the linker script fully
1115   // specifies the start of the file, but doesn't care about the end (the non
1116   // alloc sections for example).
1117   auto NextSec = std::find_if(I, E, IsLiveOutputSec);
1118   if (NextSec == E)
1119     return E;
1120 
1121   while (I != E && shouldSkip(*I))
1122     ++I;
1123   return I;
1124 }
1125 
1126 // Builds section order for handling --symbol-ordering-file.
1127 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1128   DenseMap<const InputSectionBase *, int> SectionOrder;
1129   // Use the rarely used option -call-graph-ordering-file to sort sections.
1130   if (!Config->CallGraphProfile.empty())
1131     return computeCallGraphProfileOrder();
1132 
1133   if (Config->SymbolOrderingFile.empty())
1134     return SectionOrder;
1135 
1136   struct SymbolOrderEntry {
1137     int Priority;
1138     bool Present;
1139   };
1140 
1141   // Build a map from symbols to their priorities. Symbols that didn't
1142   // appear in the symbol ordering file have the lowest priority 0.
1143   // All explicitly mentioned symbols have negative (higher) priorities.
1144   DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1145   int Priority = -Config->SymbolOrderingFile.size();
1146   for (StringRef S : Config->SymbolOrderingFile)
1147     SymbolOrder.insert({S, {Priority++, false}});
1148 
1149   // Build a map from sections to their priorities.
1150   auto AddSym = [&](Symbol &Sym) {
1151     auto It = SymbolOrder.find(Sym.getName());
1152     if (It == SymbolOrder.end())
1153       return;
1154     SymbolOrderEntry &Ent = It->second;
1155     Ent.Present = true;
1156 
1157     maybeWarnUnorderableSymbol(&Sym);
1158 
1159     if (auto *D = dyn_cast<Defined>(&Sym)) {
1160       if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1161         int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1162         Priority = std::min(Priority, Ent.Priority);
1163       }
1164     }
1165   };
1166 
1167   // We want both global and local symbols. We get the global ones from the
1168   // symbol table and iterate the object files for the local ones.
1169   for (Symbol *Sym : Symtab->getSymbols())
1170     if (!Sym->isLazy())
1171       AddSym(*Sym);
1172   for (InputFile *File : ObjectFiles)
1173     for (Symbol *Sym : File->getSymbols())
1174       if (Sym->isLocal())
1175         AddSym(*Sym);
1176 
1177   if (Config->WarnSymbolOrdering)
1178     for (auto OrderEntry : SymbolOrder)
1179       if (!OrderEntry.second.Present)
1180         warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1181 
1182   return SectionOrder;
1183 }
1184 
1185 // Sorts the sections in ISD according to the provided section order.
1186 static void
1187 sortISDBySectionOrder(InputSectionDescription *ISD,
1188                       const DenseMap<const InputSectionBase *, int> &Order) {
1189   std::vector<InputSection *> UnorderedSections;
1190   std::vector<std::pair<InputSection *, int>> OrderedSections;
1191   uint64_t UnorderedSize = 0;
1192 
1193   for (InputSection *IS : ISD->Sections) {
1194     auto I = Order.find(IS);
1195     if (I == Order.end()) {
1196       UnorderedSections.push_back(IS);
1197       UnorderedSize += IS->getSize();
1198       continue;
1199     }
1200     OrderedSections.push_back({IS, I->second});
1201   }
1202   llvm::sort(OrderedSections, [&](std::pair<InputSection *, int> A,
1203                                   std::pair<InputSection *, int> B) {
1204     return A.second < B.second;
1205   });
1206 
1207   // Find an insertion point for the ordered section list in the unordered
1208   // section list. On targets with limited-range branches, this is the mid-point
1209   // of the unordered section list. This decreases the likelihood that a range
1210   // extension thunk will be needed to enter or exit the ordered region. If the
1211   // ordered section list is a list of hot functions, we can generally expect
1212   // the ordered functions to be called more often than the unordered functions,
1213   // making it more likely that any particular call will be within range, and
1214   // therefore reducing the number of thunks required.
1215   //
1216   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1217   // If the layout is:
1218   //
1219   // 8MB hot
1220   // 32MB cold
1221   //
1222   // only the first 8-16MB of the cold code (depending on which hot function it
1223   // is actually calling) can call the hot code without a range extension thunk.
1224   // However, if we use this layout:
1225   //
1226   // 16MB cold
1227   // 8MB hot
1228   // 16MB cold
1229   //
1230   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1231   // of the second block of cold code can call the hot code without a thunk. So
1232   // we effectively double the amount of code that could potentially call into
1233   // the hot code without a thunk.
1234   size_t InsPt = 0;
1235   if (Target->getThunkSectionSpacing() && !OrderedSections.empty()) {
1236     uint64_t UnorderedPos = 0;
1237     for (; InsPt != UnorderedSections.size(); ++InsPt) {
1238       UnorderedPos += UnorderedSections[InsPt]->getSize();
1239       if (UnorderedPos > UnorderedSize / 2)
1240         break;
1241     }
1242   }
1243 
1244   ISD->Sections.clear();
1245   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1246     ISD->Sections.push_back(IS);
1247   for (std::pair<InputSection *, int> P : OrderedSections)
1248     ISD->Sections.push_back(P.first);
1249   for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1250     ISD->Sections.push_back(IS);
1251 }
1252 
1253 static void sortSection(OutputSection *Sec,
1254                         const DenseMap<const InputSectionBase *, int> &Order) {
1255   StringRef Name = Sec->Name;
1256 
1257   // Sort input sections by section name suffixes for
1258   // __attribute__((init_priority(N))).
1259   if (Name == ".init_array" || Name == ".fini_array") {
1260     if (!Script->HasSectionsCommand)
1261       Sec->sortInitFini();
1262     return;
1263   }
1264 
1265   // Sort input sections by the special rule for .ctors and .dtors.
1266   if (Name == ".ctors" || Name == ".dtors") {
1267     if (!Script->HasSectionsCommand)
1268       Sec->sortCtorsDtors();
1269     return;
1270   }
1271 
1272   // Never sort these.
1273   if (Name == ".init" || Name == ".fini")
1274     return;
1275 
1276   // .toc is allocated just after .got and is accessed using GOT-relative
1277   // relocations. Object files compiled with small code model have an
1278   // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1279   // To reduce the risk of relocation overflow, .toc contents are sorted so that
1280   // sections having smaller relocation offsets are at beginning of .toc
1281   if (Config->EMachine == EM_PPC64 && Name == ".toc") {
1282     if (Script->HasSectionsCommand)
1283       return;
1284     assert(Sec->SectionCommands.size() == 1);
1285     auto *ISD = cast<InputSectionDescription>(Sec->SectionCommands[0]);
1286     llvm::stable_sort(ISD->Sections,
1287                       [](const InputSection *A, const InputSection *B) -> bool {
1288                         return A->File->PPC64SmallCodeModelTocRelocs &&
1289                                !B->File->PPC64SmallCodeModelTocRelocs;
1290                       });
1291     return;
1292   }
1293 
1294   // Sort input sections by priority using the list provided
1295   // by --symbol-ordering-file.
1296   if (!Order.empty())
1297     for (BaseCommand *B : Sec->SectionCommands)
1298       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1299         sortISDBySectionOrder(ISD, Order);
1300 }
1301 
1302 // If no layout was provided by linker script, we want to apply default
1303 // sorting for special input sections. This also handles --symbol-ordering-file.
1304 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1305   // Build the order once since it is expensive.
1306   DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1307   for (BaseCommand *Base : Script->SectionCommands)
1308     if (auto *Sec = dyn_cast<OutputSection>(Base))
1309       sortSection(Sec, Order);
1310 }
1311 
1312 template <class ELFT> void Writer<ELFT>::sortSections() {
1313   Script->adjustSectionsBeforeSorting();
1314 
1315   // Don't sort if using -r. It is not necessary and we want to preserve the
1316   // relative order for SHF_LINK_ORDER sections.
1317   if (Config->Relocatable)
1318     return;
1319 
1320   sortInputSections();
1321 
1322   for (BaseCommand *Base : Script->SectionCommands) {
1323     auto *OS = dyn_cast<OutputSection>(Base);
1324     if (!OS)
1325       continue;
1326     OS->SortRank = getSectionRank(OS);
1327 
1328     // We want to assign rude approximation values to OutSecOff fields
1329     // to know the relative order of the input sections. We use it for
1330     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1331     uint64_t I = 0;
1332     for (InputSection *Sec : getInputSections(OS))
1333       Sec->OutSecOff = I++;
1334   }
1335 
1336   if (!Script->HasSectionsCommand) {
1337     // We know that all the OutputSections are contiguous in this case.
1338     auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1339     std::stable_sort(
1340         llvm::find_if(Script->SectionCommands, IsSection),
1341         llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1342         compareSections);
1343     return;
1344   }
1345 
1346   // Orphan sections are sections present in the input files which are
1347   // not explicitly placed into the output file by the linker script.
1348   //
1349   // The sections in the linker script are already in the correct
1350   // order. We have to figuere out where to insert the orphan
1351   // sections.
1352   //
1353   // The order of the sections in the script is arbitrary and may not agree with
1354   // compareSections. This means that we cannot easily define a strict weak
1355   // ordering. To see why, consider a comparison of a section in the script and
1356   // one not in the script. We have a two simple options:
1357   // * Make them equivalent (a is not less than b, and b is not less than a).
1358   //   The problem is then that equivalence has to be transitive and we can
1359   //   have sections a, b and c with only b in a script and a less than c
1360   //   which breaks this property.
1361   // * Use compareSectionsNonScript. Given that the script order doesn't have
1362   //   to match, we can end up with sections a, b, c, d where b and c are in the
1363   //   script and c is compareSectionsNonScript less than b. In which case d
1364   //   can be equivalent to c, a to b and d < a. As a concrete example:
1365   //   .a (rx) # not in script
1366   //   .b (rx) # in script
1367   //   .c (ro) # in script
1368   //   .d (ro) # not in script
1369   //
1370   // The way we define an order then is:
1371   // *  Sort only the orphan sections. They are in the end right now.
1372   // *  Move each orphan section to its preferred position. We try
1373   //    to put each section in the last position where it can share
1374   //    a PT_LOAD.
1375   //
1376   // There is some ambiguity as to where exactly a new entry should be
1377   // inserted, because Commands contains not only output section
1378   // commands but also other types of commands such as symbol assignment
1379   // expressions. There's no correct answer here due to the lack of the
1380   // formal specification of the linker script. We use heuristics to
1381   // determine whether a new output command should be added before or
1382   // after another commands. For the details, look at shouldSkip
1383   // function.
1384 
1385   auto I = Script->SectionCommands.begin();
1386   auto E = Script->SectionCommands.end();
1387   auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1388     if (auto *Sec = dyn_cast<OutputSection>(Base))
1389       return Sec->SectionIndex == UINT32_MAX;
1390     return false;
1391   });
1392 
1393   // Sort the orphan sections.
1394   std::stable_sort(NonScriptI, E, compareSections);
1395 
1396   // As a horrible special case, skip the first . assignment if it is before any
1397   // section. We do this because it is common to set a load address by starting
1398   // the script with ". = 0xabcd" and the expectation is that every section is
1399   // after that.
1400   auto FirstSectionOrDotAssignment =
1401       std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1402   if (FirstSectionOrDotAssignment != E &&
1403       isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1404     ++FirstSectionOrDotAssignment;
1405   I = FirstSectionOrDotAssignment;
1406 
1407   while (NonScriptI != E) {
1408     auto Pos = findOrphanPos(I, NonScriptI);
1409     OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1410 
1411     // As an optimization, find all sections with the same sort rank
1412     // and insert them with one rotate.
1413     unsigned Rank = Orphan->SortRank;
1414     auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1415       return cast<OutputSection>(Cmd)->SortRank != Rank;
1416     });
1417     std::rotate(Pos, NonScriptI, End);
1418     NonScriptI = End;
1419   }
1420 
1421   Script->adjustSectionsAfterSorting();
1422 }
1423 
1424 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1425   InputSection *LA = A->getLinkOrderDep();
1426   InputSection *LB = B->getLinkOrderDep();
1427   OutputSection *AOut = LA->getParent();
1428   OutputSection *BOut = LB->getParent();
1429 
1430   if (AOut != BOut)
1431     return AOut->SectionIndex < BOut->SectionIndex;
1432   return LA->OutSecOff < LB->OutSecOff;
1433 }
1434 
1435 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1436   for (OutputSection *Sec : OutputSections) {
1437     if (!(Sec->Flags & SHF_LINK_ORDER))
1438       continue;
1439 
1440     // Link order may be distributed across several InputSectionDescriptions
1441     // but sort must consider them all at once.
1442     std::vector<InputSection **> ScriptSections;
1443     std::vector<InputSection *> Sections;
1444     for (BaseCommand *Base : Sec->SectionCommands) {
1445       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1446         for (InputSection *&IS : ISD->Sections) {
1447           ScriptSections.push_back(&IS);
1448           Sections.push_back(IS);
1449         }
1450       }
1451     }
1452 
1453     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1454     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1455     if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1456         Sec->Type == SHT_ARM_EXIDX)
1457       continue;
1458 
1459     llvm::stable_sort(Sections, compareByFilePosition);
1460 
1461     for (int I = 0, N = Sections.size(); I < N; ++I)
1462       *ScriptSections[I] = Sections[I];
1463   }
1464 }
1465 
1466 // We need to generate and finalize the content that depends on the address of
1467 // InputSections. As the generation of the content may also alter InputSection
1468 // addresses we must converge to a fixed point. We do that here. See the comment
1469 // in Writer<ELFT>::finalizeSections().
1470 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1471   ThunkCreator TC;
1472   AArch64Err843419Patcher A64P;
1473 
1474   // For some targets, like x86, this loop iterates only once.
1475   for (;;) {
1476     bool Changed = false;
1477 
1478     Script->assignAddresses();
1479 
1480     if (Target->NeedsThunks)
1481       Changed |= TC.createThunks(OutputSections);
1482 
1483     if (Config->FixCortexA53Errata843419) {
1484       if (Changed)
1485         Script->assignAddresses();
1486       Changed |= A64P.createFixes();
1487     }
1488 
1489     if (In.MipsGot)
1490       In.MipsGot->updateAllocSize();
1491 
1492     Changed |= In.RelaDyn->updateAllocSize();
1493 
1494     if (In.RelrDyn)
1495       Changed |= In.RelrDyn->updateAllocSize();
1496 
1497     if (!Changed)
1498       return;
1499   }
1500 }
1501 
1502 static void finalizeSynthetic(SyntheticSection *Sec) {
1503   if (Sec && Sec->isNeeded() && Sec->getParent())
1504     Sec->finalizeContents();
1505 }
1506 
1507 // In order to allow users to manipulate linker-synthesized sections,
1508 // we had to add synthetic sections to the input section list early,
1509 // even before we make decisions whether they are needed. This allows
1510 // users to write scripts like this: ".mygot : { .got }".
1511 //
1512 // Doing it has an unintended side effects. If it turns out that we
1513 // don't need a .got (for example) at all because there's no
1514 // relocation that needs a .got, we don't want to emit .got.
1515 //
1516 // To deal with the above problem, this function is called after
1517 // scanRelocations is called to remove synthetic sections that turn
1518 // out to be empty.
1519 static void removeUnusedSyntheticSections() {
1520   // All input synthetic sections that can be empty are placed after
1521   // all regular ones. We iterate over them all and exit at first
1522   // non-synthetic.
1523   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1524     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1525     if (!SS)
1526       return;
1527     OutputSection *OS = SS->getParent();
1528     if (!OS || SS->isNeeded())
1529       continue;
1530 
1531     // If we reach here, then SS is an unused synthetic section and we want to
1532     // remove it from corresponding input section description of output section.
1533     for (BaseCommand *B : OS->SectionCommands)
1534       if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1535         llvm::erase_if(ISD->Sections,
1536                        [=](InputSection *IS) { return IS == SS; });
1537   }
1538 }
1539 
1540 // Returns true if a symbol can be replaced at load-time by a symbol
1541 // with the same name defined in other ELF executable or DSO.
1542 static bool computeIsPreemptible(const Symbol &B) {
1543   assert(!B.isLocal());
1544 
1545   // Only symbols that appear in dynsym can be preempted.
1546   if (!B.includeInDynsym())
1547     return false;
1548 
1549   // Only default visibility symbols can be preempted.
1550   if (B.Visibility != STV_DEFAULT)
1551     return false;
1552 
1553   // At this point copy relocations have not been created yet, so any
1554   // symbol that is not defined locally is preemptible.
1555   if (!B.isDefined())
1556     return true;
1557 
1558   // If we have a dynamic list it specifies which local symbols are preemptible.
1559   if (Config->HasDynamicList)
1560     return false;
1561 
1562   if (!Config->Shared)
1563     return false;
1564 
1565   // -Bsymbolic means that definitions are not preempted.
1566   if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1567     return false;
1568   return true;
1569 }
1570 
1571 // Create output section objects and add them to OutputSections.
1572 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1573   Out::PreinitArray = findSection(".preinit_array");
1574   Out::InitArray = findSection(".init_array");
1575   Out::FiniArray = findSection(".fini_array");
1576 
1577   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1578   // symbols for sections, so that the runtime can get the start and end
1579   // addresses of each section by section name. Add such symbols.
1580   if (!Config->Relocatable) {
1581     addStartEndSymbols();
1582     for (BaseCommand *Base : Script->SectionCommands)
1583       if (auto *Sec = dyn_cast<OutputSection>(Base))
1584         addStartStopSymbols(Sec);
1585   }
1586 
1587   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1588   // It should be okay as no one seems to care about the type.
1589   // Even the author of gold doesn't remember why gold behaves that way.
1590   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1591   if (In.Dynamic->Parent)
1592     Symtab->addDefined("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1593                        /*Size=*/0, STB_WEAK, In.Dynamic,
1594                        /*File=*/nullptr);
1595 
1596   // Define __rel[a]_iplt_{start,end} symbols if needed.
1597   addRelIpltSymbols();
1598 
1599   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1600   if (Config->EMachine == EM_RISCV)
1601     if (!dyn_cast_or_null<Defined>(Symtab->find("__global_pointer$")))
1602       addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800);
1603 
1604   // This responsible for splitting up .eh_frame section into
1605   // pieces. The relocation scan uses those pieces, so this has to be
1606   // earlier.
1607   finalizeSynthetic(In.EhFrame);
1608 
1609   for (Symbol *S : Symtab->getSymbols())
1610     if (!S->IsPreemptible)
1611       S->IsPreemptible = computeIsPreemptible(*S);
1612 
1613   // Scan relocations. This must be done after every symbol is declared so that
1614   // we can correctly decide if a dynamic relocation is needed.
1615   if (!Config->Relocatable)
1616     forEachRelSec(scanRelocations<ELFT>);
1617 
1618   addIRelativeRelocs();
1619 
1620   if (In.Plt && In.Plt->isNeeded())
1621     In.Plt->addSymbols();
1622   if (In.Iplt && In.Iplt->isNeeded())
1623     In.Iplt->addSymbols();
1624 
1625   if (!Config->AllowShlibUndefined) {
1626     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1627     // entires are seen. These cases would otherwise lead to runtime errors
1628     // reported by the dynamic linker.
1629     //
1630     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1631     // catch more cases. That is too much for us. Our approach resembles the one
1632     // used in ld.gold, achieves a good balance to be useful but not too smart.
1633     for (SharedFile *File : SharedFiles)
1634       File->AllNeededIsKnown =
1635           llvm::all_of(File->DtNeeded, [&](StringRef Needed) {
1636             return Symtab->SoNames.count(Needed);
1637           });
1638     for (Symbol *Sym : Symtab->getSymbols())
1639       if (Sym->isUndefined() && !Sym->isWeak())
1640         if (auto *F = dyn_cast_or_null<SharedFile>(Sym->File))
1641           if (F->AllNeededIsKnown)
1642             error(toString(F) + ": undefined reference to " + toString(*Sym));
1643   }
1644 
1645   // Now that we have defined all possible global symbols including linker-
1646   // synthesized ones. Visit all symbols to give the finishing touches.
1647   for (Symbol *Sym : Symtab->getSymbols()) {
1648     if (!includeInSymtab(*Sym))
1649       continue;
1650     if (In.SymTab)
1651       In.SymTab->addSymbol(Sym);
1652 
1653     if (Sym->includeInDynsym()) {
1654       In.DynSymTab->addSymbol(Sym);
1655       if (auto *File = dyn_cast_or_null<SharedFile>(Sym->File))
1656         if (File->IsNeeded && !Sym->isUndefined())
1657           addVerneed(Sym);
1658     }
1659   }
1660 
1661   // Do not proceed if there was an undefined symbol.
1662   if (errorCount())
1663     return;
1664 
1665   if (In.MipsGot)
1666     In.MipsGot->build();
1667 
1668   removeUnusedSyntheticSections();
1669 
1670   sortSections();
1671 
1672   // Now that we have the final list, create a list of all the
1673   // OutputSections for convenience.
1674   for (BaseCommand *Base : Script->SectionCommands)
1675     if (auto *Sec = dyn_cast<OutputSection>(Base))
1676       OutputSections.push_back(Sec);
1677 
1678   // Prefer command line supplied address over other constraints.
1679   for (OutputSection *Sec : OutputSections) {
1680     auto I = Config->SectionStartMap.find(Sec->Name);
1681     if (I != Config->SectionStartMap.end())
1682       Sec->AddrExpr = [=] { return I->second; };
1683   }
1684 
1685   // This is a bit of a hack. A value of 0 means undef, so we set it
1686   // to 1 to make __ehdr_start defined. The section number is not
1687   // particularly relevant.
1688   Out::ElfHeader->SectionIndex = 1;
1689 
1690   for (size_t I = 0, E = OutputSections.size(); I != E; ++I) {
1691     OutputSection *Sec = OutputSections[I];
1692     Sec->SectionIndex = I + 1;
1693     Sec->ShName = In.ShStrTab->addString(Sec->Name);
1694   }
1695 
1696   // Binary and relocatable output does not have PHDRS.
1697   // The headers have to be created before finalize as that can influence the
1698   // image base and the dynamic section on mips includes the image base.
1699   if (!Config->Relocatable && !Config->OFormatBinary) {
1700     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1701     if (Config->EMachine == EM_ARM) {
1702       // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1703       addPhdrForSection(Phdrs, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
1704     }
1705     if (Config->EMachine == EM_MIPS) {
1706       // Add separate segments for MIPS-specific sections.
1707       addPhdrForSection(Phdrs, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
1708       addPhdrForSection(Phdrs, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
1709       addPhdrForSection(Phdrs, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
1710     }
1711     Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1712 
1713     // Find the TLS segment. This happens before the section layout loop so that
1714     // Android relocation packing can look up TLS symbol addresses.
1715     for (PhdrEntry *P : Phdrs)
1716       if (P->p_type == PT_TLS)
1717         Out::TlsPhdr = P;
1718   }
1719 
1720   // Some symbols are defined in term of program headers. Now that we
1721   // have the headers, we can find out which sections they point to.
1722   setReservedSymbolSections();
1723 
1724   // Dynamic section must be the last one in this list and dynamic
1725   // symbol table section (DynSymTab) must be the first one.
1726   finalizeSynthetic(In.DynSymTab);
1727   finalizeSynthetic(In.ARMExidx);
1728   finalizeSynthetic(In.Bss);
1729   finalizeSynthetic(In.BssRelRo);
1730   finalizeSynthetic(In.GnuHashTab);
1731   finalizeSynthetic(In.HashTab);
1732   finalizeSynthetic(In.SymTabShndx);
1733   finalizeSynthetic(In.ShStrTab);
1734   finalizeSynthetic(In.StrTab);
1735   finalizeSynthetic(In.VerDef);
1736   finalizeSynthetic(In.Got);
1737   finalizeSynthetic(In.MipsGot);
1738   finalizeSynthetic(In.IgotPlt);
1739   finalizeSynthetic(In.GotPlt);
1740   finalizeSynthetic(In.RelaDyn);
1741   finalizeSynthetic(In.RelrDyn);
1742   finalizeSynthetic(In.RelaIplt);
1743   finalizeSynthetic(In.RelaPlt);
1744   finalizeSynthetic(In.Plt);
1745   finalizeSynthetic(In.Iplt);
1746   finalizeSynthetic(In.EhFrameHdr);
1747   finalizeSynthetic(In.VerSym);
1748   finalizeSynthetic(In.VerNeed);
1749   finalizeSynthetic(In.Dynamic);
1750 
1751   if (!Script->HasSectionsCommand && !Config->Relocatable)
1752     fixSectionAlignments();
1753 
1754   // SHFLinkOrder processing must be processed after relative section placements are
1755   // known but before addresses are allocated.
1756   resolveShfLinkOrder();
1757 
1758   // This is used to:
1759   // 1) Create "thunks":
1760   //    Jump instructions in many ISAs have small displacements, and therefore
1761   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
1762   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
1763   //    responsibility to create and insert small pieces of code between
1764   //    sections to extend the ranges if jump targets are out of range. Such
1765   //    code pieces are called "thunks".
1766   //
1767   //    We add thunks at this stage. We couldn't do this before this point
1768   //    because this is the earliest point where we know sizes of sections and
1769   //    their layouts (that are needed to determine if jump targets are in
1770   //    range).
1771   //
1772   // 2) Update the sections. We need to generate content that depends on the
1773   //    address of InputSections. For example, MIPS GOT section content or
1774   //    android packed relocations sections content.
1775   //
1776   // 3) Assign the final values for the linker script symbols. Linker scripts
1777   //    sometimes using forward symbol declarations. We want to set the correct
1778   //    values. They also might change after adding the thunks.
1779   finalizeAddressDependentContent();
1780 
1781   // finalizeAddressDependentContent may have added local symbols to the static symbol table.
1782   finalizeSynthetic(In.SymTab);
1783   finalizeSynthetic(In.PPC64LongBranchTarget);
1784 
1785   // Fill other section headers. The dynamic table is finalized
1786   // at the end because some tags like RELSZ depend on result
1787   // of finalizing other sections.
1788   for (OutputSection *Sec : OutputSections)
1789     Sec->finalize();
1790 }
1791 
1792 // Ensure data sections are not mixed with executable sections when
1793 // -execute-only is used. -execute-only is a feature to make pages executable
1794 // but not readable, and the feature is currently supported only on AArch64.
1795 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1796   if (!Config->ExecuteOnly)
1797     return;
1798 
1799   for (OutputSection *OS : OutputSections)
1800     if (OS->Flags & SHF_EXECINSTR)
1801       for (InputSection *IS : getInputSections(OS))
1802         if (!(IS->Flags & SHF_EXECINSTR))
1803           error("cannot place " + toString(IS) + " into " + toString(OS->Name) +
1804                 ": -execute-only does not support intermingling data and code");
1805 }
1806 
1807 // The linker is expected to define SECNAME_start and SECNAME_end
1808 // symbols for a few sections. This function defines them.
1809 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1810   // If a section does not exist, there's ambiguity as to how we
1811   // define _start and _end symbols for an init/fini section. Since
1812   // the loader assume that the symbols are always defined, we need to
1813   // always define them. But what value? The loader iterates over all
1814   // pointers between _start and _end to run global ctors/dtors, so if
1815   // the section is empty, their symbol values don't actually matter
1816   // as long as _start and _end point to the same location.
1817   //
1818   // That said, we don't want to set the symbols to 0 (which is
1819   // probably the simplest value) because that could cause some
1820   // program to fail to link due to relocation overflow, if their
1821   // program text is above 2 GiB. We use the address of the .text
1822   // section instead to prevent that failure.
1823   //
1824   // In a rare sitaution, .text section may not exist. If that's the
1825   // case, use the image base address as a last resort.
1826   OutputSection *Default = findSection(".text");
1827   if (!Default)
1828     Default = Out::ElfHeader;
1829 
1830   auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1831     if (OS) {
1832       addOptionalRegular(Start, OS, 0);
1833       addOptionalRegular(End, OS, -1);
1834     } else {
1835       addOptionalRegular(Start, Default, 0);
1836       addOptionalRegular(End, Default, 0);
1837     }
1838   };
1839 
1840   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1841   Define("__init_array_start", "__init_array_end", Out::InitArray);
1842   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1843 
1844   if (OutputSection *Sec = findSection(".ARM.exidx"))
1845     Define("__exidx_start", "__exidx_end", Sec);
1846 }
1847 
1848 // If a section name is valid as a C identifier (which is rare because of
1849 // the leading '.'), linkers are expected to define __start_<secname> and
1850 // __stop_<secname> symbols. They are at beginning and end of the section,
1851 // respectively. This is not requested by the ELF standard, but GNU ld and
1852 // gold provide the feature, and used by many programs.
1853 template <class ELFT>
1854 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1855   StringRef S = Sec->Name;
1856   if (!isValidCIdentifier(S))
1857     return;
1858   addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1859   addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1860 }
1861 
1862 static bool needsPtLoad(OutputSection *Sec) {
1863   if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1864     return false;
1865 
1866   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1867   // responsible for allocating space for them, not the PT_LOAD that
1868   // contains the TLS initialization image.
1869   if ((Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS)
1870     return false;
1871   return true;
1872 }
1873 
1874 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1875 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1876 // RW. This means that there is no alignment in the RO to RX transition and we
1877 // cannot create a PT_LOAD there.
1878 static uint64_t computeFlags(uint64_t Flags) {
1879   if (Config->Omagic)
1880     return PF_R | PF_W | PF_X;
1881   if (Config->ExecuteOnly && (Flags & PF_X))
1882     return Flags & ~PF_R;
1883   if (Config->SingleRoRx && !(Flags & PF_W))
1884     return Flags | PF_X;
1885   return Flags;
1886 }
1887 
1888 // Decide which program headers to create and which sections to include in each
1889 // one.
1890 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1891   std::vector<PhdrEntry *> Ret;
1892   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1893     Ret.push_back(make<PhdrEntry>(Type, Flags));
1894     return Ret.back();
1895   };
1896 
1897   // The first phdr entry is PT_PHDR which describes the program header itself.
1898   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1899 
1900   // PT_INTERP must be the second entry if exists.
1901   if (OutputSection *Cmd = findSection(".interp"))
1902     AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1903 
1904   // Add the first PT_LOAD segment for regular output sections.
1905   uint64_t Flags = computeFlags(PF_R);
1906   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1907 
1908   // Add the headers. We will remove them if they don't fit.
1909   Load->add(Out::ElfHeader);
1910   Load->add(Out::ProgramHeaders);
1911 
1912   // PT_GNU_RELRO includes all sections that should be marked as
1913   // read-only by dynamic linker after proccessing relocations.
1914   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1915   // an error message if more than one PT_GNU_RELRO PHDR is required.
1916   PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1917   bool InRelroPhdr = false;
1918   OutputSection *RelroEnd = nullptr;
1919   for (OutputSection *Sec : OutputSections) {
1920     if (!needsPtLoad(Sec))
1921       continue;
1922     if (isRelroSection(Sec)) {
1923       InRelroPhdr = true;
1924       if (!RelroEnd)
1925         RelRo->add(Sec);
1926       else
1927         error("section: " + Sec->Name + " is not contiguous with other relro" +
1928               " sections");
1929     } else if (InRelroPhdr) {
1930       InRelroPhdr = false;
1931       RelroEnd = Sec;
1932     }
1933   }
1934 
1935   for (OutputSection *Sec : OutputSections) {
1936     if (!(Sec->Flags & SHF_ALLOC))
1937       break;
1938     if (!needsPtLoad(Sec))
1939       continue;
1940 
1941     // Segments are contiguous memory regions that has the same attributes
1942     // (e.g. executable or writable). There is one phdr for each segment.
1943     // Therefore, we need to create a new phdr when the next section has
1944     // different flags or is loaded at a discontiguous address or memory
1945     // region using AT or AT> linker script command, respectively. At the same
1946     // time, we don't want to create a separate load segment for the headers,
1947     // even if the first output section has an AT or AT> attribute.
1948     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1949     if (((Sec->LMAExpr ||
1950           (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) &&
1951          Load->LastSec != Out::ProgramHeaders) ||
1952         Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags ||
1953         Sec == RelroEnd) {
1954       Load = AddHdr(PT_LOAD, NewFlags);
1955       Flags = NewFlags;
1956     }
1957 
1958     Load->add(Sec);
1959   }
1960 
1961   // Add a TLS segment if any.
1962   PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1963   for (OutputSection *Sec : OutputSections)
1964     if (Sec->Flags & SHF_TLS)
1965       TlsHdr->add(Sec);
1966   if (TlsHdr->FirstSec)
1967     Ret.push_back(TlsHdr);
1968 
1969   // Add an entry for .dynamic.
1970   if (OutputSection *Sec = In.Dynamic->getParent())
1971     AddHdr(PT_DYNAMIC, Sec->getPhdrFlags())->add(Sec);
1972 
1973   if (RelRo->FirstSec)
1974     Ret.push_back(RelRo);
1975 
1976   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1977   if (In.EhFrame->isNeeded() && In.EhFrameHdr && In.EhFrame->getParent() &&
1978       In.EhFrameHdr->getParent())
1979     AddHdr(PT_GNU_EH_FRAME, In.EhFrameHdr->getParent()->getPhdrFlags())
1980         ->add(In.EhFrameHdr->getParent());
1981 
1982   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1983   // the dynamic linker fill the segment with random data.
1984   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1985     AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1986 
1987   // PT_GNU_STACK is a special section to tell the loader to make the
1988   // pages for the stack non-executable. If you really want an executable
1989   // stack, you can pass -z execstack, but that's not recommended for
1990   // security reasons.
1991   unsigned Perm = PF_R | PF_W;
1992   if (Config->ZExecstack)
1993     Perm |= PF_X;
1994   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1995 
1996   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1997   // is expected to perform W^X violations, such as calling mprotect(2) or
1998   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1999   // OpenBSD.
2000   if (Config->ZWxneeded)
2001     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
2002 
2003   // Create one PT_NOTE per a group of contiguous .note sections.
2004   PhdrEntry *Note = nullptr;
2005   for (OutputSection *Sec : OutputSections) {
2006     if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
2007       if (!Note || Sec->LMAExpr)
2008         Note = AddHdr(PT_NOTE, PF_R);
2009       Note->add(Sec);
2010     } else {
2011       Note = nullptr;
2012     }
2013   }
2014   return Ret;
2015 }
2016 
2017 template <class ELFT>
2018 void Writer<ELFT>::addPhdrForSection(std::vector<PhdrEntry *> &Phdrs,
2019                                      unsigned ShType, unsigned PType,
2020                                      unsigned PFlags) {
2021   auto I = llvm::find_if(
2022       OutputSections, [=](OutputSection *Cmd) { return Cmd->Type == ShType; });
2023   if (I == OutputSections.end())
2024     return;
2025 
2026   PhdrEntry *Entry = make<PhdrEntry>(PType, PFlags);
2027   Entry->add(*I);
2028   Phdrs.push_back(Entry);
2029 }
2030 
2031 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2032 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2033 // linker can set the permissions.
2034 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2035   auto PageAlign = [](OutputSection *Cmd) {
2036     if (Cmd && !Cmd->AddrExpr)
2037       Cmd->AddrExpr = [=] {
2038         return alignTo(Script->getDot(), Config->MaxPageSize);
2039       };
2040   };
2041 
2042   for (const PhdrEntry *P : Phdrs)
2043     if (P->p_type == PT_LOAD && P->FirstSec)
2044       PageAlign(P->FirstSec);
2045 
2046   for (const PhdrEntry *P : Phdrs) {
2047     if (P->p_type != PT_GNU_RELRO)
2048       continue;
2049 
2050     if (P->FirstSec)
2051       PageAlign(P->FirstSec);
2052 
2053     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
2054     // have to align it to a page.
2055     auto End = OutputSections.end();
2056     auto I = llvm::find(OutputSections, P->LastSec);
2057     if (I == End || (I + 1) == End)
2058       continue;
2059 
2060     OutputSection *Cmd = (*(I + 1));
2061     if (needsPtLoad(Cmd))
2062       PageAlign(Cmd);
2063   }
2064 }
2065 
2066 // Compute an in-file position for a given section. The file offset must be the
2067 // same with its virtual address modulo the page size, so that the loader can
2068 // load executables without any address adjustment.
2069 static uint64_t computeFileOffset(OutputSection *OS, uint64_t Off) {
2070   // File offsets are not significant for .bss sections. By convention, we keep
2071   // section offsets monotonically increasing rather than setting to zero.
2072   if (OS->Type == SHT_NOBITS)
2073     return Off;
2074 
2075   // If the section is not in a PT_LOAD, we just have to align it.
2076   if (!OS->PtLoad)
2077     return alignTo(Off, OS->Alignment);
2078 
2079   // The first section in a PT_LOAD has to have congruent offset and address
2080   // module the page size.
2081   OutputSection *First = OS->PtLoad->FirstSec;
2082   if (OS == First) {
2083     uint64_t Alignment = std::max<uint64_t>(OS->Alignment, Config->MaxPageSize);
2084     return alignTo(Off, Alignment, OS->Addr);
2085   }
2086 
2087   // If two sections share the same PT_LOAD the file offset is calculated
2088   // using this formula: Off2 = Off1 + (VA2 - VA1).
2089   return First->Offset + OS->Addr - First->Addr;
2090 }
2091 
2092 // Set an in-file position to a given section and returns the end position of
2093 // the section.
2094 static uint64_t setFileOffset(OutputSection *OS, uint64_t Off) {
2095   Off = computeFileOffset(OS, Off);
2096   OS->Offset = Off;
2097 
2098   if (OS->Type == SHT_NOBITS)
2099     return Off;
2100   return Off + OS->Size;
2101 }
2102 
2103 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2104   uint64_t Off = 0;
2105   for (OutputSection *Sec : OutputSections)
2106     if (Sec->Flags & SHF_ALLOC)
2107       Off = setFileOffset(Sec, Off);
2108   FileSize = alignTo(Off, Config->Wordsize);
2109 }
2110 
2111 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
2112   return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
2113 }
2114 
2115 // Assign file offsets to output sections.
2116 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2117   uint64_t Off = 0;
2118   Off = setFileOffset(Out::ElfHeader, Off);
2119   Off = setFileOffset(Out::ProgramHeaders, Off);
2120 
2121   PhdrEntry *LastRX = nullptr;
2122   for (PhdrEntry *P : Phdrs)
2123     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2124       LastRX = P;
2125 
2126   for (OutputSection *Sec : OutputSections) {
2127     Off = setFileOffset(Sec, Off);
2128     if (Script->HasSectionsCommand)
2129       continue;
2130 
2131     // If this is a last section of the last executable segment and that
2132     // segment is the last loadable segment, align the offset of the
2133     // following section to avoid loading non-segments parts of the file.
2134     if (LastRX && LastRX->LastSec == Sec)
2135       Off = alignTo(Off, Target->PageSize);
2136   }
2137 
2138   SectionHeaderOff = alignTo(Off, Config->Wordsize);
2139   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2140 
2141   // Our logic assumes that sections have rising VA within the same segment.
2142   // With use of linker scripts it is possible to violate this rule and get file
2143   // offset overlaps or overflows. That should never happen with a valid script
2144   // which does not move the location counter backwards and usually scripts do
2145   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2146   // kernel, which control segment distribution explicitly and move the counter
2147   // backwards, so we have to allow doing that to support linking them. We
2148   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2149   // we want to prevent file size overflows because it would crash the linker.
2150   for (OutputSection *Sec : OutputSections) {
2151     if (Sec->Type == SHT_NOBITS)
2152       continue;
2153     if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2154       error("unable to place section " + Sec->Name + " at file offset " +
2155             rangeToString(Sec->Offset, Sec->Size) +
2156             "; check your linker script for overflows");
2157   }
2158 }
2159 
2160 // Finalize the program headers. We call this function after we assign
2161 // file offsets and VAs to all sections.
2162 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2163   for (PhdrEntry *P : Phdrs) {
2164     OutputSection *First = P->FirstSec;
2165     OutputSection *Last = P->LastSec;
2166 
2167     if (First) {
2168       P->p_filesz = Last->Offset - First->Offset;
2169       if (Last->Type != SHT_NOBITS)
2170         P->p_filesz += Last->Size;
2171 
2172       P->p_memsz = Last->Addr + Last->Size - First->Addr;
2173       P->p_offset = First->Offset;
2174       P->p_vaddr = First->Addr;
2175 
2176       if (!P->HasLMA)
2177         P->p_paddr = First->getLMA();
2178     }
2179 
2180     if (P->p_type == PT_LOAD) {
2181       P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2182     } else if (P->p_type == PT_GNU_RELRO) {
2183       P->p_align = 1;
2184       // The glibc dynamic loader rounds the size down, so we need to round up
2185       // to protect the last page. This is a no-op on FreeBSD which always
2186       // rounds up.
2187       P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2188     }
2189 
2190     if (P->p_type == PT_TLS && P->p_memsz) {
2191       if (!Config->Shared &&
2192           (Config->EMachine == EM_ARM || Config->EMachine == EM_AARCH64)) {
2193         // On ARM/AArch64, reserve extra space (8 words) between the thread
2194         // pointer and an executable's TLS segment by overaligning the segment.
2195         // This reservation is needed for backwards compatibility with Android's
2196         // TCB, which allocates several slots after the thread pointer (e.g.
2197         // TLS_SLOT_STACK_GUARD==5). For simplicity, this overalignment is also
2198         // done on other operating systems.
2199         P->p_align = std::max<uint64_t>(P->p_align, Config->Wordsize * 8);
2200       }
2201 
2202       // The TLS pointer goes after PT_TLS for variant 2 targets. At least glibc
2203       // will align it, so round up the size to make sure the offsets are
2204       // correct.
2205       P->p_memsz = alignTo(P->p_memsz, P->p_align);
2206     }
2207   }
2208 }
2209 
2210 // A helper struct for checkSectionOverlap.
2211 namespace {
2212 struct SectionOffset {
2213   OutputSection *Sec;
2214   uint64_t Offset;
2215 };
2216 } // namespace
2217 
2218 // Check whether sections overlap for a specific address range (file offsets,
2219 // load and virtual adresses).
2220 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2221                          bool IsVirtualAddr) {
2222   llvm::sort(Sections, [=](const SectionOffset &A, const SectionOffset &B) {
2223     return A.Offset < B.Offset;
2224   });
2225 
2226   // Finding overlap is easy given a vector is sorted by start position.
2227   // If an element starts before the end of the previous element, they overlap.
2228   for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2229     SectionOffset A = Sections[I - 1];
2230     SectionOffset B = Sections[I];
2231     if (B.Offset >= A.Offset + A.Sec->Size)
2232       continue;
2233 
2234     // If both sections are in OVERLAY we allow the overlapping of virtual
2235     // addresses, because it is what OVERLAY was designed for.
2236     if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2237       continue;
2238 
2239     errorOrWarn("section " + A.Sec->Name + " " + Name +
2240                 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2241                 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2242                 B.Sec->Name + " range is " +
2243                 rangeToString(B.Offset, B.Sec->Size));
2244   }
2245 }
2246 
2247 // Check for overlapping sections and address overflows.
2248 //
2249 // In this function we check that none of the output sections have overlapping
2250 // file offsets. For SHF_ALLOC sections we also check that the load address
2251 // ranges and the virtual address ranges don't overlap
2252 template <class ELFT> void Writer<ELFT>::checkSections() {
2253   // First, check that section's VAs fit in available address space for target.
2254   for (OutputSection *OS : OutputSections)
2255     if ((OS->Addr + OS->Size < OS->Addr) ||
2256         (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2257       errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2258                   " of size 0x" + utohexstr(OS->Size) +
2259                   " exceeds available address space");
2260 
2261   // Check for overlapping file offsets. In this case we need to skip any
2262   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2263   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2264   // binary is specified only add SHF_ALLOC sections are added to the output
2265   // file so we skip any non-allocated sections in that case.
2266   std::vector<SectionOffset> FileOffs;
2267   for (OutputSection *Sec : OutputSections)
2268     if (Sec->Size > 0 && Sec->Type != SHT_NOBITS &&
2269         (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2270       FileOffs.push_back({Sec, Sec->Offset});
2271   checkOverlap("file", FileOffs, false);
2272 
2273   // When linking with -r there is no need to check for overlapping virtual/load
2274   // addresses since those addresses will only be assigned when the final
2275   // executable/shared object is created.
2276   if (Config->Relocatable)
2277     return;
2278 
2279   // Checking for overlapping virtual and load addresses only needs to take
2280   // into account SHF_ALLOC sections since others will not be loaded.
2281   // Furthermore, we also need to skip SHF_TLS sections since these will be
2282   // mapped to other addresses at runtime and can therefore have overlapping
2283   // ranges in the file.
2284   std::vector<SectionOffset> VMAs;
2285   for (OutputSection *Sec : OutputSections)
2286     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2287       VMAs.push_back({Sec, Sec->Addr});
2288   checkOverlap("virtual address", VMAs, true);
2289 
2290   // Finally, check that the load addresses don't overlap. This will usually be
2291   // the same as the virtual addresses but can be different when using a linker
2292   // script with AT().
2293   std::vector<SectionOffset> LMAs;
2294   for (OutputSection *Sec : OutputSections)
2295     if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2296       LMAs.push_back({Sec, Sec->getLMA()});
2297   checkOverlap("load address", LMAs, false);
2298 }
2299 
2300 // The entry point address is chosen in the following ways.
2301 //
2302 // 1. the '-e' entry command-line option;
2303 // 2. the ENTRY(symbol) command in a linker control script;
2304 // 3. the value of the symbol _start, if present;
2305 // 4. the number represented by the entry symbol, if it is a number;
2306 // 5. the address of the first byte of the .text section, if present;
2307 // 6. the address 0.
2308 static uint64_t getEntryAddr() {
2309   // Case 1, 2 or 3
2310   if (Symbol *B = Symtab->find(Config->Entry))
2311     return B->getVA();
2312 
2313   // Case 4
2314   uint64_t Addr;
2315   if (to_integer(Config->Entry, Addr))
2316     return Addr;
2317 
2318   // Case 5
2319   if (OutputSection *Sec = findSection(".text")) {
2320     if (Config->WarnMissingEntry)
2321       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2322            utohexstr(Sec->Addr));
2323     return Sec->Addr;
2324   }
2325 
2326   // Case 6
2327   if (Config->WarnMissingEntry)
2328     warn("cannot find entry symbol " + Config->Entry +
2329          "; not setting start address");
2330   return 0;
2331 }
2332 
2333 static uint16_t getELFType() {
2334   if (Config->Pic)
2335     return ET_DYN;
2336   if (Config->Relocatable)
2337     return ET_REL;
2338   return ET_EXEC;
2339 }
2340 
2341 static uint8_t getAbiVersion() {
2342   // MIPS non-PIC executable gets ABI version 1.
2343   if (Config->EMachine == EM_MIPS) {
2344     if (getELFType() == ET_EXEC &&
2345         (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2346       return 1;
2347     return 0;
2348   }
2349 
2350   if (Config->EMachine == EM_AMDGPU) {
2351     uint8_t Ver = ObjectFiles[0]->ABIVersion;
2352     for (InputFile *File : makeArrayRef(ObjectFiles).slice(1))
2353       if (File->ABIVersion != Ver)
2354         error("incompatible ABI version: " + toString(File));
2355     return Ver;
2356   }
2357 
2358   return 0;
2359 }
2360 
2361 template <class ELFT> void Writer<ELFT>::writeHeader() {
2362   // For executable segments, the trap instructions are written before writing
2363   // the header. Setting Elf header bytes to zero ensures that any unused bytes
2364   // in header are zero-cleared, instead of having trap instructions.
2365   memset(Out::BufferStart, 0, sizeof(Elf_Ehdr));
2366   memcpy(Out::BufferStart, "\177ELF", 4);
2367 
2368   // Write the ELF header.
2369   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Out::BufferStart);
2370   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2371   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2372   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2373   EHdr->e_ident[EI_OSABI] = Config->OSABI;
2374   EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2375   EHdr->e_type = getELFType();
2376   EHdr->e_machine = Config->EMachine;
2377   EHdr->e_version = EV_CURRENT;
2378   EHdr->e_entry = getEntryAddr();
2379   EHdr->e_shoff = SectionHeaderOff;
2380   EHdr->e_flags = Config->EFlags;
2381   EHdr->e_ehsize = sizeof(Elf_Ehdr);
2382   EHdr->e_phnum = Phdrs.size();
2383   EHdr->e_shentsize = sizeof(Elf_Shdr);
2384 
2385   if (!Config->Relocatable) {
2386     EHdr->e_phoff = sizeof(Elf_Ehdr);
2387     EHdr->e_phentsize = sizeof(Elf_Phdr);
2388   }
2389 
2390   // Write the program header table.
2391   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Out::BufferStart + EHdr->e_phoff);
2392   for (PhdrEntry *P : Phdrs) {
2393     HBuf->p_type = P->p_type;
2394     HBuf->p_flags = P->p_flags;
2395     HBuf->p_offset = P->p_offset;
2396     HBuf->p_vaddr = P->p_vaddr;
2397     HBuf->p_paddr = P->p_paddr;
2398     HBuf->p_filesz = P->p_filesz;
2399     HBuf->p_memsz = P->p_memsz;
2400     HBuf->p_align = P->p_align;
2401     ++HBuf;
2402   }
2403 
2404   // Write the section header table.
2405   //
2406   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2407   // and e_shstrndx fields. When the value of one of these fields exceeds
2408   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2409   // use fields in the section header at index 0 to store
2410   // the value. The sentinel values and fields are:
2411   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2412   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2413   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Out::BufferStart + EHdr->e_shoff);
2414   size_t Num = OutputSections.size() + 1;
2415   if (Num >= SHN_LORESERVE)
2416     SHdrs->sh_size = Num;
2417   else
2418     EHdr->e_shnum = Num;
2419 
2420   uint32_t StrTabIndex = In.ShStrTab->getParent()->SectionIndex;
2421   if (StrTabIndex >= SHN_LORESERVE) {
2422     SHdrs->sh_link = StrTabIndex;
2423     EHdr->e_shstrndx = SHN_XINDEX;
2424   } else {
2425     EHdr->e_shstrndx = StrTabIndex;
2426   }
2427 
2428   for (OutputSection *Sec : OutputSections)
2429     Sec->writeHeaderTo<ELFT>(++SHdrs);
2430 }
2431 
2432 // Open a result file.
2433 template <class ELFT> void Writer<ELFT>::openFile() {
2434   uint64_t MaxSize = Config->Is64 ? INT64_MAX : UINT32_MAX;
2435   if (FileSize != size_t(FileSize) || MaxSize < FileSize) {
2436     error("output file too large: " + Twine(FileSize) + " bytes");
2437     return;
2438   }
2439 
2440   unlinkAsync(Config->OutputFile);
2441   unsigned Flags = 0;
2442   if (!Config->Relocatable)
2443     Flags = FileOutputBuffer::F_executable;
2444   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2445       FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2446 
2447   if (!BufferOrErr) {
2448     error("failed to open " + Config->OutputFile + ": " +
2449           llvm::toString(BufferOrErr.takeError()));
2450     return;
2451   }
2452   Buffer = std::move(*BufferOrErr);
2453   Out::BufferStart = Buffer->getBufferStart();
2454 }
2455 
2456 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2457   for (OutputSection *Sec : OutputSections)
2458     if (Sec->Flags & SHF_ALLOC)
2459       Sec->writeTo<ELFT>(Out::BufferStart + Sec->Offset);
2460 }
2461 
2462 static void fillTrap(uint8_t *I, uint8_t *End) {
2463   for (; I + 4 <= End; I += 4)
2464     memcpy(I, &Target->TrapInstr, 4);
2465 }
2466 
2467 // Fill the last page of executable segments with trap instructions
2468 // instead of leaving them as zero. Even though it is not required by any
2469 // standard, it is in general a good thing to do for security reasons.
2470 //
2471 // We'll leave other pages in segments as-is because the rest will be
2472 // overwritten by output sections.
2473 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2474   if (Script->HasSectionsCommand)
2475     return;
2476 
2477   // Fill the last page.
2478   for (PhdrEntry *P : Phdrs)
2479     if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2480       fillTrap(Out::BufferStart +
2481                    alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2482                Out::BufferStart +
2483                    alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2484 
2485   // Round up the file size of the last segment to the page boundary iff it is
2486   // an executable segment to ensure that other tools don't accidentally
2487   // trim the instruction padding (e.g. when stripping the file).
2488   PhdrEntry *Last = nullptr;
2489   for (PhdrEntry *P : Phdrs)
2490     if (P->p_type == PT_LOAD)
2491       Last = P;
2492 
2493   if (Last && (Last->p_flags & PF_X))
2494     Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2495 }
2496 
2497 // Write section contents to a mmap'ed file.
2498 template <class ELFT> void Writer<ELFT>::writeSections() {
2499   // In -r or -emit-relocs mode, write the relocation sections first as in
2500   // ELf_Rel targets we might find out that we need to modify the relocated
2501   // section while doing it.
2502   for (OutputSection *Sec : OutputSections)
2503     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2504       Sec->writeTo<ELFT>(Out::BufferStart + Sec->Offset);
2505 
2506   for (OutputSection *Sec : OutputSections)
2507     if (Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2508       Sec->writeTo<ELFT>(Out::BufferStart + Sec->Offset);
2509 }
2510 
2511 // Split one uint8 array into small pieces of uint8 arrays.
2512 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
2513                                             size_t ChunkSize) {
2514   std::vector<ArrayRef<uint8_t>> Ret;
2515   while (Arr.size() > ChunkSize) {
2516     Ret.push_back(Arr.take_front(ChunkSize));
2517     Arr = Arr.drop_front(ChunkSize);
2518   }
2519   if (!Arr.empty())
2520     Ret.push_back(Arr);
2521   return Ret;
2522 }
2523 
2524 // Computes a hash value of Data using a given hash function.
2525 // In order to utilize multiple cores, we first split data into 1MB
2526 // chunks, compute a hash for each chunk, and then compute a hash value
2527 // of the hash values.
2528 static void
2529 computeHash(llvm::MutableArrayRef<uint8_t> HashBuf,
2530             llvm::ArrayRef<uint8_t> Data,
2531             std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
2532   std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
2533   std::vector<uint8_t> Hashes(Chunks.size() * HashBuf.size());
2534 
2535   // Compute hash values.
2536   parallelForEachN(0, Chunks.size(), [&](size_t I) {
2537     HashFn(Hashes.data() + I * HashBuf.size(), Chunks[I]);
2538   });
2539 
2540   // Write to the final output buffer.
2541   HashFn(HashBuf.data(), Hashes);
2542 }
2543 
2544 static std::vector<uint8_t> computeBuildId(llvm::ArrayRef<uint8_t> Buf) {
2545   std::vector<uint8_t> BuildId;
2546   switch (Config->BuildId) {
2547   case BuildIdKind::Fast:
2548     BuildId.resize(8);
2549     computeHash(BuildId, Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
2550       write64le(Dest, xxHash64(Arr));
2551     });
2552     break;
2553   case BuildIdKind::Md5:
2554     BuildId.resize(16);
2555     computeHash(BuildId, Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
2556       memcpy(Dest, MD5::hash(Arr).data(), 16);
2557     });
2558     break;
2559   case BuildIdKind::Sha1:
2560     BuildId.resize(20);
2561     computeHash(BuildId, Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
2562       memcpy(Dest, SHA1::hash(Arr).data(), 20);
2563     });
2564     break;
2565   case BuildIdKind::Uuid:
2566     BuildId.resize(16);
2567     if (auto EC = llvm::getRandomBytes(BuildId.data(), 16))
2568       error("entropy source failure: " + EC.message());
2569     break;
2570   case BuildIdKind::Hexstring:
2571     BuildId = Config->BuildIdVector;
2572     break;
2573   default:
2574     llvm_unreachable("unknown BuildIdKind");
2575   }
2576   return BuildId;
2577 }
2578 
2579 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2580   if (!In.BuildId || !In.BuildId->getParent())
2581     return;
2582 
2583   // Compute a hash of all sections of the output file.
2584   std::vector<uint8_t> BuildId =
2585       computeBuildId({Out::BufferStart, size_t(FileSize)});
2586   In.BuildId->writeBuildId(BuildId);
2587 }
2588 
2589 template void elf::writeResult<ELF32LE>();
2590 template void elf::writeResult<ELF32BE>();
2591 template void elf::writeResult<ELF64LE>();
2592 template void elf::writeResult<ELF64BE>();
2593