#include "LinkerScript.h"
#include "Config.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/Strings.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TimeProfiler.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <vector>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::elf;
ScriptWrapper elf::script;
static bool isSectionPrefix(StringRef prefix, StringRef name) {
return name.consume_front(prefix) && (name.empty() || name[0] == '.');
}
static StringRef getOutputSectionName(const InputSectionBase *s) {
if (auto *isec = dyn_cast<InputSection>(s)) {
if (InputSectionBase *rel = isec->getRelocatedSection()) {
OutputSection *out = rel->getOutputSection();
if (!out) {
assert(config->relocatable && (rel->flags & SHF_LINK_ORDER));
return s->name;
}
if (s->type == SHT_CREL)
return saver().save(".crel" + out->name);
if (s->type == SHT_RELA)
return saver().save(".rela" + out->name);
return saver().save(".rel" + out->name);
}
}
if (config->relocatable)
return s->name;
if (s->name == "COMMON")
return ".bss";
if (script->hasSectionsCommand)
return s->name;
if (isSectionPrefix(".text", s->name)) {
if (config->zKeepTextSectionPrefix)
for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
".text.startup", ".text.exit", ".text.split"})
if (isSectionPrefix(v.substr(5), s->name.substr(5)))
return v;
return ".text";
}
for (StringRef v :
{".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss", ".ldata",
".lrodata", ".lbss", ".gcc_except_table", ".init_array", ".fini_array",
".tbss", ".tdata", ".ARM.exidx", ".ARM.extab", ".ctors", ".dtors"})
if (isSectionPrefix(v, s->name))
return v;
return s->name;
}
uint64_t ExprValue::getValue() const {
if (sec)
return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),
alignment);
return alignToPowerOf2(val, alignment);
}
uint64_t ExprValue::getSecAddr() const {
return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
}
uint64_t ExprValue::getSectionOffset() const {
return getValue() - getSecAddr();
}
OutputDesc *LinkerScript::createOutputSection(StringRef name,
StringRef location) {
OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
OutputDesc *sec;
if (secRef && secRef->osec.location.empty()) {
sec = secRef;
} else {
sec = make<OutputDesc>(name, SHT_PROGBITS, 0);
if (!secRef)
secRef = sec;
}
sec->osec.location = std::string(location);
return sec;
}
OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
OutputDesc *&cmdRef = nameToOutputSection[CachedHashStringRef(name)];
if (!cmdRef)
cmdRef = make<OutputDesc>(name, SHT_PROGBITS, 0);
return cmdRef;
}
static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
StringRef secName) {
memRegion->curPos += size;
}
void LinkerScript::expandMemoryRegions(uint64_t size) {
if (state->memRegion)
expandMemoryRegion(state->memRegion, size, state->outSec->name);
if (state->lmaRegion && state->memRegion != state->lmaRegion)
expandMemoryRegion(state->lmaRegion, size, state->outSec->name);
}
void LinkerScript::expandOutputSection(uint64_t size) {
state->outSec->size += size;
expandMemoryRegions(size);
}
void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
uint64_t val = e().getValue();
if (val < dot && inSec) {
recordError(loc + ": unable to move location counter (0x" +
Twine::utohexstr(dot) + ") backward to 0x" +
Twine::utohexstr(val) + " for section '" + state->outSec->name +
"'");
}
if (inSec)
expandOutputSection(val - dot);
dot = val;
}
static bool shouldDefineSym(SymbolAssignment *cmd) {
if (cmd->name == ".")
return false;
return !cmd->provide || LinkerScript::shouldAddProvideSym(cmd->name);
}
void LinkerScript::addSymbol(SymbolAssignment *cmd) {
if (!shouldDefineSym(cmd))
return;
ExprValue value = cmd->expression();
SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
uint64_t symValue = value.sec ? 0 : value.getValue();
Defined newSym(createInternalFile(cmd->location), cmd->name, STB_GLOBAL,
visibility, value.type, symValue, 0, sec);
Symbol *sym = symtab.insert(cmd->name);
sym->mergeProperties(newSym);
newSym.overwrite(*sym);
sym->isUsedInRegularObj = true;
cmd->sym = cast<Defined>(sym);
}
static void declareSymbol(SymbolAssignment *cmd) {
if (!shouldDefineSym(cmd))
return;
uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
Defined newSym(ctx.internalFile, cmd->name, STB_GLOBAL, visibility,
STT_NOTYPE, 0, 0, nullptr);
Symbol *sym = symtab.insert(cmd->name);
if (!sym->isDefined())
ctx.scriptSymOrder.insert({sym, cmd->symOrder});
sym->mergeProperties(newSym);
newSym.overwrite(*sym);
cmd->sym = cast<Defined>(sym);
cmd->provide = false;
sym->isUsedInRegularObj = true;
sym->scriptDefined = true;
}
using SymbolAssignmentMap =
DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
static SymbolAssignmentMap
getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
SymbolAssignmentMap ret;
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
if (assign->sym)
ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
assign->sym->value));
continue;
}
for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
if (assign->sym)
ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
assign->sym->value));
}
return ret;
}
static const Defined *
getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
const Defined *changed = nullptr;
for (auto &it : oldValues) {
const Defined *sym = it.first;
if (std::make_pair(sym->section, sym->value) != it.second &&
(!changed || sym->getName() < changed->getName()))
changed = sym;
}
return changed;
}
void LinkerScript::processInsertCommands() {
SmallVector<OutputDesc *, 0> moves;
for (const InsertCommand &cmd : insertCommands) {
if (config->enableNonContiguousRegions)
error("INSERT cannot be used with --enable-non-contiguous-regions");
for (StringRef name : cmd.names) {
auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
return isa<OutputDesc>(subCmd) &&
cast<OutputDesc>(subCmd)->osec.name == name;
});
if (from == sectionCommands.end())
continue;
moves.push_back(cast<OutputDesc>(*from));
sectionCommands.erase(from);
}
auto insertPos =
llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
auto *to = dyn_cast<OutputDesc>(subCmd);
return to != nullptr && to->osec.name == cmd.where;
});
if (insertPos == sectionCommands.end()) {
error("unable to insert " + cmd.names[0] +
(cmd.isAfter ? " after " : " before ") + cmd.where);
} else {
if (cmd.isAfter)
++insertPos;
sectionCommands.insert(insertPos, moves.begin(), moves.end());
}
moves.clear();
}
}
void LinkerScript::declareSymbols() {
assert(!state);
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
declareSymbol(assign);
continue;
}
const OutputSection &sec = cast<OutputDesc>(cmd)->osec;
if (sec.constraint != ConstraintKind::NoConstraint)
continue;
for (SectionCommand *cmd : sec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
declareSymbol(assign);
}
}
void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
if (cmd->name == ".") {
setDot(cmd->expression, cmd->location, inSec);
return;
}
if (!cmd->sym)
return;
ExprValue v = cmd->expression();
if (v.isAbsolute()) {
cmd->sym->section = nullptr;
cmd->sym->value = v.getValue();
} else {
cmd->sym->section = v.sec;
cmd->sym->value = v.getSectionOffset();
}
cmd->sym->type = v.type;
}
static inline StringRef getFilename(const InputFile *file) {
return file ? file->getNameForScript() : StringRef();
}
bool InputSectionDescription::matchesFile(const InputFile *file) const {
if (filePat.isTrivialMatchAll())
return true;
if (!matchesFileCache || matchesFileCache->first != file)
matchesFileCache.emplace(file, filePat.match(getFilename(file)));
return matchesFileCache->second;
}
bool SectionPattern::excludesFile(const InputFile *file) const {
if (excludedFilePat.empty())
return false;
if (!excludesFileCache || excludesFileCache->first != file)
excludesFileCache.emplace(file, excludedFilePat.match(getFilename(file)));
return excludesFileCache->second;
}
bool LinkerScript::shouldKeep(InputSectionBase *s) {
for (InputSectionDescription *id : keptSections)
if (id->matchesFile(s->file))
for (SectionPattern &p : id->sectionPatterns)
if (p.sectionPat.match(s->name) &&
(s->flags & id->withFlags) == id->withFlags &&
(s->flags & id->withoutFlags) == 0)
return true;
return false;
}
static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
ConstraintKind kind) {
if (kind == ConstraintKind::NoConstraint)
return true;
bool isRW = llvm::any_of(
sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
return (isRW && kind == ConstraintKind::ReadWrite) ||
(!isRW && kind == ConstraintKind::ReadOnly);
}
static void sortSections(MutableArrayRef<InputSectionBase *> vec,
SortSectionPolicy k) {
auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
return a->addralign > b->addralign;
};
auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
return a->name < b->name;
};
auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
return getPriority(a->name) < getPriority(b->name);
};
switch (k) {
case SortSectionPolicy::Default:
case SortSectionPolicy::None:
return;
case SortSectionPolicy::Alignment:
return llvm::stable_sort(vec, alignmentComparator);
case SortSectionPolicy::Name:
return llvm::stable_sort(vec, nameComparator);
case SortSectionPolicy::Priority:
return llvm::stable_sort(vec, priorityComparator);
case SortSectionPolicy::Reverse:
return std::reverse(vec.begin(), vec.end());
}
}
static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
SortSectionPolicy outer,
SortSectionPolicy inner) {
if (outer == SortSectionPolicy::None)
return;
if (inner == SortSectionPolicy::Default)
sortSections(vec, config->sortSection);
else
sortSections(vec, inner);
sortSections(vec, outer);
}
SmallVector<InputSectionBase *, 0>
LinkerScript::computeInputSections(const InputSectionDescription *cmd,
ArrayRef<InputSectionBase *> sections,
const OutputSection &outCmd) {
SmallVector<InputSectionBase *, 0> ret;
SmallVector<size_t, 0> indexes;
DenseSet<size_t> seen;
DenseSet<InputSectionBase *> spills;
auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
for (size_t i = begin; i != end; ++i)
ret[i] = sections[indexes[i]];
sortInputSections(
MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
config->sortSection, SortSectionPolicy::None);
};
size_t sizeAfterPrevSort = 0;
for (const SectionPattern &pat : cmd->sectionPatterns) {
size_t sizeBeforeCurrPat = ret.size();
for (size_t i = 0, e = sections.size(); i != e; ++i) {
InputSectionBase *sec = sections[i];
if (!sec->isLive() || seen.contains(i))
continue;
if (isa<InputSection>(sec) &&
cast<InputSection>(sec)->getRelocatedSection())
continue;
if (!pat.sectionPat.match(sec->name))
continue;
if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
(sec->flags & cmd->withFlags) != cmd->withFlags ||
(sec->flags & cmd->withoutFlags) != 0)
continue;
if (sec->parent) {
if (!config->enableNonContiguousRegions)
continue;
if (outCmd.name == "/DISCARD/")
continue;
if (sec->parent->name == "/DISCARD/")
continue;
if (sec->parent == &outCmd)
continue;
spills.insert(sec);
}
ret.push_back(sec);
indexes.push_back(i);
seen.insert(i);
}
if (pat.sortOuter == SortSectionPolicy::Default)
continue;
sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
sortInputSections(
MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
pat.sortOuter, pat.sortInner);
sizeAfterPrevSort = ret.size();
}
sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
if (!spills.empty()) {
for (InputSectionBase *&sec : ret) {
if (!spills.contains(sec))
continue;
PotentialSpillSection *pss = make<PotentialSpillSection>(
*sec, const_cast<InputSectionDescription &>(*cmd));
auto [it, inserted] =
potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});
if (!inserted) {
PotentialSpillSection *&tail = it->second.tail;
tail = tail->next = pss;
}
sec = pss;
}
}
return ret;
}
void LinkerScript::discard(InputSectionBase &s) {
if (&s == in.shStrTab.get())
error("discarding " + s.name + " section is not allowed");
s.markDead();
s.parent = nullptr;
for (InputSection *sec : s.dependentSections)
discard(*sec);
}
void LinkerScript::discardSynthetic(OutputSection &outCmd) {
for (Partition &part : partitions) {
if (!part.armExidx || !part.armExidx->isLive())
continue;
SmallVector<InputSectionBase *, 0> secs(
part.armExidx->exidxSections.begin(),
part.armExidx->exidxSections.end());
for (SectionCommand *cmd : outCmd.commands)
if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))
discard(*s);
}
}
SmallVector<InputSectionBase *, 0>
LinkerScript::createInputSectionList(OutputSection &outCmd) {
SmallVector<InputSectionBase *, 0> ret;
for (SectionCommand *cmd : outCmd.commands) {
if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);
for (InputSectionBase *s : isd->sectionBases)
s->parent = &outCmd;
ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
}
}
return ret;
}
void LinkerScript::processSectionCommands() {
auto process = [this](OutputSection *osec) {
SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
if (osec->name == "/DISCARD/") {
for (InputSectionBase *s : v)
discard(*s);
discardSynthetic(*osec);
osec->commands.clear();
return false;
}
if (!matchConstraints(v, osec->constraint)) {
for (InputSectionBase *s : v)
s->parent = nullptr;
osec->commands.clear();
return false;
}
if (osec->subalignExpr) {
uint32_t subalign = osec->subalignExpr().getValue();
for (InputSectionBase *s : v)
s->addralign = subalign;
}
osec->partition = 1;
return true;
};
if (config->enableNonContiguousRegions && !overwriteSections.empty())
error("OVERWRITE_SECTIONS cannot be used with "
"--enable-non-contiguous-regions");
DenseMap<CachedHashStringRef, OutputDesc *> map;
size_t i = 0;
for (OutputDesc *osd : overwriteSections) {
OutputSection *osec = &osd->osec;
if (process(osec) &&
!map.try_emplace(CachedHashStringRef(osec->name), osd).second)
warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);
}
for (SectionCommand *&base : sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(base)) {
OutputSection *osec = &osd->osec;
if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
log(overwrite->osec.location + " overwrites " + osec->name);
overwrite->osec.sectionIndex = i++;
base = overwrite;
} else if (process(osec)) {
osec->sectionIndex = i++;
}
}
for (OutputDesc *osd : overwriteSections)
if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
sectionCommands.push_back(osd);
}
void LinkerScript::processSymbolAssignments() {
aether = make<OutputSection>("", 0, SHF_ALLOC);
aether->sectionIndex = 1;
AddressState st;
state = &st;
st.outSec = aether;
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
addSymbol(assign);
else
for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
addSymbol(assign);
}
state = nullptr;
}
static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
StringRef name) {
for (SectionCommand *cmd : vec)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
if (osd->osec.name == name)
return &osd->osec;
return nullptr;
}
static OutputDesc *createSection(InputSectionBase *isec, StringRef outsecName) {
OutputDesc *osd = script->createOutputSection(outsecName, "<internal>");
osd->osec.recordSection(isec);
return osd;
}
static OutputDesc *addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
InputSectionBase *isec, StringRef outsecName) {
if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
return createSection(isec, outsecName);
if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {
auto *sec = cast<InputSection>(isec);
OutputSection *out = sec->getRelocatedSection()->getOutputSection();
if (auto *relSec = out->relocationSection) {
relSec->recordSection(sec);
return nullptr;
}
OutputDesc *osd = createSection(isec, outsecName);
out->relocationSection = &osd->osec;
return osd;
}
TinyPtrVector<OutputSection *> &v = map[outsecName];
for (OutputSection *sec : v) {
if (sec->partition != isec->partition)
continue;
if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
auto *firstIsec = cast<InputSectionBase>(
cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
OutputSection *firstIsecOut =
(firstIsec->flags & SHF_LINK_ORDER)
? firstIsec->getLinkOrderDep()->getOutputSection()
: nullptr;
if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
continue;
}
sec->recordSection(isec);
return nullptr;
}
OutputDesc *osd = createSection(isec, outsecName);
v.push_back(&osd->osec);
return osd;
}
void LinkerScript::addOrphanSections() {
StringMap<TinyPtrVector<OutputSection *>> map;
SmallVector<OutputDesc *, 0> v;
auto add = [&](InputSectionBase *s) {
if (s->isLive() && !s->parent) {
orphanSections.push_back(s);
StringRef name = getOutputSectionName(s);
if (config->unique) {
v.push_back(createSection(s, name));
} else if (OutputSection *sec = findByName(sectionCommands, name)) {
sec->recordSection(s);
} else {
if (OutputDesc *osd = addInputSec(map, s, name))
v.push_back(osd);
assert(isa<MergeInputSection>(s) ||
s->getOutputSection()->sectionIndex == UINT32_MAX);
}
}
};
size_t n = 0;
for (InputSectionBase *isec : ctx.inputSections) {
if (LLVM_LIKELY(isa<InputSection>(isec)))
ctx.inputSections[n++] = isec;
if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
continue;
if (auto *sec = dyn_cast<InputSection>(isec))
if (InputSectionBase *rel = sec->getRelocatedSection())
if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
add(relIS);
add(isec);
if (config->relocatable)
for (InputSectionBase *depSec : isec->dependentSections)
if (depSec->flags & SHF_LINK_ORDER)
add(depSec);
}
ctx.inputSections.resize(n);
if (hasSectionsCommand)
sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
else
sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
}
void LinkerScript::diagnoseOrphanHandling() const {
llvm::TimeTraceScope timeScope("Diagnose orphan sections");
if (config->orphanHandling == OrphanHandlingPolicy::Place ||
!hasSectionsCommand)
return;
for (const InputSectionBase *sec : orphanSections) {
if (sec == in.relroPadding.get())
continue;
if (isa<InputSection>(sec) &&
cast<InputSection>(sec)->getRelocatedSection())
continue;
StringRef name = getOutputSectionName(sec);
if (config->orphanHandling == OrphanHandlingPolicy::Error)
error(toString(sec) + " is being placed in '" + name + "'");
else
warn(toString(sec) + " is being placed in '" + name + "'");
}
}
void LinkerScript::diagnoseMissingSGSectionAddress() const {
if (!config->cmseImplib || !in.armCmseSGSection->isNeeded())
return;
OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");
if (sec && !sec->addrExpr && !config->sectionStartMap.count(".gnu.sgstubs"))
error("no address assigned to the veneers output section " + sec->name);
}
std::pair<MemoryRegion *, MemoryRegion *>
LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
if (!(sec->flags & SHF_ALLOC)) {
bool hasInputOrByteCommand =
sec->hasInputSections ||
llvm::any_of(sec->commands, [](SectionCommand *comm) {
return ByteCommand::classof(comm);
});
if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)
warn("ignoring memory region assignment for non-allocatable section '" +
sec->name + "'");
return {nullptr, nullptr};
}
if (!sec->memoryRegionName.empty()) {
if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
return {m, m};
error("memory region '" + sec->memoryRegionName + "' not declared");
return {nullptr, nullptr};
}
if (memoryRegions.empty())
return {nullptr, nullptr};
if (sec->sectionIndex == UINT32_MAX && hint)
return {hint, hint};
for (auto &pair : memoryRegions) {
MemoryRegion *m = pair.second;
if (m->compatibleWith(sec->flags))
return {m, nullptr};
}
error("no memory region specified for section '" + sec->name + "'");
return {nullptr, nullptr};
}
static OutputSection *findFirstSection(PhdrEntry *load) {
for (OutputSection *sec : outputSections)
if (sec->ptLoad == load)
return sec;
return nullptr;
}
bool LinkerScript::assignOffsets(OutputSection *sec) {
const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
const bool sameMemRegion = state->memRegion == sec->memRegion;
const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;
const uint64_t savedDot = dot;
bool addressChanged = false;
state->memRegion = sec->memRegion;
state->lmaRegion = sec->lmaRegion;
if (!(sec->flags & SHF_ALLOC)) {
dot = 0;
} else if (isTbss) {
if (state->tbssAddr == 0)
state->tbssAddr = dot;
else
dot = state->tbssAddr;
} else {
if (state->memRegion)
dot = state->memRegion->curPos;
if (sec->addrExpr)
setDot(sec->addrExpr, sec->location, false);
if (state->memRegion && state->memRegion->curPos < dot)
expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,
sec->name);
}
state->outSec = sec;
if (!(sec->addrExpr && script->hasSectionsCommand)) {
const uint64_t pos = dot;
dot = alignToPowerOf2(dot, sec->addralign);
expandMemoryRegions(dot - pos);
}
addressChanged = sec->addr != dot;
sec->addr = dot;
if (sec->lmaExpr) {
state->lmaOffset = sec->lmaExpr().getValue() - dot;
} else if (MemoryRegion *mr = sec->lmaRegion) {
uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);
if (mr->curPos < lmaStart)
expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);
state->lmaOffset = lmaStart - dot;
} else if (!sameMemRegion || !prevLMARegionIsDefault) {
state->lmaOffset = 0;
}
if (PhdrEntry *l = sec->ptLoad)
if (sec == findFirstSection(l))
l->lmaOffset = state->lmaOffset;
sec->size = 0;
for (SectionCommand *cmd : sec->commands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
assign->addr = dot;
assignSymbol(assign, true);
assign->size = dot - assign->addr;
continue;
}
if (auto *data = dyn_cast<ByteCommand>(cmd)) {
data->offset = dot - sec->addr;
dot += data->size;
expandOutputSection(data->size);
continue;
}
auto §ions = cast<InputSectionDescription>(cmd)->sections;
for (InputSection *isec : sections) {
assert(isec->getParent() == sec);
if (isa<PotentialSpillSection>(isec))
continue;
const uint64_t pos = dot;
dot = alignToPowerOf2(dot, isec->addralign);
isec->outSecOff = dot - sec->addr;
dot += isec->getSize();
expandOutputSection(dot - pos);
}
}
if (in.relroPadding && sec == in.relroPadding->getParent())
expandOutputSection(alignToPowerOf2(dot, config->commonPageSize) - dot);
if (!(sec->flags & SHF_ALLOC)) {
dot = savedDot;
} else if (isTbss) {
state->tbssAddr = dot;
dot = savedDot;
}
return addressChanged;
}
static bool isDiscardable(const OutputSection &sec) {
if (sec.name == "/DISCARD/")
return true;
if (sec.expressionsUseSymbols)
return false;
if (sec.usedInExpression)
return false;
for (SectionCommand *cmd : sec.commands) {
if (auto assign = dyn_cast<SymbolAssignment>(cmd))
if (assign->name != "." && !assign->sym)
continue;
if (!isa<InputSectionDescription>(*cmd))
return false;
}
return true;
}
static void maybePropagatePhdrs(OutputSection &sec,
SmallVector<StringRef, 0> &phdrs) {
if (sec.phdrs.empty()) {
if (sec.flags & SHF_ALLOC)
sec.phdrs = phdrs;
} else {
phdrs = sec.phdrs;
}
}
void LinkerScript::adjustOutputSections() {
uint64_t flags = SHF_ALLOC;
SmallVector<StringRef, 0> defPhdrs;
bool seenRelro = false;
for (SectionCommand *&cmd : sectionCommands) {
if (!isa<OutputDesc>(cmd))
continue;
auto *sec = &cast<OutputDesc>(cmd)->osec;
if (sec->alignExpr)
sec->addralign =
std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());
bool isEmpty = (getFirstInputSection(sec) == nullptr);
bool discardable = isEmpty && isDiscardable(*sec);
if (sec->hasInputSections && !discardable)
flags = sec->flags;
if (isEmpty) {
sec->flags =
flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);
sec->sortRank = getSectionRank(*sec);
}
if (sec->sectionIndex != UINT32_MAX)
maybePropagatePhdrs(*sec, defPhdrs);
if (in.relroPadding && in.relroPadding->getParent() == sec && !seenRelro)
discardable = true;
if (discardable) {
sec->markDead();
cmd = nullptr;
} else {
seenRelro |=
sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));
}
}
llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });
}
void LinkerScript::adjustSectionsAfterSorting() {
MemoryRegion *hint = nullptr;
for (SectionCommand *cmd : sectionCommands) {
if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
OutputSection *sec = &osd->osec;
if (!sec->lmaRegionName.empty()) {
if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
sec->lmaRegion = m;
else
error("memory region '" + sec->lmaRegionName + "' not declared");
}
std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);
}
}
SmallVector<StringRef, 0> defPhdrs;
auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
return cmd.type == PT_LOAD;
});
if (firstPtLoad != phdrsCommands.end())
defPhdrs.push_back(firstPtLoad->name);
for (SectionCommand *cmd : sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
maybePropagatePhdrs(osd->osec, defPhdrs);
}
static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
if (!script->hasSectionsCommand || allocateHeaders)
return 0;
return alignDown(min, config->maxPageSize);
}
void LinkerScript::allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs) {
uint64_t min = std::numeric_limits<uint64_t>::max();
for (OutputSection *sec : outputSections)
if (sec->flags & SHF_ALLOC)
min = std::min<uint64_t>(min, sec->addr);
auto it = llvm::find_if(
phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
if (it == phdrs.end())
return;
PhdrEntry *firstPTLoad = *it;
bool hasExplicitHeaders =
llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
return cmd.hasPhdrs || cmd.hasFilehdr;
});
bool paged = !config->omagic && !config->nmagic;
uint64_t headerSize = getHeaderSize();
if ((paged || hasExplicitHeaders) &&
headerSize <= min - computeBase(min, hasExplicitHeaders)) {
min = alignDown(min - headerSize, config->maxPageSize);
Out::elfHeader->addr = min;
Out::programHeaders->addr = min + Out::elfHeader->size;
return;
}
if (hasExplicitHeaders)
error("could not allocate headers");
Out::elfHeader->ptLoad = nullptr;
Out::programHeaders->ptLoad = nullptr;
firstPTLoad->firstSec = findFirstSection(firstPTLoad);
llvm::erase_if(phdrs,
[](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
}
LinkerScript::AddressState::AddressState() {
for (auto &mri : script->memoryRegions) {
MemoryRegion *mr = mri.second;
mr->curPos = (mr->origin)().getValue();
}
}
std::pair<const OutputSection *, const Defined *>
LinkerScript::assignAddresses() {
if (script->hasSectionsCommand) {
dot = config->imageBase.value_or(0);
} else {
dot = target->getImageBase();
Out::elfHeader->addr = dot;
Out::programHeaders->addr = dot + Out::elfHeader->size;
dot += getHeaderSize();
}
OutputSection *changedOsec = nullptr;
AddressState st;
state = &st;
errorOnMissingSection = true;
st.outSec = aether;
recordedErrors.clear();
SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
for (SectionCommand *cmd : sectionCommands) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
assign->addr = dot;
assignSymbol(assign, false);
assign->size = dot - assign->addr;
continue;
}
if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)
changedOsec = &cast<OutputDesc>(cmd)->osec;
}
state = nullptr;
return {changedOsec, getChangedSymbolAssignment(oldValues)};
}
static bool hasRegionOverflowed(MemoryRegion *mr) {
if (!mr)
return false;
return mr->curPos - mr->getOrigin() > mr->getLength();
}
bool LinkerScript::spillSections() {
if (!config->enableNonContiguousRegions)
return false;
bool spilled = false;
for (SectionCommand *cmd : reverse(sectionCommands)) {
auto *od = dyn_cast<OutputDesc>(cmd);
if (!od)
continue;
OutputSection *osec = &od->osec;
if (!osec->memRegion)
continue;
DenseSet<InputSection *> spilledInputSections;
for (SectionCommand *cmd : reverse(osec->commands)) {
if (!hasRegionOverflowed(osec->memRegion) &&
!hasRegionOverflowed(osec->lmaRegion))
break;
auto *isd = dyn_cast<InputSectionDescription>(cmd);
if (!isd)
continue;
for (InputSection *isec : reverse(isd->sections)) {
if (isa<PotentialSpillSection>(isec))
continue;
auto it = potentialSpillLists.find(isec);
if (it == potentialSpillLists.end())
continue;
PotentialSpillList &list = it->second;
PotentialSpillSection *spill = list.head;
if (spill->next)
list.head = spill->next;
else
potentialSpillLists.erase(isec);
spilledInputSections.insert(isec);
*llvm::find(spill->isd->sections, spill) = isec;
isec->parent = spill->parent;
isec->addralign = spill->addralign;
osec->memRegion->curPos -= isec->getSize();
if (osec->lmaRegion)
osec->lmaRegion->curPos -= isec->getSize();
if (!hasRegionOverflowed(osec->memRegion) &&
!hasRegionOverflowed(osec->lmaRegion))
break;
}
if (!spilledInputSections.empty()) {
spilled = true;
llvm::erase_if(isd->sections, [&](InputSection *isec) {
return spilledInputSections.contains(isec);
});
}
}
}
return spilled;
}
void LinkerScript::erasePotentialSpillSections() {
if (potentialSpillLists.empty())
return;
DenseSet<InputSectionDescription *> isds;
for (const auto &[_, list] : potentialSpillLists)
for (PotentialSpillSection *s = list.head; s; s = s->next)
isds.insert(s->isd);
for (InputSectionDescription *isd : isds)
llvm::erase_if(isd->sections, [](InputSection *s) {
return isa<PotentialSpillSection>(s);
});
potentialSpillLists.clear();
}
SmallVector<PhdrEntry *, 0> LinkerScript::createPhdrs() {
SmallVector<PhdrEntry *, 0> ret;
for (const PhdrsCommand &cmd : phdrsCommands) {
PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags.value_or(PF_R));
if (cmd.hasFilehdr)
phdr->add(Out::elfHeader);
if (cmd.hasPhdrs)
phdr->add(Out::programHeaders);
if (cmd.lmaExpr) {
phdr->p_paddr = cmd.lmaExpr().getValue();
phdr->hasLMA = true;
}
ret.push_back(phdr);
}
for (OutputSection *sec : outputSections) {
for (size_t id : getPhdrIndices(sec)) {
ret[id]->add(sec);
if (!phdrsCommands[id].flags)
ret[id]->p_flags |= sec->getPhdrFlags();
}
}
return ret;
}
bool LinkerScript::needsInterpSection() {
if (phdrsCommands.empty())
return true;
for (PhdrsCommand &cmd : phdrsCommands)
if (cmd.type == PT_INTERP)
return true;
return false;
}
ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
if (name == ".") {
if (state)
return {state->outSec, false, dot - state->outSec->addr, loc};
error(loc + ": unable to get location counter value");
return 0;
}
if (Symbol *sym = symtab.find(name)) {
if (auto *ds = dyn_cast<Defined>(sym)) {
ExprValue v{ds->section, false, ds->value, loc};
v.type = ds->type;
return v;
}
if (isa<SharedSymbol>(sym))
if (!errorOnMissingSection)
return {nullptr, false, 0, loc};
}
error(loc + ": symbol not found: " + name);
return 0;
}
static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
StringRef name) {
for (size_t i = 0; i < vec.size(); ++i)
if (vec[i].name == name)
return i;
return std::nullopt;
}
SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
SmallVector<size_t, 0> ret;
for (StringRef s : cmd->phdrs) {
if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
ret.push_back(*idx);
else if (s != "NONE")
error(cmd->location + ": program header '" + s +
"' is not listed in PHDRS");
}
return ret;
}
void LinkerScript::printMemoryUsage(raw_ostream& os) {
auto printSize = [&](uint64_t size) {
if ((size & 0x3fffffff) == 0)
os << format_decimal(size >> 30, 10) << " GB";
else if ((size & 0xfffff) == 0)
os << format_decimal(size >> 20, 10) << " MB";
else if ((size & 0x3ff) == 0)
os << format_decimal(size >> 10, 10) << " KB";
else
os << " " << format_decimal(size, 10) << " B";
};
os << "Memory region Used Size Region Size %age Used\n";
for (auto &pair : memoryRegions) {
MemoryRegion *m = pair.second;
uint64_t usedLength = m->curPos - m->getOrigin();
os << right_justify(m->name, 16) << ": ";
printSize(usedLength);
uint64_t length = m->getLength();
if (length != 0) {
printSize(length);
double percent = usedLength * 100.0 / length;
os << " " << format("%6.2f%%", percent);
}
os << '\n';
}
}
void LinkerScript::recordError(const Twine &msg) {
auto &str = recordedErrors.emplace_back();
msg.toVector(str);
}
static void checkMemoryRegion(const MemoryRegion *region,
const OutputSection *osec, uint64_t addr) {
uint64_t osecEnd = addr + osec->size;
uint64_t regionEnd = region->getOrigin() + region->getLength();
if (osecEnd > regionEnd) {
error("section '" + osec->name + "' will not fit in region '" +
region->name + "': overflowed by " + Twine(osecEnd - regionEnd) +
" bytes");
}
}
void LinkerScript::checkFinalScriptConditions() const {
for (StringRef err : recordedErrors)
errorOrWarn(err);
for (const OutputSection *sec : outputSections) {
if (const MemoryRegion *memoryRegion = sec->memRegion)
checkMemoryRegion(memoryRegion, sec, sec->addr);
if (const MemoryRegion *lmaRegion = sec->lmaRegion)
checkMemoryRegion(lmaRegion, sec, sec->getLMA());
}
}
void LinkerScript::addScriptReferencedSymbolsToSymTable() {
auto reference = [](StringRef name) {
Symbol *sym = symtab.addUnusedUndefined(name);
sym->isUsedInRegularObj = true;
sym->referenced = true;
};
for (StringRef name : referencedSymbols)
reference(name);
DenseSet<StringRef> added;
SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;
for (const auto &[name, symRefs] : provideMap)
if (LinkerScript::shouldAddProvideSym(name) && added.insert(name).second)
symRefsVec.push_back(&symRefs);
while (symRefsVec.size()) {
for (StringRef name : *symRefsVec.pop_back_val()) {
reference(name);
script->referencedSymbols.push_back(name);
auto it = script->provideMap.find(name);
if (it != script->provideMap.end() &&
LinkerScript::shouldAddProvideSym(name) &&
added.insert(name).second) {
symRefsVec.push_back(&it->second);
}
}
}
}
bool LinkerScript::shouldAddProvideSym(StringRef symName) {
Symbol *sym = symtab.find(symName);
return sym && !sym->isDefined() && !sym->isCommon();
}