1//===- LinkerScript.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// This file contains the parser/evaluator of the linker script.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LinkerScript.h"
14#include "Config.h"
15#include "InputFiles.h"
16#include "InputSection.h"
17#include "OutputSections.h"
18#include "SymbolTable.h"
19#include "Symbols.h"
20#include "SyntheticSections.h"
21#include "Target.h"
22#include "Writer.h"
23#include "lld/Common/CommonLinkerContext.h"
24#include "lld/Common/Strings.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/BinaryFormat/ELF.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/TimeProfiler.h"
31#include <algorithm>
32#include <cassert>
33#include <cstddef>
34#include <cstdint>
35#include <limits>
36#include <string>
37
38using namespace llvm;
39using namespace llvm::ELF;
40using namespace llvm::object;
41using namespace llvm::support::endian;
42using namespace lld;
43using namespace lld::elf;
44
45static bool isSectionPrefix(StringRef prefix, StringRef name) {
46 return name.consume_front(Prefix: prefix) && (name.empty() || name[0] == '.');
47}
48
49StringRef LinkerScript::getOutputSectionName(const InputSectionBase *s) const {
50 // This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we
51 // want to emit .rela.text.foo as .rela.text.bar for consistency (this is not
52 // technically required, but not doing it is odd). This code guarantees that.
53 if (LLVM_UNLIKELY(ctx.arg.copyRelocs)) {
54 InputSectionBase *rel = nullptr;
55 if (auto *isec = dyn_cast<InputSection>(Val: s))
56 rel = isec->getRelocatedSection();
57 if (rel) {
58 OutputSection *out = rel->getOutputSection();
59 if (!out) {
60 assert(ctx.arg.relocatable && (rel->flags & SHF_LINK_ORDER));
61 return s->name;
62 }
63 StringSaver &ss = ctx.saver;
64 if (s->type == SHT_CREL)
65 return ss.save(S: ".crel" + out->name);
66 if (s->type == SHT_RELA)
67 return ss.save(S: ".rela" + out->name);
68 return ss.save(S: ".rel" + out->name);
69 }
70 if (ctx.arg.relocatable)
71 return s->name;
72 }
73
74 // A BssSection created for a common symbol is identified as "COMMON" in
75 // linker scripts. It should go to .bss section.
76 if (s->name == "COMMON")
77 return ".bss";
78
79 if (hasSectionsCommand)
80 return s->name;
81
82 // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
83 // by grouping sections with certain prefixes.
84
85 // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
86 // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
87 // We provide an option -z keep-text-section-prefix to group such sections
88 // into separate output sections. This is more flexible. See also
89 // sortISDBySectionOrder().
90 // ".text.unknown" means the hotness of the section is unknown. When
91 // SampleFDO is used, if a function doesn't have sample, it could be very
92 // cold or it could be a new function never being sampled. Those functions
93 // will be kept in the ".text.unknown" section.
94 // ".text.split." holds symbols which are split out from functions in other
95 // input sections. For example, with -fsplit-machine-functions, placing the
96 // cold parts in .text.split instead of .text.unlikely mitigates against poor
97 // profile inaccuracy. Techniques such as hugepage remapping can make
98 // conservative decisions at the section granularity.
99 if (isSectionPrefix(prefix: ".text", name: s->name)) {
100 if (ctx.arg.zKeepTextSectionPrefix)
101 for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
102 ".text.startup", ".text.exit", ".text.split"})
103 if (isSectionPrefix(prefix: v.substr(Start: 5), name: s->name.substr(Start: 5)))
104 return v;
105 return ".text";
106 }
107 if (isSectionPrefix(prefix: ".ltext", name: s->name)) {
108 if (ctx.arg.zKeepTextSectionPrefix)
109 for (StringRef v : {".ltext.hot", ".ltext.unknown", ".ltext.unlikely",
110 ".ltext.startup", ".ltext.exit", ".ltext.split"})
111 if (isSectionPrefix(prefix: v.substr(Start: 6), name: s->name.substr(Start: 6)))
112 return v;
113 return ".ltext";
114 }
115
116 for (StringRef v : {".data.rel.ro", ".data", ".rodata",
117 ".bss.rel.ro", ".bss", ".ldata",
118 ".lrodata", ".lbss", ".gcc_except_table",
119 ".init_array", ".fini_array", ".tbss",
120 ".tdata", ".ARM.exidx", ".ARM.extab",
121 ".ctors", ".dtors", ".sbss",
122 ".sdata", ".srodata"})
123 if (isSectionPrefix(prefix: v, name: s->name))
124 return v;
125
126 return s->name;
127}
128
129uint64_t ExprValue::getValue() const {
130 if (sec)
131 return alignToPowerOf2(Value: sec->getOutputSection()->addr + sec->getOffset(offset: val),
132 Align: alignment);
133 return alignToPowerOf2(Value: val, Align: alignment);
134}
135
136uint64_t ExprValue::getSecAddr() const {
137 return sec ? sec->getOutputSection()->addr + sec->getOffset(offset: 0) : 0;
138}
139
140uint64_t ExprValue::getSectionOffset() const {
141 return getValue() - getSecAddr();
142}
143
144// std::unique_ptr<OutputSection> may be incomplete type.
145LinkerScript::LinkerScript(Ctx &ctx) : ctx(ctx) {}
146LinkerScript::~LinkerScript() {}
147
148OutputDesc *LinkerScript::createOutputSection(StringRef name,
149 StringRef location) {
150 OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
151 OutputDesc *sec;
152 if (secRef && secRef->osec.location.empty()) {
153 // There was a forward reference.
154 sec = secRef;
155 } else {
156 descPool.emplace_back(
157 Args: std::make_unique<OutputDesc>(args&: ctx, args&: name, args: SHT_PROGBITS, args: 0));
158 sec = descPool.back().get();
159 if (!secRef)
160 secRef = sec;
161 }
162 sec->osec.location = std::string(location);
163 return sec;
164}
165
166OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
167 auto &secRef = nameToOutputSection[CachedHashStringRef(name)];
168 if (!secRef) {
169 secRef = descPool
170 .emplace_back(
171 Args: std::make_unique<OutputDesc>(args&: ctx, args&: name, args: SHT_PROGBITS, args: 0))
172 .get();
173 }
174 return secRef;
175}
176
177// Expands the memory region by the specified size.
178static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
179 StringRef secName) {
180 memRegion->curPos += size;
181}
182
183void LinkerScript::expandMemoryRegions(uint64_t size) {
184 if (state->memRegion)
185 expandMemoryRegion(memRegion: state->memRegion, size, secName: state->outSec->name);
186 // Only expand the LMARegion if it is different from memRegion.
187 if (state->lmaRegion && state->memRegion != state->lmaRegion)
188 expandMemoryRegion(memRegion: state->lmaRegion, size, secName: state->outSec->name);
189}
190
191void LinkerScript::expandOutputSection(uint64_t size) {
192 state->outSec->size += size;
193 size_t regionSize = size;
194 if (state->outSec->inOverlay) {
195 // Expand the overlay if necessary, and expand the region by the
196 // corresponding amount.
197 if (state->outSec->size > state->overlaySize) {
198 regionSize = state->outSec->size - state->overlaySize;
199 state->overlaySize = state->outSec->size;
200 } else {
201 regionSize = 0;
202 }
203 }
204 expandMemoryRegions(size: regionSize);
205}
206
207void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
208 uint64_t val = e().getValue();
209 // If val is smaller and we are in an output section, record the error and
210 // report it if this is the last assignAddresses iteration. dot may be smaller
211 // if there is another assignAddresses iteration.
212 if (val < dot && inSec) {
213 recordError(msg: loc + ": unable to move location counter (0x" +
214 Twine::utohexstr(Val: dot) + ") backward to 0x" +
215 Twine::utohexstr(Val: val) + " for section '" + state->outSec->name +
216 "'");
217 }
218
219 // Update to location counter means update to section size.
220 if (inSec)
221 expandOutputSection(size: val - dot);
222
223 dot = val;
224}
225
226// Used for handling linker symbol assignments, for both finalizing
227// their values and doing early declarations. Returns true if symbol
228// should be defined from linker script.
229static bool shouldDefineSym(Ctx &ctx, SymbolAssignment *cmd) {
230 if (cmd->name == ".")
231 return false;
232
233 return !cmd->provide || ctx.script->shouldAddProvideSym(symName: cmd->name);
234}
235
236// Called by processSymbolAssignments() to assign definitions to
237// linker-script-defined symbols.
238void LinkerScript::addSymbol(SymbolAssignment *cmd) {
239 if (!shouldDefineSym(ctx, cmd))
240 return;
241
242 // Define a symbol.
243 ExprValue value = cmd->expression();
244 SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
245 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
246
247 // When this function is called, section addresses have not been
248 // fixed yet. So, we may or may not know the value of the RHS
249 // expression.
250 //
251 // For example, if an expression is `x = 42`, we know x is always 42.
252 // However, if an expression is `x = .`, there's no way to know its
253 // value at the moment.
254 //
255 // We want to set symbol values early if we can. This allows us to
256 // use symbols as variables in linker scripts. Doing so allows us to
257 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
258 uint64_t symValue = value.sec ? 0 : value.getValue();
259
260 Defined newSym(ctx, createInternalFile(ctx, name: cmd->location), cmd->name,
261 STB_GLOBAL, visibility, value.type, symValue, 0, sec);
262
263 Symbol *sym = ctx.symtab->insert(name: cmd->name);
264 sym->mergeProperties(other: newSym);
265 newSym.overwrite(sym&: *sym);
266 sym->isUsedInRegularObj = true;
267 cmd->sym = cast<Defined>(Val: sym);
268}
269
270// This function is called from LinkerScript::declareSymbols.
271// It creates a placeholder symbol if needed.
272void LinkerScript::declareSymbol(SymbolAssignment *cmd) {
273 if (!shouldDefineSym(ctx, cmd))
274 return;
275
276 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
277 Defined newSym(ctx, ctx.internalFile, cmd->name, STB_GLOBAL, visibility,
278 STT_NOTYPE, 0, 0, nullptr);
279
280 // If the symbol is already defined, its order is 0 (with absence indicating
281 // 0); otherwise it's assigned the order of the SymbolAssignment.
282 Symbol *sym = ctx.symtab->insert(name: cmd->name);
283 if (!sym->isDefined())
284 ctx.scriptSymOrder.insert(KV: {sym, cmd->symOrder});
285
286 // We can't calculate final value right now.
287 sym->mergeProperties(other: newSym);
288 newSym.overwrite(sym&: *sym);
289
290 cmd->sym = cast<Defined>(Val: sym);
291 cmd->provide = false;
292 sym->isUsedInRegularObj = true;
293 sym->scriptDefined = true;
294}
295
296using SymbolAssignmentMap =
297 DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
298
299// Collect section/value pairs of linker-script-defined symbols. This is used to
300// check whether symbol values converge.
301static SymbolAssignmentMap
302getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
303 SymbolAssignmentMap ret;
304 for (SectionCommand *cmd : sectionCommands) {
305 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd)) {
306 if (assign->sym) // sym is nullptr for dot.
307 ret.try_emplace(Key: assign->sym, Args: std::make_pair(x&: assign->sym->section,
308 y&: assign->sym->value));
309 continue;
310 }
311 if (isa<SectionClassDesc>(Val: cmd))
312 continue;
313 for (SectionCommand *subCmd : cast<OutputDesc>(Val: cmd)->osec.commands)
314 if (auto *assign = dyn_cast<SymbolAssignment>(Val: subCmd))
315 if (assign->sym)
316 ret.try_emplace(Key: assign->sym, Args: std::make_pair(x&: assign->sym->section,
317 y&: assign->sym->value));
318 }
319 return ret;
320}
321
322// Returns the lexicographical smallest (for determinism) Defined whose
323// section/value has changed.
324static const Defined *
325getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
326 const Defined *changed = nullptr;
327 for (auto &it : oldValues) {
328 const Defined *sym = it.first;
329 if (std::make_pair(x: sym->section, y: sym->value) != it.second &&
330 (!changed || sym->getName() < changed->getName()))
331 changed = sym;
332 }
333 return changed;
334}
335
336// Process INSERT [AFTER|BEFORE] commands. For each command, we move the
337// specified output section to the designated place.
338void LinkerScript::processInsertCommands() {
339 SmallVector<OutputDesc *, 0> moves;
340 for (const InsertCommand &cmd : insertCommands) {
341 if (ctx.arg.enableNonContiguousRegions)
342 ErrAlways(ctx)
343 << "INSERT cannot be used with --enable-non-contiguous-regions";
344
345 for (StringRef name : cmd.names) {
346 // If base is empty, it may have been discarded by
347 // adjustOutputSections(). We do not handle such output sections.
348 auto from = llvm::find_if(Range&: sectionCommands, P: [&](SectionCommand *subCmd) {
349 return isa<OutputDesc>(Val: subCmd) &&
350 cast<OutputDesc>(Val: subCmd)->osec.name == name;
351 });
352 if (from == sectionCommands.end())
353 continue;
354 moves.push_back(Elt: cast<OutputDesc>(Val: *from));
355 sectionCommands.erase(CI: from);
356 }
357
358 auto insertPos =
359 llvm::find_if(Range&: sectionCommands, P: [&cmd](SectionCommand *subCmd) {
360 auto *to = dyn_cast<OutputDesc>(Val: subCmd);
361 return to != nullptr && to->osec.name == cmd.where;
362 });
363 if (insertPos == sectionCommands.end()) {
364 ErrAlways(ctx) << "unable to insert " << cmd.names[0]
365 << (cmd.isAfter ? " after " : " before ") << cmd.where;
366 } else {
367 if (cmd.isAfter)
368 ++insertPos;
369 sectionCommands.insert(I: insertPos, From: moves.begin(), To: moves.end());
370 }
371 moves.clear();
372 }
373}
374
375// Symbols defined in script should not be inlined by LTO. At the same time
376// we don't know their final values until late stages of link. Here we scan
377// over symbol assignment commands and create placeholder symbols if needed.
378void LinkerScript::declareSymbols() {
379 assert(!state);
380 for (SectionCommand *cmd : sectionCommands) {
381 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd)) {
382 declareSymbol(cmd: assign);
383 continue;
384 }
385 if (isa<SectionClassDesc>(Val: cmd))
386 continue;
387
388 // If the output section directive has constraints,
389 // we can't say for sure if it is going to be included or not.
390 // Skip such sections for now. Improve the checks if we ever
391 // need symbols from that sections to be declared early.
392 const OutputSection &sec = cast<OutputDesc>(Val: cmd)->osec;
393 if (sec.constraint != ConstraintKind::NoConstraint)
394 continue;
395 for (SectionCommand *cmd : sec.commands)
396 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd))
397 declareSymbol(cmd: assign);
398 }
399}
400
401// This function is called from assignAddresses, while we are
402// fixing the output section addresses. This function is supposed
403// to set the final value for a given symbol assignment.
404void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
405 if (cmd->name == ".") {
406 setDot(e: cmd->expression, loc: cmd->location, inSec);
407 return;
408 }
409
410 if (!cmd->sym)
411 return;
412
413 ExprValue v = cmd->expression();
414 if (v.isAbsolute()) {
415 cmd->sym->section = nullptr;
416 cmd->sym->value = v.getValue();
417 } else {
418 cmd->sym->section = v.sec;
419 cmd->sym->value = v.getSectionOffset();
420 }
421 cmd->sym->type = v.type;
422}
423
424bool InputSectionDescription::matchesFile(const InputFile &file) const {
425 if (filePat.isTrivialMatchAll())
426 return true;
427
428 if (!matchesFileCache || matchesFileCache->first != &file) {
429 if (matchType == MatchType::WholeArchive) {
430 matchesFileCache.emplace(args: &file, args: filePat.match(s: file.archiveName));
431 } else {
432 if (matchType == MatchType::ArchivesExcluded && !file.archiveName.empty())
433 matchesFileCache.emplace(args: &file, args: false);
434 else
435 matchesFileCache.emplace(args: &file, args: filePat.match(s: file.getNameForScript()));
436 }
437 }
438
439 return matchesFileCache->second;
440}
441
442bool SectionPattern::excludesFile(const InputFile &file) const {
443 if (excludedFilePat.empty())
444 return false;
445
446 if (!excludesFileCache || excludesFileCache->first != &file)
447 excludesFileCache.emplace(args: &file,
448 args: excludedFilePat.match(s: file.getNameForScript()));
449
450 return excludesFileCache->second;
451}
452
453bool LinkerScript::shouldKeep(InputSectionBase *s) {
454 for (InputSectionDescription *id : keptSections)
455 if (id->matchesFile(file: *s->file))
456 for (SectionPattern &p : id->sectionPatterns)
457 if (p.sectionPat.match(s: s->name) &&
458 (s->flags & id->withFlags) == id->withFlags &&
459 (s->flags & id->withoutFlags) == 0)
460 return true;
461 return false;
462}
463
464// A helper function for the SORT() command.
465static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
466 ConstraintKind kind) {
467 if (kind == ConstraintKind::NoConstraint)
468 return true;
469
470 bool isRW = llvm::any_of(
471 Range&: sections, P: [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
472
473 return (isRW && kind == ConstraintKind::ReadWrite) ||
474 (!isRW && kind == ConstraintKind::ReadOnly);
475}
476
477static void sortSections(MutableArrayRef<InputSectionBase *> vec,
478 SortSectionPolicy k) {
479 auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
480 // ">" is not a mistake. Sections with larger alignments are placed
481 // before sections with smaller alignments in order to reduce the
482 // amount of padding necessary. This is compatible with GNU.
483 return a->addralign > b->addralign;
484 };
485 auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
486 return a->name < b->name;
487 };
488 auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
489 return getPriority(s: a->name) < getPriority(s: b->name);
490 };
491
492 switch (k) {
493 case SortSectionPolicy::Default:
494 case SortSectionPolicy::None:
495 return;
496 case SortSectionPolicy::Alignment:
497 return llvm::stable_sort(Range&: vec, C: alignmentComparator);
498 case SortSectionPolicy::Name:
499 return llvm::stable_sort(Range&: vec, C: nameComparator);
500 case SortSectionPolicy::Priority:
501 return llvm::stable_sort(Range&: vec, C: priorityComparator);
502 case SortSectionPolicy::Reverse:
503 return std::reverse(first: vec.begin(), last: vec.end());
504 }
505}
506
507// Sort sections as instructed by SORT-family commands and --sort-section
508// option. Because SORT-family commands can be nested at most two depth
509// (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
510// line option is respected even if a SORT command is given, the exact
511// behavior we have here is a bit complicated. Here are the rules.
512//
513// 1. If two SORT commands are given, --sort-section is ignored.
514// 2. If one SORT command is given, and if it is not SORT_NONE,
515// --sort-section is handled as an inner SORT command.
516// 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
517// 4. If no SORT command is given, sort according to --sort-section.
518static void sortInputSections(Ctx &ctx, MutableArrayRef<InputSectionBase *> vec,
519 SortSectionPolicy outer,
520 SortSectionPolicy inner) {
521 if (outer == SortSectionPolicy::None)
522 return;
523
524 if (inner == SortSectionPolicy::Default)
525 sortSections(vec, k: ctx.arg.sortSection);
526 else
527 sortSections(vec, k: inner);
528 sortSections(vec, k: outer);
529}
530
531// Compute and remember which sections the InputSectionDescription matches.
532SmallVector<InputSectionBase *, 0>
533LinkerScript::computeInputSections(const InputSectionDescription *cmd,
534 ArrayRef<InputSectionBase *> sections,
535 const SectionBase &outCmd) {
536 SmallVector<InputSectionBase *, 0> ret;
537 DenseSet<InputSectionBase *> spills;
538
539 // Returns whether an input section's flags match the input section
540 // description's specifiers.
541 auto flagsMatch = [cmd](InputSectionBase *sec) {
542 return (sec->flags & cmd->withFlags) == cmd->withFlags &&
543 (sec->flags & cmd->withoutFlags) == 0;
544 };
545
546 // Collects all sections that satisfy constraints of Cmd.
547 if (cmd->classRef.empty()) {
548 DenseSet<size_t> seen;
549 size_t sizeAfterPrevSort = 0;
550 SmallVector<size_t, 0> indexes;
551 auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
552 llvm::sort(C: MutableArrayRef<size_t>(indexes).slice(N: begin, M: end - begin));
553 for (size_t i = begin; i != end; ++i)
554 ret[i] = sections[indexes[i]];
555 sortInputSections(
556 ctx,
557 vec: MutableArrayRef<InputSectionBase *>(ret).slice(N: begin, M: end - begin),
558 outer: ctx.arg.sortSection, inner: SortSectionPolicy::None);
559 };
560
561 bool enableNonContiguousRegions = ctx.arg.enableNonContiguousRegions;
562 for (const SectionPattern &pat : cmd->sectionPatterns) {
563 size_t sizeBeforeCurrPat = ret.size();
564
565 for (size_t i = 0, e = sections.size(); i != e; ++i) {
566 // Skip if the section is dead, has been matched by a previous input
567 // section description with non-contiguous regions disabled, or has been
568 // matched by a previous pattern in this input section description.
569 InputSectionBase *sec = sections[i];
570 if (!sec->isLive() || (!enableNonContiguousRegions && sec->parent) ||
571 seen.contains(V: i))
572 continue;
573
574 // For --emit-relocs we have to ignore entries like
575 // .rela.dyn : { *(.rela.data) }
576 // which are common because they are in the default bfd script.
577 // We do not ignore SHT_REL[A] linker-synthesized sections here because
578 // want to support scripts that do custom layout for them.
579 if (isa<InputSection>(Val: sec) &&
580 cast<InputSection>(Val: sec)->getRelocatedSection())
581 continue;
582
583 // Check the name early to improve performance in the common case.
584 if (!pat.sectionPat.match(s: sec->name))
585 continue;
586
587 if (!cmd->matchesFile(file: *sec->file) || pat.excludesFile(file: *sec->file) ||
588 !flagsMatch(sec))
589 continue;
590
591 if (sec->parent) {
592 assert(ctx.arg.enableNonContiguousRegions);
593
594 // Disallow spilling into /DISCARD/; special handling would be needed
595 // for this in address assignment, and the semantics are nebulous.
596 if (outCmd.name == "/DISCARD/")
597 continue;
598
599 // Class definitions cannot contain spills, nor can a class definition
600 // generate a spill in a subsequent match. Those behaviors belong to
601 // class references and additional matches.
602 if (!isa<SectionClass>(Val: outCmd) && !isa<SectionClass>(Val: sec->parent))
603 spills.insert(V: sec);
604 }
605
606 ret.push_back(Elt: sec);
607 indexes.push_back(Elt: i);
608 seen.insert(V: i);
609 }
610
611 if (pat.sortOuter == SortSectionPolicy::Default)
612 continue;
613
614 // Matched sections are ordered by radix sort with the keys being (SORT*,
615 // --sort-section, input order), where SORT* (if present) is most
616 // significant.
617 //
618 // Matched sections between the previous SORT* and this SORT* are sorted
619 // by (--sort-alignment, input order).
620 sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
621 // Matched sections by this SORT* pattern are sorted using all 3 keys.
622 // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
623 // just sort by sortOuter and sortInner.
624 sortInputSections(
625 ctx,
626 vec: MutableArrayRef<InputSectionBase *>(ret).slice(N: sizeBeforeCurrPat),
627 outer: pat.sortOuter, inner: pat.sortInner);
628 sizeAfterPrevSort = ret.size();
629 }
630
631 // Matched sections after the last SORT* are sorted by (--sort-alignment,
632 // input order).
633 sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
634 } else {
635 SectionClassDesc *scd =
636 sectionClasses.lookup(Val: CachedHashStringRef(cmd->classRef));
637 if (!scd) {
638 Err(ctx) << "undefined section class '" << cmd->classRef << "'";
639 return ret;
640 }
641 if (!scd->sc.assigned) {
642 Err(ctx) << "section class '" << cmd->classRef << "' referenced by '"
643 << outCmd.name << "' before class definition";
644 return ret;
645 }
646
647 for (InputSectionDescription *isd : scd->sc.commands) {
648 for (InputSectionBase *sec : isd->sectionBases) {
649 if (!flagsMatch(sec))
650 continue;
651 bool isSpill = sec->parent && isa<OutputSection>(Val: sec->parent);
652 if (!sec->parent || (isSpill && outCmd.name == "/DISCARD/")) {
653 Err(ctx) << "section '" << sec->name
654 << "' cannot spill from/to /DISCARD/";
655 continue;
656 }
657 if (isSpill)
658 spills.insert(V: sec);
659 ret.push_back(Elt: sec);
660 }
661 }
662 }
663
664 // The flag --enable-non-contiguous-regions or the section CLASS syntax may
665 // cause sections to match an InputSectionDescription in more than one
666 // OutputSection. Matches after the first were collected in the spills set, so
667 // replace these with potential spill sections.
668 if (!spills.empty()) {
669 for (InputSectionBase *&sec : ret) {
670 if (!spills.contains(V: sec))
671 continue;
672
673 // Append the spill input section to the list for the input section,
674 // creating it if necessary.
675 PotentialSpillSection *pss = make<PotentialSpillSection>(
676 args&: *sec, args&: const_cast<InputSectionDescription &>(*cmd));
677 auto [it, inserted] =
678 potentialSpillLists.try_emplace(Key: sec, Args: PotentialSpillList{.head: pss, .tail: pss});
679 if (!inserted) {
680 PotentialSpillSection *&tail = it->second.tail;
681 tail = tail->next = pss;
682 }
683 sec = pss;
684 }
685 }
686
687 return ret;
688}
689
690void LinkerScript::discard(InputSectionBase &s) {
691 if (&s == ctx.in.shStrTab.get())
692 ErrAlways(ctx) << "discarding " << s.name << " section is not allowed";
693
694 s.markDead();
695 s.parent = nullptr;
696 for (InputSection *sec : s.dependentSections)
697 discard(s&: *sec);
698}
699
700void LinkerScript::discardSynthetic(OutputSection &outCmd) {
701 ARMExidxSyntheticSection *armExidx = ctx.in.armExidx.get();
702 if (!armExidx || !armExidx->isLive())
703 return;
704 SmallVector<InputSectionBase *, 0> secs(armExidx->exidxSections.begin(),
705 armExidx->exidxSections.end());
706 for (SectionCommand *cmd : outCmd.commands)
707 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd))
708 for (InputSectionBase *s : computeInputSections(cmd: isd, sections: secs, outCmd))
709 discard(s&: *s);
710}
711
712SmallVector<InputSectionBase *, 0>
713LinkerScript::createInputSectionList(OutputSection &outCmd) {
714 SmallVector<InputSectionBase *, 0> ret;
715
716 for (SectionCommand *cmd : outCmd.commands) {
717 if (auto *isd = dyn_cast<InputSectionDescription>(Val: cmd)) {
718 isd->sectionBases = computeInputSections(cmd: isd, sections: ctx.inputSections, outCmd);
719 for (InputSectionBase *s : isd->sectionBases)
720 s->parent = &outCmd;
721 ret.insert(I: ret.end(), From: isd->sectionBases.begin(), To: isd->sectionBases.end());
722 }
723 }
724 return ret;
725}
726
727// Create output sections described by SECTIONS commands.
728void LinkerScript::processSectionCommands() {
729 auto process = [this](OutputSection *osec) {
730 SmallVector<InputSectionBase *, 0> v = createInputSectionList(outCmd&: *osec);
731
732 // The output section name `/DISCARD/' is special.
733 // Any input section assigned to it is discarded.
734 if (osec->name == "/DISCARD/") {
735 for (InputSectionBase *s : v)
736 discard(s&: *s);
737 discardSynthetic(outCmd&: *osec);
738 osec->commands.clear();
739 return false;
740 }
741
742 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
743 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
744 // sections satisfy a given constraint. If not, a directive is handled
745 // as if it wasn't present from the beginning.
746 //
747 // Because we'll iterate over SectionCommands many more times, the easy
748 // way to "make it as if it wasn't present" is to make it empty.
749 if (!matchConstraints(sections: v, kind: osec->constraint)) {
750 for (InputSectionBase *s : v)
751 s->parent = nullptr;
752 osec->commands.clear();
753 return false;
754 }
755
756 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
757 // is given, input sections are aligned to that value, whether the
758 // given value is larger or smaller than the original section alignment.
759 if (osec->subalignExpr) {
760 uint32_t subalign = osec->subalignExpr().getValue();
761 for (InputSectionBase *s : v)
762 s->addralign = subalign;
763 }
764
765 // Mark the output section live, like OutputSection::recordSection().
766 osec->partition = 1;
767 return true;
768 };
769
770 // Process OVERWRITE_SECTIONS first so that it can overwrite the main script
771 // or orphans.
772 if (ctx.arg.enableNonContiguousRegions && !overwriteSections.empty())
773 ErrAlways(ctx) << "OVERWRITE_SECTIONS cannot be used with "
774 "--enable-non-contiguous-regions";
775 DenseMap<CachedHashStringRef, OutputDesc *> map;
776 size_t i = 0;
777 for (OutputDesc *osd : overwriteSections) {
778 OutputSection *osec = &osd->osec;
779 if (process(osec) &&
780 !map.try_emplace(Key: CachedHashStringRef(osec->name), Args&: osd).second)
781 Warn(ctx) << "OVERWRITE_SECTIONS specifies duplicate " << osec->name;
782 }
783 for (SectionCommand *&base : sectionCommands) {
784 if (auto *osd = dyn_cast<OutputDesc>(Val: base)) {
785 OutputSection *osec = &osd->osec;
786 if (OutputDesc *overwrite = map.lookup(Val: CachedHashStringRef(osec->name))) {
787 Log(ctx) << overwrite->osec.location << " overwrites " << osec->name;
788 overwrite->osec.sectionIndex = i++;
789 base = overwrite;
790 } else if (process(osec)) {
791 osec->sectionIndex = i++;
792 }
793 } else if (auto *sc = dyn_cast<SectionClassDesc>(Val: base)) {
794 for (InputSectionDescription *isd : sc->sc.commands) {
795 isd->sectionBases =
796 computeInputSections(cmd: isd, sections: ctx.inputSections, outCmd: sc->sc);
797 for (InputSectionBase *s : isd->sectionBases) {
798 // A section class containing a section with different parent isn't
799 // necessarily an error due to --enable-non-contiguous-regions. Such
800 // sections all become potential spills when the class is referenced.
801 if (!s->parent)
802 s->parent = &sc->sc;
803 }
804 }
805 sc->sc.assigned = true;
806 }
807 }
808
809 // Check that input sections cannot spill into or out of INSERT,
810 // since the semantics are nebulous. This is also true for OVERWRITE_SECTIONS,
811 // but no check is needed, since the order of processing ensures they cannot
812 // legally reference classes.
813 if (!potentialSpillLists.empty()) {
814 DenseSet<StringRef> insertNames;
815 for (InsertCommand &ic : insertCommands)
816 insertNames.insert_range(R&: ic.names);
817 for (SectionCommand *&base : sectionCommands) {
818 auto *osd = dyn_cast<OutputDesc>(Val: base);
819 if (!osd)
820 continue;
821 OutputSection *os = &osd->osec;
822 if (!insertNames.contains(V: os->name))
823 continue;
824 for (SectionCommand *sc : os->commands) {
825 auto *isd = dyn_cast<InputSectionDescription>(Val: sc);
826 if (!isd)
827 continue;
828 for (InputSectionBase *isec : isd->sectionBases)
829 if (isa<PotentialSpillSection>(Val: isec) ||
830 potentialSpillLists.contains(Val: isec))
831 Err(ctx) << "section '" << isec->name
832 << "' cannot spill from/to INSERT section '" << os->name
833 << "'";
834 }
835 }
836 }
837
838 // If an OVERWRITE_SECTIONS specified output section is not in
839 // sectionCommands, append it to the end. The section will be inserted by
840 // orphan placement.
841 for (OutputDesc *osd : overwriteSections)
842 if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
843 sectionCommands.push_back(Elt: osd);
844
845 // Input sections cannot have a section class parent past this point; they
846 // must have been assigned to an output section.
847 for (const auto &[_, sc] : sectionClasses) {
848 for (InputSectionDescription *isd : sc->sc.commands) {
849 for (InputSectionBase *sec : isd->sectionBases) {
850 if (sec->parent && isa<SectionClass>(Val: sec->parent)) {
851 Err(ctx) << "section class '" << sec->parent->name
852 << "' is unreferenced";
853 goto nextClass;
854 }
855 }
856 }
857 nextClass:;
858 }
859}
860
861void LinkerScript::processSymbolAssignments() {
862 // Dot outside an output section still represents a relative address, whose
863 // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
864 // that fills the void outside a section. It has an index of one, which is
865 // indistinguishable from any other regular section index.
866 aether = std::make_unique<OutputSection>(args&: ctx, args: "", args: 0, args: SHF_ALLOC);
867 aether->sectionIndex = 1;
868
869 // `st` captures the local AddressState and makes it accessible deliberately.
870 // This is needed as there are some cases where we cannot just thread the
871 // current state through to a lambda function created by the script parser.
872 AddressState st(*this);
873 state = &st;
874 st.outSec = aether.get();
875
876 for (SectionCommand *cmd : sectionCommands) {
877 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd))
878 addSymbol(cmd: assign);
879 else if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
880 for (SectionCommand *subCmd : osd->osec.commands)
881 if (auto *assign = dyn_cast<SymbolAssignment>(Val: subCmd))
882 addSymbol(cmd: assign);
883 }
884
885 state = nullptr;
886}
887
888static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
889 StringRef name) {
890 for (SectionCommand *cmd : vec)
891 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
892 if (osd->osec.name == name)
893 return &osd->osec;
894 return nullptr;
895}
896
897static OutputDesc *createSection(Ctx &ctx, InputSectionBase *isec,
898 StringRef outsecName) {
899 OutputDesc *osd = ctx.script->createOutputSection(name: outsecName, location: "<internal>");
900 osd->osec.recordSection(isec);
901 return osd;
902}
903
904static OutputDesc *addInputSec(Ctx &ctx,
905 StringMap<TinyPtrVector<OutputSection *>> &map,
906 InputSectionBase *isec, StringRef outsecName) {
907 // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
908 // option is given. A section with SHT_GROUP defines a "section group", and
909 // its members have SHF_GROUP attribute. Usually these flags have already been
910 // stripped by InputFiles.cpp as section groups are processed and uniquified.
911 // However, for the -r option, we want to pass through all section groups
912 // as-is because adding/removing members or merging them with other groups
913 // change their semantics.
914 if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
915 return createSection(ctx, isec, outsecName);
916
917 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
918 // relocation sections .rela.foo and .rela.bar for example. Most tools do
919 // not allow multiple REL[A] sections for output section. Hence we
920 // should combine these relocation sections into single output.
921 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
922 // other REL[A] sections created by linker itself.
923 if (!isa<SyntheticSection>(Val: isec) && isStaticRelSecType(type: isec->type)) {
924 auto *sec = cast<InputSection>(Val: isec);
925 OutputSection *out = sec->getRelocatedSection()->getOutputSection();
926
927 if (auto *relSec = out->relocationSection) {
928 relSec->recordSection(isec: sec);
929 return nullptr;
930 }
931
932 OutputDesc *osd = createSection(ctx, isec, outsecName);
933 out->relocationSection = &osd->osec;
934 return osd;
935 }
936
937 // The ELF spec just says
938 // ----------------------------------------------------------------
939 // In the first phase, input sections that match in name, type and
940 // attribute flags should be concatenated into single sections.
941 // ----------------------------------------------------------------
942 //
943 // However, it is clear that at least some flags have to be ignored for
944 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
945 // ignored. We should not have two output .text sections just because one was
946 // in a group and another was not for example.
947 //
948 // It also seems that wording was a late addition and didn't get the
949 // necessary scrutiny.
950 //
951 // Merging sections with different flags is expected by some users. One
952 // reason is that if one file has
953 //
954 // int *const bar __attribute__((section(".foo"))) = (int *)0;
955 //
956 // gcc with -fPIC will produce a read only .foo section. But if another
957 // file has
958 //
959 // int zed;
960 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
961 //
962 // gcc with -fPIC will produce a read write section.
963 //
964 // Last but not least, when using linker script the merge rules are forced by
965 // the script. Unfortunately, linker scripts are name based. This means that
966 // expressions like *(.foo*) can refer to multiple input sections with
967 // different flags. We cannot put them in different output sections or we
968 // would produce wrong results for
969 //
970 // start = .; *(.foo.*) end = .; *(.bar)
971 //
972 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
973 // another. The problem is that there is no way to layout those output
974 // sections such that the .foo sections are the only thing between the start
975 // and end symbols.
976 //
977 // Given the above issues, we instead merge sections by name and error on
978 // incompatible types and flags.
979 TinyPtrVector<OutputSection *> &v = map[outsecName];
980 for (OutputSection *sec : v) {
981 if (sec->partition != isec->partition)
982 continue;
983
984 if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER)) {
985 // Merging two SHF_LINK_ORDER sections with different sh_link fields will
986 // change their semantics, so we only merge them in -r links if they will
987 // end up being linked to the same output section. The casts are fine
988 // because everything in the map was created by the orphan placement code.
989 auto *firstIsec = cast<InputSectionBase>(
990 Val: cast<InputSectionDescription>(Val: sec->commands[0])->sectionBases[0]);
991 OutputSection *firstIsecOut =
992 (firstIsec->flags & SHF_LINK_ORDER)
993 ? firstIsec->getLinkOrderDep()->getOutputSection()
994 : nullptr;
995 if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
996 continue;
997 }
998
999 sec->recordSection(isec);
1000 return nullptr;
1001 }
1002
1003 OutputDesc *osd = createSection(ctx, isec, outsecName);
1004 v.push_back(NewVal: &osd->osec);
1005 return osd;
1006}
1007
1008// Add sections that didn't match any sections command.
1009void LinkerScript::addOrphanSections() {
1010 StringMap<TinyPtrVector<OutputSection *>> map;
1011 SmallVector<OutputDesc *, 0> v;
1012
1013 auto add = [&](InputSectionBase *s) {
1014 if (s->isLive() && !s->parent) {
1015 orphanSections.push_back(Elt: s);
1016
1017 StringRef name = getOutputSectionName(s);
1018 if (ctx.arg.unique) {
1019 v.push_back(Elt: createSection(ctx, isec: s, outsecName: name));
1020 } else if (OutputSection *sec = findByName(vec: sectionCommands, name)) {
1021 sec->recordSection(isec: s);
1022 } else {
1023 if (OutputDesc *osd = addInputSec(ctx, map, isec: s, outsecName: name))
1024 v.push_back(Elt: osd);
1025 assert(isa<MergeInputSection>(s) ||
1026 s->getOutputSection()->sectionIndex == UINT32_MAX);
1027 }
1028 }
1029 };
1030
1031 const bool copyRelocs = ctx.arg.copyRelocs;
1032 const bool relocatable = ctx.arg.relocatable;
1033 size_t n = 0;
1034 for (InputSectionBase *isec : ctx.inputSections) {
1035 // Process InputSection and MergeInputSection.
1036 if (LLVM_LIKELY(isa<InputSection>(isec)))
1037 ctx.inputSections[n++] = isec;
1038
1039 if (LLVM_UNLIKELY(copyRelocs)) {
1040 // In -r links, SHF_LINK_ORDER sections are added while adding their
1041 // parent sections because we need to know the parent's output section
1042 // before we can select an output section for the SHF_LINK_ORDER section.
1043 if (relocatable && (isec->flags & SHF_LINK_ORDER))
1044 continue;
1045
1046 if (auto *sec = dyn_cast<InputSection>(Val: isec))
1047 if (InputSectionBase *relocated = sec->getRelocatedSection()) {
1048 // For --emit-relocs and -r, ensure the output section for .text.foo
1049 // is created before the output section for .rela.text.foo.
1050 add(relocated);
1051 // EhInputSection sections are not added to ctx.inputSections. If we
1052 // see .rela.eh_frame, ensure the output section for the synthetic
1053 // EhFrameSection is created first.
1054 if (auto *p = dyn_cast_or_null<InputSectionBase>(Val: relocated->parent))
1055 add(p);
1056 }
1057 }
1058
1059 add(isec);
1060 if (LLVM_UNLIKELY(relocatable))
1061 for (InputSectionBase *depSec : isec->dependentSections)
1062 if (depSec->flags & SHF_LINK_ORDER)
1063 add(depSec);
1064 }
1065 // Keep just InputSection.
1066 ctx.inputSections.resize(N: n);
1067
1068 // If no SECTIONS command was given, we should insert sections commands
1069 // before others, so that we can handle scripts which refers them,
1070 // for example: "foo = ABSOLUTE(ADDR(.text)));".
1071 // When SECTIONS command is present we just add all orphans to the end.
1072 if (hasSectionsCommand)
1073 sectionCommands.insert(I: sectionCommands.end(), From: v.begin(), To: v.end());
1074 else
1075 sectionCommands.insert(I: sectionCommands.begin(), From: v.begin(), To: v.end());
1076}
1077
1078void LinkerScript::diagnoseOrphanHandling() const {
1079 llvm::TimeTraceScope timeScope("Diagnose orphan sections");
1080 if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Place ||
1081 !hasSectionsCommand)
1082 return;
1083 for (const InputSectionBase *sec : orphanSections) {
1084 // .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,
1085 // automatically. The section is not supposed to be specified by scripts.
1086 if (sec == ctx.in.relroPadding.get())
1087 continue;
1088 // Input SHT_REL[A] retained by --emit-relocs are ignored by
1089 // computeInputSections(). Don't warn/error.
1090 if (isa<InputSection>(Val: sec) &&
1091 cast<InputSection>(Val: sec)->getRelocatedSection())
1092 continue;
1093
1094 StringRef name = getOutputSectionName(s: sec);
1095 if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Error)
1096 ErrAlways(ctx) << sec << " is being placed in '" << name << "'";
1097 else
1098 Warn(ctx) << sec << " is being placed in '" << name << "'";
1099 }
1100}
1101
1102void LinkerScript::diagnoseMissingSGSectionAddress() const {
1103 if (!ctx.arg.cmseImplib || !ctx.in.armCmseSGSection->isNeeded())
1104 return;
1105
1106 OutputSection *sec = findByName(vec: sectionCommands, name: ".gnu.sgstubs");
1107 if (sec && !sec->addrExpr &&
1108 !ctx.arg.sectionStartMap.contains(Key: ".gnu.sgstubs"))
1109 ErrAlways(ctx) << "no address assigned to the veneers output section "
1110 << sec->name;
1111}
1112
1113// This function searches for a memory region to place the given output
1114// section in. If found, a pointer to the appropriate memory region is
1115// returned in the first member of the pair. Otherwise, a nullptr is returned.
1116// The second member of the pair is a hint that should be passed to the
1117// subsequent call of this method.
1118std::pair<MemoryRegion *, MemoryRegion *>
1119LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
1120 // Non-allocatable sections are not part of the process image.
1121 if (!(sec->flags & SHF_ALLOC)) {
1122 bool hasInputOrByteCommand =
1123 sec->hasInputSections ||
1124 llvm::any_of(Range&: sec->commands, P: [](SectionCommand *comm) {
1125 return ByteCommand::classof(c: comm);
1126 });
1127 if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)
1128 Warn(ctx)
1129 << "ignoring memory region assignment for non-allocatable section '"
1130 << sec->name << "'";
1131 return {nullptr, nullptr};
1132 }
1133
1134 // If a memory region name was specified in the output section command,
1135 // then try to find that region first.
1136 if (!sec->memoryRegionName.empty()) {
1137 if (MemoryRegion *m = memoryRegions.lookup(Key: sec->memoryRegionName))
1138 return {m, m};
1139 ErrAlways(ctx) << "memory region '" << sec->memoryRegionName
1140 << "' not declared";
1141 return {nullptr, nullptr};
1142 }
1143
1144 // If at least one memory region is defined, all sections must
1145 // belong to some memory region. Otherwise, we don't need to do
1146 // anything for memory regions.
1147 if (memoryRegions.empty())
1148 return {nullptr, nullptr};
1149
1150 // An orphan section should continue the previous memory region.
1151 if (sec->sectionIndex == UINT32_MAX && hint)
1152 return {hint, hint};
1153
1154 // See if a region can be found by matching section flags.
1155 for (auto &pair : memoryRegions) {
1156 MemoryRegion *m = pair.second;
1157 if (m->compatibleWith(secFlags: sec->flags))
1158 return {m, nullptr};
1159 }
1160
1161 // Otherwise, no suitable region was found.
1162 ErrAlways(ctx) << "no memory region specified for section '" << sec->name
1163 << "'";
1164 return {nullptr, nullptr};
1165}
1166
1167static OutputSection *findFirstSection(Ctx &ctx, PhdrEntry *load) {
1168 for (OutputSection *sec : ctx.outputSections)
1169 if (sec->ptLoad == load)
1170 return sec;
1171 return nullptr;
1172}
1173
1174// Assign addresses to an output section and offsets to its input sections and
1175// symbol assignments. Return true if the output section's address has changed.
1176bool LinkerScript::assignOffsets(OutputSection *sec) {
1177 const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
1178 const bool sameMemRegion = state->memRegion == sec->memRegion;
1179 const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;
1180 const uint64_t savedDot = dot;
1181 bool addressChanged = false;
1182 state->memRegion = sec->memRegion;
1183 state->lmaRegion = sec->lmaRegion;
1184
1185 if (!(sec->flags & SHF_ALLOC)) {
1186 // Non-SHF_ALLOC sections have zero addresses.
1187 dot = 0;
1188 } else if (isTbss) {
1189 // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range
1190 // starts from the end address of the previous tbss section.
1191 if (state->tbssAddr == 0)
1192 state->tbssAddr = dot;
1193 else
1194 dot = state->tbssAddr;
1195 } else {
1196 // If there is an explicit address expression this takes precedence over
1197 // the memory region address.
1198 if (state->memRegion && !(hasSectionsCommand && sec->addrExpr))
1199 dot = state->memRegion->curPos;
1200 if (sec->addrExpr)
1201 setDot(e: sec->addrExpr, loc: sec->location, inSec: false);
1202
1203 // If the address of the section has been moved forward by an explicit
1204 // expression so that it now starts past the current curPos of the enclosing
1205 // region, we need to expand the current region to account for the space
1206 // between the previous section, if any, and the start of this section.
1207 if (state->memRegion && state->memRegion->curPos < dot)
1208 expandMemoryRegion(memRegion: state->memRegion, size: dot - state->memRegion->curPos,
1209 secName: sec->name);
1210 }
1211
1212 state->outSec = sec;
1213 if (!(sec->addrExpr && hasSectionsCommand)) {
1214 // ALIGN is respected. sec->alignment is the max of ALIGN and the maximum of
1215 // input section alignments.
1216 const uint64_t pos = dot;
1217 dot = alignToPowerOf2(Value: dot, Align: sec->addralign);
1218 expandMemoryRegions(size: dot - pos);
1219 }
1220 addressChanged = sec->addr != dot;
1221 sec->addr = dot;
1222
1223 // state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()
1224 // or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA
1225 // region is the default, and the two sections are in the same memory region,
1226 // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
1227 // heuristics described in
1228 // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
1229 if (sec->lmaExpr) {
1230 state->lmaOffset = sec->lmaExpr().getValue() - dot;
1231 } else if (MemoryRegion *mr = sec->lmaRegion) {
1232 uint64_t lmaStart = alignToPowerOf2(Value: mr->curPos, Align: sec->addralign);
1233 if (mr->curPos < lmaStart)
1234 expandMemoryRegion(memRegion: mr, size: lmaStart - mr->curPos, secName: sec->name);
1235 state->lmaOffset = lmaStart - dot;
1236 } else if (!sameMemRegion || !prevLMARegionIsDefault) {
1237 state->lmaOffset = 0;
1238 }
1239
1240 // Propagate state->lmaOffset to the first "non-header" section.
1241 if (PhdrEntry *l = sec->ptLoad)
1242 if (sec == findFirstSection(ctx, load: l))
1243 l->lmaOffset = state->lmaOffset;
1244
1245 // We can call this method multiple times during the creation of
1246 // thunks and want to start over calculation each time.
1247 sec->size = 0;
1248 if (sec->firstInOverlay)
1249 state->overlaySize = 0;
1250
1251 bool synthesizeAlign =
1252 ctx.arg.relocatable && ctx.arg.relax && (sec->flags & SHF_EXECINSTR) &&
1253 (ctx.arg.emachine == EM_LOONGARCH || ctx.arg.emachine == EM_RISCV);
1254 // We visited SectionsCommands from processSectionCommands to
1255 // layout sections. Now, we visit SectionsCommands again to fix
1256 // section offsets.
1257 for (SectionCommand *cmd : sec->commands) {
1258 // This handles the assignments to symbol or to the dot.
1259 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd)) {
1260 assign->addr = dot;
1261 assignSymbol(cmd: assign, inSec: true);
1262 assign->size = dot - assign->addr;
1263 continue;
1264 }
1265
1266 // Handle BYTE(), SHORT(), LONG(), or QUAD().
1267 if (auto *data = dyn_cast<ByteCommand>(Val: cmd)) {
1268 data->offset = dot - sec->addr;
1269 dot += data->size;
1270 expandOutputSection(size: data->size);
1271 continue;
1272 }
1273
1274 // Handle a single input section description command.
1275 // It calculates and assigns the offsets for each section and also
1276 // updates the output section size.
1277
1278 auto &sections = cast<InputSectionDescription>(Val: cmd)->sections;
1279 for (InputSection *isec : sections) {
1280 assert(isec->getParent() == sec);
1281 if (isa<PotentialSpillSection>(Val: isec))
1282 continue;
1283 const uint64_t pos = dot;
1284 // If synthesized ALIGN may be needed, call maybeSynthesizeAlign and
1285 // disable the default handling if the return value is true.
1286 if (!(synthesizeAlign && ctx.target->synthesizeAlign(dot, sec: isec)))
1287 dot = alignToPowerOf2(Value: dot, Align: isec->addralign);
1288 isec->outSecOff = dot - sec->addr;
1289 dot += isec->getSize();
1290
1291 // Update output section size after adding each section. This is so that
1292 // SIZEOF works correctly in the case below:
1293 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
1294 expandOutputSection(size: dot - pos);
1295 }
1296 }
1297
1298 // If .relro_padding is present, round up the end to a common-page-size
1299 // boundary to protect the last page.
1300 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())
1301 expandOutputSection(size: alignToPowerOf2(Value: dot, Align: ctx.arg.commonPageSize) - dot);
1302
1303 if (synthesizeAlign) {
1304 const uint64_t pos = dot;
1305 ctx.target->synthesizeAlign(dot, sec: nullptr);
1306 expandOutputSection(size: dot - pos);
1307 }
1308
1309 // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
1310 // as they are not part of the process image.
1311 if (!(sec->flags & SHF_ALLOC)) {
1312 dot = savedDot;
1313 } else if (isTbss) {
1314 // NOBITS TLS sections are similar. Additionally save the end address.
1315 state->tbssAddr = dot;
1316 dot = savedDot;
1317 }
1318 return addressChanged;
1319}
1320
1321static bool isDiscardable(const OutputSection &sec) {
1322 if (sec.name == "/DISCARD/")
1323 return true;
1324
1325 // We do not want to remove OutputSections with expressions that reference
1326 // symbols even if the OutputSection is empty. We want to ensure that the
1327 // expressions can be evaluated and report an error if they cannot.
1328 if (sec.expressionsUseSymbols)
1329 return false;
1330
1331 // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
1332 // as an empty Section can has a valid VMA and LMA we keep the OutputSection
1333 // to maintain the integrity of the other Expression.
1334 if (sec.usedInExpression)
1335 return false;
1336
1337 for (SectionCommand *cmd : sec.commands) {
1338 if (auto assign = dyn_cast<SymbolAssignment>(Val: cmd))
1339 // Don't create empty output sections just for unreferenced PROVIDE
1340 // symbols.
1341 if (assign->name != "." && !assign->sym)
1342 continue;
1343
1344 if (!isa<InputSectionDescription>(Val: *cmd))
1345 return false;
1346 }
1347 return true;
1348}
1349
1350static void maybePropagatePhdrs(OutputSection &sec,
1351 SmallVector<StringRef, 0> &phdrs) {
1352 if (sec.phdrs.empty()) {
1353 // To match the bfd linker script behaviour, only propagate program
1354 // headers to sections that are allocated.
1355 if (sec.flags & SHF_ALLOC)
1356 sec.phdrs = phdrs;
1357 } else {
1358 phdrs = sec.phdrs;
1359 }
1360}
1361
1362void LinkerScript::adjustOutputSections() {
1363 // If the output section contains only symbol assignments, create a
1364 // corresponding output section. The issue is what to do with linker script
1365 // like ".foo : { symbol = 42; }". One option would be to convert it to
1366 // "symbol = 42;". That is, move the symbol out of the empty section
1367 // description. That seems to be what bfd does for this simple case. The
1368 // problem is that this is not completely general. bfd will give up and
1369 // create a dummy section too if there is a ". = . + 1" inside the section
1370 // for example.
1371 // Given that we want to create the section, we have to worry what impact
1372 // it will have on the link. For example, if we just create a section with
1373 // 0 for flags, it would change which PT_LOADs are created.
1374 // We could remember that particular section is dummy and ignore it in
1375 // other parts of the linker, but unfortunately there are quite a few places
1376 // that would need to change:
1377 // * The program header creation.
1378 // * The orphan section placement.
1379 // * The address assignment.
1380 // The other option is to pick flags that minimize the impact the section
1381 // will have on the rest of the linker. That is why we copy the flags from
1382 // the previous sections. We copy just SHF_ALLOC and SHF_WRITE to keep the
1383 // impact low. We do not propagate SHF_EXECINSTR as in some cases this can
1384 // lead to executable writeable section.
1385 uint64_t flags = SHF_ALLOC;
1386
1387 SmallVector<StringRef, 0> defPhdrs;
1388 bool seenRelro = false;
1389 for (SectionCommand *&cmd : sectionCommands) {
1390 if (!isa<OutputDesc>(Val: cmd))
1391 continue;
1392 auto *sec = &cast<OutputDesc>(Val: cmd)->osec;
1393
1394 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
1395 if (sec->alignExpr)
1396 sec->addralign =
1397 std::max<uint32_t>(a: sec->addralign, b: sec->alignExpr().getValue());
1398
1399 bool isEmpty = (getFirstInputSection(os: sec) == nullptr);
1400 bool discardable = isEmpty && isDiscardable(sec: *sec);
1401 // If sec has at least one input section and not discarded, remember its
1402 // flags to be inherited by subsequent output sections. (sec may contain
1403 // just one empty synthetic section.)
1404 if (sec->hasInputSections && !discardable)
1405 flags = sec->flags;
1406
1407 // We do not want to keep any special flags for output section
1408 // in case it is empty.
1409 if (isEmpty) {
1410 sec->flags =
1411 flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);
1412 sec->sortRank = getSectionRank(ctx, osec&: *sec);
1413 }
1414
1415 // The code below may remove empty output sections. We should save the
1416 // specified program headers (if exist) and propagate them to subsequent
1417 // sections which do not specify program headers.
1418 // An example of such a linker script is:
1419 // SECTIONS { .empty : { *(.empty) } :rw
1420 // .foo : { *(.foo) } }
1421 // Note: at this point the order of output sections has not been finalized,
1422 // because orphans have not been inserted into their expected positions. We
1423 // will handle them in adjustSectionsAfterSorting().
1424 if (sec->sectionIndex != UINT32_MAX)
1425 maybePropagatePhdrs(sec&: *sec, phdrs&: defPhdrs);
1426
1427 // Discard .relro_padding if we have not seen one RELRO section. Note: when
1428 // .tbss is the only RELRO section, there is no associated PT_LOAD segment
1429 // (needsPtLoad), so we don't append .relro_padding in the case.
1430 if (ctx.in.relroPadding && ctx.in.relroPadding->getParent() == sec &&
1431 !seenRelro)
1432 discardable = true;
1433 if (discardable) {
1434 sec->markDead();
1435 cmd = nullptr;
1436 } else {
1437 seenRelro |=
1438 sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));
1439 }
1440 }
1441
1442 // It is common practice to use very generic linker scripts. So for any
1443 // given run some of the output sections in the script will be empty.
1444 // We could create corresponding empty output sections, but that would
1445 // clutter the output.
1446 // We instead remove trivially empty sections. The bfd linker seems even
1447 // more aggressive at removing them.
1448 llvm::erase_if(C&: sectionCommands, P: [&](SectionCommand *cmd) { return !cmd; });
1449}
1450
1451void LinkerScript::adjustSectionsAfterSorting() {
1452 // Try and find an appropriate memory region to assign offsets in.
1453 MemoryRegion *hint = nullptr;
1454 for (SectionCommand *cmd : sectionCommands) {
1455 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd)) {
1456 OutputSection *sec = &osd->osec;
1457 if (!sec->lmaRegionName.empty()) {
1458 if (MemoryRegion *m = memoryRegions.lookup(Key: sec->lmaRegionName))
1459 sec->lmaRegion = m;
1460 else
1461 ErrAlways(ctx) << "memory region '" << sec->lmaRegionName
1462 << "' not declared";
1463 }
1464 std::tie(args&: sec->memRegion, args&: hint) = findMemoryRegion(sec, hint);
1465 }
1466 }
1467
1468 // If output section command doesn't specify any segments,
1469 // and we haven't previously assigned any section to segment,
1470 // then we simply assign section to the very first load segment.
1471 // Below is an example of such linker script:
1472 // PHDRS { seg PT_LOAD; }
1473 // SECTIONS { .aaa : { *(.aaa) } }
1474 SmallVector<StringRef, 0> defPhdrs;
1475 auto firstPtLoad = llvm::find_if(Range&: phdrsCommands, P: [](const PhdrsCommand &cmd) {
1476 return cmd.type == PT_LOAD;
1477 });
1478 if (firstPtLoad != phdrsCommands.end())
1479 defPhdrs.push_back(Elt: firstPtLoad->name);
1480
1481 // Walk the commands and propagate the program headers to commands that don't
1482 // explicitly specify them.
1483 for (SectionCommand *cmd : sectionCommands)
1484 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
1485 maybePropagatePhdrs(sec&: osd->osec, phdrs&: defPhdrs);
1486}
1487
1488// When the SECTIONS command is used, try to find an address for the file and
1489// program headers output sections, which can be added to the first PT_LOAD
1490// segment when program headers are created.
1491//
1492// We check if the headers fit below the first allocated section. If there isn't
1493// enough space for these sections, we'll remove them from the PT_LOAD segment,
1494// and we'll also remove the PT_PHDR segment.
1495void LinkerScript::allocateHeaders(
1496 SmallVector<std::unique_ptr<PhdrEntry>, 0> &phdrs) {
1497 uint64_t min = std::numeric_limits<uint64_t>::max();
1498 for (OutputSection *sec : ctx.outputSections)
1499 if (sec->flags & SHF_ALLOC)
1500 min = std::min<uint64_t>(a: min, b: sec->addr);
1501
1502 auto it = llvm::find_if(Range&: phdrs, P: [](auto &e) { return e->p_type == PT_LOAD; });
1503 if (it == phdrs.end())
1504 return;
1505 PhdrEntry *firstPTLoad = it->get();
1506
1507 bool hasExplicitHeaders =
1508 llvm::any_of(Range&: phdrsCommands, P: [](const PhdrsCommand &cmd) {
1509 return cmd.hasPhdrs || cmd.hasFilehdr;
1510 });
1511 bool paged = !ctx.arg.omagic && !ctx.arg.nmagic;
1512 uint64_t headerSize = getHeaderSize(ctx);
1513
1514 uint64_t base = 0;
1515 // If SECTIONS is present and the linkerscript is not explicit about program
1516 // headers, only allocate program headers if that would not add a page.
1517 if (hasSectionsCommand && !hasExplicitHeaders)
1518 base = alignDown(Value: min, Align: ctx.arg.maxPageSize);
1519 if ((paged || hasExplicitHeaders) && headerSize <= min - base) {
1520 min = alignDown(Value: min - headerSize, Align: ctx.arg.maxPageSize);
1521 ctx.out.elfHeader->addr = min;
1522 ctx.out.programHeaders->addr = min + ctx.out.elfHeader->size;
1523 return;
1524 }
1525
1526 // Error if we were explicitly asked to allocate headers.
1527 if (hasExplicitHeaders)
1528 ErrAlways(ctx) << "could not allocate headers";
1529
1530 ctx.out.elfHeader->ptLoad = nullptr;
1531 ctx.out.programHeaders->ptLoad = nullptr;
1532 firstPTLoad->firstSec = findFirstSection(ctx, load: firstPTLoad);
1533
1534 llvm::erase_if(C&: phdrs, P: [](auto &e) { return e->p_type == PT_PHDR; });
1535}
1536
1537LinkerScript::AddressState::AddressState(const LinkerScript &script) {
1538 for (auto &mri : script.memoryRegions) {
1539 MemoryRegion *mr = mri.second;
1540 mr->curPos = (mr->origin)().getValue();
1541 }
1542}
1543
1544// Here we assign addresses as instructed by linker script SECTIONS
1545// sub-commands. Doing that allows us to use final VA values, so here
1546// we also handle rest commands like symbol assignments and ASSERTs.
1547// Return an output section that has changed its address or null, and a symbol
1548// that has changed its section or value (or nullptr if no symbol has changed).
1549std::pair<const OutputSection *, const Defined *>
1550LinkerScript::assignAddresses() {
1551 if (hasSectionsCommand) {
1552 // With a linker script, assignment of addresses to headers is covered by
1553 // allocateHeaders().
1554 dot = ctx.arg.imageBase.value_or(u: 0);
1555 } else {
1556 // Assign addresses to headers right now.
1557 dot = ctx.target->getImageBase();
1558 ctx.out.elfHeader->addr = dot;
1559 ctx.out.programHeaders->addr = dot + ctx.out.elfHeader->size;
1560 dot += getHeaderSize(ctx);
1561 }
1562
1563 OutputSection *changedOsec = nullptr;
1564 AddressState st(*this);
1565 state = &st;
1566 errorOnMissingSection = true;
1567 st.outSec = aether.get();
1568 recordedErrors.clear();
1569
1570 SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
1571 for (SectionCommand *cmd : sectionCommands) {
1572 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd)) {
1573 assign->addr = dot;
1574 assignSymbol(cmd: assign, inSec: false);
1575 assign->size = dot - assign->addr;
1576 continue;
1577 }
1578 if (isa<SectionClassDesc>(Val: cmd))
1579 continue;
1580 if (assignOffsets(sec: &cast<OutputDesc>(Val: cmd)->osec) && !changedOsec)
1581 changedOsec = &cast<OutputDesc>(Val: cmd)->osec;
1582 }
1583
1584 state = nullptr;
1585 return {changedOsec, getChangedSymbolAssignment(oldValues)};
1586}
1587
1588static bool hasRegionOverflowed(MemoryRegion *mr) {
1589 if (!mr)
1590 return false;
1591 return mr->curPos - mr->getOrigin() > mr->getLength();
1592}
1593
1594// Spill input sections in reverse order of address assignment to (potentially)
1595// bring memory regions out of overflow. The size savings of a spill can only be
1596// estimated, since general linker script arithmetic may occur afterwards.
1597// Under-estimates may cause unnecessary spills, but over-estimates can always
1598// be corrected on the next pass.
1599bool LinkerScript::spillSections() {
1600 if (potentialSpillLists.empty())
1601 return false;
1602
1603 DenseSet<PotentialSpillSection *> skippedSpills;
1604
1605 bool spilled = false;
1606 for (SectionCommand *cmd : reverse(C&: sectionCommands)) {
1607 auto *osd = dyn_cast<OutputDesc>(Val: cmd);
1608 if (!osd)
1609 continue;
1610 OutputSection *osec = &osd->osec;
1611 if (!osec->memRegion)
1612 continue;
1613
1614 // Input sections that have replaced a potential spill and should be removed
1615 // from their input section description.
1616 DenseSet<InputSection *> spilledInputSections;
1617
1618 for (SectionCommand *cmd : reverse(C&: osec->commands)) {
1619 if (!hasRegionOverflowed(mr: osec->memRegion) &&
1620 !hasRegionOverflowed(mr: osec->lmaRegion))
1621 break;
1622
1623 auto *isd = dyn_cast<InputSectionDescription>(Val: cmd);
1624 if (!isd)
1625 continue;
1626 for (InputSection *isec : reverse(C&: isd->sections)) {
1627 // Potential spill locations cannot be spilled.
1628 if (isa<PotentialSpillSection>(Val: isec))
1629 continue;
1630
1631 auto it = potentialSpillLists.find(Val: isec);
1632 if (it == potentialSpillLists.end())
1633 break;
1634
1635 // Consume spills until finding one that might help, then consume it.
1636 auto canSpillHelp = [&](PotentialSpillSection *spill) {
1637 // Spills to the same region that overflowed cannot help.
1638 if (hasRegionOverflowed(mr: osec->memRegion) &&
1639 spill->getParent()->memRegion == osec->memRegion)
1640 return false;
1641 if (hasRegionOverflowed(mr: osec->lmaRegion) &&
1642 spill->getParent()->lmaRegion == osec->lmaRegion)
1643 return false;
1644 return true;
1645 };
1646 PotentialSpillList &list = it->second;
1647 PotentialSpillSection *spill;
1648 for (spill = list.head; spill; spill = spill->next) {
1649 if (list.head->next)
1650 list.head = spill->next;
1651 else
1652 potentialSpillLists.erase(Val: isec);
1653 if (canSpillHelp(spill))
1654 break;
1655 skippedSpills.insert(V: spill);
1656 }
1657 if (!spill)
1658 continue;
1659
1660 // Replace the next spill location with the spilled section and adjust
1661 // its properties to match the new location. Note that the alignment of
1662 // the spill section may have diverged from the original due to e.g. a
1663 // SUBALIGN. Correct assignment requires the spill's alignment to be
1664 // used, not the original.
1665 spilledInputSections.insert(V: isec);
1666 *llvm::find(Range&: spill->isd->sections, Val: spill) = isec;
1667 isec->parent = spill->parent;
1668 isec->addralign = spill->addralign;
1669
1670 // Record the (potential) reduction in the region's end position.
1671 osec->memRegion->curPos -= isec->getSize();
1672 if (osec->lmaRegion)
1673 osec->lmaRegion->curPos -= isec->getSize();
1674
1675 // Spilling continues until the end position no longer overflows the
1676 // region. Then, another round of address assignment will either confirm
1677 // the spill's success or lead to yet more spilling.
1678 if (!hasRegionOverflowed(mr: osec->memRegion) &&
1679 !hasRegionOverflowed(mr: osec->lmaRegion))
1680 break;
1681 }
1682
1683 // Remove any spilled input sections to complete their move.
1684 if (!spilledInputSections.empty()) {
1685 spilled = true;
1686 llvm::erase_if(C&: isd->sections, P: [&](InputSection *isec) {
1687 return spilledInputSections.contains(V: isec);
1688 });
1689 }
1690 }
1691 }
1692
1693 // Clean up any skipped spills.
1694 DenseSet<InputSectionDescription *> isds;
1695 for (PotentialSpillSection *s : skippedSpills)
1696 isds.insert(V: s->isd);
1697 for (InputSectionDescription *isd : isds)
1698 llvm::erase_if(C&: isd->sections, P: [&](InputSection *s) {
1699 return skippedSpills.contains(V: dyn_cast<PotentialSpillSection>(Val: s));
1700 });
1701
1702 return spilled;
1703}
1704
1705// Erase any potential spill sections that were not used.
1706void LinkerScript::erasePotentialSpillSections() {
1707 if (potentialSpillLists.empty())
1708 return;
1709
1710 // Collect the set of input section descriptions that contain potential
1711 // spills.
1712 DenseSet<InputSectionDescription *> isds;
1713 for (const auto &[_, list] : potentialSpillLists)
1714 for (PotentialSpillSection *s = list.head; s; s = s->next)
1715 isds.insert(V: s->isd);
1716
1717 for (InputSectionDescription *isd : isds)
1718 llvm::erase_if(C&: isd->sections, P: [](InputSection *s) {
1719 return isa<PotentialSpillSection>(Val: s);
1720 });
1721
1722 potentialSpillLists.clear();
1723}
1724
1725// Creates program headers as instructed by PHDRS linker script command.
1726SmallVector<std::unique_ptr<PhdrEntry>, 0> LinkerScript::createPhdrs() {
1727 SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;
1728
1729 // Process PHDRS and FILEHDR keywords because they are not
1730 // real output sections and cannot be added in the following loop.
1731 for (const PhdrsCommand &cmd : phdrsCommands) {
1732 auto phdr =
1733 std::make_unique<PhdrEntry>(args&: ctx, args: cmd.type, args: cmd.flags.value_or(u: PF_R));
1734
1735 if (cmd.hasFilehdr)
1736 phdr->add(sec: ctx.out.elfHeader.get());
1737 if (cmd.hasPhdrs)
1738 phdr->add(sec: ctx.out.programHeaders.get());
1739
1740 if (cmd.lmaExpr) {
1741 phdr->p_paddr = cmd.lmaExpr().getValue();
1742 phdr->hasLMA = true;
1743 }
1744 ret.push_back(Elt: std::move(phdr));
1745 }
1746
1747 // Add output sections to program headers.
1748 for (OutputSection *sec : ctx.outputSections) {
1749 // Assign headers specified by linker script
1750 for (size_t id : getPhdrIndices(sec)) {
1751 ret[id]->add(sec);
1752 if (!phdrsCommands[id].flags)
1753 ret[id]->p_flags |= sec->getPhdrFlags();
1754 }
1755 }
1756 return ret;
1757}
1758
1759// Returns true if we should emit an .interp section.
1760//
1761// We usually do. But if PHDRS commands are given, and
1762// no PT_INTERP is there, there's no place to emit an
1763// .interp, so we don't do that in that case.
1764bool LinkerScript::needsInterpSection() {
1765 if (phdrsCommands.empty())
1766 return true;
1767 for (PhdrsCommand &cmd : phdrsCommands)
1768 if (cmd.type == PT_INTERP)
1769 return true;
1770 return false;
1771}
1772
1773ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
1774 if (name == ".") {
1775 if (state)
1776 return {state->outSec, false, dot - state->outSec->addr, loc};
1777 ErrAlways(ctx) << loc << ": unable to get location counter value";
1778 return 0;
1779 }
1780
1781 if (Symbol *sym = ctx.symtab->find(name)) {
1782 if (auto *ds = dyn_cast<Defined>(Val: sym)) {
1783 ExprValue v{ds->section, false, ds->value, loc};
1784 // Retain the original st_type, so that the alias will get the same
1785 // behavior in relocation processing. Any operation will reset st_type to
1786 // STT_NOTYPE.
1787 v.type = ds->type;
1788 return v;
1789 }
1790 if (isa<SharedSymbol>(Val: sym))
1791 if (!errorOnMissingSection)
1792 return {nullptr, false, 0, loc};
1793 }
1794
1795 ErrAlways(ctx) << loc << ": symbol not found: " << name;
1796 return 0;
1797}
1798
1799// Returns the index of the segment named Name.
1800static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
1801 StringRef name) {
1802 for (size_t i = 0; i < vec.size(); ++i)
1803 if (vec[i].name == name)
1804 return i;
1805 return std::nullopt;
1806}
1807
1808// Returns indices of ELF headers containing specific section. Each index is a
1809// zero based number of ELF header listed within PHDRS {} script block.
1810SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1811 SmallVector<size_t, 0> ret;
1812
1813 for (StringRef s : cmd->phdrs) {
1814 if (std::optional<size_t> idx = getPhdrIndex(vec: phdrsCommands, name: s))
1815 ret.push_back(Elt: *idx);
1816 else if (s != "NONE")
1817 ErrAlways(ctx) << cmd->location << ": program header '" << s
1818 << "' is not listed in PHDRS";
1819 }
1820 return ret;
1821}
1822
1823void LinkerScript::printMemoryUsage(raw_ostream& os) {
1824 auto printSize = [&](uint64_t size) {
1825 if ((size & 0x3fffffff) == 0)
1826 os << format_decimal(N: size >> 30, Width: 10) << " GB";
1827 else if ((size & 0xfffff) == 0)
1828 os << format_decimal(N: size >> 20, Width: 10) << " MB";
1829 else if ((size & 0x3ff) == 0)
1830 os << format_decimal(N: size >> 10, Width: 10) << " KB";
1831 else
1832 os << " " << format_decimal(N: size, Width: 10) << " B";
1833 };
1834 os << "Memory region Used Size Region Size %age Used\n";
1835 for (auto &pair : memoryRegions) {
1836 MemoryRegion *m = pair.second;
1837 uint64_t usedLength = m->curPos - m->getOrigin();
1838 os << right_justify(Str: m->name, Width: 16) << ": ";
1839 printSize(usedLength);
1840 uint64_t length = m->getLength();
1841 if (length != 0) {
1842 printSize(length);
1843 double percent = usedLength * 100.0 / length;
1844 os << " " << format(Fmt: "%6.2f%%", Vals: percent);
1845 }
1846 os << '\n';
1847 }
1848}
1849
1850void LinkerScript::recordError(const Twine &msg) {
1851 auto &str = recordedErrors.emplace_back();
1852 msg.toVector(Out&: str);
1853}
1854
1855static void checkMemoryRegion(Ctx &ctx, const MemoryRegion *region,
1856 const OutputSection *osec, uint64_t addr) {
1857 uint64_t osecEnd = addr + osec->size;
1858 uint64_t regionEnd = region->getOrigin() + region->getLength();
1859 if (osecEnd > regionEnd) {
1860 ErrAlways(ctx) << "section '" << osec->name << "' will not fit in region '"
1861 << region->name << "': overflowed by "
1862 << (osecEnd - regionEnd) << " bytes";
1863 }
1864}
1865
1866void LinkerScript::checkFinalScriptConditions() const {
1867 for (StringRef err : recordedErrors)
1868 Err(ctx) << err;
1869 for (const OutputSection *sec : ctx.outputSections) {
1870 if (const MemoryRegion *memoryRegion = sec->memRegion)
1871 checkMemoryRegion(ctx, region: memoryRegion, osec: sec, addr: sec->addr);
1872 if (const MemoryRegion *lmaRegion = sec->lmaRegion)
1873 checkMemoryRegion(ctx, region: lmaRegion, osec: sec, addr: sec->getLMA());
1874 }
1875}
1876
1877void LinkerScript::addScriptReferencedSymbolsToSymTable() {
1878 // Some symbols (such as __ehdr_start) are defined lazily only when there
1879 // are undefined symbols for them, so we add these to trigger that logic.
1880 auto reference = [&ctx = ctx](StringRef name) {
1881 Symbol *sym = ctx.symtab->addUnusedUndefined(name);
1882 sym->isUsedInRegularObj = true;
1883 sym->referenced = true;
1884 };
1885 for (StringRef name : referencedSymbols)
1886 reference(name);
1887
1888 // Keeps track of references from which PROVIDE symbols have been added to the
1889 // symbol table.
1890 DenseSet<StringRef> added;
1891 SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;
1892 for (const auto &[name, symRefs] : provideMap)
1893 if (shouldAddProvideSym(symName: name) && added.insert(V: name).second)
1894 symRefsVec.push_back(Elt: &symRefs);
1895 while (symRefsVec.size()) {
1896 for (StringRef name : *symRefsVec.pop_back_val()) {
1897 reference(name);
1898 // Prevent the symbol from being discarded by --gc-sections.
1899 referencedSymbols.push_back(Elt: name);
1900 auto it = provideMap.find(Key: name);
1901 if (it != provideMap.end() && shouldAddProvideSym(symName: name) &&
1902 added.insert(V: name).second) {
1903 symRefsVec.push_back(Elt: &it->second);
1904 }
1905 }
1906 }
1907}
1908
1909bool LinkerScript::shouldAddProvideSym(StringRef symName) {
1910 // This function is called before and after garbage collection. To prevent
1911 // undefined references from the RHS, the result of this function for a
1912 // symbol must be the same for each call. We use unusedProvideSyms to not
1913 // change the return value of a demoted symbol.
1914 Symbol *sym = ctx.symtab->find(name: symName);
1915 if (!sym)
1916 return false;
1917 if (sym->isDefined() || sym->isCommon()) {
1918 unusedProvideSyms.insert(V: sym);
1919 return false;
1920 }
1921 return !unusedProvideSyms.contains(V: sym);
1922}
1923