xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision fcd549a7)
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 *isec = dyn_cast<InputSection>(s)) {
103     if (InputSectionBase *rel = isec->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 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   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
359 
360   for (Partition &part : partitions) {
361     auto add = [&](InputSectionBase *sec) {
362       sec->partition = part.getNumber();
363       inputSections.push_back(sec);
364     };
365 
366     if (!part.name.empty()) {
367       part.elfHeader = make<PartitionElfHeaderSection<ELFT>>();
368       part.elfHeader->name = part.name;
369       add(part.elfHeader);
370 
371       part.programHeaders = make<PartitionProgramHeadersSection<ELFT>>();
372       add(part.programHeaders);
373     }
374 
375     if (config->buildId != BuildIdKind::None) {
376       part.buildId = make<BuildIdSection>();
377       add(part.buildId);
378     }
379 
380     part.dynStrTab = make<StringTableSection>(".dynstr", true);
381     part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab);
382     part.dynamic = make<DynamicSection<ELFT>>();
383     if (config->androidPackDynRelocs)
384       part.relaDyn = make<AndroidPackedRelocationSection<ELFT>>(relaDynName);
385     else
386       part.relaDyn =
387           make<RelocationSection<ELFT>>(relaDynName, config->zCombreloc);
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", /*sort=*/false);
505   add(in.relaPlt);
506 
507   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
508   // relocations are processed last by the dynamic loader. We cannot place the
509   // iplt section in .rel.dyn when Android relocation packing is enabled because
510   // that would cause a section type mismatch. However, because the Android
511   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
512   // behaviour by placing the iplt section in .rel.plt.
513   in.relaIplt = make<RelocationSection<ELFT>>(
514       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
515       /*sort=*/false);
516   add(in.relaIplt);
517 
518   in.plt = make<PltSection>(false);
519   add(in.plt);
520   in.iplt = make<PltSection>(true);
521   add(in.iplt);
522 
523   if (config->andFeatures)
524     add(make<GnuPropertySection>());
525 
526   // .note.GNU-stack is always added when we are creating a re-linkable
527   // object file. Other linkers are using the presence of this marker
528   // section to control the executable-ness of the stack area, but that
529   // is irrelevant these days. Stack area should always be non-executable
530   // by default. So we emit this section unconditionally.
531   if (config->relocatable)
532     add(make<GnuStackSection>());
533 
534   if (in.symTab)
535     add(in.symTab);
536   if (in.symTabShndx)
537     add(in.symTabShndx);
538   add(in.shStrTab);
539   if (in.strTab)
540     add(in.strTab);
541 }
542 
543 // The main function of the writer.
544 template <class ELFT> void Writer<ELFT>::run() {
545   // Make copies of any input sections that need to be copied into each
546   // partition.
547   copySectionsIntoPartitions();
548 
549   // Create linker-synthesized sections such as .got or .plt.
550   // Such sections are of type input section.
551   createSyntheticSections<ELFT>();
552 
553   // Some input sections that are used for exception handling need to be moved
554   // into synthetic sections. Do that now so that they aren't assigned to
555   // output sections in the usual way.
556   if (!config->relocatable)
557     combineEhSections<ELFT>();
558 
559   // We want to process linker script commands. When SECTIONS command
560   // is given we let it create sections.
561   script->processSectionCommands();
562 
563   // Linker scripts controls how input sections are assigned to output sections.
564   // Input sections that were not handled by scripts are called "orphans", and
565   // they are assigned to output sections by the default rule. Process that.
566   script->addOrphanSections();
567 
568   if (config->discard != DiscardPolicy::All)
569     copyLocalSymbols();
570 
571   if (config->copyRelocs)
572     addSectionSymbols();
573 
574   // Now that we have a complete set of output sections. This function
575   // completes section contents. For example, we need to add strings
576   // to the string table, and add entries to .got and .plt.
577   // finalizeSections does that.
578   finalizeSections();
579   checkExecuteOnly();
580   if (errorCount())
581     return;
582 
583   script->assignAddresses();
584 
585   // If -compressed-debug-sections is specified, we need to compress
586   // .debug_* sections. Do it right now because it changes the size of
587   // output sections.
588   for (OutputSection *sec : outputSections)
589     sec->maybeCompress<ELFT>();
590 
591   script->allocateHeaders(mainPart->phdrs);
592 
593   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
594   // 0 sized region. This has to be done late since only after assignAddresses
595   // we know the size of the sections.
596   for (Partition &part : partitions)
597     removeEmptyPTLoad(part.phdrs);
598 
599   if (!config->oFormatBinary)
600     assignFileOffsets();
601   else
602     assignFileOffsetsBinary();
603 
604   for (Partition &part : partitions)
605     setPhdrs(part);
606 
607   if (config->relocatable)
608     for (OutputSection *sec : outputSections)
609       sec->addr = 0;
610 
611   if (config->checkSections)
612     checkSections();
613 
614   // It does not make sense try to open the file if we have error already.
615   if (errorCount())
616     return;
617   // Write the result down to a file.
618   openFile();
619   if (errorCount())
620     return;
621 
622   if (!config->oFormatBinary) {
623     writeTrapInstr();
624     writeHeader();
625     writeSections();
626   } else {
627     writeSectionsBinary();
628   }
629 
630   // Backfill .note.gnu.build-id section content. This is done at last
631   // because the content is usually a hash value of the entire output file.
632   writeBuildId();
633   if (errorCount())
634     return;
635 
636   // Handle -Map and -cref options.
637   writeMapFile();
638   writeCrossReferenceTable();
639   if (errorCount())
640     return;
641 
642   if (auto e = buffer->commit())
643     error("failed to write to the output file: " + toString(std::move(e)));
644 }
645 
646 static bool shouldKeepInSymtab(const Defined &sym) {
647   if (sym.isSection())
648     return false;
649 
650   if (config->discard == DiscardPolicy::None)
651     return true;
652 
653   // If -emit-reloc is given, all symbols including local ones need to be
654   // copied because they may be referenced by relocations.
655   if (config->emitRelocs)
656     return true;
657 
658   // In ELF assembly .L symbols are normally discarded by the assembler.
659   // If the assembler fails to do so, the linker discards them if
660   // * --discard-locals is used.
661   // * The symbol is in a SHF_MERGE section, which is normally the reason for
662   //   the assembler keeping the .L symbol.
663   StringRef name = sym.getName();
664   bool isLocal = name.startswith(".L") || name.empty();
665   if (!isLocal)
666     return true;
667 
668   if (config->discard == DiscardPolicy::Locals)
669     return false;
670 
671   SectionBase *sec = sym.section;
672   return !sec || !(sec->flags & SHF_MERGE);
673 }
674 
675 static bool includeInSymtab(const Symbol &b) {
676   if (!b.isLocal() && !b.isUsedInRegularObj)
677     return false;
678 
679   if (auto *d = dyn_cast<Defined>(&b)) {
680     // Always include absolute symbols.
681     SectionBase *sec = d->section;
682     if (!sec)
683       return true;
684     sec = sec->repl;
685 
686     // Exclude symbols pointing to garbage-collected sections.
687     if (isa<InputSectionBase>(sec) && !sec->isLive())
688       return false;
689 
690     if (auto *s = dyn_cast<MergeInputSection>(sec))
691       if (!s->getSectionPiece(d->value)->live)
692         return false;
693     return true;
694   }
695   return b.used;
696 }
697 
698 // Local symbols are not in the linker's symbol table. This function scans
699 // each object file's symbol table to copy local symbols to the output.
700 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
701   if (!in.symTab)
702     return;
703   for (InputFile *file : objectFiles) {
704     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
705     for (Symbol *b : f->getLocalSymbols()) {
706       if (!b->isLocal())
707         fatal(toString(f) +
708               ": broken object: getLocalSymbols returns a non-local symbol");
709       auto *dr = dyn_cast<Defined>(b);
710 
711       // No reason to keep local undefined symbol in symtab.
712       if (!dr)
713         continue;
714       if (!includeInSymtab(*b))
715         continue;
716       if (!shouldKeepInSymtab(*dr))
717         continue;
718       in.symTab->addSymbol(b);
719     }
720   }
721 }
722 
723 // Create a section symbol for each output section so that we can represent
724 // relocations that point to the section. If we know that no relocation is
725 // referring to a section (that happens if the section is a synthetic one), we
726 // don't create a section symbol for that section.
727 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
728   for (BaseCommand *base : script->sectionCommands) {
729     auto *sec = dyn_cast<OutputSection>(base);
730     if (!sec)
731       continue;
732     auto i = llvm::find_if(sec->sectionCommands, [](BaseCommand *base) {
733       if (auto *isd = dyn_cast<InputSectionDescription>(base))
734         return !isd->sections.empty();
735       return false;
736     });
737     if (i == sec->sectionCommands.end())
738       continue;
739     InputSection *isec = cast<InputSectionDescription>(*i)->sections[0];
740 
741     // Relocations are not using REL[A] section symbols.
742     if (isec->type == SHT_REL || isec->type == SHT_RELA)
743       continue;
744 
745     // Unlike other synthetic sections, mergeable output sections contain data
746     // copied from input sections, and there may be a relocation pointing to its
747     // contents if -r or -emit-reloc are given.
748     if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
749       continue;
750 
751     auto *sym =
752         make<Defined>(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION,
753                       /*value=*/0, /*size=*/0, isec);
754     in.symTab->addSymbol(sym);
755   }
756 }
757 
758 // Today's loaders have a feature to make segments read-only after
759 // processing dynamic relocations to enhance security. PT_GNU_RELRO
760 // is defined for that.
761 //
762 // This function returns true if a section needs to be put into a
763 // PT_GNU_RELRO segment.
764 static bool isRelroSection(const OutputSection *sec) {
765   if (!config->zRelro)
766     return false;
767 
768   uint64_t flags = sec->flags;
769 
770   // Non-allocatable or non-writable sections don't need RELRO because
771   // they are not writable or not even mapped to memory in the first place.
772   // RELRO is for sections that are essentially read-only but need to
773   // be writable only at process startup to allow dynamic linker to
774   // apply relocations.
775   if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
776     return false;
777 
778   // Once initialized, TLS data segments are used as data templates
779   // for a thread-local storage. For each new thread, runtime
780   // allocates memory for a TLS and copy templates there. No thread
781   // are supposed to use templates directly. Thus, it can be in RELRO.
782   if (flags & SHF_TLS)
783     return true;
784 
785   // .init_array, .preinit_array and .fini_array contain pointers to
786   // functions that are executed on process startup or exit. These
787   // pointers are set by the static linker, and they are not expected
788   // to change at runtime. But if you are an attacker, you could do
789   // interesting things by manipulating pointers in .fini_array, for
790   // example. So they are put into RELRO.
791   uint32_t type = sec->type;
792   if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
793       type == SHT_PREINIT_ARRAY)
794     return true;
795 
796   // .got contains pointers to external symbols. They are resolved by
797   // the dynamic linker when a module is loaded into memory, and after
798   // that they are not expected to change. So, it can be in RELRO.
799   if (in.got && sec == in.got->getParent())
800     return true;
801 
802   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
803   // through r2 register, which is reserved for that purpose. Since r2 is used
804   // for accessing .got as well, .got and .toc need to be close enough in the
805   // virtual address space. Usually, .toc comes just after .got. Since we place
806   // .got into RELRO, .toc needs to be placed into RELRO too.
807   if (sec->name.equals(".toc"))
808     return true;
809 
810   // .got.plt contains pointers to external function symbols. They are
811   // by default resolved lazily, so we usually cannot put it into RELRO.
812   // However, if "-z now" is given, the lazy symbol resolution is
813   // disabled, which enables us to put it into RELRO.
814   if (sec == in.gotPlt->getParent())
815     return config->zNow;
816 
817   // .dynamic section contains data for the dynamic linker, and
818   // there's no need to write to it at runtime, so it's better to put
819   // it into RELRO.
820   if (sec->name == ".dynamic")
821     return true;
822 
823   // Sections with some special names are put into RELRO. This is a
824   // bit unfortunate because section names shouldn't be significant in
825   // ELF in spirit. But in reality many linker features depend on
826   // magic section names.
827   StringRef s = sec->name;
828   return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
829          s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
830          s == ".openbsd.randomdata";
831 }
832 
833 // We compute a rank for each section. The rank indicates where the
834 // section should be placed in the file.  Instead of using simple
835 // numbers (0,1,2...), we use a series of flags. One for each decision
836 // point when placing the section.
837 // Using flags has two key properties:
838 // * It is easy to check if a give branch was taken.
839 // * It is easy two see how similar two ranks are (see getRankProximity).
840 enum RankFlags {
841   RF_NOT_ADDR_SET = 1 << 27,
842   RF_NOT_ALLOC = 1 << 26,
843   RF_PARTITION = 1 << 18, // Partition number (8 bits)
844   RF_NOT_PART_EHDR = 1 << 17,
845   RF_NOT_PART_PHDR = 1 << 16,
846   RF_NOT_INTERP = 1 << 15,
847   RF_NOT_NOTE = 1 << 14,
848   RF_WRITE = 1 << 13,
849   RF_EXEC_WRITE = 1 << 12,
850   RF_EXEC = 1 << 11,
851   RF_RODATA = 1 << 10,
852   RF_NOT_RELRO = 1 << 9,
853   RF_NOT_TLS = 1 << 8,
854   RF_BSS = 1 << 7,
855   RF_PPC_NOT_TOCBSS = 1 << 6,
856   RF_PPC_TOCL = 1 << 5,
857   RF_PPC_TOC = 1 << 4,
858   RF_PPC_GOT = 1 << 3,
859   RF_PPC_BRANCH_LT = 1 << 2,
860   RF_MIPS_GPREL = 1 << 1,
861   RF_MIPS_NOT_GOT = 1 << 0
862 };
863 
864 static unsigned getSectionRank(const OutputSection *sec) {
865   unsigned rank = sec->partition * RF_PARTITION;
866 
867   // We want to put section specified by -T option first, so we
868   // can start assigning VA starting from them later.
869   if (config->sectionStartMap.count(sec->name))
870     return rank;
871   rank |= RF_NOT_ADDR_SET;
872 
873   // Allocatable sections go first to reduce the total PT_LOAD size and
874   // so debug info doesn't change addresses in actual code.
875   if (!(sec->flags & SHF_ALLOC))
876     return rank | RF_NOT_ALLOC;
877 
878   if (sec->type == SHT_LLVM_PART_EHDR)
879     return rank;
880   rank |= RF_NOT_PART_EHDR;
881 
882   if (sec->type == SHT_LLVM_PART_PHDR)
883     return rank;
884   rank |= RF_NOT_PART_PHDR;
885 
886   // Put .interp first because some loaders want to see that section
887   // on the first page of the executable file when loaded into memory.
888   if (sec->name == ".interp")
889     return rank;
890   rank |= RF_NOT_INTERP;
891 
892   // Put .note sections (which make up one PT_NOTE) at the beginning so that
893   // they are likely to be included in a core file even if core file size is
894   // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
895   // included in a core to match core files with executables.
896   if (sec->type == SHT_NOTE)
897     return rank;
898   rank |= RF_NOT_NOTE;
899 
900   // Sort sections based on their access permission in the following
901   // order: R, RX, RWX, RW.  This order is based on the following
902   // considerations:
903   // * Read-only sections come first such that they go in the
904   //   PT_LOAD covering the program headers at the start of the file.
905   // * Read-only, executable sections come next.
906   // * Writable, executable sections follow such that .plt on
907   //   architectures where it needs to be writable will be placed
908   //   between .text and .data.
909   // * Writable sections come last, such that .bss lands at the very
910   //   end of the last PT_LOAD.
911   bool isExec = sec->flags & SHF_EXECINSTR;
912   bool isWrite = sec->flags & SHF_WRITE;
913 
914   if (isExec) {
915     if (isWrite)
916       rank |= RF_EXEC_WRITE;
917     else
918       rank |= RF_EXEC;
919   } else if (isWrite) {
920     rank |= RF_WRITE;
921   } else if (sec->type == SHT_PROGBITS) {
922     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
923     // .eh_frame) closer to .text. They likely contain PC or GOT relative
924     // relocations and there could be relocation overflow if other huge sections
925     // (.dynstr .dynsym) were placed in between.
926     rank |= RF_RODATA;
927   }
928 
929   // Place RelRo sections first. After considering SHT_NOBITS below, the
930   // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
931   // where | marks where page alignment happens. An alternative ordering is
932   // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
933   // waste more bytes due to 2 alignment places.
934   if (!isRelroSection(sec))
935     rank |= RF_NOT_RELRO;
936 
937   // If we got here we know that both A and B are in the same PT_LOAD.
938 
939   // The TLS initialization block needs to be a single contiguous block in a R/W
940   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
941   // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
942   // after PROGBITS.
943   if (!(sec->flags & SHF_TLS))
944     rank |= RF_NOT_TLS;
945 
946   // Within TLS sections, or within other RelRo sections, or within non-RelRo
947   // sections, place non-NOBITS sections first.
948   if (sec->type == SHT_NOBITS)
949     rank |= RF_BSS;
950 
951   // Some architectures have additional ordering restrictions for sections
952   // within the same PT_LOAD.
953   if (config->emachine == EM_PPC64) {
954     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
955     // that we would like to make sure appear is a specific order to maximize
956     // their coverage by a single signed 16-bit offset from the TOC base
957     // pointer. Conversely, the special .tocbss section should be first among
958     // all SHT_NOBITS sections. This will put it next to the loaded special
959     // PPC64 sections (and, thus, within reach of the TOC base pointer).
960     StringRef name = sec->name;
961     if (name != ".tocbss")
962       rank |= RF_PPC_NOT_TOCBSS;
963 
964     if (name == ".toc1")
965       rank |= RF_PPC_TOCL;
966 
967     if (name == ".toc")
968       rank |= RF_PPC_TOC;
969 
970     if (name == ".got")
971       rank |= RF_PPC_GOT;
972 
973     if (name == ".branch_lt")
974       rank |= RF_PPC_BRANCH_LT;
975   }
976 
977   if (config->emachine == EM_MIPS) {
978     // All sections with SHF_MIPS_GPREL flag should be grouped together
979     // because data in these sections is addressable with a gp relative address.
980     if (sec->flags & SHF_MIPS_GPREL)
981       rank |= RF_MIPS_GPREL;
982 
983     if (sec->name != ".got")
984       rank |= RF_MIPS_NOT_GOT;
985   }
986 
987   return rank;
988 }
989 
990 static bool compareSections(const BaseCommand *aCmd, const BaseCommand *bCmd) {
991   const OutputSection *a = cast<OutputSection>(aCmd);
992   const OutputSection *b = cast<OutputSection>(bCmd);
993 
994   if (a->sortRank != b->sortRank)
995     return a->sortRank < b->sortRank;
996 
997   if (!(a->sortRank & RF_NOT_ADDR_SET))
998     return config->sectionStartMap.lookup(a->name) <
999            config->sectionStartMap.lookup(b->name);
1000   return false;
1001 }
1002 
1003 void PhdrEntry::add(OutputSection *sec) {
1004   lastSec = sec;
1005   if (!firstSec)
1006     firstSec = sec;
1007   p_align = std::max(p_align, sec->alignment);
1008   if (p_type == PT_LOAD)
1009     sec->ptLoad = this;
1010 }
1011 
1012 // The beginning and the ending of .rel[a].plt section are marked
1013 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1014 // executable. The runtime needs these symbols in order to resolve
1015 // all IRELATIVE relocs on startup. For dynamic executables, we don't
1016 // need these symbols, since IRELATIVE relocs are resolved through GOT
1017 // and PLT. For details, see http://www.airs.com/blog/archives/403.
1018 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1019   if (config->relocatable || needsInterpSection())
1020     return;
1021 
1022   // By default, __rela_iplt_{start,end} belong to a dummy section 0
1023   // because .rela.plt might be empty and thus removed from output.
1024   // We'll override Out::elfHeader with In.relaIplt later when we are
1025   // sure that .rela.plt exists in output.
1026   ElfSym::relaIpltStart = addOptionalRegular(
1027       config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
1028       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1029 
1030   ElfSym::relaIpltEnd = addOptionalRegular(
1031       config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1032       Out::elfHeader, 0, STV_HIDDEN, STB_WEAK);
1033 }
1034 
1035 template <class ELFT>
1036 void Writer<ELFT>::forEachRelSec(
1037     llvm::function_ref<void(InputSectionBase &)> fn) {
1038   // Scan all relocations. Each relocation goes through a series
1039   // of tests to determine if it needs special treatment, such as
1040   // creating GOT, PLT, copy relocations, etc.
1041   // Note that relocations for non-alloc sections are directly
1042   // processed by InputSection::relocateNonAlloc.
1043   for (InputSectionBase *isec : inputSections)
1044     if (isec->isLive() && isa<InputSection>(isec) && (isec->flags & SHF_ALLOC))
1045       fn(*isec);
1046   for (Partition &part : partitions) {
1047     for (EhInputSection *es : part.ehFrame->sections)
1048       fn(*es);
1049     if (part.armExidx && part.armExidx->isLive())
1050       for (InputSection *ex : part.armExidx->exidxSections)
1051         fn(*ex);
1052   }
1053 }
1054 
1055 // This function generates assignments for predefined symbols (e.g. _end or
1056 // _etext) and inserts them into the commands sequence to be processed at the
1057 // appropriate time. This ensures that the value is going to be correct by the
1058 // time any references to these symbols are processed and is equivalent to
1059 // defining these symbols explicitly in the linker script.
1060 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1061   if (ElfSym::globalOffsetTable) {
1062     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1063     // to the start of the .got or .got.plt section.
1064     InputSection *gotSection = in.gotPlt;
1065     if (!target->gotBaseSymInGotPlt)
1066       gotSection = in.mipsGot ? cast<InputSection>(in.mipsGot)
1067                               : cast<InputSection>(in.got);
1068     ElfSym::globalOffsetTable->section = gotSection;
1069   }
1070 
1071   // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
1072   if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
1073     ElfSym::relaIpltStart->section = in.relaIplt;
1074     ElfSym::relaIpltEnd->section = in.relaIplt;
1075     ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1076   }
1077 
1078   PhdrEntry *last = nullptr;
1079   PhdrEntry *lastRO = nullptr;
1080 
1081   for (Partition &part : partitions) {
1082     for (PhdrEntry *p : part.phdrs) {
1083       if (p->p_type != PT_LOAD)
1084         continue;
1085       last = p;
1086       if (!(p->p_flags & PF_W))
1087         lastRO = p;
1088     }
1089   }
1090 
1091   if (lastRO) {
1092     // _etext is the first location after the last read-only loadable segment.
1093     if (ElfSym::etext1)
1094       ElfSym::etext1->section = lastRO->lastSec;
1095     if (ElfSym::etext2)
1096       ElfSym::etext2->section = lastRO->lastSec;
1097   }
1098 
1099   if (last) {
1100     // _edata points to the end of the last mapped initialized section.
1101     OutputSection *edata = nullptr;
1102     for (OutputSection *os : outputSections) {
1103       if (os->type != SHT_NOBITS)
1104         edata = os;
1105       if (os == last->lastSec)
1106         break;
1107     }
1108 
1109     if (ElfSym::edata1)
1110       ElfSym::edata1->section = edata;
1111     if (ElfSym::edata2)
1112       ElfSym::edata2->section = edata;
1113 
1114     // _end is the first location after the uninitialized data region.
1115     if (ElfSym::end1)
1116       ElfSym::end1->section = last->lastSec;
1117     if (ElfSym::end2)
1118       ElfSym::end2->section = last->lastSec;
1119   }
1120 
1121   if (ElfSym::bss)
1122     ElfSym::bss->section = findSection(".bss");
1123 
1124   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1125   // be equal to the _gp symbol's value.
1126   if (ElfSym::mipsGp) {
1127     // Find GP-relative section with the lowest address
1128     // and use this address to calculate default _gp value.
1129     for (OutputSection *os : outputSections) {
1130       if (os->flags & SHF_MIPS_GPREL) {
1131         ElfSym::mipsGp->section = os;
1132         ElfSym::mipsGp->value = 0x7ff0;
1133         break;
1134       }
1135     }
1136   }
1137 }
1138 
1139 // We want to find how similar two ranks are.
1140 // The more branches in getSectionRank that match, the more similar they are.
1141 // Since each branch corresponds to a bit flag, we can just use
1142 // countLeadingZeros.
1143 static int getRankProximityAux(OutputSection *a, OutputSection *b) {
1144   return countLeadingZeros(a->sortRank ^ b->sortRank);
1145 }
1146 
1147 static int getRankProximity(OutputSection *a, BaseCommand *b) {
1148   auto *sec = dyn_cast<OutputSection>(b);
1149   return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1;
1150 }
1151 
1152 // When placing orphan sections, we want to place them after symbol assignments
1153 // so that an orphan after
1154 //   begin_foo = .;
1155 //   foo : { *(foo) }
1156 //   end_foo = .;
1157 // doesn't break the intended meaning of the begin/end symbols.
1158 // We don't want to go over sections since findOrphanPos is the
1159 // one in charge of deciding the order of the sections.
1160 // We don't want to go over changes to '.', since doing so in
1161 //  rx_sec : { *(rx_sec) }
1162 //  . = ALIGN(0x1000);
1163 //  /* The RW PT_LOAD starts here*/
1164 //  rw_sec : { *(rw_sec) }
1165 // would mean that the RW PT_LOAD would become unaligned.
1166 static bool shouldSkip(BaseCommand *cmd) {
1167   if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1168     return assign->name != ".";
1169   return false;
1170 }
1171 
1172 // We want to place orphan sections so that they share as much
1173 // characteristics with their neighbors as possible. For example, if
1174 // both are rw, or both are tls.
1175 static std::vector<BaseCommand *>::iterator
1176 findOrphanPos(std::vector<BaseCommand *>::iterator b,
1177               std::vector<BaseCommand *>::iterator e) {
1178   OutputSection *sec = cast<OutputSection>(*e);
1179 
1180   // Find the first element that has as close a rank as possible.
1181   auto i = std::max_element(b, e, [=](BaseCommand *a, BaseCommand *b) {
1182     return getRankProximity(sec, a) < getRankProximity(sec, b);
1183   });
1184   if (i == e)
1185     return e;
1186 
1187   // Consider all existing sections with the same proximity.
1188   int proximity = getRankProximity(sec, *i);
1189   for (; i != e; ++i) {
1190     auto *curSec = dyn_cast<OutputSection>(*i);
1191     if (!curSec || !curSec->hasInputSections)
1192       continue;
1193     if (getRankProximity(sec, curSec) != proximity ||
1194         sec->sortRank < curSec->sortRank)
1195       break;
1196   }
1197 
1198   auto isOutputSecWithInputSections = [](BaseCommand *cmd) {
1199     auto *os = dyn_cast<OutputSection>(cmd);
1200     return os && os->hasInputSections;
1201   };
1202   auto j = std::find_if(llvm::make_reverse_iterator(i),
1203                         llvm::make_reverse_iterator(b),
1204                         isOutputSecWithInputSections);
1205   i = j.base();
1206 
1207   // As a special case, if the orphan section is the last section, put
1208   // it at the very end, past any other commands.
1209   // This matches bfd's behavior and is convenient when the linker script fully
1210   // specifies the start of the file, but doesn't care about the end (the non
1211   // alloc sections for example).
1212   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1213   if (nextSec == e)
1214     return e;
1215 
1216   while (i != e && shouldSkip(*i))
1217     ++i;
1218   return i;
1219 }
1220 
1221 // Builds section order for handling --symbol-ordering-file.
1222 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1223   DenseMap<const InputSectionBase *, int> sectionOrder;
1224   // Use the rarely used option -call-graph-ordering-file to sort sections.
1225   if (!config->callGraphProfile.empty())
1226     return computeCallGraphProfileOrder();
1227 
1228   if (config->symbolOrderingFile.empty())
1229     return sectionOrder;
1230 
1231   struct SymbolOrderEntry {
1232     int priority;
1233     bool present;
1234   };
1235 
1236   // Build a map from symbols to their priorities. Symbols that didn't
1237   // appear in the symbol ordering file have the lowest priority 0.
1238   // All explicitly mentioned symbols have negative (higher) priorities.
1239   DenseMap<StringRef, SymbolOrderEntry> symbolOrder;
1240   int priority = -config->symbolOrderingFile.size();
1241   for (StringRef s : config->symbolOrderingFile)
1242     symbolOrder.insert({s, {priority++, false}});
1243 
1244   // Build a map from sections to their priorities.
1245   auto addSym = [&](Symbol &sym) {
1246     auto it = symbolOrder.find(sym.getName());
1247     if (it == symbolOrder.end())
1248       return;
1249     SymbolOrderEntry &ent = it->second;
1250     ent.present = true;
1251 
1252     maybeWarnUnorderableSymbol(&sym);
1253 
1254     if (auto *d = dyn_cast<Defined>(&sym)) {
1255       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1256         int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)];
1257         priority = std::min(priority, ent.priority);
1258       }
1259     }
1260   };
1261 
1262   // We want both global and local symbols. We get the global ones from the
1263   // symbol table and iterate the object files for the local ones.
1264   symtab->forEachSymbol([&](Symbol *sym) {
1265     if (!sym->isLazy())
1266       addSym(*sym);
1267   });
1268 
1269   for (InputFile *file : objectFiles)
1270     for (Symbol *sym : file->getSymbols())
1271       if (sym->isLocal())
1272         addSym(*sym);
1273 
1274   if (config->warnSymbolOrdering)
1275     for (auto orderEntry : symbolOrder)
1276       if (!orderEntry.second.present)
1277         warn("symbol ordering file: no such symbol: " + orderEntry.first);
1278 
1279   return sectionOrder;
1280 }
1281 
1282 // Sorts the sections in ISD according to the provided section order.
1283 static void
1284 sortISDBySectionOrder(InputSectionDescription *isd,
1285                       const DenseMap<const InputSectionBase *, int> &order) {
1286   std::vector<InputSection *> unorderedSections;
1287   std::vector<std::pair<InputSection *, int>> orderedSections;
1288   uint64_t unorderedSize = 0;
1289 
1290   for (InputSection *isec : isd->sections) {
1291     auto i = order.find(isec);
1292     if (i == order.end()) {
1293       unorderedSections.push_back(isec);
1294       unorderedSize += isec->getSize();
1295       continue;
1296     }
1297     orderedSections.push_back({isec, i->second});
1298   }
1299   llvm::sort(orderedSections, [&](std::pair<InputSection *, int> a,
1300                                   std::pair<InputSection *, int> b) {
1301     return a.second < b.second;
1302   });
1303 
1304   // Find an insertion point for the ordered section list in the unordered
1305   // section list. On targets with limited-range branches, this is the mid-point
1306   // of the unordered section list. This decreases the likelihood that a range
1307   // extension thunk will be needed to enter or exit the ordered region. If the
1308   // ordered section list is a list of hot functions, we can generally expect
1309   // the ordered functions to be called more often than the unordered functions,
1310   // making it more likely that any particular call will be within range, and
1311   // therefore reducing the number of thunks required.
1312   //
1313   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1314   // If the layout is:
1315   //
1316   // 8MB hot
1317   // 32MB cold
1318   //
1319   // only the first 8-16MB of the cold code (depending on which hot function it
1320   // is actually calling) can call the hot code without a range extension thunk.
1321   // However, if we use this layout:
1322   //
1323   // 16MB cold
1324   // 8MB hot
1325   // 16MB cold
1326   //
1327   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1328   // of the second block of cold code can call the hot code without a thunk. So
1329   // we effectively double the amount of code that could potentially call into
1330   // the hot code without a thunk.
1331   size_t insPt = 0;
1332   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1333     uint64_t unorderedPos = 0;
1334     for (; insPt != unorderedSections.size(); ++insPt) {
1335       unorderedPos += unorderedSections[insPt]->getSize();
1336       if (unorderedPos > unorderedSize / 2)
1337         break;
1338     }
1339   }
1340 
1341   isd->sections.clear();
1342   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1343     isd->sections.push_back(isec);
1344   for (std::pair<InputSection *, int> p : orderedSections)
1345     isd->sections.push_back(p.first);
1346   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1347     isd->sections.push_back(isec);
1348 }
1349 
1350 static void sortSection(OutputSection *sec,
1351                         const DenseMap<const InputSectionBase *, int> &order) {
1352   StringRef name = sec->name;
1353 
1354   // Sort input sections by section name suffixes for
1355   // __attribute__((init_priority(N))).
1356   if (name == ".init_array" || name == ".fini_array") {
1357     if (!script->hasSectionsCommand)
1358       sec->sortInitFini();
1359     return;
1360   }
1361 
1362   // Sort input sections by the special rule for .ctors and .dtors.
1363   if (name == ".ctors" || name == ".dtors") {
1364     if (!script->hasSectionsCommand)
1365       sec->sortCtorsDtors();
1366     return;
1367   }
1368 
1369   // Never sort these.
1370   if (name == ".init" || name == ".fini")
1371     return;
1372 
1373   // .toc is allocated just after .got and is accessed using GOT-relative
1374   // relocations. Object files compiled with small code model have an
1375   // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1376   // To reduce the risk of relocation overflow, .toc contents are sorted so that
1377   // sections having smaller relocation offsets are at beginning of .toc
1378   if (config->emachine == EM_PPC64 && name == ".toc") {
1379     if (script->hasSectionsCommand)
1380       return;
1381     assert(sec->sectionCommands.size() == 1);
1382     auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]);
1383     llvm::stable_sort(isd->sections,
1384                       [](const InputSection *a, const InputSection *b) -> bool {
1385                         return a->file->ppc64SmallCodeModelTocRelocs &&
1386                                !b->file->ppc64SmallCodeModelTocRelocs;
1387                       });
1388     return;
1389   }
1390 
1391   // Sort input sections by priority using the list provided
1392   // by --symbol-ordering-file.
1393   if (!order.empty())
1394     for (BaseCommand *b : sec->sectionCommands)
1395       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1396         sortISDBySectionOrder(isd, order);
1397 }
1398 
1399 // If no layout was provided by linker script, we want to apply default
1400 // sorting for special input sections. This also handles --symbol-ordering-file.
1401 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1402   // Build the order once since it is expensive.
1403   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1404   for (BaseCommand *base : script->sectionCommands)
1405     if (auto *sec = dyn_cast<OutputSection>(base))
1406       sortSection(sec, order);
1407 }
1408 
1409 template <class ELFT> void Writer<ELFT>::sortSections() {
1410   script->adjustSectionsBeforeSorting();
1411 
1412   // Don't sort if using -r. It is not necessary and we want to preserve the
1413   // relative order for SHF_LINK_ORDER sections.
1414   if (config->relocatable)
1415     return;
1416 
1417   sortInputSections();
1418 
1419   for (BaseCommand *base : script->sectionCommands) {
1420     auto *os = dyn_cast<OutputSection>(base);
1421     if (!os)
1422       continue;
1423     os->sortRank = getSectionRank(os);
1424 
1425     // We want to assign rude approximation values to outSecOff fields
1426     // to know the relative order of the input sections. We use it for
1427     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1428     uint64_t i = 0;
1429     for (InputSection *sec : getInputSections(os))
1430       sec->outSecOff = i++;
1431   }
1432 
1433   if (!script->hasSectionsCommand) {
1434     // We know that all the OutputSections are contiguous in this case.
1435     auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); };
1436     std::stable_sort(
1437         llvm::find_if(script->sectionCommands, isSection),
1438         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1439         compareSections);
1440     return;
1441   }
1442 
1443   // Orphan sections are sections present in the input files which are
1444   // not explicitly placed into the output file by the linker script.
1445   //
1446   // The sections in the linker script are already in the correct
1447   // order. We have to figuere out where to insert the orphan
1448   // sections.
1449   //
1450   // The order of the sections in the script is arbitrary and may not agree with
1451   // compareSections. This means that we cannot easily define a strict weak
1452   // ordering. To see why, consider a comparison of a section in the script and
1453   // one not in the script. We have a two simple options:
1454   // * Make them equivalent (a is not less than b, and b is not less than a).
1455   //   The problem is then that equivalence has to be transitive and we can
1456   //   have sections a, b and c with only b in a script and a less than c
1457   //   which breaks this property.
1458   // * Use compareSectionsNonScript. Given that the script order doesn't have
1459   //   to match, we can end up with sections a, b, c, d where b and c are in the
1460   //   script and c is compareSectionsNonScript less than b. In which case d
1461   //   can be equivalent to c, a to b and d < a. As a concrete example:
1462   //   .a (rx) # not in script
1463   //   .b (rx) # in script
1464   //   .c (ro) # in script
1465   //   .d (ro) # not in script
1466   //
1467   // The way we define an order then is:
1468   // *  Sort only the orphan sections. They are in the end right now.
1469   // *  Move each orphan section to its preferred position. We try
1470   //    to put each section in the last position where it can share
1471   //    a PT_LOAD.
1472   //
1473   // There is some ambiguity as to where exactly a new entry should be
1474   // inserted, because Commands contains not only output section
1475   // commands but also other types of commands such as symbol assignment
1476   // expressions. There's no correct answer here due to the lack of the
1477   // formal specification of the linker script. We use heuristics to
1478   // determine whether a new output command should be added before or
1479   // after another commands. For the details, look at shouldSkip
1480   // function.
1481 
1482   auto i = script->sectionCommands.begin();
1483   auto e = script->sectionCommands.end();
1484   auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) {
1485     if (auto *sec = dyn_cast<OutputSection>(base))
1486       return sec->sectionIndex == UINT32_MAX;
1487     return false;
1488   });
1489 
1490   // Sort the orphan sections.
1491   std::stable_sort(nonScriptI, e, compareSections);
1492 
1493   // As a horrible special case, skip the first . assignment if it is before any
1494   // section. We do this because it is common to set a load address by starting
1495   // the script with ". = 0xabcd" and the expectation is that every section is
1496   // after that.
1497   auto firstSectionOrDotAssignment =
1498       std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); });
1499   if (firstSectionOrDotAssignment != e &&
1500       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1501     ++firstSectionOrDotAssignment;
1502   i = firstSectionOrDotAssignment;
1503 
1504   while (nonScriptI != e) {
1505     auto pos = findOrphanPos(i, nonScriptI);
1506     OutputSection *orphan = cast<OutputSection>(*nonScriptI);
1507 
1508     // As an optimization, find all sections with the same sort rank
1509     // and insert them with one rotate.
1510     unsigned rank = orphan->sortRank;
1511     auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) {
1512       return cast<OutputSection>(cmd)->sortRank != rank;
1513     });
1514     std::rotate(pos, nonScriptI, end);
1515     nonScriptI = end;
1516   }
1517 
1518   script->adjustSectionsAfterSorting();
1519 }
1520 
1521 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1522   InputSection *la = a->getLinkOrderDep();
1523   InputSection *lb = b->getLinkOrderDep();
1524   OutputSection *aOut = la->getParent();
1525   OutputSection *bOut = lb->getParent();
1526 
1527   if (aOut != bOut)
1528     return aOut->sectionIndex < bOut->sectionIndex;
1529   return la->outSecOff < lb->outSecOff;
1530 }
1531 
1532 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1533   for (OutputSection *sec : outputSections) {
1534     if (!(sec->flags & SHF_LINK_ORDER))
1535       continue;
1536 
1537     // Link order may be distributed across several InputSectionDescriptions
1538     // but sort must consider them all at once.
1539     std::vector<InputSection **> scriptSections;
1540     std::vector<InputSection *> sections;
1541     for (BaseCommand *base : sec->sectionCommands) {
1542       if (auto *isd = dyn_cast<InputSectionDescription>(base)) {
1543         for (InputSection *&isec : isd->sections) {
1544           scriptSections.push_back(&isec);
1545           sections.push_back(isec);
1546         }
1547       }
1548     }
1549 
1550     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1551     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1552     if (!config->relocatable && config->emachine == EM_ARM &&
1553         sec->type == SHT_ARM_EXIDX)
1554       continue;
1555 
1556     llvm::stable_sort(sections, compareByFilePosition);
1557 
1558     for (int i = 0, n = sections.size(); i < n; ++i)
1559       *scriptSections[i] = sections[i];
1560   }
1561 }
1562 
1563 // We need to generate and finalize the content that depends on the address of
1564 // InputSections. As the generation of the content may also alter InputSection
1565 // addresses we must converge to a fixed point. We do that here. See the comment
1566 // in Writer<ELFT>::finalizeSections().
1567 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1568   ThunkCreator tc;
1569   AArch64Err843419Patcher a64p;
1570 
1571   // For some targets, like x86, this loop iterates only once.
1572   for (;;) {
1573     bool changed = false;
1574 
1575     script->assignAddresses();
1576 
1577     if (target->needsThunks)
1578       changed |= tc.createThunks(outputSections);
1579 
1580     if (config->fixCortexA53Errata843419) {
1581       if (changed)
1582         script->assignAddresses();
1583       changed |= a64p.createFixes();
1584     }
1585 
1586     if (in.mipsGot)
1587       in.mipsGot->updateAllocSize();
1588 
1589     for (Partition &part : partitions) {
1590       changed |= part.relaDyn->updateAllocSize();
1591       if (part.relrDyn)
1592         changed |= part.relrDyn->updateAllocSize();
1593     }
1594 
1595     if (!changed)
1596       return;
1597   }
1598 }
1599 
1600 static void finalizeSynthetic(SyntheticSection *sec) {
1601   if (sec && sec->isNeeded() && sec->getParent())
1602     sec->finalizeContents();
1603 }
1604 
1605 // In order to allow users to manipulate linker-synthesized sections,
1606 // we had to add synthetic sections to the input section list early,
1607 // even before we make decisions whether they are needed. This allows
1608 // users to write scripts like this: ".mygot : { .got }".
1609 //
1610 // Doing it has an unintended side effects. If it turns out that we
1611 // don't need a .got (for example) at all because there's no
1612 // relocation that needs a .got, we don't want to emit .got.
1613 //
1614 // To deal with the above problem, this function is called after
1615 // scanRelocations is called to remove synthetic sections that turn
1616 // out to be empty.
1617 static void removeUnusedSyntheticSections() {
1618   // All input synthetic sections that can be empty are placed after
1619   // all regular ones. We iterate over them all and exit at first
1620   // non-synthetic.
1621   for (InputSectionBase *s : llvm::reverse(inputSections)) {
1622     SyntheticSection *ss = dyn_cast<SyntheticSection>(s);
1623     if (!ss)
1624       return;
1625     OutputSection *os = ss->getParent();
1626     if (!os || ss->isNeeded())
1627       continue;
1628 
1629     // If we reach here, then SS is an unused synthetic section and we want to
1630     // remove it from corresponding input section description of output section.
1631     for (BaseCommand *b : os->sectionCommands)
1632       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1633         llvm::erase_if(isd->sections,
1634                        [=](InputSection *isec) { return isec == ss; });
1635   }
1636 }
1637 
1638 // Returns true if a symbol can be replaced at load-time by a symbol
1639 // with the same name defined in other ELF executable or DSO.
1640 static bool computeIsPreemptible(const Symbol &b) {
1641   assert(!b.isLocal());
1642 
1643   // Only symbols that appear in dynsym can be preempted.
1644   if (!b.includeInDynsym())
1645     return false;
1646 
1647   // Only default visibility symbols can be preempted.
1648   if (b.visibility != STV_DEFAULT)
1649     return false;
1650 
1651   // At this point copy relocations have not been created yet, so any
1652   // symbol that is not defined locally is preemptible.
1653   if (!b.isDefined())
1654     return true;
1655 
1656   // If we have a dynamic list it specifies which local symbols are preemptible.
1657   if (config->hasDynamicList)
1658     return false;
1659 
1660   if (!config->shared)
1661     return false;
1662 
1663   // -Bsymbolic means that definitions are not preempted.
1664   if (config->bsymbolic || (config->bsymbolicFunctions && b.isFunc()))
1665     return false;
1666   return true;
1667 }
1668 
1669 // Create output section objects and add them to OutputSections.
1670 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1671   Out::preinitArray = findSection(".preinit_array");
1672   Out::initArray = findSection(".init_array");
1673   Out::finiArray = findSection(".fini_array");
1674 
1675   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1676   // symbols for sections, so that the runtime can get the start and end
1677   // addresses of each section by section name. Add such symbols.
1678   if (!config->relocatable) {
1679     addStartEndSymbols();
1680     for (BaseCommand *base : script->sectionCommands)
1681       if (auto *sec = dyn_cast<OutputSection>(base))
1682         addStartStopSymbols(sec);
1683   }
1684 
1685   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1686   // It should be okay as no one seems to care about the type.
1687   // Even the author of gold doesn't remember why gold behaves that way.
1688   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1689   if (mainPart->dynamic->parent)
1690     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK,
1691                               STV_HIDDEN, STT_NOTYPE,
1692                               /*value=*/0, /*size=*/0, mainPart->dynamic});
1693 
1694   // Define __rel[a]_iplt_{start,end} symbols if needed.
1695   addRelIpltSymbols();
1696 
1697   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1698   // This symbol should only be defined in an executable.
1699   if (config->emachine == EM_RISCV && !config->shared)
1700     ElfSym::riscvGlobalPointer =
1701         addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800,
1702                            STV_DEFAULT, STB_GLOBAL);
1703 
1704   if (config->emachine == EM_X86_64) {
1705     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1706     // way that:
1707     //
1708     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1709     // computes 0.
1710     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1711     // the TLS block).
1712     //
1713     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1714     // an absolute symbol of zero. This is different from GNU linkers which
1715     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1716     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1717     if (s && s->isUndefined()) {
1718       s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN,
1719                          STT_TLS, /*value=*/0, 0,
1720                          /*section=*/nullptr});
1721       ElfSym::tlsModuleBase = cast<Defined>(s);
1722     }
1723   }
1724 
1725   // This responsible for splitting up .eh_frame section into
1726   // pieces. The relocation scan uses those pieces, so this has to be
1727   // earlier.
1728   for (Partition &part : partitions)
1729     finalizeSynthetic(part.ehFrame);
1730 
1731   symtab->forEachSymbol([](Symbol *s) {
1732     if (!s->isPreemptible)
1733       s->isPreemptible = computeIsPreemptible(*s);
1734   });
1735 
1736   // Scan relocations. This must be done after every symbol is declared so that
1737   // we can correctly decide if a dynamic relocation is needed.
1738   if (!config->relocatable) {
1739     forEachRelSec(scanRelocations<ELFT>);
1740     reportUndefinedSymbols<ELFT>();
1741   }
1742 
1743   addIRelativeRelocs();
1744 
1745   if (in.plt && in.plt->isNeeded())
1746     in.plt->addSymbols();
1747   if (in.iplt && in.iplt->isNeeded())
1748     in.iplt->addSymbols();
1749 
1750   if (!config->allowShlibUndefined) {
1751     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1752     // entires are seen. These cases would otherwise lead to runtime errors
1753     // reported by the dynamic linker.
1754     //
1755     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1756     // catch more cases. That is too much for us. Our approach resembles the one
1757     // used in ld.gold, achieves a good balance to be useful but not too smart.
1758     for (SharedFile *file : sharedFiles)
1759       file->allNeededIsKnown =
1760           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1761             return symtab->soNames.count(needed);
1762           });
1763 
1764     symtab->forEachSymbol([](Symbol *sym) {
1765       if (sym->isUndefined() && !sym->isWeak())
1766         if (auto *f = dyn_cast_or_null<SharedFile>(sym->file))
1767           if (f->allNeededIsKnown)
1768             error(toString(f) + ": undefined reference to " + toString(*sym));
1769     });
1770   }
1771 
1772   // Now that we have defined all possible global symbols including linker-
1773   // synthesized ones. Visit all symbols to give the finishing touches.
1774   symtab->forEachSymbol([](Symbol *sym) {
1775     if (!includeInSymtab(*sym))
1776       return;
1777     if (in.symTab)
1778       in.symTab->addSymbol(sym);
1779 
1780     if (sym->includeInDynsym()) {
1781       partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1782       if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1783         if (file->isNeeded && !sym->isUndefined())
1784           addVerneed(sym);
1785     }
1786   });
1787 
1788   // We also need to scan the dynamic relocation tables of the other partitions
1789   // and add any referenced symbols to the partition's dynsym.
1790   for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1791     DenseSet<Symbol *> syms;
1792     for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1793       syms.insert(e.sym);
1794     for (DynamicReloc &reloc : part.relaDyn->relocs)
1795       if (reloc.sym && !reloc.useSymVA && syms.insert(reloc.sym).second)
1796         part.dynSymTab->addSymbol(reloc.sym);
1797   }
1798 
1799   // Do not proceed if there was an undefined symbol.
1800   if (errorCount())
1801     return;
1802 
1803   if (in.mipsGot)
1804     in.mipsGot->build();
1805 
1806   removeUnusedSyntheticSections();
1807 
1808   sortSections();
1809 
1810   // Now that we have the final list, create a list of all the
1811   // OutputSections for convenience.
1812   for (BaseCommand *base : script->sectionCommands)
1813     if (auto *sec = dyn_cast<OutputSection>(base))
1814       outputSections.push_back(sec);
1815 
1816   // Prefer command line supplied address over other constraints.
1817   for (OutputSection *sec : outputSections) {
1818     auto i = config->sectionStartMap.find(sec->name);
1819     if (i != config->sectionStartMap.end())
1820       sec->addrExpr = [=] { return i->second; };
1821   }
1822 
1823   // This is a bit of a hack. A value of 0 means undef, so we set it
1824   // to 1 to make __ehdr_start defined. The section number is not
1825   // particularly relevant.
1826   Out::elfHeader->sectionIndex = 1;
1827 
1828   for (size_t i = 0, e = outputSections.size(); i != e; ++i) {
1829     OutputSection *sec = outputSections[i];
1830     sec->sectionIndex = i + 1;
1831     sec->shName = in.shStrTab->addString(sec->name);
1832   }
1833 
1834   // Binary and relocatable output does not have PHDRS.
1835   // The headers have to be created before finalize as that can influence the
1836   // image base and the dynamic section on mips includes the image base.
1837   if (!config->relocatable && !config->oFormatBinary) {
1838     for (Partition &part : partitions) {
1839       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
1840                                               : createPhdrs(part);
1841       if (config->emachine == EM_ARM) {
1842         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1843         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
1844       }
1845       if (config->emachine == EM_MIPS) {
1846         // Add separate segments for MIPS-specific sections.
1847         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
1848         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
1849         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
1850       }
1851     }
1852     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
1853 
1854     // Find the TLS segment. This happens before the section layout loop so that
1855     // Android relocation packing can look up TLS symbol addresses. We only need
1856     // to care about the main partition here because all TLS symbols were moved
1857     // to the main partition (see MarkLive.cpp).
1858     for (PhdrEntry *p : mainPart->phdrs)
1859       if (p->p_type == PT_TLS)
1860         Out::tlsPhdr = p;
1861   }
1862 
1863   // Some symbols are defined in term of program headers. Now that we
1864   // have the headers, we can find out which sections they point to.
1865   setReservedSymbolSections();
1866 
1867   finalizeSynthetic(in.bss);
1868   finalizeSynthetic(in.bssRelRo);
1869   finalizeSynthetic(in.symTabShndx);
1870   finalizeSynthetic(in.shStrTab);
1871   finalizeSynthetic(in.strTab);
1872   finalizeSynthetic(in.got);
1873   finalizeSynthetic(in.mipsGot);
1874   finalizeSynthetic(in.igotPlt);
1875   finalizeSynthetic(in.gotPlt);
1876   finalizeSynthetic(in.relaIplt);
1877   finalizeSynthetic(in.relaPlt);
1878   finalizeSynthetic(in.plt);
1879   finalizeSynthetic(in.iplt);
1880   finalizeSynthetic(in.ppc32Got2);
1881   finalizeSynthetic(in.riscvSdata);
1882   finalizeSynthetic(in.partIndex);
1883 
1884   // Dynamic section must be the last one in this list and dynamic
1885   // symbol table section (dynSymTab) must be the first one.
1886   for (Partition &part : partitions) {
1887     finalizeSynthetic(part.armExidx);
1888     finalizeSynthetic(part.dynSymTab);
1889     finalizeSynthetic(part.gnuHashTab);
1890     finalizeSynthetic(part.hashTab);
1891     finalizeSynthetic(part.verDef);
1892     finalizeSynthetic(part.relaDyn);
1893     finalizeSynthetic(part.relrDyn);
1894     finalizeSynthetic(part.ehFrameHdr);
1895     finalizeSynthetic(part.verSym);
1896     finalizeSynthetic(part.verNeed);
1897     finalizeSynthetic(part.dynamic);
1898   }
1899 
1900   if (!script->hasSectionsCommand && !config->relocatable)
1901     fixSectionAlignments();
1902 
1903   // SHFLinkOrder processing must be processed after relative section placements are
1904   // known but before addresses are allocated.
1905   resolveShfLinkOrder();
1906 
1907   // This is used to:
1908   // 1) Create "thunks":
1909   //    Jump instructions in many ISAs have small displacements, and therefore
1910   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
1911   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
1912   //    responsibility to create and insert small pieces of code between
1913   //    sections to extend the ranges if jump targets are out of range. Such
1914   //    code pieces are called "thunks".
1915   //
1916   //    We add thunks at this stage. We couldn't do this before this point
1917   //    because this is the earliest point where we know sizes of sections and
1918   //    their layouts (that are needed to determine if jump targets are in
1919   //    range).
1920   //
1921   // 2) Update the sections. We need to generate content that depends on the
1922   //    address of InputSections. For example, MIPS GOT section content or
1923   //    android packed relocations sections content.
1924   //
1925   // 3) Assign the final values for the linker script symbols. Linker scripts
1926   //    sometimes using forward symbol declarations. We want to set the correct
1927   //    values. They also might change after adding the thunks.
1928   finalizeAddressDependentContent();
1929 
1930   // finalizeAddressDependentContent may have added local symbols to the static symbol table.
1931   finalizeSynthetic(in.symTab);
1932   finalizeSynthetic(in.ppc64LongBranchTarget);
1933 
1934   // Fill other section headers. The dynamic table is finalized
1935   // at the end because some tags like RELSZ depend on result
1936   // of finalizing other sections.
1937   for (OutputSection *sec : outputSections)
1938     sec->finalize();
1939 }
1940 
1941 // Ensure data sections are not mixed with executable sections when
1942 // -execute-only is used. -execute-only is a feature to make pages executable
1943 // but not readable, and the feature is currently supported only on AArch64.
1944 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1945   if (!config->executeOnly)
1946     return;
1947 
1948   for (OutputSection *os : outputSections)
1949     if (os->flags & SHF_EXECINSTR)
1950       for (InputSection *isec : getInputSections(os))
1951         if (!(isec->flags & SHF_EXECINSTR))
1952           error("cannot place " + toString(isec) + " into " + toString(os->name) +
1953                 ": -execute-only does not support intermingling data and code");
1954 }
1955 
1956 // The linker is expected to define SECNAME_start and SECNAME_end
1957 // symbols for a few sections. This function defines them.
1958 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1959   // If a section does not exist, there's ambiguity as to how we
1960   // define _start and _end symbols for an init/fini section. Since
1961   // the loader assume that the symbols are always defined, we need to
1962   // always define them. But what value? The loader iterates over all
1963   // pointers between _start and _end to run global ctors/dtors, so if
1964   // the section is empty, their symbol values don't actually matter
1965   // as long as _start and _end point to the same location.
1966   //
1967   // That said, we don't want to set the symbols to 0 (which is
1968   // probably the simplest value) because that could cause some
1969   // program to fail to link due to relocation overflow, if their
1970   // program text is above 2 GiB. We use the address of the .text
1971   // section instead to prevent that failure.
1972   //
1973   // In a rare sitaution, .text section may not exist. If that's the
1974   // case, use the image base address as a last resort.
1975   OutputSection *Default = findSection(".text");
1976   if (!Default)
1977     Default = Out::elfHeader;
1978 
1979   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
1980     if (os) {
1981       addOptionalRegular(start, os, 0);
1982       addOptionalRegular(end, os, -1);
1983     } else {
1984       addOptionalRegular(start, Default, 0);
1985       addOptionalRegular(end, Default, 0);
1986     }
1987   };
1988 
1989   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
1990   define("__init_array_start", "__init_array_end", Out::initArray);
1991   define("__fini_array_start", "__fini_array_end", Out::finiArray);
1992 
1993   if (OutputSection *sec = findSection(".ARM.exidx"))
1994     define("__exidx_start", "__exidx_end", sec);
1995 }
1996 
1997 // If a section name is valid as a C identifier (which is rare because of
1998 // the leading '.'), linkers are expected to define __start_<secname> and
1999 // __stop_<secname> symbols. They are at beginning and end of the section,
2000 // respectively. This is not requested by the ELF standard, but GNU ld and
2001 // gold provide the feature, and used by many programs.
2002 template <class ELFT>
2003 void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2004   StringRef s = sec->name;
2005   if (!isValidCIdentifier(s))
2006     return;
2007   addOptionalRegular(saver.save("__start_" + s), sec, 0, STV_PROTECTED);
2008   addOptionalRegular(saver.save("__stop_" + s), sec, -1, STV_PROTECTED);
2009 }
2010 
2011 static bool needsPtLoad(OutputSection *sec) {
2012   if (!(sec->flags & SHF_ALLOC) || sec->noload)
2013     return false;
2014 
2015   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2016   // responsible for allocating space for them, not the PT_LOAD that
2017   // contains the TLS initialization image.
2018   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2019     return false;
2020   return true;
2021 }
2022 
2023 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2024 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2025 // RW. This means that there is no alignment in the RO to RX transition and we
2026 // cannot create a PT_LOAD there.
2027 static uint64_t computeFlags(uint64_t flags) {
2028   if (config->omagic)
2029     return PF_R | PF_W | PF_X;
2030   if (config->executeOnly && (flags & PF_X))
2031     return flags & ~PF_R;
2032   if (config->singleRoRx && !(flags & PF_W))
2033     return flags | PF_X;
2034   return flags;
2035 }
2036 
2037 // Decide which program headers to create and which sections to include in each
2038 // one.
2039 template <class ELFT>
2040 std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) {
2041   std::vector<PhdrEntry *> ret;
2042   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2043     ret.push_back(make<PhdrEntry>(type, flags));
2044     return ret.back();
2045   };
2046 
2047   unsigned partNo = part.getNumber();
2048   bool isMain = partNo == 1;
2049 
2050   // The first phdr entry is PT_PHDR which describes the program header itself.
2051   if (isMain)
2052     addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2053   else
2054     addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2055 
2056   // PT_INTERP must be the second entry if exists.
2057   if (OutputSection *cmd = findSection(".interp", partNo))
2058     addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2059 
2060   // Add the first PT_LOAD segment for regular output sections.
2061   uint64_t flags = computeFlags(PF_R);
2062   PhdrEntry *load = nullptr;
2063 
2064   // Add the headers. We will remove them if they don't fit.
2065   // In the other partitions the headers are ordinary sections, so they don't
2066   // need to be added here.
2067   if (isMain) {
2068     load = addHdr(PT_LOAD, flags);
2069     load->add(Out::elfHeader);
2070     load->add(Out::programHeaders);
2071   }
2072 
2073   // PT_GNU_RELRO includes all sections that should be marked as
2074   // read-only by dynamic linker after proccessing relocations.
2075   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2076   // an error message if more than one PT_GNU_RELRO PHDR is required.
2077   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2078   bool inRelroPhdr = false;
2079   OutputSection *relroEnd = nullptr;
2080   for (OutputSection *sec : outputSections) {
2081     if (sec->partition != partNo || !needsPtLoad(sec))
2082       continue;
2083     if (isRelroSection(sec)) {
2084       inRelroPhdr = true;
2085       if (!relroEnd)
2086         relRo->add(sec);
2087       else
2088         error("section: " + sec->name + " is not contiguous with other relro" +
2089               " sections");
2090     } else if (inRelroPhdr) {
2091       inRelroPhdr = false;
2092       relroEnd = sec;
2093     }
2094   }
2095 
2096   for (OutputSection *sec : outputSections) {
2097     if (!(sec->flags & SHF_ALLOC))
2098       break;
2099     if (!needsPtLoad(sec))
2100       continue;
2101 
2102     // Normally, sections in partitions other than the current partition are
2103     // ignored. But partition number 255 is a special case: it contains the
2104     // partition end marker (.part.end). It needs to be added to the main
2105     // partition so that a segment is created for it in the main partition,
2106     // which will cause the dynamic loader to reserve space for the other
2107     // partitions.
2108     if (sec->partition != partNo) {
2109       if (isMain && sec->partition == 255)
2110         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2111       continue;
2112     }
2113 
2114     // Segments are contiguous memory regions that has the same attributes
2115     // (e.g. executable or writable). There is one phdr for each segment.
2116     // Therefore, we need to create a new phdr when the next section has
2117     // different flags or is loaded at a discontiguous address or memory
2118     // region using AT or AT> linker script command, respectively. At the same
2119     // time, we don't want to create a separate load segment for the headers,
2120     // even if the first output section has an AT or AT> attribute.
2121     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2122     if (!load ||
2123         ((sec->lmaExpr ||
2124           (sec->lmaRegion && (sec->lmaRegion != load->firstSec->lmaRegion))) &&
2125          load->lastSec != Out::programHeaders) ||
2126         sec->memRegion != load->firstSec->memRegion || flags != newFlags ||
2127         sec == relroEnd) {
2128       load = addHdr(PT_LOAD, newFlags);
2129       flags = newFlags;
2130     }
2131 
2132     load->add(sec);
2133   }
2134 
2135   // Add a TLS segment if any.
2136   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2137   for (OutputSection *sec : outputSections)
2138     if (sec->partition == partNo && sec->flags & SHF_TLS)
2139       tlsHdr->add(sec);
2140   if (tlsHdr->firstSec)
2141     ret.push_back(tlsHdr);
2142 
2143   // Add an entry for .dynamic.
2144   if (OutputSection *sec = part.dynamic->getParent())
2145     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2146 
2147   if (relRo->firstSec)
2148     ret.push_back(relRo);
2149 
2150   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2151   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2152       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2153     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2154         ->add(part.ehFrameHdr->getParent());
2155 
2156   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2157   // the dynamic linker fill the segment with random data.
2158   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2159     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2160 
2161   // PT_GNU_STACK is a special section to tell the loader to make the
2162   // pages for the stack non-executable. If you really want an executable
2163   // stack, you can pass -z execstack, but that's not recommended for
2164   // security reasons.
2165   unsigned perm = PF_R | PF_W;
2166   if (config->zExecstack)
2167     perm |= PF_X;
2168   addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2169 
2170   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2171   // is expected to perform W^X violations, such as calling mprotect(2) or
2172   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2173   // OpenBSD.
2174   if (config->zWxneeded)
2175     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2176 
2177   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2178   // same alignment.
2179   PhdrEntry *note = nullptr;
2180   for (OutputSection *sec : outputSections) {
2181     if (sec->partition != partNo)
2182       continue;
2183     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2184       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2185         note = addHdr(PT_NOTE, PF_R);
2186       note->add(sec);
2187     } else {
2188       note = nullptr;
2189     }
2190   }
2191   return ret;
2192 }
2193 
2194 template <class ELFT>
2195 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2196                                      unsigned pType, unsigned pFlags) {
2197   unsigned partNo = part.getNumber();
2198   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2199     return cmd->partition == partNo && cmd->type == shType;
2200   });
2201   if (i == outputSections.end())
2202     return;
2203 
2204   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2205   entry->add(*i);
2206   part.phdrs.push_back(entry);
2207 }
2208 
2209 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2210 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2211 // linker can set the permissions.
2212 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2213   auto pageAlign = [](OutputSection *cmd) {
2214     if (cmd && !cmd->addrExpr)
2215       cmd->addrExpr = [=] {
2216         return alignTo(script->getDot(), config->maxPageSize);
2217       };
2218   };
2219 
2220   for (Partition &part : partitions) {
2221     for (const PhdrEntry *p : part.phdrs)
2222       if (p->p_type == PT_LOAD && p->firstSec)
2223         pageAlign(p->firstSec);
2224   }
2225 }
2226 
2227 // Compute an in-file position for a given section. The file offset must be the
2228 // same with its virtual address modulo the page size, so that the loader can
2229 // load executables without any address adjustment.
2230 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2231   // File offsets are not significant for .bss sections. By convention, we keep
2232   // section offsets monotonically increasing rather than setting to zero.
2233   if (os->type == SHT_NOBITS)
2234     return off;
2235 
2236   // If the section is not in a PT_LOAD, we just have to align it.
2237   if (!os->ptLoad)
2238     return alignTo(off, os->alignment);
2239 
2240   // The first section in a PT_LOAD has to have congruent offset and address
2241   // module the page size.
2242   OutputSection *first = os->ptLoad->firstSec;
2243   if (os == first) {
2244     uint64_t alignment = std::max<uint64_t>(os->alignment, config->maxPageSize);
2245     return alignTo(off, alignment, os->addr);
2246   }
2247 
2248   // If two sections share the same PT_LOAD the file offset is calculated
2249   // using this formula: Off2 = Off1 + (VA2 - VA1).
2250   return first->offset + os->addr - first->addr;
2251 }
2252 
2253 // Set an in-file position to a given section and returns the end position of
2254 // the section.
2255 static uint64_t setFileOffset(OutputSection *os, uint64_t off) {
2256   off = computeFileOffset(os, off);
2257   os->offset = off;
2258 
2259   if (os->type == SHT_NOBITS)
2260     return off;
2261   return off + os->size;
2262 }
2263 
2264 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2265   uint64_t off = 0;
2266   for (OutputSection *sec : outputSections)
2267     if (sec->flags & SHF_ALLOC)
2268       off = setFileOffset(sec, off);
2269   fileSize = alignTo(off, config->wordsize);
2270 }
2271 
2272 static std::string rangeToString(uint64_t addr, uint64_t len) {
2273   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2274 }
2275 
2276 // Assign file offsets to output sections.
2277 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2278   uint64_t off = 0;
2279   off = setFileOffset(Out::elfHeader, off);
2280   off = setFileOffset(Out::programHeaders, off);
2281 
2282   PhdrEntry *lastRX = nullptr;
2283   for (Partition &part : partitions)
2284     for (PhdrEntry *p : part.phdrs)
2285       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2286         lastRX = p;
2287 
2288   for (OutputSection *sec : outputSections) {
2289     off = setFileOffset(sec, off);
2290 
2291     // If this is a last section of the last executable segment and that
2292     // segment is the last loadable segment, align the offset of the
2293     // following section to avoid loading non-segments parts of the file.
2294     if (config->zSeparateCode && lastRX && lastRX->lastSec == sec)
2295       off = alignTo(off, config->commonPageSize);
2296   }
2297 
2298   sectionHeaderOff = alignTo(off, config->wordsize);
2299   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2300 
2301   // Our logic assumes that sections have rising VA within the same segment.
2302   // With use of linker scripts it is possible to violate this rule and get file
2303   // offset overlaps or overflows. That should never happen with a valid script
2304   // which does not move the location counter backwards and usually scripts do
2305   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2306   // kernel, which control segment distribution explicitly and move the counter
2307   // backwards, so we have to allow doing that to support linking them. We
2308   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2309   // we want to prevent file size overflows because it would crash the linker.
2310   for (OutputSection *sec : outputSections) {
2311     if (sec->type == SHT_NOBITS)
2312       continue;
2313     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2314       error("unable to place section " + sec->name + " at file offset " +
2315             rangeToString(sec->offset, sec->size) +
2316             "; check your linker script for overflows");
2317   }
2318 }
2319 
2320 // Finalize the program headers. We call this function after we assign
2321 // file offsets and VAs to all sections.
2322 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2323   for (PhdrEntry *p : part.phdrs) {
2324     OutputSection *first = p->firstSec;
2325     OutputSection *last = p->lastSec;
2326 
2327     if (first) {
2328       p->p_filesz = last->offset - first->offset;
2329       if (last->type != SHT_NOBITS)
2330         p->p_filesz += last->size;
2331 
2332       p->p_memsz = last->addr + last->size - first->addr;
2333       p->p_offset = first->offset;
2334       p->p_vaddr = first->addr;
2335 
2336       // File offsets in partitions other than the main partition are relative
2337       // to the offset of the ELF headers. Perform that adjustment now.
2338       if (part.elfHeader)
2339         p->p_offset -= part.elfHeader->getParent()->offset;
2340 
2341       if (!p->hasLMA)
2342         p->p_paddr = first->getLMA();
2343     }
2344 
2345     if (p->p_type == PT_LOAD) {
2346       p->p_align = std::max<uint64_t>(p->p_align, config->maxPageSize);
2347     } else if (p->p_type == PT_GNU_RELRO) {
2348       p->p_align = 1;
2349       // The glibc dynamic loader rounds the size down, so we need to round up
2350       // to protect the last page. This is a no-op on FreeBSD which always
2351       // rounds up.
2352       p->p_memsz = alignTo(p->p_memsz, config->commonPageSize);
2353     }
2354   }
2355 }
2356 
2357 // A helper struct for checkSectionOverlap.
2358 namespace {
2359 struct SectionOffset {
2360   OutputSection *sec;
2361   uint64_t offset;
2362 };
2363 } // namespace
2364 
2365 // Check whether sections overlap for a specific address range (file offsets,
2366 // load and virtual adresses).
2367 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2368                          bool isVirtualAddr) {
2369   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2370     return a.offset < b.offset;
2371   });
2372 
2373   // Finding overlap is easy given a vector is sorted by start position.
2374   // If an element starts before the end of the previous element, they overlap.
2375   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2376     SectionOffset a = sections[i - 1];
2377     SectionOffset b = sections[i];
2378     if (b.offset >= a.offset + a.sec->size)
2379       continue;
2380 
2381     // If both sections are in OVERLAY we allow the overlapping of virtual
2382     // addresses, because it is what OVERLAY was designed for.
2383     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2384       continue;
2385 
2386     errorOrWarn("section " + a.sec->name + " " + name +
2387                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2388                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2389                 b.sec->name + " range is " +
2390                 rangeToString(b.offset, b.sec->size));
2391   }
2392 }
2393 
2394 // Check for overlapping sections and address overflows.
2395 //
2396 // In this function we check that none of the output sections have overlapping
2397 // file offsets. For SHF_ALLOC sections we also check that the load address
2398 // ranges and the virtual address ranges don't overlap
2399 template <class ELFT> void Writer<ELFT>::checkSections() {
2400   // First, check that section's VAs fit in available address space for target.
2401   for (OutputSection *os : outputSections)
2402     if ((os->addr + os->size < os->addr) ||
2403         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2404       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2405                   " of size 0x" + utohexstr(os->size) +
2406                   " exceeds available address space");
2407 
2408   // Check for overlapping file offsets. In this case we need to skip any
2409   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2410   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2411   // binary is specified only add SHF_ALLOC sections are added to the output
2412   // file so we skip any non-allocated sections in that case.
2413   std::vector<SectionOffset> fileOffs;
2414   for (OutputSection *sec : outputSections)
2415     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2416         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2417       fileOffs.push_back({sec, sec->offset});
2418   checkOverlap("file", fileOffs, false);
2419 
2420   // When linking with -r there is no need to check for overlapping virtual/load
2421   // addresses since those addresses will only be assigned when the final
2422   // executable/shared object is created.
2423   if (config->relocatable)
2424     return;
2425 
2426   // Checking for overlapping virtual and load addresses only needs to take
2427   // into account SHF_ALLOC sections since others will not be loaded.
2428   // Furthermore, we also need to skip SHF_TLS sections since these will be
2429   // mapped to other addresses at runtime and can therefore have overlapping
2430   // ranges in the file.
2431   std::vector<SectionOffset> vmas;
2432   for (OutputSection *sec : outputSections)
2433     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2434       vmas.push_back({sec, sec->addr});
2435   checkOverlap("virtual address", vmas, true);
2436 
2437   // Finally, check that the load addresses don't overlap. This will usually be
2438   // the same as the virtual addresses but can be different when using a linker
2439   // script with AT().
2440   std::vector<SectionOffset> lmas;
2441   for (OutputSection *sec : outputSections)
2442     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2443       lmas.push_back({sec, sec->getLMA()});
2444   checkOverlap("load address", lmas, false);
2445 }
2446 
2447 // The entry point address is chosen in the following ways.
2448 //
2449 // 1. the '-e' entry command-line option;
2450 // 2. the ENTRY(symbol) command in a linker control script;
2451 // 3. the value of the symbol _start, if present;
2452 // 4. the number represented by the entry symbol, if it is a number;
2453 // 5. the address of the first byte of the .text section, if present;
2454 // 6. the address 0.
2455 static uint64_t getEntryAddr() {
2456   // Case 1, 2 or 3
2457   if (Symbol *b = symtab->find(config->entry))
2458     return b->getVA();
2459 
2460   // Case 4
2461   uint64_t addr;
2462   if (to_integer(config->entry, addr))
2463     return addr;
2464 
2465   // Case 5
2466   if (OutputSection *sec = findSection(".text")) {
2467     if (config->warnMissingEntry)
2468       warn("cannot find entry symbol " + config->entry + "; defaulting to 0x" +
2469            utohexstr(sec->addr));
2470     return sec->addr;
2471   }
2472 
2473   // Case 6
2474   if (config->warnMissingEntry)
2475     warn("cannot find entry symbol " + config->entry +
2476          "; not setting start address");
2477   return 0;
2478 }
2479 
2480 static uint16_t getELFType() {
2481   if (config->isPic)
2482     return ET_DYN;
2483   if (config->relocatable)
2484     return ET_REL;
2485   return ET_EXEC;
2486 }
2487 
2488 template <class ELFT> void Writer<ELFT>::writeHeader() {
2489   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2490   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2491 
2492   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2493   eHdr->e_type = getELFType();
2494   eHdr->e_entry = getEntryAddr();
2495   eHdr->e_shoff = sectionHeaderOff;
2496 
2497   // Write the section header table.
2498   //
2499   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2500   // and e_shstrndx fields. When the value of one of these fields exceeds
2501   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2502   // use fields in the section header at index 0 to store
2503   // the value. The sentinel values and fields are:
2504   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2505   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2506   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2507   size_t num = outputSections.size() + 1;
2508   if (num >= SHN_LORESERVE)
2509     sHdrs->sh_size = num;
2510   else
2511     eHdr->e_shnum = num;
2512 
2513   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2514   if (strTabIndex >= SHN_LORESERVE) {
2515     sHdrs->sh_link = strTabIndex;
2516     eHdr->e_shstrndx = SHN_XINDEX;
2517   } else {
2518     eHdr->e_shstrndx = strTabIndex;
2519   }
2520 
2521   for (OutputSection *sec : outputSections)
2522     sec->writeHeaderTo<ELFT>(++sHdrs);
2523 }
2524 
2525 // Open a result file.
2526 template <class ELFT> void Writer<ELFT>::openFile() {
2527   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2528   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2529     error("output file too large: " + Twine(fileSize) + " bytes");
2530     return;
2531   }
2532 
2533   unlinkAsync(config->outputFile);
2534   unsigned flags = 0;
2535   if (!config->relocatable)
2536     flags = FileOutputBuffer::F_executable;
2537   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2538       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2539 
2540   if (!bufferOrErr) {
2541     error("failed to open " + config->outputFile + ": " +
2542           llvm::toString(bufferOrErr.takeError()));
2543     return;
2544   }
2545   buffer = std::move(*bufferOrErr);
2546   Out::bufferStart = buffer->getBufferStart();
2547 }
2548 
2549 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2550   for (OutputSection *sec : outputSections)
2551     if (sec->flags & SHF_ALLOC)
2552       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2553 }
2554 
2555 static void fillTrap(uint8_t *i, uint8_t *end) {
2556   for (; i + 4 <= end; i += 4)
2557     memcpy(i, &target->trapInstr, 4);
2558 }
2559 
2560 // Fill the last page of executable segments with trap instructions
2561 // instead of leaving them as zero. Even though it is not required by any
2562 // standard, it is in general a good thing to do for security reasons.
2563 //
2564 // We'll leave other pages in segments as-is because the rest will be
2565 // overwritten by output sections.
2566 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2567   if (!config->zSeparateCode)
2568     return;
2569 
2570   for (Partition &part : partitions) {
2571     // Fill the last page.
2572     for (PhdrEntry *p : part.phdrs)
2573       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2574         fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz,
2575                                               config->commonPageSize),
2576                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2577                                             config->commonPageSize));
2578 
2579     // Round up the file size of the last segment to the page boundary iff it is
2580     // an executable segment to ensure that other tools don't accidentally
2581     // trim the instruction padding (e.g. when stripping the file).
2582     PhdrEntry *last = nullptr;
2583     for (PhdrEntry *p : part.phdrs)
2584       if (p->p_type == PT_LOAD)
2585         last = p;
2586 
2587     if (last && (last->p_flags & PF_X))
2588       last->p_memsz = last->p_filesz =
2589           alignTo(last->p_filesz, config->commonPageSize);
2590   }
2591 }
2592 
2593 // Write section contents to a mmap'ed file.
2594 template <class ELFT> void Writer<ELFT>::writeSections() {
2595   // In -r or -emit-relocs mode, write the relocation sections first as in
2596   // ELf_Rel targets we might find out that we need to modify the relocated
2597   // section while doing it.
2598   for (OutputSection *sec : outputSections)
2599     if (sec->type == SHT_REL || sec->type == SHT_RELA)
2600       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2601 
2602   for (OutputSection *sec : outputSections)
2603     if (sec->type != SHT_REL && sec->type != SHT_RELA)
2604       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2605 }
2606 
2607 // Split one uint8 array into small pieces of uint8 arrays.
2608 static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> arr,
2609                                             size_t chunkSize) {
2610   std::vector<ArrayRef<uint8_t>> ret;
2611   while (arr.size() > chunkSize) {
2612     ret.push_back(arr.take_front(chunkSize));
2613     arr = arr.drop_front(chunkSize);
2614   }
2615   if (!arr.empty())
2616     ret.push_back(arr);
2617   return ret;
2618 }
2619 
2620 // Computes a hash value of Data using a given hash function.
2621 // In order to utilize multiple cores, we first split data into 1MB
2622 // chunks, compute a hash for each chunk, and then compute a hash value
2623 // of the hash values.
2624 static void
2625 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2626             llvm::ArrayRef<uint8_t> data,
2627             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2628   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2629   std::vector<uint8_t> hashes(chunks.size() * hashBuf.size());
2630 
2631   // Compute hash values.
2632   parallelForEachN(0, chunks.size(), [&](size_t i) {
2633     hashFn(hashes.data() + i * hashBuf.size(), chunks[i]);
2634   });
2635 
2636   // Write to the final output buffer.
2637   hashFn(hashBuf.data(), hashes);
2638 }
2639 
2640 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2641   if (!mainPart->buildId || !mainPart->buildId->getParent())
2642     return;
2643 
2644   if (config->buildId == BuildIdKind::Hexstring) {
2645     for (Partition &part : partitions)
2646       part.buildId->writeBuildId(config->buildIdVector);
2647     return;
2648   }
2649 
2650   // Compute a hash of all sections of the output file.
2651   size_t hashSize = mainPart->buildId->hashSize;
2652   std::vector<uint8_t> buildId(hashSize);
2653   llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)};
2654 
2655   switch (config->buildId) {
2656   case BuildIdKind::Fast:
2657     computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2658       write64le(dest, xxHash64(arr));
2659     });
2660     break;
2661   case BuildIdKind::Md5:
2662     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2663       memcpy(dest, MD5::hash(arr).data(), hashSize);
2664     });
2665     break;
2666   case BuildIdKind::Sha1:
2667     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2668       memcpy(dest, SHA1::hash(arr).data(), hashSize);
2669     });
2670     break;
2671   case BuildIdKind::Uuid:
2672     if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize))
2673       error("entropy source failure: " + ec.message());
2674     break;
2675   default:
2676     llvm_unreachable("unknown BuildIdKind");
2677   }
2678   for (Partition &part : partitions)
2679     part.buildId->writeBuildId(buildId);
2680 }
2681 
2682 template void elf::writeResult<ELF32LE>();
2683 template void elf::writeResult<ELF32BE>();
2684 template void elf::writeResult<ELF64LE>();
2685 template void elf::writeResult<ELF64BE>();
2686