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