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