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 { SectionKind, OtherKind, ImportThunkKind };
59 Kind kind() const { return chunkKind; }
60
61 // Returns the size of this chunk (even if this is a common or BSS.)
62 size_t getSize() const;
63
64 // Returns chunk alignment in power of two form. Value values are powers of
65 // two from 1 to 8192.
66 uint32_t getAlignment() const { return 1U << p2Align; }
67
68 // Update the chunk section alignment measured in bytes. Internally alignment
69 // is stored in log2.
70 void setAlignment(uint32_t align) {
71 // Treat zero byte alignment as 1 byte alignment.
72 align = align ? align : 1;
73 assert(llvm::isPowerOf2_32(align) && "alignment is not a power of 2");
74 p2Align = llvm::Log2_32(Value: align);
75 assert(p2Align <= Log2MaxSectionAlignment &&
76 "impossible requested alignment");
77 }
78
79 // Write this chunk to a mmap'ed file, assuming Buf is pointing to
80 // beginning of the file. Because this function may use RVA values
81 // of other chunks for relocations, you need to set them properly
82 // before calling this function.
83 void writeTo(uint8_t *buf) const;
84
85 // The writer sets and uses the addresses. In practice, PE images cannot be
86 // larger than 2GB. Chunks are always laid as part of the image, so Chunk RVAs
87 // can be stored with 32 bits.
88 uint32_t getRVA() const { return rva; }
89 void setRVA(uint64_t v) {
90 // This may truncate. The writer checks for overflow later.
91 rva = (uint32_t)v;
92 }
93
94 // Returns readable/writable/executable bits.
95 uint32_t getOutputCharacteristics() const;
96
97 // Returns the section name if this is a section chunk.
98 // It is illegal to call this function on non-section chunks.
99 StringRef getSectionName() const;
100
101 // An output section has pointers to chunks in the section, and each
102 // chunk has a back pointer to an output section.
103 void setOutputSectionIdx(uint16_t o) { osidx = o; }
104 uint16_t getOutputSectionIdx() const { return osidx; }
105
106 // Windows-specific.
107 // Collect all locations that contain absolute addresses for base relocations.
108 void getBaserels(std::vector<Baserel> *res);
109
110 // Returns a human-readable name of this chunk. Chunks are unnamed chunks of
111 // bytes, so this is used only for logging or debugging.
112 StringRef getDebugName() const;
113
114 // Return true if this file has the hotpatch flag set to true in the
115 // S_COMPILE3 record in codeview debug info. Also returns true for some thunks
116 // synthesized by the linker.
117 bool isHotPatchable() const;
118
119 MachineTypes getMachine() const;
120 llvm::Triple::ArchType getArch() const;
121 std::optional<chpe_range_type> getArm64ECRangeType() const;
122
123protected:
124 Chunk(Kind k = OtherKind) : chunkKind(k), hasData(true), p2Align(0) {}
125
126 const Kind chunkKind;
127
128public:
129 // Returns true if this has non-zero data. BSS chunks return
130 // false. If false is returned, the space occupied by this chunk
131 // will be filled with zeros. Corresponds to the
132 // IMAGE_SCN_CNT_UNINITIALIZED_DATA section characteristic bit.
133 uint8_t hasData : 1;
134
135public:
136 // The alignment of this chunk, stored in log2 form. The writer uses the
137 // value.
138 uint8_t p2Align : 7;
139
140 // The output section index for this chunk. The first valid section number is
141 // one.
142 uint16_t osidx = 0;
143
144 // The RVA of this chunk in the output. The writer sets a value.
145 uint32_t rva = 0;
146};
147
148class NonSectionChunk : public Chunk {
149public:
150 virtual ~NonSectionChunk() = default;
151
152 // Returns the size of this chunk (even if this is a common or BSS.)
153 virtual size_t getSize() const = 0;
154
155 virtual uint32_t getOutputCharacteristics() const { return 0; }
156
157 // Write this chunk to a mmap'ed file, assuming Buf is pointing to
158 // beginning of the file. Because this function may use RVA values
159 // of other chunks for relocations, you need to set them properly
160 // before calling this function.
161 virtual void writeTo(uint8_t *buf) const {}
162
163 // Returns the section name if this is a section chunk.
164 // It is illegal to call this function on non-section chunks.
165 virtual StringRef getSectionName() const {
166 llvm_unreachable("unimplemented getSectionName");
167 }
168
169 // Windows-specific.
170 // Collect all locations that contain absolute addresses for base relocations.
171 virtual void getBaserels(std::vector<Baserel> *res) {}
172
173 virtual MachineTypes getMachine() const { return IMAGE_FILE_MACHINE_UNKNOWN; }
174
175 // Returns a human-readable name of this chunk. Chunks are unnamed chunks of
176 // bytes, so this is used only for logging or debugging.
177 virtual StringRef getDebugName() const { return ""; }
178
179 static bool classof(const Chunk *c) { return c->kind() != SectionKind; }
180
181protected:
182 NonSectionChunk(Kind k = OtherKind) : Chunk(k) {}
183};
184
185class NonSectionCodeChunk : public NonSectionChunk {
186public:
187 virtual uint32_t getOutputCharacteristics() const override {
188 return llvm::COFF::IMAGE_SCN_MEM_READ | llvm::COFF::IMAGE_SCN_MEM_EXECUTE;
189 }
190
191protected:
192 NonSectionCodeChunk(Kind k = OtherKind) : NonSectionChunk(k) {}
193};
194
195// MinGW specific; information about one individual location in the image
196// that needs to be fixed up at runtime after loading. This represents
197// one individual element in the PseudoRelocTableChunk table.
198class RuntimePseudoReloc {
199public:
200 RuntimePseudoReloc(Defined *sym, SectionChunk *target, uint32_t targetOffset,
201 int flags)
202 : sym(sym), target(target), targetOffset(targetOffset), flags(flags) {}
203
204 Defined *sym;
205 SectionChunk *target;
206 uint32_t targetOffset;
207 // The Flags field contains the size of the relocation, in bits. No other
208 // flags are currently defined.
209 int flags;
210};
211
212// A chunk corresponding a section of an input file.
213class SectionChunk final : public Chunk {
214 // Identical COMDAT Folding feature accesses section internal data.
215 friend class ICF;
216
217public:
218 class symbol_iterator : public llvm::iterator_adaptor_base<
219 symbol_iterator, const coff_relocation *,
220 std::random_access_iterator_tag, Symbol *> {
221 friend SectionChunk;
222
223 ObjFile *file;
224
225 symbol_iterator(ObjFile *file, const coff_relocation *i)
226 : symbol_iterator::iterator_adaptor_base(i), file(file) {}
227
228 public:
229 symbol_iterator() = default;
230
231 Symbol *operator*() const { return file->getSymbol(symbolIndex: I->SymbolTableIndex); }
232 };
233
234 SectionChunk(ObjFile *file, const coff_section *header);
235 static bool classof(const Chunk *c) { return c->kind() == SectionKind; }
236 size_t getSize() const { return header->SizeOfRawData; }
237 ArrayRef<uint8_t> getContents() const;
238 void writeTo(uint8_t *buf) const;
239
240 MachineTypes getMachine() const { return file->getMachineType(); }
241
242 // Defend against unsorted relocations. This may be overly conservative.
243 void sortRelocations();
244
245 // Write and relocate a portion of the section. This is intended to be called
246 // in a loop. Relocations must be sorted first.
247 void writeAndRelocateSubsection(ArrayRef<uint8_t> sec,
248 ArrayRef<uint8_t> subsec,
249 uint32_t &nextRelocIndex, uint8_t *buf) const;
250
251 uint32_t getOutputCharacteristics() const {
252 return header->Characteristics & (permMask | typeMask);
253 }
254 StringRef getSectionName() const {
255 return StringRef(sectionNameData, sectionNameSize);
256 }
257 void getBaserels(std::vector<Baserel> *res);
258 bool isCOMDAT() const;
259 void applyRelocation(uint8_t *off, const coff_relocation &rel) const;
260 void applyRelX64(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
261 uint64_t p, uint64_t imageBase) const;
262 void applyRelX86(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
263 uint64_t p, uint64_t imageBase) const;
264 void applyRelARM(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
265 uint64_t p, uint64_t imageBase) const;
266 void applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os, uint64_t s,
267 uint64_t p, uint64_t imageBase) const;
268
269 void getRuntimePseudoRelocs(std::vector<RuntimePseudoReloc> &res);
270
271 // Called if the garbage collector decides to not include this chunk
272 // in a final output. It's supposed to print out a log message to stdout.
273 void printDiscardedMessage() const;
274
275 // Adds COMDAT associative sections to this COMDAT section. A chunk
276 // and its children are treated as a group by the garbage collector.
277 void addAssociative(SectionChunk *child);
278
279 StringRef getDebugName() const;
280
281 // True if this is a codeview debug info chunk. These will not be laid out in
282 // the image. Instead they will end up in the PDB, if one is requested.
283 bool isCodeView() const {
284 return getSectionName() == ".debug" || getSectionName().starts_with(Prefix: ".debug$");
285 }
286
287 // True if this is a DWARF debug info or exception handling chunk.
288 bool isDWARF() const {
289 return getSectionName().starts_with(Prefix: ".debug_") || getSectionName() == ".eh_frame";
290 }
291
292 // Allow iteration over the bodies of this chunk's relocated symbols.
293 llvm::iterator_range<symbol_iterator> symbols() const {
294 return llvm::make_range(x: symbol_iterator(file, relocsData),
295 y: symbol_iterator(file, relocsData + relocsSize));
296 }
297
298 ArrayRef<coff_relocation> getRelocs() const {
299 return llvm::ArrayRef(relocsData, relocsSize);
300 }
301
302 // Reloc setter used by ARM range extension thunk insertion.
303 void setRelocs(ArrayRef<coff_relocation> newRelocs) {
304 relocsData = newRelocs.data();
305 relocsSize = newRelocs.size();
306 assert(relocsSize == newRelocs.size() && "reloc size truncation");
307 }
308
309 // Single linked list iterator for associated comdat children.
310 class AssociatedIterator
311 : public llvm::iterator_facade_base<
312 AssociatedIterator, std::forward_iterator_tag, SectionChunk> {
313 public:
314 AssociatedIterator() = default;
315 AssociatedIterator(SectionChunk *head) : cur(head) {}
316 bool operator==(const AssociatedIterator &r) const { return cur == r.cur; }
317 // FIXME: Wrong const-ness, but it makes filter ranges work.
318 SectionChunk &operator*() const { return *cur; }
319 SectionChunk &operator*() { return *cur; }
320 AssociatedIterator &operator++() {
321 cur = cur->assocChildren;
322 return *this;
323 }
324
325 private:
326 SectionChunk *cur = nullptr;
327 };
328
329 // Allow iteration over the associated child chunks for this section.
330 llvm::iterator_range<AssociatedIterator> children() const {
331 // Associated sections do not have children. The assocChildren field is
332 // part of the parent's list of children.
333 bool isAssoc = selection == llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
334 return llvm::make_range(
335 x: AssociatedIterator(isAssoc ? nullptr : assocChildren),
336 y: AssociatedIterator(nullptr));
337 }
338
339 // The section ID this chunk belongs to in its Obj.
340 uint32_t getSectionNumber() const;
341
342 ArrayRef<uint8_t> consumeDebugMagic();
343
344 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> data,
345 StringRef sectionName);
346
347 static SectionChunk *findByName(ArrayRef<SectionChunk *> sections,
348 StringRef name);
349
350 // The file that this chunk was created from.
351 ObjFile *file;
352
353 // Pointer to the COFF section header in the input file.
354 const coff_section *header;
355
356 // The COMDAT leader symbol if this is a COMDAT chunk.
357 DefinedRegular *sym = nullptr;
358
359 // The CRC of the contents as described in the COFF spec 4.5.5.
360 // Auxiliary Format 5: Section Definitions. Used for ICF.
361 uint32_t checksum = 0;
362
363 // Used by the garbage collector.
364 bool live;
365
366 // Whether this section needs to be kept distinct from other sections during
367 // ICF. This is set by the driver using address-significance tables.
368 bool keepUnique = false;
369
370 // The COMDAT selection if this is a COMDAT chunk.
371 llvm::COFF::COMDATType selection = (llvm::COFF::COMDATType)0;
372
373 // A pointer pointing to a replacement for this chunk.
374 // Initially it points to "this" object. If this chunk is merged
375 // with other chunk by ICF, it points to another chunk,
376 // and this chunk is considered as dead.
377 SectionChunk *repl;
378
379private:
380 SectionChunk *assocChildren = nullptr;
381
382 // Used for ICF (Identical COMDAT Folding)
383 void replace(SectionChunk *other);
384 uint32_t eqClass[2] = {0, 0};
385
386 // Relocations for this section. Size is stored below.
387 const coff_relocation *relocsData;
388
389 // Section name string. Size is stored below.
390 const char *sectionNameData;
391
392 uint32_t relocsSize = 0;
393 uint32_t sectionNameSize = 0;
394};
395
396// Inline methods to implement faux-virtual dispatch for SectionChunk.
397
398inline size_t Chunk::getSize() const {
399 if (isa<SectionChunk>(Val: this))
400 return static_cast<const SectionChunk *>(this)->getSize();
401 return static_cast<const NonSectionChunk *>(this)->getSize();
402}
403
404inline uint32_t Chunk::getOutputCharacteristics() const {
405 if (isa<SectionChunk>(Val: this))
406 return static_cast<const SectionChunk *>(this)->getOutputCharacteristics();
407 return static_cast<const NonSectionChunk *>(this)->getOutputCharacteristics();
408}
409
410inline void Chunk::writeTo(uint8_t *buf) const {
411 if (isa<SectionChunk>(Val: this))
412 static_cast<const SectionChunk *>(this)->writeTo(buf);
413 else
414 static_cast<const NonSectionChunk *>(this)->writeTo(buf);
415}
416
417inline StringRef Chunk::getSectionName() const {
418 if (isa<SectionChunk>(Val: this))
419 return static_cast<const SectionChunk *>(this)->getSectionName();
420 return static_cast<const NonSectionChunk *>(this)->getSectionName();
421}
422
423inline void Chunk::getBaserels(std::vector<Baserel> *res) {
424 if (isa<SectionChunk>(Val: this))
425 static_cast<SectionChunk *>(this)->getBaserels(res);
426 else
427 static_cast<NonSectionChunk *>(this)->getBaserels(res);
428}
429
430inline StringRef Chunk::getDebugName() const {
431 if (isa<SectionChunk>(Val: this))
432 return static_cast<const SectionChunk *>(this)->getDebugName();
433 return static_cast<const NonSectionChunk *>(this)->getDebugName();
434}
435
436inline MachineTypes Chunk::getMachine() const {
437 if (isa<SectionChunk>(Val: this))
438 return static_cast<const SectionChunk *>(this)->getMachine();
439 return static_cast<const NonSectionChunk *>(this)->getMachine();
440}
441
442inline llvm::Triple::ArchType Chunk::getArch() const {
443 return llvm::getMachineArchType(machine: getMachine());
444}
445
446inline std::optional<chpe_range_type> Chunk::getArm64ECRangeType() const {
447 // Data sections don't need codemap entries.
448 if (!(getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE))
449 return std::nullopt;
450
451 switch (getMachine()) {
452 case AMD64:
453 return chpe_range_type::Amd64;
454 case ARM64EC:
455 return chpe_range_type::Arm64EC;
456 default:
457 return chpe_range_type::Arm64;
458 }
459}
460
461// This class is used to implement an lld-specific feature (not implemented in
462// MSVC) that minimizes the output size by finding string literals sharing tail
463// parts and merging them.
464//
465// If string tail merging is enabled and a section is identified as containing a
466// string literal, it is added to a MergeChunk with an appropriate alignment.
467// The MergeChunk then tail merges the strings using the StringTableBuilder
468// class and assigns RVAs and section offsets to each of the member chunks based
469// on the offsets assigned by the StringTableBuilder.
470class MergeChunk : public NonSectionChunk {
471public:
472 MergeChunk(uint32_t alignment);
473 static void addSection(COFFLinkerContext &ctx, SectionChunk *c);
474 void finalizeContents();
475 void assignSubsectionRVAs();
476
477 uint32_t getOutputCharacteristics() const override;
478 StringRef getSectionName() const override { return ".rdata"; }
479 size_t getSize() const override;
480 void writeTo(uint8_t *buf) const override;
481
482 std::vector<SectionChunk *> sections;
483
484private:
485 llvm::StringTableBuilder builder;
486 bool finalized = false;
487};
488
489// A chunk for common symbols. Common chunks don't have actual data.
490class CommonChunk : public NonSectionChunk {
491public:
492 CommonChunk(const COFFSymbolRef sym);
493 size_t getSize() const override { return sym.getValue(); }
494 uint32_t getOutputCharacteristics() const override;
495 StringRef getSectionName() const override { return ".bss"; }
496
497private:
498 const COFFSymbolRef sym;
499};
500
501// A chunk for linker-created strings.
502class StringChunk : public NonSectionChunk {
503public:
504 explicit StringChunk(StringRef s) : str(s) {}
505 size_t getSize() const override { return str.size() + 1; }
506 void writeTo(uint8_t *buf) const override;
507
508private:
509 StringRef str;
510};
511
512static const uint8_t importThunkX86[] = {
513 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // JMP *0x0
514};
515
516static const uint8_t importThunkARM[] = {
517 0x40, 0xf2, 0x00, 0x0c, // mov.w ip, #0
518 0xc0, 0xf2, 0x00, 0x0c, // mov.t ip, #0
519 0xdc, 0xf8, 0x00, 0xf0, // ldr.w pc, [ip]
520};
521
522static const uint8_t importThunkARM64[] = {
523 0x10, 0x00, 0x00, 0x90, // adrp x16, #0
524 0x10, 0x02, 0x40, 0xf9, // ldr x16, [x16]
525 0x00, 0x02, 0x1f, 0xd6, // br x16
526};
527
528// Windows-specific.
529// A chunk for DLL import jump table entry. In a final output, its
530// contents will be a JMP instruction to some __imp_ symbol.
531class ImportThunkChunk : public NonSectionCodeChunk {
532public:
533 ImportThunkChunk(COFFLinkerContext &ctx, Defined *s)
534 : NonSectionCodeChunk(ImportThunkKind), impSymbol(s), ctx(ctx) {}
535 static bool classof(const Chunk *c) { return c->kind() == ImportThunkKind; }
536
537protected:
538 Defined *impSymbol;
539 COFFLinkerContext &ctx;
540};
541
542class ImportThunkChunkX64 : public ImportThunkChunk {
543public:
544 explicit ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s);
545 size_t getSize() const override { return sizeof(importThunkX86); }
546 void writeTo(uint8_t *buf) const override;
547 MachineTypes getMachine() const override { return AMD64; }
548};
549
550class ImportThunkChunkX86 : public ImportThunkChunk {
551public:
552 explicit ImportThunkChunkX86(COFFLinkerContext &ctx, Defined *s)
553 : ImportThunkChunk(ctx, s) {}
554 size_t getSize() const override { return sizeof(importThunkX86); }
555 void getBaserels(std::vector<Baserel> *res) override;
556 void writeTo(uint8_t *buf) const override;
557 MachineTypes getMachine() const override { return I386; }
558};
559
560class ImportThunkChunkARM : public ImportThunkChunk {
561public:
562 explicit ImportThunkChunkARM(COFFLinkerContext &ctx, Defined *s)
563 : ImportThunkChunk(ctx, s) {
564 setAlignment(2);
565 }
566 size_t getSize() const override { return sizeof(importThunkARM); }
567 void getBaserels(std::vector<Baserel> *res) override;
568 void writeTo(uint8_t *buf) const override;
569 MachineTypes getMachine() const override { return ARMNT; }
570};
571
572class ImportThunkChunkARM64 : public ImportThunkChunk {
573public:
574 explicit ImportThunkChunkARM64(COFFLinkerContext &ctx, Defined *s)
575 : ImportThunkChunk(ctx, s) {
576 setAlignment(4);
577 }
578 size_t getSize() const override { return sizeof(importThunkARM64); }
579 void writeTo(uint8_t *buf) const override;
580 MachineTypes getMachine() const override { return ARM64; }
581};
582
583class RangeExtensionThunkARM : public NonSectionCodeChunk {
584public:
585 explicit RangeExtensionThunkARM(COFFLinkerContext &ctx, Defined *t)
586 : target(t), ctx(ctx) {
587 setAlignment(2);
588 }
589 size_t getSize() const override;
590 void writeTo(uint8_t *buf) const override;
591 MachineTypes getMachine() const override { return ARMNT; }
592
593 Defined *target;
594
595private:
596 COFFLinkerContext &ctx;
597};
598
599class RangeExtensionThunkARM64 : public NonSectionCodeChunk {
600public:
601 explicit RangeExtensionThunkARM64(COFFLinkerContext &ctx, Defined *t)
602 : target(t), ctx(ctx) {
603 setAlignment(4);
604 }
605 size_t getSize() const override;
606 void writeTo(uint8_t *buf) const override;
607 MachineTypes getMachine() const override { return ARM64; }
608
609 Defined *target;
610
611private:
612 COFFLinkerContext &ctx;
613};
614
615// Windows-specific.
616// See comments for DefinedLocalImport class.
617class LocalImportChunk : public NonSectionChunk {
618public:
619 explicit LocalImportChunk(COFFLinkerContext &ctx, Defined *s);
620 size_t getSize() const override;
621 void getBaserels(std::vector<Baserel> *res) override;
622 void writeTo(uint8_t *buf) const override;
623
624private:
625 Defined *sym;
626 COFFLinkerContext &ctx;
627};
628
629// Duplicate RVAs are not allowed in RVA tables, so unique symbols by chunk and
630// offset into the chunk. Order does not matter as the RVA table will be sorted
631// later.
632struct ChunkAndOffset {
633 Chunk *inputChunk;
634 uint32_t offset;
635
636 struct DenseMapInfo {
637 static ChunkAndOffset getEmptyKey() {
638 return {.inputChunk: llvm::DenseMapInfo<Chunk *>::getEmptyKey(), .offset: 0};
639 }
640 static ChunkAndOffset getTombstoneKey() {
641 return {.inputChunk: llvm::DenseMapInfo<Chunk *>::getTombstoneKey(), .offset: 0};
642 }
643 static unsigned getHashValue(const ChunkAndOffset &co) {
644 return llvm::DenseMapInfo<std::pair<Chunk *, uint32_t>>::getHashValue(
645 PairVal: {co.inputChunk, co.offset});
646 }
647 static bool isEqual(const ChunkAndOffset &lhs, const ChunkAndOffset &rhs) {
648 return lhs.inputChunk == rhs.inputChunk && lhs.offset == rhs.offset;
649 }
650 };
651};
652
653using SymbolRVASet = llvm::DenseSet<ChunkAndOffset>;
654
655// Table which contains symbol RVAs. Used for /safeseh and /guard:cf.
656class RVATableChunk : public NonSectionChunk {
657public:
658 explicit RVATableChunk(SymbolRVASet s) : syms(std::move(s)) {}
659 size_t getSize() const override { return syms.size() * 4; }
660 void writeTo(uint8_t *buf) const override;
661
662private:
663 SymbolRVASet syms;
664};
665
666// Table which contains symbol RVAs with flags. Used for /guard:ehcont.
667class RVAFlagTableChunk : public NonSectionChunk {
668public:
669 explicit RVAFlagTableChunk(SymbolRVASet s) : syms(std::move(s)) {}
670 size_t getSize() const override { return syms.size() * 5; }
671 void writeTo(uint8_t *buf) const override;
672
673private:
674 SymbolRVASet syms;
675};
676
677// Windows-specific.
678// This class represents a block in .reloc section.
679// See the PE/COFF spec 5.6 for details.
680class BaserelChunk : public NonSectionChunk {
681public:
682 BaserelChunk(uint32_t page, Baserel *begin, Baserel *end);
683 size_t getSize() const override { return data.size(); }
684 void writeTo(uint8_t *buf) const override;
685
686private:
687 std::vector<uint8_t> data;
688};
689
690class Baserel {
691public:
692 Baserel(uint32_t v, uint8_t ty) : rva(v), type(ty) {}
693 explicit Baserel(uint32_t v, llvm::COFF::MachineTypes machine)
694 : Baserel(v, getDefaultType(machine)) {}
695 uint8_t getDefaultType(llvm::COFF::MachineTypes machine);
696
697 uint32_t rva;
698 uint8_t type;
699};
700
701// This is a placeholder Chunk, to allow attaching a DefinedSynthetic to a
702// specific place in a section, without any data. This is used for the MinGW
703// specific symbol __RUNTIME_PSEUDO_RELOC_LIST_END__, even though the concept
704// of an empty chunk isn't MinGW specific.
705class EmptyChunk : public NonSectionChunk {
706public:
707 EmptyChunk() {}
708 size_t getSize() const override { return 0; }
709 void writeTo(uint8_t *buf) const override {}
710};
711
712class ECCodeMapEntry {
713public:
714 ECCodeMapEntry(Chunk *first, Chunk *last, chpe_range_type type)
715 : first(first), last(last), type(type) {}
716 Chunk *first;
717 Chunk *last;
718 chpe_range_type type;
719};
720
721// This is a chunk containing CHPE code map on EC targets. It's a table
722// of address ranges and their types.
723class ECCodeMapChunk : public NonSectionChunk {
724public:
725 ECCodeMapChunk(std::vector<ECCodeMapEntry> &map) : map(map) {}
726 size_t getSize() const override;
727 void writeTo(uint8_t *buf) const override;
728
729private:
730 std::vector<ECCodeMapEntry> &map;
731};
732
733// MinGW specific, for the "automatic import of variables from DLLs" feature.
734// This provides the table of runtime pseudo relocations, for variable
735// references that turned out to need to be imported from a DLL even though
736// the reference didn't use the dllimport attribute. The MinGW runtime will
737// process this table after loading, before handling control over to user
738// code.
739class PseudoRelocTableChunk : public NonSectionChunk {
740public:
741 PseudoRelocTableChunk(std::vector<RuntimePseudoReloc> &relocs)
742 : relocs(std::move(relocs)) {
743 setAlignment(4);
744 }
745 size_t getSize() const override;
746 void writeTo(uint8_t *buf) const override;
747
748private:
749 std::vector<RuntimePseudoReloc> relocs;
750};
751
752// MinGW specific. A Chunk that contains one pointer-sized absolute value.
753class AbsolutePointerChunk : public NonSectionChunk {
754public:
755 AbsolutePointerChunk(COFFLinkerContext &ctx, uint64_t value)
756 : value(value), ctx(ctx) {
757 setAlignment(getSize());
758 }
759 size_t getSize() const override;
760 void writeTo(uint8_t *buf) const override;
761
762private:
763 uint64_t value;
764 COFFLinkerContext &ctx;
765};
766
767// Return true if this file has the hotpatch flag set to true in the S_COMPILE3
768// record in codeview debug info. Also returns true for some thunks synthesized
769// by the linker.
770inline bool Chunk::isHotPatchable() const {
771 if (auto *sc = dyn_cast<SectionChunk>(Val: this))
772 return sc->file->hotPatchable;
773 else if (isa<ImportThunkChunk>(Val: this))
774 return true;
775 return false;
776}
777
778void applyMOV32T(uint8_t *off, uint32_t v);
779void applyBranch24T(uint8_t *off, int32_t v);
780
781void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift);
782void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit);
783void applyArm64Branch26(uint8_t *off, int64_t v);
784
785// Convenience class for initializing a coff_section with specific flags.
786class FakeSection {
787public:
788 FakeSection(int c) { section.Characteristics = c; }
789
790 coff_section section;
791};
792
793// Convenience class for initializing a SectionChunk with specific flags.
794class FakeSectionChunk {
795public:
796 FakeSectionChunk(const coff_section *section) : chunk(nullptr, section) {
797 // Comdats from LTO files can't be fully treated as regular comdats
798 // at this point; we don't know what size or contents they are going to
799 // have, so we can't do proper checking of such aspects of them.
800 chunk.selection = llvm::COFF::IMAGE_COMDAT_SELECT_ANY;
801 }
802
803 SectionChunk chunk;
804};
805
806} // namespace lld::coff
807
808namespace llvm {
809template <>
810struct DenseMapInfo<lld::coff::ChunkAndOffset>
811 : lld::coff::ChunkAndOffset::DenseMapInfo {};
812}
813
814#endif
815

source code of lld/COFF/Chunks.h