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;
29using namespace llvm::support::endian;
30using namespace llvm::COFF;
31using llvm::support::ulittle32_t;
32
33namespace lld::coff {
34
35SectionChunk::SectionChunk(ObjFile *f, const coff_section *h, Kind k)
36 : Chunk(k), file(f), header(h), repl(this) {
37 // Initialize relocs.
38 if (file)
39 setRelocs(file->getCOFFObj()->getRelocations(Sec: header));
40
41 // Initialize sectionName.
42 StringRef sectionName;
43 if (file) {
44 if (Expected<StringRef> e = file->getCOFFObj()->getSectionName(Sec: header))
45 sectionName = *e;
46 }
47 sectionNameData = sectionName.data();
48 sectionNameSize = sectionName.size();
49
50 setAlignment(header->getAlignment());
51
52 hasData = !(header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
53
54 // If linker GC is disabled, every chunk starts out alive. If linker GC is
55 // enabled, treat non-comdat sections as roots. Generally optimized object
56 // files will be built with -ffunction-sections or /Gy, so most things worth
57 // stripping will be in a comdat.
58 if (file)
59 live = !file->symtab.ctx.config.doGC || !isCOMDAT();
60 else
61 live = true;
62}
63
64MachineTypes SectionChunk::getMachine() const {
65 MachineTypes machine = file->getMachineType();
66 // On ARM64EC, the IMAGE_SCN_GPREL flag is repurposed to indicate that section
67 // code is x86_64. This enables embedding x86_64 code within ARM64EC object
68 // files. MSVC uses this for export thunks in .exp files.
69 if (isArm64EC(Machine: machine) && (header->Characteristics & IMAGE_SCN_GPREL))
70 machine = AMD64;
71 return machine;
72}
73
74// SectionChunk is one of the most frequently allocated classes, so it is
75// important to keep it as compact as possible. As of this writing, the number
76// below is the size of this class on x64 platforms.
77static_assert(sizeof(SectionChunk) <= 88, "SectionChunk grew unexpectedly");
78
79static void add16(uint8_t *p, int16_t v) { write16le(P: p, V: read16le(P: p) + v); }
80static void add32(uint8_t *p, int32_t v) { write32le(P: p, V: read32le(P: p) + v); }
81static void add64(uint8_t *p, int64_t v) { write64le(P: p, V: read64le(P: p) + v); }
82static void or16(uint8_t *p, uint16_t v) { write16le(P: p, V: read16le(P: p) | v); }
83static void or32(uint8_t *p, uint32_t v) { write32le(P: p, V: read32le(P: p) | v); }
84
85// Verify that given sections are appropriate targets for SECREL
86// relocations. This check is relaxed because unfortunately debug
87// sections have section-relative relocations against absolute symbols.
88static bool checkSecRel(const SectionChunk *sec, OutputSection *os) {
89 if (os)
90 return true;
91 if (sec->isCodeView())
92 return false;
93 error(msg: "SECREL relocation cannot be applied to absolute symbols");
94 return false;
95}
96
97static void applySecRel(const SectionChunk *sec, uint8_t *off,
98 OutputSection *os, uint64_t s) {
99 if (!checkSecRel(sec, os))
100 return;
101 uint64_t secRel = s - os->getRVA();
102 if (secRel > UINT32_MAX) {
103 error(msg: "overflow in SECREL relocation in section: " + sec->getSectionName());
104 return;
105 }
106 add32(p: off, v: secRel);
107}
108
109static void applySecIdx(uint8_t *off, OutputSection *os,
110 unsigned numOutputSections) {
111 // numOutputSections is the largest valid section index. Make sure that
112 // it fits in 16 bits.
113 assert(numOutputSections <= 0xffff && "size of outputSections is too big");
114
115 // Absolute symbol doesn't have section index, but section index relocation
116 // against absolute symbol should be resolved to one plus the last output
117 // section index. This is required for compatibility with MSVC.
118 if (os)
119 add16(p: off, v: os->sectionIndex);
120 else
121 add16(p: off, v: numOutputSections + 1);
122}
123
124void SectionChunk::applyRelX64(uint8_t *off, uint16_t type, OutputSection *os,
125 uint64_t s, uint64_t p,
126 uint64_t imageBase) const {
127 switch (type) {
128 case IMAGE_REL_AMD64_ADDR32:
129 add32(p: off, v: s + imageBase);
130 break;
131 case IMAGE_REL_AMD64_ADDR64:
132 add64(p: off, v: s + imageBase);
133 break;
134 case IMAGE_REL_AMD64_ADDR32NB: add32(p: off, v: s); break;
135 case IMAGE_REL_AMD64_REL32: add32(p: off, v: s - p - 4); break;
136 case IMAGE_REL_AMD64_REL32_1: add32(p: off, v: s - p - 5); break;
137 case IMAGE_REL_AMD64_REL32_2: add32(p: off, v: s - p - 6); break;
138 case IMAGE_REL_AMD64_REL32_3: add32(p: off, v: s - p - 7); break;
139 case IMAGE_REL_AMD64_REL32_4: add32(p: off, v: s - p - 8); break;
140 case IMAGE_REL_AMD64_REL32_5: add32(p: off, v: s - p - 9); break;
141 case IMAGE_REL_AMD64_SECTION:
142 applySecIdx(off, os, numOutputSections: file->symtab.ctx.outputSections.size());
143 break;
144 case IMAGE_REL_AMD64_SECREL: applySecRel(sec: this, off, os, s); break;
145 default:
146 error(msg: "unsupported relocation type 0x" + Twine::utohexstr(Val: type) + " in " +
147 toString(file));
148 }
149}
150
151void SectionChunk::applyRelX86(uint8_t *off, uint16_t type, OutputSection *os,
152 uint64_t s, uint64_t p,
153 uint64_t imageBase) const {
154 switch (type) {
155 case IMAGE_REL_I386_ABSOLUTE: break;
156 case IMAGE_REL_I386_DIR32:
157 add32(p: off, v: s + imageBase);
158 break;
159 case IMAGE_REL_I386_DIR32NB: add32(p: off, v: s); break;
160 case IMAGE_REL_I386_REL32: add32(p: off, v: s - p - 4); break;
161 case IMAGE_REL_I386_SECTION:
162 applySecIdx(off, os, numOutputSections: file->symtab.ctx.outputSections.size());
163 break;
164 case IMAGE_REL_I386_SECREL: applySecRel(sec: this, off, os, s); break;
165 default:
166 error(msg: "unsupported relocation type 0x" + Twine::utohexstr(Val: type) + " in " +
167 toString(file));
168 }
169}
170
171static void applyMOV(uint8_t *off, uint16_t v) {
172 write16le(P: off, V: (read16le(P: off) & 0xfbf0) | ((v & 0x800) >> 1) | ((v >> 12) & 0xf));
173 write16le(P: off + 2, V: (read16le(P: off + 2) & 0x8f00) | ((v & 0x700) << 4) | (v & 0xff));
174}
175
176static uint16_t readMOV(uint8_t *off, bool movt) {
177 uint16_t op1 = read16le(P: off);
178 if ((op1 & 0xfbf0) != (movt ? 0xf2c0 : 0xf240))
179 error(msg: "unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +
180 " instruction in MOV32T relocation");
181 uint16_t op2 = read16le(P: off + 2);
182 if ((op2 & 0x8000) != 0)
183 error(msg: "unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +
184 " instruction in MOV32T relocation");
185 return (op2 & 0x00ff) | ((op2 >> 4) & 0x0700) | ((op1 << 1) & 0x0800) |
186 ((op1 & 0x000f) << 12);
187}
188
189void applyMOV32T(uint8_t *off, uint32_t v) {
190 uint16_t immW = readMOV(off, movt: false); // read MOVW operand
191 uint16_t immT = readMOV(off: off + 4, movt: true); // read MOVT operand
192 uint32_t imm = immW | (immT << 16);
193 v += imm; // add the immediate offset
194 applyMOV(off, v); // set MOVW operand
195 applyMOV(off: off + 4, v: v >> 16); // set MOVT operand
196}
197
198static void applyBranch20T(uint8_t *off, int32_t v) {
199 if (!isInt<21>(x: v))
200 error(msg: "relocation out of range");
201 uint32_t s = v < 0 ? 1 : 0;
202 uint32_t j1 = (v >> 19) & 1;
203 uint32_t j2 = (v >> 18) & 1;
204 or16(p: off, v: (s << 10) | ((v >> 12) & 0x3f));
205 or16(p: off + 2, v: (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));
206}
207
208void applyBranch24T(uint8_t *off, int32_t v) {
209 if (!isInt<25>(x: v))
210 error(msg: "relocation out of range");
211 uint32_t s = v < 0 ? 1 : 0;
212 uint32_t j1 = ((~v >> 23) & 1) ^ s;
213 uint32_t j2 = ((~v >> 22) & 1) ^ s;
214 or16(p: off, v: (s << 10) | ((v >> 12) & 0x3ff));
215 // Clear out the J1 and J2 bits which may be set.
216 write16le(P: off + 2, V: (read16le(P: off + 2) & 0xd000) | (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));
217}
218
219void SectionChunk::applyRelARM(uint8_t *off, uint16_t type, OutputSection *os,
220 uint64_t s, uint64_t p,
221 uint64_t imageBase) const {
222 // Pointer to thumb code must have the LSB set.
223 uint64_t sx = s;
224 if (os && (os->header.Characteristics & IMAGE_SCN_MEM_EXECUTE))
225 sx |= 1;
226 switch (type) {
227 case IMAGE_REL_ARM_ADDR32:
228 add32(p: off, v: sx + imageBase);
229 break;
230 case IMAGE_REL_ARM_ADDR32NB: add32(p: off, v: sx); break;
231 case IMAGE_REL_ARM_MOV32T:
232 applyMOV32T(off, v: sx + imageBase);
233 break;
234 case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(off, v: sx - p - 4); break;
235 case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(off, v: sx - p - 4); break;
236 case IMAGE_REL_ARM_BLX23T: applyBranch24T(off, v: sx - p - 4); break;
237 case IMAGE_REL_ARM_SECTION:
238 applySecIdx(off, os, numOutputSections: file->symtab.ctx.outputSections.size());
239 break;
240 case IMAGE_REL_ARM_SECREL: applySecRel(sec: this, off, os, s); break;
241 case IMAGE_REL_ARM_REL32: add32(p: off, v: sx - p - 4); break;
242 default:
243 error(msg: "unsupported relocation type 0x" + Twine::utohexstr(Val: type) + " in " +
244 toString(file));
245 }
246}
247
248// Interpret the existing immediate value as a byte offset to the
249// target symbol, then update the instruction with the immediate as
250// the page offset from the current instruction to the target.
251void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift) {
252 uint32_t orig = read32le(P: off);
253 int64_t imm =
254 SignExtend64<21>(x: ((orig >> 29) & 0x3) | ((orig >> 3) & 0x1FFFFC));
255 s += imm;
256 imm = (s >> shift) - (p >> shift);
257 uint32_t immLo = (imm & 0x3) << 29;
258 uint32_t immHi = (imm & 0x1FFFFC) << 3;
259 uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);
260 write32le(P: off, V: (orig & ~mask) | immLo | immHi);
261}
262
263// Update the immediate field in a AARCH64 ldr, str, and add instruction.
264// Optionally limit the range of the written immediate by one or more bits
265// (rangeLimit).
266void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit) {
267 uint32_t orig = read32le(P: off);
268 imm += (orig >> 10) & 0xFFF;
269 orig &= ~(0xFFF << 10);
270 write32le(P: off, V: orig | ((imm & (0xFFF >> rangeLimit)) << 10));
271}
272
273// Add the 12 bit page offset to the existing immediate.
274// Ldr/str instructions store the opcode immediate scaled
275// by the load/store size (giving a larger range for larger
276// loads/stores). The immediate is always (both before and after
277// fixing up the relocation) stored scaled similarly.
278// Even if larger loads/stores have a larger range, limit the
279// effective offset to 12 bit, since it is intended to be a
280// page offset.
281static void applyArm64Ldr(uint8_t *off, uint64_t imm) {
282 uint32_t orig = read32le(P: off);
283 uint32_t size = orig >> 30;
284 // 0x04000000 indicates SIMD/FP registers
285 // 0x00800000 indicates 128 bit
286 if ((orig & 0x4800000) == 0x4800000)
287 size += 4;
288 if ((imm & ((1 << size) - 1)) != 0)
289 error(msg: "misaligned ldr/str offset");
290 applyArm64Imm(off, imm: imm >> size, rangeLimit: size);
291}
292
293static void applySecRelLow12A(const SectionChunk *sec, uint8_t *off,
294 OutputSection *os, uint64_t s) {
295 if (checkSecRel(sec, os))
296 applyArm64Imm(off, imm: (s - os->getRVA()) & 0xfff, rangeLimit: 0);
297}
298
299static void applySecRelHigh12A(const SectionChunk *sec, uint8_t *off,
300 OutputSection *os, uint64_t s) {
301 if (!checkSecRel(sec, os))
302 return;
303 uint32_t orig = read32le(P: off);
304 uint64_t imm = (orig >> 10) & 0xFFF;
305 orig &= ~(0xFFF << 10);
306 imm = (s + imm - os->getRVA()) >> 12;
307 if (0xfff < imm) {
308 error(msg: "overflow in SECREL_HIGH12A relocation in section: " +
309 sec->getSectionName());
310 return;
311 }
312 write32le(P: off, V: orig | (imm << 10));
313}
314
315static void applySecRelLdr(const SectionChunk *sec, uint8_t *off,
316 OutputSection *os, uint64_t s) {
317 if (checkSecRel(sec, os))
318 applyArm64Ldr(off, imm: (s - os->getRVA()) & 0xfff);
319}
320
321void applyArm64Branch26(uint8_t *off, int64_t v) {
322 if (!isInt<28>(x: v))
323 error(msg: "relocation out of range");
324 or32(p: off, v: (v & 0x0FFFFFFC) >> 2);
325}
326
327static void applyArm64Branch19(uint8_t *off, int64_t v) {
328 if (!isInt<21>(x: v))
329 error(msg: "relocation out of range");
330 or32(p: off, v: (v & 0x001FFFFC) << 3);
331}
332
333static void applyArm64Branch14(uint8_t *off, int64_t v) {
334 if (!isInt<16>(x: v))
335 error(msg: "relocation out of range");
336 or32(p: off, v: (v & 0x0000FFFC) << 3);
337}
338
339void SectionChunk::applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os,
340 uint64_t s, uint64_t p,
341 uint64_t imageBase) const {
342 switch (type) {
343 case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(off, s, p, shift: 12); break;
344 case IMAGE_REL_ARM64_REL21: applyArm64Addr(off, s, p, shift: 0); break;
345 case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(off, imm: s & 0xfff, rangeLimit: 0); break;
346 case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(off, imm: s & 0xfff); break;
347 case IMAGE_REL_ARM64_BRANCH26: applyArm64Branch26(off, v: s - p); break;
348 case IMAGE_REL_ARM64_BRANCH19: applyArm64Branch19(off, v: s - p); break;
349 case IMAGE_REL_ARM64_BRANCH14: applyArm64Branch14(off, v: s - p); break;
350 case IMAGE_REL_ARM64_ADDR32:
351 add32(p: off, v: s + imageBase);
352 break;
353 case IMAGE_REL_ARM64_ADDR32NB: add32(p: off, v: s); break;
354 case IMAGE_REL_ARM64_ADDR64:
355 add64(p: off, v: s + imageBase);
356 break;
357 case IMAGE_REL_ARM64_SECREL: applySecRel(sec: this, off, os, s); break;
358 case IMAGE_REL_ARM64_SECREL_LOW12A: applySecRelLow12A(sec: this, off, os, s); break;
359 case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(sec: this, off, os, s); break;
360 case IMAGE_REL_ARM64_SECREL_LOW12L: applySecRelLdr(sec: this, off, os, s); break;
361 case IMAGE_REL_ARM64_SECTION:
362 applySecIdx(off, os, numOutputSections: file->symtab.ctx.outputSections.size());
363 break;
364 case IMAGE_REL_ARM64_REL32: add32(p: off, v: s - p - 4); break;
365 default:
366 error(msg: "unsupported relocation type 0x" + Twine::utohexstr(Val: type) + " in " +
367 toString(file));
368 }
369}
370
371static void applyMipsBranch(uint8_t *off, int64_t v) {
372 if (v & 3)
373 error(msg: "misaligned jmp offset");
374 add32(p: off, v: (v >> 2) & 0x03FFFFFC);
375}
376
377void SectionChunk::applyRelMIPS(uint8_t *off, uint16_t type, OutputSection *os,
378 uint64_t s, uint64_t p,
379 uint64_t imageBase) const {
380 switch (type) {
381 case IMAGE_REL_MIPS_REFWORD:
382 add32(p: off, v: s + imageBase);
383 break;
384 case IMAGE_REL_MIPS_JMPADDR:
385 applyMipsBranch(off, v: s + imageBase);
386 break;
387 case IMAGE_REL_MIPS_REFHI:
388 add16(p: off, v: (s + imageBase) >> 16);
389 break;
390 case IMAGE_REL_MIPS_REFLO:
391 add16(p: off, v: s + imageBase);
392 break;
393 case IMAGE_REL_MIPS_PAIR:
394 // Nothing to do
395 break;
396 case IMAGE_REL_MIPS_REFWORDNB:
397 add32(p: off, v: s);
398 break;
399 case IMAGE_REL_MIPS_SECTION:
400 applySecIdx(off, os, numOutputSections: file->symtab.ctx.outputSections.size());
401 break;
402 case IMAGE_REL_MIPS_SECREL:
403 applySecRel(sec: this, off, os, s);
404 break;
405 default:
406 error(msg: "unsupported relocation type 0x" + Twine::utohexstr(Val: type) + " in " +
407 toString(file));
408 }
409}
410
411static void maybeReportRelocationToDiscarded(const SectionChunk *fromChunk,
412 Defined *sym,
413 const coff_relocation &rel,
414 bool isMinGW) {
415 // Don't report these errors when the relocation comes from a debug info
416 // section or in mingw mode. MinGW mode object files (built by GCC) can
417 // have leftover sections with relocations against discarded comdat
418 // sections. Such sections are left as is, with relocations untouched.
419 if (fromChunk->isCodeView() || fromChunk->isDWARF() || isMinGW)
420 return;
421
422 // Get the name of the symbol. If it's null, it was discarded early, so we
423 // have to go back to the object file.
424 ObjFile *file = fromChunk->file;
425 std::string name;
426 if (sym) {
427 name = toString(ctx: file->symtab.ctx, b&: *sym);
428 } else {
429 COFFSymbolRef coffSym =
430 check(e: file->getCOFFObj()->getSymbol(index: rel.SymbolTableIndex));
431 name = maybeDemangleSymbol(
432 ctx: file->symtab.ctx, symName: check(e: file->getCOFFObj()->getSymbolName(Symbol: coffSym)));
433 }
434
435 std::vector<std::string> symbolLocations =
436 getSymbolLocations(file, symIndex: rel.SymbolTableIndex);
437
438 std::string out;
439 llvm::raw_string_ostream os(out);
440 os << "relocation against symbol in discarded section: " + name;
441 for (const std::string &s : symbolLocations)
442 os << s;
443 error(msg: out);
444}
445
446void SectionChunk::writeTo(uint8_t *buf) const {
447 if (!hasData)
448 return;
449 // Copy section contents from source object file to output file.
450 ArrayRef<uint8_t> a = getContents();
451 if (!a.empty())
452 memcpy(dest: buf, src: a.data(), n: a.size());
453
454 // Apply relocations.
455 size_t inputSize = getSize();
456 for (const coff_relocation &rel : getRelocs()) {
457 // Check for an invalid relocation offset. This check isn't perfect, because
458 // we don't have the relocation size, which is only known after checking the
459 // machine and relocation type. As a result, a relocation may overwrite the
460 // beginning of the following input section.
461 if (rel.VirtualAddress >= inputSize) {
462 error(msg: "relocation points beyond the end of its parent section");
463 continue;
464 }
465
466 applyRelocation(off: buf + rel.VirtualAddress, rel);
467 }
468}
469
470void SectionChunk::applyRelocation(uint8_t *off,
471 const coff_relocation &rel) const {
472 auto *sym = dyn_cast_or_null<Defined>(Val: file->getSymbol(symbolIndex: rel.SymbolTableIndex));
473
474 // Get the output section of the symbol for this relocation. The output
475 // section is needed to compute SECREL and SECTION relocations used in debug
476 // info.
477 Chunk *c = sym ? sym->getChunk() : nullptr;
478 COFFLinkerContext &ctx = file->symtab.ctx;
479 OutputSection *os = c ? ctx.getOutputSection(c) : nullptr;
480
481 // Skip the relocation if it refers to a discarded section, and diagnose it
482 // as an error if appropriate. If a symbol was discarded early, it may be
483 // null. If it was discarded late, the output section will be null, unless
484 // it was an absolute or synthetic symbol.
485 if (!sym ||
486 (!os && !isa<DefinedAbsolute>(Val: sym) && !isa<DefinedSynthetic>(Val: sym))) {
487 maybeReportRelocationToDiscarded(fromChunk: this, sym, rel, isMinGW: ctx.config.mingw);
488 return;
489 }
490
491 uint64_t s = sym->getRVA();
492
493 // Compute the RVA of the relocation for relative relocations.
494 uint64_t p = rva + rel.VirtualAddress;
495 uint64_t imageBase = ctx.config.imageBase;
496 switch (getArch()) {
497 case Triple::x86_64:
498 applyRelX64(off, type: rel.Type, os, s, p, imageBase);
499 break;
500 case Triple::x86:
501 applyRelX86(off, type: rel.Type, os, s, p, imageBase);
502 break;
503 case Triple::thumb:
504 applyRelARM(off, type: rel.Type, os, s, p, imageBase);
505 break;
506 case Triple::aarch64:
507 applyRelARM64(off, type: rel.Type, os, s, p, imageBase);
508 break;
509 case Triple::mipsel:
510 applyRelMIPS(off, type: rel.Type, os, s, p, imageBase);
511 break;
512 default:
513 llvm_unreachable("unknown machine type");
514 }
515}
516
517// Defend against unsorted relocations. This may be overly conservative.
518void SectionChunk::sortRelocations() {
519 auto cmpByVa = [](const coff_relocation &l, const coff_relocation &r) {
520 return l.VirtualAddress < r.VirtualAddress;
521 };
522 if (llvm::is_sorted(Range: getRelocs(), C: cmpByVa))
523 return;
524 warn(msg: "some relocations in " + file->getName() + " are not sorted");
525 MutableArrayRef<coff_relocation> newRelocs(
526 bAlloc().Allocate<coff_relocation>(Num: relocsSize), relocsSize);
527 memcpy(dest: newRelocs.data(), src: relocsData, n: relocsSize * sizeof(coff_relocation));
528 llvm::sort(C&: newRelocs, Comp: cmpByVa);
529 setRelocs(newRelocs);
530}
531
532// Similar to writeTo, but suitable for relocating a subsection of the overall
533// section.
534void SectionChunk::writeAndRelocateSubsection(ArrayRef<uint8_t> sec,
535 ArrayRef<uint8_t> subsec,
536 uint32_t &nextRelocIndex,
537 uint8_t *buf) const {
538 assert(!subsec.empty() && !sec.empty());
539 assert(sec.begin() <= subsec.begin() && subsec.end() <= sec.end() &&
540 "subsection is not part of this section");
541 size_t vaBegin = std::distance(first: sec.begin(), last: subsec.begin());
542 size_t vaEnd = std::distance(first: sec.begin(), last: subsec.end());
543 memcpy(dest: buf, src: subsec.data(), n: subsec.size());
544 for (; nextRelocIndex < relocsSize; ++nextRelocIndex) {
545 const coff_relocation &rel = relocsData[nextRelocIndex];
546 // Only apply relocations that apply to this subsection. These checks
547 // assume that all subsections completely contain their relocations.
548 // Relocations must not straddle the beginning or end of a subsection.
549 if (rel.VirtualAddress < vaBegin)
550 continue;
551 if (rel.VirtualAddress + 1 >= vaEnd)
552 break;
553 applyRelocation(off: &buf[rel.VirtualAddress - vaBegin], rel);
554 }
555}
556
557void SectionChunk::addAssociative(SectionChunk *child) {
558 // Insert the child section into the list of associated children. Keep the
559 // list ordered by section name so that ICF does not depend on section order.
560 assert(child->assocChildren == nullptr &&
561 "associated sections cannot have their own associated children");
562 SectionChunk *prev = this;
563 SectionChunk *next = assocChildren;
564 for (; next != nullptr; prev = next, next = next->assocChildren) {
565 if (next->getSectionName() <= child->getSectionName())
566 break;
567 }
568
569 // Insert child between prev and next.
570 assert(prev->assocChildren == next);
571 prev->assocChildren = child;
572 child->assocChildren = next;
573}
574
575static uint8_t getBaserelType(const coff_relocation &rel,
576 Triple::ArchType arch) {
577 switch (arch) {
578 case Triple::x86_64:
579 if (rel.Type == IMAGE_REL_AMD64_ADDR64)
580 return IMAGE_REL_BASED_DIR64;
581 if (rel.Type == IMAGE_REL_AMD64_ADDR32)
582 return IMAGE_REL_BASED_HIGHLOW;
583 return IMAGE_REL_BASED_ABSOLUTE;
584 case Triple::x86:
585 if (rel.Type == IMAGE_REL_I386_DIR32)
586 return IMAGE_REL_BASED_HIGHLOW;
587 return IMAGE_REL_BASED_ABSOLUTE;
588 case Triple::thumb:
589 if (rel.Type == IMAGE_REL_ARM_ADDR32)
590 return IMAGE_REL_BASED_HIGHLOW;
591 if (rel.Type == IMAGE_REL_ARM_MOV32T)
592 return IMAGE_REL_BASED_ARM_MOV32T;
593 return IMAGE_REL_BASED_ABSOLUTE;
594 case Triple::aarch64:
595 if (rel.Type == IMAGE_REL_ARM64_ADDR64)
596 return IMAGE_REL_BASED_DIR64;
597 return IMAGE_REL_BASED_ABSOLUTE;
598 case Triple::mipsel:
599 return IMAGE_REL_BASED_ABSOLUTE;
600 default:
601 llvm_unreachable("unknown machine type");
602 }
603}
604
605// Windows-specific.
606// Collect all locations that contain absolute addresses, which need to be
607// fixed by the loader if load-time relocation is needed.
608// Only called when base relocation is enabled.
609void SectionChunk::getBaserels(std::vector<Baserel> *res) {
610 for (const coff_relocation &rel : getRelocs()) {
611 uint8_t ty = getBaserelType(rel, arch: getArch());
612 if (ty == IMAGE_REL_BASED_ABSOLUTE)
613 continue;
614 Symbol *target = file->getSymbol(symbolIndex: rel.SymbolTableIndex);
615 if (!isa_and_nonnull<Defined>(Val: target) || isa<DefinedAbsolute>(Val: target))
616 continue;
617 res->emplace_back(args: rva + rel.VirtualAddress, args&: ty);
618 }
619
620 // Insert a 64-bit relocation for CHPEMetadataPointer in the native load
621 // config of a hybrid ARM64X image. Its value will be set in prepareLoadConfig
622 // to match the value in the EC load config, which is expected to be
623 // a relocatable pointer to the __chpe_metadata symbol.
624 COFFLinkerContext &ctx = file->symtab.ctx;
625 if (ctx.config.machine == ARM64X && ctx.hybridSymtab->loadConfigSym &&
626 ctx.hybridSymtab->loadConfigSym->getChunk() == this &&
627 ctx.symtab.loadConfigSym &&
628 ctx.hybridSymtab->loadConfigSize >=
629 offsetof(coff_load_configuration64, CHPEMetadataPointer) +
630 sizeof(coff_load_configuration64::CHPEMetadataPointer))
631 res->emplace_back(
632 args: ctx.hybridSymtab->loadConfigSym->getRVA() +
633 offsetof(coff_load_configuration64, CHPEMetadataPointer),
634 args: IMAGE_REL_BASED_DIR64);
635}
636
637// MinGW specific.
638// Check whether a static relocation of type Type can be deferred and
639// handled at runtime as a pseudo relocation (for references to a module
640// local variable, which turned out to actually need to be imported from
641// another DLL) This returns the size the relocation is supposed to update,
642// in bits, or 0 if the relocation cannot be handled as a runtime pseudo
643// relocation.
644static int getRuntimePseudoRelocSize(uint16_t type, Triple::ArchType arch) {
645 // Relocations that either contain an absolute address, or a plain
646 // relative offset, since the runtime pseudo reloc implementation
647 // adds 8/16/32/64 bit values to a memory address.
648 //
649 // Given a pseudo relocation entry,
650 //
651 // typedef struct {
652 // DWORD sym;
653 // DWORD target;
654 // DWORD flags;
655 // } runtime_pseudo_reloc_item_v2;
656 //
657 // the runtime relocation performs this adjustment:
658 // *(base + .target) += *(base + .sym) - (base + .sym)
659 //
660 // This works for both absolute addresses (IMAGE_REL_*_ADDR32/64,
661 // IMAGE_REL_I386_DIR32, where the memory location initially contains
662 // the address of the IAT slot, and for relative addresses (IMAGE_REL*_REL32),
663 // where the memory location originally contains the relative offset to the
664 // IAT slot.
665 //
666 // This requires the target address to be writable, either directly out of
667 // the image, or temporarily changed at runtime with VirtualProtect.
668 // Since this only operates on direct address values, it doesn't work for
669 // ARM/ARM64 relocations, other than the plain ADDR32/ADDR64 relocations.
670 switch (arch) {
671 case Triple::x86_64:
672 switch (type) {
673 case IMAGE_REL_AMD64_ADDR64:
674 return 64;
675 case IMAGE_REL_AMD64_ADDR32:
676 case IMAGE_REL_AMD64_REL32:
677 case IMAGE_REL_AMD64_REL32_1:
678 case IMAGE_REL_AMD64_REL32_2:
679 case IMAGE_REL_AMD64_REL32_3:
680 case IMAGE_REL_AMD64_REL32_4:
681 case IMAGE_REL_AMD64_REL32_5:
682 return 32;
683 default:
684 return 0;
685 }
686 case Triple::x86:
687 switch (type) {
688 case IMAGE_REL_I386_DIR32:
689 case IMAGE_REL_I386_REL32:
690 return 32;
691 default:
692 return 0;
693 }
694 case Triple::thumb:
695 switch (type) {
696 case IMAGE_REL_ARM_ADDR32:
697 return 32;
698 default:
699 return 0;
700 }
701 case Triple::aarch64:
702 switch (type) {
703 case IMAGE_REL_ARM64_ADDR64:
704 return 64;
705 case IMAGE_REL_ARM64_ADDR32:
706 return 32;
707 default:
708 return 0;
709 }
710 default:
711 llvm_unreachable("unknown machine type");
712 }
713}
714
715// MinGW specific.
716// Append information to the provided vector about all relocations that
717// need to be handled at runtime as runtime pseudo relocations (references
718// to a module local variable, which turned out to actually need to be
719// imported from another DLL).
720void SectionChunk::getRuntimePseudoRelocs(
721 std::vector<RuntimePseudoReloc> &res) {
722 for (const coff_relocation &rel : getRelocs()) {
723 auto *target =
724 dyn_cast_or_null<Defined>(Val: file->getSymbol(symbolIndex: rel.SymbolTableIndex));
725 if (!target || !target->isRuntimePseudoReloc)
726 continue;
727 // If the target doesn't have a chunk allocated, it may be a
728 // DefinedImportData symbol which ended up unnecessary after GC.
729 // Normally we wouldn't eliminate section chunks that are referenced, but
730 // references within DWARF sections don't count for keeping section chunks
731 // alive. Thus such dangling references in DWARF sections are expected.
732 if (!target->getChunk())
733 continue;
734 int sizeInBits = getRuntimePseudoRelocSize(type: rel.Type, arch: getArch());
735 if (sizeInBits == 0) {
736 error(msg: "unable to automatically import from " + target->getName() +
737 " with relocation type " +
738 file->getCOFFObj()->getRelocationTypeName(Type: rel.Type) + " in " +
739 toString(file));
740 continue;
741 }
742 int addressSizeInBits = file->symtab.ctx.config.is64() ? 64 : 32;
743 if (sizeInBits < addressSizeInBits) {
744 warn(msg: "runtime pseudo relocation in " + toString(file) + " against " +
745 "symbol " + target->getName() + " is too narrow (only " +
746 Twine(sizeInBits) + " bits wide); this can fail at runtime " +
747 "depending on memory layout");
748 }
749 // sizeInBits is used to initialize the Flags field; currently no
750 // other flags are defined.
751 res.emplace_back(args&: target, args: this, args: rel.VirtualAddress, args&: sizeInBits);
752 }
753}
754
755bool SectionChunk::isCOMDAT() const {
756 return header->Characteristics & IMAGE_SCN_LNK_COMDAT;
757}
758
759void SectionChunk::printDiscardedMessage() const {
760 // Removed by dead-stripping. If it's removed by ICF, ICF already
761 // printed out the name, so don't repeat that here.
762 if (sym && this == repl)
763 log(msg: "Discarded " + sym->getName());
764}
765
766StringRef SectionChunk::getDebugName() const {
767 if (sym)
768 return sym->getName();
769 return "";
770}
771
772ArrayRef<uint8_t> SectionChunk::getContents() const {
773 ArrayRef<uint8_t> a;
774 cantFail(Err: file->getCOFFObj()->getSectionContents(Sec: header, Res&: a));
775 return a;
776}
777
778ArrayRef<uint8_t> SectionChunk::consumeDebugMagic() {
779 assert(isCodeView());
780 return consumeDebugMagic(data: getContents(), sectionName: getSectionName());
781}
782
783ArrayRef<uint8_t> SectionChunk::consumeDebugMagic(ArrayRef<uint8_t> data,
784 StringRef sectionName) {
785 if (data.empty())
786 return {};
787
788 // First 4 bytes are section magic.
789 if (data.size() < 4)
790 fatal(msg: "the section is too short: " + sectionName);
791
792 if (!sectionName.starts_with(Prefix: ".debug$"))
793 fatal(msg: "invalid section: " + sectionName);
794
795 uint32_t magic = support::endian::read32le(P: data.data());
796 uint32_t expectedMagic = sectionName == ".debug$H"
797 ? DEBUG_HASHES_SECTION_MAGIC
798 : DEBUG_SECTION_MAGIC;
799 if (magic != expectedMagic) {
800 warn(msg: "ignoring section " + sectionName + " with unrecognized magic 0x" +
801 utohexstr(X: magic));
802 return {};
803 }
804 return data.slice(N: 4);
805}
806
807SectionChunk *SectionChunk::findByName(ArrayRef<SectionChunk *> sections,
808 StringRef name) {
809 for (SectionChunk *c : sections)
810 if (c->getSectionName() == name)
811 return c;
812 return nullptr;
813}
814
815void SectionChunk::replace(SectionChunk *other) {
816 p2Align = std::max(a: p2Align, b: other->p2Align);
817 other->repl = repl;
818 other->live = false;
819}
820
821uint32_t SectionChunk::getSectionNumber() const {
822 DataRefImpl r;
823 r.p = reinterpret_cast<uintptr_t>(header);
824 SectionRef s(r, file->getCOFFObj());
825 return s.getIndex() + 1;
826}
827
828CommonChunk::CommonChunk(const COFFSymbolRef s) : live(false), sym(s) {
829 // The value of a common symbol is its size. Align all common symbols smaller
830 // than 32 bytes naturally, i.e. round the size up to the next power of two.
831 // This is what MSVC link.exe does.
832 setAlignment(std::min(a: 32U, b: uint32_t(PowerOf2Ceil(A: sym.getValue()))));
833 hasData = false;
834}
835
836uint32_t CommonChunk::getOutputCharacteristics() const {
837 return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
838 IMAGE_SCN_MEM_WRITE;
839}
840
841void StringChunk::writeTo(uint8_t *buf) const {
842 memcpy(dest: buf, src: str.data(), n: str.size());
843 buf[str.size()] = '\0';
844}
845
846ImportThunkChunk::ImportThunkChunk(COFFLinkerContext &ctx, Defined *s)
847 : NonSectionCodeChunk(ImportThunkKind), live(!ctx.config.doGC),
848 impSymbol(s), ctx(ctx) {}
849
850ImportThunkChunkX64::ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s)
851 : ImportThunkChunk(ctx, s) {
852 // Intel Optimization Manual says that all branch targets
853 // should be 16-byte aligned. MSVC linker does this too.
854 setAlignment(16);
855}
856
857void ImportThunkChunkX64::writeTo(uint8_t *buf) const {
858 memcpy(dest: buf, src: importThunkX86, n: sizeof(importThunkX86));
859 // The first two bytes is a JMP instruction. Fill its operand.
860 write32le(P: buf + 2, V: impSymbol->getRVA() - rva - getSize());
861}
862
863void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *res) {
864 res->emplace_back(args: getRVA() + 2, args&: ctx.config.machine);
865}
866
867void ImportThunkChunkX86::writeTo(uint8_t *buf) const {
868 memcpy(dest: buf, src: importThunkX86, n: sizeof(importThunkX86));
869 // The first two bytes is a JMP instruction. Fill its operand.
870 write32le(P: buf + 2, V: impSymbol->getRVA() + ctx.config.imageBase);
871}
872
873void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *res) {
874 res->emplace_back(args: getRVA(), args: IMAGE_REL_BASED_ARM_MOV32T);
875}
876
877void ImportThunkChunkARM::writeTo(uint8_t *buf) const {
878 memcpy(dest: buf, src: importThunkARM, n: sizeof(importThunkARM));
879 // Fix mov.w and mov.t operands.
880 applyMOV32T(off: buf, v: impSymbol->getRVA() + ctx.config.imageBase);
881}
882
883void ImportThunkChunkARM64::writeTo(uint8_t *buf) const {
884 int64_t off = impSymbol->getRVA() & 0xfff;
885 memcpy(dest: buf, src: importThunkARM64, n: sizeof(importThunkARM64));
886 applyArm64Addr(off: buf, s: impSymbol->getRVA(), p: rva, shift: 12);
887 applyArm64Ldr(off: buf + 4, imm: off);
888}
889
890// A Thumb2, PIC, non-interworking range extension thunk.
891const uint8_t armThunk[] = {
892 0x40, 0xf2, 0x00, 0x0c, // P: movw ip,:lower16:S - (P + (L1-P) + 4)
893 0xc0, 0xf2, 0x00, 0x0c, // movt ip,:upper16:S - (P + (L1-P) + 4)
894 0xe7, 0x44, // L1: add pc, ip
895};
896
897size_t RangeExtensionThunkARM::getSize() const {
898 assert(ctx.config.machine == ARMNT);
899 (void)&ctx;
900 return sizeof(armThunk);
901}
902
903void RangeExtensionThunkARM::writeTo(uint8_t *buf) const {
904 assert(ctx.config.machine == ARMNT);
905 uint64_t offset = target->getRVA() - rva - 12;
906 memcpy(dest: buf, src: armThunk, n: sizeof(armThunk));
907 applyMOV32T(off: buf, v: uint32_t(offset));
908}
909
910// A position independent ARM64 adrp+add thunk, with a maximum range of
911// +/- 4 GB, which is enough for any PE-COFF.
912const uint8_t arm64Thunk[] = {
913 0x10, 0x00, 0x00, 0x90, // adrp x16, Dest
914 0x10, 0x02, 0x00, 0x91, // add x16, x16, :lo12:Dest
915 0x00, 0x02, 0x1f, 0xd6, // br x16
916};
917
918size_t RangeExtensionThunkARM64::getSize() const { return sizeof(arm64Thunk); }
919
920void RangeExtensionThunkARM64::writeTo(uint8_t *buf) const {
921 memcpy(dest: buf, src: arm64Thunk, n: sizeof(arm64Thunk));
922 applyArm64Addr(off: buf + 0, s: target->getRVA(), p: rva, shift: 12);
923 applyArm64Imm(off: buf + 4, imm: target->getRVA() & 0xfff, rangeLimit: 0);
924}
925
926void SameAddressThunkARM64EC::setDynamicRelocs(COFFLinkerContext &ctx) const {
927 // Add ARM64X relocations replacing adrp/add instructions with a version using
928 // the hybrid target.
929 RangeExtensionThunkARM64 hybridView(ARM64EC, hybridTarget);
930 uint8_t buf[sizeof(arm64Thunk)];
931 hybridView.setRVA(rva);
932 hybridView.writeTo(buf);
933 uint32_t addrp = *reinterpret_cast<ulittle32_t *>(buf);
934 uint32_t add = *reinterpret_cast<ulittle32_t *>(buf + sizeof(uint32_t));
935 ctx.dynamicRelocs->set(offset: this, value: addrp);
936 ctx.dynamicRelocs->set(offset: Arm64XRelocVal(this, sizeof(uint32_t)), value: add);
937}
938
939LocalImportChunk::LocalImportChunk(COFFLinkerContext &c, Defined *s)
940 : sym(s), ctx(c) {
941 setAlignment(ctx.config.wordsize);
942}
943
944void LocalImportChunk::getBaserels(std::vector<Baserel> *res) {
945 res->emplace_back(args: getRVA(), args&: ctx.config.machine);
946}
947
948size_t LocalImportChunk::getSize() const { return ctx.config.wordsize; }
949
950void LocalImportChunk::writeTo(uint8_t *buf) const {
951 if (ctx.config.is64()) {
952 write64le(P: buf, V: sym->getRVA() + ctx.config.imageBase);
953 } else {
954 uint32_t bit = 0;
955 // Pointer to thumb code must have the LSB set, so adjust it. Only code is
956 // adjusted: dllimport of a locally defined variable is valid, and the
957 // pointer to such a variable must stay unmodified.
958 if (ctx.config.machine == ARMNT && sym->getChunk() &&
959 (sym->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
960 bit = 1;
961 write32le(P: buf, V: (sym->getRVA() + ctx.config.imageBase) | bit);
962 }
963}
964
965void RVATableChunk::writeTo(uint8_t *buf) const {
966 ulittle32_t *begin = reinterpret_cast<ulittle32_t *>(buf);
967 size_t cnt = 0;
968 for (const ChunkAndOffset &co : syms)
969 begin[cnt++] = co.inputChunk->getRVA() + co.offset;
970 llvm::sort(Start: begin, End: begin + cnt);
971 assert(std::unique(begin, begin + cnt) == begin + cnt &&
972 "RVA tables should be de-duplicated");
973}
974
975void RVAFlagTableChunk::writeTo(uint8_t *buf) const {
976 struct RVAFlag {
977 ulittle32_t rva;
978 uint8_t flag;
979 };
980 auto flags =
981 MutableArrayRef(reinterpret_cast<RVAFlag *>(buf), syms.size());
982 for (auto t : zip(t: syms, u&: flags)) {
983 const auto &sym = std::get<0>(t&: t);
984 auto &flag = std::get<1>(t&: t);
985 flag.rva = sym.inputChunk->getRVA() + sym.offset;
986 flag.flag = 0;
987 }
988 llvm::sort(C&: flags,
989 Comp: [](const RVAFlag &a, const RVAFlag &b) { return a.rva < b.rva; });
990 assert(llvm::unique(flags, [](const RVAFlag &a,
991 const RVAFlag &b) { return a.rva == b.rva; }) ==
992 flags.end() &&
993 "RVA tables should be de-duplicated");
994}
995
996size_t ECCodeMapChunk::getSize() const {
997 return map.size() * sizeof(chpe_range_entry);
998}
999
1000void ECCodeMapChunk::writeTo(uint8_t *buf) const {
1001 auto table = reinterpret_cast<chpe_range_entry *>(buf);
1002 for (uint32_t i = 0; i < map.size(); i++) {
1003 const ECCodeMapEntry &entry = map[i];
1004 uint32_t start = entry.first->getRVA() & ~0xfff;
1005 table[i].StartOffset = start | entry.type;
1006 table[i].Length = entry.last->getRVA() + entry.last->getSize() - start;
1007 }
1008}
1009
1010// MinGW specific, for the "automatic import of variables from DLLs" feature.
1011size_t PseudoRelocTableChunk::getSize() const {
1012 if (relocs.empty())
1013 return 0;
1014 return 12 + 12 * relocs.size();
1015}
1016
1017// MinGW specific.
1018void PseudoRelocTableChunk::writeTo(uint8_t *buf) const {
1019 if (relocs.empty())
1020 return;
1021
1022 ulittle32_t *table = reinterpret_cast<ulittle32_t *>(buf);
1023 // This is the list header, to signal the runtime pseudo relocation v2
1024 // format.
1025 table[0] = 0;
1026 table[1] = 0;
1027 table[2] = 1;
1028
1029 size_t idx = 3;
1030 for (const RuntimePseudoReloc &rpr : relocs) {
1031 table[idx + 0] = rpr.sym->getRVA();
1032 table[idx + 1] = rpr.target->getRVA() + rpr.targetOffset;
1033 table[idx + 2] = rpr.flags;
1034 idx += 3;
1035 }
1036}
1037
1038// Windows-specific. This class represents a block in .reloc section.
1039// The format is described here.
1040//
1041// On Windows, each DLL is linked against a fixed base address and
1042// usually loaded to that address. However, if there's already another
1043// DLL that overlaps, the loader has to relocate it. To do that, DLLs
1044// contain .reloc sections which contain offsets that need to be fixed
1045// up at runtime. If the loader finds that a DLL cannot be loaded to its
1046// desired base address, it loads it to somewhere else, and add <actual
1047// base address> - <desired base address> to each offset that is
1048// specified by the .reloc section. In ELF terms, .reloc sections
1049// contain relative relocations in REL format (as opposed to RELA.)
1050//
1051// This already significantly reduces the size of relocations compared
1052// to ELF .rel.dyn, but Windows does more to reduce it (probably because
1053// it was invented for PCs in the late '80s or early '90s.) Offsets in
1054// .reloc are grouped by page where the page size is 12 bits, and
1055// offsets sharing the same page address are stored consecutively to
1056// represent them with less space. This is very similar to the page
1057// table which is grouped by (multiple stages of) pages.
1058//
1059// For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,
1060// 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4
1061// bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they
1062// are represented like this:
1063//
1064// 0x00000 -- page address (4 bytes)
1065// 16 -- size of this block (4 bytes)
1066// 0xA030 -- entries (2 bytes each)
1067// 0xA500
1068// 0xA700
1069// 0xAA00
1070// 0x20000 -- page address (4 bytes)
1071// 12 -- size of this block (4 bytes)
1072// 0xA004 -- entries (2 bytes each)
1073// 0xA008
1074//
1075// Usually we have a lot of relocations for each page, so the number of
1076// bytes for one .reloc entry is close to 2 bytes on average.
1077BaserelChunk::BaserelChunk(uint32_t page, Baserel *begin, Baserel *end) {
1078 // Block header consists of 4 byte page RVA and 4 byte block size.
1079 // Each entry is 2 byte. Last entry may be padding.
1080 data.resize(new_size: alignTo(Value: (end - begin) * 2 + 8, Align: 4));
1081 uint8_t *p = data.data();
1082 write32le(P: p, V: page);
1083 write32le(P: p + 4, V: data.size());
1084 p += 8;
1085 for (Baserel *i = begin; i != end; ++i) {
1086 write16le(P: p, V: (i->type << 12) | (i->rva - page));
1087 p += 2;
1088 }
1089}
1090
1091void BaserelChunk::writeTo(uint8_t *buf) const {
1092 memcpy(dest: buf, src: data.data(), n: data.size());
1093}
1094
1095uint8_t Baserel::getDefaultType(llvm::COFF::MachineTypes machine) {
1096 return is64Bit(Machine: machine) ? IMAGE_REL_BASED_DIR64 : IMAGE_REL_BASED_HIGHLOW;
1097}
1098
1099MergeChunk::MergeChunk(uint32_t alignment)
1100 : builder(StringTableBuilder::RAW, llvm::Align(alignment)) {
1101 setAlignment(alignment);
1102}
1103
1104void MergeChunk::addSection(COFFLinkerContext &ctx, SectionChunk *c) {
1105 assert(isPowerOf2_32(c->getAlignment()));
1106 uint8_t p2Align = llvm::Log2_32(Value: c->getAlignment());
1107 assert(p2Align < std::size(ctx.mergeChunkInstances));
1108 auto *&mc = ctx.mergeChunkInstances[p2Align];
1109 if (!mc)
1110 mc = make<MergeChunk>(args: c->getAlignment());
1111 mc->sections.push_back(x: c);
1112}
1113
1114void MergeChunk::finalizeContents() {
1115 assert(!finalized && "should only finalize once");
1116 for (SectionChunk *c : sections)
1117 if (c->live)
1118 builder.add(S: toStringRef(Input: c->getContents()));
1119 builder.finalize();
1120 finalized = true;
1121}
1122
1123void MergeChunk::assignSubsectionRVAs() {
1124 for (SectionChunk *c : sections) {
1125 if (!c->live)
1126 continue;
1127 size_t off = builder.getOffset(S: toStringRef(Input: c->getContents()));
1128 c->setRVA(rva + off);
1129 }
1130}
1131
1132uint32_t MergeChunk::getOutputCharacteristics() const {
1133 return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;
1134}
1135
1136size_t MergeChunk::getSize() const {
1137 return builder.getSize();
1138}
1139
1140void MergeChunk::writeTo(uint8_t *buf) const {
1141 builder.write(Buf: buf);
1142}
1143
1144// MinGW specific.
1145size_t AbsolutePointerChunk::getSize() const {
1146 return symtab.ctx.config.wordsize;
1147}
1148
1149void AbsolutePointerChunk::writeTo(uint8_t *buf) const {
1150 if (symtab.ctx.config.is64()) {
1151 write64le(P: buf, V: value);
1152 } else {
1153 write32le(P: buf, V: value);
1154 }
1155}
1156
1157MachineTypes AbsolutePointerChunk::getMachine() const { return symtab.machine; }
1158
1159void ECExportThunkChunk::writeTo(uint8_t *buf) const {
1160 memcpy(dest: buf, src: ECExportThunkCode, n: sizeof(ECExportThunkCode));
1161 write32le(P: buf + 10, V: target->getRVA() - rva - 14);
1162}
1163
1164size_t CHPECodeRangesChunk::getSize() const {
1165 return exportThunks.size() * sizeof(chpe_code_range_entry);
1166}
1167
1168void CHPECodeRangesChunk::writeTo(uint8_t *buf) const {
1169 auto ranges = reinterpret_cast<chpe_code_range_entry *>(buf);
1170
1171 for (uint32_t i = 0; i < exportThunks.size(); i++) {
1172 Chunk *thunk = exportThunks[i].first;
1173 uint32_t start = thunk->getRVA();
1174 ranges[i].StartRva = start;
1175 ranges[i].EndRva = start + thunk->getSize();
1176 ranges[i].EntryPoint = start;
1177 }
1178}
1179
1180size_t CHPERedirectionChunk::getSize() const {
1181 // Add an extra +1 for a terminator entry.
1182 return (exportThunks.size() + 1) * sizeof(chpe_redirection_entry);
1183}
1184
1185void CHPERedirectionChunk::writeTo(uint8_t *buf) const {
1186 auto entries = reinterpret_cast<chpe_redirection_entry *>(buf);
1187
1188 for (uint32_t i = 0; i < exportThunks.size(); i++) {
1189 entries[i].Source = exportThunks[i].first->getRVA();
1190 entries[i].Destination = exportThunks[i].second->getRVA();
1191 }
1192}
1193
1194ImportThunkChunkARM64EC::ImportThunkChunkARM64EC(ImportFile *file)
1195 : ImportThunkChunk(file->symtab.ctx, file->impSym), file(file) {}
1196
1197size_t ImportThunkChunkARM64EC::getSize() const {
1198 if (!extended)
1199 return sizeof(importThunkARM64EC);
1200 // The last instruction is replaced with an inline range extension thunk.
1201 return sizeof(importThunkARM64EC) + sizeof(arm64Thunk) - sizeof(uint32_t);
1202}
1203
1204void ImportThunkChunkARM64EC::writeTo(uint8_t *buf) const {
1205 memcpy(dest: buf, src: importThunkARM64EC, n: sizeof(importThunkARM64EC));
1206 applyArm64Addr(off: buf, s: file->impSym->getRVA(), p: rva, shift: 12);
1207 applyArm64Ldr(off: buf + 4, imm: file->impSym->getRVA() & 0xfff);
1208
1209 // The exit thunk may be missing. This can happen if the application only
1210 // references a function by its address (in which case the thunk is never
1211 // actually used, but is still required to fill the auxiliary IAT), or in
1212 // cases of hand-written assembly calling an imported ARM64EC function (where
1213 // the exit thunk is ignored by __icall_helper_arm64ec). In such cases, MSVC
1214 // link.exe uses 0 as the RVA.
1215 uint32_t exitThunkRVA = exitThunk ? exitThunk->getRVA() : 0;
1216 applyArm64Addr(off: buf + 8, s: exitThunkRVA, p: rva + 8, shift: 12);
1217 applyArm64Imm(off: buf + 12, imm: exitThunkRVA & 0xfff, rangeLimit: 0);
1218
1219 Defined *helper = cast<Defined>(Val: file->symtab.ctx.config.arm64ECIcallHelper);
1220 if (extended) {
1221 // Replace last instruction with an inline range extension thunk.
1222 memcpy(dest: buf + 16, src: arm64Thunk, n: sizeof(arm64Thunk));
1223 applyArm64Addr(off: buf + 16, s: helper->getRVA(), p: rva + 16, shift: 12);
1224 applyArm64Imm(off: buf + 20, imm: helper->getRVA() & 0xfff, rangeLimit: 0);
1225 } else {
1226 applyArm64Branch26(off: buf + 16, v: helper->getRVA() - rva - 16);
1227 }
1228}
1229
1230bool ImportThunkChunkARM64EC::verifyRanges() {
1231 if (extended)
1232 return true;
1233 auto helper = cast<Defined>(Val: file->symtab.ctx.config.arm64ECIcallHelper);
1234 return isInt<28>(x: helper->getRVA() - rva - 16);
1235}
1236
1237uint32_t ImportThunkChunkARM64EC::extendRanges() {
1238 if (extended || verifyRanges())
1239 return 0;
1240 extended = true;
1241 // The last instruction is replaced with an inline range extension thunk.
1242 return sizeof(arm64Thunk) - sizeof(uint32_t);
1243}
1244
1245uint64_t Arm64XRelocVal::get() const {
1246 return (sym ? sym->getRVA() : 0) + (chunk ? chunk->getRVA() : 0) + value;
1247}
1248
1249size_t Arm64XDynamicRelocEntry::getSize() const {
1250 switch (type) {
1251 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
1252 return sizeof(uint16_t); // Just a header.
1253 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
1254 return sizeof(uint16_t) + size; // A header and a payload.
1255 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
1256 return 2 * sizeof(uint16_t); // A header and a delta.
1257 }
1258 llvm_unreachable("invalid type");
1259}
1260
1261void Arm64XDynamicRelocEntry::writeTo(uint8_t *buf) const {
1262 auto out = reinterpret_cast<ulittle16_t *>(buf);
1263 *out = (offset.get() & 0xfff) | (type << 12);
1264
1265 switch (type) {
1266 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
1267 *out |= ((bit_width(Value: size) - 1) << 14); // Encode the size.
1268 break;
1269 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
1270 *out |= ((bit_width(Value: size) - 1) << 14); // Encode the size.
1271 switch (size) {
1272 case 2:
1273 out[1] = value.get();
1274 break;
1275 case 4:
1276 *reinterpret_cast<ulittle32_t *>(out + 1) = value.get();
1277 break;
1278 case 8:
1279 *reinterpret_cast<ulittle64_t *>(out + 1) = value.get();
1280 break;
1281 default:
1282 llvm_unreachable("invalid size");
1283 }
1284 break;
1285 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
1286 int delta = value.get();
1287 // Negative offsets use a sign bit in the header.
1288 if (delta < 0) {
1289 *out |= 1 << 14;
1290 delta = -delta;
1291 }
1292 // Depending on the value, the delta is encoded with a shift of 2 or 3 bits.
1293 if (delta & 7) {
1294 assert(!(delta & 3));
1295 delta >>= 2;
1296 } else {
1297 *out |= (1 << 15);
1298 delta >>= 3;
1299 }
1300 out[1] = delta;
1301 assert(!(delta & ~0xffff));
1302 break;
1303 }
1304}
1305
1306void DynamicRelocsChunk::finalize() {
1307 llvm::stable_sort(Range&: arm64xRelocs, C: [=](const Arm64XDynamicRelocEntry &a,
1308 const Arm64XDynamicRelocEntry &b) {
1309 return a.offset.get() < b.offset.get();
1310 });
1311
1312 size = sizeof(coff_dynamic_reloc_table) + sizeof(coff_dynamic_relocation64);
1313 uint32_t prevPage = 0xfff;
1314
1315 for (const Arm64XDynamicRelocEntry &entry : arm64xRelocs) {
1316 uint32_t page = entry.offset.get() & ~0xfff;
1317 if (page != prevPage) {
1318 size = alignTo(Value: size, Align: sizeof(uint32_t)) +
1319 sizeof(coff_base_reloc_block_header);
1320 prevPage = page;
1321 }
1322 size += entry.getSize();
1323 }
1324
1325 size = alignTo(Value: size, Align: sizeof(uint32_t));
1326}
1327
1328// Set the reloc value. The reloc entry must be allocated beforehand.
1329void DynamicRelocsChunk::set(Arm64XRelocVal offset, Arm64XRelocVal value) {
1330 uint32_t rva = offset.get();
1331 auto entry =
1332 llvm::find_if(Range&: arm64xRelocs, P: [rva](const Arm64XDynamicRelocEntry &e) {
1333 return e.offset.get() == rva;
1334 });
1335 assert(entry != arm64xRelocs.end());
1336 assert(!entry->value.get());
1337 entry->value = value;
1338}
1339
1340void DynamicRelocsChunk::writeTo(uint8_t *buf) const {
1341 auto table = reinterpret_cast<coff_dynamic_reloc_table *>(buf);
1342 table->Version = 1;
1343 table->Size = sizeof(coff_dynamic_relocation64);
1344 buf += sizeof(*table);
1345
1346 auto header = reinterpret_cast<coff_dynamic_relocation64 *>(buf);
1347 header->Symbol = IMAGE_DYNAMIC_RELOCATION_ARM64X;
1348 buf += sizeof(*header);
1349
1350 coff_base_reloc_block_header *pageHeader = nullptr;
1351 size_t relocSize = 0;
1352 for (const Arm64XDynamicRelocEntry &entry : arm64xRelocs) {
1353 uint32_t page = entry.offset.get() & ~0xfff;
1354 if (!pageHeader || page != pageHeader->PageRVA) {
1355 relocSize = alignTo(Value: relocSize, Align: sizeof(uint32_t));
1356 if (pageHeader)
1357 pageHeader->BlockSize =
1358 buf + relocSize - reinterpret_cast<uint8_t *>(pageHeader);
1359 pageHeader =
1360 reinterpret_cast<coff_base_reloc_block_header *>(buf + relocSize);
1361 pageHeader->PageRVA = page;
1362 relocSize += sizeof(*pageHeader);
1363 }
1364
1365 entry.writeTo(buf: buf + relocSize);
1366 relocSize += entry.getSize();
1367 }
1368 relocSize = alignTo(Value: relocSize, Align: sizeof(uint32_t));
1369 pageHeader->BlockSize =
1370 buf + relocSize - reinterpret_cast<uint8_t *>(pageHeader);
1371
1372 header->BaseRelocSize = relocSize;
1373 table->Size += relocSize;
1374 assert(size == sizeof(*table) + sizeof(*header) + relocSize);
1375}
1376
1377} // namespace lld::coff
1378