#include "InputSection.h"
#include "Config.h"
#include "InputFiles.h"
#include "OutputSections.h"
#include "Relocations.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/CommonLinkerContext.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
#include <mutex>
#include <optional>
#include <vector>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support;
using namespace llvm::support::endian;
using namespace llvm::sys;
using namespace lld;
using namespace lld::elf;
DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax;
std::string lld::toString(const InputSectionBase *sec) {
return (toString(sec->file) + ":(" + sec->name + ")").str();
}
template <class ELFT>
static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
const typename ELFT::Shdr &hdr) {
if (hdr.sh_type == SHT_NOBITS)
return ArrayRef<uint8_t>(nullptr, hdr.sh_size);
return check(file.getObj().getSectionContents(hdr));
}
InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,
uint32_t type, uint64_t entsize,
uint32_t link, uint32_t info,
uint32_t addralign, ArrayRef<uint8_t> data,
StringRef name, Kind sectionKind)
: SectionBase(sectionKind, name, flags, entsize, addralign, type, info,
link),
file(file), content_(data.data()), size(data.size()) {
if (sectionKind == SectionBase::Merge && content().size() > UINT32_MAX)
error(toString(this) + ": section too large");
uint32_t v = std::max<uint32_t>(addralign, 1);
if (!isPowerOf2_64(v))
fatal(toString(this) + ": sh_addralign is not a power of 2");
this->addralign = v;
if (flags & SHF_COMPRESSED)
invokeELFT(parseCompressedHeader,);
}
static uint64_t getFlags(uint64_t flags) {
flags &= ~(uint64_t)SHF_INFO_LINK;
if (config->resolveGroups)
flags &= ~(uint64_t)SHF_GROUP;
return flags;
}
template <class ELFT>
InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
const typename ELFT::Shdr &hdr,
StringRef name, Kind sectionKind)
: InputSectionBase(&file, getFlags(hdr.sh_flags), hdr.sh_type,
hdr.sh_entsize, hdr.sh_link, hdr.sh_info,
hdr.sh_addralign, getSectionContents(file, hdr), name,
sectionKind) {
if (hdr.sh_addralign > UINT32_MAX)
fatal(toString(&file) + ": section sh_addralign is too large");
}
size_t InputSectionBase::getSize() const {
if (auto *s = dyn_cast<SyntheticSection>(this))
return s->getSize();
return size - bytesDropped;
}
template <class ELFT>
static void decompressAux(const InputSectionBase &sec, uint8_t *out,
size_t size) {
auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(sec.content_);
auto compressed = ArrayRef<uint8_t>(sec.content_, sec.compressedSize)
.slice(sizeof(typename ELFT::Chdr));
if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
? compression::zlib::decompress(compressed, out, size)
: compression::zstd::decompress(compressed, out, size))
fatal(toString(&sec) +
": decompress failed: " + llvm::toString(std::move(e)));
}
void InputSectionBase::decompress() const {
uint8_t *uncompressedBuf;
{
static std::mutex mu;
std::lock_guard<std::mutex> lock(mu);
uncompressedBuf = bAlloc().Allocate<uint8_t>(size);
}
invokeELFT(decompressAux, *this, uncompressedBuf, size);
content_ = uncompressedBuf;
compressed = false;
}
template <class ELFT>
RelsOrRelas<ELFT> InputSectionBase::relsOrRelas(bool supportsCrel) const {
if (relSecIdx == 0)
return {};
RelsOrRelas<ELFT> ret;
auto *f = cast<ObjFile<ELFT>>(file);
typename ELFT::Shdr shdr = f->template getELFShdrs<ELFT>()[relSecIdx];
if (shdr.sh_type == SHT_CREL) {
if (supportsCrel) {
ret.crels = Relocs<typename ELFT::Crel>(
(const uint8_t *)f->mb.getBufferStart() + shdr.sh_offset);
return ret;
}
InputSectionBase *const &relSec = f->getSections()[relSecIdx];
if (!relSec || !cast<InputSection>(relSec)->decodedCrel) {
auto *sec = makeThreadLocal<InputSection>(*f, shdr, name);
f->cacheDecodedCrel(relSecIdx, sec);
sec->type = SHT_RELA;
sec->decodedCrel = true;
RelocsCrel<ELFT::Is64Bits> entries(sec->content_);
sec->size = entries.size() * sizeof(typename ELFT::Rela);
auto *relas = makeThreadLocalN<typename ELFT::Rela>(entries.size());
sec->content_ = reinterpret_cast<uint8_t *>(relas);
for (auto [i, r] : llvm::enumerate(entries)) {
relas[i].r_offset = r.r_offset;
relas[i].setSymbolAndType(r.r_symidx, r.r_type, false);
relas[i].r_addend = r.r_addend;
}
}
ret.relas = {ArrayRef(
reinterpret_cast<const typename ELFT::Rela *>(relSec->content_),
relSec->size / sizeof(typename ELFT::Rela))};
return ret;
}
const void *content = f->mb.getBufferStart() + shdr.sh_offset;
size_t size = shdr.sh_size;
if (shdr.sh_type == SHT_REL) {
ret.rels = {ArrayRef(reinterpret_cast<const typename ELFT::Rel *>(content),
size / sizeof(typename ELFT::Rel))};
} else {
assert(shdr.sh_type == SHT_RELA);
ret.relas = {
ArrayRef(reinterpret_cast<const typename ELFT::Rela *>(content),
size / sizeof(typename ELFT::Rela))};
}
return ret;
}
uint64_t SectionBase::getOffset(uint64_t offset) const {
switch (kind()) {
case Output: {
auto *os = cast<OutputSection>(this);
return offset == uint64_t(-1) ? os->size : offset;
}
case Regular:
case Synthetic:
case Spill:
return cast<InputSection>(this)->outSecOff + offset;
case EHFrame: {
const EhInputSection *es = cast<EhInputSection>(this);
if (!es->content().empty())
if (InputSection *isec = es->getParent())
return isec->outSecOff + es->getParentOffset(offset);
return offset;
}
case Merge:
const MergeInputSection *ms = cast<MergeInputSection>(this);
if (InputSection *isec = ms->getParent())
return isec->outSecOff + ms->getParentOffset(offset);
return ms->getParentOffset(offset);
}
llvm_unreachable("invalid section kind");
}
uint64_t SectionBase::getVA(uint64_t offset) const {
const OutputSection *out = getOutputSection();
return (out ? out->addr : 0) + getOffset(offset);
}
OutputSection *SectionBase::getOutputSection() {
InputSection *sec;
if (auto *isec = dyn_cast<InputSection>(this))
sec = isec;
else if (auto *ms = dyn_cast<MergeInputSection>(this))
sec = ms->getParent();
else if (auto *eh = dyn_cast<EhInputSection>(this))
sec = eh->getParent();
else
return cast<OutputSection>(this);
return sec ? sec->getParent() : nullptr;
}
template <typename ELFT> void InputSectionBase::parseCompressedHeader() {
flags &= ~(uint64_t)SHF_COMPRESSED;
if (content().size() < sizeof(typename ELFT::Chdr)) {
error(toString(this) + ": corrupted compressed section");
return;
}
auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content().data());
if (hdr->ch_type == ELFCOMPRESS_ZLIB) {
if (!compression::zlib::isAvailable())
error(toString(this) + " is compressed with ELFCOMPRESS_ZLIB, but lld is "
"not built with zlib support");
} else if (hdr->ch_type == ELFCOMPRESS_ZSTD) {
if (!compression::zstd::isAvailable())
error(toString(this) + " is compressed with ELFCOMPRESS_ZSTD, but lld is "
"not built with zstd support");
} else {
error(toString(this) + ": unsupported compression type (" +
Twine(hdr->ch_type) + ")");
return;
}
compressed = true;
compressedSize = size;
size = hdr->ch_size;
addralign = std::max<uint32_t>(hdr->ch_addralign, 1);
}
InputSection *InputSectionBase::getLinkOrderDep() const {
assert(flags & SHF_LINK_ORDER);
if (!link)
return nullptr;
return cast<InputSection>(file->getSections()[link]);
}
Defined *InputSectionBase::getEnclosingSymbol(uint64_t offset,
uint8_t type) const {
if (file->isInternal())
return nullptr;
for (Symbol *b : file->getSymbols())
if (Defined *d = dyn_cast<Defined>(b))
if (d->section == this && d->value <= offset &&
offset < d->value + d->size && (type == 0 || type == d->type))
return d;
return nullptr;
}
std::string InputSectionBase::getLocation(uint64_t offset) const {
std::string secAndOffset =
(name + "+0x" + Twine::utohexstr(offset) + ")").str();
if (file == nullptr)
return (config->outputFile + ":(" + secAndOffset).str();
std::string filename = toString(file);
if (Defined *d = getEnclosingFunction(offset))
return filename + ":(function " + toString(*d) + ": " + secAndOffset;
return filename + ":(" + secAndOffset;
}
std::string InputSectionBase::getSrcMsg(const Symbol &sym,
uint64_t offset) const {
return file->getSrcMsg(sym, *this, offset);
}
std::string InputSectionBase::getObjMsg(uint64_t off) const {
std::string filename = std::string(file->getName());
std::string archive;
if (!file->archiveName.empty())
archive = (" in archive " + file->archiveName).str();
if (Defined *d = getEnclosingSymbol(off))
return filename + ":(" + toString(*d) + ")" + archive;
return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)
.str();
}
PotentialSpillSection::PotentialSpillSection(const InputSectionBase &source,
InputSectionDescription &isd)
: InputSection(source.file, source.flags, source.type, source.addralign, {},
source.name, SectionBase::Spill),
isd(&isd) {}
InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,
uint32_t addralign, ArrayRef<uint8_t> data,
StringRef name, Kind k)
: InputSectionBase(f, flags, type,
0, 0, 0, addralign, data,
name, k) {
assert(f || this == &InputSection::discarded);
}
template <class ELFT>
InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::Regular) {}
template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
using u32 = typename ELFT::Word;
ArrayRef<u32> from = getDataAs<u32>();
auto *to = reinterpret_cast<u32 *>(buf);
*to++ = from[0];
ArrayRef<InputSectionBase *> sections = file->getSections();
DenseSet<uint32_t> seen;
for (uint32_t idx : from.slice(1)) {
OutputSection *osec = sections[idx]->getOutputSection();
if (osec && seen.insert(osec->sectionIndex).second)
*to++ = osec->sectionIndex;
}
}
InputSectionBase *InputSection::getRelocatedSection() const {
if (file->isInternal() || !isStaticRelSecType(type))
return nullptr;
ArrayRef<InputSectionBase *> sections = file->getSections();
return sections[info];
}
template <class ELFT, class RelTy>
void InputSection::copyRelocations(uint8_t *buf) {
if (config->relax && !config->relocatable &&
(config->emachine == EM_RISCV || config->emachine == EM_LOONGARCH)) {
InputSectionBase *sec = getRelocatedSection();
copyRelocations<ELFT, RelTy>(buf, llvm::make_range(sec->relocations.begin(),
sec->relocations.end()));
} else {
struct MapRel {
const ObjFile<ELFT> &file;
Relocation operator()(const RelTy &rel) const {
return Relocation{R_NONE, rel.getType(config->isMips64EL), rel.r_offset,
getAddend<ELFT>(rel), &file.getRelocTargetSym(rel)};
}
};
using RawRels = ArrayRef<RelTy>;
using MapRelIter =
llvm::mapped_iterator<typename RawRels::iterator, MapRel>;
auto mapRel = MapRel{*getFile<ELFT>()};
RawRels rawRels = getDataAs<RelTy>();
auto rels = llvm::make_range(MapRelIter(rawRels.begin(), mapRel),
MapRelIter(rawRels.end(), mapRel));
copyRelocations<ELFT, RelTy>(buf, rels);
}
}
template <class ELFT, class RelTy, class RelIt>
void InputSection::copyRelocations(uint8_t *buf,
llvm::iterator_range<RelIt> rels) {
const TargetInfo &target = *elf::target;
InputSectionBase *sec = getRelocatedSection();
(void)sec->contentMaybeDecompress();
for (const Relocation &rel : rels) {
RelType type = rel.type;
const ObjFile<ELFT> *file = getFile<ELFT>();
Symbol &sym = *rel.sym;
auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
buf += sizeof(RelTy);
if (RelTy::HasAddend)
p->r_addend = rel.addend;
p->r_offset = sec->getVA(rel.offset);
p->setSymbolAndType(in.symTab->getSymbolIndex(sym), type,
config->isMips64EL);
if (sym.type == STT_SECTION) {
auto *d = dyn_cast<Defined>(&sym);
if (!d) {
if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&
sec->name != ".gcc_except_table" && sec->name != ".got2" &&
sec->name != ".toc") {
uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;
Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx];
warn("relocation refers to a discarded section: " +
CHECK(file->getObj().getSectionName(sec), file) +
"\n>>> referenced by " + getObjMsg(p->r_offset));
}
p->setSymbolAndType(0, 0, false);
continue;
}
SectionBase *section = d->section;
assert(section->isLive());
int64_t addend = rel.addend;
const uint8_t *bufLoc = sec->content().begin() + rel.offset;
if (!RelTy::HasAddend)
addend = target.getImplicitAddend(bufLoc, type);
if (config->emachine == EM_MIPS &&
target.getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {
addend += sec->getFile<ELFT>()->mipsGp0;
}
if (RelTy::HasAddend)
p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr;
else if (config->relocatable && (sec->flags & SHF_ALLOC) &&
type != target.noneRel)
sec->addReloc({R_ABS, type, rel.offset, addend, &sym});
} else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 &&
p->r_addend >= 0x8000 && sec->file->ppc32Got2) {
p->r_addend += sec->file->ppc32Got2->outSecOff;
}
}
}
static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
uint32_t p) {
switch (type) {
case R_ARM_THM_JUMP8:
case R_ARM_THM_JUMP11:
return p + 2 + a;
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PC24:
case R_ARM_PLT32:
case R_ARM_PREL31:
case R_ARM_THM_JUMP19:
case R_ARM_THM_JUMP24:
return p + 4 + a;
case R_ARM_THM_CALL:
return p + 5 + a;
case R_ARM_MOVW_PREL_NC:
case R_ARM_MOVT_PREL:
case R_ARM_REL32:
case R_ARM_THM_ALU_PREL_11_0:
case R_ARM_THM_MOVW_PREL_NC:
case R_ARM_THM_MOVT_PREL:
case R_ARM_THM_PC12:
return p + a;
case R_ARM_THM_PC8:
return p;
}
llvm_unreachable("ARM pc-relative relocation expected\n");
}
static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
switch (type) {
case R_AARCH64_CALL26:
case R_AARCH64_CONDBR19:
case R_AARCH64_JUMP26:
case R_AARCH64_TSTBR14:
return p + 4;
case R_AARCH64_PREL16:
case R_AARCH64_PREL32:
case R_AARCH64_PREL64:
case R_AARCH64_ADR_PREL_LO21:
case R_AARCH64_LD_PREL_LO19:
case R_AARCH64_PLT32:
return p;
}
llvm_unreachable("AArch64 pc-relative relocation expected\n");
}
static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
switch (type) {
case R_RISCV_BRANCH:
case R_RISCV_JAL:
case R_RISCV_CALL:
case R_RISCV_CALL_PLT:
case R_RISCV_RVC_BRANCH:
case R_RISCV_RVC_JUMP:
case R_RISCV_PLT32:
return p;
default:
return 0;
}
}
static uint64_t getARMStaticBase(const Symbol &sym) {
OutputSection *os = sym.getOutputSection();
if (!os || !os->ptLoad || !os->ptLoad->firstSec)
fatal("SBREL relocation to " + sym.getName() + " without static base");
return os->ptLoad->firstSec->addr;
}
static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) {
const Defined *d = cast<Defined>(sym);
if (!d->section) {
errorOrWarn("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " +
sym->getName());
return nullptr;
}
InputSection *isec = cast<InputSection>(d->section);
if (addend != 0)
warn("non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
isec->getObjMsg(d->value) + " is ignored");
Relocation r;
r.offset = d->value;
auto range =
std::equal_range(isec->relocs().begin(), isec->relocs().end(), r,
[](const Relocation &lhs, const Relocation &rhs) {
return lhs.offset < rhs.offset;
});
for (auto it = range.first; it != range.second; ++it)
if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||
it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)
return &*it;
errorOrWarn("R_RISCV_PCREL_LO12 relocation points to " +
isec->getObjMsg(d->value) +
" without an associated R_RISCV_PCREL_HI20 relocation");
return nullptr;
}
static int64_t getTlsTpOffset(const Symbol &s) {
if (&s == ElfSym::tlsModuleBase)
return 0;
PhdrEntry *tls = Out::tlsPhdr;
switch (config->emachine) {
case EM_ARM:
case EM_AARCH64:
return s.getVA(0) + config->wordsize * 2 +
((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));
case EM_MIPS:
case EM_PPC:
case EM_PPC64:
return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
case EM_LOONGARCH:
case EM_RISCV:
if (s.type != STT_TLS)
return 0;
return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));
case EM_HEXAGON:
case EM_S390:
case EM_SPARCV9:
case EM_386:
case EM_X86_64:
return s.getVA(0) - tls->p_memsz -
((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
default:
llvm_unreachable("unhandled Config->EMachine");
}
}
uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,
int64_t a, uint64_t p,
const Symbol &sym, RelExpr expr) {
switch (expr) {
case R_ABS:
case R_DTPREL:
case R_RELAX_TLS_LD_TO_LE_ABS:
case R_RELAX_GOT_PC_NOPIC:
case R_AARCH64_AUTH:
case R_RISCV_ADD:
case R_RISCV_LEB128:
return sym.getVA(a);
case R_ADDEND:
return a;
case R_RELAX_HINT:
return 0;
case R_ARM_SBREL:
return sym.getVA(a) - getARMStaticBase(sym);
case R_GOT:
case R_RELAX_TLS_GD_TO_IE_ABS:
return sym.getGotVA() + a;
case R_LOONGARCH_GOT:
if (sym.hasFlag(NEEDS_TLSGD) && type != R_LARCH_TLS_IE_PC_LO12)
return in.got->getGlobalDynAddr(sym) + a;
return getRelocTargetVA(file, type, a, p, sym, R_GOT);
case R_GOTONLY_PC:
return in.got->getVA() + a - p;
case R_GOTPLTONLY_PC:
return in.gotPlt->getVA() + a - p;
case R_GOTREL:
case R_PPC64_RELAX_TOC:
return sym.getVA(a) - in.got->getVA();
case R_GOTPLTREL:
return sym.getVA(a) - in.gotPlt->getVA();
case R_GOTPLT:
case R_RELAX_TLS_GD_TO_IE_GOTPLT:
return sym.getGotVA() + a - in.gotPlt->getVA();
case R_TLSLD_GOT_OFF:
case R_GOT_OFF:
case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
return sym.getGotOffset() + a;
case R_AARCH64_GOT_PAGE_PC:
case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);
case R_AARCH64_GOT_PAGE:
return sym.getGotVA() + a - getAArch64Page(in.got->getVA());
case R_GOT_PC:
case R_RELAX_TLS_GD_TO_IE:
return sym.getGotVA() + a - p;
case R_GOTPLT_GOTREL:
return sym.getGotPltVA() + a - in.got->getVA();
case R_GOTPLT_PC:
return sym.getGotPltVA() + a - p;
case R_LOONGARCH_GOT_PAGE_PC:
if (sym.hasFlag(NEEDS_TLSGD))
return getLoongArchPageDelta(in.got->getGlobalDynAddr(sym) + a, p, type);
return getLoongArchPageDelta(sym.getGotVA() + a, p, type);
case R_MIPS_GOTREL:
return sym.getVA(a) - in.mipsGot->getGp(file);
case R_MIPS_GOT_GP:
return in.mipsGot->getGp(file) + a;
case R_MIPS_GOT_GP_PC: {
uint64_t v = in.mipsGot->getGp(file) + a - p;
if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)
v += 4;
if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)
v -= 1;
return v;
}
case R_MIPS_GOT_LOCAL_PAGE:
return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -
in.mipsGot->getGp(file);
case R_MIPS_GOT_OFF:
case R_MIPS_GOT_OFF32:
return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -
in.mipsGot->getGp(file);
case R_MIPS_TLSGD:
return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -
in.mipsGot->getGp(file);
case R_MIPS_TLSLD:
return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -
in.mipsGot->getGp(file);
case R_AARCH64_PAGE_PC: {
uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);
return getAArch64Page(val) - getAArch64Page(p);
}
case R_RISCV_PC_INDIRECT: {
if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))
return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),
*hiRel->sym, hiRel->expr);
return 0;
}
case R_LOONGARCH_PAGE_PC:
return getLoongArchPageDelta(sym.getVA(a), p, type);
case R_PC:
case R_ARM_PCA: {
uint64_t dest;
if (expr == R_ARM_PCA)
p = p & 0xfffffffc;
if (sym.isUndefined()) {
if (config->emachine == EM_ARM)
dest = getARMUndefinedRelativeWeakVA(type, a, p);
else if (config->emachine == EM_AARCH64)
dest = getAArch64UndefinedRelativeWeakVA(type, p) + a;
else if (config->emachine == EM_PPC)
dest = p;
else if (config->emachine == EM_RISCV)
dest = getRISCVUndefinedRelativeWeakVA(type, p) + a;
else
dest = sym.getVA(a);
} else {
dest = sym.getVA(a);
}
return dest - p;
}
case R_PLT:
return sym.getPltVA() + a;
case R_PLT_PC:
case R_PPC64_CALL_PLT:
return sym.getPltVA() + a - p;
case R_LOONGARCH_PLT_PAGE_PC:
return getLoongArchPageDelta(sym.getPltVA() + a, p, type);
case R_PLT_GOTPLT:
return sym.getPltVA() + a - in.gotPlt->getVA();
case R_PLT_GOTREL:
return sym.getPltVA() + a - in.got->getVA();
case R_PPC32_PLTREL:
return sym.getPltVA() - p;
case R_PPC64_CALL: {
uint64_t symVA = sym.getVA(a);
if (!symVA)
return 0;
return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);
}
case R_PPC64_TOCBASE:
return getPPC64TocBase() + a;
case R_RELAX_GOT_PC:
case R_PPC64_RELAX_GOT_PC:
return sym.getVA(a) - p;
case R_RELAX_TLS_GD_TO_LE:
case R_RELAX_TLS_IE_TO_LE:
case R_RELAX_TLS_LD_TO_LE:
case R_TPREL:
if (sym.isUndefined())
return a;
return getTlsTpOffset(sym) + a;
case R_RELAX_TLS_GD_TO_LE_NEG:
case R_TPREL_NEG:
if (sym.isUndefined())
return a;
return -getTlsTpOffset(sym) + a;
case R_SIZE:
return sym.getSize() + a;
case R_TLSDESC:
return in.got->getTlsDescAddr(sym) + a;
case R_TLSDESC_PC:
return in.got->getTlsDescAddr(sym) + a - p;
case R_TLSDESC_GOTPLT:
return in.got->getTlsDescAddr(sym) + a - in.gotPlt->getVA();
case R_AARCH64_TLSDESC_PAGE:
return getAArch64Page(in.got->getTlsDescAddr(sym) + a) - getAArch64Page(p);
case R_LOONGARCH_TLSDESC_PAGE_PC:
return getLoongArchPageDelta(in.got->getTlsDescAddr(sym) + a, p, type);
case R_TLSGD_GOT:
return in.got->getGlobalDynOffset(sym) + a;
case R_TLSGD_GOTPLT:
return in.got->getGlobalDynAddr(sym) + a - in.gotPlt->getVA();
case R_TLSGD_PC:
return in.got->getGlobalDynAddr(sym) + a - p;
case R_LOONGARCH_TLSGD_PAGE_PC:
return getLoongArchPageDelta(in.got->getGlobalDynAddr(sym) + a, p, type);
case R_TLSLD_GOTPLT:
return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();
case R_TLSLD_GOT:
return in.got->getTlsIndexOff() + a;
case R_TLSLD_PC:
return in.got->getTlsIndexVA() + a - p;
default:
llvm_unreachable("invalid expression");
}
}
template <class ELFT, class RelTy>
void InputSection::relocateNonAlloc(uint8_t *buf, Relocs<RelTy> rels) {
const unsigned bits = sizeof(typename ELFT::uint) * 8;
const TargetInfo &target = *elf::target;
const auto emachine = config->emachine;
const bool isDebug = isDebugSection(*this);
const bool isDebugLine = isDebug && name == ".debug_line";
std::optional<uint64_t> tombstone;
if (isDebug) {
if (name == ".debug_loc" || name == ".debug_ranges")
tombstone = 1;
else if (name == ".debug_names")
tombstone = UINT64_MAX;
else
tombstone = 0;
}
for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))
if (patAndValue.first.match(this->name)) {
tombstone = patAndValue.second;
break;
}
const InputFile *f = this->file;
for (auto it = rels.begin(), end = rels.end(); it != end; ++it) {
const RelTy &rel = *it;
const RelType type = rel.getType(config->isMips64EL);
const uint64_t offset = rel.r_offset;
uint8_t *bufLoc = buf + offset;
int64_t addend = getAddend<ELFT>(rel);
if (!RelTy::HasAddend)
addend += target.getImplicitAddend(bufLoc, type);
Symbol &sym = f->getRelocTargetSym(rel);
RelExpr expr = target.getRelExpr(type, sym, bufLoc);
if (expr == R_NONE)
continue;
auto *ds = dyn_cast<Defined>(&sym);
if (emachine == EM_RISCV && type == R_RISCV_SET_ULEB128) {
if (++it != end &&
it->getType(false) == R_RISCV_SUB_ULEB128 &&
it->r_offset == offset) {
uint64_t val;
if (!ds && tombstone) {
val = *tombstone;
} else {
val = sym.getVA(addend) -
(f->getRelocTargetSym(*it).getVA(0) + getAddend<ELFT>(*it));
}
if (overwriteULEB128(bufLoc, val) >= 0x80)
errorOrWarn(getLocation(offset) + ": ULEB128 value " + Twine(val) +
" exceeds available space; references '" +
lld::toString(sym) + "'");
continue;
}
errorOrWarn(getLocation(offset) +
": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");
return;
}
if (tombstone && (expr == R_ABS || expr == R_DTPREL)) {
if (!ds || (ds->folded && !isDebugLine)) {
uint64_t value = SignExtend64<bits>(*tombstone);
if (emachine == EM_X86_64 && type == R_X86_64_32)
value = static_cast<uint32_t>(value);
target.relocateNoSym(bufLoc, type, value);
continue;
}
}
if (config->relocatable && (RelTy::HasAddend || sym.type != STT_SECTION))
continue;
if (LLVM_LIKELY(expr == R_ABS) || expr == R_DTPREL || expr == R_GOTPLTREL ||
expr == R_RISCV_ADD) {
target.relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));
continue;
}
if (expr == R_SIZE) {
target.relocateNoSym(bufLoc, type,
SignExtend64<bits>(sym.getSize() + addend));
continue;
}
std::string msg = getLocation(offset) + ": has non-ABS relocation " +
toString(type) + " against symbol '" + toString(sym) +
"'";
if (expr != R_PC && !(emachine == EM_386 && type == R_386_GOTPC)) {
errorOrWarn(msg);
return;
}
warn(msg);
target.relocateNoSym(
bufLoc, type,
SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));
}
}
template <class ELFT>
void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {
if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))
adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);
if (flags & SHF_ALLOC) {
target->relocateAlloc(*this, buf);
return;
}
auto *sec = cast<InputSection>(this);
invokeOnRelocs(*sec, sec->relocateNonAlloc<ELFT>, buf);
}
static void switchMorestackCallsToMorestackNonSplit(
DenseSet<Defined *> &prologues,
SmallVector<Relocation *, 0> &morestackCalls) {
Symbol *moreStackNonSplit = symtab.find("__morestack_non_split");
if (!moreStackNonSplit) {
error("mixing split-stack objects requires a definition of "
"__morestack_non_split");
return;
}
llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
return l->offset < r->offset;
});
std::vector<Defined *> functions(prologues.begin(), prologues.end());
llvm::sort(functions, [](const Defined *l, const Defined *r) {
return l->value < r->value;
});
auto it = morestackCalls.begin();
for (Defined *f : functions) {
while (it != morestackCalls.end() && (*it)->offset < f->value)
++it;
while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
(*it)->sym = moreStackNonSplit;
++it;
}
}
}
static bool enclosingPrologueAttempted(uint64_t offset,
const DenseSet<Defined *> &prologues) {
for (Defined *f : prologues)
if (f->value <= offset && offset < f->value + f->size)
return true;
return false;
}
template <class ELFT>
void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,
uint8_t *end) {
DenseSet<Defined *> prologues;
SmallVector<Relocation *, 0> morestackCalls;
for (Relocation &rel : relocs()) {
if (rel.sym->getName().starts_with("__morestack")) {
if (rel.sym->getName() == "__morestack")
morestackCalls.push_back(&rel);
continue;
}
if (rel.sym->type != STT_FUNC)
continue;
if (Defined *d = dyn_cast<Defined>(rel.sym))
if (InputSection *isec = cast_or_null<InputSection>(d->section))
if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
continue;
if (enclosingPrologueAttempted(rel.offset, prologues))
continue;
if (Defined *f = getEnclosingFunction(rel.offset)) {
prologues.insert(f);
if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,
f->stOther))
continue;
if (!getFile<ELFT>()->someNoSplitStack)
error(lld::toString(this) + ": " + f->getName() +
" (with -fsplit-stack) calls " + rel.sym->getName() +
" (without -fsplit-stack), but couldn't adjust its prologue");
}
}
if (target->needsMoreStackNonSplit)
switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);
}
template <class ELFT> void InputSection::writeTo(uint8_t *buf) {
if (LLVM_UNLIKELY(type == SHT_NOBITS))
return;
if (LLVM_UNLIKELY(type == SHT_RELA)) {
copyRelocations<ELFT, typename ELFT::Rela>(buf);
return;
}
if (LLVM_UNLIKELY(type == SHT_REL)) {
copyRelocations<ELFT, typename ELFT::Rel>(buf);
return;
}
if (LLVM_UNLIKELY(type == SHT_GROUP)) {
copyShtGroup<ELFT>(buf);
return;
}
if (compressed) {
auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content_);
auto compressed = ArrayRef<uint8_t>(content_, compressedSize)
.slice(sizeof(typename ELFT::Chdr));
size_t size = this->size;
if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
? compression::zlib::decompress(compressed, buf, size)
: compression::zstd::decompress(compressed, buf, size))
fatal(toString(this) +
": decompress failed: " + llvm::toString(std::move(e)));
uint8_t *bufEnd = buf + size;
relocate<ELFT>(buf, bufEnd);
return;
}
memcpy(buf, content().data(), content().size());
relocate<ELFT>(buf, buf + content().size());
}
void InputSection::replace(InputSection *other) {
addralign = std::max(addralign, other->addralign);
if (partition != other->partition) {
partition = 1;
for (InputSection *isec : dependentSections)
isec->partition = 1;
}
other->repl = repl;
other->markDead();
}
template <class ELFT>
EhInputSection::EhInputSection(ObjFile<ELFT> &f,
const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
SyntheticSection *EhInputSection::getParent() const {
return cast_or_null<SyntheticSection>(parent);
}
template <class ELFT> void EhInputSection::split() {
const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>(false);
if (rels.areRelocsRel()) {
SmallVector<typename ELFT::Rel, 0> storage;
split<ELFT>(sortRels(rels.rels, storage));
} else {
SmallVector<typename ELFT::Rela, 0> storage;
split<ELFT>(sortRels(rels.relas, storage));
}
}
template <class ELFT, class RelTy>
void EhInputSection::split(ArrayRef<RelTy> rels) {
ArrayRef<uint8_t> d = content();
const char *msg = nullptr;
unsigned relI = 0;
while (!d.empty()) {
if (d.size() < 4) {
msg = "CIE/FDE too small";
break;
}
uint64_t size = endian::read32<ELFT::Endianness>(d.data());
if (size == 0)
break;
uint32_t id = endian::read32<ELFT::Endianness>(d.data() + 4);
size += 4;
if (LLVM_UNLIKELY(size > d.size())) {
msg = size == UINT32_MAX + uint64_t(4)
? "CIE/FDE too large"
: "CIE/FDE ends past the end of the section";
break;
}
const uint64_t off = d.data() - content().data();
while (relI != rels.size() && rels[relI].r_offset < off)
++relI;
unsigned firstRel = -1;
if (relI != rels.size() && rels[relI].r_offset < off + size)
firstRel = relI;
(id == 0 ? cies : fdes).emplace_back(off, this, size, firstRel);
d = d.slice(size);
}
if (msg)
errorOrWarn("corrupted .eh_frame: " + Twine(msg) + "\n>>> defined in " +
getObjMsg(d.data() - content().data()));
}
uint64_t EhInputSection::getParentOffset(uint64_t offset) const {
auto it = partition_point(
fdes, [=](EhSectionPiece p) { return p.inputOff <= offset; });
if (it == fdes.begin() || it[-1].inputOff + it[-1].size <= offset) {
it = partition_point(
cies, [=](EhSectionPiece p) { return p.inputOff <= offset; });
if (it == cies.begin())
return offset;
}
if (it[-1].outputOff == -1)
return offset - it[-1].inputOff;
return it[-1].outputOff + (offset - it[-1].inputOff);
}
static size_t findNull(StringRef s, size_t entSize) {
for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
const char *b = s.begin() + i;
if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
return i;
}
llvm_unreachable("");
}
void MergeInputSection::splitStrings(StringRef s, size_t entSize) {
const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
const char *p = s.data(), *end = s.data() + s.size();
if (!std::all_of(end - entSize, end, [](char c) { return c == 0; }))
fatal(toString(this) + ": string is not null terminated");
if (entSize == 1) {
do {
size_t size = strlen(p);
pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);
p += size + 1;
} while (p != end);
} else {
do {
size_t size = findNull(StringRef(p, end - p), entSize);
pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);
p += size + entSize;
} while (p != end);
}
}
void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
size_t entSize) {
size_t size = data.size();
assert((size % entSize) == 0);
const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
pieces.resize_for_overwrite(size / entSize);
for (size_t i = 0, j = 0; i != size; i += entSize, j++)
pieces[j] = {i, (uint32_t)xxh3_64bits(data.slice(i, entSize)), live};
}
template <class ELFT>
MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::Merge) {}
MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,
uint64_t entsize, ArrayRef<uint8_t> data,
StringRef name)
: InputSectionBase(nullptr, flags, type, entsize, 0, 0,
entsize, data, name, SectionBase::Merge) {}
void MergeInputSection::splitIntoPieces() {
assert(pieces.empty());
if (flags & SHF_STRINGS)
splitStrings(toStringRef(contentMaybeDecompress()), entsize);
else
splitNonStrings(contentMaybeDecompress(), entsize);
}
SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {
if (content().size() <= offset)
fatal(toString(this) + ": offset is outside the section");
return partition_point(
pieces, [=](SectionPiece p) { return p.inputOff <= offset; })[-1];
}
uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
const SectionPiece &piece = getSectionPiece(offset);
return piece.outputOff + (offset - piece.inputOff);
}
template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
StringRef);
template void InputSection::writeTo<ELF32LE>(uint8_t *);
template void InputSection::writeTo<ELF32BE>(uint8_t *);
template void InputSection::writeTo<ELF64LE>(uint8_t *);
template void InputSection::writeTo<ELF64BE>(uint8_t *);
template RelsOrRelas<ELF32LE>
InputSectionBase::relsOrRelas<ELF32LE>(bool) const;
template RelsOrRelas<ELF32BE>
InputSectionBase::relsOrRelas<ELF32BE>(bool) const;
template RelsOrRelas<ELF64LE>
InputSectionBase::relsOrRelas<ELF64LE>(bool) const;
template RelsOrRelas<ELF64BE>
InputSectionBase::relsOrRelas<ELF64BE>(bool) const;
template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
const ELF32LE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
const ELF32BE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
const ELF64LE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
const ELF64BE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
const ELF32LE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
const ELF32BE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
const ELF64LE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
const ELF64BE::Shdr &, StringRef);
template void EhInputSection::split<ELF32LE>();
template void EhInputSection::split<ELF32BE>();
template void EhInputSection::split<ELF64LE>();
template void EhInputSection::split<ELF64BE>();