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