Path: blob/main/contrib/llvm-project/lld/ELF/InputSection.cpp
34869 views
//===- InputSection.cpp ---------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "InputSection.h"9#include "Config.h"10#include "InputFiles.h"11#include "OutputSections.h"12#include "Relocations.h"13#include "SymbolTable.h"14#include "Symbols.h"15#include "SyntheticSections.h"16#include "Target.h"17#include "lld/Common/CommonLinkerContext.h"18#include "llvm/Support/Compiler.h"19#include "llvm/Support/Compression.h"20#include "llvm/Support/Endian.h"21#include "llvm/Support/xxhash.h"22#include <algorithm>23#include <mutex>24#include <optional>25#include <vector>2627using namespace llvm;28using namespace llvm::ELF;29using namespace llvm::object;30using namespace llvm::support;31using namespace llvm::support::endian;32using namespace llvm::sys;33using namespace lld;34using namespace lld::elf;3536DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax;3738// Returns a string to construct an error message.39std::string lld::toString(const InputSectionBase *sec) {40return (toString(sec->file) + ":(" + sec->name + ")").str();41}4243template <class ELFT>44static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,45const typename ELFT::Shdr &hdr) {46if (hdr.sh_type == SHT_NOBITS)47return ArrayRef<uint8_t>(nullptr, hdr.sh_size);48return check(file.getObj().getSectionContents(hdr));49}5051InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,52uint32_t type, uint64_t entsize,53uint32_t link, uint32_t info,54uint32_t addralign, ArrayRef<uint8_t> data,55StringRef name, Kind sectionKind)56: SectionBase(sectionKind, name, flags, entsize, addralign, type, info,57link),58file(file), content_(data.data()), size(data.size()) {59// In order to reduce memory allocation, we assume that mergeable60// sections are smaller than 4 GiB, which is not an unreasonable61// assumption as of 2017.62if (sectionKind == SectionBase::Merge && content().size() > UINT32_MAX)63error(toString(this) + ": section too large");6465// The ELF spec states that a value of 0 means the section has66// no alignment constraints.67uint32_t v = std::max<uint32_t>(addralign, 1);68if (!isPowerOf2_64(v))69fatal(toString(this) + ": sh_addralign is not a power of 2");70this->addralign = v;7172// If SHF_COMPRESSED is set, parse the header. The legacy .zdebug format is no73// longer supported.74if (flags & SHF_COMPRESSED)75invokeELFT(parseCompressedHeader,);76}7778// SHF_INFO_LINK and SHF_GROUP are normally resolved and not copied to the79// output section. However, for relocatable linking without80// --force-group-allocation, the SHF_GROUP flag and section groups are retained.81static uint64_t getFlags(uint64_t flags) {82flags &= ~(uint64_t)SHF_INFO_LINK;83if (config->resolveGroups)84flags &= ~(uint64_t)SHF_GROUP;85return flags;86}8788template <class ELFT>89InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,90const typename ELFT::Shdr &hdr,91StringRef name, Kind sectionKind)92: InputSectionBase(&file, getFlags(hdr.sh_flags), hdr.sh_type,93hdr.sh_entsize, hdr.sh_link, hdr.sh_info,94hdr.sh_addralign, getSectionContents(file, hdr), name,95sectionKind) {96// We reject object files having insanely large alignments even though97// they are allowed by the spec. I think 4GB is a reasonable limitation.98// We might want to relax this in the future.99if (hdr.sh_addralign > UINT32_MAX)100fatal(toString(&file) + ": section sh_addralign is too large");101}102103size_t InputSectionBase::getSize() const {104if (auto *s = dyn_cast<SyntheticSection>(this))105return s->getSize();106return size - bytesDropped;107}108109template <class ELFT>110static void decompressAux(const InputSectionBase &sec, uint8_t *out,111size_t size) {112auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(sec.content_);113auto compressed = ArrayRef<uint8_t>(sec.content_, sec.compressedSize)114.slice(sizeof(typename ELFT::Chdr));115if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB116? compression::zlib::decompress(compressed, out, size)117: compression::zstd::decompress(compressed, out, size))118fatal(toString(&sec) +119": decompress failed: " + llvm::toString(std::move(e)));120}121122void InputSectionBase::decompress() const {123uint8_t *uncompressedBuf;124{125static std::mutex mu;126std::lock_guard<std::mutex> lock(mu);127uncompressedBuf = bAlloc().Allocate<uint8_t>(size);128}129130invokeELFT(decompressAux, *this, uncompressedBuf, size);131content_ = uncompressedBuf;132compressed = false;133}134135template <class ELFT>136RelsOrRelas<ELFT> InputSectionBase::relsOrRelas(bool supportsCrel) const {137if (relSecIdx == 0)138return {};139RelsOrRelas<ELFT> ret;140auto *f = cast<ObjFile<ELFT>>(file);141typename ELFT::Shdr shdr = f->template getELFShdrs<ELFT>()[relSecIdx];142if (shdr.sh_type == SHT_CREL) {143// Return an iterator if supported by caller.144if (supportsCrel) {145ret.crels = Relocs<typename ELFT::Crel>(146(const uint8_t *)f->mb.getBufferStart() + shdr.sh_offset);147return ret;148}149InputSectionBase *const &relSec = f->getSections()[relSecIdx];150// Otherwise, allocate a buffer to hold the decoded RELA relocations. When151// called for the first time, relSec is null (without --emit-relocs) or an152// InputSection with false decodedCrel.153if (!relSec || !cast<InputSection>(relSec)->decodedCrel) {154auto *sec = makeThreadLocal<InputSection>(*f, shdr, name);155f->cacheDecodedCrel(relSecIdx, sec);156sec->type = SHT_RELA;157sec->decodedCrel = true;158159RelocsCrel<ELFT::Is64Bits> entries(sec->content_);160sec->size = entries.size() * sizeof(typename ELFT::Rela);161auto *relas = makeThreadLocalN<typename ELFT::Rela>(entries.size());162sec->content_ = reinterpret_cast<uint8_t *>(relas);163for (auto [i, r] : llvm::enumerate(entries)) {164relas[i].r_offset = r.r_offset;165relas[i].setSymbolAndType(r.r_symidx, r.r_type, false);166relas[i].r_addend = r.r_addend;167}168}169ret.relas = {ArrayRef(170reinterpret_cast<const typename ELFT::Rela *>(relSec->content_),171relSec->size / sizeof(typename ELFT::Rela))};172return ret;173}174175const void *content = f->mb.getBufferStart() + shdr.sh_offset;176size_t size = shdr.sh_size;177if (shdr.sh_type == SHT_REL) {178ret.rels = {ArrayRef(reinterpret_cast<const typename ELFT::Rel *>(content),179size / sizeof(typename ELFT::Rel))};180} else {181assert(shdr.sh_type == SHT_RELA);182ret.relas = {183ArrayRef(reinterpret_cast<const typename ELFT::Rela *>(content),184size / sizeof(typename ELFT::Rela))};185}186return ret;187}188189uint64_t SectionBase::getOffset(uint64_t offset) const {190switch (kind()) {191case Output: {192auto *os = cast<OutputSection>(this);193// For output sections we treat offset -1 as the end of the section.194return offset == uint64_t(-1) ? os->size : offset;195}196case Regular:197case Synthetic:198case Spill:199return cast<InputSection>(this)->outSecOff + offset;200case EHFrame: {201// Two code paths may reach here. First, clang_rt.crtbegin.o and GCC202// crtbeginT.o may reference the start of an empty .eh_frame to identify the203// start of the output .eh_frame. Just return offset.204//205// Second, InputSection::copyRelocations on .eh_frame. Some pieces may be206// discarded due to GC/ICF. We should compute the output section offset.207const EhInputSection *es = cast<EhInputSection>(this);208if (!es->content().empty())209if (InputSection *isec = es->getParent())210return isec->outSecOff + es->getParentOffset(offset);211return offset;212}213case Merge:214const MergeInputSection *ms = cast<MergeInputSection>(this);215if (InputSection *isec = ms->getParent())216return isec->outSecOff + ms->getParentOffset(offset);217return ms->getParentOffset(offset);218}219llvm_unreachable("invalid section kind");220}221222uint64_t SectionBase::getVA(uint64_t offset) const {223const OutputSection *out = getOutputSection();224return (out ? out->addr : 0) + getOffset(offset);225}226227OutputSection *SectionBase::getOutputSection() {228InputSection *sec;229if (auto *isec = dyn_cast<InputSection>(this))230sec = isec;231else if (auto *ms = dyn_cast<MergeInputSection>(this))232sec = ms->getParent();233else if (auto *eh = dyn_cast<EhInputSection>(this))234sec = eh->getParent();235else236return cast<OutputSection>(this);237return sec ? sec->getParent() : nullptr;238}239240// When a section is compressed, `rawData` consists with a header followed241// by zlib-compressed data. This function parses a header to initialize242// `uncompressedSize` member and remove the header from `rawData`.243template <typename ELFT> void InputSectionBase::parseCompressedHeader() {244flags &= ~(uint64_t)SHF_COMPRESSED;245246// New-style header247if (content().size() < sizeof(typename ELFT::Chdr)) {248error(toString(this) + ": corrupted compressed section");249return;250}251252auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content().data());253if (hdr->ch_type == ELFCOMPRESS_ZLIB) {254if (!compression::zlib::isAvailable())255error(toString(this) + " is compressed with ELFCOMPRESS_ZLIB, but lld is "256"not built with zlib support");257} else if (hdr->ch_type == ELFCOMPRESS_ZSTD) {258if (!compression::zstd::isAvailable())259error(toString(this) + " is compressed with ELFCOMPRESS_ZSTD, but lld is "260"not built with zstd support");261} else {262error(toString(this) + ": unsupported compression type (" +263Twine(hdr->ch_type) + ")");264return;265}266267compressed = true;268compressedSize = size;269size = hdr->ch_size;270addralign = std::max<uint32_t>(hdr->ch_addralign, 1);271}272273InputSection *InputSectionBase::getLinkOrderDep() const {274assert(flags & SHF_LINK_ORDER);275if (!link)276return nullptr;277return cast<InputSection>(file->getSections()[link]);278}279280// Find a symbol that encloses a given location.281Defined *InputSectionBase::getEnclosingSymbol(uint64_t offset,282uint8_t type) const {283if (file->isInternal())284return nullptr;285for (Symbol *b : file->getSymbols())286if (Defined *d = dyn_cast<Defined>(b))287if (d->section == this && d->value <= offset &&288offset < d->value + d->size && (type == 0 || type == d->type))289return d;290return nullptr;291}292293// Returns an object file location string. Used to construct an error message.294std::string InputSectionBase::getLocation(uint64_t offset) const {295std::string secAndOffset =296(name + "+0x" + Twine::utohexstr(offset) + ")").str();297298// We don't have file for synthetic sections.299if (file == nullptr)300return (config->outputFile + ":(" + secAndOffset).str();301302std::string filename = toString(file);303if (Defined *d = getEnclosingFunction(offset))304return filename + ":(function " + toString(*d) + ": " + secAndOffset;305306return filename + ":(" + secAndOffset;307}308309// This function is intended to be used for constructing an error message.310// The returned message looks like this:311//312// foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)313//314// Returns an empty string if there's no way to get line info.315std::string InputSectionBase::getSrcMsg(const Symbol &sym,316uint64_t offset) const {317return file->getSrcMsg(sym, *this, offset);318}319320// Returns a filename string along with an optional section name. This321// function is intended to be used for constructing an error322// message. The returned message looks like this:323//324// path/to/foo.o:(function bar)325//326// or327//328// path/to/foo.o:(function bar) in archive path/to/bar.a329std::string InputSectionBase::getObjMsg(uint64_t off) const {330std::string filename = std::string(file->getName());331332std::string archive;333if (!file->archiveName.empty())334archive = (" in archive " + file->archiveName).str();335336// Find a symbol that encloses a given location. getObjMsg may be called337// before ObjFile::initSectionsAndLocalSyms where local symbols are338// initialized.339if (Defined *d = getEnclosingSymbol(off))340return filename + ":(" + toString(*d) + ")" + archive;341342// If there's no symbol, print out the offset in the section.343return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)344.str();345}346347PotentialSpillSection::PotentialSpillSection(const InputSectionBase &source,348InputSectionDescription &isd)349: InputSection(source.file, source.flags, source.type, source.addralign, {},350source.name, SectionBase::Spill),351isd(&isd) {}352353InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");354355InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,356uint32_t addralign, ArrayRef<uint8_t> data,357StringRef name, Kind k)358: InputSectionBase(f, flags, type,359/*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, addralign, data,360name, k) {361assert(f || this == &InputSection::discarded);362}363364template <class ELFT>365InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,366StringRef name)367: InputSectionBase(f, header, name, InputSectionBase::Regular) {}368369// Copy SHT_GROUP section contents. Used only for the -r option.370template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {371// ELFT::Word is the 32-bit integral type in the target endianness.372using u32 = typename ELFT::Word;373ArrayRef<u32> from = getDataAs<u32>();374auto *to = reinterpret_cast<u32 *>(buf);375376// The first entry is not a section number but a flag.377*to++ = from[0];378379// Adjust section numbers because section numbers in an input object files are380// different in the output. We also need to handle combined or discarded381// members.382ArrayRef<InputSectionBase *> sections = file->getSections();383DenseSet<uint32_t> seen;384for (uint32_t idx : from.slice(1)) {385OutputSection *osec = sections[idx]->getOutputSection();386if (osec && seen.insert(osec->sectionIndex).second)387*to++ = osec->sectionIndex;388}389}390391InputSectionBase *InputSection::getRelocatedSection() const {392if (file->isInternal() || !isStaticRelSecType(type))393return nullptr;394ArrayRef<InputSectionBase *> sections = file->getSections();395return sections[info];396}397398template <class ELFT, class RelTy>399void InputSection::copyRelocations(uint8_t *buf) {400if (config->relax && !config->relocatable &&401(config->emachine == EM_RISCV || config->emachine == EM_LOONGARCH)) {402// On LoongArch and RISC-V, relaxation might change relocations: copy403// from internal ones that are updated by relaxation.404InputSectionBase *sec = getRelocatedSection();405copyRelocations<ELFT, RelTy>(buf, llvm::make_range(sec->relocations.begin(),406sec->relocations.end()));407} else {408// Convert the raw relocations in the input section into Relocation objects409// suitable to be used by copyRelocations below.410struct MapRel {411const ObjFile<ELFT> &file;412Relocation operator()(const RelTy &rel) const {413// RelExpr is not used so set to a dummy value.414return Relocation{R_NONE, rel.getType(config->isMips64EL), rel.r_offset,415getAddend<ELFT>(rel), &file.getRelocTargetSym(rel)};416}417};418419using RawRels = ArrayRef<RelTy>;420using MapRelIter =421llvm::mapped_iterator<typename RawRels::iterator, MapRel>;422auto mapRel = MapRel{*getFile<ELFT>()};423RawRels rawRels = getDataAs<RelTy>();424auto rels = llvm::make_range(MapRelIter(rawRels.begin(), mapRel),425MapRelIter(rawRels.end(), mapRel));426copyRelocations<ELFT, RelTy>(buf, rels);427}428}429430// This is used for -r and --emit-relocs. We can't use memcpy to copy431// relocations because we need to update symbol table offset and section index432// for each relocation. So we copy relocations one by one.433template <class ELFT, class RelTy, class RelIt>434void InputSection::copyRelocations(uint8_t *buf,435llvm::iterator_range<RelIt> rels) {436const TargetInfo &target = *elf::target;437InputSectionBase *sec = getRelocatedSection();438(void)sec->contentMaybeDecompress(); // uncompress if needed439440for (const Relocation &rel : rels) {441RelType type = rel.type;442const ObjFile<ELFT> *file = getFile<ELFT>();443Symbol &sym = *rel.sym;444445auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);446buf += sizeof(RelTy);447448if (RelTy::HasAddend)449p->r_addend = rel.addend;450451// Output section VA is zero for -r, so r_offset is an offset within the452// section, but for --emit-relocs it is a virtual address.453p->r_offset = sec->getVA(rel.offset);454p->setSymbolAndType(in.symTab->getSymbolIndex(sym), type,455config->isMips64EL);456457if (sym.type == STT_SECTION) {458// We combine multiple section symbols into only one per459// section. This means we have to update the addend. That is460// trivial for Elf_Rela, but for Elf_Rel we have to write to the461// section data. We do that by adding to the Relocation vector.462463// .eh_frame is horribly special and can reference discarded sections. To464// avoid having to parse and recreate .eh_frame, we just replace any465// relocation in it pointing to discarded sections with R_*_NONE, which466// hopefully creates a frame that is ignored at runtime. Also, don't warn467// on .gcc_except_table and debug sections.468//469// See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc470auto *d = dyn_cast<Defined>(&sym);471if (!d) {472if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&473sec->name != ".gcc_except_table" && sec->name != ".got2" &&474sec->name != ".toc") {475uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;476Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx];477warn("relocation refers to a discarded section: " +478CHECK(file->getObj().getSectionName(sec), file) +479"\n>>> referenced by " + getObjMsg(p->r_offset));480}481p->setSymbolAndType(0, 0, false);482continue;483}484SectionBase *section = d->section;485assert(section->isLive());486487int64_t addend = rel.addend;488const uint8_t *bufLoc = sec->content().begin() + rel.offset;489if (!RelTy::HasAddend)490addend = target.getImplicitAddend(bufLoc, type);491492if (config->emachine == EM_MIPS &&493target.getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {494// Some MIPS relocations depend on "gp" value. By default,495// this value has 0x7ff0 offset from a .got section. But496// relocatable files produced by a compiler or a linker497// might redefine this default value and we must use it498// for a calculation of the relocation result. When we499// generate EXE or DSO it's trivial. Generating a relocatable500// output is more difficult case because the linker does501// not calculate relocations in this mode and loses502// individual "gp" values used by each input object file.503// As a workaround we add the "gp" value to the relocation504// addend and save it back to the file.505addend += sec->getFile<ELFT>()->mipsGp0;506}507508if (RelTy::HasAddend)509p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr;510// For SHF_ALLOC sections relocated by REL, append a relocation to511// sec->relocations so that relocateAlloc transitively called by512// writeSections will update the implicit addend. Non-SHF_ALLOC sections513// utilize relocateNonAlloc to process raw relocations and do not need514// this sec->relocations change.515else if (config->relocatable && (sec->flags & SHF_ALLOC) &&516type != target.noneRel)517sec->addReloc({R_ABS, type, rel.offset, addend, &sym});518} else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 &&519p->r_addend >= 0x8000 && sec->file->ppc32Got2) {520// Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24521// indicates that r30 is relative to the input section .got2522// (r_addend>=0x8000), after linking, r30 should be relative to the output523// section .got2 . To compensate for the shift, adjust r_addend by524// ppc32Got->outSecOff.525p->r_addend += sec->file->ppc32Got2->outSecOff;526}527}528}529530// The ARM and AArch64 ABI handle pc-relative relocations to undefined weak531// references specially. The general rule is that the value of the symbol in532// this context is the address of the place P. A further special case is that533// branch relocations to an undefined weak reference resolve to the next534// instruction.535static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,536uint32_t p) {537switch (type) {538// Unresolved branch relocations to weak references resolve to next539// instruction, this will be either 2 or 4 bytes on from P.540case R_ARM_THM_JUMP8:541case R_ARM_THM_JUMP11:542return p + 2 + a;543case R_ARM_CALL:544case R_ARM_JUMP24:545case R_ARM_PC24:546case R_ARM_PLT32:547case R_ARM_PREL31:548case R_ARM_THM_JUMP19:549case R_ARM_THM_JUMP24:550return p + 4 + a;551case R_ARM_THM_CALL:552// We don't want an interworking BLX to ARM553return p + 5 + a;554// Unresolved non branch pc-relative relocations555// R_ARM_TARGET2 which can be resolved relatively is not present as it never556// targets a weak-reference.557case R_ARM_MOVW_PREL_NC:558case R_ARM_MOVT_PREL:559case R_ARM_REL32:560case R_ARM_THM_ALU_PREL_11_0:561case R_ARM_THM_MOVW_PREL_NC:562case R_ARM_THM_MOVT_PREL:563case R_ARM_THM_PC12:564return p + a;565// p + a is unrepresentable as negative immediates can't be encoded.566case R_ARM_THM_PC8:567return p;568}569llvm_unreachable("ARM pc-relative relocation expected\n");570}571572// The comment above getARMUndefinedRelativeWeakVA applies to this function.573static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) {574switch (type) {575// Unresolved branch relocations to weak references resolve to next576// instruction, this is 4 bytes on from P.577case R_AARCH64_CALL26:578case R_AARCH64_CONDBR19:579case R_AARCH64_JUMP26:580case R_AARCH64_TSTBR14:581return p + 4;582// Unresolved non branch pc-relative relocations583case R_AARCH64_PREL16:584case R_AARCH64_PREL32:585case R_AARCH64_PREL64:586case R_AARCH64_ADR_PREL_LO21:587case R_AARCH64_LD_PREL_LO19:588case R_AARCH64_PLT32:589return p;590}591llvm_unreachable("AArch64 pc-relative relocation expected\n");592}593594static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) {595switch (type) {596case R_RISCV_BRANCH:597case R_RISCV_JAL:598case R_RISCV_CALL:599case R_RISCV_CALL_PLT:600case R_RISCV_RVC_BRANCH:601case R_RISCV_RVC_JUMP:602case R_RISCV_PLT32:603return p;604default:605return 0;606}607}608609// ARM SBREL relocations are of the form S + A - B where B is the static base610// The ARM ABI defines base to be "addressing origin of the output segment611// defining the symbol S". We defined the "addressing origin"/static base to be612// the base of the PT_LOAD segment containing the Sym.613// The procedure call standard only defines a Read Write Position Independent614// RWPI variant so in practice we should expect the static base to be the base615// of the RW segment.616static uint64_t getARMStaticBase(const Symbol &sym) {617OutputSection *os = sym.getOutputSection();618if (!os || !os->ptLoad || !os->ptLoad->firstSec)619fatal("SBREL relocation to " + sym.getName() + " without static base");620return os->ptLoad->firstSec->addr;621}622623// For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually624// points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA625// is calculated using PCREL_HI20's symbol.626//627// This function returns the R_RISCV_PCREL_HI20 relocation from628// R_RISCV_PCREL_LO12's symbol and addend.629static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) {630const Defined *d = cast<Defined>(sym);631if (!d->section) {632errorOrWarn("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " +633sym->getName());634return nullptr;635}636InputSection *isec = cast<InputSection>(d->section);637638if (addend != 0)639warn("non-zero addend in R_RISCV_PCREL_LO12 relocation to " +640isec->getObjMsg(d->value) + " is ignored");641642// Relocations are sorted by offset, so we can use std::equal_range to do643// binary search.644Relocation r;645r.offset = d->value;646auto range =647std::equal_range(isec->relocs().begin(), isec->relocs().end(), r,648[](const Relocation &lhs, const Relocation &rhs) {649return lhs.offset < rhs.offset;650});651652for (auto it = range.first; it != range.second; ++it)653if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||654it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)655return &*it;656657errorOrWarn("R_RISCV_PCREL_LO12 relocation points to " +658isec->getObjMsg(d->value) +659" without an associated R_RISCV_PCREL_HI20 relocation");660return nullptr;661}662663// A TLS symbol's virtual address is relative to the TLS segment. Add a664// target-specific adjustment to produce a thread-pointer-relative offset.665static int64_t getTlsTpOffset(const Symbol &s) {666// On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.667if (&s == ElfSym::tlsModuleBase)668return 0;669670// There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2671// while most others use Variant 1. At run time TP will be aligned to p_align.672673// Variant 1. TP will be followed by an optional gap (which is the size of 2674// pointers on ARM/AArch64, 0 on other targets), followed by alignment675// padding, then the static TLS blocks. The alignment padding is added so that676// (TP + gap + padding) is congruent to p_vaddr modulo p_align.677//678// Variant 2. Static TLS blocks, followed by alignment padding are placed679// before TP. The alignment padding is added so that (TP - padding -680// p_memsz) is congruent to p_vaddr modulo p_align.681PhdrEntry *tls = Out::tlsPhdr;682switch (config->emachine) {683// Variant 1.684case EM_ARM:685case EM_AARCH64:686return s.getVA(0) + config->wordsize * 2 +687((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));688case EM_MIPS:689case EM_PPC:690case EM_PPC64:691// Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is692// to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library693// data and 0xf000 of the program's TLS segment.694return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;695case EM_LOONGARCH:696case EM_RISCV:697// See the comment in handleTlsRelocation. For TLSDESC=>IE,698// R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} also reach here. While699// `tls` may be null, the return value is ignored.700if (s.type != STT_TLS)701return 0;702return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));703704// Variant 2.705case EM_HEXAGON:706case EM_S390:707case EM_SPARCV9:708case EM_386:709case EM_X86_64:710return s.getVA(0) - tls->p_memsz -711((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));712default:713llvm_unreachable("unhandled Config->EMachine");714}715}716717uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,718int64_t a, uint64_t p,719const Symbol &sym, RelExpr expr) {720switch (expr) {721case R_ABS:722case R_DTPREL:723case R_RELAX_TLS_LD_TO_LE_ABS:724case R_RELAX_GOT_PC_NOPIC:725case R_AARCH64_AUTH:726case R_RISCV_ADD:727case R_RISCV_LEB128:728return sym.getVA(a);729case R_ADDEND:730return a;731case R_RELAX_HINT:732return 0;733case R_ARM_SBREL:734return sym.getVA(a) - getARMStaticBase(sym);735case R_GOT:736case R_RELAX_TLS_GD_TO_IE_ABS:737return sym.getGotVA() + a;738case R_LOONGARCH_GOT:739// The LoongArch TLS GD relocs reuse the R_LARCH_GOT_PC_LO12 reloc type740// for their page offsets. The arithmetics are different in the TLS case741// so we have to duplicate some logic here.742if (sym.hasFlag(NEEDS_TLSGD) && type != R_LARCH_TLS_IE_PC_LO12)743// Like R_LOONGARCH_TLSGD_PAGE_PC but taking the absolute value.744return in.got->getGlobalDynAddr(sym) + a;745return getRelocTargetVA(file, type, a, p, sym, R_GOT);746case R_GOTONLY_PC:747return in.got->getVA() + a - p;748case R_GOTPLTONLY_PC:749return in.gotPlt->getVA() + a - p;750case R_GOTREL:751case R_PPC64_RELAX_TOC:752return sym.getVA(a) - in.got->getVA();753case R_GOTPLTREL:754return sym.getVA(a) - in.gotPlt->getVA();755case R_GOTPLT:756case R_RELAX_TLS_GD_TO_IE_GOTPLT:757return sym.getGotVA() + a - in.gotPlt->getVA();758case R_TLSLD_GOT_OFF:759case R_GOT_OFF:760case R_RELAX_TLS_GD_TO_IE_GOT_OFF:761return sym.getGotOffset() + a;762case R_AARCH64_GOT_PAGE_PC:763case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:764return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);765case R_AARCH64_GOT_PAGE:766return sym.getGotVA() + a - getAArch64Page(in.got->getVA());767case R_GOT_PC:768case R_RELAX_TLS_GD_TO_IE:769return sym.getGotVA() + a - p;770case R_GOTPLT_GOTREL:771return sym.getGotPltVA() + a - in.got->getVA();772case R_GOTPLT_PC:773return sym.getGotPltVA() + a - p;774case R_LOONGARCH_GOT_PAGE_PC:775if (sym.hasFlag(NEEDS_TLSGD))776return getLoongArchPageDelta(in.got->getGlobalDynAddr(sym) + a, p, type);777return getLoongArchPageDelta(sym.getGotVA() + a, p, type);778case R_MIPS_GOTREL:779return sym.getVA(a) - in.mipsGot->getGp(file);780case R_MIPS_GOT_GP:781return in.mipsGot->getGp(file) + a;782case R_MIPS_GOT_GP_PC: {783// R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target784// is _gp_disp symbol. In that case we should use the following785// formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at786// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf787// microMIPS variants of these relocations use slightly different788// expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()789// to correctly handle less-significant bit of the microMIPS symbol.790uint64_t v = in.mipsGot->getGp(file) + a - p;791if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)792v += 4;793if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)794v -= 1;795return v;796}797case R_MIPS_GOT_LOCAL_PAGE:798// If relocation against MIPS local symbol requires GOT entry, this entry799// should be initialized by 'page address'. This address is high 16-bits800// of sum the symbol's value and the addend.801return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -802in.mipsGot->getGp(file);803case R_MIPS_GOT_OFF:804case R_MIPS_GOT_OFF32:805// In case of MIPS if a GOT relocation has non-zero addend this addend806// should be applied to the GOT entry content not to the GOT entry offset.807// That is why we use separate expression type.808return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -809in.mipsGot->getGp(file);810case R_MIPS_TLSGD:811return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -812in.mipsGot->getGp(file);813case R_MIPS_TLSLD:814return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -815in.mipsGot->getGp(file);816case R_AARCH64_PAGE_PC: {817uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);818return getAArch64Page(val) - getAArch64Page(p);819}820case R_RISCV_PC_INDIRECT: {821if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))822return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),823*hiRel->sym, hiRel->expr);824return 0;825}826case R_LOONGARCH_PAGE_PC:827return getLoongArchPageDelta(sym.getVA(a), p, type);828case R_PC:829case R_ARM_PCA: {830uint64_t dest;831if (expr == R_ARM_PCA)832// Some PC relative ARM (Thumb) relocations align down the place.833p = p & 0xfffffffc;834if (sym.isUndefined()) {835// On ARM and AArch64 a branch to an undefined weak resolves to the next836// instruction, otherwise the place. On RISC-V, resolve an undefined weak837// to the same instruction to cause an infinite loop (making the user838// aware of the issue) while ensuring no overflow.839// Note: if the symbol is hidden, its binding has been converted to local,840// so we just check isUndefined() here.841if (config->emachine == EM_ARM)842dest = getARMUndefinedRelativeWeakVA(type, a, p);843else if (config->emachine == EM_AARCH64)844dest = getAArch64UndefinedRelativeWeakVA(type, p) + a;845else if (config->emachine == EM_PPC)846dest = p;847else if (config->emachine == EM_RISCV)848dest = getRISCVUndefinedRelativeWeakVA(type, p) + a;849else850dest = sym.getVA(a);851} else {852dest = sym.getVA(a);853}854return dest - p;855}856case R_PLT:857return sym.getPltVA() + a;858case R_PLT_PC:859case R_PPC64_CALL_PLT:860return sym.getPltVA() + a - p;861case R_LOONGARCH_PLT_PAGE_PC:862return getLoongArchPageDelta(sym.getPltVA() + a, p, type);863case R_PLT_GOTPLT:864return sym.getPltVA() + a - in.gotPlt->getVA();865case R_PLT_GOTREL:866return sym.getPltVA() + a - in.got->getVA();867case R_PPC32_PLTREL:868// R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30869// stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for870// target VA computation.871return sym.getPltVA() - p;872case R_PPC64_CALL: {873uint64_t symVA = sym.getVA(a);874// If we have an undefined weak symbol, we might get here with a symbol875// address of zero. That could overflow, but the code must be unreachable,876// so don't bother doing anything at all.877if (!symVA)878return 0;879880// PPC64 V2 ABI describes two entry points to a function. The global entry881// point is used for calls where the caller and callee (may) have different882// TOC base pointers and r2 needs to be modified to hold the TOC base for883// the callee. For local calls the caller and callee share the same884// TOC base and so the TOC pointer initialization code should be skipped by885// branching to the local entry point.886return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);887}888case R_PPC64_TOCBASE:889return getPPC64TocBase() + a;890case R_RELAX_GOT_PC:891case R_PPC64_RELAX_GOT_PC:892return sym.getVA(a) - p;893case R_RELAX_TLS_GD_TO_LE:894case R_RELAX_TLS_IE_TO_LE:895case R_RELAX_TLS_LD_TO_LE:896case R_TPREL:897// It is not very clear what to return if the symbol is undefined. With898// --noinhibit-exec, even a non-weak undefined reference may reach here.899// Just return A, which matches R_ABS, and the behavior of some dynamic900// loaders.901if (sym.isUndefined())902return a;903return getTlsTpOffset(sym) + a;904case R_RELAX_TLS_GD_TO_LE_NEG:905case R_TPREL_NEG:906if (sym.isUndefined())907return a;908return -getTlsTpOffset(sym) + a;909case R_SIZE:910return sym.getSize() + a;911case R_TLSDESC:912return in.got->getTlsDescAddr(sym) + a;913case R_TLSDESC_PC:914return in.got->getTlsDescAddr(sym) + a - p;915case R_TLSDESC_GOTPLT:916return in.got->getTlsDescAddr(sym) + a - in.gotPlt->getVA();917case R_AARCH64_TLSDESC_PAGE:918return getAArch64Page(in.got->getTlsDescAddr(sym) + a) - getAArch64Page(p);919case R_LOONGARCH_TLSDESC_PAGE_PC:920return getLoongArchPageDelta(in.got->getTlsDescAddr(sym) + a, p, type);921case R_TLSGD_GOT:922return in.got->getGlobalDynOffset(sym) + a;923case R_TLSGD_GOTPLT:924return in.got->getGlobalDynAddr(sym) + a - in.gotPlt->getVA();925case R_TLSGD_PC:926return in.got->getGlobalDynAddr(sym) + a - p;927case R_LOONGARCH_TLSGD_PAGE_PC:928return getLoongArchPageDelta(in.got->getGlobalDynAddr(sym) + a, p, type);929case R_TLSLD_GOTPLT:930return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();931case R_TLSLD_GOT:932return in.got->getTlsIndexOff() + a;933case R_TLSLD_PC:934return in.got->getTlsIndexVA() + a - p;935default:936llvm_unreachable("invalid expression");937}938}939940// This function applies relocations to sections without SHF_ALLOC bit.941// Such sections are never mapped to memory at runtime. Debug sections are942// an example. Relocations in non-alloc sections are much easier to943// handle than in allocated sections because it will never need complex944// treatment such as GOT or PLT (because at runtime no one refers them).945// So, we handle relocations for non-alloc sections directly in this946// function as a performance optimization.947template <class ELFT, class RelTy>948void InputSection::relocateNonAlloc(uint8_t *buf, Relocs<RelTy> rels) {949const unsigned bits = sizeof(typename ELFT::uint) * 8;950const TargetInfo &target = *elf::target;951const auto emachine = config->emachine;952const bool isDebug = isDebugSection(*this);953const bool isDebugLine = isDebug && name == ".debug_line";954std::optional<uint64_t> tombstone;955if (isDebug) {956if (name == ".debug_loc" || name == ".debug_ranges")957tombstone = 1;958else if (name == ".debug_names")959tombstone = UINT64_MAX; // tombstone value960else961tombstone = 0;962}963for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))964if (patAndValue.first.match(this->name)) {965tombstone = patAndValue.second;966break;967}968969const InputFile *f = this->file;970for (auto it = rels.begin(), end = rels.end(); it != end; ++it) {971const RelTy &rel = *it;972const RelType type = rel.getType(config->isMips64EL);973const uint64_t offset = rel.r_offset;974uint8_t *bufLoc = buf + offset;975int64_t addend = getAddend<ELFT>(rel);976if (!RelTy::HasAddend)977addend += target.getImplicitAddend(bufLoc, type);978979Symbol &sym = f->getRelocTargetSym(rel);980RelExpr expr = target.getRelExpr(type, sym, bufLoc);981if (expr == R_NONE)982continue;983auto *ds = dyn_cast<Defined>(&sym);984985if (emachine == EM_RISCV && type == R_RISCV_SET_ULEB128) {986if (++it != end &&987it->getType(/*isMips64EL=*/false) == R_RISCV_SUB_ULEB128 &&988it->r_offset == offset) {989uint64_t val;990if (!ds && tombstone) {991val = *tombstone;992} else {993val = sym.getVA(addend) -994(f->getRelocTargetSym(*it).getVA(0) + getAddend<ELFT>(*it));995}996if (overwriteULEB128(bufLoc, val) >= 0x80)997errorOrWarn(getLocation(offset) + ": ULEB128 value " + Twine(val) +998" exceeds available space; references '" +999lld::toString(sym) + "'");1000continue;1001}1002errorOrWarn(getLocation(offset) +1003": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");1004return;1005}10061007if (tombstone && (expr == R_ABS || expr == R_DTPREL)) {1008// Resolve relocations in .debug_* referencing (discarded symbols or ICF1009// folded section symbols) to a tombstone value. Resolving to addend is1010// unsatisfactory because the result address range may collide with a1011// valid range of low address, or leave multiple CUs claiming ownership of1012// the same range of code, which may confuse consumers.1013//1014// To address the problems, we use -1 as a tombstone value for most1015// .debug_* sections. We have to ignore the addend because we don't want1016// to resolve an address attribute (which may have a non-zero addend) to1017// -1+addend (wrap around to a low address).1018//1019// R_DTPREL type relocations represent an offset into the dynamic thread1020// vector. The computed value is st_value plus a non-negative offset.1021// Negative values are invalid, so -1 can be used as the tombstone value.1022//1023// If the referenced symbol is relative to a discarded section (due to1024// --gc-sections, COMDAT, etc), it has been converted to a Undefined.1025// `ds->folded` catches the ICF folded case. However, resolving a1026// relocation in .debug_line to -1 would stop debugger users from setting1027// breakpoints on the folded-in function, so exclude .debug_line.1028//1029// For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value1030// (base address selection entry), use 1 (which is used by GNU ld for1031// .debug_ranges).1032//1033// TODO To reduce disruption, we use 0 instead of -1 as the tombstone1034// value. Enable -1 in a future release.1035if (!ds || (ds->folded && !isDebugLine)) {1036// If -z dead-reloc-in-nonalloc= is specified, respect it.1037uint64_t value = SignExtend64<bits>(*tombstone);1038// For a 32-bit local TU reference in .debug_names, X86_64::relocate1039// requires that the unsigned value for R_X86_64_32 is truncated to1040// 32-bit. Other 64-bit targets's don't discern signed/unsigned 32-bit1041// absolute relocations and do not need this change.1042if (emachine == EM_X86_64 && type == R_X86_64_32)1043value = static_cast<uint32_t>(value);1044target.relocateNoSym(bufLoc, type, value);1045continue;1046}1047}10481049// For a relocatable link, content relocated by relocation types with an1050// explicit addend, such as RELA, remain unchanged and we can stop here.1051// While content relocated by relocation types with an implicit addend, such1052// as REL, needs the implicit addend updated.1053if (config->relocatable && (RelTy::HasAddend || sym.type != STT_SECTION))1054continue;10551056// R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC1057// sections.1058if (LLVM_LIKELY(expr == R_ABS) || expr == R_DTPREL || expr == R_GOTPLTREL ||1059expr == R_RISCV_ADD) {1060target.relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));1061continue;1062}10631064if (expr == R_SIZE) {1065target.relocateNoSym(bufLoc, type,1066SignExtend64<bits>(sym.getSize() + addend));1067continue;1068}10691070std::string msg = getLocation(offset) + ": has non-ABS relocation " +1071toString(type) + " against symbol '" + toString(sym) +1072"'";1073if (expr != R_PC && !(emachine == EM_386 && type == R_386_GOTPC)) {1074errorOrWarn(msg);1075return;1076}10771078// If the control reaches here, we found a PC-relative relocation in a1079// non-ALLOC section. Since non-ALLOC section is not loaded into memory1080// at runtime, the notion of PC-relative doesn't make sense here. So,1081// this is a usage error. However, GNU linkers historically accept such1082// relocations without any errors and relocate them as if they were at1083// address 0. For bug-compatibility, we accept them with warnings. We1084// know Steel Bank Common Lisp as of 2018 have this bug.1085//1086// GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations1087// against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed in1088// 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we need to1089// keep this bug-compatible code for a while.1090warn(msg);1091target.relocateNoSym(1092bufLoc, type,1093SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));1094}1095}10961097template <class ELFT>1098void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {1099if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))1100adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);11011102if (flags & SHF_ALLOC) {1103target->relocateAlloc(*this, buf);1104return;1105}11061107auto *sec = cast<InputSection>(this);1108// For a relocatable link, also call relocateNonAlloc() to rewrite applicable1109// locations with tombstone values.1110invokeOnRelocs(*sec, sec->relocateNonAlloc<ELFT>, buf);1111}11121113// For each function-defining prologue, find any calls to __morestack,1114// and replace them with calls to __morestack_non_split.1115static void switchMorestackCallsToMorestackNonSplit(1116DenseSet<Defined *> &prologues,1117SmallVector<Relocation *, 0> &morestackCalls) {11181119// If the target adjusted a function's prologue, all calls to1120// __morestack inside that function should be switched to1121// __morestack_non_split.1122Symbol *moreStackNonSplit = symtab.find("__morestack_non_split");1123if (!moreStackNonSplit) {1124error("mixing split-stack objects requires a definition of "1125"__morestack_non_split");1126return;1127}11281129// Sort both collections to compare addresses efficiently.1130llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {1131return l->offset < r->offset;1132});1133std::vector<Defined *> functions(prologues.begin(), prologues.end());1134llvm::sort(functions, [](const Defined *l, const Defined *r) {1135return l->value < r->value;1136});11371138auto it = morestackCalls.begin();1139for (Defined *f : functions) {1140// Find the first call to __morestack within the function.1141while (it != morestackCalls.end() && (*it)->offset < f->value)1142++it;1143// Adjust all calls inside the function.1144while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {1145(*it)->sym = moreStackNonSplit;1146++it;1147}1148}1149}11501151static bool enclosingPrologueAttempted(uint64_t offset,1152const DenseSet<Defined *> &prologues) {1153for (Defined *f : prologues)1154if (f->value <= offset && offset < f->value + f->size)1155return true;1156return false;1157}11581159// If a function compiled for split stack calls a function not1160// compiled for split stack, then the caller needs its prologue1161// adjusted to ensure that the called function will have enough stack1162// available. Find those functions, and adjust their prologues.1163template <class ELFT>1164void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,1165uint8_t *end) {1166DenseSet<Defined *> prologues;1167SmallVector<Relocation *, 0> morestackCalls;11681169for (Relocation &rel : relocs()) {1170// Ignore calls into the split-stack api.1171if (rel.sym->getName().starts_with("__morestack")) {1172if (rel.sym->getName() == "__morestack")1173morestackCalls.push_back(&rel);1174continue;1175}11761177// A relocation to non-function isn't relevant. Sometimes1178// __morestack is not marked as a function, so this check comes1179// after the name check.1180if (rel.sym->type != STT_FUNC)1181continue;11821183// If the callee's-file was compiled with split stack, nothing to do. In1184// this context, a "Defined" symbol is one "defined by the binary currently1185// being produced". So an "undefined" symbol might be provided by a shared1186// library. It is not possible to tell how such symbols were compiled, so be1187// conservative.1188if (Defined *d = dyn_cast<Defined>(rel.sym))1189if (InputSection *isec = cast_or_null<InputSection>(d->section))1190if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)1191continue;11921193if (enclosingPrologueAttempted(rel.offset, prologues))1194continue;11951196if (Defined *f = getEnclosingFunction(rel.offset)) {1197prologues.insert(f);1198if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,1199f->stOther))1200continue;1201if (!getFile<ELFT>()->someNoSplitStack)1202error(lld::toString(this) + ": " + f->getName() +1203" (with -fsplit-stack) calls " + rel.sym->getName() +1204" (without -fsplit-stack), but couldn't adjust its prologue");1205}1206}12071208if (target->needsMoreStackNonSplit)1209switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);1210}12111212template <class ELFT> void InputSection::writeTo(uint8_t *buf) {1213if (LLVM_UNLIKELY(type == SHT_NOBITS))1214return;1215// If -r or --emit-relocs is given, then an InputSection1216// may be a relocation section.1217if (LLVM_UNLIKELY(type == SHT_RELA)) {1218copyRelocations<ELFT, typename ELFT::Rela>(buf);1219return;1220}1221if (LLVM_UNLIKELY(type == SHT_REL)) {1222copyRelocations<ELFT, typename ELFT::Rel>(buf);1223return;1224}12251226// If -r is given, we may have a SHT_GROUP section.1227if (LLVM_UNLIKELY(type == SHT_GROUP)) {1228copyShtGroup<ELFT>(buf);1229return;1230}12311232// If this is a compressed section, uncompress section contents directly1233// to the buffer.1234if (compressed) {1235auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content_);1236auto compressed = ArrayRef<uint8_t>(content_, compressedSize)1237.slice(sizeof(typename ELFT::Chdr));1238size_t size = this->size;1239if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB1240? compression::zlib::decompress(compressed, buf, size)1241: compression::zstd::decompress(compressed, buf, size))1242fatal(toString(this) +1243": decompress failed: " + llvm::toString(std::move(e)));1244uint8_t *bufEnd = buf + size;1245relocate<ELFT>(buf, bufEnd);1246return;1247}12481249// Copy section contents from source object file to output file1250// and then apply relocations.1251memcpy(buf, content().data(), content().size());1252relocate<ELFT>(buf, buf + content().size());1253}12541255void InputSection::replace(InputSection *other) {1256addralign = std::max(addralign, other->addralign);12571258// When a section is replaced with another section that was allocated to1259// another partition, the replacement section (and its associated sections)1260// need to be placed in the main partition so that both partitions will be1261// able to access it.1262if (partition != other->partition) {1263partition = 1;1264for (InputSection *isec : dependentSections)1265isec->partition = 1;1266}12671268other->repl = repl;1269other->markDead();1270}12711272template <class ELFT>1273EhInputSection::EhInputSection(ObjFile<ELFT> &f,1274const typename ELFT::Shdr &header,1275StringRef name)1276: InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}12771278SyntheticSection *EhInputSection::getParent() const {1279return cast_or_null<SyntheticSection>(parent);1280}12811282// .eh_frame is a sequence of CIE or FDE records.1283// This function splits an input section into records and returns them.1284template <class ELFT> void EhInputSection::split() {1285const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>(/*supportsCrel=*/false);1286// getReloc expects the relocations to be sorted by r_offset. See the comment1287// in scanRelocs.1288if (rels.areRelocsRel()) {1289SmallVector<typename ELFT::Rel, 0> storage;1290split<ELFT>(sortRels(rels.rels, storage));1291} else {1292SmallVector<typename ELFT::Rela, 0> storage;1293split<ELFT>(sortRels(rels.relas, storage));1294}1295}12961297template <class ELFT, class RelTy>1298void EhInputSection::split(ArrayRef<RelTy> rels) {1299ArrayRef<uint8_t> d = content();1300const char *msg = nullptr;1301unsigned relI = 0;1302while (!d.empty()) {1303if (d.size() < 4) {1304msg = "CIE/FDE too small";1305break;1306}1307uint64_t size = endian::read32<ELFT::Endianness>(d.data());1308if (size == 0) // ZERO terminator1309break;1310uint32_t id = endian::read32<ELFT::Endianness>(d.data() + 4);1311size += 4;1312if (LLVM_UNLIKELY(size > d.size())) {1313// If it is 0xFFFFFFFF, the next 8 bytes contain the size instead,1314// but we do not support that format yet.1315msg = size == UINT32_MAX + uint64_t(4)1316? "CIE/FDE too large"1317: "CIE/FDE ends past the end of the section";1318break;1319}13201321// Find the first relocation that points to [off,off+size). Relocations1322// have been sorted by r_offset.1323const uint64_t off = d.data() - content().data();1324while (relI != rels.size() && rels[relI].r_offset < off)1325++relI;1326unsigned firstRel = -1;1327if (relI != rels.size() && rels[relI].r_offset < off + size)1328firstRel = relI;1329(id == 0 ? cies : fdes).emplace_back(off, this, size, firstRel);1330d = d.slice(size);1331}1332if (msg)1333errorOrWarn("corrupted .eh_frame: " + Twine(msg) + "\n>>> defined in " +1334getObjMsg(d.data() - content().data()));1335}13361337// Return the offset in an output section for a given input offset.1338uint64_t EhInputSection::getParentOffset(uint64_t offset) const {1339auto it = partition_point(1340fdes, [=](EhSectionPiece p) { return p.inputOff <= offset; });1341if (it == fdes.begin() || it[-1].inputOff + it[-1].size <= offset) {1342it = partition_point(1343cies, [=](EhSectionPiece p) { return p.inputOff <= offset; });1344if (it == cies.begin()) // invalid piece1345return offset;1346}1347if (it[-1].outputOff == -1) // invalid piece1348return offset - it[-1].inputOff;1349return it[-1].outputOff + (offset - it[-1].inputOff);1350}13511352static size_t findNull(StringRef s, size_t entSize) {1353for (unsigned i = 0, n = s.size(); i != n; i += entSize) {1354const char *b = s.begin() + i;1355if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))1356return i;1357}1358llvm_unreachable("");1359}13601361// Split SHF_STRINGS section. Such section is a sequence of1362// null-terminated strings.1363void MergeInputSection::splitStrings(StringRef s, size_t entSize) {1364const bool live = !(flags & SHF_ALLOC) || !config->gcSections;1365const char *p = s.data(), *end = s.data() + s.size();1366if (!std::all_of(end - entSize, end, [](char c) { return c == 0; }))1367fatal(toString(this) + ": string is not null terminated");1368if (entSize == 1) {1369// Optimize the common case.1370do {1371size_t size = strlen(p);1372pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);1373p += size + 1;1374} while (p != end);1375} else {1376do {1377size_t size = findNull(StringRef(p, end - p), entSize);1378pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);1379p += size + entSize;1380} while (p != end);1381}1382}13831384// Split non-SHF_STRINGS section. Such section is a sequence of1385// fixed size records.1386void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,1387size_t entSize) {1388size_t size = data.size();1389assert((size % entSize) == 0);1390const bool live = !(flags & SHF_ALLOC) || !config->gcSections;13911392pieces.resize_for_overwrite(size / entSize);1393for (size_t i = 0, j = 0; i != size; i += entSize, j++)1394pieces[j] = {i, (uint32_t)xxh3_64bits(data.slice(i, entSize)), live};1395}13961397template <class ELFT>1398MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,1399const typename ELFT::Shdr &header,1400StringRef name)1401: InputSectionBase(f, header, name, InputSectionBase::Merge) {}14021403MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,1404uint64_t entsize, ArrayRef<uint8_t> data,1405StringRef name)1406: InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0,1407/*Alignment*/ entsize, data, name, SectionBase::Merge) {}14081409// This function is called after we obtain a complete list of input sections1410// that need to be linked. This is responsible to split section contents1411// into small chunks for further processing.1412//1413// Note that this function is called from parallelForEach. This must be1414// thread-safe (i.e. no memory allocation from the pools).1415void MergeInputSection::splitIntoPieces() {1416assert(pieces.empty());14171418if (flags & SHF_STRINGS)1419splitStrings(toStringRef(contentMaybeDecompress()), entsize);1420else1421splitNonStrings(contentMaybeDecompress(), entsize);1422}14231424SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {1425if (content().size() <= offset)1426fatal(toString(this) + ": offset is outside the section");1427return partition_point(1428pieces, [=](SectionPiece p) { return p.inputOff <= offset; })[-1];1429}14301431// Return the offset in an output section for a given input offset.1432uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {1433const SectionPiece &piece = getSectionPiece(offset);1434return piece.outputOff + (offset - piece.inputOff);1435}14361437template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,1438StringRef);1439template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,1440StringRef);1441template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,1442StringRef);1443template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,1444StringRef);14451446template void InputSection::writeTo<ELF32LE>(uint8_t *);1447template void InputSection::writeTo<ELF32BE>(uint8_t *);1448template void InputSection::writeTo<ELF64LE>(uint8_t *);1449template void InputSection::writeTo<ELF64BE>(uint8_t *);14501451template RelsOrRelas<ELF32LE>1452InputSectionBase::relsOrRelas<ELF32LE>(bool) const;1453template RelsOrRelas<ELF32BE>1454InputSectionBase::relsOrRelas<ELF32BE>(bool) const;1455template RelsOrRelas<ELF64LE>1456InputSectionBase::relsOrRelas<ELF64LE>(bool) const;1457template RelsOrRelas<ELF64BE>1458InputSectionBase::relsOrRelas<ELF64BE>(bool) const;14591460template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,1461const ELF32LE::Shdr &, StringRef);1462template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,1463const ELF32BE::Shdr &, StringRef);1464template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,1465const ELF64LE::Shdr &, StringRef);1466template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,1467const ELF64BE::Shdr &, StringRef);14681469template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,1470const ELF32LE::Shdr &, StringRef);1471template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,1472const ELF32BE::Shdr &, StringRef);1473template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,1474const ELF64LE::Shdr &, StringRef);1475template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,1476const ELF64BE::Shdr &, StringRef);14771478template void EhInputSection::split<ELF32LE>();1479template void EhInputSection::split<ELF32BE>();1480template void EhInputSection::split<ELF64LE>();1481template void EhInputSection::split<ELF64BE>();148214831484