Path: blob/main/contrib/llvm-project/lld/ELF/LinkerScript.cpp
34869 views
//===- LinkerScript.cpp ---------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains the parser/evaluator of the linker script.9//10//===----------------------------------------------------------------------===//1112#include "LinkerScript.h"13#include "Config.h"14#include "InputFiles.h"15#include "InputSection.h"16#include "OutputSections.h"17#include "SymbolTable.h"18#include "Symbols.h"19#include "SyntheticSections.h"20#include "Target.h"21#include "Writer.h"22#include "lld/Common/CommonLinkerContext.h"23#include "lld/Common/Strings.h"24#include "llvm/ADT/STLExtras.h"25#include "llvm/ADT/StringRef.h"26#include "llvm/BinaryFormat/ELF.h"27#include "llvm/Support/Casting.h"28#include "llvm/Support/Endian.h"29#include "llvm/Support/ErrorHandling.h"30#include "llvm/Support/TimeProfiler.h"31#include <algorithm>32#include <cassert>33#include <cstddef>34#include <cstdint>35#include <limits>36#include <string>37#include <vector>3839using namespace llvm;40using namespace llvm::ELF;41using namespace llvm::object;42using namespace llvm::support::endian;43using namespace lld;44using namespace lld::elf;4546ScriptWrapper elf::script;4748static bool isSectionPrefix(StringRef prefix, StringRef name) {49return name.consume_front(prefix) && (name.empty() || name[0] == '.');50}5152static StringRef getOutputSectionName(const InputSectionBase *s) {53// This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we54// want to emit .rela.text.foo as .rela.text.bar for consistency (this is not55// technically required, but not doing it is odd). This code guarantees that.56if (auto *isec = dyn_cast<InputSection>(s)) {57if (InputSectionBase *rel = isec->getRelocatedSection()) {58OutputSection *out = rel->getOutputSection();59if (!out) {60assert(config->relocatable && (rel->flags & SHF_LINK_ORDER));61return s->name;62}63if (s->type == SHT_CREL)64return saver().save(".crel" + out->name);65if (s->type == SHT_RELA)66return saver().save(".rela" + out->name);67return saver().save(".rel" + out->name);68}69}7071if (config->relocatable)72return s->name;7374// A BssSection created for a common symbol is identified as "COMMON" in75// linker scripts. It should go to .bss section.76if (s->name == "COMMON")77return ".bss";7879if (script->hasSectionsCommand)80return s->name;8182// When no SECTIONS is specified, emulate GNU ld's internal linker scripts83// by grouping sections with certain prefixes.8485// 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 sections88// into separate output sections. This is more flexible. See also89// sortISDBySectionOrder().90// ".text.unknown" means the hotness of the section is unknown. When91// SampleFDO is used, if a function doesn't have sample, it could be very92// cold or it could be a new function never being sampled. Those functions93// will be kept in the ".text.unknown" section.94// ".text.split." holds symbols which are split out from functions in other95// input sections. For example, with -fsplit-machine-functions, placing the96// cold parts in .text.split instead of .text.unlikely mitigates against poor97// profile inaccuracy. Techniques such as hugepage remapping can make98// conservative decisions at the section granularity.99if (isSectionPrefix(".text", s->name)) {100if (config->zKeepTextSectionPrefix)101for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",102".text.startup", ".text.exit", ".text.split"})103if (isSectionPrefix(v.substr(5), s->name.substr(5)))104return v;105return ".text";106}107108for (StringRef v :109{".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss", ".ldata",110".lrodata", ".lbss", ".gcc_except_table", ".init_array", ".fini_array",111".tbss", ".tdata", ".ARM.exidx", ".ARM.extab", ".ctors", ".dtors"})112if (isSectionPrefix(v, s->name))113return v;114115return s->name;116}117118uint64_t ExprValue::getValue() const {119if (sec)120return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),121alignment);122return alignToPowerOf2(val, alignment);123}124125uint64_t ExprValue::getSecAddr() const {126return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;127}128129uint64_t ExprValue::getSectionOffset() const {130return getValue() - getSecAddr();131}132133OutputDesc *LinkerScript::createOutputSection(StringRef name,134StringRef location) {135OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];136OutputDesc *sec;137if (secRef && secRef->osec.location.empty()) {138// There was a forward reference.139sec = secRef;140} else {141sec = make<OutputDesc>(name, SHT_PROGBITS, 0);142if (!secRef)143secRef = sec;144}145sec->osec.location = std::string(location);146return sec;147}148149OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {150OutputDesc *&cmdRef = nameToOutputSection[CachedHashStringRef(name)];151if (!cmdRef)152cmdRef = make<OutputDesc>(name, SHT_PROGBITS, 0);153return cmdRef;154}155156// Expands the memory region by the specified size.157static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,158StringRef secName) {159memRegion->curPos += size;160}161162void LinkerScript::expandMemoryRegions(uint64_t size) {163if (state->memRegion)164expandMemoryRegion(state->memRegion, size, state->outSec->name);165// Only expand the LMARegion if it is different from memRegion.166if (state->lmaRegion && state->memRegion != state->lmaRegion)167expandMemoryRegion(state->lmaRegion, size, state->outSec->name);168}169170void LinkerScript::expandOutputSection(uint64_t size) {171state->outSec->size += size;172expandMemoryRegions(size);173}174175void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {176uint64_t val = e().getValue();177// If val is smaller and we are in an output section, record the error and178// report it if this is the last assignAddresses iteration. dot may be smaller179// if there is another assignAddresses iteration.180if (val < dot && inSec) {181recordError(loc + ": unable to move location counter (0x" +182Twine::utohexstr(dot) + ") backward to 0x" +183Twine::utohexstr(val) + " for section '" + state->outSec->name +184"'");185}186187// Update to location counter means update to section size.188if (inSec)189expandOutputSection(val - dot);190191dot = val;192}193194// Used for handling linker symbol assignments, for both finalizing195// their values and doing early declarations. Returns true if symbol196// should be defined from linker script.197static bool shouldDefineSym(SymbolAssignment *cmd) {198if (cmd->name == ".")199return false;200201return !cmd->provide || LinkerScript::shouldAddProvideSym(cmd->name);202}203204// Called by processSymbolAssignments() to assign definitions to205// linker-script-defined symbols.206void LinkerScript::addSymbol(SymbolAssignment *cmd) {207if (!shouldDefineSym(cmd))208return;209210// Define a symbol.211ExprValue value = cmd->expression();212SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;213uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;214215// When this function is called, section addresses have not been216// fixed yet. So, we may or may not know the value of the RHS217// expression.218//219// For example, if an expression is `x = 42`, we know x is always 42.220// However, if an expression is `x = .`, there's no way to know its221// value at the moment.222//223// We want to set symbol values early if we can. This allows us to224// use symbols as variables in linker scripts. Doing so allows us to225// write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.226uint64_t symValue = value.sec ? 0 : value.getValue();227228Defined newSym(createInternalFile(cmd->location), cmd->name, STB_GLOBAL,229visibility, value.type, symValue, 0, sec);230231Symbol *sym = symtab.insert(cmd->name);232sym->mergeProperties(newSym);233newSym.overwrite(*sym);234sym->isUsedInRegularObj = true;235cmd->sym = cast<Defined>(sym);236}237238// This function is called from LinkerScript::declareSymbols.239// It creates a placeholder symbol if needed.240static void declareSymbol(SymbolAssignment *cmd) {241if (!shouldDefineSym(cmd))242return;243244uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;245Defined newSym(ctx.internalFile, cmd->name, STB_GLOBAL, visibility,246STT_NOTYPE, 0, 0, nullptr);247248// If the symbol is already defined, its order is 0 (with absence indicating249// 0); otherwise it's assigned the order of the SymbolAssignment.250Symbol *sym = symtab.insert(cmd->name);251if (!sym->isDefined())252ctx.scriptSymOrder.insert({sym, cmd->symOrder});253254// We can't calculate final value right now.255sym->mergeProperties(newSym);256newSym.overwrite(*sym);257258cmd->sym = cast<Defined>(sym);259cmd->provide = false;260sym->isUsedInRegularObj = true;261sym->scriptDefined = true;262}263264using SymbolAssignmentMap =265DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;266267// Collect section/value pairs of linker-script-defined symbols. This is used to268// check whether symbol values converge.269static SymbolAssignmentMap270getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {271SymbolAssignmentMap ret;272for (SectionCommand *cmd : sectionCommands) {273if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {274if (assign->sym) // sym is nullptr for dot.275ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,276assign->sym->value));277continue;278}279for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)280if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))281if (assign->sym)282ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,283assign->sym->value));284}285return ret;286}287288// Returns the lexicographical smallest (for determinism) Defined whose289// section/value has changed.290static const Defined *291getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {292const Defined *changed = nullptr;293for (auto &it : oldValues) {294const Defined *sym = it.first;295if (std::make_pair(sym->section, sym->value) != it.second &&296(!changed || sym->getName() < changed->getName()))297changed = sym;298}299return changed;300}301302// Process INSERT [AFTER|BEFORE] commands. For each command, we move the303// specified output section to the designated place.304void LinkerScript::processInsertCommands() {305SmallVector<OutputDesc *, 0> moves;306for (const InsertCommand &cmd : insertCommands) {307if (config->enableNonContiguousRegions)308error("INSERT cannot be used with --enable-non-contiguous-regions");309310for (StringRef name : cmd.names) {311// If base is empty, it may have been discarded by312// adjustOutputSections(). We do not handle such output sections.313auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {314return isa<OutputDesc>(subCmd) &&315cast<OutputDesc>(subCmd)->osec.name == name;316});317if (from == sectionCommands.end())318continue;319moves.push_back(cast<OutputDesc>(*from));320sectionCommands.erase(from);321}322323auto insertPos =324llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {325auto *to = dyn_cast<OutputDesc>(subCmd);326return to != nullptr && to->osec.name == cmd.where;327});328if (insertPos == sectionCommands.end()) {329error("unable to insert " + cmd.names[0] +330(cmd.isAfter ? " after " : " before ") + cmd.where);331} else {332if (cmd.isAfter)333++insertPos;334sectionCommands.insert(insertPos, moves.begin(), moves.end());335}336moves.clear();337}338}339340// Symbols defined in script should not be inlined by LTO. At the same time341// we don't know their final values until late stages of link. Here we scan342// over symbol assignment commands and create placeholder symbols if needed.343void LinkerScript::declareSymbols() {344assert(!state);345for (SectionCommand *cmd : sectionCommands) {346if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {347declareSymbol(assign);348continue;349}350351// If the output section directive has constraints,352// we can't say for sure if it is going to be included or not.353// Skip such sections for now. Improve the checks if we ever354// need symbols from that sections to be declared early.355const OutputSection &sec = cast<OutputDesc>(cmd)->osec;356if (sec.constraint != ConstraintKind::NoConstraint)357continue;358for (SectionCommand *cmd : sec.commands)359if (auto *assign = dyn_cast<SymbolAssignment>(cmd))360declareSymbol(assign);361}362}363364// This function is called from assignAddresses, while we are365// fixing the output section addresses. This function is supposed366// to set the final value for a given symbol assignment.367void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {368if (cmd->name == ".") {369setDot(cmd->expression, cmd->location, inSec);370return;371}372373if (!cmd->sym)374return;375376ExprValue v = cmd->expression();377if (v.isAbsolute()) {378cmd->sym->section = nullptr;379cmd->sym->value = v.getValue();380} else {381cmd->sym->section = v.sec;382cmd->sym->value = v.getSectionOffset();383}384cmd->sym->type = v.type;385}386387static inline StringRef getFilename(const InputFile *file) {388return file ? file->getNameForScript() : StringRef();389}390391bool InputSectionDescription::matchesFile(const InputFile *file) const {392if (filePat.isTrivialMatchAll())393return true;394395if (!matchesFileCache || matchesFileCache->first != file)396matchesFileCache.emplace(file, filePat.match(getFilename(file)));397398return matchesFileCache->second;399}400401bool SectionPattern::excludesFile(const InputFile *file) const {402if (excludedFilePat.empty())403return false;404405if (!excludesFileCache || excludesFileCache->first != file)406excludesFileCache.emplace(file, excludedFilePat.match(getFilename(file)));407408return excludesFileCache->second;409}410411bool LinkerScript::shouldKeep(InputSectionBase *s) {412for (InputSectionDescription *id : keptSections)413if (id->matchesFile(s->file))414for (SectionPattern &p : id->sectionPatterns)415if (p.sectionPat.match(s->name) &&416(s->flags & id->withFlags) == id->withFlags &&417(s->flags & id->withoutFlags) == 0)418return true;419return false;420}421422// A helper function for the SORT() command.423static bool matchConstraints(ArrayRef<InputSectionBase *> sections,424ConstraintKind kind) {425if (kind == ConstraintKind::NoConstraint)426return true;427428bool isRW = llvm::any_of(429sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });430431return (isRW && kind == ConstraintKind::ReadWrite) ||432(!isRW && kind == ConstraintKind::ReadOnly);433}434435static void sortSections(MutableArrayRef<InputSectionBase *> vec,436SortSectionPolicy k) {437auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {438// ">" is not a mistake. Sections with larger alignments are placed439// before sections with smaller alignments in order to reduce the440// amount of padding necessary. This is compatible with GNU.441return a->addralign > b->addralign;442};443auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {444return a->name < b->name;445};446auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {447return getPriority(a->name) < getPriority(b->name);448};449450switch (k) {451case SortSectionPolicy::Default:452case SortSectionPolicy::None:453return;454case SortSectionPolicy::Alignment:455return llvm::stable_sort(vec, alignmentComparator);456case SortSectionPolicy::Name:457return llvm::stable_sort(vec, nameComparator);458case SortSectionPolicy::Priority:459return llvm::stable_sort(vec, priorityComparator);460case SortSectionPolicy::Reverse:461return std::reverse(vec.begin(), vec.end());462}463}464465// Sort sections as instructed by SORT-family commands and --sort-section466// option. Because SORT-family commands can be nested at most two depth467// (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command468// line option is respected even if a SORT command is given, the exact469// behavior we have here is a bit complicated. Here are the rules.470//471// 1. If two SORT commands are given, --sort-section is ignored.472// 2. If one SORT command is given, and if it is not SORT_NONE,473// --sort-section is handled as an inner SORT command.474// 3. If one SORT command is given, and if it is SORT_NONE, don't sort.475// 4. If no SORT command is given, sort according to --sort-section.476static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,477SortSectionPolicy outer,478SortSectionPolicy inner) {479if (outer == SortSectionPolicy::None)480return;481482if (inner == SortSectionPolicy::Default)483sortSections(vec, config->sortSection);484else485sortSections(vec, inner);486sortSections(vec, outer);487}488489// Compute and remember which sections the InputSectionDescription matches.490SmallVector<InputSectionBase *, 0>491LinkerScript::computeInputSections(const InputSectionDescription *cmd,492ArrayRef<InputSectionBase *> sections,493const OutputSection &outCmd) {494SmallVector<InputSectionBase *, 0> ret;495SmallVector<size_t, 0> indexes;496DenseSet<size_t> seen;497DenseSet<InputSectionBase *> spills;498auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {499llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));500for (size_t i = begin; i != end; ++i)501ret[i] = sections[indexes[i]];502sortInputSections(503MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),504config->sortSection, SortSectionPolicy::None);505};506507// Collects all sections that satisfy constraints of Cmd.508size_t sizeAfterPrevSort = 0;509for (const SectionPattern &pat : cmd->sectionPatterns) {510size_t sizeBeforeCurrPat = ret.size();511512for (size_t i = 0, e = sections.size(); i != e; ++i) {513// Skip if the section is dead or has been matched by a previous pattern514// in this input section description.515InputSectionBase *sec = sections[i];516if (!sec->isLive() || seen.contains(i))517continue;518519// For --emit-relocs we have to ignore entries like520// .rela.dyn : { *(.rela.data) }521// which are common because they are in the default bfd script.522// We do not ignore SHT_REL[A] linker-synthesized sections here because523// want to support scripts that do custom layout for them.524if (isa<InputSection>(sec) &&525cast<InputSection>(sec)->getRelocatedSection())526continue;527528// Check the name early to improve performance in the common case.529if (!pat.sectionPat.match(sec->name))530continue;531532if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||533(sec->flags & cmd->withFlags) != cmd->withFlags ||534(sec->flags & cmd->withoutFlags) != 0)535continue;536537if (sec->parent) {538// Skip if not allowing multiple matches.539if (!config->enableNonContiguousRegions)540continue;541542// Disallow spilling into /DISCARD/; special handling would be needed543// for this in address assignment, and the semantics are nebulous.544if (outCmd.name == "/DISCARD/")545continue;546547// Skip if the section's first match was /DISCARD/; such sections are548// always discarded.549if (sec->parent->name == "/DISCARD/")550continue;551552// Skip if the section was already matched by a different input section553// description within this output section.554if (sec->parent == &outCmd)555continue;556557spills.insert(sec);558}559560ret.push_back(sec);561indexes.push_back(i);562seen.insert(i);563}564565if (pat.sortOuter == SortSectionPolicy::Default)566continue;567568// Matched sections are ordered by radix sort with the keys being (SORT*,569// --sort-section, input order), where SORT* (if present) is most570// significant.571//572// Matched sections between the previous SORT* and this SORT* are sorted by573// (--sort-alignment, input order).574sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);575// Matched sections by this SORT* pattern are sorted using all 3 keys.576// ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we577// just sort by sortOuter and sortInner.578sortInputSections(579MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),580pat.sortOuter, pat.sortInner);581sizeAfterPrevSort = ret.size();582}583// Matched sections after the last SORT* are sorted by (--sort-alignment,584// input order).585sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());586587// The flag --enable-non-contiguous-regions may cause sections to match an588// InputSectionDescription in more than one OutputSection. Matches after the589// first were collected in the spills set, so replace these with potential590// spill sections.591if (!spills.empty()) {592for (InputSectionBase *&sec : ret) {593if (!spills.contains(sec))594continue;595596// Append the spill input section to the list for the input section,597// creating it if necessary.598PotentialSpillSection *pss = make<PotentialSpillSection>(599*sec, const_cast<InputSectionDescription &>(*cmd));600auto [it, inserted] =601potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});602if (!inserted) {603PotentialSpillSection *&tail = it->second.tail;604tail = tail->next = pss;605}606sec = pss;607}608}609610return ret;611}612613void LinkerScript::discard(InputSectionBase &s) {614if (&s == in.shStrTab.get())615error("discarding " + s.name + " section is not allowed");616617s.markDead();618s.parent = nullptr;619for (InputSection *sec : s.dependentSections)620discard(*sec);621}622623void LinkerScript::discardSynthetic(OutputSection &outCmd) {624for (Partition &part : partitions) {625if (!part.armExidx || !part.armExidx->isLive())626continue;627SmallVector<InputSectionBase *, 0> secs(628part.armExidx->exidxSections.begin(),629part.armExidx->exidxSections.end());630for (SectionCommand *cmd : outCmd.commands)631if (auto *isd = dyn_cast<InputSectionDescription>(cmd))632for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))633discard(*s);634}635}636637SmallVector<InputSectionBase *, 0>638LinkerScript::createInputSectionList(OutputSection &outCmd) {639SmallVector<InputSectionBase *, 0> ret;640641for (SectionCommand *cmd : outCmd.commands) {642if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {643isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);644for (InputSectionBase *s : isd->sectionBases)645s->parent = &outCmd;646ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());647}648}649return ret;650}651652// Create output sections described by SECTIONS commands.653void LinkerScript::processSectionCommands() {654auto process = [this](OutputSection *osec) {655SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);656657// The output section name `/DISCARD/' is special.658// Any input section assigned to it is discarded.659if (osec->name == "/DISCARD/") {660for (InputSectionBase *s : v)661discard(*s);662discardSynthetic(*osec);663osec->commands.clear();664return false;665}666667// This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive668// ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input669// sections satisfy a given constraint. If not, a directive is handled670// as if it wasn't present from the beginning.671//672// Because we'll iterate over SectionCommands many more times, the easy673// way to "make it as if it wasn't present" is to make it empty.674if (!matchConstraints(v, osec->constraint)) {675for (InputSectionBase *s : v)676s->parent = nullptr;677osec->commands.clear();678return false;679}680681// Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign682// is given, input sections are aligned to that value, whether the683// given value is larger or smaller than the original section alignment.684if (osec->subalignExpr) {685uint32_t subalign = osec->subalignExpr().getValue();686for (InputSectionBase *s : v)687s->addralign = subalign;688}689690// Set the partition field the same way OutputSection::recordSection()691// does. Partitions cannot be used with the SECTIONS command, so this is692// always 1.693osec->partition = 1;694return true;695};696697// Process OVERWRITE_SECTIONS first so that it can overwrite the main script698// or orphans.699if (config->enableNonContiguousRegions && !overwriteSections.empty())700error("OVERWRITE_SECTIONS cannot be used with "701"--enable-non-contiguous-regions");702DenseMap<CachedHashStringRef, OutputDesc *> map;703size_t i = 0;704for (OutputDesc *osd : overwriteSections) {705OutputSection *osec = &osd->osec;706if (process(osec) &&707!map.try_emplace(CachedHashStringRef(osec->name), osd).second)708warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);709}710for (SectionCommand *&base : sectionCommands)711if (auto *osd = dyn_cast<OutputDesc>(base)) {712OutputSection *osec = &osd->osec;713if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {714log(overwrite->osec.location + " overwrites " + osec->name);715overwrite->osec.sectionIndex = i++;716base = overwrite;717} else if (process(osec)) {718osec->sectionIndex = i++;719}720}721722// If an OVERWRITE_SECTIONS specified output section is not in723// sectionCommands, append it to the end. The section will be inserted by724// orphan placement.725for (OutputDesc *osd : overwriteSections)726if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)727sectionCommands.push_back(osd);728}729730void LinkerScript::processSymbolAssignments() {731// Dot outside an output section still represents a relative address, whose732// sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section733// that fills the void outside a section. It has an index of one, which is734// indistinguishable from any other regular section index.735aether = make<OutputSection>("", 0, SHF_ALLOC);736aether->sectionIndex = 1;737738// `st` captures the local AddressState and makes it accessible deliberately.739// This is needed as there are some cases where we cannot just thread the740// current state through to a lambda function created by the script parser.741AddressState st;742state = &st;743st.outSec = aether;744745for (SectionCommand *cmd : sectionCommands) {746if (auto *assign = dyn_cast<SymbolAssignment>(cmd))747addSymbol(assign);748else749for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)750if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))751addSymbol(assign);752}753754state = nullptr;755}756757static OutputSection *findByName(ArrayRef<SectionCommand *> vec,758StringRef name) {759for (SectionCommand *cmd : vec)760if (auto *osd = dyn_cast<OutputDesc>(cmd))761if (osd->osec.name == name)762return &osd->osec;763return nullptr;764}765766static OutputDesc *createSection(InputSectionBase *isec, StringRef outsecName) {767OutputDesc *osd = script->createOutputSection(outsecName, "<internal>");768osd->osec.recordSection(isec);769return osd;770}771772static OutputDesc *addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,773InputSectionBase *isec, StringRef outsecName) {774// Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r775// option is given. A section with SHT_GROUP defines a "section group", and776// its members have SHF_GROUP attribute. Usually these flags have already been777// stripped by InputFiles.cpp as section groups are processed and uniquified.778// However, for the -r option, we want to pass through all section groups779// as-is because adding/removing members or merging them with other groups780// change their semantics.781if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))782return createSection(isec, outsecName);783784// Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have785// relocation sections .rela.foo and .rela.bar for example. Most tools do786// not allow multiple REL[A] sections for output section. Hence we787// should combine these relocation sections into single output.788// We skip synthetic sections because it can be .rela.dyn/.rela.plt or any789// other REL[A] sections created by linker itself.790if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {791auto *sec = cast<InputSection>(isec);792OutputSection *out = sec->getRelocatedSection()->getOutputSection();793794if (auto *relSec = out->relocationSection) {795relSec->recordSection(sec);796return nullptr;797}798799OutputDesc *osd = createSection(isec, outsecName);800out->relocationSection = &osd->osec;801return osd;802}803804// The ELF spec just says805// ----------------------------------------------------------------806// In the first phase, input sections that match in name, type and807// attribute flags should be concatenated into single sections.808// ----------------------------------------------------------------809//810// However, it is clear that at least some flags have to be ignored for811// section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be812// ignored. We should not have two output .text sections just because one was813// in a group and another was not for example.814//815// It also seems that wording was a late addition and didn't get the816// necessary scrutiny.817//818// Merging sections with different flags is expected by some users. One819// reason is that if one file has820//821// int *const bar __attribute__((section(".foo"))) = (int *)0;822//823// gcc with -fPIC will produce a read only .foo section. But if another824// file has825//826// int zed;827// int *const bar __attribute__((section(".foo"))) = (int *)&zed;828//829// gcc with -fPIC will produce a read write section.830//831// Last but not least, when using linker script the merge rules are forced by832// the script. Unfortunately, linker scripts are name based. This means that833// expressions like *(.foo*) can refer to multiple input sections with834// different flags. We cannot put them in different output sections or we835// would produce wrong results for836//837// start = .; *(.foo.*) end = .; *(.bar)838//839// and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to840// another. The problem is that there is no way to layout those output841// sections such that the .foo sections are the only thing between the start842// and end symbols.843//844// Given the above issues, we instead merge sections by name and error on845// incompatible types and flags.846TinyPtrVector<OutputSection *> &v = map[outsecName];847for (OutputSection *sec : v) {848if (sec->partition != isec->partition)849continue;850851if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {852// Merging two SHF_LINK_ORDER sections with different sh_link fields will853// change their semantics, so we only merge them in -r links if they will854// end up being linked to the same output section. The casts are fine855// because everything in the map was created by the orphan placement code.856auto *firstIsec = cast<InputSectionBase>(857cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);858OutputSection *firstIsecOut =859(firstIsec->flags & SHF_LINK_ORDER)860? firstIsec->getLinkOrderDep()->getOutputSection()861: nullptr;862if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())863continue;864}865866sec->recordSection(isec);867return nullptr;868}869870OutputDesc *osd = createSection(isec, outsecName);871v.push_back(&osd->osec);872return osd;873}874875// Add sections that didn't match any sections command.876void LinkerScript::addOrphanSections() {877StringMap<TinyPtrVector<OutputSection *>> map;878SmallVector<OutputDesc *, 0> v;879880auto add = [&](InputSectionBase *s) {881if (s->isLive() && !s->parent) {882orphanSections.push_back(s);883884StringRef name = getOutputSectionName(s);885if (config->unique) {886v.push_back(createSection(s, name));887} else if (OutputSection *sec = findByName(sectionCommands, name)) {888sec->recordSection(s);889} else {890if (OutputDesc *osd = addInputSec(map, s, name))891v.push_back(osd);892assert(isa<MergeInputSection>(s) ||893s->getOutputSection()->sectionIndex == UINT32_MAX);894}895}896};897898// For further --emit-reloc handling code we need target output section899// to be created before we create relocation output section, so we want900// to create target sections first. We do not want priority handling901// for synthetic sections because them are special.902size_t n = 0;903for (InputSectionBase *isec : ctx.inputSections) {904// Process InputSection and MergeInputSection.905if (LLVM_LIKELY(isa<InputSection>(isec)))906ctx.inputSections[n++] = isec;907908// In -r links, SHF_LINK_ORDER sections are added while adding their parent909// sections because we need to know the parent's output section before we910// can select an output section for the SHF_LINK_ORDER section.911if (config->relocatable && (isec->flags & SHF_LINK_ORDER))912continue;913914if (auto *sec = dyn_cast<InputSection>(isec))915if (InputSectionBase *rel = sec->getRelocatedSection())916if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))917add(relIS);918add(isec);919if (config->relocatable)920for (InputSectionBase *depSec : isec->dependentSections)921if (depSec->flags & SHF_LINK_ORDER)922add(depSec);923}924// Keep just InputSection.925ctx.inputSections.resize(n);926927// If no SECTIONS command was given, we should insert sections commands928// before others, so that we can handle scripts which refers them,929// for example: "foo = ABSOLUTE(ADDR(.text)));".930// When SECTIONS command is present we just add all orphans to the end.931if (hasSectionsCommand)932sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());933else934sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());935}936937void LinkerScript::diagnoseOrphanHandling() const {938llvm::TimeTraceScope timeScope("Diagnose orphan sections");939if (config->orphanHandling == OrphanHandlingPolicy::Place ||940!hasSectionsCommand)941return;942for (const InputSectionBase *sec : orphanSections) {943// .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,944// automatically. The section is not supposed to be specified by scripts.945if (sec == in.relroPadding.get())946continue;947// Input SHT_REL[A] retained by --emit-relocs are ignored by948// computeInputSections(). Don't warn/error.949if (isa<InputSection>(sec) &&950cast<InputSection>(sec)->getRelocatedSection())951continue;952953StringRef name = getOutputSectionName(sec);954if (config->orphanHandling == OrphanHandlingPolicy::Error)955error(toString(sec) + " is being placed in '" + name + "'");956else957warn(toString(sec) + " is being placed in '" + name + "'");958}959}960961void LinkerScript::diagnoseMissingSGSectionAddress() const {962if (!config->cmseImplib || !in.armCmseSGSection->isNeeded())963return;964965OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");966if (sec && !sec->addrExpr && !config->sectionStartMap.count(".gnu.sgstubs"))967error("no address assigned to the veneers output section " + sec->name);968}969970// This function searches for a memory region to place the given output971// section in. If found, a pointer to the appropriate memory region is972// returned in the first member of the pair. Otherwise, a nullptr is returned.973// The second member of the pair is a hint that should be passed to the974// subsequent call of this method.975std::pair<MemoryRegion *, MemoryRegion *>976LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {977// Non-allocatable sections are not part of the process image.978if (!(sec->flags & SHF_ALLOC)) {979bool hasInputOrByteCommand =980sec->hasInputSections ||981llvm::any_of(sec->commands, [](SectionCommand *comm) {982return ByteCommand::classof(comm);983});984if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)985warn("ignoring memory region assignment for non-allocatable section '" +986sec->name + "'");987return {nullptr, nullptr};988}989990// If a memory region name was specified in the output section command,991// then try to find that region first.992if (!sec->memoryRegionName.empty()) {993if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))994return {m, m};995error("memory region '" + sec->memoryRegionName + "' not declared");996return {nullptr, nullptr};997}998999// If at least one memory region is defined, all sections must1000// belong to some memory region. Otherwise, we don't need to do1001// anything for memory regions.1002if (memoryRegions.empty())1003return {nullptr, nullptr};10041005// An orphan section should continue the previous memory region.1006if (sec->sectionIndex == UINT32_MAX && hint)1007return {hint, hint};10081009// See if a region can be found by matching section flags.1010for (auto &pair : memoryRegions) {1011MemoryRegion *m = pair.second;1012if (m->compatibleWith(sec->flags))1013return {m, nullptr};1014}10151016// Otherwise, no suitable region was found.1017error("no memory region specified for section '" + sec->name + "'");1018return {nullptr, nullptr};1019}10201021static OutputSection *findFirstSection(PhdrEntry *load) {1022for (OutputSection *sec : outputSections)1023if (sec->ptLoad == load)1024return sec;1025return nullptr;1026}10271028// Assign addresses to an output section and offsets to its input sections and1029// symbol assignments. Return true if the output section's address has changed.1030bool LinkerScript::assignOffsets(OutputSection *sec) {1031const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;1032const bool sameMemRegion = state->memRegion == sec->memRegion;1033const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;1034const uint64_t savedDot = dot;1035bool addressChanged = false;1036state->memRegion = sec->memRegion;1037state->lmaRegion = sec->lmaRegion;10381039if (!(sec->flags & SHF_ALLOC)) {1040// Non-SHF_ALLOC sections have zero addresses.1041dot = 0;1042} else if (isTbss) {1043// Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range1044// starts from the end address of the previous tbss section.1045if (state->tbssAddr == 0)1046state->tbssAddr = dot;1047else1048dot = state->tbssAddr;1049} else {1050if (state->memRegion)1051dot = state->memRegion->curPos;1052if (sec->addrExpr)1053setDot(sec->addrExpr, sec->location, false);10541055// If the address of the section has been moved forward by an explicit1056// expression so that it now starts past the current curPos of the enclosing1057// region, we need to expand the current region to account for the space1058// between the previous section, if any, and the start of this section.1059if (state->memRegion && state->memRegion->curPos < dot)1060expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,1061sec->name);1062}10631064state->outSec = sec;1065if (!(sec->addrExpr && script->hasSectionsCommand)) {1066// ALIGN is respected. sec->alignment is the max of ALIGN and the maximum of1067// input section alignments.1068const uint64_t pos = dot;1069dot = alignToPowerOf2(dot, sec->addralign);1070expandMemoryRegions(dot - pos);1071}1072addressChanged = sec->addr != dot;1073sec->addr = dot;10741075// state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()1076// or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA1077// region is the default, and the two sections are in the same memory region,1078// reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates1079// heuristics described in1080// https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html1081if (sec->lmaExpr) {1082state->lmaOffset = sec->lmaExpr().getValue() - dot;1083} else if (MemoryRegion *mr = sec->lmaRegion) {1084uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);1085if (mr->curPos < lmaStart)1086expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);1087state->lmaOffset = lmaStart - dot;1088} else if (!sameMemRegion || !prevLMARegionIsDefault) {1089state->lmaOffset = 0;1090}10911092// Propagate state->lmaOffset to the first "non-header" section.1093if (PhdrEntry *l = sec->ptLoad)1094if (sec == findFirstSection(l))1095l->lmaOffset = state->lmaOffset;10961097// We can call this method multiple times during the creation of1098// thunks and want to start over calculation each time.1099sec->size = 0;11001101// We visited SectionsCommands from processSectionCommands to1102// layout sections. Now, we visit SectionsCommands again to fix1103// section offsets.1104for (SectionCommand *cmd : sec->commands) {1105// This handles the assignments to symbol or to the dot.1106if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {1107assign->addr = dot;1108assignSymbol(assign, true);1109assign->size = dot - assign->addr;1110continue;1111}11121113// Handle BYTE(), SHORT(), LONG(), or QUAD().1114if (auto *data = dyn_cast<ByteCommand>(cmd)) {1115data->offset = dot - sec->addr;1116dot += data->size;1117expandOutputSection(data->size);1118continue;1119}11201121// Handle a single input section description command.1122// It calculates and assigns the offsets for each section and also1123// updates the output section size.11241125auto §ions = cast<InputSectionDescription>(cmd)->sections;1126for (InputSection *isec : sections) {1127assert(isec->getParent() == sec);1128if (isa<PotentialSpillSection>(isec))1129continue;1130const uint64_t pos = dot;1131dot = alignToPowerOf2(dot, isec->addralign);1132isec->outSecOff = dot - sec->addr;1133dot += isec->getSize();11341135// Update output section size after adding each section. This is so that1136// SIZEOF works correctly in the case below:1137// .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }1138expandOutputSection(dot - pos);1139}1140}11411142// If .relro_padding is present, round up the end to a common-page-size1143// boundary to protect the last page.1144if (in.relroPadding && sec == in.relroPadding->getParent())1145expandOutputSection(alignToPowerOf2(dot, config->commonPageSize) - dot);11461147// Non-SHF_ALLOC sections do not affect the addresses of other OutputSections1148// as they are not part of the process image.1149if (!(sec->flags & SHF_ALLOC)) {1150dot = savedDot;1151} else if (isTbss) {1152// NOBITS TLS sections are similar. Additionally save the end address.1153state->tbssAddr = dot;1154dot = savedDot;1155}1156return addressChanged;1157}11581159static bool isDiscardable(const OutputSection &sec) {1160if (sec.name == "/DISCARD/")1161return true;11621163// We do not want to remove OutputSections with expressions that reference1164// symbols even if the OutputSection is empty. We want to ensure that the1165// expressions can be evaluated and report an error if they cannot.1166if (sec.expressionsUseSymbols)1167return false;11681169// OutputSections may be referenced by name in ADDR and LOADADDR expressions,1170// as an empty Section can has a valid VMA and LMA we keep the OutputSection1171// to maintain the integrity of the other Expression.1172if (sec.usedInExpression)1173return false;11741175for (SectionCommand *cmd : sec.commands) {1176if (auto assign = dyn_cast<SymbolAssignment>(cmd))1177// Don't create empty output sections just for unreferenced PROVIDE1178// symbols.1179if (assign->name != "." && !assign->sym)1180continue;11811182if (!isa<InputSectionDescription>(*cmd))1183return false;1184}1185return true;1186}11871188static void maybePropagatePhdrs(OutputSection &sec,1189SmallVector<StringRef, 0> &phdrs) {1190if (sec.phdrs.empty()) {1191// To match the bfd linker script behaviour, only propagate program1192// headers to sections that are allocated.1193if (sec.flags & SHF_ALLOC)1194sec.phdrs = phdrs;1195} else {1196phdrs = sec.phdrs;1197}1198}11991200void LinkerScript::adjustOutputSections() {1201// If the output section contains only symbol assignments, create a1202// corresponding output section. The issue is what to do with linker script1203// like ".foo : { symbol = 42; }". One option would be to convert it to1204// "symbol = 42;". That is, move the symbol out of the empty section1205// description. That seems to be what bfd does for this simple case. The1206// problem is that this is not completely general. bfd will give up and1207// create a dummy section too if there is a ". = . + 1" inside the section1208// for example.1209// Given that we want to create the section, we have to worry what impact1210// it will have on the link. For example, if we just create a section with1211// 0 for flags, it would change which PT_LOADs are created.1212// We could remember that particular section is dummy and ignore it in1213// other parts of the linker, but unfortunately there are quite a few places1214// that would need to change:1215// * The program header creation.1216// * The orphan section placement.1217// * The address assignment.1218// The other option is to pick flags that minimize the impact the section1219// will have on the rest of the linker. That is why we copy the flags from1220// the previous sections. We copy just SHF_ALLOC and SHF_WRITE to keep the1221// impact low. We do not propagate SHF_EXECINSTR as in some cases this can1222// lead to executable writeable section.1223uint64_t flags = SHF_ALLOC;12241225SmallVector<StringRef, 0> defPhdrs;1226bool seenRelro = false;1227for (SectionCommand *&cmd : sectionCommands) {1228if (!isa<OutputDesc>(cmd))1229continue;1230auto *sec = &cast<OutputDesc>(cmd)->osec;12311232// Handle align (e.g. ".foo : ALIGN(16) { ... }").1233if (sec->alignExpr)1234sec->addralign =1235std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());12361237bool isEmpty = (getFirstInputSection(sec) == nullptr);1238bool discardable = isEmpty && isDiscardable(*sec);1239// If sec has at least one input section and not discarded, remember its1240// flags to be inherited by subsequent output sections. (sec may contain1241// just one empty synthetic section.)1242if (sec->hasInputSections && !discardable)1243flags = sec->flags;12441245// We do not want to keep any special flags for output section1246// in case it is empty.1247if (isEmpty) {1248sec->flags =1249flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);1250sec->sortRank = getSectionRank(*sec);1251}12521253// The code below may remove empty output sections. We should save the1254// specified program headers (if exist) and propagate them to subsequent1255// sections which do not specify program headers.1256// An example of such a linker script is:1257// SECTIONS { .empty : { *(.empty) } :rw1258// .foo : { *(.foo) } }1259// Note: at this point the order of output sections has not been finalized,1260// because orphans have not been inserted into their expected positions. We1261// will handle them in adjustSectionsAfterSorting().1262if (sec->sectionIndex != UINT32_MAX)1263maybePropagatePhdrs(*sec, defPhdrs);12641265// Discard .relro_padding if we have not seen one RELRO section. Note: when1266// .tbss is the only RELRO section, there is no associated PT_LOAD segment1267// (needsPtLoad), so we don't append .relro_padding in the case.1268if (in.relroPadding && in.relroPadding->getParent() == sec && !seenRelro)1269discardable = true;1270if (discardable) {1271sec->markDead();1272cmd = nullptr;1273} else {1274seenRelro |=1275sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));1276}1277}12781279// It is common practice to use very generic linker scripts. So for any1280// given run some of the output sections in the script will be empty.1281// We could create corresponding empty output sections, but that would1282// clutter the output.1283// We instead remove trivially empty sections. The bfd linker seems even1284// more aggressive at removing them.1285llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });1286}12871288void LinkerScript::adjustSectionsAfterSorting() {1289// Try and find an appropriate memory region to assign offsets in.1290MemoryRegion *hint = nullptr;1291for (SectionCommand *cmd : sectionCommands) {1292if (auto *osd = dyn_cast<OutputDesc>(cmd)) {1293OutputSection *sec = &osd->osec;1294if (!sec->lmaRegionName.empty()) {1295if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))1296sec->lmaRegion = m;1297else1298error("memory region '" + sec->lmaRegionName + "' not declared");1299}1300std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);1301}1302}13031304// If output section command doesn't specify any segments,1305// and we haven't previously assigned any section to segment,1306// then we simply assign section to the very first load segment.1307// Below is an example of such linker script:1308// PHDRS { seg PT_LOAD; }1309// SECTIONS { .aaa : { *(.aaa) } }1310SmallVector<StringRef, 0> defPhdrs;1311auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {1312return cmd.type == PT_LOAD;1313});1314if (firstPtLoad != phdrsCommands.end())1315defPhdrs.push_back(firstPtLoad->name);13161317// Walk the commands and propagate the program headers to commands that don't1318// explicitly specify them.1319for (SectionCommand *cmd : sectionCommands)1320if (auto *osd = dyn_cast<OutputDesc>(cmd))1321maybePropagatePhdrs(osd->osec, defPhdrs);1322}13231324static uint64_t computeBase(uint64_t min, bool allocateHeaders) {1325// If there is no SECTIONS or if the linkerscript is explicit about program1326// headers, do our best to allocate them.1327if (!script->hasSectionsCommand || allocateHeaders)1328return 0;1329// Otherwise only allocate program headers if that would not add a page.1330return alignDown(min, config->maxPageSize);1331}13321333// When the SECTIONS command is used, try to find an address for the file and1334// program headers output sections, which can be added to the first PT_LOAD1335// segment when program headers are created.1336//1337// We check if the headers fit below the first allocated section. If there isn't1338// enough space for these sections, we'll remove them from the PT_LOAD segment,1339// and we'll also remove the PT_PHDR segment.1340void LinkerScript::allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs) {1341uint64_t min = std::numeric_limits<uint64_t>::max();1342for (OutputSection *sec : outputSections)1343if (sec->flags & SHF_ALLOC)1344min = std::min<uint64_t>(min, sec->addr);13451346auto it = llvm::find_if(1347phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });1348if (it == phdrs.end())1349return;1350PhdrEntry *firstPTLoad = *it;13511352bool hasExplicitHeaders =1353llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {1354return cmd.hasPhdrs || cmd.hasFilehdr;1355});1356bool paged = !config->omagic && !config->nmagic;1357uint64_t headerSize = getHeaderSize();1358if ((paged || hasExplicitHeaders) &&1359headerSize <= min - computeBase(min, hasExplicitHeaders)) {1360min = alignDown(min - headerSize, config->maxPageSize);1361Out::elfHeader->addr = min;1362Out::programHeaders->addr = min + Out::elfHeader->size;1363return;1364}13651366// Error if we were explicitly asked to allocate headers.1367if (hasExplicitHeaders)1368error("could not allocate headers");13691370Out::elfHeader->ptLoad = nullptr;1371Out::programHeaders->ptLoad = nullptr;1372firstPTLoad->firstSec = findFirstSection(firstPTLoad);13731374llvm::erase_if(phdrs,1375[](const PhdrEntry *e) { return e->p_type == PT_PHDR; });1376}13771378LinkerScript::AddressState::AddressState() {1379for (auto &mri : script->memoryRegions) {1380MemoryRegion *mr = mri.second;1381mr->curPos = (mr->origin)().getValue();1382}1383}13841385// Here we assign addresses as instructed by linker script SECTIONS1386// sub-commands. Doing that allows us to use final VA values, so here1387// we also handle rest commands like symbol assignments and ASSERTs.1388// Return an output section that has changed its address or null, and a symbol1389// that has changed its section or value (or nullptr if no symbol has changed).1390std::pair<const OutputSection *, const Defined *>1391LinkerScript::assignAddresses() {1392if (script->hasSectionsCommand) {1393// With a linker script, assignment of addresses to headers is covered by1394// allocateHeaders().1395dot = config->imageBase.value_or(0);1396} else {1397// Assign addresses to headers right now.1398dot = target->getImageBase();1399Out::elfHeader->addr = dot;1400Out::programHeaders->addr = dot + Out::elfHeader->size;1401dot += getHeaderSize();1402}14031404OutputSection *changedOsec = nullptr;1405AddressState st;1406state = &st;1407errorOnMissingSection = true;1408st.outSec = aether;1409recordedErrors.clear();14101411SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);1412for (SectionCommand *cmd : sectionCommands) {1413if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {1414assign->addr = dot;1415assignSymbol(assign, false);1416assign->size = dot - assign->addr;1417continue;1418}1419if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)1420changedOsec = &cast<OutputDesc>(cmd)->osec;1421}14221423state = nullptr;1424return {changedOsec, getChangedSymbolAssignment(oldValues)};1425}14261427static bool hasRegionOverflowed(MemoryRegion *mr) {1428if (!mr)1429return false;1430return mr->curPos - mr->getOrigin() > mr->getLength();1431}14321433// Spill input sections in reverse order of address assignment to (potentially)1434// bring memory regions out of overflow. The size savings of a spill can only be1435// estimated, since general linker script arithmetic may occur afterwards.1436// Under-estimates may cause unnecessary spills, but over-estimates can always1437// be corrected on the next pass.1438bool LinkerScript::spillSections() {1439if (!config->enableNonContiguousRegions)1440return false;14411442bool spilled = false;1443for (SectionCommand *cmd : reverse(sectionCommands)) {1444auto *od = dyn_cast<OutputDesc>(cmd);1445if (!od)1446continue;1447OutputSection *osec = &od->osec;1448if (!osec->memRegion)1449continue;14501451// Input sections that have replaced a potential spill and should be removed1452// from their input section description.1453DenseSet<InputSection *> spilledInputSections;14541455for (SectionCommand *cmd : reverse(osec->commands)) {1456if (!hasRegionOverflowed(osec->memRegion) &&1457!hasRegionOverflowed(osec->lmaRegion))1458break;14591460auto *isd = dyn_cast<InputSectionDescription>(cmd);1461if (!isd)1462continue;1463for (InputSection *isec : reverse(isd->sections)) {1464// Potential spill locations cannot be spilled.1465if (isa<PotentialSpillSection>(isec))1466continue;14671468// Find the next potential spill location and remove it from the list.1469auto it = potentialSpillLists.find(isec);1470if (it == potentialSpillLists.end())1471continue;1472PotentialSpillList &list = it->second;1473PotentialSpillSection *spill = list.head;1474if (spill->next)1475list.head = spill->next;1476else1477potentialSpillLists.erase(isec);14781479// Replace the next spill location with the spilled section and adjust1480// its properties to match the new location. Note that the alignment of1481// the spill section may have diverged from the original due to e.g. a1482// SUBALIGN. Correct assignment requires the spill's alignment to be1483// used, not the original.1484spilledInputSections.insert(isec);1485*llvm::find(spill->isd->sections, spill) = isec;1486isec->parent = spill->parent;1487isec->addralign = spill->addralign;14881489// Record the (potential) reduction in the region's end position.1490osec->memRegion->curPos -= isec->getSize();1491if (osec->lmaRegion)1492osec->lmaRegion->curPos -= isec->getSize();14931494// Spilling continues until the end position no longer overflows the1495// region. Then, another round of address assignment will either confirm1496// the spill's success or lead to yet more spilling.1497if (!hasRegionOverflowed(osec->memRegion) &&1498!hasRegionOverflowed(osec->lmaRegion))1499break;1500}15011502// Remove any spilled input sections to complete their move.1503if (!spilledInputSections.empty()) {1504spilled = true;1505llvm::erase_if(isd->sections, [&](InputSection *isec) {1506return spilledInputSections.contains(isec);1507});1508}1509}1510}15111512return spilled;1513}15141515// Erase any potential spill sections that were not used.1516void LinkerScript::erasePotentialSpillSections() {1517if (potentialSpillLists.empty())1518return;15191520// Collect the set of input section descriptions that contain potential1521// spills.1522DenseSet<InputSectionDescription *> isds;1523for (const auto &[_, list] : potentialSpillLists)1524for (PotentialSpillSection *s = list.head; s; s = s->next)1525isds.insert(s->isd);15261527for (InputSectionDescription *isd : isds)1528llvm::erase_if(isd->sections, [](InputSection *s) {1529return isa<PotentialSpillSection>(s);1530});15311532potentialSpillLists.clear();1533}15341535// Creates program headers as instructed by PHDRS linker script command.1536SmallVector<PhdrEntry *, 0> LinkerScript::createPhdrs() {1537SmallVector<PhdrEntry *, 0> ret;15381539// Process PHDRS and FILEHDR keywords because they are not1540// real output sections and cannot be added in the following loop.1541for (const PhdrsCommand &cmd : phdrsCommands) {1542PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags.value_or(PF_R));15431544if (cmd.hasFilehdr)1545phdr->add(Out::elfHeader);1546if (cmd.hasPhdrs)1547phdr->add(Out::programHeaders);15481549if (cmd.lmaExpr) {1550phdr->p_paddr = cmd.lmaExpr().getValue();1551phdr->hasLMA = true;1552}1553ret.push_back(phdr);1554}15551556// Add output sections to program headers.1557for (OutputSection *sec : outputSections) {1558// Assign headers specified by linker script1559for (size_t id : getPhdrIndices(sec)) {1560ret[id]->add(sec);1561if (!phdrsCommands[id].flags)1562ret[id]->p_flags |= sec->getPhdrFlags();1563}1564}1565return ret;1566}15671568// Returns true if we should emit an .interp section.1569//1570// We usually do. But if PHDRS commands are given, and1571// no PT_INTERP is there, there's no place to emit an1572// .interp, so we don't do that in that case.1573bool LinkerScript::needsInterpSection() {1574if (phdrsCommands.empty())1575return true;1576for (PhdrsCommand &cmd : phdrsCommands)1577if (cmd.type == PT_INTERP)1578return true;1579return false;1580}15811582ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {1583if (name == ".") {1584if (state)1585return {state->outSec, false, dot - state->outSec->addr, loc};1586error(loc + ": unable to get location counter value");1587return 0;1588}15891590if (Symbol *sym = symtab.find(name)) {1591if (auto *ds = dyn_cast<Defined>(sym)) {1592ExprValue v{ds->section, false, ds->value, loc};1593// Retain the original st_type, so that the alias will get the same1594// behavior in relocation processing. Any operation will reset st_type to1595// STT_NOTYPE.1596v.type = ds->type;1597return v;1598}1599if (isa<SharedSymbol>(sym))1600if (!errorOnMissingSection)1601return {nullptr, false, 0, loc};1602}16031604error(loc + ": symbol not found: " + name);1605return 0;1606}16071608// Returns the index of the segment named Name.1609static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,1610StringRef name) {1611for (size_t i = 0; i < vec.size(); ++i)1612if (vec[i].name == name)1613return i;1614return std::nullopt;1615}16161617// Returns indices of ELF headers containing specific section. Each index is a1618// zero based number of ELF header listed within PHDRS {} script block.1619SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {1620SmallVector<size_t, 0> ret;16211622for (StringRef s : cmd->phdrs) {1623if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))1624ret.push_back(*idx);1625else if (s != "NONE")1626error(cmd->location + ": program header '" + s +1627"' is not listed in PHDRS");1628}1629return ret;1630}16311632void LinkerScript::printMemoryUsage(raw_ostream& os) {1633auto printSize = [&](uint64_t size) {1634if ((size & 0x3fffffff) == 0)1635os << format_decimal(size >> 30, 10) << " GB";1636else if ((size & 0xfffff) == 0)1637os << format_decimal(size >> 20, 10) << " MB";1638else if ((size & 0x3ff) == 0)1639os << format_decimal(size >> 10, 10) << " KB";1640else1641os << " " << format_decimal(size, 10) << " B";1642};1643os << "Memory region Used Size Region Size %age Used\n";1644for (auto &pair : memoryRegions) {1645MemoryRegion *m = pair.second;1646uint64_t usedLength = m->curPos - m->getOrigin();1647os << right_justify(m->name, 16) << ": ";1648printSize(usedLength);1649uint64_t length = m->getLength();1650if (length != 0) {1651printSize(length);1652double percent = usedLength * 100.0 / length;1653os << " " << format("%6.2f%%", percent);1654}1655os << '\n';1656}1657}16581659void LinkerScript::recordError(const Twine &msg) {1660auto &str = recordedErrors.emplace_back();1661msg.toVector(str);1662}16631664static void checkMemoryRegion(const MemoryRegion *region,1665const OutputSection *osec, uint64_t addr) {1666uint64_t osecEnd = addr + osec->size;1667uint64_t regionEnd = region->getOrigin() + region->getLength();1668if (osecEnd > regionEnd) {1669error("section '" + osec->name + "' will not fit in region '" +1670region->name + "': overflowed by " + Twine(osecEnd - regionEnd) +1671" bytes");1672}1673}16741675void LinkerScript::checkFinalScriptConditions() const {1676for (StringRef err : recordedErrors)1677errorOrWarn(err);1678for (const OutputSection *sec : outputSections) {1679if (const MemoryRegion *memoryRegion = sec->memRegion)1680checkMemoryRegion(memoryRegion, sec, sec->addr);1681if (const MemoryRegion *lmaRegion = sec->lmaRegion)1682checkMemoryRegion(lmaRegion, sec, sec->getLMA());1683}1684}16851686void LinkerScript::addScriptReferencedSymbolsToSymTable() {1687// Some symbols (such as __ehdr_start) are defined lazily only when there1688// are undefined symbols for them, so we add these to trigger that logic.1689auto reference = [](StringRef name) {1690Symbol *sym = symtab.addUnusedUndefined(name);1691sym->isUsedInRegularObj = true;1692sym->referenced = true;1693};1694for (StringRef name : referencedSymbols)1695reference(name);16961697// Keeps track of references from which PROVIDE symbols have been added to the1698// symbol table.1699DenseSet<StringRef> added;1700SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;1701for (const auto &[name, symRefs] : provideMap)1702if (LinkerScript::shouldAddProvideSym(name) && added.insert(name).second)1703symRefsVec.push_back(&symRefs);1704while (symRefsVec.size()) {1705for (StringRef name : *symRefsVec.pop_back_val()) {1706reference(name);1707// Prevent the symbol from being discarded by --gc-sections.1708script->referencedSymbols.push_back(name);1709auto it = script->provideMap.find(name);1710if (it != script->provideMap.end() &&1711LinkerScript::shouldAddProvideSym(name) &&1712added.insert(name).second) {1713symRefsVec.push_back(&it->second);1714}1715}1716}1717}17181719bool LinkerScript::shouldAddProvideSym(StringRef symName) {1720Symbol *sym = symtab.find(symName);1721return sym && !sym->isDefined() && !sym->isCommon();1722}172317241725