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