Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lld / ELF / Writer.cpp
blob57e1aa06c6aa873574dfefc1e45455b06917cbb3
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 //===----------------------------------------------------------------------===//
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>
35 #define DEBUG_TYPE "lld"
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;
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)
51 Writer() : buffer(errorHandler().outputBuffer) {}
53 void run();
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();
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();
82 std::unique_ptr<FileOutputBuffer> &buffer;
84 void addRelIpltSymbols();
85 void addStartEndSymbols();
86 void addStartStopSymbols(OutputSection &osec);
88 uint64_t fileSize;
89 uint64_t sectionHeaderOff;
91 } // anonymous namespace
93 static bool needsInterpSection() {
94 return !config->relocatable && !config->shared &&
95 !config->dynamicLinker.empty() && script->needsInterpSection();
98 template <class ELFT> void elf::writeResult() {
99 Writer<ELFT>().run();
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;
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());
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);
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);
141 ctx.inputSections.insert(ctx.inputSections.end(), newSections.begin(),
142 newSections.end());
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;
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);
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);
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");
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");
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();
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_";
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;
212 uint64_t gotOff = 0;
213 if (config->emachine == EM_PPC64)
214 gotOff = 0x8000;
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);
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);
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);
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);
236 // If linker script do layout we do not need to create any standard symbols.
237 if (script->hasSectionsCommand)
238 return;
240 auto add = [](StringRef s, int64_t pos) {
241 return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
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);
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);
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.
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;
289 if (config->hasDynSymTab)
290 sym->isPreemptible = computeIsPreemptible(*sym);
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());
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;
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;
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);
333 auto add = [](SyntheticSection &sec) { ctx.inputSections.push_back(&sec); };
335 in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
337 Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
338 Out::programHeaders->addralign = config->wordsize;
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>();
346 in.bss = std::make_unique<BssSection>(".bss", 0, 1);
347 add(*in.bss);
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);
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);
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);
371 StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
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);
380 if (!part.name.empty()) {
381 part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
382 part.elfHeader->name = part.name;
383 add(*part.elfHeader);
385 part.programHeaders =
386 std::make_unique<PartitionProgramHeadersSection<ELFT>>();
387 add(*part.programHeaders);
390 if (config->buildId != BuildIdKind::None) {
391 part.buildId = std::make_unique<BuildIdSection>();
392 add(*part.buildId);
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>>();
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);
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);
414 if (config->hasDynSymTab) {
415 add(*part.dynSymTab);
417 part.verSym = std::make_unique<VersionTableSection>();
418 add(*part.verSym);
420 if (!namedVersionDefs().empty()) {
421 part.verDef = std::make_unique<VersionDefinitionSection>();
422 add(*part.verDef);
425 part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
426 add(*part.verNeed);
428 if (config->gnuHash) {
429 part.gnuHashTab = std::make_unique<GnuHashTableSection>();
430 add(*part.gnuHashTab);
433 if (config->sysvHash) {
434 part.hashTab = std::make_unique<HashTableSection>();
435 add(*part.hashTab);
438 add(*part.dynamic);
439 add(*part.dynStrTab);
440 add(*part.relaDyn);
443 if (config->relrPackDynRelocs) {
444 part.relrDyn = std::make_unique<RelrSection<ELFT>>(threadCount);
445 add(*part.relrDyn);
448 if (!config->relocatable) {
449 if (config->ehFrameHdr) {
450 part.ehFrameHdr = std::make_unique<EhFrameHeader>();
451 add(*part.ehFrameHdr);
453 part.ehFrame = std::make_unique<EhFrameSection>();
454 add(*part.ehFrame);
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);
463 if (!config->packageMetadata.empty()) {
464 part.packageMetadataNote = std::make_unique<PackageMetadataNote>();
465 add(*part.packageMetadataNote);
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);
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);
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);
495 if (config->emachine == EM_PPC) {
496 in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
497 add(*in.ppc32Got2);
500 if (config->emachine == EM_PPC64) {
501 in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
502 add(*in.ppc64LongBranchTarget);
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);
517 if (config->emachine == EM_ARM) {
518 in.armCmseSGSection = std::make_unique<ArmCmseSGSection>();
519 add(*in.armCmseSGSection);
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;
531 if (config->gdbIndex)
532 add(*GdbIndexSection::create<ELFT>());
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);
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);
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);
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);
566 if (config->andFeatures)
567 add(*make<GnuPropertySection>());
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>());
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);
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();
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>();
600 if (script->hasSectionsCommand)
601 script->allocateHeaders(mainPart->phdrs);
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);
609 if (!config->oFormatBinary)
610 assignFileOffsets();
611 else
612 assignFileOffsetsBinary();
614 for (Partition &part : partitions)
615 setPhdrs(part);
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();
622 // Handle --print-memory-usage option.
623 if (config->printMemoryUsage)
624 script->printMemoryUsage(lld::outs());
626 if (config->checkSections)
627 checkSections();
629 // It does not make sense try to open the file if we have error already.
630 if (errorCount())
631 return;
634 llvm::TimeTraceScope timeScope("Write output file");
635 // Write the result down to a file.
636 openFile();
637 if (errorCount())
638 return;
640 if (!config->oFormatBinary) {
641 if (config->zSeparate != SeparateSegmentKind::None)
642 writeTrapInstr();
643 writeHeader();
644 writeSections();
645 } else {
646 writeSectionsBinary();
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;
655 if (auto e = buffer->commit())
656 fatal("failed to write output '" + buffer->getPath() +
657 "': " + toString(std::move(e)));
659 if (!config->cmseOutputLib.empty())
660 writeARMCmseImportLib<ELFT>();
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;
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>());
695 static bool shouldKeepInSymtab(const Defined &sym) {
696 if (sym.isSection())
697 return false;
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;
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;
713 if (config->discard == DiscardPolicy::None)
714 return true;
715 if (config->discard == DiscardPolicy::All)
716 return false;
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;
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());
738 if (auto *s = dyn_cast<MergeInputSection>(sec))
739 return s->getSectionPiece(d->value).live;
740 return true;
742 return b.used || !config->gcSections;
745 // Scan local symbols to:
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;
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);
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;
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;
796 isec = s;
797 break;
800 if (!isec)
801 continue;
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));
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.
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;
824 uint64_t flags = sec->flags;
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;
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;
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;
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;
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;
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;
873 if (in.relroPadding && sec == in.relroPadding->getParent())
874 return true;
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;
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";
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,
915 static unsigned getSectionRank(OutputSection &osec) {
916 unsigned rank = osec.partition * RF_PARTITION;
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;
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;
929 if (osec.type == SHT_LLVM_PART_EHDR)
930 return rank;
931 if (osec.type == SHT_LLVM_PART_PHDR)
932 return rank | 1;
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;
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;
945 rank |= RF_NOT_SPECIAL;
947 // Sort sections based on their access permission in the following
948 // order: R, RX, RXW, RW(RELRO), RW(non-RELRO).
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.
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;
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;
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;
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;
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;
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;
1024 return rank;
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;
1032 if (a->sortRank != b->sortRank)
1033 return a->sortRank < b->sortRank;
1035 if (!(a->sortRank & RF_NOT_ADDR_SET))
1036 return config->sectionStartMap.lookup(a->name) <
1037 config->sectionStartMap.lookup(b->name);
1038 return false;
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;
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;
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);
1068 ElfSym::relaIpltEnd = addOptionalRegular(
1069 config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1070 Out::elfHeader, 0, STV_HIDDEN);
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;
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();
1096 PhdrEntry *last = nullptr;
1097 PhdrEntry *lastRO = nullptr;
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;
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;
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;
1127 if (ElfSym::edata1)
1128 ElfSym::edata1->section = edata;
1129 if (ElfSym::edata2)
1130 ElfSym::edata2->section = edata;
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;
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");
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;
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;
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;
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;
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;
1208 if (i != e)
1209 return i;
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);
1216 if (i == e)
1217 return e;
1218 if (!isa<OutputDesc>(*i))
1219 return e;
1220 auto foundSec = &cast<OutputDesc>(*i)->osec;
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;
1242 auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
1243 auto *osd = dyn_cast<OutputDesc>(cmd);
1244 return osd && osd->osec.hasInputSections;
1246 auto j =
1247 std::find_if(std::make_reverse_iterator(i), std::make_reverse_iterator(b),
1248 isOutputSecWithInputSections);
1249 i = j.base();
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;
1260 while (i != e && shouldSkip(*i))
1261 ++i;
1262 return i;
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;
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);
1288 size_t i = 0;
1289 for (InputSectionBase *&sec : sections)
1290 if (patAndSeed.first.match(sec->name))
1291 sec = matched[i++];
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;
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();
1310 if (config->symbolOrderingFile.empty())
1311 return sectionOrder;
1313 struct SymbolOrderEntry {
1314 int priority;
1315 bool present;
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}});
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;
1334 maybeWarnUnorderableSymbol(&sym);
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);
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);
1349 for (ELFFileBase *file : ctx.objectFiles)
1350 for (Symbol *sym : file->getLocalSymbols())
1351 addSym(*sym);
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());
1358 return sectionOrder;
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;
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;
1380 orderedSections.push_back({isec, i->second});
1382 llvm::sort(orderedSections, llvm::less_second());
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.
1393 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1394 // If the layout is:
1396 // 8MB hot
1397 // 32MB cold
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:
1403 // 16MB cold
1404 // 8MB hot
1405 // 16MB cold
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.
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;
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);
1437 static void sortSection(OutputSection &osec,
1438 const DenseMap<const InputSectionBase *, int> &order) {
1439 StringRef name = osec.name;
1441 // Never sort these.
1442 if (name == ".init" || name == ".fini")
1443 return;
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;
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);
1462 if (script->hasSectionsCommand)
1463 return;
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;
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);
1496 template <class ELFT> void Writer<ELFT>::sortSections() {
1497 llvm::TimeTraceScope timeScope("Sort sections");
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;
1506 sortInputSections();
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);
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();
1525 if (script->hasSectionsCommand)
1526 sortOrphanSections();
1528 script->adjustSectionsAfterSorting();
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.
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.
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
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.
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.
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;
1579 // Sort the orphan sections.
1580 std::stable_sort(nonScriptI, e, compareSections);
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;
1593 while (nonScriptI != e) {
1594 auto pos = findOrphanPos(i, nonScriptI);
1595 OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
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;
1603 std::rotate(pos, nonScriptI, end);
1604 nonScriptI = end;
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();
1618 if (aOut != bOut)
1619 return aOut->addr < bOut->addr;
1620 return la->outSecOff < lb->outSecOff;
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;
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;
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;
1654 scriptSections.push_back(&isec);
1655 sections.push_back(isec);
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];
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();
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();
1691 // Converts call x@GDPLT to call __tls_get_addr
1692 if (config->emachine == EM_HEXAGON)
1693 hexagonTLSSymbolUpdate(outputSections);
1695 uint32_t pass = 0, assignPasses = 0;
1696 for (;;) {
1697 bool changed = target->needsThunks ? tc.createThunks(pass, outputSections)
1698 : target->relaxOnce(pass);
1699 ++pass;
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;
1709 if (config->fixCortexA53Errata843419) {
1710 if (changed)
1711 script->assignAddresses();
1712 changed |= a64p.createFixes();
1714 if (config->fixCortexA8) {
1715 if (changed)
1716 script->assignAddresses();
1717 changed |= a32p.createFixes();
1720 finalizeSynthetic(in.got.get());
1721 if (in.mipsGot)
1722 in.mipsGot->updateAllocSize();
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();
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;
1746 if (!config->relocatable && config->emachine == EM_RISCV)
1747 riscvFinalizeRelax(pass);
1749 if (config->relocatable)
1750 for (OutputSection *sec : outputSections)
1751 sec->addr = 0;
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) + ")");
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;
1776 const SectionBase *sec = def->section;
1777 if (!sec)
1778 return;
1780 const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1781 if (!inputSec || !inputSec->bytesDropped)
1782 return;
1784 const size_t OldSize = inputSec->content().size();
1785 const size_t NewSize = OldSize - inputSec->bytesDropped;
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;
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;
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;
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);
1836 if (numDeleted > 0) {
1837 script->assignAddresses();
1838 LLVM_DEBUG(llvm::dbgs()
1839 << "Removing " << numDeleted << " fall through jumps\n");
1843 fixSymbolsAfterShrinking();
1845 for (OutputSection *osec : outputSections)
1846 for (InputSection *is : getInputSections(*osec, storage))
1847 is->trim();
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 }".
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.
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();
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;
1881 ctx.inputSections.erase(end, ctx.inputSections.end());
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);
1892 llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {
1893 return unused.count(sec);
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");
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);
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;
1923 // Define __rel[a]_iplt_{start,end} symbols if needed.
1924 addRelIpltSymbols();
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);
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:
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).
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);
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.
1971 llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1972 for (Partition &part : partitions)
1973 finalizeSynthetic(part.ehFrame.get());
1977 demoteSymbolsAndComputeIsPreemptible();
1979 if (config->copyRelocs && config->discard != DiscardPolicy::None)
1980 markUsedLocalSymbols<ELFT>();
1981 demoteAndCopyLocalSymbols();
1983 if (config->copyRelocs)
1984 addSectionSymbols();
1986 // Change values of linker-script-defined symbols from placeholders (assigned
1987 // by declareSymbols) to actual definitions.
1988 script->processSymbolAssignments();
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();
2001 if (in.plt && in.plt->isNeeded())
2002 in.plt->addSymbols();
2003 if (in.iplt && in.iplt->isNeeded())
2004 in.iplt->addSymbols();
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.
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));
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));
2035 llvm::TimeTraceScope timeScope("Add symbols to symtabs");
2036 // Now that we have defined all possible global symbols including linker-
2037 // synthesized ones. Visit all symbols to give the finishing touches.
2038 for (Symbol *sym : symtab.getSymbols()) {
2039 if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
2040 continue;
2041 if (!config->relocatable)
2042 sym->binding = sym->computeBinding();
2043 if (in.symTab)
2044 in.symTab->addSymbol(sym);
2046 if (sym->includeInDynsym()) {
2047 partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
2048 if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
2049 if (file->isNeeded && !sym->isUndefined())
2050 addVerneed(sym);
2054 // We also need to scan the dynamic relocation tables of the other
2055 // partitions and add any referenced symbols to the partition's dynsym.
2056 for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
2057 DenseSet<Symbol *> syms;
2058 for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
2059 syms.insert(e.sym);
2060 for (DynamicReloc &reloc : part.relaDyn->relocs)
2061 if (reloc.sym && reloc.needsDynSymIndex() &&
2062 syms.insert(reloc.sym).second)
2063 part.dynSymTab->addSymbol(reloc.sym);
2067 if (in.mipsGot)
2068 in.mipsGot->build();
2070 removeUnusedSyntheticSections();
2071 script->diagnoseOrphanHandling();
2072 script->diagnoseMissingSGSectionAddress();
2074 sortSections();
2076 // Create a list of OutputSections, assign sectionIndex, and populate
2077 // in.shStrTab.
2078 for (SectionCommand *cmd : script->sectionCommands)
2079 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
2080 OutputSection *osec = &osd->osec;
2081 outputSections.push_back(osec);
2082 osec->sectionIndex = outputSections.size();
2083 osec->shName = in.shStrTab->addString(osec->name);
2086 // Prefer command line supplied address over other constraints.
2087 for (OutputSection *sec : outputSections) {
2088 auto i = config->sectionStartMap.find(sec->name);
2089 if (i != config->sectionStartMap.end())
2090 sec->addrExpr = [=] { return i->second; };
2093 // With the outputSections available check for GDPLT relocations
2094 // and add __tls_get_addr symbol if needed.
2095 if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2096 Symbol *sym = symtab.addSymbol(Undefined{
2097 nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2098 sym->isPreemptible = true;
2099 partitions[0].dynSymTab->addSymbol(sym);
2102 // This is a bit of a hack. A value of 0 means undef, so we set it
2103 // to 1 to make __ehdr_start defined. The section number is not
2104 // particularly relevant.
2105 Out::elfHeader->sectionIndex = 1;
2106 Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2108 // Binary and relocatable output does not have PHDRS.
2109 // The headers have to be created before finalize as that can influence the
2110 // image base and the dynamic section on mips includes the image base.
2111 if (!config->relocatable && !config->oFormatBinary) {
2112 for (Partition &part : partitions) {
2113 part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2114 : createPhdrs(part);
2115 if (config->emachine == EM_ARM) {
2116 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2117 addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2119 if (config->emachine == EM_MIPS) {
2120 // Add separate segments for MIPS-specific sections.
2121 addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2122 addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2123 addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2125 if (config->emachine == EM_RISCV)
2126 addPhdrForSection(part, SHT_RISCV_ATTRIBUTES, PT_RISCV_ATTRIBUTES,
2127 PF_R);
2129 Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2131 // Find the TLS segment. This happens before the section layout loop so that
2132 // Android relocation packing can look up TLS symbol addresses. We only need
2133 // to care about the main partition here because all TLS symbols were moved
2134 // to the main partition (see MarkLive.cpp).
2135 for (PhdrEntry *p : mainPart->phdrs)
2136 if (p->p_type == PT_TLS)
2137 Out::tlsPhdr = p;
2140 // Some symbols are defined in term of program headers. Now that we
2141 // have the headers, we can find out which sections they point to.
2142 setReservedSymbolSections();
2145 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2147 finalizeSynthetic(in.bss.get());
2148 finalizeSynthetic(in.bssRelRo.get());
2149 finalizeSynthetic(in.symTabShndx.get());
2150 finalizeSynthetic(in.shStrTab.get());
2151 finalizeSynthetic(in.strTab.get());
2152 finalizeSynthetic(in.got.get());
2153 finalizeSynthetic(in.mipsGot.get());
2154 finalizeSynthetic(in.igotPlt.get());
2155 finalizeSynthetic(in.gotPlt.get());
2156 finalizeSynthetic(in.relaIplt.get());
2157 finalizeSynthetic(in.relaPlt.get());
2158 finalizeSynthetic(in.plt.get());
2159 finalizeSynthetic(in.iplt.get());
2160 finalizeSynthetic(in.ppc32Got2.get());
2161 finalizeSynthetic(in.partIndex.get());
2163 // Dynamic section must be the last one in this list and dynamic
2164 // symbol table section (dynSymTab) must be the first one.
2165 for (Partition &part : partitions) {
2166 if (part.relaDyn) {
2167 part.relaDyn->mergeRels();
2168 // Compute DT_RELACOUNT to be used by part.dynamic.
2169 part.relaDyn->partitionRels();
2170 finalizeSynthetic(part.relaDyn.get());
2172 if (part.relrDyn) {
2173 part.relrDyn->mergeRels();
2174 finalizeSynthetic(part.relrDyn.get());
2177 finalizeSynthetic(part.dynSymTab.get());
2178 finalizeSynthetic(part.gnuHashTab.get());
2179 finalizeSynthetic(part.hashTab.get());
2180 finalizeSynthetic(part.verDef.get());
2181 finalizeSynthetic(part.ehFrameHdr.get());
2182 finalizeSynthetic(part.verSym.get());
2183 finalizeSynthetic(part.verNeed.get());
2184 finalizeSynthetic(part.dynamic.get());
2188 if (!script->hasSectionsCommand && !config->relocatable)
2189 fixSectionAlignments();
2191 // This is used to:
2192 // 1) Create "thunks":
2193 // Jump instructions in many ISAs have small displacements, and therefore
2194 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2195 // JAL instruction can target only +-1 MiB from PC. It is a linker's
2196 // responsibility to create and insert small pieces of code between
2197 // sections to extend the ranges if jump targets are out of range. Such
2198 // code pieces are called "thunks".
2200 // We add thunks at this stage. We couldn't do this before this point
2201 // because this is the earliest point where we know sizes of sections and
2202 // their layouts (that are needed to determine if jump targets are in
2203 // range).
2205 // 2) Update the sections. We need to generate content that depends on the
2206 // address of InputSections. For example, MIPS GOT section content or
2207 // android packed relocations sections content.
2209 // 3) Assign the final values for the linker script symbols. Linker scripts
2210 // sometimes using forward symbol declarations. We want to set the correct
2211 // values. They also might change after adding the thunks.
2212 finalizeAddressDependentContent();
2214 // All information needed for OutputSection part of Map file is available.
2215 if (errorCount())
2216 return;
2219 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2220 // finalizeAddressDependentContent may have added local symbols to the
2221 // static symbol table.
2222 finalizeSynthetic(in.symTab.get());
2223 finalizeSynthetic(in.ppc64LongBranchTarget.get());
2224 finalizeSynthetic(in.armCmseSGSection.get());
2227 // Relaxation to delete inter-basic block jumps created by basic block
2228 // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2229 // can relax jump instructions based on symbol offset.
2230 if (config->optimizeBBJumps)
2231 optimizeBasicBlockJumps();
2233 // Fill other section headers. The dynamic table is finalized
2234 // at the end because some tags like RELSZ depend on result
2235 // of finalizing other sections.
2236 for (OutputSection *sec : outputSections)
2237 sec->finalize();
2239 script->checkFinalScriptConditions();
2241 if (config->emachine == EM_ARM && !config->isLE && config->armBe8) {
2242 addArmInputSectionMappingSymbols();
2243 sortArmMappingSymbols();
2247 // Ensure data sections are not mixed with executable sections when
2248 // --execute-only is used. --execute-only make pages executable but not
2249 // readable.
2250 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2251 if (!config->executeOnly)
2252 return;
2254 SmallVector<InputSection *, 0> storage;
2255 for (OutputSection *osec : outputSections)
2256 if (osec->flags & SHF_EXECINSTR)
2257 for (InputSection *isec : getInputSections(*osec, storage))
2258 if (!(isec->flags & SHF_EXECINSTR))
2259 error("cannot place " + toString(isec) + " into " +
2260 toString(osec->name) +
2261 ": --execute-only does not support intermingling data and code");
2264 // The linker is expected to define SECNAME_start and SECNAME_end
2265 // symbols for a few sections. This function defines them.
2266 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2267 // If a section does not exist, there's ambiguity as to how we
2268 // define _start and _end symbols for an init/fini section. Since
2269 // the loader assume that the symbols are always defined, we need to
2270 // always define them. But what value? The loader iterates over all
2271 // pointers between _start and _end to run global ctors/dtors, so if
2272 // the section is empty, their symbol values don't actually matter
2273 // as long as _start and _end point to the same location.
2275 // That said, we don't want to set the symbols to 0 (which is
2276 // probably the simplest value) because that could cause some
2277 // program to fail to link due to relocation overflow, if their
2278 // program text is above 2 GiB. We use the address of the .text
2279 // section instead to prevent that failure.
2281 // In rare situations, the .text section may not exist. If that's the
2282 // case, use the image base address as a last resort.
2283 OutputSection *Default = findSection(".text");
2284 if (!Default)
2285 Default = Out::elfHeader;
2287 auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2288 if (os && !script->isDiscarded(os)) {
2289 addOptionalRegular(start, os, 0);
2290 addOptionalRegular(end, os, -1);
2291 } else {
2292 addOptionalRegular(start, Default, 0);
2293 addOptionalRegular(end, Default, 0);
2297 define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2298 define("__init_array_start", "__init_array_end", Out::initArray);
2299 define("__fini_array_start", "__fini_array_end", Out::finiArray);
2301 if (OutputSection *sec = findSection(".ARM.exidx"))
2302 define("__exidx_start", "__exidx_end", sec);
2305 // If a section name is valid as a C identifier (which is rare because of
2306 // the leading '.'), linkers are expected to define __start_<secname> and
2307 // __stop_<secname> symbols. They are at beginning and end of the section,
2308 // respectively. This is not requested by the ELF standard, but GNU ld and
2309 // gold provide the feature, and used by many programs.
2310 template <class ELFT>
2311 void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
2312 StringRef s = osec.name;
2313 if (!isValidCIdentifier(s))
2314 return;
2315 addOptionalRegular(saver().save("__start_" + s), &osec, 0,
2316 config->zStartStopVisibility);
2317 addOptionalRegular(saver().save("__stop_" + s), &osec, -1,
2318 config->zStartStopVisibility);
2321 static bool needsPtLoad(OutputSection *sec) {
2322 if (!(sec->flags & SHF_ALLOC))
2323 return false;
2325 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2326 // responsible for allocating space for them, not the PT_LOAD that
2327 // contains the TLS initialization image.
2328 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2329 return false;
2330 return true;
2333 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2334 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2335 // RW. This means that there is no alignment in the RO to RX transition and we
2336 // cannot create a PT_LOAD there.
2337 static uint64_t computeFlags(uint64_t flags) {
2338 if (config->omagic)
2339 return PF_R | PF_W | PF_X;
2340 if (config->executeOnly && (flags & PF_X))
2341 return flags & ~PF_R;
2342 if (config->singleRoRx && !(flags & PF_W))
2343 return flags | PF_X;
2344 return flags;
2347 // Decide which program headers to create and which sections to include in each
2348 // one.
2349 template <class ELFT>
2350 SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
2351 SmallVector<PhdrEntry *, 0> ret;
2352 auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2353 ret.push_back(make<PhdrEntry>(type, flags));
2354 return ret.back();
2357 unsigned partNo = part.getNumber();
2358 bool isMain = partNo == 1;
2360 // Add the first PT_LOAD segment for regular output sections.
2361 uint64_t flags = computeFlags(PF_R);
2362 PhdrEntry *load = nullptr;
2364 // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2365 // PT_LOAD.
2366 if (!config->nmagic && !config->omagic) {
2367 // The first phdr entry is PT_PHDR which describes the program header
2368 // itself.
2369 if (isMain)
2370 addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2371 else
2372 addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2374 // PT_INTERP must be the second entry if exists.
2375 if (OutputSection *cmd = findSection(".interp", partNo))
2376 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2378 // Add the headers. We will remove them if they don't fit.
2379 // In the other partitions the headers are ordinary sections, so they don't
2380 // need to be added here.
2381 if (isMain) {
2382 load = addHdr(PT_LOAD, flags);
2383 load->add(Out::elfHeader);
2384 load->add(Out::programHeaders);
2388 // PT_GNU_RELRO includes all sections that should be marked as
2389 // read-only by dynamic linker after processing relocations.
2390 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2391 // an error message if more than one PT_GNU_RELRO PHDR is required.
2392 PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2393 bool inRelroPhdr = false;
2394 OutputSection *relroEnd = nullptr;
2395 for (OutputSection *sec : outputSections) {
2396 if (sec->partition != partNo || !needsPtLoad(sec))
2397 continue;
2398 if (isRelroSection(sec)) {
2399 inRelroPhdr = true;
2400 if (!relroEnd)
2401 relRo->add(sec);
2402 else
2403 error("section: " + sec->name + " is not contiguous with other relro" +
2404 " sections");
2405 } else if (inRelroPhdr) {
2406 inRelroPhdr = false;
2407 relroEnd = sec;
2410 relRo->p_align = 1;
2412 for (OutputSection *sec : outputSections) {
2413 if (!needsPtLoad(sec))
2414 continue;
2416 // Normally, sections in partitions other than the current partition are
2417 // ignored. But partition number 255 is a special case: it contains the
2418 // partition end marker (.part.end). It needs to be added to the main
2419 // partition so that a segment is created for it in the main partition,
2420 // which will cause the dynamic loader to reserve space for the other
2421 // partitions.
2422 if (sec->partition != partNo) {
2423 if (isMain && sec->partition == 255)
2424 addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2425 continue;
2428 // Segments are contiguous memory regions that has the same attributes
2429 // (e.g. executable or writable). There is one phdr for each segment.
2430 // Therefore, we need to create a new phdr when the next section has
2431 // different flags or is loaded at a discontiguous address or memory region
2432 // using AT or AT> linker script command, respectively.
2434 // As an exception, we don't create a separate load segment for the ELF
2435 // headers, even if the first "real" output has an AT or AT> attribute.
2437 // In addition, NOBITS sections should only be placed at the end of a LOAD
2438 // segment (since it's represented as p_filesz < p_memsz). If we have a
2439 // not-NOBITS section after a NOBITS, we create a new LOAD for the latter
2440 // even if flags match, so as not to require actually writing the
2441 // supposed-to-be-NOBITS section to the output file. (However, we cannot do
2442 // so when hasSectionsCommand, since we cannot introduce the extra alignment
2443 // needed to create a new LOAD)
2444 uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2445 bool sameLMARegion =
2446 load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2447 if (!(load && newFlags == flags && sec != relroEnd &&
2448 sec->memRegion == load->firstSec->memRegion &&
2449 (sameLMARegion || load->lastSec == Out::programHeaders) &&
2450 (script->hasSectionsCommand || sec->type == SHT_NOBITS ||
2451 load->lastSec->type != SHT_NOBITS))) {
2452 load = addHdr(PT_LOAD, newFlags);
2453 flags = newFlags;
2456 load->add(sec);
2459 // Add a TLS segment if any.
2460 PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2461 for (OutputSection *sec : outputSections)
2462 if (sec->partition == partNo && sec->flags & SHF_TLS)
2463 tlsHdr->add(sec);
2464 if (tlsHdr->firstSec)
2465 ret.push_back(tlsHdr);
2467 // Add an entry for .dynamic.
2468 if (OutputSection *sec = part.dynamic->getParent())
2469 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2471 if (relRo->firstSec)
2472 ret.push_back(relRo);
2474 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2475 if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2476 part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2477 addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2478 ->add(part.ehFrameHdr->getParent());
2480 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2481 // the dynamic linker fill the segment with random data.
2482 if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2483 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2485 if (config->zGnustack != GnuStackKind::None) {
2486 // PT_GNU_STACK is a special section to tell the loader to make the
2487 // pages for the stack non-executable. If you really want an executable
2488 // stack, you can pass -z execstack, but that's not recommended for
2489 // security reasons.
2490 unsigned perm = PF_R | PF_W;
2491 if (config->zGnustack == GnuStackKind::Exec)
2492 perm |= PF_X;
2493 addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2496 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2497 // is expected to perform W^X violations, such as calling mprotect(2) or
2498 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2499 // OpenBSD.
2500 if (config->zWxneeded)
2501 addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2503 if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2504 addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2506 // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2507 // same alignment.
2508 PhdrEntry *note = nullptr;
2509 for (OutputSection *sec : outputSections) {
2510 if (sec->partition != partNo)
2511 continue;
2512 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2513 if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2514 note = addHdr(PT_NOTE, PF_R);
2515 note->add(sec);
2516 } else {
2517 note = nullptr;
2520 return ret;
2523 template <class ELFT>
2524 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2525 unsigned pType, unsigned pFlags) {
2526 unsigned partNo = part.getNumber();
2527 auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2528 return cmd->partition == partNo && cmd->type == shType;
2530 if (i == outputSections.end())
2531 return;
2533 PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2534 entry->add(*i);
2535 part.phdrs.push_back(entry);
2538 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2539 // This is achieved by assigning an alignment expression to addrExpr of each
2540 // such section.
2541 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2542 const PhdrEntry *prev;
2543 auto pageAlign = [&](const PhdrEntry *p) {
2544 OutputSection *cmd = p->firstSec;
2545 if (!cmd)
2546 return;
2547 cmd->alignExpr = [align = cmd->addralign]() { return align; };
2548 if (!cmd->addrExpr) {
2549 // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2550 // padding in the file contents.
2552 // When -z separate-code is used we must not have any overlap in pages
2553 // between an executable segment and a non-executable segment. We align to
2554 // the next maximum page size boundary on transitions between executable
2555 // and non-executable segments.
2557 // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2558 // sections will be extracted to a separate file. Align to the next
2559 // maximum page size boundary so that we can find the ELF header at the
2560 // start. We cannot benefit from overlapping p_offset ranges with the
2561 // previous segment anyway.
2562 if (config->zSeparate == SeparateSegmentKind::Loadable ||
2563 (config->zSeparate == SeparateSegmentKind::Code && prev &&
2564 (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2565 cmd->type == SHT_LLVM_PART_EHDR)
2566 cmd->addrExpr = [] {
2567 return alignToPowerOf2(script->getDot(), config->maxPageSize);
2569 // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2570 // it must be the RW. Align to p_align(PT_TLS) to make sure
2571 // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2572 // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2573 // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2574 // be congruent to 0 modulo p_align(PT_TLS).
2576 // Technically this is not required, but as of 2019, some dynamic loaders
2577 // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2578 // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2579 // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2580 // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2581 // blocks correctly. We need to keep the workaround for a while.
2582 else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2583 cmd->addrExpr = [] {
2584 return alignToPowerOf2(script->getDot(), config->maxPageSize) +
2585 alignToPowerOf2(script->getDot() % config->maxPageSize,
2586 Out::tlsPhdr->p_align);
2588 else
2589 cmd->addrExpr = [] {
2590 return alignToPowerOf2(script->getDot(), config->maxPageSize) +
2591 script->getDot() % config->maxPageSize;
2596 for (Partition &part : partitions) {
2597 prev = nullptr;
2598 for (const PhdrEntry *p : part.phdrs)
2599 if (p->p_type == PT_LOAD && p->firstSec) {
2600 pageAlign(p);
2601 prev = p;
2606 // Compute an in-file position for a given section. The file offset must be the
2607 // same with its virtual address modulo the page size, so that the loader can
2608 // load executables without any address adjustment.
2609 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2610 // The first section in a PT_LOAD has to have congruent offset and address
2611 // modulo the maximum page size.
2612 if (os->ptLoad && os->ptLoad->firstSec == os)
2613 return alignTo(off, os->ptLoad->p_align, os->addr);
2615 // File offsets are not significant for .bss sections other than the first one
2616 // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2617 // increasing rather than setting to zero.
2618 if (os->type == SHT_NOBITS &&
2619 (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2620 return off;
2622 // If the section is not in a PT_LOAD, we just have to align it.
2623 if (!os->ptLoad)
2624 return alignToPowerOf2(off, os->addralign);
2626 // If two sections share the same PT_LOAD the file offset is calculated
2627 // using this formula: Off2 = Off1 + (VA2 - VA1).
2628 OutputSection *first = os->ptLoad->firstSec;
2629 return first->offset + os->addr - first->addr;
2632 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2633 // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2634 auto needsOffset = [](OutputSection &sec) {
2635 return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2637 uint64_t minAddr = UINT64_MAX;
2638 for (OutputSection *sec : outputSections)
2639 if (needsOffset(*sec)) {
2640 sec->offset = sec->getLMA();
2641 minAddr = std::min(minAddr, sec->offset);
2644 // Sections are laid out at LMA minus minAddr.
2645 fileSize = 0;
2646 for (OutputSection *sec : outputSections)
2647 if (needsOffset(*sec)) {
2648 sec->offset -= minAddr;
2649 fileSize = std::max(fileSize, sec->offset + sec->size);
2653 static std::string rangeToString(uint64_t addr, uint64_t len) {
2654 return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2657 // Assign file offsets to output sections.
2658 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2659 Out::programHeaders->offset = Out::elfHeader->size;
2660 uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
2662 PhdrEntry *lastRX = nullptr;
2663 for (Partition &part : partitions)
2664 for (PhdrEntry *p : part.phdrs)
2665 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2666 lastRX = p;
2668 // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2669 // will not occupy file offsets contained by a PT_LOAD.
2670 for (OutputSection *sec : outputSections) {
2671 if (!(sec->flags & SHF_ALLOC))
2672 continue;
2673 off = computeFileOffset(sec, off);
2674 sec->offset = off;
2675 if (sec->type != SHT_NOBITS)
2676 off += sec->size;
2678 // If this is a last section of the last executable segment and that
2679 // segment is the last loadable segment, align the offset of the
2680 // following section to avoid loading non-segments parts of the file.
2681 if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2682 lastRX->lastSec == sec)
2683 off = alignToPowerOf2(off, config->maxPageSize);
2685 for (OutputSection *osec : outputSections)
2686 if (!(osec->flags & SHF_ALLOC)) {
2687 osec->offset = alignToPowerOf2(off, osec->addralign);
2688 off = osec->offset + osec->size;
2691 sectionHeaderOff = alignToPowerOf2(off, config->wordsize);
2692 fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2694 // Our logic assumes that sections have rising VA within the same segment.
2695 // With use of linker scripts it is possible to violate this rule and get file
2696 // offset overlaps or overflows. That should never happen with a valid script
2697 // which does not move the location counter backwards and usually scripts do
2698 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2699 // kernel, which control segment distribution explicitly and move the counter
2700 // backwards, so we have to allow doing that to support linking them. We
2701 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2702 // we want to prevent file size overflows because it would crash the linker.
2703 for (OutputSection *sec : outputSections) {
2704 if (sec->type == SHT_NOBITS)
2705 continue;
2706 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2707 error("unable to place section " + sec->name + " at file offset " +
2708 rangeToString(sec->offset, sec->size) +
2709 "; check your linker script for overflows");
2713 // Finalize the program headers. We call this function after we assign
2714 // file offsets and VAs to all sections.
2715 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2716 for (PhdrEntry *p : part.phdrs) {
2717 OutputSection *first = p->firstSec;
2718 OutputSection *last = p->lastSec;
2720 // .ARM.exidx sections may not be within a single .ARM.exidx
2721 // output section. We always want to describe just the
2722 // SyntheticSection.
2723 if (part.armExidx && p->p_type == PT_ARM_EXIDX) {
2724 p->p_filesz = part.armExidx->getSize();
2725 p->p_memsz = part.armExidx->getSize();
2726 p->p_offset = first->offset + part.armExidx->outSecOff;
2727 p->p_vaddr = first->addr + part.armExidx->outSecOff;
2728 p->p_align = part.armExidx->addralign;
2729 if (part.elfHeader)
2730 p->p_offset -= part.elfHeader->getParent()->offset;
2732 if (!p->hasLMA)
2733 p->p_paddr = first->getLMA() + part.armExidx->outSecOff;
2734 return;
2737 if (first) {
2738 p->p_filesz = last->offset - first->offset;
2739 if (last->type != SHT_NOBITS)
2740 p->p_filesz += last->size;
2742 p->p_memsz = last->addr + last->size - first->addr;
2743 p->p_offset = first->offset;
2744 p->p_vaddr = first->addr;
2746 // File offsets in partitions other than the main partition are relative
2747 // to the offset of the ELF headers. Perform that adjustment now.
2748 if (part.elfHeader)
2749 p->p_offset -= part.elfHeader->getParent()->offset;
2751 if (!p->hasLMA)
2752 p->p_paddr = first->getLMA();
2757 // A helper struct for checkSectionOverlap.
2758 namespace {
2759 struct SectionOffset {
2760 OutputSection *sec;
2761 uint64_t offset;
2763 } // namespace
2765 // Check whether sections overlap for a specific address range (file offsets,
2766 // load and virtual addresses).
2767 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2768 bool isVirtualAddr) {
2769 llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2770 return a.offset < b.offset;
2773 // Finding overlap is easy given a vector is sorted by start position.
2774 // If an element starts before the end of the previous element, they overlap.
2775 for (size_t i = 1, end = sections.size(); i < end; ++i) {
2776 SectionOffset a = sections[i - 1];
2777 SectionOffset b = sections[i];
2778 if (b.offset >= a.offset + a.sec->size)
2779 continue;
2781 // If both sections are in OVERLAY we allow the overlapping of virtual
2782 // addresses, because it is what OVERLAY was designed for.
2783 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2784 continue;
2786 errorOrWarn("section " + a.sec->name + " " + name +
2787 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2788 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2789 b.sec->name + " range is " +
2790 rangeToString(b.offset, b.sec->size));
2794 // Check for overlapping sections and address overflows.
2796 // In this function we check that none of the output sections have overlapping
2797 // file offsets. For SHF_ALLOC sections we also check that the load address
2798 // ranges and the virtual address ranges don't overlap
2799 template <class ELFT> void Writer<ELFT>::checkSections() {
2800 // First, check that section's VAs fit in available address space for target.
2801 for (OutputSection *os : outputSections)
2802 if ((os->addr + os->size < os->addr) ||
2803 (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2804 errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2805 " of size 0x" + utohexstr(os->size) +
2806 " exceeds available address space");
2808 // Check for overlapping file offsets. In this case we need to skip any
2809 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2810 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2811 // binary is specified only add SHF_ALLOC sections are added to the output
2812 // file so we skip any non-allocated sections in that case.
2813 std::vector<SectionOffset> fileOffs;
2814 for (OutputSection *sec : outputSections)
2815 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2816 (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2817 fileOffs.push_back({sec, sec->offset});
2818 checkOverlap("file", fileOffs, false);
2820 // When linking with -r there is no need to check for overlapping virtual/load
2821 // addresses since those addresses will only be assigned when the final
2822 // executable/shared object is created.
2823 if (config->relocatable)
2824 return;
2826 // Checking for overlapping virtual and load addresses only needs to take
2827 // into account SHF_ALLOC sections since others will not be loaded.
2828 // Furthermore, we also need to skip SHF_TLS sections since these will be
2829 // mapped to other addresses at runtime and can therefore have overlapping
2830 // ranges in the file.
2831 std::vector<SectionOffset> vmas;
2832 for (OutputSection *sec : outputSections)
2833 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2834 vmas.push_back({sec, sec->addr});
2835 checkOverlap("virtual address", vmas, true);
2837 // Finally, check that the load addresses don't overlap. This will usually be
2838 // the same as the virtual addresses but can be different when using a linker
2839 // script with AT().
2840 std::vector<SectionOffset> lmas;
2841 for (OutputSection *sec : outputSections)
2842 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2843 lmas.push_back({sec, sec->getLMA()});
2844 checkOverlap("load address", lmas, false);
2847 // The entry point address is chosen in the following ways.
2849 // 1. the '-e' entry command-line option;
2850 // 2. the ENTRY(symbol) command in a linker control script;
2851 // 3. the value of the symbol _start, if present;
2852 // 4. the number represented by the entry symbol, if it is a number;
2853 // 5. the address 0.
2854 static uint64_t getEntryAddr() {
2855 // Case 1, 2 or 3
2856 if (Symbol *b = symtab.find(config->entry))
2857 return b->getVA();
2859 // Case 4
2860 uint64_t addr;
2861 if (to_integer(config->entry, addr))
2862 return addr;
2864 // Case 5
2865 if (config->warnMissingEntry)
2866 warn("cannot find entry symbol " + config->entry +
2867 "; not setting start address");
2868 return 0;
2871 static uint16_t getELFType() {
2872 if (config->isPic)
2873 return ET_DYN;
2874 if (config->relocatable)
2875 return ET_REL;
2876 return ET_EXEC;
2879 template <class ELFT> void Writer<ELFT>::writeHeader() {
2880 writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2881 writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2883 auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2884 eHdr->e_type = getELFType();
2885 eHdr->e_entry = getEntryAddr();
2886 eHdr->e_shoff = sectionHeaderOff;
2888 // Write the section header table.
2890 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2891 // and e_shstrndx fields. When the value of one of these fields exceeds
2892 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2893 // use fields in the section header at index 0 to store
2894 // the value. The sentinel values and fields are:
2895 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2896 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2897 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2898 size_t num = outputSections.size() + 1;
2899 if (num >= SHN_LORESERVE)
2900 sHdrs->sh_size = num;
2901 else
2902 eHdr->e_shnum = num;
2904 uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2905 if (strTabIndex >= SHN_LORESERVE) {
2906 sHdrs->sh_link = strTabIndex;
2907 eHdr->e_shstrndx = SHN_XINDEX;
2908 } else {
2909 eHdr->e_shstrndx = strTabIndex;
2912 for (OutputSection *sec : outputSections)
2913 sec->writeHeaderTo<ELFT>(++sHdrs);
2916 // Open a result file.
2917 template <class ELFT> void Writer<ELFT>::openFile() {
2918 uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2919 if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2920 std::string msg;
2921 raw_string_ostream s(msg);
2922 s << "output file too large: " << Twine(fileSize) << " bytes\n"
2923 << "section sizes:\n";
2924 for (OutputSection *os : outputSections)
2925 s << os->name << ' ' << os->size << "\n";
2926 error(s.str());
2927 return;
2930 unlinkAsync(config->outputFile);
2931 unsigned flags = 0;
2932 if (!config->relocatable)
2933 flags |= FileOutputBuffer::F_executable;
2934 if (!config->mmapOutputFile)
2935 flags |= FileOutputBuffer::F_no_mmap;
2936 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2937 FileOutputBuffer::create(config->outputFile, fileSize, flags);
2939 if (!bufferOrErr) {
2940 error("failed to open " + config->outputFile + ": " +
2941 llvm::toString(bufferOrErr.takeError()));
2942 return;
2944 buffer = std::move(*bufferOrErr);
2945 Out::bufferStart = buffer->getBufferStart();
2948 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2949 parallel::TaskGroup tg;
2950 for (OutputSection *sec : outputSections)
2951 if (sec->flags & SHF_ALLOC)
2952 sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
2955 static void fillTrap(uint8_t *i, uint8_t *end) {
2956 for (; i + 4 <= end; i += 4)
2957 memcpy(i, &target->trapInstr, 4);
2960 // Fill the last page of executable segments with trap instructions
2961 // instead of leaving them as zero. Even though it is not required by any
2962 // standard, it is in general a good thing to do for security reasons.
2964 // We'll leave other pages in segments as-is because the rest will be
2965 // overwritten by output sections.
2966 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2967 for (Partition &part : partitions) {
2968 // Fill the last page.
2969 for (PhdrEntry *p : part.phdrs)
2970 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2971 fillTrap(Out::bufferStart +
2972 alignDown(p->firstSec->offset + p->p_filesz, 4),
2973 Out::bufferStart +
2974 alignToPowerOf2(p->firstSec->offset + p->p_filesz,
2975 config->maxPageSize));
2977 // Round up the file size of the last segment to the page boundary iff it is
2978 // an executable segment to ensure that other tools don't accidentally
2979 // trim the instruction padding (e.g. when stripping the file).
2980 PhdrEntry *last = nullptr;
2981 for (PhdrEntry *p : part.phdrs)
2982 if (p->p_type == PT_LOAD)
2983 last = p;
2985 if (last && (last->p_flags & PF_X))
2986 last->p_memsz = last->p_filesz =
2987 alignToPowerOf2(last->p_filesz, config->maxPageSize);
2991 // Write section contents to a mmap'ed file.
2992 template <class ELFT> void Writer<ELFT>::writeSections() {
2993 llvm::TimeTraceScope timeScope("Write sections");
2996 // In -r or --emit-relocs mode, write the relocation sections first as in
2997 // ELf_Rel targets we might find out that we need to modify the relocated
2998 // section while doing it.
2999 parallel::TaskGroup tg;
3000 for (OutputSection *sec : outputSections)
3001 if (sec->type == SHT_REL || sec->type == SHT_RELA)
3002 sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
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);
3011 // Finally, check that all dynamic relocation addends were written correctly.
3012 if (config->checkDynamicRelocs && config->writeAddends) {
3013 for (OutputSection *sec : outputSections)
3014 if (sec->type == SHT_REL || sec->type == SHT_RELA)
3015 sec->checkDynRelAddends(Out::bufferStart);
3019 // Computes a hash value of Data using a given hash function.
3020 // In order to utilize multiple cores, we first split data into 1MB
3021 // chunks, compute a hash for each chunk, and then compute a hash value
3022 // of the hash values.
3023 static void
3024 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
3025 llvm::ArrayRef<uint8_t> data,
3026 std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
3027 std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
3028 const size_t hashesSize = chunks.size() * hashBuf.size();
3029 std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
3031 // Compute hash values.
3032 parallelFor(0, chunks.size(), [&](size_t i) {
3033 hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
3036 // Write to the final output buffer.
3037 hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
3040 template <class ELFT> void Writer<ELFT>::writeBuildId() {
3041 if (!mainPart->buildId || !mainPart->buildId->getParent())
3042 return;
3044 if (config->buildId == BuildIdKind::Hexstring) {
3045 for (Partition &part : partitions)
3046 part.buildId->writeBuildId(config->buildIdVector);
3047 return;
3050 // Compute a hash of all sections of the output file.
3051 size_t hashSize = mainPart->buildId->hashSize;
3052 std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
3053 MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
3054 llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
3056 // Fedora introduced build ID as "approximation of true uniqueness across all
3057 // binaries that might be used by overlapping sets of people". It does not
3058 // need some security goals that some hash algorithms strive to provide, e.g.
3059 // (second-)preimage and collision resistance. In practice people use 'md5'
3060 // and 'sha1' just for different lengths. Implement them with the more
3061 // efficient BLAKE3.
3062 switch (config->buildId) {
3063 case BuildIdKind::Fast:
3064 computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
3065 write64le(dest, xxh3_64bits(arr));
3067 break;
3068 case BuildIdKind::Md5:
3069 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3070 memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
3072 break;
3073 case BuildIdKind::Sha1:
3074 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3075 memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
3077 break;
3078 case BuildIdKind::Uuid:
3079 if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
3080 error("entropy source failure: " + ec.message());
3081 break;
3082 default:
3083 llvm_unreachable("unknown BuildIdKind");
3085 for (Partition &part : partitions)
3086 part.buildId->writeBuildId(output);
3089 template void elf::createSyntheticSections<ELF32LE>();
3090 template void elf::createSyntheticSections<ELF32BE>();
3091 template void elf::createSyntheticSections<ELF64LE>();
3092 template void elf::createSyntheticSections<ELF64BE>();
3094 template void elf::writeResult<ELF32LE>();
3095 template void elf::writeResult<ELF32BE>();
3096 template void elf::writeResult<ELF64LE>();
3097 template void elf::writeResult<ELF64BE>();