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