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