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