Path: blob/main/contrib/llvm-project/lld/COFF/Chunks.cpp
34870 views
//===- Chunks.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 "Chunks.h"9#include "COFFLinkerContext.h"10#include "InputFiles.h"11#include "SymbolTable.h"12#include "Symbols.h"13#include "Writer.h"14#include "llvm/ADT/STLExtras.h"15#include "llvm/ADT/StringExtras.h"16#include "llvm/ADT/Twine.h"17#include "llvm/BinaryFormat/COFF.h"18#include "llvm/Object/COFF.h"19#include "llvm/Support/Debug.h"20#include "llvm/Support/Endian.h"21#include "llvm/Support/raw_ostream.h"22#include <algorithm>23#include <iterator>2425using namespace llvm;26using namespace llvm::object;27using namespace llvm::support::endian;28using namespace llvm::COFF;29using llvm::support::ulittle32_t;3031namespace lld::coff {3233SectionChunk::SectionChunk(ObjFile *f, const coff_section *h, Kind k)34: Chunk(k), file(f), header(h), repl(this) {35// Initialize relocs.36if (file)37setRelocs(file->getCOFFObj()->getRelocations(header));3839// Initialize sectionName.40StringRef sectionName;41if (file) {42if (Expected<StringRef> e = file->getCOFFObj()->getSectionName(header))43sectionName = *e;44}45sectionNameData = sectionName.data();46sectionNameSize = sectionName.size();4748setAlignment(header->getAlignment());4950hasData = !(header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);5152// If linker GC is disabled, every chunk starts out alive. If linker GC is53// enabled, treat non-comdat sections as roots. Generally optimized object54// files will be built with -ffunction-sections or /Gy, so most things worth55// stripping will be in a comdat.56if (file)57live = !file->ctx.config.doGC || !isCOMDAT();58else59live = true;60}6162// SectionChunk is one of the most frequently allocated classes, so it is63// important to keep it as compact as possible. As of this writing, the number64// below is the size of this class on x64 platforms.65static_assert(sizeof(SectionChunk) <= 88, "SectionChunk grew unexpectedly");6667static void add16(uint8_t *p, int16_t v) { write16le(p, read16le(p) + v); }68static void add32(uint8_t *p, int32_t v) { write32le(p, read32le(p) + v); }69static void add64(uint8_t *p, int64_t v) { write64le(p, read64le(p) + v); }70static void or16(uint8_t *p, uint16_t v) { write16le(p, read16le(p) | v); }71static void or32(uint8_t *p, uint32_t v) { write32le(p, read32le(p) | v); }7273// Verify that given sections are appropriate targets for SECREL74// relocations. This check is relaxed because unfortunately debug75// sections have section-relative relocations against absolute symbols.76static bool checkSecRel(const SectionChunk *sec, OutputSection *os) {77if (os)78return true;79if (sec->isCodeView())80return false;81error("SECREL relocation cannot be applied to absolute symbols");82return false;83}8485static void applySecRel(const SectionChunk *sec, uint8_t *off,86OutputSection *os, uint64_t s) {87if (!checkSecRel(sec, os))88return;89uint64_t secRel = s - os->getRVA();90if (secRel > UINT32_MAX) {91error("overflow in SECREL relocation in section: " + sec->getSectionName());92return;93}94add32(off, secRel);95}9697static void applySecIdx(uint8_t *off, OutputSection *os,98unsigned numOutputSections) {99// numOutputSections is the largest valid section index. Make sure that100// it fits in 16 bits.101assert(numOutputSections <= 0xffff && "size of outputSections is too big");102103// Absolute symbol doesn't have section index, but section index relocation104// against absolute symbol should be resolved to one plus the last output105// section index. This is required for compatibility with MSVC.106if (os)107add16(off, os->sectionIndex);108else109add16(off, numOutputSections + 1);110}111112void SectionChunk::applyRelX64(uint8_t *off, uint16_t type, OutputSection *os,113uint64_t s, uint64_t p,114uint64_t imageBase) const {115switch (type) {116case IMAGE_REL_AMD64_ADDR32:117add32(off, s + imageBase);118break;119case IMAGE_REL_AMD64_ADDR64:120add64(off, s + imageBase);121break;122case IMAGE_REL_AMD64_ADDR32NB: add32(off, s); break;123case IMAGE_REL_AMD64_REL32: add32(off, s - p - 4); break;124case IMAGE_REL_AMD64_REL32_1: add32(off, s - p - 5); break;125case IMAGE_REL_AMD64_REL32_2: add32(off, s - p - 6); break;126case IMAGE_REL_AMD64_REL32_3: add32(off, s - p - 7); break;127case IMAGE_REL_AMD64_REL32_4: add32(off, s - p - 8); break;128case IMAGE_REL_AMD64_REL32_5: add32(off, s - p - 9); break;129case IMAGE_REL_AMD64_SECTION:130applySecIdx(off, os, file->ctx.outputSections.size());131break;132case IMAGE_REL_AMD64_SECREL: applySecRel(this, off, os, s); break;133default:134error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +135toString(file));136}137}138139void SectionChunk::applyRelX86(uint8_t *off, uint16_t type, OutputSection *os,140uint64_t s, uint64_t p,141uint64_t imageBase) const {142switch (type) {143case IMAGE_REL_I386_ABSOLUTE: break;144case IMAGE_REL_I386_DIR32:145add32(off, s + imageBase);146break;147case IMAGE_REL_I386_DIR32NB: add32(off, s); break;148case IMAGE_REL_I386_REL32: add32(off, s - p - 4); break;149case IMAGE_REL_I386_SECTION:150applySecIdx(off, os, file->ctx.outputSections.size());151break;152case IMAGE_REL_I386_SECREL: applySecRel(this, off, os, s); break;153default:154error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +155toString(file));156}157}158159static void applyMOV(uint8_t *off, uint16_t v) {160write16le(off, (read16le(off) & 0xfbf0) | ((v & 0x800) >> 1) | ((v >> 12) & 0xf));161write16le(off + 2, (read16le(off + 2) & 0x8f00) | ((v & 0x700) << 4) | (v & 0xff));162}163164static uint16_t readMOV(uint8_t *off, bool movt) {165uint16_t op1 = read16le(off);166if ((op1 & 0xfbf0) != (movt ? 0xf2c0 : 0xf240))167error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +168" instruction in MOV32T relocation");169uint16_t op2 = read16le(off + 2);170if ((op2 & 0x8000) != 0)171error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +172" instruction in MOV32T relocation");173return (op2 & 0x00ff) | ((op2 >> 4) & 0x0700) | ((op1 << 1) & 0x0800) |174((op1 & 0x000f) << 12);175}176177void applyMOV32T(uint8_t *off, uint32_t v) {178uint16_t immW = readMOV(off, false); // read MOVW operand179uint16_t immT = readMOV(off + 4, true); // read MOVT operand180uint32_t imm = immW | (immT << 16);181v += imm; // add the immediate offset182applyMOV(off, v); // set MOVW operand183applyMOV(off + 4, v >> 16); // set MOVT operand184}185186static void applyBranch20T(uint8_t *off, int32_t v) {187if (!isInt<21>(v))188error("relocation out of range");189uint32_t s = v < 0 ? 1 : 0;190uint32_t j1 = (v >> 19) & 1;191uint32_t j2 = (v >> 18) & 1;192or16(off, (s << 10) | ((v >> 12) & 0x3f));193or16(off + 2, (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));194}195196void applyBranch24T(uint8_t *off, int32_t v) {197if (!isInt<25>(v))198error("relocation out of range");199uint32_t s = v < 0 ? 1 : 0;200uint32_t j1 = ((~v >> 23) & 1) ^ s;201uint32_t j2 = ((~v >> 22) & 1) ^ s;202or16(off, (s << 10) | ((v >> 12) & 0x3ff));203// Clear out the J1 and J2 bits which may be set.204write16le(off + 2, (read16le(off + 2) & 0xd000) | (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));205}206207void SectionChunk::applyRelARM(uint8_t *off, uint16_t type, OutputSection *os,208uint64_t s, uint64_t p,209uint64_t imageBase) const {210// Pointer to thumb code must have the LSB set.211uint64_t sx = s;212if (os && (os->header.Characteristics & IMAGE_SCN_MEM_EXECUTE))213sx |= 1;214switch (type) {215case IMAGE_REL_ARM_ADDR32:216add32(off, sx + imageBase);217break;218case IMAGE_REL_ARM_ADDR32NB: add32(off, sx); break;219case IMAGE_REL_ARM_MOV32T:220applyMOV32T(off, sx + imageBase);221break;222case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(off, sx - p - 4); break;223case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(off, sx - p - 4); break;224case IMAGE_REL_ARM_BLX23T: applyBranch24T(off, sx - p - 4); break;225case IMAGE_REL_ARM_SECTION:226applySecIdx(off, os, file->ctx.outputSections.size());227break;228case IMAGE_REL_ARM_SECREL: applySecRel(this, off, os, s); break;229case IMAGE_REL_ARM_REL32: add32(off, sx - p - 4); break;230default:231error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +232toString(file));233}234}235236// Interpret the existing immediate value as a byte offset to the237// target symbol, then update the instruction with the immediate as238// the page offset from the current instruction to the target.239void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift) {240uint32_t orig = read32le(off);241int64_t imm =242SignExtend64<21>(((orig >> 29) & 0x3) | ((orig >> 3) & 0x1FFFFC));243s += imm;244imm = (s >> shift) - (p >> shift);245uint32_t immLo = (imm & 0x3) << 29;246uint32_t immHi = (imm & 0x1FFFFC) << 3;247uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);248write32le(off, (orig & ~mask) | immLo | immHi);249}250251// Update the immediate field in a AARCH64 ldr, str, and add instruction.252// Optionally limit the range of the written immediate by one or more bits253// (rangeLimit).254void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit) {255uint32_t orig = read32le(off);256imm += (orig >> 10) & 0xFFF;257orig &= ~(0xFFF << 10);258write32le(off, orig | ((imm & (0xFFF >> rangeLimit)) << 10));259}260261// Add the 12 bit page offset to the existing immediate.262// Ldr/str instructions store the opcode immediate scaled263// by the load/store size (giving a larger range for larger264// loads/stores). The immediate is always (both before and after265// fixing up the relocation) stored scaled similarly.266// Even if larger loads/stores have a larger range, limit the267// effective offset to 12 bit, since it is intended to be a268// page offset.269static void applyArm64Ldr(uint8_t *off, uint64_t imm) {270uint32_t orig = read32le(off);271uint32_t size = orig >> 30;272// 0x04000000 indicates SIMD/FP registers273// 0x00800000 indicates 128 bit274if ((orig & 0x4800000) == 0x4800000)275size += 4;276if ((imm & ((1 << size) - 1)) != 0)277error("misaligned ldr/str offset");278applyArm64Imm(off, imm >> size, size);279}280281static void applySecRelLow12A(const SectionChunk *sec, uint8_t *off,282OutputSection *os, uint64_t s) {283if (checkSecRel(sec, os))284applyArm64Imm(off, (s - os->getRVA()) & 0xfff, 0);285}286287static void applySecRelHigh12A(const SectionChunk *sec, uint8_t *off,288OutputSection *os, uint64_t s) {289if (!checkSecRel(sec, os))290return;291uint64_t secRel = (s - os->getRVA()) >> 12;292if (0xfff < secRel) {293error("overflow in SECREL_HIGH12A relocation in section: " +294sec->getSectionName());295return;296}297applyArm64Imm(off, secRel & 0xfff, 0);298}299300static void applySecRelLdr(const SectionChunk *sec, uint8_t *off,301OutputSection *os, uint64_t s) {302if (checkSecRel(sec, os))303applyArm64Ldr(off, (s - os->getRVA()) & 0xfff);304}305306void applyArm64Branch26(uint8_t *off, int64_t v) {307if (!isInt<28>(v))308error("relocation out of range");309or32(off, (v & 0x0FFFFFFC) >> 2);310}311312static void applyArm64Branch19(uint8_t *off, int64_t v) {313if (!isInt<21>(v))314error("relocation out of range");315or32(off, (v & 0x001FFFFC) << 3);316}317318static void applyArm64Branch14(uint8_t *off, int64_t v) {319if (!isInt<16>(v))320error("relocation out of range");321or32(off, (v & 0x0000FFFC) << 3);322}323324void SectionChunk::applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os,325uint64_t s, uint64_t p,326uint64_t imageBase) const {327switch (type) {328case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(off, s, p, 12); break;329case IMAGE_REL_ARM64_REL21: applyArm64Addr(off, s, p, 0); break;330case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(off, s & 0xfff, 0); break;331case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(off, s & 0xfff); break;332case IMAGE_REL_ARM64_BRANCH26: applyArm64Branch26(off, s - p); break;333case IMAGE_REL_ARM64_BRANCH19: applyArm64Branch19(off, s - p); break;334case IMAGE_REL_ARM64_BRANCH14: applyArm64Branch14(off, s - p); break;335case IMAGE_REL_ARM64_ADDR32:336add32(off, s + imageBase);337break;338case IMAGE_REL_ARM64_ADDR32NB: add32(off, s); break;339case IMAGE_REL_ARM64_ADDR64:340add64(off, s + imageBase);341break;342case IMAGE_REL_ARM64_SECREL: applySecRel(this, off, os, s); break;343case IMAGE_REL_ARM64_SECREL_LOW12A: applySecRelLow12A(this, off, os, s); break;344case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(this, off, os, s); break;345case IMAGE_REL_ARM64_SECREL_LOW12L: applySecRelLdr(this, off, os, s); break;346case IMAGE_REL_ARM64_SECTION:347applySecIdx(off, os, file->ctx.outputSections.size());348break;349case IMAGE_REL_ARM64_REL32: add32(off, s - p - 4); break;350default:351error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +352toString(file));353}354}355356static void maybeReportRelocationToDiscarded(const SectionChunk *fromChunk,357Defined *sym,358const coff_relocation &rel,359bool isMinGW) {360// Don't report these errors when the relocation comes from a debug info361// section or in mingw mode. MinGW mode object files (built by GCC) can362// have leftover sections with relocations against discarded comdat363// sections. Such sections are left as is, with relocations untouched.364if (fromChunk->isCodeView() || fromChunk->isDWARF() || isMinGW)365return;366367// Get the name of the symbol. If it's null, it was discarded early, so we368// have to go back to the object file.369ObjFile *file = fromChunk->file;370StringRef name;371if (sym) {372name = sym->getName();373} else {374COFFSymbolRef coffSym =375check(file->getCOFFObj()->getSymbol(rel.SymbolTableIndex));376name = check(file->getCOFFObj()->getSymbolName(coffSym));377}378379std::vector<std::string> symbolLocations =380getSymbolLocations(file, rel.SymbolTableIndex);381382std::string out;383llvm::raw_string_ostream os(out);384os << "relocation against symbol in discarded section: " + name;385for (const std::string &s : symbolLocations)386os << s;387error(os.str());388}389390void SectionChunk::writeTo(uint8_t *buf) const {391if (!hasData)392return;393// Copy section contents from source object file to output file.394ArrayRef<uint8_t> a = getContents();395if (!a.empty())396memcpy(buf, a.data(), a.size());397398// Apply relocations.399size_t inputSize = getSize();400for (const coff_relocation &rel : getRelocs()) {401// Check for an invalid relocation offset. This check isn't perfect, because402// we don't have the relocation size, which is only known after checking the403// machine and relocation type. As a result, a relocation may overwrite the404// beginning of the following input section.405if (rel.VirtualAddress >= inputSize) {406error("relocation points beyond the end of its parent section");407continue;408}409410applyRelocation(buf + rel.VirtualAddress, rel);411}412413// Write the offset to EC entry thunk preceding section contents. The low bit414// is always set, so it's effectively an offset from the last byte of the415// offset.416if (Defined *entryThunk = getEntryThunk())417write32le(buf - sizeof(uint32_t), entryThunk->getRVA() - rva + 1);418}419420void SectionChunk::applyRelocation(uint8_t *off,421const coff_relocation &rel) const {422auto *sym = dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));423424// Get the output section of the symbol for this relocation. The output425// section is needed to compute SECREL and SECTION relocations used in debug426// info.427Chunk *c = sym ? sym->getChunk() : nullptr;428OutputSection *os = c ? file->ctx.getOutputSection(c) : nullptr;429430// Skip the relocation if it refers to a discarded section, and diagnose it431// as an error if appropriate. If a symbol was discarded early, it may be432// null. If it was discarded late, the output section will be null, unless433// it was an absolute or synthetic symbol.434if (!sym ||435(!os && !isa<DefinedAbsolute>(sym) && !isa<DefinedSynthetic>(sym))) {436maybeReportRelocationToDiscarded(this, sym, rel, file->ctx.config.mingw);437return;438}439440uint64_t s = sym->getRVA();441442// Compute the RVA of the relocation for relative relocations.443uint64_t p = rva + rel.VirtualAddress;444uint64_t imageBase = file->ctx.config.imageBase;445switch (getArch()) {446case Triple::x86_64:447applyRelX64(off, rel.Type, os, s, p, imageBase);448break;449case Triple::x86:450applyRelX86(off, rel.Type, os, s, p, imageBase);451break;452case Triple::thumb:453applyRelARM(off, rel.Type, os, s, p, imageBase);454break;455case Triple::aarch64:456applyRelARM64(off, rel.Type, os, s, p, imageBase);457break;458default:459llvm_unreachable("unknown machine type");460}461}462463// Defend against unsorted relocations. This may be overly conservative.464void SectionChunk::sortRelocations() {465auto cmpByVa = [](const coff_relocation &l, const coff_relocation &r) {466return l.VirtualAddress < r.VirtualAddress;467};468if (llvm::is_sorted(getRelocs(), cmpByVa))469return;470warn("some relocations in " + file->getName() + " are not sorted");471MutableArrayRef<coff_relocation> newRelocs(472bAlloc().Allocate<coff_relocation>(relocsSize), relocsSize);473memcpy(newRelocs.data(), relocsData, relocsSize * sizeof(coff_relocation));474llvm::sort(newRelocs, cmpByVa);475setRelocs(newRelocs);476}477478// Similar to writeTo, but suitable for relocating a subsection of the overall479// section.480void SectionChunk::writeAndRelocateSubsection(ArrayRef<uint8_t> sec,481ArrayRef<uint8_t> subsec,482uint32_t &nextRelocIndex,483uint8_t *buf) const {484assert(!subsec.empty() && !sec.empty());485assert(sec.begin() <= subsec.begin() && subsec.end() <= sec.end() &&486"subsection is not part of this section");487size_t vaBegin = std::distance(sec.begin(), subsec.begin());488size_t vaEnd = std::distance(sec.begin(), subsec.end());489memcpy(buf, subsec.data(), subsec.size());490for (; nextRelocIndex < relocsSize; ++nextRelocIndex) {491const coff_relocation &rel = relocsData[nextRelocIndex];492// Only apply relocations that apply to this subsection. These checks493// assume that all subsections completely contain their relocations.494// Relocations must not straddle the beginning or end of a subsection.495if (rel.VirtualAddress < vaBegin)496continue;497if (rel.VirtualAddress + 1 >= vaEnd)498break;499applyRelocation(&buf[rel.VirtualAddress - vaBegin], rel);500}501}502503void SectionChunk::addAssociative(SectionChunk *child) {504// Insert the child section into the list of associated children. Keep the505// list ordered by section name so that ICF does not depend on section order.506assert(child->assocChildren == nullptr &&507"associated sections cannot have their own associated children");508SectionChunk *prev = this;509SectionChunk *next = assocChildren;510for (; next != nullptr; prev = next, next = next->assocChildren) {511if (next->getSectionName() <= child->getSectionName())512break;513}514515// Insert child between prev and next.516assert(prev->assocChildren == next);517prev->assocChildren = child;518child->assocChildren = next;519}520521static uint8_t getBaserelType(const coff_relocation &rel,522Triple::ArchType arch) {523switch (arch) {524case Triple::x86_64:525if (rel.Type == IMAGE_REL_AMD64_ADDR64)526return IMAGE_REL_BASED_DIR64;527if (rel.Type == IMAGE_REL_AMD64_ADDR32)528return IMAGE_REL_BASED_HIGHLOW;529return IMAGE_REL_BASED_ABSOLUTE;530case Triple::x86:531if (rel.Type == IMAGE_REL_I386_DIR32)532return IMAGE_REL_BASED_HIGHLOW;533return IMAGE_REL_BASED_ABSOLUTE;534case Triple::thumb:535if (rel.Type == IMAGE_REL_ARM_ADDR32)536return IMAGE_REL_BASED_HIGHLOW;537if (rel.Type == IMAGE_REL_ARM_MOV32T)538return IMAGE_REL_BASED_ARM_MOV32T;539return IMAGE_REL_BASED_ABSOLUTE;540case Triple::aarch64:541if (rel.Type == IMAGE_REL_ARM64_ADDR64)542return IMAGE_REL_BASED_DIR64;543return IMAGE_REL_BASED_ABSOLUTE;544default:545llvm_unreachable("unknown machine type");546}547}548549// Windows-specific.550// Collect all locations that contain absolute addresses, which need to be551// fixed by the loader if load-time relocation is needed.552// Only called when base relocation is enabled.553void SectionChunk::getBaserels(std::vector<Baserel> *res) {554for (const coff_relocation &rel : getRelocs()) {555uint8_t ty = getBaserelType(rel, getArch());556if (ty == IMAGE_REL_BASED_ABSOLUTE)557continue;558Symbol *target = file->getSymbol(rel.SymbolTableIndex);559if (!target || isa<DefinedAbsolute>(target))560continue;561res->emplace_back(rva + rel.VirtualAddress, ty);562}563}564565// MinGW specific.566// Check whether a static relocation of type Type can be deferred and567// handled at runtime as a pseudo relocation (for references to a module568// local variable, which turned out to actually need to be imported from569// another DLL) This returns the size the relocation is supposed to update,570// in bits, or 0 if the relocation cannot be handled as a runtime pseudo571// relocation.572static int getRuntimePseudoRelocSize(uint16_t type,573llvm::COFF::MachineTypes machine) {574// Relocations that either contain an absolute address, or a plain575// relative offset, since the runtime pseudo reloc implementation576// adds 8/16/32/64 bit values to a memory address.577//578// Given a pseudo relocation entry,579//580// typedef struct {581// DWORD sym;582// DWORD target;583// DWORD flags;584// } runtime_pseudo_reloc_item_v2;585//586// the runtime relocation performs this adjustment:587// *(base + .target) += *(base + .sym) - (base + .sym)588//589// This works for both absolute addresses (IMAGE_REL_*_ADDR32/64,590// IMAGE_REL_I386_DIR32, where the memory location initially contains591// the address of the IAT slot, and for relative addresses (IMAGE_REL*_REL32),592// where the memory location originally contains the relative offset to the593// IAT slot.594//595// This requires the target address to be writable, either directly out of596// the image, or temporarily changed at runtime with VirtualProtect.597// Since this only operates on direct address values, it doesn't work for598// ARM/ARM64 relocations, other than the plain ADDR32/ADDR64 relocations.599switch (machine) {600case AMD64:601switch (type) {602case IMAGE_REL_AMD64_ADDR64:603return 64;604case IMAGE_REL_AMD64_ADDR32:605case IMAGE_REL_AMD64_REL32:606case IMAGE_REL_AMD64_REL32_1:607case IMAGE_REL_AMD64_REL32_2:608case IMAGE_REL_AMD64_REL32_3:609case IMAGE_REL_AMD64_REL32_4:610case IMAGE_REL_AMD64_REL32_5:611return 32;612default:613return 0;614}615case I386:616switch (type) {617case IMAGE_REL_I386_DIR32:618case IMAGE_REL_I386_REL32:619return 32;620default:621return 0;622}623case ARMNT:624switch (type) {625case IMAGE_REL_ARM_ADDR32:626return 32;627default:628return 0;629}630case ARM64:631switch (type) {632case IMAGE_REL_ARM64_ADDR64:633return 64;634case IMAGE_REL_ARM64_ADDR32:635return 32;636default:637return 0;638}639default:640llvm_unreachable("unknown machine type");641}642}643644// MinGW specific.645// Append information to the provided vector about all relocations that646// need to be handled at runtime as runtime pseudo relocations (references647// to a module local variable, which turned out to actually need to be648// imported from another DLL).649void SectionChunk::getRuntimePseudoRelocs(650std::vector<RuntimePseudoReloc> &res) {651for (const coff_relocation &rel : getRelocs()) {652auto *target =653dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));654if (!target || !target->isRuntimePseudoReloc)655continue;656// If the target doesn't have a chunk allocated, it may be a657// DefinedImportData symbol which ended up unnecessary after GC.658// Normally we wouldn't eliminate section chunks that are referenced, but659// references within DWARF sections don't count for keeping section chunks660// alive. Thus such dangling references in DWARF sections are expected.661if (!target->getChunk())662continue;663int sizeInBits =664getRuntimePseudoRelocSize(rel.Type, file->ctx.config.machine);665if (sizeInBits == 0) {666error("unable to automatically import from " + target->getName() +667" with relocation type " +668file->getCOFFObj()->getRelocationTypeName(rel.Type) + " in " +669toString(file));670continue;671}672int addressSizeInBits = file->ctx.config.is64() ? 64 : 32;673if (sizeInBits < addressSizeInBits) {674warn("runtime pseudo relocation in " + toString(file) + " against " +675"symbol " + target->getName() + " is too narrow (only " +676Twine(sizeInBits) + " bits wide); this can fail at runtime " +677"depending on memory layout");678}679// sizeInBits is used to initialize the Flags field; currently no680// other flags are defined.681res.emplace_back(target, this, rel.VirtualAddress, sizeInBits);682}683}684685bool SectionChunk::isCOMDAT() const {686return header->Characteristics & IMAGE_SCN_LNK_COMDAT;687}688689void SectionChunk::printDiscardedMessage() const {690// Removed by dead-stripping. If it's removed by ICF, ICF already691// printed out the name, so don't repeat that here.692if (sym && this == repl)693log("Discarded " + sym->getName());694}695696StringRef SectionChunk::getDebugName() const {697if (sym)698return sym->getName();699return "";700}701702ArrayRef<uint8_t> SectionChunk::getContents() const {703ArrayRef<uint8_t> a;704cantFail(file->getCOFFObj()->getSectionContents(header, a));705return a;706}707708ArrayRef<uint8_t> SectionChunk::consumeDebugMagic() {709assert(isCodeView());710return consumeDebugMagic(getContents(), getSectionName());711}712713ArrayRef<uint8_t> SectionChunk::consumeDebugMagic(ArrayRef<uint8_t> data,714StringRef sectionName) {715if (data.empty())716return {};717718// First 4 bytes are section magic.719if (data.size() < 4)720fatal("the section is too short: " + sectionName);721722if (!sectionName.starts_with(".debug$"))723fatal("invalid section: " + sectionName);724725uint32_t magic = support::endian::read32le(data.data());726uint32_t expectedMagic = sectionName == ".debug$H"727? DEBUG_HASHES_SECTION_MAGIC728: DEBUG_SECTION_MAGIC;729if (magic != expectedMagic) {730warn("ignoring section " + sectionName + " with unrecognized magic 0x" +731utohexstr(magic));732return {};733}734return data.slice(4);735}736737SectionChunk *SectionChunk::findByName(ArrayRef<SectionChunk *> sections,738StringRef name) {739for (SectionChunk *c : sections)740if (c->getSectionName() == name)741return c;742return nullptr;743}744745void SectionChunk::replace(SectionChunk *other) {746p2Align = std::max(p2Align, other->p2Align);747other->repl = repl;748other->live = false;749}750751uint32_t SectionChunk::getSectionNumber() const {752DataRefImpl r;753r.p = reinterpret_cast<uintptr_t>(header);754SectionRef s(r, file->getCOFFObj());755return s.getIndex() + 1;756}757758CommonChunk::CommonChunk(const COFFSymbolRef s) : sym(s) {759// The value of a common symbol is its size. Align all common symbols smaller760// than 32 bytes naturally, i.e. round the size up to the next power of two.761// This is what MSVC link.exe does.762setAlignment(std::min(32U, uint32_t(PowerOf2Ceil(sym.getValue()))));763hasData = false;764}765766uint32_t CommonChunk::getOutputCharacteristics() const {767return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |768IMAGE_SCN_MEM_WRITE;769}770771void StringChunk::writeTo(uint8_t *buf) const {772memcpy(buf, str.data(), str.size());773buf[str.size()] = '\0';774}775776ImportThunkChunkX64::ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s)777: ImportThunkChunk(ctx, s) {778// Intel Optimization Manual says that all branch targets779// should be 16-byte aligned. MSVC linker does this too.780setAlignment(16);781}782783void ImportThunkChunkX64::writeTo(uint8_t *buf) const {784memcpy(buf, importThunkX86, sizeof(importThunkX86));785// The first two bytes is a JMP instruction. Fill its operand.786write32le(buf + 2, impSymbol->getRVA() - rva - getSize());787}788789void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *res) {790res->emplace_back(getRVA() + 2, ctx.config.machine);791}792793void ImportThunkChunkX86::writeTo(uint8_t *buf) const {794memcpy(buf, importThunkX86, sizeof(importThunkX86));795// The first two bytes is a JMP instruction. Fill its operand.796write32le(buf + 2, impSymbol->getRVA() + ctx.config.imageBase);797}798799void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *res) {800res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T);801}802803void ImportThunkChunkARM::writeTo(uint8_t *buf) const {804memcpy(buf, importThunkARM, sizeof(importThunkARM));805// Fix mov.w and mov.t operands.806applyMOV32T(buf, impSymbol->getRVA() + ctx.config.imageBase);807}808809void ImportThunkChunkARM64::writeTo(uint8_t *buf) const {810int64_t off = impSymbol->getRVA() & 0xfff;811memcpy(buf, importThunkARM64, sizeof(importThunkARM64));812applyArm64Addr(buf, impSymbol->getRVA(), rva, 12);813applyArm64Ldr(buf + 4, off);814}815816// A Thumb2, PIC, non-interworking range extension thunk.817const uint8_t armThunk[] = {8180x40, 0xf2, 0x00, 0x0c, // P: movw ip,:lower16:S - (P + (L1-P) + 4)8190xc0, 0xf2, 0x00, 0x0c, // movt ip,:upper16:S - (P + (L1-P) + 4)8200xe7, 0x44, // L1: add pc, ip821};822823size_t RangeExtensionThunkARM::getSize() const {824assert(ctx.config.machine == ARMNT);825(void)&ctx;826return sizeof(armThunk);827}828829void RangeExtensionThunkARM::writeTo(uint8_t *buf) const {830assert(ctx.config.machine == ARMNT);831uint64_t offset = target->getRVA() - rva - 12;832memcpy(buf, armThunk, sizeof(armThunk));833applyMOV32T(buf, uint32_t(offset));834}835836// A position independent ARM64 adrp+add thunk, with a maximum range of837// +/- 4 GB, which is enough for any PE-COFF.838const uint8_t arm64Thunk[] = {8390x10, 0x00, 0x00, 0x90, // adrp x16, Dest8400x10, 0x02, 0x00, 0x91, // add x16, x16, :lo12:Dest8410x00, 0x02, 0x1f, 0xd6, // br x16842};843844size_t RangeExtensionThunkARM64::getSize() const {845assert(ctx.config.machine == ARM64);846(void)&ctx;847return sizeof(arm64Thunk);848}849850void RangeExtensionThunkARM64::writeTo(uint8_t *buf) const {851assert(ctx.config.machine == ARM64);852memcpy(buf, arm64Thunk, sizeof(arm64Thunk));853applyArm64Addr(buf + 0, target->getRVA(), rva, 12);854applyArm64Imm(buf + 4, target->getRVA() & 0xfff, 0);855}856857LocalImportChunk::LocalImportChunk(COFFLinkerContext &c, Defined *s)858: sym(s), ctx(c) {859setAlignment(ctx.config.wordsize);860}861862void LocalImportChunk::getBaserels(std::vector<Baserel> *res) {863res->emplace_back(getRVA(), ctx.config.machine);864}865866size_t LocalImportChunk::getSize() const { return ctx.config.wordsize; }867868void LocalImportChunk::writeTo(uint8_t *buf) const {869if (ctx.config.is64()) {870write64le(buf, sym->getRVA() + ctx.config.imageBase);871} else {872write32le(buf, sym->getRVA() + ctx.config.imageBase);873}874}875876void RVATableChunk::writeTo(uint8_t *buf) const {877ulittle32_t *begin = reinterpret_cast<ulittle32_t *>(buf);878size_t cnt = 0;879for (const ChunkAndOffset &co : syms)880begin[cnt++] = co.inputChunk->getRVA() + co.offset;881llvm::sort(begin, begin + cnt);882assert(std::unique(begin, begin + cnt) == begin + cnt &&883"RVA tables should be de-duplicated");884}885886void RVAFlagTableChunk::writeTo(uint8_t *buf) const {887struct RVAFlag {888ulittle32_t rva;889uint8_t flag;890};891auto flags =892MutableArrayRef(reinterpret_cast<RVAFlag *>(buf), syms.size());893for (auto t : zip(syms, flags)) {894const auto &sym = std::get<0>(t);895auto &flag = std::get<1>(t);896flag.rva = sym.inputChunk->getRVA() + sym.offset;897flag.flag = 0;898}899llvm::sort(flags,900[](const RVAFlag &a, const RVAFlag &b) { return a.rva < b.rva; });901assert(llvm::unique(flags, [](const RVAFlag &a,902const RVAFlag &b) { return a.rva == b.rva; }) ==903flags.end() &&904"RVA tables should be de-duplicated");905}906907size_t ECCodeMapChunk::getSize() const {908return map.size() * sizeof(chpe_range_entry);909}910911void ECCodeMapChunk::writeTo(uint8_t *buf) const {912auto table = reinterpret_cast<chpe_range_entry *>(buf);913for (uint32_t i = 0; i < map.size(); i++) {914const ECCodeMapEntry &entry = map[i];915uint32_t start = entry.first->getRVA();916table[i].StartOffset = start | entry.type;917table[i].Length = entry.last->getRVA() + entry.last->getSize() - start;918}919}920921// MinGW specific, for the "automatic import of variables from DLLs" feature.922size_t PseudoRelocTableChunk::getSize() const {923if (relocs.empty())924return 0;925return 12 + 12 * relocs.size();926}927928// MinGW specific.929void PseudoRelocTableChunk::writeTo(uint8_t *buf) const {930if (relocs.empty())931return;932933ulittle32_t *table = reinterpret_cast<ulittle32_t *>(buf);934// This is the list header, to signal the runtime pseudo relocation v2935// format.936table[0] = 0;937table[1] = 0;938table[2] = 1;939940size_t idx = 3;941for (const RuntimePseudoReloc &rpr : relocs) {942table[idx + 0] = rpr.sym->getRVA();943table[idx + 1] = rpr.target->getRVA() + rpr.targetOffset;944table[idx + 2] = rpr.flags;945idx += 3;946}947}948949// Windows-specific. This class represents a block in .reloc section.950// The format is described here.951//952// On Windows, each DLL is linked against a fixed base address and953// usually loaded to that address. However, if there's already another954// DLL that overlaps, the loader has to relocate it. To do that, DLLs955// contain .reloc sections which contain offsets that need to be fixed956// up at runtime. If the loader finds that a DLL cannot be loaded to its957// desired base address, it loads it to somewhere else, and add <actual958// base address> - <desired base address> to each offset that is959// specified by the .reloc section. In ELF terms, .reloc sections960// contain relative relocations in REL format (as opposed to RELA.)961//962// This already significantly reduces the size of relocations compared963// to ELF .rel.dyn, but Windows does more to reduce it (probably because964// it was invented for PCs in the late '80s or early '90s.) Offsets in965// .reloc are grouped by page where the page size is 12 bits, and966// offsets sharing the same page address are stored consecutively to967// represent them with less space. This is very similar to the page968// table which is grouped by (multiple stages of) pages.969//970// For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,971// 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4972// bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they973// are represented like this:974//975// 0x00000 -- page address (4 bytes)976// 16 -- size of this block (4 bytes)977// 0xA030 -- entries (2 bytes each)978// 0xA500979// 0xA700980// 0xAA00981// 0x20000 -- page address (4 bytes)982// 12 -- size of this block (4 bytes)983// 0xA004 -- entries (2 bytes each)984// 0xA008985//986// Usually we have a lot of relocations for each page, so the number of987// bytes for one .reloc entry is close to 2 bytes on average.988BaserelChunk::BaserelChunk(uint32_t page, Baserel *begin, Baserel *end) {989// Block header consists of 4 byte page RVA and 4 byte block size.990// Each entry is 2 byte. Last entry may be padding.991data.resize(alignTo((end - begin) * 2 + 8, 4));992uint8_t *p = data.data();993write32le(p, page);994write32le(p + 4, data.size());995p += 8;996for (Baserel *i = begin; i != end; ++i) {997write16le(p, (i->type << 12) | (i->rva - page));998p += 2;999}1000}10011002void BaserelChunk::writeTo(uint8_t *buf) const {1003memcpy(buf, data.data(), data.size());1004}10051006uint8_t Baserel::getDefaultType(llvm::COFF::MachineTypes machine) {1007switch (machine) {1008case AMD64:1009case ARM64:1010return IMAGE_REL_BASED_DIR64;1011case I386:1012case ARMNT:1013return IMAGE_REL_BASED_HIGHLOW;1014default:1015llvm_unreachable("unknown machine type");1016}1017}10181019MergeChunk::MergeChunk(uint32_t alignment)1020: builder(StringTableBuilder::RAW, llvm::Align(alignment)) {1021setAlignment(alignment);1022}10231024void MergeChunk::addSection(COFFLinkerContext &ctx, SectionChunk *c) {1025assert(isPowerOf2_32(c->getAlignment()));1026uint8_t p2Align = llvm::Log2_32(c->getAlignment());1027assert(p2Align < std::size(ctx.mergeChunkInstances));1028auto *&mc = ctx.mergeChunkInstances[p2Align];1029if (!mc)1030mc = make<MergeChunk>(c->getAlignment());1031mc->sections.push_back(c);1032}10331034void MergeChunk::finalizeContents() {1035assert(!finalized && "should only finalize once");1036for (SectionChunk *c : sections)1037if (c->live)1038builder.add(toStringRef(c->getContents()));1039builder.finalize();1040finalized = true;1041}10421043void MergeChunk::assignSubsectionRVAs() {1044for (SectionChunk *c : sections) {1045if (!c->live)1046continue;1047size_t off = builder.getOffset(toStringRef(c->getContents()));1048c->setRVA(rva + off);1049}1050}10511052uint32_t MergeChunk::getOutputCharacteristics() const {1053return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;1054}10551056size_t MergeChunk::getSize() const {1057return builder.getSize();1058}10591060void MergeChunk::writeTo(uint8_t *buf) const {1061builder.write(buf);1062}10631064// MinGW specific.1065size_t AbsolutePointerChunk::getSize() const { return ctx.config.wordsize; }10661067void AbsolutePointerChunk::writeTo(uint8_t *buf) const {1068if (ctx.config.is64()) {1069write64le(buf, value);1070} else {1071write32le(buf, value);1072}1073}10741075} // namespace lld::coff107610771078