#include "MarkLive.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "LinkerScript.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/Strings.h"
#include "llvm/ADT/DenseMapInfoVariant.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/TimeProfiler.h"
#include <variant>
#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;
namespace {
using SecOffset = std::pair<InputSectionBase *, unsigned>;
using LiveItem = std::variant<InputSectionBase *, Symbol *, SecOffset>;
struct LiveReason {
std::optional<LiveItem> item;
StringRef desc;
};
template <class ELFT, bool TrackWhyLive> class MarkLive {
public:
MarkLive(Ctx &ctx, unsigned partition) : ctx(ctx), partition(partition) {}
void run();
void moveToMain();
void printWhyLive(Symbol *s) const;
private:
void enqueue(InputSectionBase *sec, uint64_t offset, Symbol *sym,
LiveReason reason);
void markSymbol(Symbol *sym, StringRef reason);
void mark();
template <class RelTy>
void resolveReloc(InputSectionBase &sec, const RelTy &rel, bool fromFDE);
void scanEhFrameSection(EhInputSection &eh);
Ctx &ctx;
unsigned partition;
SmallVector<InputSection *, 0> queue;
DenseMap<StringRef, SmallVector<InputSectionBase *, 0>> cNamedSections;
DenseMap<LiveItem, LiveReason> whyLive;
};
}
template <class ELFT>
static uint64_t getAddend(Ctx &ctx, InputSectionBase &sec,
const typename ELFT::Rel &rel) {
return ctx.target->getImplicitAddend(sec.content().begin() + rel.r_offset,
rel.getType(ctx.arg.isMips64EL));
}
template <class ELFT>
static uint64_t getAddend(Ctx &, InputSectionBase &sec,
const typename ELFT::Rela &rel) {
return rel.r_addend;
}
template <class ELFT>
static uint64_t getAddend(Ctx &, InputSectionBase &sec,
const typename ELFT::Crel &rel) {
return rel.r_addend;
}
template <class ELFT, bool TrackWhyLive>
template <class RelTy>
void MarkLive<ELFT, TrackWhyLive>::resolveReloc(InputSectionBase &sec,
const RelTy &rel,
bool fromFDE) {
Symbol *sym;
if constexpr (std::is_same_v<RelTy, Relocation>) {
assert(isa<EhInputSection>(sec));
sym = rel.sym;
} else {
sym = &sec.file->getRelocTargetSym(rel);
}
sym->used = true;
LiveReason reason;
if (TrackWhyLive) {
if constexpr (std::is_same_v<RelTy, Relocation>)
reason = {SecOffset(&sec, rel.offset), "referenced by"};
else
reason = {SecOffset(&sec, rel.r_offset), "referenced by"};
}
if (auto *d = dyn_cast<Defined>(sym)) {
auto *relSec = dyn_cast_or_null<InputSectionBase>(d->section);
if (!relSec)
return;
uint64_t offset = d->value;
if (d->isSection()) {
if constexpr (std::is_same_v<RelTy, Relocation>)
offset += rel.addend;
else
offset += getAddend<ELFT>(ctx, sec, rel);
}
if (!(fromFDE && std::is_same_v<RelTy, Relocation> &&
((relSec->flags & (SHF_EXECINSTR | SHF_LINK_ORDER)) ||
relSec->nextInSectionGroup))) {
Symbol *canonicalSym = d;
if (TrackWhyLive && d->isSection()) {
if (Symbol *s = relSec->getEnclosingSymbol(offset))
canonicalSym = s;
else
canonicalSym = nullptr;
}
enqueue(relSec, offset, canonicalSym, reason);
}
return;
}
if (auto *ss = dyn_cast<SharedSymbol>(sym)) {
if (!ss->isWeak()) {
cast<SharedFile>(ss->file)->isNeeded = true;
if (TrackWhyLive)
whyLive.try_emplace(sym, reason);
}
}
for (InputSectionBase *sec : cNamedSections.lookup(sym->getName()))
enqueue(sec, 0, nullptr, reason);
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::scanEhFrameSection(EhInputSection &eh) {
ArrayRef<Relocation> rels = eh.rels;
for (const EhSectionPiece &cie : eh.cies)
if (cie.firstRelocation != unsigned(-1))
resolveReloc(eh, rels[cie.firstRelocation], false);
for (const EhSectionPiece &fde : eh.fdes) {
size_t firstRelI = fde.firstRelocation;
if (firstRelI == (unsigned)-1)
continue;
uint64_t pieceEnd = fde.inputOff + fde.size;
for (size_t j = firstRelI, end2 = rels.size();
j < end2 && rels[j].offset < pieceEnd; ++j)
resolveReloc(eh, rels[j], true);
}
}
static bool isReserved(InputSectionBase *sec) {
switch (sec->type) {
case SHT_FINI_ARRAY:
case SHT_INIT_ARRAY:
case SHT_PREINIT_ARRAY:
return true;
case SHT_NOTE:
return !sec->nextInSectionGroup;
default:
StringRef s = sec->name;
return s == ".init" || s == ".fini" || s.starts_with(".init_array") ||
s == ".jcr" || s.starts_with(".ctors") || s.starts_with(".dtors");
}
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::enqueue(InputSectionBase *sec,
uint64_t offset, Symbol *sym,
LiveReason reason) {
if (auto *ms = dyn_cast<MergeInputSection>(sec))
ms->getSectionPiece(offset).live = true;
if (sec->partition == 1 || sec->partition == partition)
return;
sec->partition = sec->partition ? 1 : partition;
if (TrackWhyLive) {
if (sym) {
whyLive.try_emplace(sym, reason);
whyLive.try_emplace(sec, LiveReason{sym, "contained live symbol"});
} else {
whyLive.try_emplace(sec, reason);
}
}
if (InputSection *s = dyn_cast<InputSection>(sec))
queue.push_back(s);
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::printWhyLive(Symbol *s) const {
if (auto *d = dyn_cast<Defined>(s)) {
auto *sec = dyn_cast_or_null<InputSectionBase>(d->section);
if (sec && !sec->isLive())
return;
}
auto msg = Msg(ctx);
const auto printSymbol = [&](Symbol *s) {
msg << s->file << ":(" << s << ')';
};
msg << "live symbol: ";
printSymbol(s);
LiveItem cur = s;
while (true) {
auto it = whyLive.find(cur);
LiveReason reason;
if (it != whyLive.end()) {
reason = it->second;
} else {
InputSectionBase *sec = nullptr;
if (auto *d = dyn_cast<Defined>(std::get<Symbol *>(cur)))
sec = dyn_cast_or_null<InputSectionBase>(d->section);
reason = sec ? LiveReason{sec, "in live section"}
: LiveReason{std::nullopt, "no section"};
}
if (!reason.item) {
msg << " (" << reason.desc << ')';
break;
}
msg << "\n>>> " << reason.desc << ": ";
if (std::holds_alternative<SecOffset>(*reason.item)) {
const auto &so = std::get<SecOffset>(*reason.item);
InputSectionBase *sec = so.first;
Defined *sym = sec->getEnclosingSymbol(so.second);
cur = sym ? LiveItem(sym) : LiveItem(sec);
} else {
cur = *reason.item;
}
if (std::holds_alternative<Symbol *>(cur))
printSymbol(std::get<Symbol *>(cur));
else
msg << std::get<InputSectionBase *>(cur);
}
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::markSymbol(Symbol *sym, StringRef reason) {
if (auto *d = dyn_cast_or_null<Defined>(sym))
if (auto *isec = dyn_cast_or_null<InputSectionBase>(d->section))
enqueue(isec, d->value, sym, {std::nullopt, reason});
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::run() {
for (Symbol *sym : ctx.symtab->getSymbols())
if (sym->isExported && sym->partition == partition)
markSymbol(sym, "externally visible symbol; may interpose");
if (partition != 1) {
mark();
return;
}
markSymbol(ctx.symtab->find(ctx.arg.entry), "entry point");
markSymbol(ctx.symtab->find(ctx.arg.init), "initializer function");
markSymbol(ctx.symtab->find(ctx.arg.fini), "finalizer function");
for (StringRef s : ctx.arg.undefined)
markSymbol(ctx.symtab->find(s), "undefined command line flag");
for (StringRef s : ctx.script->referencedSymbols)
markSymbol(ctx.symtab->find(s), "referenced by linker script");
for (auto [symName, _] : ctx.symtab->cmseSymMap) {
markSymbol(ctx.symtab->cmseSymMap[symName].sym, "ARM CMSE symbol");
markSymbol(ctx.symtab->cmseSymMap[symName].acleSeSym, "ARM CMSE symbol");
}
for (EhInputSection *eh : ctx.ehInputSections)
scanEhFrameSection(*eh);
for (InputSectionBase *sec : ctx.inputSections) {
if (sec->flags & SHF_GNU_RETAIN) {
enqueue(sec, 0, nullptr, {std::nullopt, "retained"});
continue;
}
if (sec->flags & SHF_LINK_ORDER)
continue;
if (!(sec->flags & SHF_ALLOC)) {
if (!isStaticRelSecType(sec->type) && !sec->nextInSectionGroup) {
sec->markLive();
for (InputSection *isec : sec->dependentSections)
isec->markLive();
}
}
if (isReserved(sec)) {
enqueue(sec, 0, nullptr, {std::nullopt, "reserved"});
} else if (ctx.script->shouldKeep(sec)) {
enqueue(sec, 0, nullptr,
{std::nullopt, "KEEP in linker script"});
} else if ((!ctx.arg.zStartStopGC || sec->name.starts_with("__libc_")) &&
isValidCIdentifier(sec->name)) {
cNamedSections[ctx.saver.save("__start_" + sec->name)].push_back(sec);
cNamedSections[ctx.saver.save("__stop_" + sec->name)].push_back(sec);
}
}
mark();
if (TrackWhyLive) {
const auto handleSym = [&](Symbol *sym) {
if (llvm::any_of(ctx.arg.whyLive, [sym](const llvm::GlobPattern &pat) {
return pat.match(sym->getName());
}))
printWhyLive(sym);
};
for (Symbol *sym : ctx.symtab->getSymbols())
handleSym(sym);
for (ELFFileBase *file : ctx.objectFiles)
for (Symbol *sym : file->getSymbols())
if (sym->isLocal())
handleSym(sym);
}
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::mark() {
while (!queue.empty()) {
InputSectionBase &sec = *queue.pop_back_val();
const RelsOrRelas<ELFT> rels = sec.template relsOrRelas<ELFT>();
for (const typename ELFT::Rel &rel : rels.rels)
resolveReloc(sec, rel, false);
for (const typename ELFT::Rela &rel : rels.relas)
resolveReloc(sec, rel, false);
for (const typename ELFT::Crel &rel : rels.crels)
resolveReloc(sec, rel, false);
for (InputSectionBase *isec : sec.dependentSections)
enqueue(isec, 0, nullptr,
{&sec, "depended on by section"});
if (sec.nextInSectionGroup)
enqueue(sec.nextInSectionGroup, 0, nullptr,
{&sec, "in section group with"});
}
}
template <class ELFT, bool TrackWhyLive>
void MarkLive<ELFT, TrackWhyLive>::moveToMain() {
for (ELFFileBase *file : ctx.objectFiles)
for (Symbol *s : file->getSymbols())
if (auto *d = dyn_cast<Defined>(s))
if ((d->type == STT_GNU_IFUNC || d->type == STT_TLS) && d->section &&
d->section->isLive())
markSymbol(s, {});
for (InputSectionBase *sec : ctx.inputSections) {
if (!sec->isLive() || !isValidCIdentifier(sec->name))
continue;
if (ctx.symtab->find(("__start_" + sec->name).str()) ||
ctx.symtab->find(("__stop_" + sec->name).str()))
enqueue(sec, 0, nullptr, {});
}
mark();
}
template <class ELFT> void elf::markLive(Ctx &ctx) {
llvm::TimeTraceScope timeScope("markLive");
if (!ctx.arg.gcSections) {
for (Symbol *sym : ctx.symtab->getSymbols())
if (auto *s = dyn_cast<SharedSymbol>(sym))
if (s->isUsedInRegularObj && !s->isWeak())
cast<SharedFile>(s->file)->isNeeded = true;
return;
}
for (InputSectionBase *sec : ctx.inputSections)
sec->markDead();
for (unsigned i = 1, e = ctx.partitions.size(); i <= e; ++i)
if (ctx.arg.whyLive.empty())
MarkLive<ELFT, false>(ctx, i).run();
else
MarkLive<ELFT, true>(ctx, i).run();
if (ctx.partitions.size() != 1)
MarkLive<ELFT, false>(ctx, 1).moveToMain();
if (ctx.arg.printGcSections.empty())
return;
std::error_code ec;
raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.printGcSections, ec);
if (ec) {
Err(ctx) << "cannot open --print-gc-sections= file "
<< ctx.arg.printGcSections << ": " << ec.message();
return;
}
for (InputSectionBase *sec : ctx.inputSections)
if (!sec->isLive())
os << "removing unused section " << toStr(ctx, sec) << '\n';
}
template void elf::markLive<ELF32LE>(Ctx &);
template void elf::markLive<ELF32BE>(Ctx &);
template void elf::markLive<ELF64LE>(Ctx &);
template void elf::markLive<ELF64BE>(Ctx &);