Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lld / ELF / LinkerScript.cpp
blobdf091613dc0a1449c15155208ff3f76043cc1f7f
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 std::unique_ptr<LinkerScript> elf::script;
49 static bool isSectionPrefix(StringRef prefix, StringRef name) {
50 return name.consume_front(prefix) && (name.empty() || name[0] == '.');
53 static StringRef getOutputSectionName(const InputSectionBase *s) {
54 if (config->relocatable)
55 return s->name;
57 // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
58 // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
59 // technically required, but not doing it is odd). This code guarantees that.
60 if (auto *isec = dyn_cast<InputSection>(s)) {
61 if (InputSectionBase *rel = isec->getRelocatedSection()) {
62 OutputSection *out = rel->getOutputSection();
63 if (s->type == SHT_RELA)
64 return saver().save(".rela" + out->name);
65 return saver().save(".rel" + out->name);
69 // A BssSection created for a common symbol is identified as "COMMON" in
70 // linker scripts. It should go to .bss section.
71 if (s->name == "COMMON")
72 return ".bss";
74 if (script->hasSectionsCommand)
75 return s->name;
77 // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
78 // by grouping sections with certain prefixes.
80 // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
81 // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
82 // We provide an option -z keep-text-section-prefix to group such sections
83 // into separate output sections. This is more flexible. See also
84 // sortISDBySectionOrder().
85 // ".text.unknown" means the hotness of the section is unknown. When
86 // SampleFDO is used, if a function doesn't have sample, it could be very
87 // cold or it could be a new function never being sampled. Those functions
88 // will be kept in the ".text.unknown" section.
89 // ".text.split." holds symbols which are split out from functions in other
90 // input sections. For example, with -fsplit-machine-functions, placing the
91 // cold parts in .text.split instead of .text.unlikely mitigates against poor
92 // profile inaccuracy. Techniques such as hugepage remapping can make
93 // conservative decisions at the section granularity.
94 if (isSectionPrefix(".text", s->name)) {
95 if (config->zKeepTextSectionPrefix)
96 for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
97 ".text.startup", ".text.exit", ".text.split"})
98 if (isSectionPrefix(v.substr(5), s->name.substr(5)))
99 return v;
100 return ".text";
103 for (StringRef v :
104 {".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss", ".ldata",
105 ".lrodata", ".lbss", ".gcc_except_table", ".init_array", ".fini_array",
106 ".tbss", ".tdata", ".ARM.exidx", ".ARM.extab", ".ctors", ".dtors"})
107 if (isSectionPrefix(v, s->name))
108 return v;
110 return s->name;
113 uint64_t ExprValue::getValue() const {
114 if (sec)
115 return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),
116 alignment);
117 return alignToPowerOf2(val, alignment);
120 uint64_t ExprValue::getSecAddr() const {
121 return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
124 uint64_t ExprValue::getSectionOffset() const {
125 return getValue() - getSecAddr();
128 OutputDesc *LinkerScript::createOutputSection(StringRef name,
129 StringRef location) {
130 OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
131 OutputDesc *sec;
132 if (secRef && secRef->osec.location.empty()) {
133 // There was a forward reference.
134 sec = secRef;
135 } else {
136 sec = make<OutputDesc>(name, SHT_PROGBITS, 0);
137 if (!secRef)
138 secRef = sec;
140 sec->osec.location = std::string(location);
141 return sec;
144 OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
145 OutputDesc *&cmdRef = nameToOutputSection[CachedHashStringRef(name)];
146 if (!cmdRef)
147 cmdRef = make<OutputDesc>(name, SHT_PROGBITS, 0);
148 return cmdRef;
151 // Expands the memory region by the specified size.
152 static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
153 StringRef secName) {
154 memRegion->curPos += size;
157 void LinkerScript::expandMemoryRegions(uint64_t size) {
158 if (state->memRegion)
159 expandMemoryRegion(state->memRegion, size, state->outSec->name);
160 // Only expand the LMARegion if it is different from memRegion.
161 if (state->lmaRegion && state->memRegion != state->lmaRegion)
162 expandMemoryRegion(state->lmaRegion, size, state->outSec->name);
165 void LinkerScript::expandOutputSection(uint64_t size) {
166 state->outSec->size += size;
167 expandMemoryRegions(size);
170 void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
171 uint64_t val = e().getValue();
172 // If val is smaller and we are in an output section, record the error and
173 // report it if this is the last assignAddresses iteration. dot may be smaller
174 // if there is another assignAddresses iteration.
175 if (val < dot && inSec) {
176 backwardDotErr =
177 (loc + ": unable to move location counter (0x" + Twine::utohexstr(dot) +
178 ") backward to 0x" + Twine::utohexstr(val) + " for section '" +
179 state->outSec->name + "'")
180 .str();
183 // Update to location counter means update to section size.
184 if (inSec)
185 expandOutputSection(val - dot);
187 dot = val;
190 // Used for handling linker symbol assignments, for both finalizing
191 // their values and doing early declarations. Returns true if symbol
192 // should be defined from linker script.
193 static bool shouldDefineSym(SymbolAssignment *cmd) {
194 if (cmd->name == ".")
195 return false;
197 if (!cmd->provide)
198 return true;
200 // If a symbol was in PROVIDE(), we need to define it only
201 // when it is a referenced undefined symbol.
202 Symbol *b = symtab.find(cmd->name);
203 if (b && !b->isDefined() && !b->isCommon())
204 return true;
205 return false;
208 // Called by processSymbolAssignments() to assign definitions to
209 // linker-script-defined symbols.
210 void LinkerScript::addSymbol(SymbolAssignment *cmd) {
211 if (!shouldDefineSym(cmd))
212 return;
214 // Define a symbol.
215 ExprValue value = cmd->expression();
216 SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
217 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
219 // When this function is called, section addresses have not been
220 // fixed yet. So, we may or may not know the value of the RHS
221 // expression.
223 // For example, if an expression is `x = 42`, we know x is always 42.
224 // However, if an expression is `x = .`, there's no way to know its
225 // value at the moment.
227 // We want to set symbol values early if we can. This allows us to
228 // use symbols as variables in linker scripts. Doing so allows us to
229 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
230 uint64_t symValue = value.sec ? 0 : value.getValue();
232 Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, value.type,
233 symValue, 0, sec);
235 Symbol *sym = symtab.insert(cmd->name);
236 sym->mergeProperties(newSym);
237 newSym.overwrite(*sym);
238 sym->isUsedInRegularObj = true;
239 cmd->sym = cast<Defined>(sym);
242 // This function is called from LinkerScript::declareSymbols.
243 // It creates a placeholder symbol if needed.
244 static void declareSymbol(SymbolAssignment *cmd) {
245 if (!shouldDefineSym(cmd))
246 return;
248 uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
249 Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, STT_NOTYPE, 0, 0,
250 nullptr);
252 // If the symbol is already defined, its order is 0 (with absence indicating
253 // 0); otherwise it's assigned the order of the SymbolAssignment.
254 Symbol *sym = symtab.insert(cmd->name);
255 if (!sym->isDefined())
256 ctx.scriptSymOrder.insert({sym, cmd->symOrder});
258 // We can't calculate final value right now.
259 sym->mergeProperties(newSym);
260 newSym.overwrite(*sym);
262 cmd->sym = cast<Defined>(sym);
263 cmd->provide = false;
264 sym->isUsedInRegularObj = true;
265 sym->scriptDefined = true;
268 using SymbolAssignmentMap =
269 DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
271 // Collect section/value pairs of linker-script-defined symbols. This is used to
272 // check whether symbol values converge.
273 static SymbolAssignmentMap
274 getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
275 SymbolAssignmentMap ret;
276 for (SectionCommand *cmd : sectionCommands) {
277 if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
278 if (assign->sym) // sym is nullptr for dot.
279 ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
280 assign->sym->value));
281 continue;
283 for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
284 if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
285 if (assign->sym)
286 ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
287 assign->sym->value));
289 return ret;
292 // Returns the lexicographical smallest (for determinism) Defined whose
293 // section/value has changed.
294 static const Defined *
295 getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
296 const Defined *changed = nullptr;
297 for (auto &it : oldValues) {
298 const Defined *sym = it.first;
299 if (std::make_pair(sym->section, sym->value) != it.second &&
300 (!changed || sym->getName() < changed->getName()))
301 changed = sym;
303 return changed;
306 // Process INSERT [AFTER|BEFORE] commands. For each command, we move the
307 // specified output section to the designated place.
308 void LinkerScript::processInsertCommands() {
309 SmallVector<OutputDesc *, 0> moves;
310 for (const InsertCommand &cmd : insertCommands) {
311 for (StringRef name : cmd.names) {
312 // If base is empty, it may have been discarded by
313 // adjustOutputSections(). We do not handle such output sections.
314 auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
315 return isa<OutputDesc>(subCmd) &&
316 cast<OutputDesc>(subCmd)->osec.name == name;
318 if (from == sectionCommands.end())
319 continue;
320 moves.push_back(cast<OutputDesc>(*from));
321 sectionCommands.erase(from);
324 auto insertPos =
325 llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
326 auto *to = dyn_cast<OutputDesc>(subCmd);
327 return to != nullptr && to->osec.name == cmd.where;
329 if (insertPos == sectionCommands.end()) {
330 error("unable to insert " + cmd.names[0] +
331 (cmd.isAfter ? " after " : " before ") + cmd.where);
332 } else {
333 if (cmd.isAfter)
334 ++insertPos;
335 sectionCommands.insert(insertPos, moves.begin(), moves.end());
337 moves.clear();
341 // Symbols defined in script should not be inlined by LTO. At the same time
342 // we don't know their final values until late stages of link. Here we scan
343 // over symbol assignment commands and create placeholder symbols if needed.
344 void LinkerScript::declareSymbols() {
345 assert(!state);
346 for (SectionCommand *cmd : sectionCommands) {
347 if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
348 declareSymbol(assign);
349 continue;
352 // If the output section directive has constraints,
353 // we can't say for sure if it is going to be included or not.
354 // Skip such sections for now. Improve the checks if we ever
355 // need symbols from that sections to be declared early.
356 const OutputSection &sec = cast<OutputDesc>(cmd)->osec;
357 if (sec.constraint != ConstraintKind::NoConstraint)
358 continue;
359 for (SectionCommand *cmd : sec.commands)
360 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
361 declareSymbol(assign);
365 // This function is called from assignAddresses, while we are
366 // fixing the output section addresses. This function is supposed
367 // to set the final value for a given symbol assignment.
368 void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
369 if (cmd->name == ".") {
370 setDot(cmd->expression, cmd->location, inSec);
371 return;
374 if (!cmd->sym)
375 return;
377 ExprValue v = cmd->expression();
378 if (v.isAbsolute()) {
379 cmd->sym->section = nullptr;
380 cmd->sym->value = v.getValue();
381 } else {
382 cmd->sym->section = v.sec;
383 cmd->sym->value = v.getSectionOffset();
385 cmd->sym->type = v.type;
388 static inline StringRef getFilename(const InputFile *file) {
389 return file ? file->getNameForScript() : StringRef();
392 bool InputSectionDescription::matchesFile(const InputFile *file) const {
393 if (filePat.isTrivialMatchAll())
394 return true;
396 if (!matchesFileCache || matchesFileCache->first != file)
397 matchesFileCache.emplace(file, filePat.match(getFilename(file)));
399 return matchesFileCache->second;
402 bool SectionPattern::excludesFile(const InputFile *file) const {
403 if (excludedFilePat.empty())
404 return false;
406 if (!excludesFileCache || excludesFileCache->first != file)
407 excludesFileCache.emplace(file, excludedFilePat.match(getFilename(file)));
409 return excludesFileCache->second;
412 bool LinkerScript::shouldKeep(InputSectionBase *s) {
413 for (InputSectionDescription *id : keptSections)
414 if (id->matchesFile(s->file))
415 for (SectionPattern &p : id->sectionPatterns)
416 if (p.sectionPat.match(s->name) &&
417 (s->flags & id->withFlags) == id->withFlags &&
418 (s->flags & id->withoutFlags) == 0)
419 return true;
420 return false;
423 // A helper function for the SORT() command.
424 static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
425 ConstraintKind kind) {
426 if (kind == ConstraintKind::NoConstraint)
427 return true;
429 bool isRW = llvm::any_of(
430 sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
432 return (isRW && kind == ConstraintKind::ReadWrite) ||
433 (!isRW && kind == ConstraintKind::ReadOnly);
436 static void sortSections(MutableArrayRef<InputSectionBase *> vec,
437 SortSectionPolicy k) {
438 auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
439 // ">" is not a mistake. Sections with larger alignments are placed
440 // before sections with smaller alignments in order to reduce the
441 // amount of padding necessary. This is compatible with GNU.
442 return a->addralign > b->addralign;
444 auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
445 return a->name < b->name;
447 auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
448 return getPriority(a->name) < getPriority(b->name);
451 switch (k) {
452 case SortSectionPolicy::Default:
453 case SortSectionPolicy::None:
454 return;
455 case SortSectionPolicy::Alignment:
456 return llvm::stable_sort(vec, alignmentComparator);
457 case SortSectionPolicy::Name:
458 return llvm::stable_sort(vec, nameComparator);
459 case SortSectionPolicy::Priority:
460 return llvm::stable_sort(vec, priorityComparator);
461 case SortSectionPolicy::Reverse:
462 return std::reverse(vec.begin(), vec.end());
466 // Sort sections as instructed by SORT-family commands and --sort-section
467 // option. Because SORT-family commands can be nested at most two depth
468 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
469 // line option is respected even if a SORT command is given, the exact
470 // behavior we have here is a bit complicated. Here are the rules.
472 // 1. If two SORT commands are given, --sort-section is ignored.
473 // 2. If one SORT command is given, and if it is not SORT_NONE,
474 // --sort-section is handled as an inner SORT command.
475 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
476 // 4. If no SORT command is given, sort according to --sort-section.
477 static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
478 SortSectionPolicy outer,
479 SortSectionPolicy inner) {
480 if (outer == SortSectionPolicy::None)
481 return;
483 if (inner == SortSectionPolicy::Default)
484 sortSections(vec, config->sortSection);
485 else
486 sortSections(vec, inner);
487 sortSections(vec, outer);
490 // Compute and remember which sections the InputSectionDescription matches.
491 SmallVector<InputSectionBase *, 0>
492 LinkerScript::computeInputSections(const InputSectionDescription *cmd,
493 ArrayRef<InputSectionBase *> sections) {
494 SmallVector<InputSectionBase *, 0> ret;
495 SmallVector<size_t, 0> indexes;
496 DenseSet<size_t> seen;
497 auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
498 llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
499 for (size_t i = begin; i != end; ++i)
500 ret[i] = sections[indexes[i]];
501 sortInputSections(
502 MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
503 config->sortSection, SortSectionPolicy::None);
506 // Collects all sections that satisfy constraints of Cmd.
507 size_t sizeAfterPrevSort = 0;
508 for (const SectionPattern &pat : cmd->sectionPatterns) {
509 size_t sizeBeforeCurrPat = ret.size();
511 for (size_t i = 0, e = sections.size(); i != e; ++i) {
512 // Skip if the section is dead or has been matched by a previous input
513 // section description or a previous pattern.
514 InputSectionBase *sec = sections[i];
515 if (!sec->isLive() || sec->parent || seen.contains(i))
516 continue;
518 // For --emit-relocs we have to ignore entries like
519 // .rela.dyn : { *(.rela.data) }
520 // which are common because they are in the default bfd script.
521 // We do not ignore SHT_REL[A] linker-synthesized sections here because
522 // want to support scripts that do custom layout for them.
523 if (isa<InputSection>(sec) &&
524 cast<InputSection>(sec)->getRelocatedSection())
525 continue;
527 // Check the name early to improve performance in the common case.
528 if (!pat.sectionPat.match(sec->name))
529 continue;
531 if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
532 (sec->flags & cmd->withFlags) != cmd->withFlags ||
533 (sec->flags & cmd->withoutFlags) != 0)
534 continue;
536 ret.push_back(sec);
537 indexes.push_back(i);
538 seen.insert(i);
541 if (pat.sortOuter == SortSectionPolicy::Default)
542 continue;
544 // Matched sections are ordered by radix sort with the keys being (SORT*,
545 // --sort-section, input order), where SORT* (if present) is most
546 // significant.
548 // Matched sections between the previous SORT* and this SORT* are sorted by
549 // (--sort-alignment, input order).
550 sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
551 // Matched sections by this SORT* pattern are sorted using all 3 keys.
552 // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
553 // just sort by sortOuter and sortInner.
554 sortInputSections(
555 MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
556 pat.sortOuter, pat.sortInner);
557 sizeAfterPrevSort = ret.size();
559 // Matched sections after the last SORT* are sorted by (--sort-alignment,
560 // input order).
561 sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
562 return ret;
565 void LinkerScript::discard(InputSectionBase &s) {
566 if (&s == in.shStrTab.get())
567 error("discarding " + s.name + " section is not allowed");
569 s.markDead();
570 s.parent = nullptr;
571 for (InputSection *sec : s.dependentSections)
572 discard(*sec);
575 void LinkerScript::discardSynthetic(OutputSection &outCmd) {
576 for (Partition &part : partitions) {
577 if (!part.armExidx || !part.armExidx->isLive())
578 continue;
579 SmallVector<InputSectionBase *, 0> secs(
580 part.armExidx->exidxSections.begin(),
581 part.armExidx->exidxSections.end());
582 for (SectionCommand *cmd : outCmd.commands)
583 if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
584 for (InputSectionBase *s : computeInputSections(isd, secs))
585 discard(*s);
589 SmallVector<InputSectionBase *, 0>
590 LinkerScript::createInputSectionList(OutputSection &outCmd) {
591 SmallVector<InputSectionBase *, 0> ret;
593 for (SectionCommand *cmd : outCmd.commands) {
594 if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
595 isd->sectionBases = computeInputSections(isd, ctx.inputSections);
596 for (InputSectionBase *s : isd->sectionBases)
597 s->parent = &outCmd;
598 ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
601 return ret;
604 // Create output sections described by SECTIONS commands.
605 void LinkerScript::processSectionCommands() {
606 auto process = [this](OutputSection *osec) {
607 SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
609 // The output section name `/DISCARD/' is special.
610 // Any input section assigned to it is discarded.
611 if (osec->name == "/DISCARD/") {
612 for (InputSectionBase *s : v)
613 discard(*s);
614 discardSynthetic(*osec);
615 osec->commands.clear();
616 return false;
619 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
620 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
621 // sections satisfy a given constraint. If not, a directive is handled
622 // as if it wasn't present from the beginning.
624 // Because we'll iterate over SectionCommands many more times, the easy
625 // way to "make it as if it wasn't present" is to make it empty.
626 if (!matchConstraints(v, osec->constraint)) {
627 for (InputSectionBase *s : v)
628 s->parent = nullptr;
629 osec->commands.clear();
630 return false;
633 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
634 // is given, input sections are aligned to that value, whether the
635 // given value is larger or smaller than the original section alignment.
636 if (osec->subalignExpr) {
637 uint32_t subalign = osec->subalignExpr().getValue();
638 for (InputSectionBase *s : v)
639 s->addralign = subalign;
642 // Set the partition field the same way OutputSection::recordSection()
643 // does. Partitions cannot be used with the SECTIONS command, so this is
644 // always 1.
645 osec->partition = 1;
646 return true;
649 // Process OVERWRITE_SECTIONS first so that it can overwrite the main script
650 // or orphans.
651 DenseMap<CachedHashStringRef, OutputDesc *> map;
652 size_t i = 0;
653 for (OutputDesc *osd : overwriteSections) {
654 OutputSection *osec = &osd->osec;
655 if (process(osec) &&
656 !map.try_emplace(CachedHashStringRef(osec->name), osd).second)
657 warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);
659 for (SectionCommand *&base : sectionCommands)
660 if (auto *osd = dyn_cast<OutputDesc>(base)) {
661 OutputSection *osec = &osd->osec;
662 if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
663 log(overwrite->osec.location + " overwrites " + osec->name);
664 overwrite->osec.sectionIndex = i++;
665 base = overwrite;
666 } else if (process(osec)) {
667 osec->sectionIndex = i++;
671 // If an OVERWRITE_SECTIONS specified output section is not in
672 // sectionCommands, append it to the end. The section will be inserted by
673 // orphan placement.
674 for (OutputDesc *osd : overwriteSections)
675 if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
676 sectionCommands.push_back(osd);
679 void LinkerScript::processSymbolAssignments() {
680 // Dot outside an output section still represents a relative address, whose
681 // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
682 // that fills the void outside a section. It has an index of one, which is
683 // indistinguishable from any other regular section index.
684 aether = make<OutputSection>("", 0, SHF_ALLOC);
685 aether->sectionIndex = 1;
687 // `st` captures the local AddressState and makes it accessible deliberately.
688 // This is needed as there are some cases where we cannot just thread the
689 // current state through to a lambda function created by the script parser.
690 AddressState st;
691 state = &st;
692 st.outSec = aether;
694 for (SectionCommand *cmd : sectionCommands) {
695 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
696 addSymbol(assign);
697 else
698 for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
699 if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
700 addSymbol(assign);
703 state = nullptr;
706 static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
707 StringRef name) {
708 for (SectionCommand *cmd : vec)
709 if (auto *osd = dyn_cast<OutputDesc>(cmd))
710 if (osd->osec.name == name)
711 return &osd->osec;
712 return nullptr;
715 static OutputDesc *createSection(InputSectionBase *isec, StringRef outsecName) {
716 OutputDesc *osd = script->createOutputSection(outsecName, "<internal>");
717 osd->osec.recordSection(isec);
718 return osd;
721 static OutputDesc *addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
722 InputSectionBase *isec, StringRef outsecName) {
723 // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
724 // option is given. A section with SHT_GROUP defines a "section group", and
725 // its members have SHF_GROUP attribute. Usually these flags have already been
726 // stripped by InputFiles.cpp as section groups are processed and uniquified.
727 // However, for the -r option, we want to pass through all section groups
728 // as-is because adding/removing members or merging them with other groups
729 // change their semantics.
730 if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
731 return createSection(isec, outsecName);
733 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
734 // relocation sections .rela.foo and .rela.bar for example. Most tools do
735 // not allow multiple REL[A] sections for output section. Hence we
736 // should combine these relocation sections into single output.
737 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
738 // other REL[A] sections created by linker itself.
739 if (!isa<SyntheticSection>(isec) &&
740 (isec->type == SHT_REL || isec->type == SHT_RELA)) {
741 auto *sec = cast<InputSection>(isec);
742 OutputSection *out = sec->getRelocatedSection()->getOutputSection();
744 if (out->relocationSection) {
745 out->relocationSection->recordSection(sec);
746 return nullptr;
749 OutputDesc *osd = createSection(isec, outsecName);
750 out->relocationSection = &osd->osec;
751 return osd;
754 // The ELF spec just says
755 // ----------------------------------------------------------------
756 // In the first phase, input sections that match in name, type and
757 // attribute flags should be concatenated into single sections.
758 // ----------------------------------------------------------------
760 // However, it is clear that at least some flags have to be ignored for
761 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
762 // ignored. We should not have two output .text sections just because one was
763 // in a group and another was not for example.
765 // It also seems that wording was a late addition and didn't get the
766 // necessary scrutiny.
768 // Merging sections with different flags is expected by some users. One
769 // reason is that if one file has
771 // int *const bar __attribute__((section(".foo"))) = (int *)0;
773 // gcc with -fPIC will produce a read only .foo section. But if another
774 // file has
776 // int zed;
777 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
779 // gcc with -fPIC will produce a read write section.
781 // Last but not least, when using linker script the merge rules are forced by
782 // the script. Unfortunately, linker scripts are name based. This means that
783 // expressions like *(.foo*) can refer to multiple input sections with
784 // different flags. We cannot put them in different output sections or we
785 // would produce wrong results for
787 // start = .; *(.foo.*) end = .; *(.bar)
789 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
790 // another. The problem is that there is no way to layout those output
791 // sections such that the .foo sections are the only thing between the start
792 // and end symbols.
794 // Given the above issues, we instead merge sections by name and error on
795 // incompatible types and flags.
796 TinyPtrVector<OutputSection *> &v = map[outsecName];
797 for (OutputSection *sec : v) {
798 if (sec->partition != isec->partition)
799 continue;
801 if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
802 // Merging two SHF_LINK_ORDER sections with different sh_link fields will
803 // change their semantics, so we only merge them in -r links if they will
804 // end up being linked to the same output section. The casts are fine
805 // because everything in the map was created by the orphan placement code.
806 auto *firstIsec = cast<InputSectionBase>(
807 cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
808 OutputSection *firstIsecOut =
809 firstIsec->flags & SHF_LINK_ORDER
810 ? firstIsec->getLinkOrderDep()->getOutputSection()
811 : nullptr;
812 if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
813 continue;
816 sec->recordSection(isec);
817 return nullptr;
820 OutputDesc *osd = createSection(isec, outsecName);
821 v.push_back(&osd->osec);
822 return osd;
825 // Add sections that didn't match any sections command.
826 void LinkerScript::addOrphanSections() {
827 StringMap<TinyPtrVector<OutputSection *>> map;
828 SmallVector<OutputDesc *, 0> v;
830 auto add = [&](InputSectionBase *s) {
831 if (s->isLive() && !s->parent) {
832 orphanSections.push_back(s);
834 StringRef name = getOutputSectionName(s);
835 if (config->unique) {
836 v.push_back(createSection(s, name));
837 } else if (OutputSection *sec = findByName(sectionCommands, name)) {
838 sec->recordSection(s);
839 } else {
840 if (OutputDesc *osd = addInputSec(map, s, name))
841 v.push_back(osd);
842 assert(isa<MergeInputSection>(s) ||
843 s->getOutputSection()->sectionIndex == UINT32_MAX);
848 // For further --emit-reloc handling code we need target output section
849 // to be created before we create relocation output section, so we want
850 // to create target sections first. We do not want priority handling
851 // for synthetic sections because them are special.
852 size_t n = 0;
853 for (InputSectionBase *isec : ctx.inputSections) {
854 // Process InputSection and MergeInputSection.
855 if (LLVM_LIKELY(isa<InputSection>(isec)))
856 ctx.inputSections[n++] = isec;
858 // In -r links, SHF_LINK_ORDER sections are added while adding their parent
859 // sections because we need to know the parent's output section before we
860 // can select an output section for the SHF_LINK_ORDER section.
861 if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
862 continue;
864 if (auto *sec = dyn_cast<InputSection>(isec))
865 if (InputSectionBase *rel = sec->getRelocatedSection())
866 if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
867 add(relIS);
868 add(isec);
869 if (config->relocatable)
870 for (InputSectionBase *depSec : isec->dependentSections)
871 if (depSec->flags & SHF_LINK_ORDER)
872 add(depSec);
874 // Keep just InputSection.
875 ctx.inputSections.resize(n);
877 // If no SECTIONS command was given, we should insert sections commands
878 // before others, so that we can handle scripts which refers them,
879 // for example: "foo = ABSOLUTE(ADDR(.text)));".
880 // When SECTIONS command is present we just add all orphans to the end.
881 if (hasSectionsCommand)
882 sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
883 else
884 sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
887 void LinkerScript::diagnoseOrphanHandling() const {
888 llvm::TimeTraceScope timeScope("Diagnose orphan sections");
889 if (config->orphanHandling == OrphanHandlingPolicy::Place)
890 return;
891 for (const InputSectionBase *sec : orphanSections) {
892 // .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,
893 // automatically. The section is not supposed to be specified by scripts.
894 if (sec == in.relroPadding.get())
895 continue;
896 // Input SHT_REL[A] retained by --emit-relocs are ignored by
897 // computeInputSections(). Don't warn/error.
898 if (isa<InputSection>(sec) &&
899 cast<InputSection>(sec)->getRelocatedSection())
900 continue;
902 StringRef name = getOutputSectionName(sec);
903 if (config->orphanHandling == OrphanHandlingPolicy::Error)
904 error(toString(sec) + " is being placed in '" + name + "'");
905 else
906 warn(toString(sec) + " is being placed in '" + name + "'");
910 void LinkerScript::diagnoseMissingSGSectionAddress() const {
911 if (!config->cmseImplib || !in.armCmseSGSection->isNeeded())
912 return;
914 OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");
915 if (sec && !sec->addrExpr && !config->sectionStartMap.count(".gnu.sgstubs"))
916 error("no address assigned to the veneers output section " + sec->name);
919 // This function searches for a memory region to place the given output
920 // section in. If found, a pointer to the appropriate memory region is
921 // returned in the first member of the pair. Otherwise, a nullptr is returned.
922 // The second member of the pair is a hint that should be passed to the
923 // subsequent call of this method.
924 std::pair<MemoryRegion *, MemoryRegion *>
925 LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
926 // Non-allocatable sections are not part of the process image.
927 if (!(sec->flags & SHF_ALLOC)) {
928 bool hasInputOrByteCommand =
929 sec->hasInputSections ||
930 llvm::any_of(sec->commands, [](SectionCommand *comm) {
931 return ByteCommand::classof(comm);
933 if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)
934 warn("ignoring memory region assignment for non-allocatable section '" +
935 sec->name + "'");
936 return {nullptr, nullptr};
939 // If a memory region name was specified in the output section command,
940 // then try to find that region first.
941 if (!sec->memoryRegionName.empty()) {
942 if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
943 return {m, m};
944 error("memory region '" + sec->memoryRegionName + "' not declared");
945 return {nullptr, nullptr};
948 // If at least one memory region is defined, all sections must
949 // belong to some memory region. Otherwise, we don't need to do
950 // anything for memory regions.
951 if (memoryRegions.empty())
952 return {nullptr, nullptr};
954 // An orphan section should continue the previous memory region.
955 if (sec->sectionIndex == UINT32_MAX && hint)
956 return {hint, hint};
958 // See if a region can be found by matching section flags.
959 for (auto &pair : memoryRegions) {
960 MemoryRegion *m = pair.second;
961 if (m->compatibleWith(sec->flags))
962 return {m, nullptr};
965 // Otherwise, no suitable region was found.
966 error("no memory region specified for section '" + sec->name + "'");
967 return {nullptr, nullptr};
970 static OutputSection *findFirstSection(PhdrEntry *load) {
971 for (OutputSection *sec : outputSections)
972 if (sec->ptLoad == load)
973 return sec;
974 return nullptr;
977 // This function assigns offsets to input sections and an output section
978 // for a single sections command (e.g. ".text { *(.text); }").
979 void LinkerScript::assignOffsets(OutputSection *sec) {
980 const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
981 const bool sameMemRegion = state->memRegion == sec->memRegion;
982 const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;
983 const uint64_t savedDot = dot;
984 state->memRegion = sec->memRegion;
985 state->lmaRegion = sec->lmaRegion;
987 if (!(sec->flags & SHF_ALLOC)) {
988 // Non-SHF_ALLOC sections have zero addresses.
989 dot = 0;
990 } else if (isTbss) {
991 // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range
992 // starts from the end address of the previous tbss section.
993 if (state->tbssAddr == 0)
994 state->tbssAddr = dot;
995 else
996 dot = state->tbssAddr;
997 } else {
998 if (state->memRegion)
999 dot = state->memRegion->curPos;
1000 if (sec->addrExpr)
1001 setDot(sec->addrExpr, sec->location, false);
1003 // If the address of the section has been moved forward by an explicit
1004 // expression so that it now starts past the current curPos of the enclosing
1005 // region, we need to expand the current region to account for the space
1006 // between the previous section, if any, and the start of this section.
1007 if (state->memRegion && state->memRegion->curPos < dot)
1008 expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,
1009 sec->name);
1012 state->outSec = sec;
1013 if (sec->addrExpr && script->hasSectionsCommand) {
1014 // The alignment is ignored.
1015 sec->addr = dot;
1016 } else {
1017 // sec->alignment is the max of ALIGN and the maximum of input
1018 // section alignments.
1019 const uint64_t pos = dot;
1020 dot = alignToPowerOf2(dot, sec->addralign);
1021 sec->addr = dot;
1022 expandMemoryRegions(dot - pos);
1025 // state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()
1026 // or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA
1027 // region is the default, and the two sections are in the same memory region,
1028 // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
1029 // heuristics described in
1030 // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
1031 if (sec->lmaExpr) {
1032 state->lmaOffset = sec->lmaExpr().getValue() - dot;
1033 } else if (MemoryRegion *mr = sec->lmaRegion) {
1034 uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);
1035 if (mr->curPos < lmaStart)
1036 expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);
1037 state->lmaOffset = lmaStart - dot;
1038 } else if (!sameMemRegion || !prevLMARegionIsDefault) {
1039 state->lmaOffset = 0;
1042 // Propagate state->lmaOffset to the first "non-header" section.
1043 if (PhdrEntry *l = sec->ptLoad)
1044 if (sec == findFirstSection(l))
1045 l->lmaOffset = state->lmaOffset;
1047 // We can call this method multiple times during the creation of
1048 // thunks and want to start over calculation each time.
1049 sec->size = 0;
1051 // We visited SectionsCommands from processSectionCommands to
1052 // layout sections. Now, we visit SectionsCommands again to fix
1053 // section offsets.
1054 for (SectionCommand *cmd : sec->commands) {
1055 // This handles the assignments to symbol or to the dot.
1056 if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
1057 assign->addr = dot;
1058 assignSymbol(assign, true);
1059 assign->size = dot - assign->addr;
1060 continue;
1063 // Handle BYTE(), SHORT(), LONG(), or QUAD().
1064 if (auto *data = dyn_cast<ByteCommand>(cmd)) {
1065 data->offset = dot - sec->addr;
1066 dot += data->size;
1067 expandOutputSection(data->size);
1068 continue;
1071 // Handle a single input section description command.
1072 // It calculates and assigns the offsets for each section and also
1073 // updates the output section size.
1074 for (InputSection *isec : cast<InputSectionDescription>(cmd)->sections) {
1075 assert(isec->getParent() == sec);
1076 const uint64_t pos = dot;
1077 dot = alignToPowerOf2(dot, isec->addralign);
1078 isec->outSecOff = dot - sec->addr;
1079 dot += isec->getSize();
1081 // Update output section size after adding each section. This is so that
1082 // SIZEOF works correctly in the case below:
1083 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
1084 expandOutputSection(dot - pos);
1088 // If .relro_padding is present, round up the end to a common-page-size
1089 // boundary to protect the last page.
1090 if (in.relroPadding && sec == in.relroPadding->getParent())
1091 expandOutputSection(alignToPowerOf2(dot, config->commonPageSize) - dot);
1093 // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
1094 // as they are not part of the process image.
1095 if (!(sec->flags & SHF_ALLOC)) {
1096 dot = savedDot;
1097 } else if (isTbss) {
1098 // NOBITS TLS sections are similar. Additionally save the end address.
1099 state->tbssAddr = dot;
1100 dot = savedDot;
1104 static bool isDiscardable(const OutputSection &sec) {
1105 if (sec.name == "/DISCARD/")
1106 return true;
1108 // We do not want to remove OutputSections with expressions that reference
1109 // symbols even if the OutputSection is empty. We want to ensure that the
1110 // expressions can be evaluated and report an error if they cannot.
1111 if (sec.expressionsUseSymbols)
1112 return false;
1114 // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
1115 // as an empty Section can has a valid VMA and LMA we keep the OutputSection
1116 // to maintain the integrity of the other Expression.
1117 if (sec.usedInExpression)
1118 return false;
1120 for (SectionCommand *cmd : sec.commands) {
1121 if (auto assign = dyn_cast<SymbolAssignment>(cmd))
1122 // Don't create empty output sections just for unreferenced PROVIDE
1123 // symbols.
1124 if (assign->name != "." && !assign->sym)
1125 continue;
1127 if (!isa<InputSectionDescription>(*cmd))
1128 return false;
1130 return true;
1133 bool LinkerScript::isDiscarded(const OutputSection *sec) const {
1134 return hasSectionsCommand && (getFirstInputSection(sec) == nullptr) &&
1135 isDiscardable(*sec);
1138 static void maybePropagatePhdrs(OutputSection &sec,
1139 SmallVector<StringRef, 0> &phdrs) {
1140 if (sec.phdrs.empty()) {
1141 // To match the bfd linker script behaviour, only propagate program
1142 // headers to sections that are allocated.
1143 if (sec.flags & SHF_ALLOC)
1144 sec.phdrs = phdrs;
1145 } else {
1146 phdrs = sec.phdrs;
1150 void LinkerScript::adjustOutputSections() {
1151 // If the output section contains only symbol assignments, create a
1152 // corresponding output section. The issue is what to do with linker script
1153 // like ".foo : { symbol = 42; }". One option would be to convert it to
1154 // "symbol = 42;". That is, move the symbol out of the empty section
1155 // description. That seems to be what bfd does for this simple case. The
1156 // problem is that this is not completely general. bfd will give up and
1157 // create a dummy section too if there is a ". = . + 1" inside the section
1158 // for example.
1159 // Given that we want to create the section, we have to worry what impact
1160 // it will have on the link. For example, if we just create a section with
1161 // 0 for flags, it would change which PT_LOADs are created.
1162 // We could remember that particular section is dummy and ignore it in
1163 // other parts of the linker, but unfortunately there are quite a few places
1164 // that would need to change:
1165 // * The program header creation.
1166 // * The orphan section placement.
1167 // * The address assignment.
1168 // The other option is to pick flags that minimize the impact the section
1169 // will have on the rest of the linker. That is why we copy the flags from
1170 // the previous sections. Only a few flags are needed to keep the impact low.
1171 uint64_t flags = SHF_ALLOC;
1173 SmallVector<StringRef, 0> defPhdrs;
1174 bool seenRelro = false;
1175 for (SectionCommand *&cmd : sectionCommands) {
1176 if (!isa<OutputDesc>(cmd))
1177 continue;
1178 auto *sec = &cast<OutputDesc>(cmd)->osec;
1180 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
1181 if (sec->alignExpr)
1182 sec->addralign =
1183 std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());
1185 bool isEmpty = (getFirstInputSection(sec) == nullptr);
1186 bool discardable = isEmpty && isDiscardable(*sec);
1187 // If sec has at least one input section and not discarded, remember its
1188 // flags to be inherited by subsequent output sections. (sec may contain
1189 // just one empty synthetic section.)
1190 if (sec->hasInputSections && !discardable)
1191 flags = sec->flags;
1193 // We do not want to keep any special flags for output section
1194 // in case it is empty.
1195 if (isEmpty)
1196 sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
1197 SHF_WRITE | SHF_EXECINSTR);
1199 // The code below may remove empty output sections. We should save the
1200 // specified program headers (if exist) and propagate them to subsequent
1201 // sections which do not specify program headers.
1202 // An example of such a linker script is:
1203 // SECTIONS { .empty : { *(.empty) } :rw
1204 // .foo : { *(.foo) } }
1205 // Note: at this point the order of output sections has not been finalized,
1206 // because orphans have not been inserted into their expected positions. We
1207 // will handle them in adjustSectionsAfterSorting().
1208 if (sec->sectionIndex != UINT32_MAX)
1209 maybePropagatePhdrs(*sec, defPhdrs);
1211 // Discard .relro_padding if we have not seen one RELRO section. Note: when
1212 // .tbss is the only RELRO section, there is no associated PT_LOAD segment
1213 // (needsPtLoad), so we don't append .relro_padding in the case.
1214 if (in.relroPadding && in.relroPadding->getParent() == sec && !seenRelro)
1215 discardable = true;
1216 if (discardable) {
1217 sec->markDead();
1218 cmd = nullptr;
1219 } else {
1220 seenRelro |=
1221 sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));
1225 // It is common practice to use very generic linker scripts. So for any
1226 // given run some of the output sections in the script will be empty.
1227 // We could create corresponding empty output sections, but that would
1228 // clutter the output.
1229 // We instead remove trivially empty sections. The bfd linker seems even
1230 // more aggressive at removing them.
1231 llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });
1234 void LinkerScript::adjustSectionsAfterSorting() {
1235 // Try and find an appropriate memory region to assign offsets in.
1236 MemoryRegion *hint = nullptr;
1237 for (SectionCommand *cmd : sectionCommands) {
1238 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1239 OutputSection *sec = &osd->osec;
1240 if (!sec->lmaRegionName.empty()) {
1241 if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
1242 sec->lmaRegion = m;
1243 else
1244 error("memory region '" + sec->lmaRegionName + "' not declared");
1246 std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);
1250 // If output section command doesn't specify any segments,
1251 // and we haven't previously assigned any section to segment,
1252 // then we simply assign section to the very first load segment.
1253 // Below is an example of such linker script:
1254 // PHDRS { seg PT_LOAD; }
1255 // SECTIONS { .aaa : { *(.aaa) } }
1256 SmallVector<StringRef, 0> defPhdrs;
1257 auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
1258 return cmd.type == PT_LOAD;
1260 if (firstPtLoad != phdrsCommands.end())
1261 defPhdrs.push_back(firstPtLoad->name);
1263 // Walk the commands and propagate the program headers to commands that don't
1264 // explicitly specify them.
1265 for (SectionCommand *cmd : sectionCommands)
1266 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1267 maybePropagatePhdrs(osd->osec, defPhdrs);
1270 static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
1271 // If there is no SECTIONS or if the linkerscript is explicit about program
1272 // headers, do our best to allocate them.
1273 if (!script->hasSectionsCommand || allocateHeaders)
1274 return 0;
1275 // Otherwise only allocate program headers if that would not add a page.
1276 return alignDown(min, config->maxPageSize);
1279 // When the SECTIONS command is used, try to find an address for the file and
1280 // program headers output sections, which can be added to the first PT_LOAD
1281 // segment when program headers are created.
1283 // We check if the headers fit below the first allocated section. If there isn't
1284 // enough space for these sections, we'll remove them from the PT_LOAD segment,
1285 // and we'll also remove the PT_PHDR segment.
1286 void LinkerScript::allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs) {
1287 uint64_t min = std::numeric_limits<uint64_t>::max();
1288 for (OutputSection *sec : outputSections)
1289 if (sec->flags & SHF_ALLOC)
1290 min = std::min<uint64_t>(min, sec->addr);
1292 auto it = llvm::find_if(
1293 phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
1294 if (it == phdrs.end())
1295 return;
1296 PhdrEntry *firstPTLoad = *it;
1298 bool hasExplicitHeaders =
1299 llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
1300 return cmd.hasPhdrs || cmd.hasFilehdr;
1302 bool paged = !config->omagic && !config->nmagic;
1303 uint64_t headerSize = getHeaderSize();
1304 if ((paged || hasExplicitHeaders) &&
1305 headerSize <= min - computeBase(min, hasExplicitHeaders)) {
1306 min = alignDown(min - headerSize, config->maxPageSize);
1307 Out::elfHeader->addr = min;
1308 Out::programHeaders->addr = min + Out::elfHeader->size;
1309 return;
1312 // Error if we were explicitly asked to allocate headers.
1313 if (hasExplicitHeaders)
1314 error("could not allocate headers");
1316 Out::elfHeader->ptLoad = nullptr;
1317 Out::programHeaders->ptLoad = nullptr;
1318 firstPTLoad->firstSec = findFirstSection(firstPTLoad);
1320 llvm::erase_if(phdrs,
1321 [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
1324 LinkerScript::AddressState::AddressState() {
1325 for (auto &mri : script->memoryRegions) {
1326 MemoryRegion *mr = mri.second;
1327 mr->curPos = (mr->origin)().getValue();
1331 // Here we assign addresses as instructed by linker script SECTIONS
1332 // sub-commands. Doing that allows us to use final VA values, so here
1333 // we also handle rest commands like symbol assignments and ASSERTs.
1334 // Returns a symbol that has changed its section or value, or nullptr if no
1335 // symbol has changed.
1336 const Defined *LinkerScript::assignAddresses() {
1337 if (script->hasSectionsCommand) {
1338 // With a linker script, assignment of addresses to headers is covered by
1339 // allocateHeaders().
1340 dot = config->imageBase.value_or(0);
1341 } else {
1342 // Assign addresses to headers right now.
1343 dot = target->getImageBase();
1344 Out::elfHeader->addr = dot;
1345 Out::programHeaders->addr = dot + Out::elfHeader->size;
1346 dot += getHeaderSize();
1349 AddressState st;
1350 state = &st;
1351 errorOnMissingSection = true;
1352 st.outSec = aether;
1353 backwardDotErr.clear();
1355 SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
1356 for (SectionCommand *cmd : sectionCommands) {
1357 if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
1358 assign->addr = dot;
1359 assignSymbol(assign, false);
1360 assign->size = dot - assign->addr;
1361 continue;
1363 assignOffsets(&cast<OutputDesc>(cmd)->osec);
1366 state = nullptr;
1367 return getChangedSymbolAssignment(oldValues);
1370 // Creates program headers as instructed by PHDRS linker script command.
1371 SmallVector<PhdrEntry *, 0> LinkerScript::createPhdrs() {
1372 SmallVector<PhdrEntry *, 0> ret;
1374 // Process PHDRS and FILEHDR keywords because they are not
1375 // real output sections and cannot be added in the following loop.
1376 for (const PhdrsCommand &cmd : phdrsCommands) {
1377 PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags.value_or(PF_R));
1379 if (cmd.hasFilehdr)
1380 phdr->add(Out::elfHeader);
1381 if (cmd.hasPhdrs)
1382 phdr->add(Out::programHeaders);
1384 if (cmd.lmaExpr) {
1385 phdr->p_paddr = cmd.lmaExpr().getValue();
1386 phdr->hasLMA = true;
1388 ret.push_back(phdr);
1391 // Add output sections to program headers.
1392 for (OutputSection *sec : outputSections) {
1393 // Assign headers specified by linker script
1394 for (size_t id : getPhdrIndices(sec)) {
1395 ret[id]->add(sec);
1396 if (!phdrsCommands[id].flags)
1397 ret[id]->p_flags |= sec->getPhdrFlags();
1400 return ret;
1403 // Returns true if we should emit an .interp section.
1405 // We usually do. But if PHDRS commands are given, and
1406 // no PT_INTERP is there, there's no place to emit an
1407 // .interp, so we don't do that in that case.
1408 bool LinkerScript::needsInterpSection() {
1409 if (phdrsCommands.empty())
1410 return true;
1411 for (PhdrsCommand &cmd : phdrsCommands)
1412 if (cmd.type == PT_INTERP)
1413 return true;
1414 return false;
1417 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
1418 if (name == ".") {
1419 if (state)
1420 return {state->outSec, false, dot - state->outSec->addr, loc};
1421 error(loc + ": unable to get location counter value");
1422 return 0;
1425 if (Symbol *sym = symtab.find(name)) {
1426 if (auto *ds = dyn_cast<Defined>(sym)) {
1427 ExprValue v{ds->section, false, ds->value, loc};
1428 // Retain the original st_type, so that the alias will get the same
1429 // behavior in relocation processing. Any operation will reset st_type to
1430 // STT_NOTYPE.
1431 v.type = ds->type;
1432 return v;
1434 if (isa<SharedSymbol>(sym))
1435 if (!errorOnMissingSection)
1436 return {nullptr, false, 0, loc};
1439 error(loc + ": symbol not found: " + name);
1440 return 0;
1443 // Returns the index of the segment named Name.
1444 static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
1445 StringRef name) {
1446 for (size_t i = 0; i < vec.size(); ++i)
1447 if (vec[i].name == name)
1448 return i;
1449 return std::nullopt;
1452 // Returns indices of ELF headers containing specific section. Each index is a
1453 // zero based number of ELF header listed within PHDRS {} script block.
1454 SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1455 SmallVector<size_t, 0> ret;
1457 for (StringRef s : cmd->phdrs) {
1458 if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
1459 ret.push_back(*idx);
1460 else if (s != "NONE")
1461 error(cmd->location + ": program header '" + s +
1462 "' is not listed in PHDRS");
1464 return ret;
1467 void LinkerScript::printMemoryUsage(raw_ostream& os) {
1468 auto printSize = [&](uint64_t size) {
1469 if ((size & 0x3fffffff) == 0)
1470 os << format_decimal(size >> 30, 10) << " GB";
1471 else if ((size & 0xfffff) == 0)
1472 os << format_decimal(size >> 20, 10) << " MB";
1473 else if ((size & 0x3ff) == 0)
1474 os << format_decimal(size >> 10, 10) << " KB";
1475 else
1476 os << " " << format_decimal(size, 10) << " B";
1478 os << "Memory region Used Size Region Size %age Used\n";
1479 for (auto &pair : memoryRegions) {
1480 MemoryRegion *m = pair.second;
1481 uint64_t usedLength = m->curPos - m->getOrigin();
1482 os << right_justify(m->name, 16) << ": ";
1483 printSize(usedLength);
1484 uint64_t length = m->getLength();
1485 if (length != 0) {
1486 printSize(length);
1487 double percent = usedLength * 100.0 / length;
1488 os << " " << format("%6.2f%%", percent);
1490 os << '\n';
1494 static void checkMemoryRegion(const MemoryRegion *region,
1495 const OutputSection *osec, uint64_t addr) {
1496 uint64_t osecEnd = addr + osec->size;
1497 uint64_t regionEnd = region->getOrigin() + region->getLength();
1498 if (osecEnd > regionEnd) {
1499 error("section '" + osec->name + "' will not fit in region '" +
1500 region->name + "': overflowed by " + Twine(osecEnd - regionEnd) +
1501 " bytes");
1505 void LinkerScript::checkFinalScriptConditions() const {
1506 if (backwardDotErr.size())
1507 errorOrWarn(backwardDotErr);
1508 for (const OutputSection *sec : outputSections) {
1509 if (const MemoryRegion *memoryRegion = sec->memRegion)
1510 checkMemoryRegion(memoryRegion, sec, sec->addr);
1511 if (const MemoryRegion *lmaRegion = sec->lmaRegion)
1512 checkMemoryRegion(lmaRegion, sec, sec->getLMA());