#include "Symbols.h"
#include "Driver.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/Support/Compiler.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
static_assert(sizeof(SymbolUnion) <= 64, "SymbolUnion too large");
template <typename T> struct AssertSymbol {
static_assert(std::is_trivially_destructible<T>(),
"Symbol types must be trivially destructible");
static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
static_assert(alignof(T) <= alignof(SymbolUnion),
"SymbolUnion not aligned enough");
};
[[maybe_unused]] static inline void assertSymbols() {
AssertSymbol<Defined>();
AssertSymbol<CommonSymbol>();
AssertSymbol<Undefined>();
AssertSymbol<SharedSymbol>();
AssertSymbol<LazySymbol>();
}
static std::string maybeDemangleSymbol(Ctx &ctx, StringRef symName) {
return ctx.arg.demangle ? demangle(symName.str()) : symName.str();
}
std::string elf::toStr(Ctx &ctx, const elf::Symbol &sym) {
StringRef name = sym.getName();
std::string ret = maybeDemangleSymbol(ctx, name);
const char *suffix = sym.getVersionSuffix();
if (*suffix == '@')
ret += suffix;
return ret;
}
const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
const Symbol *sym) {
return s << toStr(s.ctx, *sym);
}
static uint64_t getSymVA(Ctx &ctx, const Symbol &sym, int64_t addend) {
switch (sym.kind()) {
case Symbol::DefinedKind: {
auto &d = cast<Defined>(sym);
SectionBase *isec = d.section;
if (!isec)
return d.value;
assert(isec != &InputSection::discarded);
uint64_t offset = d.value;
if (d.isSection())
offset += addend;
uint64_t va = isec->getVA(offset);
if (d.isSection())
va -= addend;
if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx) &&
((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(NEEDS_COPY)))
va |= 1;
if (d.isTls() && !ctx.arg.relocatable) {
if (!ctx.tlsPhdr || !ctx.tlsPhdr->firstSec) {
Err(ctx) << d.file
<< " has an STT_TLS symbol but doesn't have a PT_TLS segment";
return 0;
}
return va - ctx.tlsPhdr->firstSec->addr;
}
return va;
}
case Symbol::SharedKind:
case Symbol::UndefinedKind:
return 0;
case Symbol::LazyKind:
llvm_unreachable("lazy symbol reached writer");
case Symbol::CommonKind:
llvm_unreachable("common symbol reached writer");
case Symbol::PlaceholderKind:
llvm_unreachable("placeholder symbol reached writer");
}
llvm_unreachable("invalid symbol kind");
}
uint64_t Symbol::getVA(Ctx &ctx, int64_t addend) const {
return getSymVA(ctx, *this, addend) + addend;
}
uint64_t Symbol::getGotVA(Ctx &ctx) const {
if (gotInIgot)
return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
return ctx.in.got->getVA() + getGotOffset(ctx);
}
uint64_t Symbol::getGotOffset(Ctx &ctx) const {
return getGotIdx(ctx) * ctx.target->gotEntrySize;
}
uint64_t Symbol::getGotPltVA(Ctx &ctx) const {
if (isInIplt)
return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
return ctx.in.gotPlt->getVA() + getGotPltOffset(ctx);
}
uint64_t Symbol::getGotPltOffset(Ctx &ctx) const {
if (isInIplt)
return getPltIdx(ctx) * ctx.target->gotEntrySize;
return (getPltIdx(ctx) + ctx.target->gotPltHeaderEntriesNum) *
ctx.target->gotEntrySize;
}
uint64_t Symbol::getPltVA(Ctx &ctx) const {
uint64_t outVA = isInIplt ? ctx.in.iplt->getVA() +
getPltIdx(ctx) * ctx.target->ipltEntrySize
: ctx.in.plt->getVA() + ctx.in.plt->headerSize +
getPltIdx(ctx) * ctx.target->pltEntrySize;
if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx))
outVA |= 1;
return outVA;
}
uint64_t Symbol::getSize() const {
if (const auto *dr = dyn_cast<Defined>(this))
return dr->size;
return cast<SharedSymbol>(this)->size;
}
OutputSection *Symbol::getOutputSection() const {
if (auto *s = dyn_cast<Defined>(this)) {
if (auto *sec = s->section)
return sec->getOutputSection();
return nullptr;
}
return nullptr;
}
void Symbol::parseSymbolVersion(Ctx &ctx) {
if (versionId == VER_NDX_LOCAL)
return;
StringRef s = getName();
size_t pos = s.find('@');
if (pos == StringRef::npos)
return;
StringRef verstr = s.substr(pos + 1);
nameSize = pos;
if (verstr.empty())
return;
if (!isDefined())
return;
bool isDefault = (verstr[0] == '@');
if (isDefault)
verstr = verstr.substr(1);
for (const VersionDefinition &ver : namedVersionDefs(ctx)) {
if (ver.name != verstr)
continue;
if (isDefault)
versionId = ver.id;
else
versionId = ver.id | VERSYM_HIDDEN;
return;
}
if (ctx.arg.shared && versionId != VER_NDX_LOCAL)
ErrAlways(ctx) << file << ": symbol " << s << " has undefined version "
<< verstr;
}
void Symbol::extract(Ctx &ctx) const {
assert(file->lazy);
file->lazy = false;
parseFile(ctx, file);
}
uint8_t Symbol::computeBinding(Ctx &ctx) const {
auto v = visibility();
if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
return STB_LOCAL;
if (binding == STB_GNU_UNIQUE && !ctx.arg.gnuUnique)
return STB_GLOBAL;
return binding;
}
void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
std::string s;
if (sym.isUndefined())
s = ": reference to ";
else if (sym.isLazy())
s = ": lazy definition of ";
else if (sym.isShared())
s = ": shared definition of ";
else if (sym.isCommon())
s = ": common definition of ";
else
s = ": definition of ";
Msg(sym.file->ctx) << sym.file << s << name;
}
static void recordWhyExtract(Ctx &ctx, const InputFile *reference,
const InputFile &extracted, const Symbol &sym) {
ctx.whyExtractRecords.emplace_back(toStr(ctx, reference), &extracted, sym);
}
void elf::maybeWarnUnorderableSymbol(Ctx &ctx, const Symbol *sym) {
if (!ctx.arg.warnSymbolOrdering)
return;
if (sym->isUndefined() && !cast<Undefined>(sym)->discardedSecIdx &&
ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore)
return;
const InputFile *file = sym->file;
auto *d = dyn_cast<Defined>(sym);
auto report = [&](StringRef s) { Warn(ctx) << file << s << sym->getName(); };
if (sym->isUndefined()) {
if (cast<Undefined>(sym)->discardedSecIdx)
report(": unable to order discarded symbol: ");
else
report(": unable to order undefined symbol: ");
} else if (sym->isShared())
report(": unable to order shared symbol: ");
else if (d && !d->section)
report(": unable to order absolute symbol: ");
else if (d && isa<OutputSection>(d->section))
report(": unable to order synthetic symbol: ");
else if (d && !d->section->isLive())
report(": unable to order discarded symbol: ");
}
bool elf::computeIsPreemptible(Ctx &ctx, const Symbol &sym) {
assert(!sym.isLocal() || sym.isPlaceholder());
if (sym.visibility() != STV_DEFAULT)
return false;
if (!sym.isDefined())
return !sym.isUndefined() || ctx.arg.zDynamicUndefined;
if (!ctx.arg.shared)
return false;
if (ctx.arg.symbolic ||
(ctx.arg.bsymbolic == BsymbolicKind::NonWeak &&
sym.binding != STB_WEAK) ||
(ctx.arg.bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
(ctx.arg.bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
sym.binding != STB_WEAK))
return sym.inDynamicList;
return true;
}
void elf::parseVersionAndComputeIsPreemptible(Ctx &ctx) {
for (Symbol *sym : ctx.symtab->getSymbols()) {
if (sym->hasVersionSuffix)
sym->parseSymbolVersion(ctx);
if (sym->computeBinding(ctx) == STB_LOCAL) {
sym->isExported = false;
continue;
}
if (!sym->isDefined() && !sym->isCommon()) {
sym->isPreemptible = computeIsPreemptible(ctx, *sym);
} else if (ctx.arg.exportDynamic &&
(sym->isUsedInRegularObj || !sym->ltoCanOmit)) {
sym->isExported = true;
sym->isPreemptible = computeIsPreemptible(ctx, *sym);
}
}
}
void Symbol::mergeProperties(const Symbol &other) {
if (!other.isShared() && other.visibility() != STV_DEFAULT) {
uint8_t v = visibility(), ov = other.visibility();
setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
}
}
void Symbol::resolve(Ctx &ctx, const Undefined &other) {
if (other.visibility() != STV_DEFAULT) {
uint8_t v = visibility(), ov = other.visibility();
setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
}
if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
(isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
other.overwrite(*this);
return;
}
if (traced)
printTraceSymbol(other, getName());
if (isLazy()) {
if (other.binding == STB_WEAK) {
binding = STB_WEAK;
type = other.type;
return;
}
bool backref = ctx.arg.warnBackrefs && file->groupId < other.file->groupId;
extract(ctx);
if (!ctx.arg.whyExtract.empty())
recordWhyExtract(ctx, other.file, *file, *this);
if (backref && !isWeak())
ctx.backwardReferences.try_emplace(this,
std::make_pair(other.file, file));
return;
}
if (isa<SharedFile>(other.file))
return;
if (isUndefined() || isShared()) {
if (other.binding != STB_WEAK || !referenced)
binding = other.binding;
}
}
bool Symbol::shouldReplace(Ctx &ctx, const Defined &other) const {
if (LLVM_UNLIKELY(isCommon())) {
if (ctx.arg.warnCommon)
Warn(ctx) << "common " << getName() << " is overridden";
return !other.isWeak();
}
if (!isDefined())
return true;
return !isGlobal() && other.isGlobal();
}
void elf::reportDuplicate(Ctx &ctx, const Symbol &sym, const InputFile *newFile,
InputSectionBase *errSec, uint64_t errOffset) {
if (ctx.arg.allowMultipleDefinition)
return;
const Defined *d = dyn_cast<Defined>(&sym);
if (!d || d->getName() == "__x86.get_pc_thunk.bx")
return;
if (!d->section && !errSec && errOffset && d->value == errOffset)
return;
if (!d->section || !errSec) {
Err(ctx) << "duplicate symbol: " << &sym << "\n>>> defined in " << sym.file
<< "\n>>> defined in " << newFile;
return;
}
auto *sec1 = cast<InputSectionBase>(d->section);
auto diag = Err(ctx);
diag << "duplicate symbol: " << &sym << "\n>>> defined at ";
auto tell = diag.tell();
diag << sec1->getSrcMsg(sym, d->value);
if (tell != diag.tell())
diag << "\n>>> ";
diag << sec1->getObjMsg(d->value) << "\n>>> defined at ";
tell = diag.tell();
diag << errSec->getSrcMsg(sym, errOffset);
if (tell != diag.tell())
diag << "\n>>> ";
diag << errSec->getObjMsg(errOffset);
}
void Symbol::checkDuplicate(Ctx &ctx, const Defined &other) const {
if (isDefined() && !isWeak() && !other.isWeak())
reportDuplicate(ctx, *this, other.file,
dyn_cast_or_null<InputSectionBase>(other.section),
other.value);
}
void Symbol::resolve(Ctx &ctx, const CommonSymbol &other) {
if (other.visibility() != STV_DEFAULT) {
uint8_t v = visibility(), ov = other.visibility();
setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
}
if (isDefined() && !isWeak()) {
if (ctx.arg.warnCommon)
Warn(ctx) << "common " << getName() << " is overridden";
return;
}
if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
if (ctx.arg.warnCommon)
Warn(ctx) << "multiple common of " << getName();
oldSym->alignment = std::max(oldSym->alignment, other.alignment);
if (oldSym->size < other.size) {
oldSym->file = other.file;
oldSym->size = other.size;
}
return;
}
if (auto *s = dyn_cast<SharedSymbol>(this)) {
uint64_t size = s->size;
other.overwrite(*this);
if (size > cast<CommonSymbol>(this)->size)
cast<CommonSymbol>(this)->size = size;
} else {
other.overwrite(*this);
}
}
void Symbol::resolve(Ctx &ctx, const Defined &other) {
if (other.visibility() != STV_DEFAULT) {
uint8_t v = visibility(), ov = other.visibility();
setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
}
if (shouldReplace(ctx, other))
other.overwrite(*this);
}
void Symbol::resolve(Ctx &ctx, const LazySymbol &other) {
if (isPlaceholder()) {
other.overwrite(*this);
return;
}
if (LLVM_UNLIKELY(!isUndefined())) {
if (isDefined()) {
ctx.backwardReferences.erase(this);
} else if (isCommon() && ctx.arg.fortranCommon &&
other.file->shouldExtractForCommon(getName())) {
ctx.backwardReferences.erase(this);
other.overwrite(*this);
other.extract(ctx);
}
return;
}
if (isWeak()) {
uint8_t ty = type;
other.overwrite(*this);
type = ty;
binding = STB_WEAK;
return;
}
const InputFile *oldFile = file;
other.extract(ctx);
if (!ctx.arg.whyExtract.empty())
recordWhyExtract(ctx, oldFile, *file, *this);
}
void Symbol::resolve(Ctx &ctx, const SharedSymbol &other) {
isExported = true;
if (isPlaceholder()) {
other.overwrite(*this);
return;
}
if (isCommon()) {
if (other.size > cast<CommonSymbol>(this)->size)
cast<CommonSymbol>(this)->size = other.size;
return;
}
if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
uint8_t bind = binding;
other.overwrite(*this);
binding = bind;
} else if (traced)
printTraceSymbol(other, getName());
}
void Defined::overwrite(Symbol &sym) const {
if (isa_and_nonnull<SharedFile>(sym.file))
sym.versionId = VER_NDX_GLOBAL;
Symbol::overwrite(sym, DefinedKind);
auto &s = static_cast<Defined &>(sym);
s.value = value;
s.size = size;
s.section = section;
}