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