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