llvm-project
1076 строк · 37.6 Кб
1//===- Chunks.cpp ---------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Chunks.h"10#include "COFFLinkerContext.h"11#include "InputFiles.h"12#include "SymbolTable.h"13#include "Symbols.h"14#include "Writer.h"15#include "llvm/ADT/STLExtras.h"16#include "llvm/ADT/StringExtras.h"17#include "llvm/ADT/Twine.h"18#include "llvm/BinaryFormat/COFF.h"19#include "llvm/Object/COFF.h"20#include "llvm/Support/Debug.h"21#include "llvm/Support/Endian.h"22#include "llvm/Support/raw_ostream.h"23#include <algorithm>24#include <iterator>25
26using namespace llvm;27using namespace llvm::object;28using namespace llvm::support::endian;29using namespace llvm::COFF;30using llvm::support::ulittle32_t;31
32namespace lld::coff {33
34SectionChunk::SectionChunk(ObjFile *f, const coff_section *h, Kind k)35: Chunk(k), file(f), header(h), repl(this) {36// Initialize relocs.37if (file)38setRelocs(file->getCOFFObj()->getRelocations(header));39
40// Initialize sectionName.41StringRef sectionName;42if (file) {43if (Expected<StringRef> e = file->getCOFFObj()->getSectionName(header))44sectionName = *e;45}46sectionNameData = sectionName.data();47sectionNameSize = sectionName.size();48
49setAlignment(header->getAlignment());50
51hasData = !(header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);52
53// If linker GC is disabled, every chunk starts out alive. If linker GC is54// enabled, treat non-comdat sections as roots. Generally optimized object55// files will be built with -ffunction-sections or /Gy, so most things worth56// stripping will be in a comdat.57if (file)58live = !file->ctx.config.doGC || !isCOMDAT();59else60live = true;61}
62
63// SectionChunk is one of the most frequently allocated classes, so it is
64// important to keep it as compact as possible. As of this writing, the number
65// below is the size of this class on x64 platforms.
66static_assert(sizeof(SectionChunk) <= 88, "SectionChunk grew unexpectedly");67
68static void add16(uint8_t *p, int16_t v) { write16le(p, read16le(p) + v); }69static void add32(uint8_t *p, int32_t v) { write32le(p, read32le(p) + v); }70static void add64(uint8_t *p, int64_t v) { write64le(p, read64le(p) + v); }71static void or16(uint8_t *p, uint16_t v) { write16le(p, read16le(p) | v); }72static void or32(uint8_t *p, uint32_t v) { write32le(p, read32le(p) | v); }73
74// Verify that given sections are appropriate targets for SECREL
75// relocations. This check is relaxed because unfortunately debug
76// sections have section-relative relocations against absolute symbols.
77static bool checkSecRel(const SectionChunk *sec, OutputSection *os) {78if (os)79return true;80if (sec->isCodeView())81return false;82error("SECREL relocation cannot be applied to absolute symbols");83return false;84}
85
86static void applySecRel(const SectionChunk *sec, uint8_t *off,87OutputSection *os, uint64_t s) {88if (!checkSecRel(sec, os))89return;90uint64_t secRel = s - os->getRVA();91if (secRel > UINT32_MAX) {92error("overflow in SECREL relocation in section: " + sec->getSectionName());93return;94}95add32(off, secRel);96}
97
98static void applySecIdx(uint8_t *off, OutputSection *os,99unsigned numOutputSections) {100// numOutputSections is the largest valid section index. Make sure that101// it fits in 16 bits.102assert(numOutputSections <= 0xffff && "size of outputSections is too big");103
104// Absolute symbol doesn't have section index, but section index relocation105// against absolute symbol should be resolved to one plus the last output106// section index. This is required for compatibility with MSVC.107if (os)108add16(off, os->sectionIndex);109else110add16(off, numOutputSections + 1);111}
112
113void SectionChunk::applyRelX64(uint8_t *off, uint16_t type, OutputSection *os,114uint64_t s, uint64_t p,115uint64_t imageBase) const {116switch (type) {117case IMAGE_REL_AMD64_ADDR32:118add32(off, s + imageBase);119break;120case IMAGE_REL_AMD64_ADDR64:121add64(off, s + imageBase);122break;123case IMAGE_REL_AMD64_ADDR32NB: add32(off, s); break;124case IMAGE_REL_AMD64_REL32: add32(off, s - p - 4); break;125case IMAGE_REL_AMD64_REL32_1: add32(off, s - p - 5); break;126case IMAGE_REL_AMD64_REL32_2: add32(off, s - p - 6); break;127case IMAGE_REL_AMD64_REL32_3: add32(off, s - p - 7); break;128case IMAGE_REL_AMD64_REL32_4: add32(off, s - p - 8); break;129case IMAGE_REL_AMD64_REL32_5: add32(off, s - p - 9); break;130case IMAGE_REL_AMD64_SECTION:131applySecIdx(off, os, file->ctx.outputSections.size());132break;133case IMAGE_REL_AMD64_SECREL: applySecRel(this, off, os, s); break;134default:135error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +136toString(file));137}138}
139
140void SectionChunk::applyRelX86(uint8_t *off, uint16_t type, OutputSection *os,141uint64_t s, uint64_t p,142uint64_t imageBase) const {143switch (type) {144case IMAGE_REL_I386_ABSOLUTE: break;145case IMAGE_REL_I386_DIR32:146add32(off, s + imageBase);147break;148case IMAGE_REL_I386_DIR32NB: add32(off, s); break;149case IMAGE_REL_I386_REL32: add32(off, s - p - 4); break;150case IMAGE_REL_I386_SECTION:151applySecIdx(off, os, file->ctx.outputSections.size());152break;153case IMAGE_REL_I386_SECREL: applySecRel(this, off, os, s); break;154default:155error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +156toString(file));157}158}
159
160static void applyMOV(uint8_t *off, uint16_t v) {161write16le(off, (read16le(off) & 0xfbf0) | ((v & 0x800) >> 1) | ((v >> 12) & 0xf));162write16le(off + 2, (read16le(off + 2) & 0x8f00) | ((v & 0x700) << 4) | (v & 0xff));163}
164
165static uint16_t readMOV(uint8_t *off, bool movt) {166uint16_t op1 = read16le(off);167if ((op1 & 0xfbf0) != (movt ? 0xf2c0 : 0xf240))168error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +169" instruction in MOV32T relocation");170uint16_t op2 = read16le(off + 2);171if ((op2 & 0x8000) != 0)172error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +173" instruction in MOV32T relocation");174return (op2 & 0x00ff) | ((op2 >> 4) & 0x0700) | ((op1 << 1) & 0x0800) |175((op1 & 0x000f) << 12);176}
177
178void applyMOV32T(uint8_t *off, uint32_t v) {179uint16_t immW = readMOV(off, false); // read MOVW operand180uint16_t immT = readMOV(off + 4, true); // read MOVT operand181uint32_t imm = immW | (immT << 16);182v += imm; // add the immediate offset183applyMOV(off, v); // set MOVW operand184applyMOV(off + 4, v >> 16); // set MOVT operand185}
186
187static void applyBranch20T(uint8_t *off, int32_t v) {188if (!isInt<21>(v))189error("relocation out of range");190uint32_t s = v < 0 ? 1 : 0;191uint32_t j1 = (v >> 19) & 1;192uint32_t j2 = (v >> 18) & 1;193or16(off, (s << 10) | ((v >> 12) & 0x3f));194or16(off + 2, (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));195}
196
197void applyBranch24T(uint8_t *off, int32_t v) {198if (!isInt<25>(v))199error("relocation out of range");200uint32_t s = v < 0 ? 1 : 0;201uint32_t j1 = ((~v >> 23) & 1) ^ s;202uint32_t j2 = ((~v >> 22) & 1) ^ s;203or16(off, (s << 10) | ((v >> 12) & 0x3ff));204// Clear out the J1 and J2 bits which may be set.205write16le(off + 2, (read16le(off + 2) & 0xd000) | (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));206}
207
208void SectionChunk::applyRelARM(uint8_t *off, uint16_t type, OutputSection *os,209uint64_t s, uint64_t p,210uint64_t imageBase) const {211// Pointer to thumb code must have the LSB set.212uint64_t sx = s;213if (os && (os->header.Characteristics & IMAGE_SCN_MEM_EXECUTE))214sx |= 1;215switch (type) {216case IMAGE_REL_ARM_ADDR32:217add32(off, sx + imageBase);218break;219case IMAGE_REL_ARM_ADDR32NB: add32(off, sx); break;220case IMAGE_REL_ARM_MOV32T:221applyMOV32T(off, sx + imageBase);222break;223case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(off, sx - p - 4); break;224case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(off, sx - p - 4); break;225case IMAGE_REL_ARM_BLX23T: applyBranch24T(off, sx - p - 4); break;226case IMAGE_REL_ARM_SECTION:227applySecIdx(off, os, file->ctx.outputSections.size());228break;229case IMAGE_REL_ARM_SECREL: applySecRel(this, off, os, s); break;230case IMAGE_REL_ARM_REL32: add32(off, sx - p - 4); break;231default:232error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +233toString(file));234}235}
236
237// Interpret the existing immediate value as a byte offset to the
238// target symbol, then update the instruction with the immediate as
239// the page offset from the current instruction to the target.
240void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift) {241uint32_t orig = read32le(off);242int64_t imm =243SignExtend64<21>(((orig >> 29) & 0x3) | ((orig >> 3) & 0x1FFFFC));244s += imm;245imm = (s >> shift) - (p >> shift);246uint32_t immLo = (imm & 0x3) << 29;247uint32_t immHi = (imm & 0x1FFFFC) << 3;248uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);249write32le(off, (orig & ~mask) | immLo | immHi);250}
251
252// Update the immediate field in a AARCH64 ldr, str, and add instruction.
253// Optionally limit the range of the written immediate by one or more bits
254// (rangeLimit).
255void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit) {256uint32_t orig = read32le(off);257imm += (orig >> 10) & 0xFFF;258orig &= ~(0xFFF << 10);259write32le(off, orig | ((imm & (0xFFF >> rangeLimit)) << 10));260}
261
262// Add the 12 bit page offset to the existing immediate.
263// Ldr/str instructions store the opcode immediate scaled
264// by the load/store size (giving a larger range for larger
265// loads/stores). The immediate is always (both before and after
266// fixing up the relocation) stored scaled similarly.
267// Even if larger loads/stores have a larger range, limit the
268// effective offset to 12 bit, since it is intended to be a
269// page offset.
270static void applyArm64Ldr(uint8_t *off, uint64_t imm) {271uint32_t orig = read32le(off);272uint32_t size = orig >> 30;273// 0x04000000 indicates SIMD/FP registers274// 0x00800000 indicates 128 bit275if ((orig & 0x4800000) == 0x4800000)276size += 4;277if ((imm & ((1 << size) - 1)) != 0)278error("misaligned ldr/str offset");279applyArm64Imm(off, imm >> size, size);280}
281
282static void applySecRelLow12A(const SectionChunk *sec, uint8_t *off,283OutputSection *os, uint64_t s) {284if (checkSecRel(sec, os))285applyArm64Imm(off, (s - os->getRVA()) & 0xfff, 0);286}
287
288static void applySecRelHigh12A(const SectionChunk *sec, uint8_t *off,289OutputSection *os, uint64_t s) {290if (!checkSecRel(sec, os))291return;292uint64_t secRel = (s - os->getRVA()) >> 12;293if (0xfff < secRel) {294error("overflow in SECREL_HIGH12A relocation in section: " +295sec->getSectionName());296return;297}298applyArm64Imm(off, secRel & 0xfff, 0);299}
300
301static void applySecRelLdr(const SectionChunk *sec, uint8_t *off,302OutputSection *os, uint64_t s) {303if (checkSecRel(sec, os))304applyArm64Ldr(off, (s - os->getRVA()) & 0xfff);305}
306
307void applyArm64Branch26(uint8_t *off, int64_t v) {308if (!isInt<28>(v))309error("relocation out of range");310or32(off, (v & 0x0FFFFFFC) >> 2);311}
312
313static void applyArm64Branch19(uint8_t *off, int64_t v) {314if (!isInt<21>(v))315error("relocation out of range");316or32(off, (v & 0x001FFFFC) << 3);317}
318
319static void applyArm64Branch14(uint8_t *off, int64_t v) {320if (!isInt<16>(v))321error("relocation out of range");322or32(off, (v & 0x0000FFFC) << 3);323}
324
325void SectionChunk::applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os,326uint64_t s, uint64_t p,327uint64_t imageBase) const {328switch (type) {329case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(off, s, p, 12); break;330case IMAGE_REL_ARM64_REL21: applyArm64Addr(off, s, p, 0); break;331case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(off, s & 0xfff, 0); break;332case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(off, s & 0xfff); break;333case IMAGE_REL_ARM64_BRANCH26: applyArm64Branch26(off, s - p); break;334case IMAGE_REL_ARM64_BRANCH19: applyArm64Branch19(off, s - p); break;335case IMAGE_REL_ARM64_BRANCH14: applyArm64Branch14(off, s - p); break;336case IMAGE_REL_ARM64_ADDR32:337add32(off, s + imageBase);338break;339case IMAGE_REL_ARM64_ADDR32NB: add32(off, s); break;340case IMAGE_REL_ARM64_ADDR64:341add64(off, s + imageBase);342break;343case IMAGE_REL_ARM64_SECREL: applySecRel(this, off, os, s); break;344case IMAGE_REL_ARM64_SECREL_LOW12A: applySecRelLow12A(this, off, os, s); break;345case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(this, off, os, s); break;346case IMAGE_REL_ARM64_SECREL_LOW12L: applySecRelLdr(this, off, os, s); break;347case IMAGE_REL_ARM64_SECTION:348applySecIdx(off, os, file->ctx.outputSections.size());349break;350case IMAGE_REL_ARM64_REL32: add32(off, s - p - 4); break;351default:352error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +353toString(file));354}355}
356
357static void maybeReportRelocationToDiscarded(const SectionChunk *fromChunk,358Defined *sym,359const coff_relocation &rel,360bool isMinGW) {361// Don't report these errors when the relocation comes from a debug info362// section or in mingw mode. MinGW mode object files (built by GCC) can363// have leftover sections with relocations against discarded comdat364// sections. Such sections are left as is, with relocations untouched.365if (fromChunk->isCodeView() || fromChunk->isDWARF() || isMinGW)366return;367
368// Get the name of the symbol. If it's null, it was discarded early, so we369// have to go back to the object file.370ObjFile *file = fromChunk->file;371StringRef name;372if (sym) {373name = sym->getName();374} else {375COFFSymbolRef coffSym =376check(file->getCOFFObj()->getSymbol(rel.SymbolTableIndex));377name = check(file->getCOFFObj()->getSymbolName(coffSym));378}379
380std::vector<std::string> symbolLocations =381getSymbolLocations(file, rel.SymbolTableIndex);382
383std::string out;384llvm::raw_string_ostream os(out);385os << "relocation against symbol in discarded section: " + name;386for (const std::string &s : symbolLocations)387os << s;388error(os.str());389}
390
391void SectionChunk::writeTo(uint8_t *buf) const {392if (!hasData)393return;394// Copy section contents from source object file to output file.395ArrayRef<uint8_t> a = getContents();396if (!a.empty())397memcpy(buf, a.data(), a.size());398
399// Apply relocations.400size_t inputSize = getSize();401for (const coff_relocation &rel : getRelocs()) {402// Check for an invalid relocation offset. This check isn't perfect, because403// we don't have the relocation size, which is only known after checking the404// machine and relocation type. As a result, a relocation may overwrite the405// beginning of the following input section.406if (rel.VirtualAddress >= inputSize) {407error("relocation points beyond the end of its parent section");408continue;409}410
411applyRelocation(buf + rel.VirtualAddress, rel);412}413
414// Write the offset to EC entry thunk preceding section contents. The low bit415// is always set, so it's effectively an offset from the last byte of the416// offset.417if (Defined *entryThunk = getEntryThunk())418write32le(buf - sizeof(uint32_t), entryThunk->getRVA() - rva + 1);419}
420
421void SectionChunk::applyRelocation(uint8_t *off,422const coff_relocation &rel) const {423auto *sym = dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));424
425// Get the output section of the symbol for this relocation. The output426// section is needed to compute SECREL and SECTION relocations used in debug427// info.428Chunk *c = sym ? sym->getChunk() : nullptr;429OutputSection *os = c ? file->ctx.getOutputSection(c) : nullptr;430
431// Skip the relocation if it refers to a discarded section, and diagnose it432// as an error if appropriate. If a symbol was discarded early, it may be433// null. If it was discarded late, the output section will be null, unless434// it was an absolute or synthetic symbol.435if (!sym ||436(!os && !isa<DefinedAbsolute>(sym) && !isa<DefinedSynthetic>(sym))) {437maybeReportRelocationToDiscarded(this, sym, rel, file->ctx.config.mingw);438return;439}440
441uint64_t s = sym->getRVA();442
443// Compute the RVA of the relocation for relative relocations.444uint64_t p = rva + rel.VirtualAddress;445uint64_t imageBase = file->ctx.config.imageBase;446switch (getArch()) {447case Triple::x86_64:448applyRelX64(off, rel.Type, os, s, p, imageBase);449break;450case Triple::x86:451applyRelX86(off, rel.Type, os, s, p, imageBase);452break;453case Triple::thumb:454applyRelARM(off, rel.Type, os, s, p, imageBase);455break;456case Triple::aarch64:457applyRelARM64(off, rel.Type, os, s, p, imageBase);458break;459default:460llvm_unreachable("unknown machine type");461}462}
463
464// Defend against unsorted relocations. This may be overly conservative.
465void SectionChunk::sortRelocations() {466auto cmpByVa = [](const coff_relocation &l, const coff_relocation &r) {467return l.VirtualAddress < r.VirtualAddress;468};469if (llvm::is_sorted(getRelocs(), cmpByVa))470return;471warn("some relocations in " + file->getName() + " are not sorted");472MutableArrayRef<coff_relocation> newRelocs(473bAlloc().Allocate<coff_relocation>(relocsSize), relocsSize);474memcpy(newRelocs.data(), relocsData, relocsSize * sizeof(coff_relocation));475llvm::sort(newRelocs, cmpByVa);476setRelocs(newRelocs);477}
478
479// Similar to writeTo, but suitable for relocating a subsection of the overall
480// section.
481void SectionChunk::writeAndRelocateSubsection(ArrayRef<uint8_t> sec,482ArrayRef<uint8_t> subsec,483uint32_t &nextRelocIndex,484uint8_t *buf) const {485assert(!subsec.empty() && !sec.empty());486assert(sec.begin() <= subsec.begin() && subsec.end() <= sec.end() &&487"subsection is not part of this section");488size_t vaBegin = std::distance(sec.begin(), subsec.begin());489size_t vaEnd = std::distance(sec.begin(), subsec.end());490memcpy(buf, subsec.data(), subsec.size());491for (; nextRelocIndex < relocsSize; ++nextRelocIndex) {492const coff_relocation &rel = relocsData[nextRelocIndex];493// Only apply relocations that apply to this subsection. These checks494// assume that all subsections completely contain their relocations.495// Relocations must not straddle the beginning or end of a subsection.496if (rel.VirtualAddress < vaBegin)497continue;498if (rel.VirtualAddress + 1 >= vaEnd)499break;500applyRelocation(&buf[rel.VirtualAddress - vaBegin], rel);501}502}
503
504void SectionChunk::addAssociative(SectionChunk *child) {505// Insert the child section into the list of associated children. Keep the506// list ordered by section name so that ICF does not depend on section order.507assert(child->assocChildren == nullptr &&508"associated sections cannot have their own associated children");509SectionChunk *prev = this;510SectionChunk *next = assocChildren;511for (; next != nullptr; prev = next, next = next->assocChildren) {512if (next->getSectionName() <= child->getSectionName())513break;514}515
516// Insert child between prev and next.517assert(prev->assocChildren == next);518prev->assocChildren = child;519child->assocChildren = next;520}
521
522static uint8_t getBaserelType(const coff_relocation &rel,523Triple::ArchType arch) {524switch (arch) {525case Triple::x86_64:526if (rel.Type == IMAGE_REL_AMD64_ADDR64)527return IMAGE_REL_BASED_DIR64;528if (rel.Type == IMAGE_REL_AMD64_ADDR32)529return IMAGE_REL_BASED_HIGHLOW;530return IMAGE_REL_BASED_ABSOLUTE;531case Triple::x86:532if (rel.Type == IMAGE_REL_I386_DIR32)533return IMAGE_REL_BASED_HIGHLOW;534return IMAGE_REL_BASED_ABSOLUTE;535case Triple::thumb:536if (rel.Type == IMAGE_REL_ARM_ADDR32)537return IMAGE_REL_BASED_HIGHLOW;538if (rel.Type == IMAGE_REL_ARM_MOV32T)539return IMAGE_REL_BASED_ARM_MOV32T;540return IMAGE_REL_BASED_ABSOLUTE;541case Triple::aarch64:542if (rel.Type == IMAGE_REL_ARM64_ADDR64)543return IMAGE_REL_BASED_DIR64;544return IMAGE_REL_BASED_ABSOLUTE;545default:546llvm_unreachable("unknown machine type");547}548}
549
550// Windows-specific.
551// Collect all locations that contain absolute addresses, which need to be
552// fixed by the loader if load-time relocation is needed.
553// Only called when base relocation is enabled.
554void SectionChunk::getBaserels(std::vector<Baserel> *res) {555for (const coff_relocation &rel : getRelocs()) {556uint8_t ty = getBaserelType(rel, getArch());557if (ty == IMAGE_REL_BASED_ABSOLUTE)558continue;559Symbol *target = file->getSymbol(rel.SymbolTableIndex);560if (!target || isa<DefinedAbsolute>(target))561continue;562res->emplace_back(rva + rel.VirtualAddress, ty);563}564}
565
566// MinGW specific.
567// Check whether a static relocation of type Type can be deferred and
568// handled at runtime as a pseudo relocation (for references to a module
569// local variable, which turned out to actually need to be imported from
570// another DLL) This returns the size the relocation is supposed to update,
571// in bits, or 0 if the relocation cannot be handled as a runtime pseudo
572// relocation.
573static int getRuntimePseudoRelocSize(uint16_t type,574llvm::COFF::MachineTypes machine) {575// Relocations that either contain an absolute address, or a plain576// relative offset, since the runtime pseudo reloc implementation577// adds 8/16/32/64 bit values to a memory address.578//579// Given a pseudo relocation entry,580//581// typedef struct {582// DWORD sym;583// DWORD target;584// DWORD flags;585// } runtime_pseudo_reloc_item_v2;586//587// the runtime relocation performs this adjustment:588// *(base + .target) += *(base + .sym) - (base + .sym)589//590// This works for both absolute addresses (IMAGE_REL_*_ADDR32/64,591// IMAGE_REL_I386_DIR32, where the memory location initially contains592// the address of the IAT slot, and for relative addresses (IMAGE_REL*_REL32),593// where the memory location originally contains the relative offset to the594// IAT slot.595//596// This requires the target address to be writable, either directly out of597// the image, or temporarily changed at runtime with VirtualProtect.598// Since this only operates on direct address values, it doesn't work for599// ARM/ARM64 relocations, other than the plain ADDR32/ADDR64 relocations.600switch (machine) {601case AMD64:602switch (type) {603case IMAGE_REL_AMD64_ADDR64:604return 64;605case IMAGE_REL_AMD64_ADDR32:606case IMAGE_REL_AMD64_REL32:607case IMAGE_REL_AMD64_REL32_1:608case IMAGE_REL_AMD64_REL32_2:609case IMAGE_REL_AMD64_REL32_3:610case IMAGE_REL_AMD64_REL32_4:611case IMAGE_REL_AMD64_REL32_5:612return 32;613default:614return 0;615}616case I386:617switch (type) {618case IMAGE_REL_I386_DIR32:619case IMAGE_REL_I386_REL32:620return 32;621default:622return 0;623}624case ARMNT:625switch (type) {626case IMAGE_REL_ARM_ADDR32:627return 32;628default:629return 0;630}631case ARM64:632switch (type) {633case IMAGE_REL_ARM64_ADDR64:634return 64;635case IMAGE_REL_ARM64_ADDR32:636return 32;637default:638return 0;639}640default:641llvm_unreachable("unknown machine type");642}643}
644
645// MinGW specific.
646// Append information to the provided vector about all relocations that
647// need to be handled at runtime as runtime pseudo relocations (references
648// to a module local variable, which turned out to actually need to be
649// imported from another DLL).
650void SectionChunk::getRuntimePseudoRelocs(651std::vector<RuntimePseudoReloc> &res) {652for (const coff_relocation &rel : getRelocs()) {653auto *target =654dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));655if (!target || !target->isRuntimePseudoReloc)656continue;657// If the target doesn't have a chunk allocated, it may be a658// DefinedImportData symbol which ended up unnecessary after GC.659// Normally we wouldn't eliminate section chunks that are referenced, but660// references within DWARF sections don't count for keeping section chunks661// alive. Thus such dangling references in DWARF sections are expected.662if (!target->getChunk())663continue;664int sizeInBits =665getRuntimePseudoRelocSize(rel.Type, file->ctx.config.machine);666if (sizeInBits == 0) {667error("unable to automatically import from " + target->getName() +668" with relocation type " +669file->getCOFFObj()->getRelocationTypeName(rel.Type) + " in " +670toString(file));671continue;672}673int addressSizeInBits = file->ctx.config.is64() ? 64 : 32;674if (sizeInBits < addressSizeInBits) {675warn("runtime pseudo relocation in " + toString(file) + " against " +676"symbol " + target->getName() + " is too narrow (only " +677Twine(sizeInBits) + " bits wide); this can fail at runtime " +678"depending on memory layout");679}680// sizeInBits is used to initialize the Flags field; currently no681// other flags are defined.682res.emplace_back(target, this, rel.VirtualAddress, sizeInBits);683}684}
685
686bool SectionChunk::isCOMDAT() const {687return header->Characteristics & IMAGE_SCN_LNK_COMDAT;688}
689
690void SectionChunk::printDiscardedMessage() const {691// Removed by dead-stripping. If it's removed by ICF, ICF already692// printed out the name, so don't repeat that here.693if (sym && this == repl)694log("Discarded " + sym->getName());695}
696
697StringRef SectionChunk::getDebugName() const {698if (sym)699return sym->getName();700return "";701}
702
703ArrayRef<uint8_t> SectionChunk::getContents() const {704ArrayRef<uint8_t> a;705cantFail(file->getCOFFObj()->getSectionContents(header, a));706return a;707}
708
709ArrayRef<uint8_t> SectionChunk::consumeDebugMagic() {710assert(isCodeView());711return consumeDebugMagic(getContents(), getSectionName());712}
713
714ArrayRef<uint8_t> SectionChunk::consumeDebugMagic(ArrayRef<uint8_t> data,715StringRef sectionName) {716if (data.empty())717return {};718
719// First 4 bytes are section magic.720if (data.size() < 4)721fatal("the section is too short: " + sectionName);722
723if (!sectionName.starts_with(".debug$"))724fatal("invalid section: " + sectionName);725
726uint32_t magic = support::endian::read32le(data.data());727uint32_t expectedMagic = sectionName == ".debug$H"728? DEBUG_HASHES_SECTION_MAGIC729: DEBUG_SECTION_MAGIC;730if (magic != expectedMagic) {731warn("ignoring section " + sectionName + " with unrecognized magic 0x" +732utohexstr(magic));733return {};734}735return data.slice(4);736}
737
738SectionChunk *SectionChunk::findByName(ArrayRef<SectionChunk *> sections,739StringRef name) {740for (SectionChunk *c : sections)741if (c->getSectionName() == name)742return c;743return nullptr;744}
745
746void SectionChunk::replace(SectionChunk *other) {747p2Align = std::max(p2Align, other->p2Align);748other->repl = repl;749other->live = false;750}
751
752uint32_t SectionChunk::getSectionNumber() const {753DataRefImpl r;754r.p = reinterpret_cast<uintptr_t>(header);755SectionRef s(r, file->getCOFFObj());756return s.getIndex() + 1;757}
758
759CommonChunk::CommonChunk(const COFFSymbolRef s) : sym(s) {760// The value of a common symbol is its size. Align all common symbols smaller761// than 32 bytes naturally, i.e. round the size up to the next power of two.762// This is what MSVC link.exe does.763setAlignment(std::min(32U, uint32_t(PowerOf2Ceil(sym.getValue()))));764hasData = false;765}
766
767uint32_t CommonChunk::getOutputCharacteristics() const {768return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |769IMAGE_SCN_MEM_WRITE;770}
771
772void StringChunk::writeTo(uint8_t *buf) const {773memcpy(buf, str.data(), str.size());774buf[str.size()] = '\0';775}
776
777ImportThunkChunkX64::ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s)778: ImportThunkChunk(ctx, s) {779// Intel Optimization Manual says that all branch targets780// should be 16-byte aligned. MSVC linker does this too.781setAlignment(16);782}
783
784void ImportThunkChunkX64::writeTo(uint8_t *buf) const {785memcpy(buf, importThunkX86, sizeof(importThunkX86));786// The first two bytes is a JMP instruction. Fill its operand.787write32le(buf + 2, impSymbol->getRVA() - rva - getSize());788}
789
790void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *res) {791res->emplace_back(getRVA() + 2, ctx.config.machine);792}
793
794void ImportThunkChunkX86::writeTo(uint8_t *buf) const {795memcpy(buf, importThunkX86, sizeof(importThunkX86));796// The first two bytes is a JMP instruction. Fill its operand.797write32le(buf + 2, impSymbol->getRVA() + ctx.config.imageBase);798}
799
800void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *res) {801res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T);802}
803
804void ImportThunkChunkARM::writeTo(uint8_t *buf) const {805memcpy(buf, importThunkARM, sizeof(importThunkARM));806// Fix mov.w and mov.t operands.807applyMOV32T(buf, impSymbol->getRVA() + ctx.config.imageBase);808}
809
810void ImportThunkChunkARM64::writeTo(uint8_t *buf) const {811int64_t off = impSymbol->getRVA() & 0xfff;812memcpy(buf, importThunkARM64, sizeof(importThunkARM64));813applyArm64Addr(buf, impSymbol->getRVA(), rva, 12);814applyArm64Ldr(buf + 4, off);815}
816
817// A Thumb2, PIC, non-interworking range extension thunk.
818const uint8_t armThunk[] = {8190x40, 0xf2, 0x00, 0x0c, // P: movw ip,:lower16:S - (P + (L1-P) + 4)8200xc0, 0xf2, 0x00, 0x0c, // movt ip,:upper16:S - (P + (L1-P) + 4)8210xe7, 0x44, // L1: add pc, ip822};823
824size_t RangeExtensionThunkARM::getSize() const {825assert(ctx.config.machine == ARMNT);826(void)&ctx;827return sizeof(armThunk);828}
829
830void RangeExtensionThunkARM::writeTo(uint8_t *buf) const {831assert(ctx.config.machine == ARMNT);832uint64_t offset = target->getRVA() - rva - 12;833memcpy(buf, armThunk, sizeof(armThunk));834applyMOV32T(buf, uint32_t(offset));835}
836
837// A position independent ARM64 adrp+add thunk, with a maximum range of
838// +/- 4 GB, which is enough for any PE-COFF.
839const uint8_t arm64Thunk[] = {8400x10, 0x00, 0x00, 0x90, // adrp x16, Dest8410x10, 0x02, 0x00, 0x91, // add x16, x16, :lo12:Dest8420x00, 0x02, 0x1f, 0xd6, // br x16843};844
845size_t RangeExtensionThunkARM64::getSize() const {846assert(ctx.config.machine == ARM64);847(void)&ctx;848return sizeof(arm64Thunk);849}
850
851void RangeExtensionThunkARM64::writeTo(uint8_t *buf) const {852assert(ctx.config.machine == ARM64);853memcpy(buf, arm64Thunk, sizeof(arm64Thunk));854applyArm64Addr(buf + 0, target->getRVA(), rva, 12);855applyArm64Imm(buf + 4, target->getRVA() & 0xfff, 0);856}
857
858LocalImportChunk::LocalImportChunk(COFFLinkerContext &c, Defined *s)859: sym(s), ctx(c) {860setAlignment(ctx.config.wordsize);861}
862
863void LocalImportChunk::getBaserels(std::vector<Baserel> *res) {864res->emplace_back(getRVA(), ctx.config.machine);865}
866
867size_t LocalImportChunk::getSize() const { return ctx.config.wordsize; }868
869void LocalImportChunk::writeTo(uint8_t *buf) const {870if (ctx.config.is64()) {871write64le(buf, sym->getRVA() + ctx.config.imageBase);872} else {873write32le(buf, sym->getRVA() + ctx.config.imageBase);874}875}
876
877void RVATableChunk::writeTo(uint8_t *buf) const {878ulittle32_t *begin = reinterpret_cast<ulittle32_t *>(buf);879size_t cnt = 0;880for (const ChunkAndOffset &co : syms)881begin[cnt++] = co.inputChunk->getRVA() + co.offset;882llvm::sort(begin, begin + cnt);883assert(std::unique(begin, begin + cnt) == begin + cnt &&884"RVA tables should be de-duplicated");885}
886
887void RVAFlagTableChunk::writeTo(uint8_t *buf) const {888struct RVAFlag {889ulittle32_t rva;890uint8_t flag;891};892auto flags =893MutableArrayRef(reinterpret_cast<RVAFlag *>(buf), syms.size());894for (auto t : zip(syms, flags)) {895const auto &sym = std::get<0>(t);896auto &flag = std::get<1>(t);897flag.rva = sym.inputChunk->getRVA() + sym.offset;898flag.flag = 0;899}900llvm::sort(flags,901[](const RVAFlag &a, const RVAFlag &b) { return a.rva < b.rva; });902assert(llvm::unique(flags, [](const RVAFlag &a,903const RVAFlag &b) { return a.rva == b.rva; }) ==904flags.end() &&905"RVA tables should be de-duplicated");906}
907
908size_t ECCodeMapChunk::getSize() const {909return map.size() * sizeof(chpe_range_entry);910}
911
912void ECCodeMapChunk::writeTo(uint8_t *buf) const {913auto table = reinterpret_cast<chpe_range_entry *>(buf);914for (uint32_t i = 0; i < map.size(); i++) {915const ECCodeMapEntry &entry = map[i];916uint32_t start = entry.first->getRVA();917table[i].StartOffset = start | entry.type;918table[i].Length = entry.last->getRVA() + entry.last->getSize() - start;919}920}
921
922// MinGW specific, for the "automatic import of variables from DLLs" feature.
923size_t PseudoRelocTableChunk::getSize() const {924if (relocs.empty())925return 0;926return 12 + 12 * relocs.size();927}
928
929// MinGW specific.
930void PseudoRelocTableChunk::writeTo(uint8_t *buf) const {931if (relocs.empty())932return;933
934ulittle32_t *table = reinterpret_cast<ulittle32_t *>(buf);935// This is the list header, to signal the runtime pseudo relocation v2936// format.937table[0] = 0;938table[1] = 0;939table[2] = 1;940
941size_t idx = 3;942for (const RuntimePseudoReloc &rpr : relocs) {943table[idx + 0] = rpr.sym->getRVA();944table[idx + 1] = rpr.target->getRVA() + rpr.targetOffset;945table[idx + 2] = rpr.flags;946idx += 3;947}948}
949
950// Windows-specific. This class represents a block in .reloc section.
951// The format is described here.
952//
953// On Windows, each DLL is linked against a fixed base address and
954// usually loaded to that address. However, if there's already another
955// DLL that overlaps, the loader has to relocate it. To do that, DLLs
956// contain .reloc sections which contain offsets that need to be fixed
957// up at runtime. If the loader finds that a DLL cannot be loaded to its
958// desired base address, it loads it to somewhere else, and add <actual
959// base address> - <desired base address> to each offset that is
960// specified by the .reloc section. In ELF terms, .reloc sections
961// contain relative relocations in REL format (as opposed to RELA.)
962//
963// This already significantly reduces the size of relocations compared
964// to ELF .rel.dyn, but Windows does more to reduce it (probably because
965// it was invented for PCs in the late '80s or early '90s.) Offsets in
966// .reloc are grouped by page where the page size is 12 bits, and
967// offsets sharing the same page address are stored consecutively to
968// represent them with less space. This is very similar to the page
969// table which is grouped by (multiple stages of) pages.
970//
971// For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,
972// 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4
973// bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they
974// are represented like this:
975//
976// 0x00000 -- page address (4 bytes)
977// 16 -- size of this block (4 bytes)
978// 0xA030 -- entries (2 bytes each)
979// 0xA500
980// 0xA700
981// 0xAA00
982// 0x20000 -- page address (4 bytes)
983// 12 -- size of this block (4 bytes)
984// 0xA004 -- entries (2 bytes each)
985// 0xA008
986//
987// Usually we have a lot of relocations for each page, so the number of
988// bytes for one .reloc entry is close to 2 bytes on average.
989BaserelChunk::BaserelChunk(uint32_t page, Baserel *begin, Baserel *end) {990// Block header consists of 4 byte page RVA and 4 byte block size.991// Each entry is 2 byte. Last entry may be padding.992data.resize(alignTo((end - begin) * 2 + 8, 4));993uint8_t *p = data.data();994write32le(p, page);995write32le(p + 4, data.size());996p += 8;997for (Baserel *i = begin; i != end; ++i) {998write16le(p, (i->type << 12) | (i->rva - page));999p += 2;1000}1001}
1002
1003void BaserelChunk::writeTo(uint8_t *buf) const {1004memcpy(buf, data.data(), data.size());1005}
1006
1007uint8_t Baserel::getDefaultType(llvm::COFF::MachineTypes machine) {1008switch (machine) {1009case AMD64:1010case ARM64:1011return IMAGE_REL_BASED_DIR64;1012case I386:1013case ARMNT:1014return IMAGE_REL_BASED_HIGHLOW;1015default:1016llvm_unreachable("unknown machine type");1017}1018}
1019
1020MergeChunk::MergeChunk(uint32_t alignment)1021: builder(StringTableBuilder::RAW, llvm::Align(alignment)) {1022setAlignment(alignment);1023}
1024
1025void MergeChunk::addSection(COFFLinkerContext &ctx, SectionChunk *c) {1026assert(isPowerOf2_32(c->getAlignment()));1027uint8_t p2Align = llvm::Log2_32(c->getAlignment());1028assert(p2Align < std::size(ctx.mergeChunkInstances));1029auto *&mc = ctx.mergeChunkInstances[p2Align];1030if (!mc)1031mc = make<MergeChunk>(c->getAlignment());1032mc->sections.push_back(c);1033}
1034
1035void MergeChunk::finalizeContents() {1036assert(!finalized && "should only finalize once");1037for (SectionChunk *c : sections)1038if (c->live)1039builder.add(toStringRef(c->getContents()));1040builder.finalize();1041finalized = true;1042}
1043
1044void MergeChunk::assignSubsectionRVAs() {1045for (SectionChunk *c : sections) {1046if (!c->live)1047continue;1048size_t off = builder.getOffset(toStringRef(c->getContents()));1049c->setRVA(rva + off);1050}1051}
1052
1053uint32_t MergeChunk::getOutputCharacteristics() const {1054return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;1055}
1056
1057size_t MergeChunk::getSize() const {1058return builder.getSize();1059}
1060
1061void MergeChunk::writeTo(uint8_t *buf) const {1062builder.write(buf);1063}
1064
1065// MinGW specific.
1066size_t AbsolutePointerChunk::getSize() const { return ctx.config.wordsize; }1067
1068void AbsolutePointerChunk::writeTo(uint8_t *buf) const {1069if (ctx.config.is64()) {1070write64le(buf, value);1071} else {1072write32le(buf, value);1073}1074}
1075
1076} // namespace lld::coff1077