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