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// In order to allow users to manipulate linker-synthesized sections,
1751// we had to add synthetic sections to the input section list early,
1752// even before we make decisions whether they are needed. This allows
1753// users to write scripts like this: ".mygot : { .got }".
1754//
1755// Doing it has an unintended side effects. If it turns out that we
1756// don't need a .got (for example) at all because there's no
1757// relocation that needs a .got, we don't want to emit .got.
1758//
1759// To deal with the above problem, this function is called after
1760// scanRelocations is called to remove synthetic sections that turn
1761// out to be empty.
1762static void removeUnusedSyntheticSections(Ctx &ctx) {
1763 // All input synthetic sections that can be empty are placed after
1764 // all regular ones. Reverse iterate to find the first synthetic section
1765 // after a non-synthetic one which will be our starting point.
1766 auto start =
1767 llvm::find_if(Range: llvm::reverse(C&: ctx.inputSections), P: [](InputSectionBase *s) {
1768 return !isa<SyntheticSection>(Val: s);
1769 }).base();
1770
1771 // Remove unused synthetic sections from ctx.inputSections;
1772 DenseSet<InputSectionBase *> unused;
1773 auto end =
1774 std::remove_if(first: start, last: ctx.inputSections.end(), pred: [&](InputSectionBase *s) {
1775 auto *sec = cast<SyntheticSection>(Val: s);
1776 if (sec->getParent() && sec->isNeeded())
1777 return false;
1778 // .relr.auth.dyn relocations may be moved to .rela.dyn in
1779 // finalizeAddressDependentContent, making .rela.dyn no longer empty.
1780 // Conservatively keep .rela.dyn. .relr.auth.dyn can be made empty, but
1781 // we would fail to remove it here.
1782 if (ctx.arg.emachine == EM_AARCH64 && ctx.arg.relrPackDynRelocs &&
1783 sec == ctx.in.relaDyn.get() && ctx.in.relrAuthDyn &&
1784 ctx.in.relrAuthDyn->isNeeded())
1785 return false;
1786 unused.insert(V: sec);
1787 return true;
1788 });
1789 ctx.inputSections.erase(CS: end, CE: ctx.inputSections.end());
1790
1791 // Remove unused synthetic sections from the corresponding input section
1792 // description and orphanSections.
1793 for (auto *sec : unused)
1794 if (OutputSection *osec = cast<SyntheticSection>(Val: sec)->getParent())
1795 for (SectionCommand *cmd : osec->commands)
1796 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd))
1797 llvm::erase_if(C&: isd->sections, P: [&](InputSection *isec) {
1798 return unused.contains(V: isec);
1799 });
1800 llvm::erase_if(C&: ctx.script->orphanSections, P: [&](const InputSectionBase *sec) {
1801 return unused.contains(V: sec);
1802 });
1803}
1804
1805// Create output section objects and add them to OutputSections.
1806template <class ELFT> void Writer<ELFT>::finalizeSections() {
1807 if (!ctx.arg.relocatable) {
1808 ctx.out.preinitArray = findSection(ctx, name: ".preinit_array");
1809 ctx.out.initArray = findSection(ctx, name: ".init_array");
1810 ctx.out.finiArray = findSection(ctx, name: ".fini_array");
1811
1812 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1813 // symbols for sections, so that the runtime can get the start and end
1814 // addresses of each section by section name. Add such symbols.
1815 addStartEndSymbols();
1816 for (SectionCommand *cmd : ctx.script->sectionCommands)
1817 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
1818 addStartStopSymbols(osec&: osd->osec);
1819
1820 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1821 // It should be okay as no one seems to care about the type.
1822 // Even the author of gold doesn't remember why gold behaves that way.
1823 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1824 if (ctx.in.dynamic->parent) {
1825 Symbol *s = ctx.symtab->addSymbol(newSym: Defined{
1826 ctx, ctx.internalFile, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1827 /*value=*/0, /*size=*/0, ctx.in.dynamic.get()});
1828 s->isUsedInRegularObj = true;
1829 }
1830
1831 // Define __rel[a]_iplt_{start,end} symbols if needed.
1832 addRelIpltSymbols();
1833
1834 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1835 // should only be defined in an executable. If .sdata does not exist, its
1836 // value/section does not matter but it has to be relative, so set its
1837 // st_shndx arbitrarily to 1 (ctx.out.elfHeader).
1838 if (ctx.arg.emachine == EM_RISCV) {
1839 if (!ctx.arg.shared) {
1840 OutputSection *sec = findSection(ctx, name: ".sdata");
1841 addOptionalRegular(ctx, name: "__global_pointer$",
1842 sec: sec ? sec : ctx.out.elfHeader.get(), val: 0x800,
1843 stOther: STV_DEFAULT);
1844 // Set riscvGlobalPointer to be used by the optional global pointer
1845 // relaxation.
1846 if (ctx.arg.relaxGP) {
1847 Symbol *s = ctx.symtab->find(name: "__global_pointer$");
1848 if (s && s->isDefined())
1849 ctx.sym.riscvGlobalPointer = cast<Defined>(Val: s);
1850 }
1851 }
1852 }
1853
1854 if (ctx.arg.emachine == EM_386 || ctx.arg.emachine == EM_X86_64) {
1855 // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1856 // way that:
1857 //
1858 // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1859 // computes 0.
1860 // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address
1861 // in the TLS block).
1862 //
1863 // 2) is special cased in @tpoff computation. To satisfy 1), we define it
1864 // as an absolute symbol of zero. This is different from GNU linkers which
1865 // define _TLS_MODULE_BASE_ relative to the first TLS section.
1866 Symbol *s = ctx.symtab->find(name: "_TLS_MODULE_BASE_");
1867 if (s && s->isUndefined()) {
1868 s->resolve(ctx, other: Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
1869 STV_HIDDEN, STT_TLS, /*value=*/0, 0,
1870 /*section=*/nullptr});
1871 ctx.sym.tlsModuleBase = cast<Defined>(Val: s);
1872 }
1873 }
1874
1875 // This responsible for splitting up .eh_frame section into
1876 // pieces. The relocation scan uses those pieces, so this has to be
1877 // earlier.
1878 {
1879 llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1880 finalizeSynthetic(ctx, sec: ctx.in.ehFrame.get());
1881 }
1882 }
1883
1884 // If the previous code block defines any non-hidden symbols (e.g.
1885 // __global_pointer$), they may be exported.
1886 if (ctx.arg.exportDynamic)
1887 for (Symbol *sym : ctx.synthesizedSymbols)
1888 if (sym->computeBinding(ctx) != STB_LOCAL)
1889 sym->isExported = true;
1890
1891 demoteSymbolsAndComputeIsPreemptible(ctx);
1892
1893 demoteAndCopyLocalSymbols(ctx);
1894
1895 if (ctx.arg.copyRelocs)
1896 addSectionSymbols();
1897
1898 // Change values of linker-script-defined symbols from placeholders (assigned
1899 // by declareSymbols) to actual definitions.
1900 ctx.script->processSymbolAssignments();
1901
1902 if (!ctx.arg.relocatable) {
1903 llvm::TimeTraceScope timeScope("Scan relocations");
1904 // Scan relocations. This must be done after every symbol is declared so
1905 // that we can correctly decide if a dynamic relocation is needed. This is
1906 // called after processSymbolAssignments() because it needs to know whether
1907 // a linker-script-defined symbol is absolute.
1908 scanRelocations<ELFT>(ctx);
1909 reportUndefinedSymbols(ctx);
1910 postScanRelocations(ctx);
1911
1912 if (ctx.in.plt && ctx.in.plt->isNeeded())
1913 ctx.in.plt->addSymbols();
1914 if (ctx.in.iplt && ctx.in.iplt->isNeeded())
1915 ctx.in.iplt->addSymbols();
1916
1917 if (ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1918 auto diag =
1919 ctx.arg.unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError &&
1920 !ctx.arg.noinhibitExec
1921 ? DiagLevel::Err
1922 : DiagLevel::Warn;
1923 // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1924 // entries are seen. These cases would otherwise lead to runtime errors
1925 // reported by the dynamic linker.
1926 //
1927 // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker
1928 // to catch more cases. That is too much for us. Our approach resembles
1929 // the one used in ld.gold, achieves a good balance to be useful but not
1930 // too smart.
1931 //
1932 // If a DSO reference is resolved by a SharedSymbol, but the SharedSymbol
1933 // is overridden by a hidden visibility Defined (which is later discarded
1934 // due to GC), don't report the diagnostic. However, this may indicate an
1935 // unintended SharedSymbol.
1936 for (SharedFile *file : ctx.sharedFiles) {
1937 bool allNeededIsKnown =
1938 llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1939 return ctx.symtab->soNames.contains(Val: CachedHashStringRef(needed));
1940 });
1941 if (!allNeededIsKnown)
1942 continue;
1943 for (Symbol *sym : file->requiredSymbols) {
1944 if (sym->dsoDefined)
1945 continue;
1946 if (sym->isUndefined() && !sym->isWeak()) {
1947 ELFSyncStream(ctx, diag)
1948 << "undefined reference: " << sym << "\n>>> referenced by "
1949 << file << " (disallowed by --no-allow-shlib-undefined)";
1950 } else if (sym->isDefined() &&
1951 sym->computeBinding(ctx) == STB_LOCAL) {
1952 ELFSyncStream(ctx, diag)
1953 << "non-exported symbol '" << sym << "' in '" << sym->file
1954 << "' is referenced by DSO '" << file << "'";
1955 }
1956 }
1957 }
1958 }
1959 }
1960
1961 {
1962 llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1963 if (ctx.in.symTab)
1964 ctx.in.symTab->markGlobalPart();
1965 // Now that we have defined all possible global symbols including linker-
1966 // synthesized ones. Visit all symbols to give the finishing touches.
1967 for (Symbol *sym : ctx.symtab->getSymbols()) {
1968 if (!sym->isUsedInRegularObj || !includeInSymtab(ctx, b: *sym))
1969 continue;
1970 if (!ctx.arg.relocatable)
1971 sym->binding = sym->computeBinding(ctx);
1972 if (ctx.in.symTab &&
1973 (!ctx.arg.retainSymbols || retainKeepsInSymtab(ctx, sym: *sym)))
1974 ctx.in.symTab->addSymbol(sym);
1975
1976 // computeBinding might localize a symbol that was considered exported
1977 // but then synthesized as hidden (e.g. _DYNAMIC).
1978 if ((sym->isExported || sym->isPreemptible) && !sym->isLocal()) {
1979 ctx.in.dynSymTab->addSymbol(sym);
1980 if (auto *file = dyn_cast<SharedFile>(Val: sym->file))
1981 if (file->isNeeded && !sym->isUndefined())
1982 addVerneed(ctx, ss&: *sym);
1983 }
1984 }
1985 if (ctx.in.symTab && !ctx.arg.relocatable)
1986 ctx.in.symTab->maybeAddSttFile();
1987 }
1988
1989 if (ctx.in.mipsGot)
1990 ctx.in.mipsGot->build();
1991
1992 removeUnusedSyntheticSections(ctx);
1993 ctx.script->diagnoseOrphanHandling();
1994 ctx.script->diagnoseMissingSGSectionAddress();
1995
1996 sortSections();
1997
1998 // Create a list of OutputSections, assign sectionIndex, and populate
1999 // ctx.in.shStrTab. If -z nosectionheader is specified, drop non-ALLOC
2000 // sections.
2001 for (SectionCommand *cmd : ctx.script->sectionCommands)
2002 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd)) {
2003 OutputSection *osec = &osd->osec;
2004 if (!ctx.in.shStrTab && !(osec->flags & SHF_ALLOC))
2005 continue;
2006 ctx.outputSections.push_back(Elt: osec);
2007 osec->sectionIndex = ctx.outputSections.size();
2008 if (ctx.in.shStrTab)
2009 osec->shName = ctx.in.shStrTab->addString(s: osec->name);
2010 }
2011
2012 // Prefer command line supplied address over other constraints.
2013 for (OutputSection *sec : ctx.outputSections) {
2014 auto i = ctx.arg.sectionStartMap.find(Key: sec->name);
2015 if (i != ctx.arg.sectionStartMap.end())
2016 sec->addrExpr = [=] { return i->second; };
2017 }
2018
2019 // This is a bit of a hack. A value of 0 means undef, so we set it
2020 // to 1 to make __ehdr_start defined. The section number is not
2021 // particularly relevant.
2022 ctx.out.elfHeader->sectionIndex = 1;
2023 ctx.out.elfHeader->size = sizeof(typename ELFT::Ehdr);
2024
2025 // Binary and relocatable output does not have PHDRS.
2026 // The headers have to be created before finalize as that can influence the
2027 // image base and the dynamic section on mips includes the image base.
2028 if (!ctx.arg.relocatable && !ctx.arg.oFormatBinary) {
2029 ctx.phdrs = ctx.script->hasPhdrsCommands() ? ctx.script->createPhdrs()
2030 : createPhdrs();
2031 if (ctx.arg.emachine == EM_ARM) {
2032 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2033 addPhdrForSection(shType: SHT_ARM_EXIDX, pType: PT_ARM_EXIDX, pFlags: PF_R);
2034 }
2035 if (ctx.arg.emachine == EM_MIPS) {
2036 // Add separate segments for MIPS-specific sections.
2037 addPhdrForSection(shType: SHT_MIPS_REGINFO, pType: PT_MIPS_REGINFO, pFlags: PF_R);
2038 addPhdrForSection(shType: SHT_MIPS_OPTIONS, pType: PT_MIPS_OPTIONS, pFlags: PF_R);
2039 addPhdrForSection(shType: SHT_MIPS_ABIFLAGS, pType: PT_MIPS_ABIFLAGS, pFlags: PF_R);
2040 }
2041 if (ctx.arg.emachine == EM_RISCV)
2042 addPhdrForSection(shType: SHT_RISCV_ATTRIBUTES, pType: PT_RISCV_ATTRIBUTES, pFlags: PF_R);
2043 ctx.out.programHeaders->size = sizeof(Elf_Phdr) * ctx.phdrs.size();
2044
2045 // Find the TLS segment. This happens before the section layout loop so that
2046 // Android relocation packing can look up TLS symbol addresses.
2047 for (auto &p : ctx.phdrs)
2048 if (p->p_type == PT_TLS)
2049 ctx.tlsPhdr = p.get();
2050 }
2051
2052 // Some symbols are defined in term of program headers. Now that we
2053 // have the headers, we can find out which sections they point to.
2054 setReservedSymbolSections();
2055
2056 if (ctx.script->noCrossRefs.size()) {
2057 llvm::TimeTraceScope timeScope("Check NOCROSSREFS");
2058 checkNoCrossRefs<ELFT>(ctx);
2059 }
2060
2061 {
2062 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2063
2064 finalizeSynthetic(ctx, sec: ctx.in.bss.get());
2065 finalizeSynthetic(ctx, sec: ctx.in.bssRelRo.get());
2066 finalizeSynthetic(ctx, sec: ctx.in.symTabShndx.get());
2067 finalizeSynthetic(ctx, sec: ctx.in.shStrTab.get());
2068 finalizeSynthetic(ctx, sec: ctx.in.strTab.get());
2069 finalizeSynthetic(ctx, sec: ctx.in.got.get());
2070 finalizeSynthetic(ctx, sec: ctx.in.mipsGot.get());
2071 finalizeSynthetic(ctx, sec: ctx.in.igotPlt.get());
2072 finalizeSynthetic(ctx, sec: ctx.in.gotPlt.get());
2073 finalizeSynthetic(ctx, sec: ctx.in.relaPlt.get());
2074 finalizeSynthetic(ctx, sec: ctx.in.plt.get());
2075 finalizeSynthetic(ctx, sec: ctx.in.iplt.get());
2076 finalizeSynthetic(ctx, sec: ctx.in.ppc32Got2.get());
2077
2078 // Dynamic section must be the last one in this list and dynamic
2079 // symbol table section (dynSymTab) must be the first one.
2080 finalizeSynthetic(ctx, sec: ctx.in.relaDyn.get());
2081 finalizeSynthetic(ctx, sec: ctx.in.relrDyn.get());
2082 finalizeSynthetic(ctx, sec: ctx.in.relrAuthDyn.get());
2083
2084 finalizeSynthetic(ctx, sec: ctx.in.dynSymTab.get());
2085 finalizeSynthetic(ctx, sec: ctx.in.gnuHashTab.get());
2086 finalizeSynthetic(ctx, sec: ctx.in.hashTab.get());
2087 finalizeSynthetic(ctx, sec: ctx.in.verDef.get());
2088 finalizeSynthetic(ctx, sec: ctx.in.ehFrameHdr.get());
2089 finalizeSynthetic(ctx, sec: ctx.in.verSym.get());
2090 finalizeSynthetic(ctx, sec: ctx.in.verNeed.get());
2091 finalizeSynthetic(ctx, sec: ctx.in.dynamic.get());
2092 }
2093
2094 if (!ctx.script->hasSectionsCommand && !ctx.arg.relocatable)
2095 fixSectionAlignments();
2096
2097 // This is used to:
2098 // 1) Create "thunks":
2099 // Jump instructions in many ISAs have small displacements, and therefore
2100 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2101 // JAL instruction can target only +-1 MiB from PC. It is a linker's
2102 // responsibility to create and insert small pieces of code between
2103 // sections to extend the ranges if jump targets are out of range. Such
2104 // code pieces are called "thunks".
2105 //
2106 // We add thunks at this stage. We couldn't do this before this point
2107 // because this is the earliest point where we know sizes of sections and
2108 // their layouts (that are needed to determine if jump targets are in
2109 // range).
2110 //
2111 // 2) Update the sections. We need to generate content that depends on the
2112 // address of InputSections. For example, MIPS GOT section content or
2113 // android packed relocations sections content.
2114 //
2115 // 3) Assign the final values for the linker script symbols. Linker scripts
2116 // sometimes using forward symbol declarations. We want to set the correct
2117 // values. They also might change after adding the thunks.
2118 finalizeAddressDependentContent();
2119
2120 // All information needed for OutputSection part of Map file is available.
2121 if (errCount(ctx))
2122 return;
2123
2124 {
2125 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2126 // finalizeAddressDependentContent may have added local symbols to the
2127 // static symbol table.
2128 finalizeSynthetic(ctx, sec: ctx.in.symTab.get());
2129 finalizeSynthetic(ctx, sec: ctx.in.debugNames.get());
2130 finalizeSynthetic(ctx, sec: ctx.in.ppc64LongBranchTarget.get());
2131 finalizeSynthetic(ctx, sec: ctx.in.armCmseSGSection.get());
2132 }
2133
2134 // Relaxation to delete inter-basic block jumps created by basic block
2135 // sections. Run after ctx.in.symTab is finalized as optimizeBasicBlockJumps
2136 // can relax jump instructions based on symbol offset.
2137 if (ctx.arg.optimizeBBJumps)
2138 optimizeBasicBlockJumps();
2139
2140 // Fill other section headers. The dynamic table is finalized
2141 // at the end because some tags like RELSZ depend on result
2142 // of finalizing other sections.
2143 for (OutputSection *sec : ctx.outputSections)
2144 sec->finalize(ctx);
2145
2146 ctx.script->checkFinalScriptConditions();
2147
2148 if (ctx.arg.emachine == EM_ARM && !ctx.arg.isLE && ctx.arg.armBe8) {
2149 addArmInputSectionMappingSymbols(ctx);
2150 sortArmMappingSymbols(ctx);
2151 }
2152}
2153
2154// Ensure data sections are not mixed with executable sections when
2155// --execute-only is used. --execute-only make pages executable but not
2156// readable.
2157template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2158 if (!ctx.arg.executeOnly)
2159 return;
2160
2161 SmallVector<InputSection *, 0> storage;
2162 for (OutputSection *osec : ctx.outputSections)
2163 if (osec->flags & SHF_EXECINSTR)
2164 for (InputSection *isec : getInputSections(os: *osec, storage))
2165 if (!(isec->flags & SHF_EXECINSTR))
2166 ErrAlways(ctx) << "cannot place " << isec << " into " << osec->name
2167 << ": --execute-only does not support intermingling "
2168 "data and code";
2169}
2170
2171// Check which input sections of RX output sections don't have the
2172// SHF_AARCH64_PURECODE or SHF_ARM_PURECODE flag set.
2173template <class ELFT> void Writer<ELFT>::checkExecuteOnlyReport() {
2174 if (ctx.arg.zExecuteOnlyReport == ReportPolicy::None)
2175 return;
2176
2177 auto reportUnless = [&](bool cond) -> ELFSyncStream {
2178 if (cond)
2179 return {ctx, DiagLevel::None};
2180 return {ctx, toDiagLevel(policy: ctx.arg.zExecuteOnlyReport)};
2181 };
2182
2183 uint64_t purecodeFlag =
2184 ctx.arg.emachine == EM_AARCH64 ? SHF_AARCH64_PURECODE : SHF_ARM_PURECODE;
2185 StringRef purecodeFlagName = ctx.arg.emachine == EM_AARCH64
2186 ? "SHF_AARCH64_PURECODE"
2187 : "SHF_ARM_PURECODE";
2188 SmallVector<InputSection *, 0> storage;
2189 for (OutputSection *osec : ctx.outputSections) {
2190 if (osec->getPhdrFlags() != (PF_R | PF_X))
2191 continue;
2192 for (InputSection *sec : getInputSections(os: *osec, storage)) {
2193 if (isa<SyntheticSection>(Val: sec))
2194 continue;
2195 reportUnless(sec->flags & purecodeFlag)
2196 << "-z execute-only-report: " << sec << " does not have "
2197 << purecodeFlagName << " flag set";
2198 }
2199 }
2200}
2201
2202// The linker is expected to define SECNAME_start and SECNAME_end
2203// symbols for a few sections. This function defines them.
2204template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2205 // If the associated output section does not exist, there is ambiguity as to
2206 // how we define _start and _end symbols for an init/fini section. Users
2207 // expect no "undefined symbol" linker errors and loaders expect equal
2208 // st_value but do not particularly care whether the symbols are defined or
2209 // not. We retain the output section so that the section indexes will be
2210 // correct.
2211 auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2212 if (os) {
2213 Defined *startSym = addOptionalRegular(ctx, name: start, sec: os, val: 0);
2214 Defined *stopSym = addOptionalRegular(ctx, name: end, sec: os, val: -1);
2215 if (startSym || stopSym)
2216 os->usedInExpression = true;
2217 } else {
2218 addOptionalRegular(ctx, name: start, sec: ctx.out.elfHeader.get(), val: 0);
2219 addOptionalRegular(ctx, name: end, sec: ctx.out.elfHeader.get(), val: 0);
2220 }
2221 };
2222
2223 define("__preinit_array_start", "__preinit_array_end", ctx.out.preinitArray);
2224 define("__init_array_start", "__init_array_end", ctx.out.initArray);
2225 define("__fini_array_start", "__fini_array_end", ctx.out.finiArray);
2226
2227 // As a special case, don't unnecessarily retain .ARM.exidx, which would
2228 // create an empty PT_ARM_EXIDX.
2229 if (OutputSection *sec = findSection(ctx, name: ".ARM.exidx"))
2230 define("__exidx_start", "__exidx_end", sec);
2231}
2232
2233// If a section name is valid as a C identifier (which is rare because of
2234// the leading '.'), linkers are expected to define __start_<secname> and
2235// __stop_<secname> symbols. They are at beginning and end of the section,
2236// respectively. This is not requested by the ELF standard, but GNU ld and
2237// gold provide the feature, and used by many programs.
2238template <class ELFT>
2239void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
2240 StringRef s = osec.name;
2241 if (!isValidCIdentifier(s))
2242 return;
2243 StringSaver &ss = ctx.saver;
2244 Defined *startSym = addOptionalRegular(ctx, name: ss.save(S: "__start_" + s), sec: &osec, val: 0,
2245 stOther: ctx.arg.zStartStopVisibility);
2246 Defined *stopSym = addOptionalRegular(ctx, name: ss.save(S: "__stop_" + s), sec: &osec, val: -1,
2247 stOther: ctx.arg.zStartStopVisibility);
2248 if (startSym || stopSym)
2249 osec.usedInExpression = true;
2250}
2251
2252static bool needsPtLoad(OutputSection *sec) {
2253 if (!(sec->flags & SHF_ALLOC))
2254 return false;
2255
2256 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2257 // responsible for allocating space for them, not the PT_LOAD that
2258 // contains the TLS initialization image.
2259 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2260 return false;
2261 return true;
2262}
2263
2264// Adjust phdr flags according to certain options.
2265static uint64_t computeFlags(Ctx &ctx, uint64_t flags) {
2266 if (ctx.arg.omagic)
2267 return PF_R | PF_W | PF_X;
2268 if (ctx.arg.executeOnly && (flags & PF_X))
2269 return flags & ~PF_R;
2270 return flags;
2271}
2272
2273// Decide which program headers to create and which sections to include in each
2274// one.
2275template <class ELFT>
2276SmallVector<std::unique_ptr<PhdrEntry>, 0> Writer<ELFT>::createPhdrs() {
2277 SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;
2278 auto addHdr = [&, &ctx = ctx](unsigned type, unsigned flags) -> PhdrEntry * {
2279 ret.push_back(Elt: std::make_unique<PhdrEntry>(args&: ctx, args&: type, args&: flags));
2280 return ret.back().get();
2281 };
2282
2283 // Add the first PT_LOAD segment for regular output sections.
2284 uint64_t flags = computeFlags(ctx, flags: PF_R);
2285 PhdrEntry *load = nullptr;
2286
2287 // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2288 // PT_LOAD.
2289 if (!ctx.arg.nmagic && !ctx.arg.omagic) {
2290 // The first phdr entry is PT_PHDR which describes the program header
2291 // itself.
2292 addHdr(PT_PHDR, PF_R)->add(ctx.out.programHeaders.get());
2293
2294 // PT_INTERP must be the second entry if exists.
2295 if (OutputSection *cmd = findSection(ctx, name: ".interp"))
2296 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2297
2298 // Add the headers. We will remove them if they don't fit.
2299 load = addHdr(PT_LOAD, flags);
2300 load->add(sec: ctx.out.elfHeader.get());
2301 load->add(sec: ctx.out.programHeaders.get());
2302 }
2303
2304 // PT_GNU_RELRO includes all sections that should be marked as read-only by
2305 // dynamic linker after processing relocations. Create one PT_GNU_RELRO for
2306 // each run of contiguous relro sections. No diagnostics even if some loaders
2307 // only honor one PT_GNU_RELRO.
2308 SmallVector<std::unique_ptr<PhdrEntry>, 0> relRos;
2309 SmallPtrSet<OutputSection *, 1> relroEnds;
2310 PhdrEntry *activeRelRo = nullptr;
2311 for (OutputSection *sec : ctx.outputSections) {
2312 if (!needsPtLoad(sec))
2313 continue;
2314 if (isRelroSection(ctx, sec)) {
2315 if (!activeRelRo) {
2316 relRos.push_back(Elt: std::make_unique<PhdrEntry>(args&: ctx, args: PT_GNU_RELRO, args: PF_R));
2317 activeRelRo = relRos.back().get();
2318 }
2319 activeRelRo->add(sec);
2320 } else if (activeRelRo) {
2321 activeRelRo = nullptr;
2322 relroEnds.insert(Ptr: sec);
2323 }
2324 }
2325
2326 for (OutputSection *sec : ctx.outputSections) {
2327 if (!needsPtLoad(sec))
2328 continue;
2329
2330 // Segments are contiguous memory regions that has the same attributes
2331 // (e.g. executable or writable). There is one phdr for each segment.
2332 // Therefore, we need to create a new phdr when the next section has
2333 // incompatible flags or is loaded at a discontiguous address or memory
2334 // region using AT or AT> linker script command, respectively.
2335 //
2336 // As an exception, we don't create a separate load segment for the ELF
2337 // headers, even if the first "real" output has an AT or AT> attribute.
2338 //
2339 // In addition, NOBITS sections should only be placed at the end of a LOAD
2340 // segment (since it's represented as p_filesz < p_memsz). If we have a
2341 // not-NOBITS section after a NOBITS, we create a new LOAD for the latter
2342 // even if flags match, so as not to require actually writing the
2343 // supposed-to-be-NOBITS section to the output file. (However, we cannot do
2344 // so when hasSectionsCommand, since we cannot introduce the extra alignment
2345 // needed to create a new LOAD)
2346 uint64_t newFlags = computeFlags(ctx, flags: sec->getPhdrFlags());
2347 uint64_t incompatible = flags ^ newFlags;
2348 if (!(newFlags & PF_W)) {
2349 // When --no-rosegment is specified, RO and RX sections are compatible.
2350 if (ctx.arg.singleRoRx)
2351 incompatible &= ~PF_X;
2352 // When --no-xosegment is specified (the default), XO and RX sections are
2353 // compatible.
2354 if (ctx.arg.singleXoRx)
2355 incompatible &= ~PF_R;
2356 }
2357 if (incompatible)
2358 load = nullptr;
2359
2360 bool sameLMARegion =
2361 load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2362 if (load && !relroEnds.contains(Ptr: sec) &&
2363 sec->memRegion == load->firstSec->memRegion &&
2364 (sameLMARegion || load->lastSec == ctx.out.programHeaders.get()) &&
2365 (ctx.script->hasSectionsCommand || sec->type == SHT_NOBITS ||
2366 load->lastSec->type != SHT_NOBITS)) {
2367 load->p_flags |= newFlags;
2368 } else {
2369 load = addHdr(PT_LOAD, newFlags);
2370 flags = newFlags;
2371 }
2372
2373 load->add(sec);
2374 }
2375
2376 // Add a TLS segment if any.
2377 auto tlsHdr = std::make_unique<PhdrEntry>(args&: ctx, args: PT_TLS, args: PF_R);
2378 for (OutputSection *sec : ctx.outputSections)
2379 if (sec->flags & SHF_TLS)
2380 tlsHdr->add(sec);
2381 if (tlsHdr->firstSec)
2382 ret.push_back(Elt: std::move(tlsHdr));
2383
2384 // Add an entry for .dynamic.
2385 if (ctx.in.dynamic)
2386 if (OutputSection *sec = ctx.in.dynamic->getParent())
2387 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2388
2389 for (std::unique_ptr<PhdrEntry> &phdr : relRos) {
2390 phdr->p_align = 1;
2391 ret.push_back(Elt: std::move(phdr));
2392 }
2393
2394 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2395 if (ctx.in.ehFrameHdr && ctx.in.ehFrameHdr->isNeeded())
2396 addHdr(PT_GNU_EH_FRAME, ctx.in.ehFrameHdr->getParent()->getPhdrFlags())
2397 ->add(ctx.in.ehFrameHdr->getParent());
2398
2399 if (ctx.arg.osabi == ELFOSABI_OPENBSD) {
2400 // PT_OPENBSD_MUTABLE makes the dynamic linker fill the segment with
2401 // zero data, like bss, but it can be treated differently.
2402 if (OutputSection *cmd = findSection(ctx, name: ".openbsd.mutable"))
2403 addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
2404
2405 // PT_OPENBSD_RANDOMIZE makes the dynamic linker fill the segment
2406 // with random data.
2407 if (OutputSection *cmd = findSection(ctx, name: ".openbsd.randomdata"))
2408 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2409
2410 // PT_OPENBSD_SYSCALLS makes the kernel and dynamic linker register
2411 // system call sites.
2412 if (OutputSection *cmd = findSection(ctx, name: ".openbsd.syscalls"))
2413 addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
2414 }
2415
2416 if (ctx.arg.zGnustack != GnuStackKind::None) {
2417 // PT_GNU_STACK is a special section to tell the loader to make the
2418 // pages for the stack non-executable. If you really want an executable
2419 // stack, you can pass -z execstack, but that's not recommended for
2420 // security reasons.
2421 unsigned perm = PF_R | PF_W;
2422 if (ctx.arg.zGnustack == GnuStackKind::Exec)
2423 perm |= PF_X;
2424 addHdr(PT_GNU_STACK, perm)->p_memsz = ctx.arg.zStackSize;
2425 }
2426
2427 // PT_OPENBSD_NOBTCFI is an OpenBSD-specific header to mark that the
2428 // executable is expected to violate branch-target CFI checks.
2429 if (ctx.arg.zNoBtCfi)
2430 addHdr(PT_OPENBSD_NOBTCFI, PF_X);
2431
2432 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2433 // is expected to perform W^X violations, such as calling mprotect(2) or
2434 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2435 // OpenBSD.
2436 if (ctx.arg.zWxneeded)
2437 addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2438
2439 if (OutputSection *cmd = findSection(ctx, name: ".note.gnu.property"))
2440 addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2441
2442 // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2443 // same alignment.
2444 PhdrEntry *note = nullptr;
2445 for (OutputSection *sec : ctx.outputSections) {
2446 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2447 if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2448 note = addHdr(PT_NOTE, PF_R);
2449 note->add(sec);
2450 } else {
2451 note = nullptr;
2452 }
2453 }
2454 return ret;
2455}
2456
2457template <class ELFT>
2458void Writer<ELFT>::addPhdrForSection(unsigned shType, unsigned pType,
2459 unsigned pFlags) {
2460 auto i = llvm::find_if(ctx.outputSections, [=](OutputSection *cmd) {
2461 return cmd->type == shType;
2462 });
2463 if (i == ctx.outputSections.end())
2464 return;
2465
2466 auto entry = std::make_unique<PhdrEntry>(args&: ctx, args&: pType, args&: pFlags);
2467 entry->add(sec: *i);
2468 ctx.phdrs.push_back(Elt: std::move(entry));
2469}
2470
2471// Place the first section of each PT_LOAD to a different page (of maxPageSize).
2472// This is achieved by assigning an alignment expression to addrExpr of each
2473// such section.
2474template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2475 const PhdrEntry *prev;
2476 auto pageAlign = [&, &ctx = this->ctx](const PhdrEntry *p) {
2477 OutputSection *cmd = p->firstSec;
2478 if (!cmd)
2479 return;
2480 cmd->alignExpr = [align = cmd->addralign]() { return align; };
2481 if (!cmd->addrExpr) {
2482 // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2483 // padding in the file contents.
2484 //
2485 // When -z separate-code is used we must not have any overlap in pages
2486 // between an executable segment and a non-executable segment. We align to
2487 // the next maximum page size boundary on transitions between executable
2488 // and non-executable segments.
2489 if (ctx.arg.zSeparate == SeparateSegmentKind::Loadable ||
2490 (ctx.arg.zSeparate == SeparateSegmentKind::Code && prev &&
2491 (prev->p_flags & PF_X) != (p->p_flags & PF_X)))
2492 cmd->addrExpr = [&ctx = this->ctx] {
2493 return alignToPowerOf2(Value: ctx.script->getDot(), Align: ctx.arg.maxPageSize);
2494 };
2495 // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2496 // it must be the RW. Align to p_align(PT_TLS) to make sure
2497 // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2498 // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2499 // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2500 // be congruent to 0 modulo p_align(PT_TLS).
2501 //
2502 // Technically this is not required, but as of 2019, some dynamic loaders
2503 // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2504 // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2505 // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2506 // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2507 // blocks correctly. We need to keep the workaround for a while.
2508 else if (ctx.tlsPhdr && ctx.tlsPhdr->firstSec == p->firstSec)
2509 cmd->addrExpr = [&ctx] {
2510 return alignToPowerOf2(Value: ctx.script->getDot(), Align: ctx.arg.maxPageSize) +
2511 alignToPowerOf2(Value: ctx.script->getDot() % ctx.arg.maxPageSize,
2512 Align: ctx.tlsPhdr->p_align);
2513 };
2514 else
2515 cmd->addrExpr = [&ctx] {
2516 return alignToPowerOf2(Value: ctx.script->getDot(), Align: ctx.arg.maxPageSize) +
2517 ctx.script->getDot() % ctx.arg.maxPageSize;
2518 };
2519 }
2520 };
2521
2522 prev = nullptr;
2523 for (auto &ph : ctx.phdrs)
2524 if (ph->p_type == PT_LOAD && ph->firstSec) {
2525 pageAlign(ph.get());
2526 prev = ph.get();
2527 }
2528}
2529
2530// Compute an in-file position for a given section. The file offset must be the
2531// same with its virtual address modulo the page size, so that the loader can
2532// load executables without any address adjustment.
2533static uint64_t computeFileOffset(Ctx &ctx, OutputSection *os, uint64_t off) {
2534 // The first section in a PT_LOAD has to have congruent offset and address
2535 // modulo the maximum page size.
2536 if (os->ptLoad && os->ptLoad->firstSec == os)
2537 return alignTo(Value: off, Align: os->ptLoad->p_align, Skew: os->addr);
2538
2539 // File offsets are not significant for .bss sections other than the first one
2540 // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2541 // increasing rather than setting to zero.
2542 if (os->type == SHT_NOBITS && (!ctx.tlsPhdr || ctx.tlsPhdr->firstSec != os))
2543 return off;
2544
2545 // If the section is not in a PT_LOAD, we just have to align it.
2546 if (!os->ptLoad)
2547 return alignToPowerOf2(Value: off, Align: os->addralign);
2548
2549 // If two sections share the same PT_LOAD the file offset is calculated
2550 // using this formula: Off2 = Off1 + (VA2 - VA1).
2551 OutputSection *first = os->ptLoad->firstSec;
2552 return first->offset + os->addr - first->addr;
2553}
2554
2555template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2556 // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2557 auto needsOffset = [](OutputSection &sec) {
2558 return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2559 };
2560 uint64_t minAddr = UINT64_MAX;
2561 for (OutputSection *sec : ctx.outputSections)
2562 if (needsOffset(*sec)) {
2563 sec->offset = sec->getLMA();
2564 minAddr = std::min(a: minAddr, b: sec->offset);
2565 }
2566
2567 // Sections are laid out at LMA minus minAddr.
2568 fileSize = 0;
2569 for (OutputSection *sec : ctx.outputSections)
2570 if (needsOffset(*sec)) {
2571 sec->offset -= minAddr;
2572 fileSize = std::max(a: fileSize, b: sec->offset + sec->size);
2573 }
2574}
2575
2576static std::string rangeToString(uint64_t addr, uint64_t len) {
2577 return "[0x" + utohexstr(X: addr) + ", 0x" + utohexstr(X: addr + len - 1) + "]";
2578}
2579
2580// Assign file offsets to output sections.
2581template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2582 ctx.out.programHeaders->offset = ctx.out.elfHeader->size;
2583 uint64_t off = ctx.out.elfHeader->size + ctx.out.programHeaders->size;
2584
2585 PhdrEntry *lastRX = nullptr;
2586 for (auto &p : ctx.phdrs)
2587 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2588 lastRX = p.get();
2589
2590 // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2591 // will not occupy file offsets contained by a PT_LOAD.
2592 for (OutputSection *sec : ctx.outputSections) {
2593 if (!(sec->flags & SHF_ALLOC))
2594 continue;
2595 off = computeFileOffset(ctx, os: sec, off);
2596 sec->offset = off;
2597 if (sec->type != SHT_NOBITS)
2598 off += sec->size;
2599
2600 // If this is a last section of the last executable segment and that
2601 // segment is the last loadable segment, align the offset of the
2602 // following section to avoid loading non-segments parts of the file.
2603 if (ctx.arg.zSeparate != SeparateSegmentKind::None && lastRX &&
2604 lastRX->lastSec == sec)
2605 off = alignToPowerOf2(Value: off, Align: ctx.arg.maxPageSize);
2606 }
2607 for (OutputSection *osec : ctx.outputSections) {
2608 if (osec->flags & SHF_ALLOC)
2609 continue;
2610 osec->offset = alignToPowerOf2(Value: off, Align: osec->addralign);
2611 off = osec->offset + osec->size;
2612 }
2613
2614 sectionHeaderOff = alignToPowerOf2(Value: off, Align: ctx.arg.wordsize);
2615 fileSize =
2616 sectionHeaderOff + (ctx.outputSections.size() + 1) * sizeof(Elf_Shdr);
2617
2618 // Our logic assumes that sections have rising VA within the same segment.
2619 // With use of linker scripts it is possible to violate this rule and get file
2620 // offset overlaps or overflows. That should never happen with a valid script
2621 // which does not move the location counter backwards and usually scripts do
2622 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2623 // kernel, which control segment distribution explicitly and move the counter
2624 // backwards, so we have to allow doing that to support linking them. We
2625 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2626 // we want to prevent file size overflows because it would crash the linker.
2627 for (OutputSection *sec : ctx.outputSections) {
2628 if (sec->type == SHT_NOBITS)
2629 continue;
2630 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2631 ErrAlways(ctx) << "unable to place section " << sec->name
2632 << " at file offset "
2633 << rangeToString(addr: sec->offset, len: sec->size)
2634 << "; check your linker script for overflows";
2635 }
2636}
2637
2638// Finalize the program headers. We call this function after we assign
2639// file offsets and VAs to all sections.
2640template <class ELFT> void Writer<ELFT>::setPhdrs() {
2641 for (std::unique_ptr<PhdrEntry> &p : ctx.phdrs) {
2642 OutputSection *first = p->firstSec;
2643 OutputSection *last = p->lastSec;
2644
2645 // .ARM.exidx sections may not be within a single .ARM.exidx
2646 // output section. We always want to describe just the
2647 // SyntheticSection.
2648 if (ctx.in.armExidx && p->p_type == PT_ARM_EXIDX) {
2649 p->p_filesz = ctx.in.armExidx->getSize();
2650 p->p_memsz = p->p_filesz;
2651 p->p_offset = first->offset + ctx.in.armExidx->outSecOff;
2652 p->p_vaddr = first->addr + ctx.in.armExidx->outSecOff;
2653 p->p_align = ctx.in.armExidx->addralign;
2654 if (!p->hasLMA)
2655 p->p_paddr = first->getLMA() + ctx.in.armExidx->outSecOff;
2656 return;
2657 }
2658
2659 if (first) {
2660 p->p_filesz = last->offset - first->offset;
2661 if (last->type != SHT_NOBITS)
2662 p->p_filesz += last->size;
2663
2664 p->p_memsz = last->addr + last->size - first->addr;
2665 p->p_offset = first->offset;
2666 p->p_vaddr = first->addr;
2667
2668 if (!p->hasLMA)
2669 p->p_paddr = first->getLMA();
2670 }
2671 }
2672}
2673
2674// A helper struct for checkSectionOverlap.
2675namespace {
2676struct SectionOffset {
2677 OutputSection *sec;
2678 uint64_t offset;
2679};
2680} // namespace
2681
2682// Check whether sections overlap for a specific address range (file offsets,
2683// load and virtual addresses).
2684static void checkOverlap(Ctx &ctx, StringRef name,
2685 std::vector<SectionOffset> &sections,
2686 bool isVirtualAddr) {
2687 llvm::sort(C&: sections, Comp: [=](const SectionOffset &a, const SectionOffset &b) {
2688 return a.offset < b.offset;
2689 });
2690
2691 // Finding overlap is easy given a vector is sorted by start position.
2692 // If an element starts before the end of the previous element, they overlap.
2693 for (size_t i = 1, end = sections.size(); i < end; ++i) {
2694 SectionOffset a = sections[i - 1];
2695 SectionOffset b = sections[i];
2696 if (b.offset >= a.offset + a.sec->size)
2697 continue;
2698
2699 // If both sections are in OVERLAY we allow the overlapping of virtual
2700 // addresses, because it is what OVERLAY was designed for.
2701 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2702 continue;
2703
2704 Err(ctx) << "section " << a.sec->name << " " << name
2705 << " range overlaps with " << b.sec->name << "\n>>> "
2706 << a.sec->name << " range is "
2707 << rangeToString(addr: a.offset, len: a.sec->size) << "\n>>> " << b.sec->name
2708 << " range is " << rangeToString(addr: b.offset, len: b.sec->size);
2709 }
2710}
2711
2712// Check for overlapping sections and address overflows.
2713//
2714// In this function we check that none of the output sections have overlapping
2715// file offsets. For SHF_ALLOC sections we also check that the load address
2716// ranges and the virtual address ranges don't overlap
2717template <class ELFT> void Writer<ELFT>::checkSections() {
2718 // First, check that section's VAs fit in available address space for target.
2719 for (OutputSection *os : ctx.outputSections)
2720 if ((os->addr + os->size < os->addr) ||
2721 (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2722 Err(ctx) << "section " << os->name << " at 0x"
2723 << utohexstr(X: os->addr, LowerCase: true) << " of size 0x"
2724 << utohexstr(X: os->size, LowerCase: true)
2725 << " exceeds available address space";
2726
2727 // Check for overlapping file offsets. In this case we need to skip any
2728 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2729 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2730 // binary is specified only add SHF_ALLOC sections are added to the output
2731 // file so we skip any non-allocated sections in that case.
2732 std::vector<SectionOffset> fileOffs;
2733 for (OutputSection *sec : ctx.outputSections)
2734 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2735 (!ctx.arg.oFormatBinary || (sec->flags & SHF_ALLOC)))
2736 fileOffs.push_back(x: {.sec: sec, .offset: sec->offset});
2737 checkOverlap(ctx, name: "file", sections&: fileOffs, isVirtualAddr: false);
2738
2739 // When linking with -r there is no need to check for overlapping virtual/load
2740 // addresses since those addresses will only be assigned when the final
2741 // executable/shared object is created.
2742 if (ctx.arg.relocatable)
2743 return;
2744
2745 // Checking for overlapping virtual and load addresses only needs to take
2746 // into account SHF_ALLOC sections since others will not be loaded.
2747 // Furthermore, we also need to skip SHF_TLS sections since these will be
2748 // mapped to other addresses at runtime and can therefore have overlapping
2749 // ranges in the file.
2750 std::vector<SectionOffset> vmas;
2751 for (OutputSection *sec : ctx.outputSections)
2752 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2753 vmas.push_back(x: {.sec: sec, .offset: sec->addr});
2754 checkOverlap(ctx, name: "virtual address", sections&: vmas, isVirtualAddr: true);
2755
2756 // Finally, check that the load addresses don't overlap. This will
2757 // usually be the same as the virtual addresses but can be different
2758 // when using a linker script with AT(). SHT_NOBITS sections consume
2759 // no space in the file so their load address is normally unimportant.
2760 // Following GNU ld we permit the load address of a SHT_PROGBITS section
2761 // to overlap the load address of a SHT_NOBITS section. This is used
2762 // by embedded systems that copy the SHT_PROGBITS sections to a
2763 // non-overlapping VMA before the SHT_NOBITS section is zero-initialized.
2764 std::vector<SectionOffset> lmas;
2765 for (OutputSection *sec : ctx.outputSections)
2766 if (sec->size > 0 && (sec->type != SHT_NOBITS) &&
2767 (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2768 lmas.push_back(x: {.sec: sec, .offset: sec->getLMA()});
2769 checkOverlap(ctx, name: "load address", sections&: lmas, isVirtualAddr: false);
2770}
2771
2772// The entry point address is chosen in the following ways.
2773//
2774// 1. the '-e' entry command-line option;
2775// 2. the ENTRY(symbol) command in a linker control script;
2776// 3. the value of the symbol _start, if present;
2777// 4. the number represented by the entry symbol, if it is a number;
2778// 5. the address 0.
2779static uint64_t getEntryAddr(Ctx &ctx) {
2780 // Case 1, 2 or 3
2781 if (Symbol *b = ctx.symtab->find(name: ctx.arg.entry))
2782 return b->getVA(ctx);
2783
2784 // Case 4
2785 uint64_t addr;
2786 if (to_integer(S: ctx.arg.entry, Num&: addr))
2787 return addr;
2788
2789 // Case 5
2790 if (ctx.arg.warnMissingEntry)
2791 Warn(ctx) << "cannot find entry symbol " << ctx.arg.entry
2792 << "; not setting start address";
2793 return 0;
2794}
2795
2796static uint16_t getELFType(Ctx &ctx) {
2797 if (ctx.arg.isPic)
2798 return ET_DYN;
2799 if (ctx.arg.relocatable)
2800 return ET_REL;
2801 return ET_EXEC;
2802}
2803
2804template <class ELFT> void Writer<ELFT>::writeHeader() {
2805 writeEhdr<ELFT>(ctx, ctx.bufferStart);
2806 writePhdrs<ELFT>(ctx, ctx.bufferStart + sizeof(Elf_Ehdr));
2807
2808 auto *eHdr = reinterpret_cast<Elf_Ehdr *>(ctx.bufferStart);
2809 eHdr->e_type = getELFType(ctx);
2810 eHdr->e_entry = getEntryAddr(ctx);
2811
2812 // If -z nosectionheader is specified, omit the section header table.
2813 if (!ctx.in.shStrTab)
2814 return;
2815 eHdr->e_shoff = sectionHeaderOff;
2816
2817 // Write the section header table.
2818 //
2819 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2820 // and e_shstrndx fields. When the value of one of these fields exceeds
2821 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2822 // use fields in the section header at index 0 to store
2823 // the value. The sentinel values and fields are:
2824 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2825 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2826 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(ctx.bufferStart + eHdr->e_shoff);
2827 size_t num = ctx.outputSections.size() + 1;
2828 if (num >= SHN_LORESERVE)
2829 sHdrs->sh_size = num;
2830 else
2831 eHdr->e_shnum = num;
2832
2833 uint32_t strTabIndex = ctx.in.shStrTab->getParent()->sectionIndex;
2834 if (strTabIndex >= SHN_LORESERVE) {
2835 sHdrs->sh_link = strTabIndex;
2836 eHdr->e_shstrndx = SHN_XINDEX;
2837 } else {
2838 eHdr->e_shstrndx = strTabIndex;
2839 }
2840
2841 for (OutputSection *sec : ctx.outputSections)
2842 sec->writeHeaderTo<ELFT>(++sHdrs);
2843}
2844
2845// Open a result file.
2846template <class ELFT> void Writer<ELFT>::openFile() {
2847 uint64_t maxSize = ctx.arg.is64 ? INT64_MAX : UINT32_MAX;
2848 if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2849 std::string msg;
2850 raw_string_ostream s(msg);
2851 s << "output file too large: " << fileSize << " bytes\n"
2852 << "section sizes:\n";
2853 for (OutputSection *os : ctx.outputSections)
2854 s << os->name << ' ' << os->size << "\n";
2855 ErrAlways(ctx) << msg;
2856 return;
2857 }
2858
2859 unlinkAsync(path: ctx.arg.outputFile);
2860 unsigned flags = 0;
2861 if (!ctx.arg.relocatable)
2862 flags |= FileOutputBuffer::F_executable;
2863 if (ctx.arg.mmapOutputFile)
2864 flags |= FileOutputBuffer::F_mmap;
2865 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2866 FileOutputBuffer::create(FilePath: ctx.arg.outputFile, Size: fileSize, Flags: flags);
2867
2868 if (!bufferOrErr) {
2869 ErrAlways(ctx) << "failed to open " << ctx.arg.outputFile << ": "
2870 << bufferOrErr.takeError();
2871 return;
2872 }
2873 buffer = std::move(*bufferOrErr);
2874 ctx.bufferStart = buffer->getBufferStart();
2875}
2876
2877template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2878 parallel::TaskGroup tg;
2879 for (OutputSection *sec : ctx.outputSections)
2880 if (sec->flags & SHF_ALLOC)
2881 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2882}
2883
2884static void fillTrap(std::array<uint8_t, 4> trapInstr, uint8_t *i,
2885 uint8_t *end) {
2886 for (; i + 4 <= end; i += 4)
2887 memcpy(dest: i, src: trapInstr.data(), n: 4);
2888}
2889
2890// Fill executable segments with trap instructions. This includes both the
2891// gaps between sections (due to alignment) and the tail padding to the page
2892// boundary. Even though it is not required by any standard, it is in general
2893// a good thing to do for security reasons.
2894template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2895 // Fill gaps between consecutive sections in the same executable segment.
2896 OutputSection *prev = nullptr;
2897 for (OutputSection *sec : ctx.outputSections) {
2898 PhdrEntry *p = sec->ptLoad;
2899 if (!p || !(p->p_flags & PF_X))
2900 continue;
2901 if (prev && prev->ptLoad == p)
2902 fillTrap(trapInstr: ctx.target->trapInstr,
2903 i: ctx.bufferStart + alignDown(Value: prev->offset + prev->size, Align: 4),
2904 end: ctx.bufferStart + sec->offset);
2905 prev = sec;
2906 }
2907
2908 // Fill the last page.
2909 for (std::unique_ptr<PhdrEntry> &p : ctx.phdrs)
2910 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2911 fillTrap(
2912 trapInstr: ctx.target->trapInstr,
2913 i: ctx.bufferStart + alignDown(Value: p->firstSec->offset + p->p_filesz, Align: 4),
2914 end: ctx.bufferStart + alignToPowerOf2(Value: p->firstSec->offset + p->p_filesz,
2915 Align: ctx.arg.maxPageSize));
2916
2917 // Round up the file size of the last segment to the page boundary iff it is
2918 // an executable segment to ensure that other tools don't accidentally
2919 // trim the instruction padding (e.g. when stripping the file).
2920 PhdrEntry *last = nullptr;
2921 for (std::unique_ptr<PhdrEntry> &p : ctx.phdrs)
2922 if (p->p_type == PT_LOAD)
2923 last = p.get();
2924
2925 if (last && (last->p_flags & PF_X)) {
2926 last->p_filesz = alignToPowerOf2(Value: last->p_filesz, Align: ctx.arg.maxPageSize);
2927 // p_memsz might be larger than the aligned p_filesz due to trailing BSS
2928 // sections. Don't decrease it.
2929 last->p_memsz = std::max(a: last->p_memsz, b: last->p_filesz);
2930 }
2931}
2932
2933// Write section contents to a mmap'ed file.
2934template <class ELFT> void Writer<ELFT>::writeSections() {
2935 llvm::TimeTraceScope timeScope("Write sections");
2936
2937 {
2938 // In -r or --emit-relocs mode, write the relocation sections first as in
2939 // ELf_Rel targets we might find out that we need to modify the relocated
2940 // section while doing it.
2941 parallel::TaskGroup tg;
2942 for (OutputSection *sec : ctx.outputSections)
2943 if (isStaticRelSecType(type: sec->type))
2944 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2945 }
2946 {
2947 parallel::TaskGroup tg;
2948 for (OutputSection *sec : ctx.outputSections)
2949 if (!isStaticRelSecType(type: sec->type))
2950 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2951 }
2952
2953 // Finally, check that all dynamic relocation addends were written correctly.
2954 if (ctx.arg.checkDynamicRelocs && ctx.arg.writeAddends) {
2955 for (OutputSection *sec : ctx.outputSections)
2956 if (isStaticRelSecType(type: sec->type))
2957 sec->checkDynRelAddends(ctx);
2958 }
2959}
2960
2961// Computes a hash value of Data using a given hash function.
2962// In order to utilize multiple cores, we first split data into 1MB
2963// chunks, compute a hash for each chunk, and then compute a hash value
2964// of the hash values.
2965static void
2966computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2967 llvm::ArrayRef<uint8_t> data,
2968 std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2969 std::vector<ArrayRef<uint8_t>> chunks = split(arr: data, chunkSize: 1024 * 1024);
2970 const size_t hashesSize = chunks.size() * hashBuf.size();
2971 std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2972
2973 // Compute hash values.
2974 parallelFor(Begin: 0, End: chunks.size(), Fn: [&](size_t i) {
2975 hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2976 });
2977
2978 // Write to the final output buffer.
2979 hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
2980}
2981
2982template <class ELFT> void Writer<ELFT>::writeBuildId() {
2983 if (!ctx.in.buildId || !ctx.in.buildId->getParent())
2984 return;
2985
2986 if (ctx.arg.buildId == BuildIdKind::Hexstring) {
2987 ctx.in.buildId->writeBuildId(buf: ctx.arg.buildIdVector);
2988 return;
2989 }
2990
2991 // Compute a hash of all sections of the output file.
2992 size_t hashSize = ctx.in.buildId->hashSize;
2993 std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2994 MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2995 llvm::ArrayRef<uint8_t> input{ctx.bufferStart, size_t(fileSize)};
2996
2997 // Fedora introduced build ID as "approximation of true uniqueness across all
2998 // binaries that might be used by overlapping sets of people". It does not
2999 // need some security goals that some hash algorithms strive to provide, e.g.
3000 // (second-)preimage and collision resistance. In practice people use 'md5'
3001 // and 'sha1' just for different lengths. Implement them with the more
3002 // efficient BLAKE3.
3003 switch (ctx.arg.buildId) {
3004 case BuildIdKind::Fast:
3005 computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
3006 write64le(P: dest, V: xxh3_64bits(data: arr));
3007 });
3008 break;
3009 case BuildIdKind::Md5:
3010 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3011 memcpy(dest: dest, src: BLAKE3::hash<16>(Data: arr).data(), n: hashSize);
3012 });
3013 break;
3014 case BuildIdKind::Sha1:
3015 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3016 memcpy(dest: dest, src: BLAKE3::hash<20>(Data: arr).data(), n: hashSize);
3017 });
3018 break;
3019 case BuildIdKind::Uuid:
3020 if (auto ec = llvm::getRandomBytes(Buffer: buildId.get(), Size: hashSize))
3021 ErrAlways(ctx) << "entropy source failure: " << ec.message();
3022 break;
3023 default:
3024 llvm_unreachable("unknown BuildIdKind");
3025 }
3026 ctx.in.buildId->writeBuildId(buf: output);
3027}
3028
3029template void elf::writeResult<ELF32LE>(Ctx &);
3030template void elf::writeResult<ELF32BE>(Ctx &);
3031template void elf::writeResult<ELF64LE>(Ctx &);
3032template void elf::writeResult<ELF64BE>(Ctx &);
3033