1//===- Chunks.h -------------------------------------------------*- C++ -*-===//
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#ifndef LLD_COFF_CHUNKS_H
10#define LLD_COFF_CHUNKS_H
11
12#include "Config.h"
13#include "InputFiles.h"
14#include "lld/Common/LLVM.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/PointerIntPair.h"
17#include "llvm/ADT/iterator.h"
18#include "llvm/ADT/iterator_range.h"
19#include "llvm/MC/StringTableBuilder.h"
20#include "llvm/Object/COFF.h"
21#include "llvm/Object/WindowsMachineFlag.h"
22#include <utility>
23#include <vector>
24
25namespace lld::coff {
26
27using llvm::COFF::ImportDirectoryTableEntry;
28using llvm::object::chpe_range_type;
29using llvm::object::coff_relocation;
30using llvm::object::coff_section;
31using llvm::object::COFFSymbolRef;
32using llvm::object::SectionRef;
33
34class Baserel;
35class Defined;
36class DefinedImportData;
37class DefinedRegular;
38class ObjFile;
39class OutputSection;
40class RuntimePseudoReloc;
41class Symbol;
42
43// Mask for permissions (discardable, writable, readable, executable, etc).
44const uint32_t permMask = 0xFE000000;
45
46// Mask for section types (code, data, bss).
47const uint32_t typeMask = 0x000000E0;
48
49// The log base 2 of the largest section alignment, which is log2(8192), or 13.
50enum : unsigned { Log2MaxSectionAlignment = 13 };
51
52// A Chunk represents a chunk of data that will occupy space in the
53// output (if the resolver chose that). It may or may not be backed by
54// a section of an input file. It could be linker-created data, or
55// doesn't even have actual data (if common or bss).
56class Chunk {
57public:
58 enum Kind : uint8_t {
59 SectionKind,
60 SectionECKind,
61 OtherKind,
62 ImportThunkKind,
63 ECExportThunkKind
64 };
65 Kind kind() const { return chunkKind; }
66
67 // Returns the size of this chunk (even if this is a common or BSS.)
68 size_t getSize() const;
69
70 // Returns chunk alignment in power of two form. Value values are powers of
71 // two from 1 to 8192.
72 uint32_t getAlignment() const { return 1U << p2Align; }
73
74 // Update the chunk section alignment measured in bytes. Internally alignment
75 // is stored in log2.
76 void setAlignment(uint32_t align) {
77 // Treat zero byte alignment as 1 byte alignment.
78 align = align ? align : 1;
79 assert(llvm::isPowerOf2_32(align) && "alignment is not a power of 2");
80 p2Align = llvm::Log2_32(Value: align);
81 assert(p2Align <= Log2MaxSectionAlignment &&
82 "impossible requested alignment");
83 }
84
85 // Write this chunk to a mmap'ed file, assuming Buf is pointing to
86 // beginning of the file. Because this function may use RVA values
87 // of other chunks for relocations, you need to set them properly
88 // before calling this function.
89 void writeTo(uint8_t *buf) const;
90
91 // The writer sets and uses the addresses. In practice, PE images cannot be
92 // larger than 2GB. Chunks are always laid as part of the image, so Chunk RVAs
93 // can be stored with 32 bits.
94 uint32_t getRVA() const { return rva; }
95 void setRVA(uint64_t v) {
96 // This may truncate. The writer checks for overflow later.
97 rva = (uint32_t)v;
98 }
99
100 // Returns readable/writable/executable bits.
101 uint32_t getOutputCharacteristics() const;
102
103 // Returns the section name if this is a section chunk.
104 // It is illegal to call this function on non-section chunks.
105 StringRef getSectionName() const;
106
107 // An output section has pointers to chunks in the section, and each
108 // chunk has a back pointer to an output section.
109 void setOutputSectionIdx(uint16_t o) { osidx = o; }
110 uint16_t getOutputSectionIdx() const { return osidx; }
111
112 // Windows-specific.
113 // Collect all locations that contain absolute addresses for base relocations.
114 void getBaserels(std::vector<Baserel> *res);
115
116 // Returns a human-readable name of this chunk. Chunks are unnamed chunks of
117 // bytes, so this is used only for logging or debugging.
118 StringRef getDebugName() const;
119
120 // Return true if this file has the hotpatch flag set to true in the
121 // S_COMPILE3 record in codeview debug info. Also returns true for some thunks
122 // synthesized by the linker.
123 bool isHotPatchable() const;
124
125 MachineTypes getMachine() const;
126 llvm::Triple::ArchType getArch() const;
127 std::optional<chpe_range_type> getArm64ECRangeType() const;
128
129 // ARM64EC entry thunk associated with the chunk.
130 Defined *getEntryThunk() const;
131 void setEntryThunk(Defined *entryThunk);
132
133protected:
134 Chunk(Kind k = OtherKind) : chunkKind(k), hasData(true), p2Align(0) {}
135
136 const Kind chunkKind;
137
138public:
139 // Returns true if this has non-zero data. BSS chunks return
140 // false. If false is returned, the space occupied by this chunk
141 // will be filled with zeros. Corresponds to the
142 // IMAGE_SCN_CNT_UNINITIALIZED_DATA section characteristic bit.
143 uint8_t hasData : 1;
144
145public:
146 // The alignment of this chunk, stored in log2 form. The writer uses the
147 // value.
148 uint8_t p2Align : 7;
149
150 // The output section index for this chunk. The first valid section number is
151 // one.
152 uint16_t osidx = 0;
153
154 // The RVA of this chunk in the output. The writer sets a value.
155 uint32_t rva = 0;
156};
157
158class NonSectionChunk : public Chunk {
159public:
160 virtual ~NonSectionChunk() = default;
161
162 // Returns the size of this chunk (even if this is a common or BSS.)
163 virtual size_t getSize() const = 0;
164
165 virtual uint32_t getOutputCharacteristics() const { return 0; }
166
167 // Write this chunk to a mmap'ed file, assuming Buf is pointing to
168 // beginning of the file. Because this function may use RVA values
169 // of other chunks for relocations, you need to set them properly
170 // before calling this function.
171 virtual void writeTo(uint8_t *buf) const {}
172
173 // Returns the section name if this is a section chunk.
174 // It is illegal to call this function on non-section chunks.
175 virtual StringRef getSectionName() const {
176 llvm_unreachable("unimplemented getSectionName");
177 }
178
179 // Windows-specific.
180 // Collect all locations that contain absolute addresses for base relocations.
181 virtual void getBaserels(std::vector<Baserel> *res) {}
182
183 virtual MachineTypes getMachine() const { return IMAGE_FILE_MACHINE_UNKNOWN; }
184
185 // Returns a human-readable name of this chunk. Chunks are unnamed chunks of
186 // bytes, so this is used only for logging or debugging.
187 virtual StringRef getDebugName() const { return ""; }
188
189 // Verify that chunk relocations are within their ranges.
190 virtual bool verifyRanges() { return true; };
191
192 // If needed, extend the chunk to ensure all relocations are within the
193 // allowed ranges. Return the additional space required for the extension.
194 virtual uint32_t extendRanges() { return 0; };
195
196 virtual Defined *getEntryThunk() const { return nullptr; };
197
198 static bool classof(const Chunk *c) { return c->kind() >= OtherKind; }
199
200protected:
201 NonSectionChunk(Kind k = OtherKind) : Chunk(k) {}
202};
203
204class NonSectionCodeChunk : public NonSectionChunk {
205public:
206 virtual uint32_t getOutputCharacteristics() const override {
207 return llvm::COFF::IMAGE_SCN_MEM_READ | llvm::COFF::IMAGE_SCN_MEM_EXECUTE;
208 }
209
210protected:
211 NonSectionCodeChunk(Kind k = OtherKind) : NonSectionChunk(k) {}
212};
213
214// MinGW specific; information about one individual location in the image
215// that needs to be fixed up at runtime after loading. This represents
216// one individual element in the PseudoRelocTableChunk table.
217class RuntimePseudoReloc {
218public:
219 RuntimePseudoReloc(Defined *sym, SectionChunk *target, uint32_t targetOffset,
220 int flags)
221 : sym(sym), target(target), targetOffset(targetOffset), flags(flags) {}
222
223 Defined *sym;
224 SectionChunk *target;
225 uint32_t targetOffset;
226 // The Flags field contains the size of the relocation, in bits. No other
227 // flags are currently defined.
228 int flags;
229};
230
231// A chunk corresponding a section of an input file.
232class SectionChunk : public Chunk {
233 // Identical COMDAT Folding feature accesses section internal data.
234 friend class ICF;
235
236public:
237 class symbol_iterator : public llvm::iterator_adaptor_base<
238 symbol_iterator, const coff_relocation *,
239 std::random_access_iterator_tag, Symbol *> {
240 friend SectionChunk;
241
242 ObjFile *file;
243
244 symbol_iterator(ObjFile *file, const coff_relocation *i)
245 : symbol_iterator::iterator_adaptor_base(i), file(file) {}
246
247 public:
248 symbol_iterator() = default;
249
250 Symbol *operator*() const { return file->getSymbol(symbolIndex: I->SymbolTableIndex); }
251 };
252
253 SectionChunk(ObjFile *file, const coff_section *header, Kind k = SectionKind);
254 static bool classof(const Chunk *c) { return c->kind() <= SectionECKind; }
255 size_t getSize() const { return header->SizeOfRawData; }
256 ArrayRef<uint8_t> getContents() const;
257 void writeTo(uint8_t *buf) const;
258 MachineTypes getMachine() const;
259
260 // Defend against unsorted relocations. This may be overly conservative.
261 void sortRelocations();
262
263 // Write and relocate a portion of the section. This is intended to be called
264 // in a loop. Relocations must be sorted first.
265 void writeAndRelocateSubsection(ArrayRef<uint8_t> sec,
266 ArrayRef<uint8_t> subsec,
267 uint32_t &nextRelocIndex, uint8_t *buf) const;
268
269 uint32_t getOutputCharacteristics() const {
270 return header->Characteristics & (permMask | typeMask);
271 }
272 StringRef getSectionName() const {
273 return StringRef(sectionNameData, sectionNameSize);
274 }
275 void getBaserels(std::vector<Baserel> *res);
276 bool isCOMDAT() const;
277 void applyRelocation(uint8_t *off, const coff_relocation &rel) const;
278 void applyRelX64(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
279 uint64_t p, uint64_t imageBase) const;
280 void applyRelX86(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
281 uint64_t p, uint64_t imageBase) const;
282 void applyRelARM(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
283 uint64_t p, uint64_t imageBase) const;
284 void applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
285 uint64_t p, uint64_t imageBase) const;
286 void applyRelMIPS(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
287 uint64_t p, uint64_t imageBase) const;
288
289 void getRuntimePseudoRelocs(std::vector<RuntimePseudoReloc> &res);
290
291 // Called if the garbage collector decides to not include this chunk
292 // in a final output. It's supposed to print out a log message to stdout.
293 void printDiscardedMessage() const;
294
295 // Adds COMDAT associative sections to this COMDAT section. A chunk
296 // and its children are treated as a group by the garbage collector.
297 void addAssociative(SectionChunk *child);
298
299 StringRef getDebugName() const;
300
301 // True if this is a codeview debug info chunk. These will not be laid out in
302 // the image. Instead they will end up in the PDB, if one is requested.
303 bool isCodeView() const {
304 return getSectionName() == ".debug" || getSectionName().starts_with(Prefix: ".debug$");
305 }
306
307 // True if this is a DWARF debug info or exception handling chunk.
308 bool isDWARF() const {
309 return getSectionName().starts_with(Prefix: ".debug_") || getSectionName() == ".eh_frame";
310 }
311
312 // Allow iteration over the bodies of this chunk's relocated symbols.
313 llvm::iterator_range<symbol_iterator> symbols() const {
314 return llvm::make_range(x: symbol_iterator(file, relocsData),
315 y: symbol_iterator(file, relocsData + relocsSize));
316 }
317
318 ArrayRef<coff_relocation> getRelocs() const {
319 return llvm::ArrayRef(relocsData, relocsSize);
320 }
321
322 // Reloc setter used by ARM range extension thunk insertion.
323 void setRelocs(ArrayRef<coff_relocation> newRelocs) {
324 relocsData = newRelocs.data();
325 relocsSize = newRelocs.size();
326 assert(relocsSize == newRelocs.size() && "reloc size truncation");
327 }
328
329 // Single linked list iterator for associated comdat children.
330 class AssociatedIterator
331 : public llvm::iterator_facade_base<
332 AssociatedIterator, std::forward_iterator_tag, SectionChunk> {
333 public:
334 AssociatedIterator() = default;
335 AssociatedIterator(SectionChunk *head) : cur(head) {}
336 bool operator==(const AssociatedIterator &r) const { return cur == r.cur; }
337 // FIXME: Wrong const-ness, but it makes filter ranges work.
338 SectionChunk &operator*() const { return *cur; }
339 SectionChunk &operator*() { return *cur; }
340 AssociatedIterator &operator++() {
341 cur = cur->assocChildren;
342 return *this;
343 }
344
345 private:
346 SectionChunk *cur = nullptr;
347 };
348
349 // Allow iteration over the associated child chunks for this section.
350 llvm::iterator_range<AssociatedIterator> children() const {
351 // Associated sections do not have children. The assocChildren field is
352 // part of the parent's list of children.
353 bool isAssoc = selection == llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
354 return llvm::make_range(
355 x: AssociatedIterator(isAssoc ? nullptr : assocChildren),
356 y: AssociatedIterator(nullptr));
357 }
358
359 // The section ID this chunk belongs to in its Obj.
360 uint32_t getSectionNumber() const;
361
362 ArrayRef<uint8_t> consumeDebugMagic();
363
364 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> data,
365 StringRef sectionName);
366
367 static SectionChunk *findByName(ArrayRef<SectionChunk *> sections,
368 StringRef name);
369
370 // The file that this chunk was created from.
371 ObjFile *file;
372
373 // Pointer to the COFF section header in the input file.
374 const coff_section *header;
375
376 // The COMDAT leader symbol if this is a COMDAT chunk.
377 DefinedRegular *sym = nullptr;
378
379 // The CRC of the contents as described in the COFF spec 4.5.5.
380 // Auxiliary Format 5: Section Definitions. Used for ICF.
381 uint32_t checksum = 0;
382
383 // Used by the garbage collector.
384 bool live;
385
386 // Whether this section needs to be kept distinct from other sections during
387 // ICF. This is set by the driver using address-significance tables.
388 bool keepUnique = false;
389
390 // The COMDAT selection if this is a COMDAT chunk.
391 llvm::COFF::COMDATType selection = (llvm::COFF::COMDATType)0;
392
393 // A pointer pointing to a replacement for this chunk.
394 // Initially it points to "this" object. If this chunk is merged
395 // with other chunk by ICF, it points to another chunk,
396 // and this chunk is considered as dead.
397 SectionChunk *repl;
398
399 void replace(SectionChunk *other);
400
401private:
402 SectionChunk *assocChildren = nullptr;
403
404 // Used for ICF (Identical COMDAT Folding)
405 uint32_t eqClass[2] = {0, 0};
406
407 // Relocations for this section. Size is stored below.
408 const coff_relocation *relocsData;
409
410 // Section name string. Size is stored below.
411 const char *sectionNameData;
412
413 uint32_t relocsSize = 0;
414 uint32_t sectionNameSize = 0;
415};
416
417// A section chunk corresponding a section of an EC input file.
418class SectionChunkEC final : public SectionChunk {
419public:
420 static bool classof(const Chunk *c) { return c->kind() == SectionECKind; }
421
422 SectionChunkEC(ObjFile *file, const coff_section *header)
423 : SectionChunk(file, header, SectionECKind) {}
424 Defined *entryThunk = nullptr;
425};
426
427// Inline methods to implement faux-virtual dispatch for SectionChunk.
428
429inline size_t Chunk::getSize() const {
430 if (isa<SectionChunk>(Val: this))
431 return static_cast<const SectionChunk *>(this)->getSize();
432 return static_cast<const NonSectionChunk *>(this)->getSize();
433}
434
435inline uint32_t Chunk::getOutputCharacteristics() const {
436 if (isa<SectionChunk>(Val: this))
437 return static_cast<const SectionChunk *>(this)->getOutputCharacteristics();
438 return static_cast<const NonSectionChunk *>(this)->getOutputCharacteristics();
439}
440
441inline void Chunk::writeTo(uint8_t *buf) const {
442 if (isa<SectionChunk>(Val: this))
443 static_cast<const SectionChunk *>(this)->writeTo(buf);
444 else
445 static_cast<const NonSectionChunk *>(this)->writeTo(buf);
446}
447
448inline StringRef Chunk::getSectionName() const {
449 if (isa<SectionChunk>(Val: this))
450 return static_cast<const SectionChunk *>(this)->getSectionName();
451 return static_cast<const NonSectionChunk *>(this)->getSectionName();
452}
453
454inline void Chunk::getBaserels(std::vector<Baserel> *res) {
455 if (isa<SectionChunk>(Val: this))
456 static_cast<SectionChunk *>(this)->getBaserels(res);
457 else
458 static_cast<NonSectionChunk *>(this)->getBaserels(res);
459}
460
461inline StringRef Chunk::getDebugName() const {
462 if (isa<SectionChunk>(Val: this))
463 return static_cast<const SectionChunk *>(this)->getDebugName();
464 return static_cast<const NonSectionChunk *>(this)->getDebugName();
465}
466
467inline MachineTypes Chunk::getMachine() const {
468 if (isa<SectionChunk>(Val: this))
469 return static_cast<const SectionChunk *>(this)->getMachine();
470 return static_cast<const NonSectionChunk *>(this)->getMachine();
471}
472
473inline llvm::Triple::ArchType Chunk::getArch() const {
474 return llvm::getMachineArchType(machine: getMachine());
475}
476
477inline std::optional<chpe_range_type> Chunk::getArm64ECRangeType() const {
478 // Data sections don't need codemap entries.
479 if (!(getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE))
480 return std::nullopt;
481
482 switch (getMachine()) {
483 case AMD64:
484 return chpe_range_type::Amd64;
485 case ARM64EC:
486 return chpe_range_type::Arm64EC;
487 default:
488 return chpe_range_type::Arm64;
489 }
490}
491
492// This class is used to implement an lld-specific feature (not implemented in
493// MSVC) that minimizes the output size by finding string literals sharing tail
494// parts and merging them.
495//
496// If string tail merging is enabled and a section is identified as containing a
497// string literal, it is added to a MergeChunk with an appropriate alignment.
498// The MergeChunk then tail merges the strings using the StringTableBuilder
499// class and assigns RVAs and section offsets to each of the member chunks based
500// on the offsets assigned by the StringTableBuilder.
501class MergeChunk : public NonSectionChunk {
502public:
503 MergeChunk(uint32_t alignment);
504 static void addSection(COFFLinkerContext &ctx, SectionChunk *c);
505 void finalizeContents();
506 void assignSubsectionRVAs();
507
508 uint32_t getOutputCharacteristics() const override;
509 StringRef getSectionName() const override { return ".rdata"; }
510 size_t getSize() const override;
511 void writeTo(uint8_t *buf) const override;
512
513 std::vector<SectionChunk *> sections;
514
515private:
516 llvm::StringTableBuilder builder;
517 bool finalized = false;
518};
519
520// A chunk for common symbols. Common chunks don't have actual data.
521class CommonChunk : public NonSectionChunk {
522public:
523 CommonChunk(const COFFSymbolRef sym);
524 size_t getSize() const override { return sym.getValue(); }
525 uint32_t getOutputCharacteristics() const override;
526 StringRef getSectionName() const override { return ".bss"; }
527
528 bool live;
529
530private:
531 const COFFSymbolRef sym;
532};
533
534// A chunk for linker-created strings.
535class StringChunk : public NonSectionChunk {
536public:
537 explicit StringChunk(StringRef s) : str(s) {}
538 size_t getSize() const override { return str.size() + 1; }
539 void writeTo(uint8_t *buf) const override;
540
541private:
542 StringRef str;
543};
544
545static const uint8_t importThunkX86[] = {
546 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // JMP *0x0
547};
548
549static const uint8_t importThunkARM[] = {
550 0x40, 0xf2, 0x00, 0x0c, // mov.w ip, #0
551 0xc0, 0xf2, 0x00, 0x0c, // mov.t ip, #0
552 0xdc, 0xf8, 0x00, 0xf0, // ldr.w pc, [ip]
553};
554
555static const uint8_t importThunkARM64[] = {
556 0x10, 0x00, 0x00, 0x90, // adrp x16, #0
557 0x10, 0x02, 0x40, 0xf9, // ldr x16, [x16]
558 0x00, 0x02, 0x1f, 0xd6, // br x16
559};
560
561static const uint8_t importThunkARM64EC[] = {
562 0x0b, 0x00, 0x00, 0x90, // adrp x11, 0x0
563 0x6b, 0x01, 0x40, 0xf9, // ldr x11, [x11]
564 0x0a, 0x00, 0x00, 0x90, // adrp x10, 0x0
565 0x4a, 0x01, 0x00, 0x91, // add x10, x10, #0x0
566 0x00, 0x00, 0x00, 0x14 // b 0x0
567};
568
569// Windows-specific.
570// A chunk for DLL import jump table entry. In a final output, its
571// contents will be a JMP instruction to some __imp_ symbol.
572class ImportThunkChunk : public NonSectionCodeChunk {
573public:
574 ImportThunkChunk(COFFLinkerContext &ctx, Defined *s);
575 static bool classof(const Chunk *c) { return c->kind() == ImportThunkKind; }
576
577 // We track the usage of the thunk symbol separately from the import file
578 // to avoid generating unnecessary thunks.
579 bool live;
580
581protected:
582 Defined *impSymbol;
583 COFFLinkerContext &ctx;
584};
585
586class ImportThunkChunkX64 : public ImportThunkChunk {
587public:
588 explicit ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s);
589 size_t getSize() const override { return sizeof(importThunkX86); }
590 void writeTo(uint8_t *buf) const override;
591 MachineTypes getMachine() const override { return AMD64; }
592};
593
594class ImportThunkChunkX86 : public ImportThunkChunk {
595public:
596 explicit ImportThunkChunkX86(COFFLinkerContext &ctx, Defined *s)
597 : ImportThunkChunk(ctx, s) {}
598 size_t getSize() const override { return sizeof(importThunkX86); }
599 void getBaserels(std::vector<Baserel> *res) override;
600 void writeTo(uint8_t *buf) const override;
601 MachineTypes getMachine() const override { return I386; }
602};
603
604class ImportThunkChunkARM : public ImportThunkChunk {
605public:
606 explicit ImportThunkChunkARM(COFFLinkerContext &ctx, Defined *s)
607 : ImportThunkChunk(ctx, s) {
608 setAlignment(2);
609 }
610 size_t getSize() const override { return sizeof(importThunkARM); }
611 void getBaserels(std::vector<Baserel> *res) override;
612 void writeTo(uint8_t *buf) const override;
613 MachineTypes getMachine() const override { return ARMNT; }
614};
615
616class ImportThunkChunkARM64 : public ImportThunkChunk {
617public:
618 explicit ImportThunkChunkARM64(COFFLinkerContext &ctx, Defined *s,
619 MachineTypes machine)
620 : ImportThunkChunk(ctx, s), machine(machine) {
621 setAlignment(4);
622 }
623 size_t getSize() const override { return sizeof(importThunkARM64); }
624 void writeTo(uint8_t *buf) const override;
625 MachineTypes getMachine() const override { return machine; }
626
627private:
628 MachineTypes machine;
629};
630
631// ARM64EC __impchk_* thunk implementation.
632// Performs an indirect call to an imported function pointer
633// using the __icall_helper_arm64ec helper function.
634class ImportThunkChunkARM64EC : public ImportThunkChunk {
635public:
636 explicit ImportThunkChunkARM64EC(ImportFile *file);
637 size_t getSize() const override;
638 MachineTypes getMachine() const override { return ARM64EC; }
639 void writeTo(uint8_t *buf) const override;
640 bool verifyRanges() override;
641 uint32_t extendRanges() override;
642
643 Defined *exitThunk = nullptr;
644 Defined *sym = nullptr;
645 bool extended = false;
646
647private:
648 ImportFile *file;
649};
650
651class RangeExtensionThunkARM : public NonSectionCodeChunk {
652public:
653 explicit RangeExtensionThunkARM(COFFLinkerContext &ctx, Defined *t)
654 : target(t), ctx(ctx) {
655 setAlignment(2);
656 }
657 size_t getSize() const override;
658 void writeTo(uint8_t *buf) const override;
659 MachineTypes getMachine() const override { return ARMNT; }
660
661 Defined *target;
662
663private:
664 COFFLinkerContext &ctx;
665};
666
667// A ragnge extension thunk used for both ARM64EC and ARM64 machine types.
668class RangeExtensionThunkARM64 : public NonSectionCodeChunk {
669public:
670 explicit RangeExtensionThunkARM64(MachineTypes machine, Defined *t)
671 : target(t), machine(machine) {
672 setAlignment(4);
673 assert(llvm::COFF::isAnyArm64(machine));
674 }
675 size_t getSize() const override;
676 void writeTo(uint8_t *buf) const override;
677 MachineTypes getMachine() const override { return machine; }
678
679 Defined *target;
680
681private:
682 MachineTypes machine;
683};
684
685// A chunk used to guarantee the same address for a function in both views of
686// a hybrid image. Similar to RangeExtensionThunkARM64 chunks, it calls the
687// target symbol using a BR instruction. It also contains an entry thunk for EC
688// compatibility and additional ARM64X relocations that swap targets between
689// views.
690class SameAddressThunkARM64EC : public RangeExtensionThunkARM64 {
691public:
692 explicit SameAddressThunkARM64EC(Defined *t, Defined *hybridTarget,
693 Defined *entryThunk)
694 : RangeExtensionThunkARM64(ARM64EC, t), hybridTarget(hybridTarget),
695 entryThunk(entryThunk) {}
696
697 Defined *getEntryThunk() const override { return entryThunk; }
698 void setDynamicRelocs(COFFLinkerContext &ctx) const;
699
700private:
701 Defined *hybridTarget;
702 Defined *entryThunk;
703};
704
705// Windows-specific.
706// See comments for DefinedLocalImport class.
707class LocalImportChunk : public NonSectionChunk {
708public:
709 explicit LocalImportChunk(COFFLinkerContext &ctx, Defined *s);
710 size_t getSize() const override;
711 void getBaserels(std::vector<Baserel> *res) override;
712 void writeTo(uint8_t *buf) const override;
713
714private:
715 Defined *sym;
716 COFFLinkerContext &ctx;
717};
718
719// Duplicate RVAs are not allowed in RVA tables, so unique symbols by chunk and
720// offset into the chunk. Order does not matter as the RVA table will be sorted
721// later.
722struct ChunkAndOffset {
723 Chunk *inputChunk;
724 uint32_t offset;
725
726 struct DenseMapInfo {
727 static unsigned getHashValue(const ChunkAndOffset &co) {
728 return llvm::DenseMapInfo<std::pair<Chunk *, uint32_t>>::getHashValue(
729 PairVal: {co.inputChunk, co.offset});
730 }
731 static bool isEqual(const ChunkAndOffset &lhs, const ChunkAndOffset &rhs) {
732 return lhs.inputChunk == rhs.inputChunk && lhs.offset == rhs.offset;
733 }
734 };
735};
736
737using SymbolRVASet = llvm::DenseSet<ChunkAndOffset>;
738
739// Table which contains symbol RVAs. Used for /safeseh and /guard:cf.
740class RVATableChunk : public NonSectionChunk {
741public:
742 explicit RVATableChunk(SymbolRVASet s) : syms(std::move(s)) {}
743 size_t getSize() const override { return syms.size() * 4; }
744 void writeTo(uint8_t *buf) const override;
745
746private:
747 SymbolRVASet syms;
748};
749
750// Table which contains symbol RVAs with flags. Used for /guard:ehcont.
751class RVAFlagTableChunk : public NonSectionChunk {
752public:
753 explicit RVAFlagTableChunk(SymbolRVASet s) : syms(std::move(s)) {}
754 size_t getSize() const override { return syms.size() * 5; }
755 void writeTo(uint8_t *buf) const override;
756
757private:
758 SymbolRVASet syms;
759};
760
761// Windows-specific.
762// This class represents a block in .reloc section.
763// See the PE/COFF spec 5.6 for details.
764class BaserelChunk : public NonSectionChunk {
765public:
766 BaserelChunk(uint32_t page, Baserel *begin, Baserel *end);
767 size_t getSize() const override { return data.size(); }
768 void writeTo(uint8_t *buf) const override;
769
770private:
771 std::vector<uint8_t> data;
772};
773
774class Baserel {
775public:
776 Baserel(uint32_t v, uint8_t ty) : rva(v), type(ty) {}
777 explicit Baserel(uint32_t v, llvm::COFF::MachineTypes machine)
778 : Baserel(v, getDefaultType(machine)) {}
779 static uint8_t getDefaultType(llvm::COFF::MachineTypes machine);
780
781 uint32_t rva;
782 uint8_t type;
783};
784
785// This is a placeholder Chunk, to allow attaching a DefinedSynthetic to a
786// specific place in a section, without any data. This is used for the MinGW
787// specific symbol __RUNTIME_PSEUDO_RELOC_LIST_END__, even though the concept
788// of an empty chunk isn't MinGW specific.
789class EmptyChunk : public NonSectionChunk {
790public:
791 EmptyChunk() {}
792 size_t getSize() const override { return 0; }
793 void writeTo(uint8_t *buf) const override {}
794};
795
796class ECCodeMapEntry {
797public:
798 ECCodeMapEntry(Chunk *first, Chunk *last, chpe_range_type type)
799 : first(first), last(last), type(type) {}
800 Chunk *first;
801 Chunk *last;
802 chpe_range_type type;
803};
804
805// This is a chunk containing CHPE code map on EC targets. It's a table
806// of address ranges and their types.
807class ECCodeMapChunk : public NonSectionChunk {
808public:
809 ECCodeMapChunk(std::vector<ECCodeMapEntry> &map) : map(map) {}
810 size_t getSize() const override;
811 void writeTo(uint8_t *buf) const override;
812
813private:
814 std::vector<ECCodeMapEntry> &map;
815};
816
817class CHPECodeRangesChunk : public NonSectionChunk {
818public:
819 CHPECodeRangesChunk(std::vector<std::pair<Chunk *, Defined *>> &exportThunks)
820 : exportThunks(exportThunks) {}
821 size_t getSize() const override;
822 void writeTo(uint8_t *buf) const override;
823
824private:
825 std::vector<std::pair<Chunk *, Defined *>> &exportThunks;
826};
827
828class CHPERedirectionChunk : public NonSectionChunk {
829public:
830 CHPERedirectionChunk(std::vector<std::pair<Chunk *, Defined *>> &exportThunks)
831 : exportThunks(exportThunks) {}
832 size_t getSize() const override;
833 void writeTo(uint8_t *buf) const override;
834
835private:
836 std::vector<std::pair<Chunk *, Defined *>> &exportThunks;
837};
838
839static const uint8_t ECExportThunkCode[] = {
840 0x48, 0x8b, 0xc4, // movq %rsp, %rax
841 0x48, 0x89, 0x58, 0x20, // movq %rbx, 0x20(%rax)
842 0x55, // pushq %rbp
843 0x5d, // popq %rbp
844 0xe9, 0, 0, 0, 0, // jmp *0x0
845 0xcc, // int3
846 0xcc // int3
847};
848
849class ECExportThunkChunk : public NonSectionCodeChunk {
850public:
851 explicit ECExportThunkChunk(Defined *targetSym)
852 : NonSectionCodeChunk(ECExportThunkKind), target(targetSym) {}
853 static bool classof(const Chunk *c) { return c->kind() == ECExportThunkKind; }
854
855 size_t getSize() const override { return sizeof(ECExportThunkCode); };
856 void writeTo(uint8_t *buf) const override;
857 MachineTypes getMachine() const override { return AMD64; }
858
859 Defined *target;
860};
861
862// ARM64X relocation value, potentially relative to a symbol.
863class Arm64XRelocVal {
864public:
865 Arm64XRelocVal(uint64_t value = 0) : value(value) {}
866 Arm64XRelocVal(Defined *sym, int32_t offset = 0) : sym(sym), value(offset) {}
867 Arm64XRelocVal(const Chunk *chunk, int32_t offset = 0)
868 : chunk(chunk), value(offset) {}
869 uint64_t get() const;
870
871private:
872 Defined *sym = nullptr;
873 const Chunk *chunk = nullptr;
874 uint64_t value;
875};
876
877// ARM64X entry for dynamic relocations.
878class Arm64XDynamicRelocEntry {
879public:
880 Arm64XDynamicRelocEntry(llvm::COFF::Arm64XFixupType type, uint8_t size,
881 Arm64XRelocVal offset, Arm64XRelocVal value)
882 : offset(offset), value(value), type(type), size(size) {}
883
884 size_t getSize() const;
885 void writeTo(uint8_t *buf) const;
886
887 Arm64XRelocVal offset;
888 Arm64XRelocVal value;
889
890private:
891 llvm::COFF::Arm64XFixupType type;
892 uint8_t size;
893};
894
895// Dynamic relocation chunk containing ARM64X relocations for the hybrid image.
896class DynamicRelocsChunk : public NonSectionChunk {
897public:
898 DynamicRelocsChunk() {}
899 size_t getSize() const override { return size; }
900 void writeTo(uint8_t *buf) const override;
901 void finalize();
902
903 void add(llvm::COFF::Arm64XFixupType type, uint8_t size,
904 Arm64XRelocVal offset, Arm64XRelocVal value = Arm64XRelocVal()) {
905 arm64xRelocs.emplace_back(args&: type, args&: size, args&: offset, args&: value);
906 }
907
908 void set(Arm64XRelocVal offset, Arm64XRelocVal value);
909
910private:
911 std::vector<Arm64XDynamicRelocEntry> arm64xRelocs;
912 size_t size;
913};
914
915// MinGW specific, for the "automatic import of variables from DLLs" feature.
916// This provides the table of runtime pseudo relocations, for variable
917// references that turned out to need to be imported from a DLL even though
918// the reference didn't use the dllimport attribute. The MinGW runtime will
919// process this table after loading, before handling control over to user
920// code.
921class PseudoRelocTableChunk : public NonSectionChunk {
922public:
923 PseudoRelocTableChunk(std::vector<RuntimePseudoReloc> &relocs)
924 : relocs(std::move(relocs)) {
925 setAlignment(4);
926 }
927 size_t getSize() const override;
928 void writeTo(uint8_t *buf) const override;
929
930private:
931 std::vector<RuntimePseudoReloc> relocs;
932};
933
934// MinGW specific. A Chunk that contains one pointer-sized absolute value.
935class AbsolutePointerChunk : public NonSectionChunk {
936public:
937 AbsolutePointerChunk(SymbolTable &symtab, uint64_t value)
938 : value(value), symtab(symtab) {
939 setAlignment(getSize());
940 }
941 size_t getSize() const override;
942 void writeTo(uint8_t *buf) const override;
943 MachineTypes getMachine() const override;
944
945private:
946 uint64_t value;
947 SymbolTable &symtab;
948};
949
950// Return true if this file has the hotpatch flag set to true in the S_COMPILE3
951// record in codeview debug info. Also returns true for some thunks synthesized
952// by the linker.
953inline bool Chunk::isHotPatchable() const {
954 if (auto *sc = dyn_cast<SectionChunk>(Val: this))
955 return sc->file->hotPatchable;
956 else if (isa<ImportThunkChunk>(Val: this))
957 return true;
958 return false;
959}
960
961inline Defined *Chunk::getEntryThunk() const {
962 if (auto *c = dyn_cast<const SectionChunkEC>(Val: this))
963 return c->entryThunk;
964 if (auto *c = dyn_cast<const NonSectionChunk>(Val: this))
965 return c->getEntryThunk();
966 return nullptr;
967}
968
969inline void Chunk::setEntryThunk(Defined *entryThunk) {
970 if (auto c = dyn_cast<SectionChunkEC>(Val: this))
971 c->entryThunk = entryThunk;
972}
973
974void applyMOV32T(uint8_t *off, uint32_t v);
975void applyBranch24T(uint8_t *off, int32_t v);
976
977void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift);
978void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit);
979void applyArm64Branch26(uint8_t *off, int64_t v);
980
981// Convenience class for initializing a coff_section with specific flags.
982class FakeSection {
983public:
984 FakeSection(int c) { section.Characteristics = c; }
985
986 coff_section section;
987};
988
989// Convenience class for initializing a SectionChunk with specific flags.
990class FakeSectionChunk {
991public:
992 FakeSectionChunk(const coff_section *section) : chunk(nullptr, section) {
993 // Comdats from LTO files can't be fully treated as regular comdats
994 // at this point; we don't know what size or contents they are going to
995 // have, so we can't do proper checking of such aspects of them.
996 chunk.selection = llvm::COFF::IMAGE_COMDAT_SELECT_ANY;
997 }
998
999 SectionChunk chunk;
1000};
1001
1002} // namespace lld::coff
1003
1004namespace llvm {
1005template <>
1006struct DenseMapInfo<lld::coff::ChunkAndOffset>
1007 : lld::coff::ChunkAndOffset::DenseMapInfo {};
1008}
1009
1010#endif
1011