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