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