1 //===- COFF.h - COFF object file implementation -----------------*- 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 // This file declares the COFFObjectFile class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_OBJECT_COFF_H
14 #define LLVM_OBJECT_COFF_H
15 
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/BinaryFormat/COFF.h"
18 #include "llvm/MC/SubtargetFeature.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/CVDebugRecord.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/BinaryByteStream.h"
24 #include "llvm/Support/ConvertUTF.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <cassert>
28 #include <cstddef>
29 #include <cstdint>
30 #include <system_error>
31 
32 namespace llvm {
33 
34 template <typename T> class ArrayRef;
35 
36 namespace object {
37 
38 class BaseRelocRef;
39 class DelayImportDirectoryEntryRef;
40 class ExportDirectoryEntryRef;
41 class ImportDirectoryEntryRef;
42 class ImportedSymbolRef;
43 class ResourceSectionRef;
44 
45 using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>;
46 using delay_import_directory_iterator =
47     content_iterator<DelayImportDirectoryEntryRef>;
48 using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>;
49 using imported_symbol_iterator = content_iterator<ImportedSymbolRef>;
50 using base_reloc_iterator = content_iterator<BaseRelocRef>;
51 
52 /// The DOS compatible header at the front of all PE/COFF executables.
53 struct dos_header {
54   char                 Magic[2];
55   support::ulittle16_t UsedBytesInTheLastPage;
56   support::ulittle16_t FileSizeInPages;
57   support::ulittle16_t NumberOfRelocationItems;
58   support::ulittle16_t HeaderSizeInParagraphs;
59   support::ulittle16_t MinimumExtraParagraphs;
60   support::ulittle16_t MaximumExtraParagraphs;
61   support::ulittle16_t InitialRelativeSS;
62   support::ulittle16_t InitialSP;
63   support::ulittle16_t Checksum;
64   support::ulittle16_t InitialIP;
65   support::ulittle16_t InitialRelativeCS;
66   support::ulittle16_t AddressOfRelocationTable;
67   support::ulittle16_t OverlayNumber;
68   support::ulittle16_t Reserved[4];
69   support::ulittle16_t OEMid;
70   support::ulittle16_t OEMinfo;
71   support::ulittle16_t Reserved2[10];
72   support::ulittle32_t AddressOfNewExeHeader;
73 };
74 
75 struct coff_file_header {
76   support::ulittle16_t Machine;
77   support::ulittle16_t NumberOfSections;
78   support::ulittle32_t TimeDateStamp;
79   support::ulittle32_t PointerToSymbolTable;
80   support::ulittle32_t NumberOfSymbols;
81   support::ulittle16_t SizeOfOptionalHeader;
82   support::ulittle16_t Characteristics;
83 
84   bool isImportLibrary() const { return NumberOfSections == 0xffff; }
85 };
86 
87 struct coff_bigobj_file_header {
88   support::ulittle16_t Sig1;
89   support::ulittle16_t Sig2;
90   support::ulittle16_t Version;
91   support::ulittle16_t Machine;
92   support::ulittle32_t TimeDateStamp;
93   uint8_t              UUID[16];
94   support::ulittle32_t unused1;
95   support::ulittle32_t unused2;
96   support::ulittle32_t unused3;
97   support::ulittle32_t unused4;
98   support::ulittle32_t NumberOfSections;
99   support::ulittle32_t PointerToSymbolTable;
100   support::ulittle32_t NumberOfSymbols;
101 };
102 
103 /// The 32-bit PE header that follows the COFF header.
104 struct pe32_header {
105   support::ulittle16_t Magic;
106   uint8_t MajorLinkerVersion;
107   uint8_t MinorLinkerVersion;
108   support::ulittle32_t SizeOfCode;
109   support::ulittle32_t SizeOfInitializedData;
110   support::ulittle32_t SizeOfUninitializedData;
111   support::ulittle32_t AddressOfEntryPoint;
112   support::ulittle32_t BaseOfCode;
113   support::ulittle32_t BaseOfData;
114   support::ulittle32_t ImageBase;
115   support::ulittle32_t SectionAlignment;
116   support::ulittle32_t FileAlignment;
117   support::ulittle16_t MajorOperatingSystemVersion;
118   support::ulittle16_t MinorOperatingSystemVersion;
119   support::ulittle16_t MajorImageVersion;
120   support::ulittle16_t MinorImageVersion;
121   support::ulittle16_t MajorSubsystemVersion;
122   support::ulittle16_t MinorSubsystemVersion;
123   support::ulittle32_t Win32VersionValue;
124   support::ulittle32_t SizeOfImage;
125   support::ulittle32_t SizeOfHeaders;
126   support::ulittle32_t CheckSum;
127   support::ulittle16_t Subsystem;
128   // FIXME: This should be DllCharacteristics.
129   support::ulittle16_t DLLCharacteristics;
130   support::ulittle32_t SizeOfStackReserve;
131   support::ulittle32_t SizeOfStackCommit;
132   support::ulittle32_t SizeOfHeapReserve;
133   support::ulittle32_t SizeOfHeapCommit;
134   support::ulittle32_t LoaderFlags;
135   // FIXME: This should be NumberOfRvaAndSizes.
136   support::ulittle32_t NumberOfRvaAndSize;
137 };
138 
139 /// The 64-bit PE header that follows the COFF header.
140 struct pe32plus_header {
141   support::ulittle16_t Magic;
142   uint8_t MajorLinkerVersion;
143   uint8_t MinorLinkerVersion;
144   support::ulittle32_t SizeOfCode;
145   support::ulittle32_t SizeOfInitializedData;
146   support::ulittle32_t SizeOfUninitializedData;
147   support::ulittle32_t AddressOfEntryPoint;
148   support::ulittle32_t BaseOfCode;
149   support::ulittle64_t ImageBase;
150   support::ulittle32_t SectionAlignment;
151   support::ulittle32_t FileAlignment;
152   support::ulittle16_t MajorOperatingSystemVersion;
153   support::ulittle16_t MinorOperatingSystemVersion;
154   support::ulittle16_t MajorImageVersion;
155   support::ulittle16_t MinorImageVersion;
156   support::ulittle16_t MajorSubsystemVersion;
157   support::ulittle16_t MinorSubsystemVersion;
158   support::ulittle32_t Win32VersionValue;
159   support::ulittle32_t SizeOfImage;
160   support::ulittle32_t SizeOfHeaders;
161   support::ulittle32_t CheckSum;
162   support::ulittle16_t Subsystem;
163   support::ulittle16_t DLLCharacteristics;
164   support::ulittle64_t SizeOfStackReserve;
165   support::ulittle64_t SizeOfStackCommit;
166   support::ulittle64_t SizeOfHeapReserve;
167   support::ulittle64_t SizeOfHeapCommit;
168   support::ulittle32_t LoaderFlags;
169   support::ulittle32_t NumberOfRvaAndSize;
170 };
171 
172 struct data_directory {
173   support::ulittle32_t RelativeVirtualAddress;
174   support::ulittle32_t Size;
175 };
176 
177 struct debug_directory {
178   support::ulittle32_t Characteristics;
179   support::ulittle32_t TimeDateStamp;
180   support::ulittle16_t MajorVersion;
181   support::ulittle16_t MinorVersion;
182   support::ulittle32_t Type;
183   support::ulittle32_t SizeOfData;
184   support::ulittle32_t AddressOfRawData;
185   support::ulittle32_t PointerToRawData;
186 };
187 
188 template <typename IntTy>
189 struct import_lookup_table_entry {
190   IntTy Data;
191 
192   bool isOrdinal() const { return Data < 0; }
193 
194   uint16_t getOrdinal() const {
195     assert(isOrdinal() && "ILT entry is not an ordinal!");
196     return Data & 0xFFFF;
197   }
198 
199   uint32_t getHintNameRVA() const {
200     assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
201     return Data & 0xFFFFFFFF;
202   }
203 };
204 
205 using import_lookup_table_entry32 =
206     import_lookup_table_entry<support::little32_t>;
207 using import_lookup_table_entry64 =
208     import_lookup_table_entry<support::little64_t>;
209 
210 struct delay_import_directory_table_entry {
211   // dumpbin reports this field as "Characteristics" instead of "Attributes".
212   support::ulittle32_t Attributes;
213   support::ulittle32_t Name;
214   support::ulittle32_t ModuleHandle;
215   support::ulittle32_t DelayImportAddressTable;
216   support::ulittle32_t DelayImportNameTable;
217   support::ulittle32_t BoundDelayImportTable;
218   support::ulittle32_t UnloadDelayImportTable;
219   support::ulittle32_t TimeStamp;
220 };
221 
222 struct export_directory_table_entry {
223   support::ulittle32_t ExportFlags;
224   support::ulittle32_t TimeDateStamp;
225   support::ulittle16_t MajorVersion;
226   support::ulittle16_t MinorVersion;
227   support::ulittle32_t NameRVA;
228   support::ulittle32_t OrdinalBase;
229   support::ulittle32_t AddressTableEntries;
230   support::ulittle32_t NumberOfNamePointers;
231   support::ulittle32_t ExportAddressTableRVA;
232   support::ulittle32_t NamePointerRVA;
233   support::ulittle32_t OrdinalTableRVA;
234 };
235 
236 union export_address_table_entry {
237   support::ulittle32_t ExportRVA;
238   support::ulittle32_t ForwarderRVA;
239 };
240 
241 using export_name_pointer_table_entry = support::ulittle32_t;
242 using export_ordinal_table_entry = support::ulittle16_t;
243 
244 struct StringTableOffset {
245   support::ulittle32_t Zeroes;
246   support::ulittle32_t Offset;
247 };
248 
249 template <typename SectionNumberType>
250 struct coff_symbol {
251   union {
252     char ShortName[COFF::NameSize];
253     StringTableOffset Offset;
254   } Name;
255 
256   support::ulittle32_t Value;
257   SectionNumberType SectionNumber;
258 
259   support::ulittle16_t Type;
260 
261   uint8_t StorageClass;
262   uint8_t NumberOfAuxSymbols;
263 };
264 
265 using coff_symbol16 = coff_symbol<support::ulittle16_t>;
266 using coff_symbol32 = coff_symbol<support::ulittle32_t>;
267 
268 // Contains only common parts of coff_symbol16 and coff_symbol32.
269 struct coff_symbol_generic {
270   union {
271     char ShortName[COFF::NameSize];
272     StringTableOffset Offset;
273   } Name;
274   support::ulittle32_t Value;
275 };
276 
277 struct coff_aux_section_definition;
278 struct coff_aux_weak_external;
279 
280 class COFFSymbolRef {
281 public:
282   COFFSymbolRef() = default;
283   COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {}
284   COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {}
285 
286   const void *getRawPtr() const {
287     return CS16 ? static_cast<const void *>(CS16) : CS32;
288   }
289 
290   const coff_symbol_generic *getGeneric() const {
291     if (CS16)
292       return reinterpret_cast<const coff_symbol_generic *>(CS16);
293     return reinterpret_cast<const coff_symbol_generic *>(CS32);
294   }
295 
296   friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
297     return A.getRawPtr() < B.getRawPtr();
298   }
299 
300   bool isBigObj() const {
301     if (CS16)
302       return false;
303     if (CS32)
304       return true;
305     llvm_unreachable("COFFSymbolRef points to nothing!");
306   }
307 
308   const char *getShortName() const {
309     return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
310   }
311 
312   const StringTableOffset &getStringTableOffset() const {
313     assert(isSet() && "COFFSymbolRef points to nothing!");
314     return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
315   }
316 
317   uint32_t getValue() const {
318     assert(isSet() && "COFFSymbolRef points to nothing!");
319     return CS16 ? CS16->Value : CS32->Value;
320   }
321 
322   int32_t getSectionNumber() const {
323     assert(isSet() && "COFFSymbolRef points to nothing!");
324     if (CS16) {
325       // Reserved sections are returned as negative numbers.
326       if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
327         return CS16->SectionNumber;
328       return static_cast<int16_t>(CS16->SectionNumber);
329     }
330     return static_cast<int32_t>(CS32->SectionNumber);
331   }
332 
333   uint16_t getType() const {
334     assert(isSet() && "COFFSymbolRef points to nothing!");
335     return CS16 ? CS16->Type : CS32->Type;
336   }
337 
338   uint8_t getStorageClass() const {
339     assert(isSet() && "COFFSymbolRef points to nothing!");
340     return CS16 ? CS16->StorageClass : CS32->StorageClass;
341   }
342 
343   uint8_t getNumberOfAuxSymbols() const {
344     assert(isSet() && "COFFSymbolRef points to nothing!");
345     return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols;
346   }
347 
348   uint8_t getBaseType() const { return getType() & 0x0F; }
349 
350   uint8_t getComplexType() const {
351     return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
352   }
353 
354   template <typename T> const T *getAux() const {
355     return CS16 ? reinterpret_cast<const T *>(CS16 + 1)
356                 : reinterpret_cast<const T *>(CS32 + 1);
357   }
358 
359   const coff_aux_section_definition *getSectionDefinition() const {
360     if (!getNumberOfAuxSymbols() ||
361         getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC)
362       return nullptr;
363     return getAux<coff_aux_section_definition>();
364   }
365 
366   const coff_aux_weak_external *getWeakExternal() const {
367     if (!getNumberOfAuxSymbols() ||
368         getStorageClass() != COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
369       return nullptr;
370     return getAux<coff_aux_weak_external>();
371   }
372 
373   bool isAbsolute() const {
374     return getSectionNumber() == -1;
375   }
376 
377   bool isExternal() const {
378     return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
379   }
380 
381   bool isCommon() const {
382     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
383            getValue() != 0;
384   }
385 
386   bool isUndefined() const {
387     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
388            getValue() == 0;
389   }
390 
391   bool isWeakExternal() const {
392     return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
393   }
394 
395   bool isFunctionDefinition() const {
396     return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
397            getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
398            !COFF::isReservedSectionNumber(getSectionNumber());
399   }
400 
401   bool isFunctionLineInfo() const {
402     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
403   }
404 
405   bool isAnyUndefined() const {
406     return isUndefined() || isWeakExternal();
407   }
408 
409   bool isFileRecord() const {
410     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
411   }
412 
413   bool isSection() const {
414     return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
415   }
416 
417   bool isSectionDefinition() const {
418     // C++/CLI creates external ABS symbols for non-const appdomain globals.
419     // These are also followed by an auxiliary section definition.
420     bool isAppdomainGlobal =
421         getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
422         getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE;
423     bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
424     if (!getNumberOfAuxSymbols())
425       return false;
426     return isAppdomainGlobal || isOrdinarySection;
427   }
428 
429   bool isCLRToken() const {
430     return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
431   }
432 
433 private:
434   bool isSet() const { return CS16 || CS32; }
435 
436   const coff_symbol16 *CS16 = nullptr;
437   const coff_symbol32 *CS32 = nullptr;
438 };
439 
440 struct coff_section {
441   char Name[COFF::NameSize];
442   support::ulittle32_t VirtualSize;
443   support::ulittle32_t VirtualAddress;
444   support::ulittle32_t SizeOfRawData;
445   support::ulittle32_t PointerToRawData;
446   support::ulittle32_t PointerToRelocations;
447   support::ulittle32_t PointerToLinenumbers;
448   support::ulittle16_t NumberOfRelocations;
449   support::ulittle16_t NumberOfLinenumbers;
450   support::ulittle32_t Characteristics;
451 
452   // Returns true if the actual number of relocations is stored in
453   // VirtualAddress field of the first relocation table entry.
454   bool hasExtendedRelocations() const {
455     return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
456            NumberOfRelocations == UINT16_MAX;
457   }
458 
459   uint32_t getAlignment() const {
460     // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to
461     // IMAGE_SCN_ALIGN_1BYTES.
462     if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD)
463       return 1;
464 
465     // Bit [20:24] contains section alignment. 0 means use a default alignment
466     // of 16.
467     uint32_t Shift = (Characteristics >> 20) & 0xF;
468     if (Shift > 0)
469       return 1U << (Shift - 1);
470     return 16;
471   }
472 };
473 
474 struct coff_relocation {
475   support::ulittle32_t VirtualAddress;
476   support::ulittle32_t SymbolTableIndex;
477   support::ulittle16_t Type;
478 };
479 
480 struct coff_aux_function_definition {
481   support::ulittle32_t TagIndex;
482   support::ulittle32_t TotalSize;
483   support::ulittle32_t PointerToLinenumber;
484   support::ulittle32_t PointerToNextFunction;
485   char Unused1[2];
486 };
487 
488 static_assert(sizeof(coff_aux_function_definition) == 18,
489               "auxiliary entry must be 18 bytes");
490 
491 struct coff_aux_bf_and_ef_symbol {
492   char Unused1[4];
493   support::ulittle16_t Linenumber;
494   char Unused2[6];
495   support::ulittle32_t PointerToNextFunction;
496   char Unused3[2];
497 };
498 
499 static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18,
500               "auxiliary entry must be 18 bytes");
501 
502 struct coff_aux_weak_external {
503   support::ulittle32_t TagIndex;
504   support::ulittle32_t Characteristics;
505   char Unused1[10];
506 };
507 
508 static_assert(sizeof(coff_aux_weak_external) == 18,
509               "auxiliary entry must be 18 bytes");
510 
511 struct coff_aux_section_definition {
512   support::ulittle32_t Length;
513   support::ulittle16_t NumberOfRelocations;
514   support::ulittle16_t NumberOfLinenumbers;
515   support::ulittle32_t CheckSum;
516   support::ulittle16_t NumberLowPart;
517   uint8_t              Selection;
518   uint8_t              Unused;
519   support::ulittle16_t NumberHighPart;
520   int32_t getNumber(bool IsBigObj) const {
521     uint32_t Number = static_cast<uint32_t>(NumberLowPart);
522     if (IsBigObj)
523       Number |= static_cast<uint32_t>(NumberHighPart) << 16;
524     return static_cast<int32_t>(Number);
525   }
526 };
527 
528 static_assert(sizeof(coff_aux_section_definition) == 18,
529               "auxiliary entry must be 18 bytes");
530 
531 struct coff_aux_clr_token {
532   uint8_t              AuxType;
533   uint8_t              Reserved;
534   support::ulittle32_t SymbolTableIndex;
535   char                 MBZ[12];
536 };
537 
538 static_assert(sizeof(coff_aux_clr_token) == 18,
539               "auxiliary entry must be 18 bytes");
540 
541 struct coff_import_header {
542   support::ulittle16_t Sig1;
543   support::ulittle16_t Sig2;
544   support::ulittle16_t Version;
545   support::ulittle16_t Machine;
546   support::ulittle32_t TimeDateStamp;
547   support::ulittle32_t SizeOfData;
548   support::ulittle16_t OrdinalHint;
549   support::ulittle16_t TypeInfo;
550 
551   int getType() const { return TypeInfo & 0x3; }
552   int getNameType() const { return (TypeInfo >> 2) & 0x7; }
553 };
554 
555 struct coff_import_directory_table_entry {
556   support::ulittle32_t ImportLookupTableRVA;
557   support::ulittle32_t TimeDateStamp;
558   support::ulittle32_t ForwarderChain;
559   support::ulittle32_t NameRVA;
560   support::ulittle32_t ImportAddressTableRVA;
561 
562   bool isNull() const {
563     return ImportLookupTableRVA == 0 && TimeDateStamp == 0 &&
564            ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0;
565   }
566 };
567 
568 template <typename IntTy>
569 struct coff_tls_directory {
570   IntTy StartAddressOfRawData;
571   IntTy EndAddressOfRawData;
572   IntTy AddressOfIndex;
573   IntTy AddressOfCallBacks;
574   support::ulittle32_t SizeOfZeroFill;
575   support::ulittle32_t Characteristics;
576 
577   uint32_t getAlignment() const {
578     // Bit [20:24] contains section alignment.
579     uint32_t Shift = (Characteristics & COFF::IMAGE_SCN_ALIGN_MASK) >> 20;
580     if (Shift > 0)
581       return 1U << (Shift - 1);
582     return 0;
583   }
584 
585   void setAlignment(uint32_t Align) {
586     uint32_t AlignBits = 0;
587     if (Align) {
588       assert(llvm::isPowerOf2_32(Align) && "alignment is not a power of 2");
589       assert(llvm::Log2_32(Align) <= 13 && "alignment requested is too large");
590       AlignBits = (llvm::Log2_32(Align) + 1) << 20;
591     }
592     Characteristics =
593         (Characteristics & ~COFF::IMAGE_SCN_ALIGN_MASK) | AlignBits;
594   }
595 };
596 
597 using coff_tls_directory32 = coff_tls_directory<support::little32_t>;
598 using coff_tls_directory64 = coff_tls_directory<support::little64_t>;
599 
600 /// Bits in control flow guard flags as we understand them.
601 enum class coff_guard_flags : uint32_t {
602   CFInstrumented = 0x00000100,
603   HasFidTable = 0x00000400,
604   ProtectDelayLoadIAT = 0x00001000,
605   DelayLoadIATSection = 0x00002000, // Delay load in separate section
606   HasLongJmpTable = 0x00010000,
607   HasEHContTable = 0x00400000,
608   FidTableHasFlags = 0x10000000, // Indicates that fid tables are 5 bytes
609 };
610 
611 enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 };
612 
613 struct coff_load_config_code_integrity {
614   support::ulittle16_t Flags;
615   support::ulittle16_t Catalog;
616   support::ulittle32_t CatalogOffset;
617   support::ulittle32_t Reserved;
618 };
619 
620 /// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32)
621 struct coff_load_configuration32 {
622   support::ulittle32_t Size;
623   support::ulittle32_t TimeDateStamp;
624   support::ulittle16_t MajorVersion;
625   support::ulittle16_t MinorVersion;
626   support::ulittle32_t GlobalFlagsClear;
627   support::ulittle32_t GlobalFlagsSet;
628   support::ulittle32_t CriticalSectionDefaultTimeout;
629   support::ulittle32_t DeCommitFreeBlockThreshold;
630   support::ulittle32_t DeCommitTotalFreeThreshold;
631   support::ulittle32_t LockPrefixTable;
632   support::ulittle32_t MaximumAllocationSize;
633   support::ulittle32_t VirtualMemoryThreshold;
634   support::ulittle32_t ProcessAffinityMask;
635   support::ulittle32_t ProcessHeapFlags;
636   support::ulittle16_t CSDVersion;
637   support::ulittle16_t DependentLoadFlags;
638   support::ulittle32_t EditList;
639   support::ulittle32_t SecurityCookie;
640   support::ulittle32_t SEHandlerTable;
641   support::ulittle32_t SEHandlerCount;
642 
643   // Added in MSVC 2015 for /guard:cf.
644   support::ulittle32_t GuardCFCheckFunction;
645   support::ulittle32_t GuardCFCheckDispatch;
646   support::ulittle32_t GuardCFFunctionTable;
647   support::ulittle32_t GuardCFFunctionCount;
648   support::ulittle32_t GuardFlags; // coff_guard_flags
649 
650   // Added in MSVC 2017
651   coff_load_config_code_integrity CodeIntegrity;
652   support::ulittle32_t GuardAddressTakenIatEntryTable;
653   support::ulittle32_t GuardAddressTakenIatEntryCount;
654   support::ulittle32_t GuardLongJumpTargetTable;
655   support::ulittle32_t GuardLongJumpTargetCount;
656   support::ulittle32_t DynamicValueRelocTable;
657   support::ulittle32_t CHPEMetadataPointer;
658   support::ulittle32_t GuardRFFailureRoutine;
659   support::ulittle32_t GuardRFFailureRoutineFunctionPointer;
660   support::ulittle32_t DynamicValueRelocTableOffset;
661   support::ulittle16_t DynamicValueRelocTableSection;
662   support::ulittle16_t Reserved2;
663   support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer;
664   support::ulittle32_t HotPatchTableOffset;
665 
666   // Added in MSVC 2019
667   support::ulittle32_t Reserved3;
668   support::ulittle32_t EnclaveConfigurationPointer;
669   support::ulittle32_t VolatileMetadataPointer;
670   support::ulittle32_t GuardEHContinuationTable;
671   support::ulittle32_t GuardEHContinuationCount;
672   support::ulittle32_t GuardXFGCheckFunctionPointer;
673   support::ulittle32_t GuardXFGDispatchFunctionPointer;
674   support::ulittle32_t GuardXFGTableDispatchFunctionPointer;
675   support::ulittle32_t CastGuardOsDeterminedFailureMode;
676 };
677 
678 /// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64)
679 struct coff_load_configuration64 {
680   support::ulittle32_t Size;
681   support::ulittle32_t TimeDateStamp;
682   support::ulittle16_t MajorVersion;
683   support::ulittle16_t MinorVersion;
684   support::ulittle32_t GlobalFlagsClear;
685   support::ulittle32_t GlobalFlagsSet;
686   support::ulittle32_t CriticalSectionDefaultTimeout;
687   support::ulittle64_t DeCommitFreeBlockThreshold;
688   support::ulittle64_t DeCommitTotalFreeThreshold;
689   support::ulittle64_t LockPrefixTable;
690   support::ulittle64_t MaximumAllocationSize;
691   support::ulittle64_t VirtualMemoryThreshold;
692   support::ulittle64_t ProcessAffinityMask;
693   support::ulittle32_t ProcessHeapFlags;
694   support::ulittle16_t CSDVersion;
695   support::ulittle16_t DependentLoadFlags;
696   support::ulittle64_t EditList;
697   support::ulittle64_t SecurityCookie;
698   support::ulittle64_t SEHandlerTable;
699   support::ulittle64_t SEHandlerCount;
700 
701   // Added in MSVC 2015 for /guard:cf.
702   support::ulittle64_t GuardCFCheckFunction;
703   support::ulittle64_t GuardCFCheckDispatch;
704   support::ulittle64_t GuardCFFunctionTable;
705   support::ulittle64_t GuardCFFunctionCount;
706   support::ulittle32_t GuardFlags;
707 
708   // Added in MSVC 2017
709   coff_load_config_code_integrity CodeIntegrity;
710   support::ulittle64_t GuardAddressTakenIatEntryTable;
711   support::ulittle64_t GuardAddressTakenIatEntryCount;
712   support::ulittle64_t GuardLongJumpTargetTable;
713   support::ulittle64_t GuardLongJumpTargetCount;
714   support::ulittle64_t DynamicValueRelocTable;
715   support::ulittle64_t CHPEMetadataPointer;
716   support::ulittle64_t GuardRFFailureRoutine;
717   support::ulittle64_t GuardRFFailureRoutineFunctionPointer;
718   support::ulittle32_t DynamicValueRelocTableOffset;
719   support::ulittle16_t DynamicValueRelocTableSection;
720   support::ulittle16_t Reserved2;
721   support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer;
722   support::ulittle32_t HotPatchTableOffset;
723 
724   // Added in MSVC 2019
725   support::ulittle32_t Reserved3;
726   support::ulittle64_t EnclaveConfigurationPointer;
727   support::ulittle64_t VolatileMetadataPointer;
728   support::ulittle64_t GuardEHContinuationTable;
729   support::ulittle64_t GuardEHContinuationCount;
730   support::ulittle64_t GuardXFGCheckFunctionPointer;
731   support::ulittle64_t GuardXFGDispatchFunctionPointer;
732   support::ulittle64_t GuardXFGTableDispatchFunctionPointer;
733   support::ulittle64_t CastGuardOsDeterminedFailureMode;
734 };
735 
736 struct coff_runtime_function_x64 {
737   support::ulittle32_t BeginAddress;
738   support::ulittle32_t EndAddress;
739   support::ulittle32_t UnwindInformation;
740 };
741 
742 struct coff_base_reloc_block_header {
743   support::ulittle32_t PageRVA;
744   support::ulittle32_t BlockSize;
745 };
746 
747 struct coff_base_reloc_block_entry {
748   support::ulittle16_t Data;
749 
750   int getType() const { return Data >> 12; }
751   int getOffset() const { return Data & ((1 << 12) - 1); }
752 };
753 
754 struct coff_resource_dir_entry {
755   union {
756     support::ulittle32_t NameOffset;
757     support::ulittle32_t ID;
758     uint32_t getNameOffset() const {
759       return maskTrailingOnes<uint32_t>(31) & NameOffset;
760     }
761     // Even though the PE/COFF spec doesn't mention this, the high bit of a name
762     // offset is set.
763     void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); }
764   } Identifier;
765   union {
766     support::ulittle32_t DataEntryOffset;
767     support::ulittle32_t SubdirOffset;
768 
769     bool isSubDir() const { return SubdirOffset >> 31; }
770     uint32_t value() const {
771       return maskTrailingOnes<uint32_t>(31) & SubdirOffset;
772     }
773 
774   } Offset;
775 };
776 
777 struct coff_resource_data_entry {
778   support::ulittle32_t DataRVA;
779   support::ulittle32_t DataSize;
780   support::ulittle32_t Codepage;
781   support::ulittle32_t Reserved;
782 };
783 
784 struct coff_resource_dir_table {
785   support::ulittle32_t Characteristics;
786   support::ulittle32_t TimeDateStamp;
787   support::ulittle16_t MajorVersion;
788   support::ulittle16_t MinorVersion;
789   support::ulittle16_t NumberOfNameEntries;
790   support::ulittle16_t NumberOfIDEntries;
791 };
792 
793 struct debug_h_header {
794   support::ulittle32_t Magic;
795   support::ulittle16_t Version;
796   support::ulittle16_t HashAlgorithm;
797 };
798 
799 class COFFObjectFile : public ObjectFile {
800 private:
801   COFFObjectFile(MemoryBufferRef Object);
802 
803   friend class ImportDirectoryEntryRef;
804   friend class ExportDirectoryEntryRef;
805   const coff_file_header *COFFHeader;
806   const coff_bigobj_file_header *COFFBigObjHeader;
807   const pe32_header *PE32Header;
808   const pe32plus_header *PE32PlusHeader;
809   const data_directory *DataDirectory;
810   const coff_section *SectionTable;
811   const coff_symbol16 *SymbolTable16;
812   const coff_symbol32 *SymbolTable32;
813   const char *StringTable;
814   uint32_t StringTableSize;
815   const coff_import_directory_table_entry *ImportDirectory;
816   const delay_import_directory_table_entry *DelayImportDirectory;
817   uint32_t NumberOfDelayImportDirectory;
818   const export_directory_table_entry *ExportDirectory;
819   const coff_base_reloc_block_header *BaseRelocHeader;
820   const coff_base_reloc_block_header *BaseRelocEnd;
821   const debug_directory *DebugDirectoryBegin;
822   const debug_directory *DebugDirectoryEnd;
823   const coff_tls_directory32 *TLSDirectory32;
824   const coff_tls_directory64 *TLSDirectory64;
825   // Either coff_load_configuration32 or coff_load_configuration64.
826   const void *LoadConfig = nullptr;
827 
828   Expected<StringRef> getString(uint32_t offset) const;
829 
830   template <typename coff_symbol_type>
831   const coff_symbol_type *toSymb(DataRefImpl Symb) const;
832   const coff_section *toSec(DataRefImpl Sec) const;
833   const coff_relocation *toRel(DataRefImpl Rel) const;
834 
835   // Finish initializing the object and return success or an error.
836   Error initialize();
837 
838   Error initSymbolTablePtr();
839   Error initImportTablePtr();
840   Error initDelayImportTablePtr();
841   Error initExportTablePtr();
842   Error initBaseRelocPtr();
843   Error initDebugDirectoryPtr();
844   Error initTLSDirectoryPtr();
845   Error initLoadConfigPtr();
846 
847 public:
848   static Expected<std::unique_ptr<COFFObjectFile>>
849   create(MemoryBufferRef Object);
850 
851   uintptr_t getSymbolTable() const {
852     if (SymbolTable16)
853       return reinterpret_cast<uintptr_t>(SymbolTable16);
854     if (SymbolTable32)
855       return reinterpret_cast<uintptr_t>(SymbolTable32);
856     return uintptr_t(0);
857   }
858 
859   uint16_t getMachine() const {
860     if (COFFHeader)
861       return COFFHeader->Machine;
862     if (COFFBigObjHeader)
863       return COFFBigObjHeader->Machine;
864     llvm_unreachable("no COFF header!");
865   }
866 
867   uint16_t getSizeOfOptionalHeader() const {
868     if (COFFHeader)
869       return COFFHeader->isImportLibrary() ? 0
870                                            : COFFHeader->SizeOfOptionalHeader;
871     // bigobj doesn't have this field.
872     if (COFFBigObjHeader)
873       return 0;
874     llvm_unreachable("no COFF header!");
875   }
876 
877   uint16_t getCharacteristics() const {
878     if (COFFHeader)
879       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
880     // bigobj doesn't have characteristics to speak of,
881     // editbin will silently lie to you if you attempt to set any.
882     if (COFFBigObjHeader)
883       return 0;
884     llvm_unreachable("no COFF header!");
885   }
886 
887   uint32_t getTimeDateStamp() const {
888     if (COFFHeader)
889       return COFFHeader->TimeDateStamp;
890     if (COFFBigObjHeader)
891       return COFFBigObjHeader->TimeDateStamp;
892     llvm_unreachable("no COFF header!");
893   }
894 
895   uint32_t getNumberOfSections() const {
896     if (COFFHeader)
897       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
898     if (COFFBigObjHeader)
899       return COFFBigObjHeader->NumberOfSections;
900     llvm_unreachable("no COFF header!");
901   }
902 
903   uint32_t getPointerToSymbolTable() const {
904     if (COFFHeader)
905       return COFFHeader->isImportLibrary() ? 0
906                                            : COFFHeader->PointerToSymbolTable;
907     if (COFFBigObjHeader)
908       return COFFBigObjHeader->PointerToSymbolTable;
909     llvm_unreachable("no COFF header!");
910   }
911 
912   uint32_t getRawNumberOfSymbols() const {
913     if (COFFHeader)
914       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
915     if (COFFBigObjHeader)
916       return COFFBigObjHeader->NumberOfSymbols;
917     llvm_unreachable("no COFF header!");
918   }
919 
920   uint32_t getNumberOfSymbols() const {
921     if (!SymbolTable16 && !SymbolTable32)
922       return 0;
923     return getRawNumberOfSymbols();
924   }
925 
926   uint32_t getStringTableSize() const { return StringTableSize; }
927 
928   const coff_load_configuration32 *getLoadConfig32() const {
929     assert(!is64());
930     return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig);
931   }
932 
933   const coff_load_configuration64 *getLoadConfig64() const {
934     assert(is64());
935     return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig);
936   }
937   StringRef getRelocationTypeName(uint16_t Type) const;
938 
939 protected:
940   void moveSymbolNext(DataRefImpl &Symb) const override;
941   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
942   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
943   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
944   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
945   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
946   Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
947   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
948   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
949   void moveSectionNext(DataRefImpl &Sec) const override;
950   Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
951   uint64_t getSectionAddress(DataRefImpl Sec) const override;
952   uint64_t getSectionIndex(DataRefImpl Sec) const override;
953   uint64_t getSectionSize(DataRefImpl Sec) const override;
954   Expected<ArrayRef<uint8_t>>
955   getSectionContents(DataRefImpl Sec) const override;
956   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
957   bool isSectionCompressed(DataRefImpl Sec) const override;
958   bool isSectionText(DataRefImpl Sec) const override;
959   bool isSectionData(DataRefImpl Sec) const override;
960   bool isSectionBSS(DataRefImpl Sec) const override;
961   bool isSectionVirtual(DataRefImpl Sec) const override;
962   bool isDebugSection(DataRefImpl Sec) const override;
963   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
964   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
965 
966   void moveRelocationNext(DataRefImpl &Rel) const override;
967   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
968   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
969   uint64_t getRelocationType(DataRefImpl Rel) const override;
970   void getRelocationTypeName(DataRefImpl Rel,
971                              SmallVectorImpl<char> &Result) const override;
972 
973 public:
974   basic_symbol_iterator symbol_begin() const override;
975   basic_symbol_iterator symbol_end() const override;
976   section_iterator section_begin() const override;
977   section_iterator section_end() const override;
978 
979   const coff_section *getCOFFSection(const SectionRef &Section) const;
980   COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
981   COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
982   const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
983   unsigned getSectionID(SectionRef Sec) const;
984   unsigned getSymbolSectionID(SymbolRef Sym) const;
985 
986   uint8_t getBytesInAddress() const override;
987   StringRef getFileFormatName() const override;
988   Triple::ArchType getArch() const override;
989   Expected<uint64_t> getStartAddress() const override;
990   SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
991 
992   import_directory_iterator import_directory_begin() const;
993   import_directory_iterator import_directory_end() const;
994   delay_import_directory_iterator delay_import_directory_begin() const;
995   delay_import_directory_iterator delay_import_directory_end() const;
996   export_directory_iterator export_directory_begin() const;
997   export_directory_iterator export_directory_end() const;
998   base_reloc_iterator base_reloc_begin() const;
999   base_reloc_iterator base_reloc_end() const;
1000   const debug_directory *debug_directory_begin() const {
1001     return DebugDirectoryBegin;
1002   }
1003   const debug_directory *debug_directory_end() const {
1004     return DebugDirectoryEnd;
1005   }
1006 
1007   iterator_range<import_directory_iterator> import_directories() const;
1008   iterator_range<delay_import_directory_iterator>
1009       delay_import_directories() const;
1010   iterator_range<export_directory_iterator> export_directories() const;
1011   iterator_range<base_reloc_iterator> base_relocs() const;
1012   iterator_range<const debug_directory *> debug_directories() const {
1013     return make_range(debug_directory_begin(), debug_directory_end());
1014   }
1015 
1016   const coff_tls_directory32 *getTLSDirectory32() const {
1017     return TLSDirectory32;
1018   }
1019   const coff_tls_directory64 *getTLSDirectory64() const {
1020     return TLSDirectory64;
1021   }
1022 
1023   const dos_header *getDOSHeader() const {
1024     if (!PE32Header && !PE32PlusHeader)
1025       return nullptr;
1026     return reinterpret_cast<const dos_header *>(base());
1027   }
1028 
1029   const coff_file_header *getCOFFHeader() const { return COFFHeader; }
1030   const coff_bigobj_file_header *getCOFFBigObjHeader() const {
1031     return COFFBigObjHeader;
1032   }
1033   const pe32_header *getPE32Header() const { return PE32Header; }
1034   const pe32plus_header *getPE32PlusHeader() const { return PE32PlusHeader; }
1035 
1036   const data_directory *getDataDirectory(uint32_t index) const;
1037   Expected<const coff_section *> getSection(int32_t index) const;
1038 
1039   Expected<COFFSymbolRef> getSymbol(uint32_t index) const {
1040     if (index >= getNumberOfSymbols())
1041       return errorCodeToError(object_error::parse_failed);
1042     if (SymbolTable16)
1043       return COFFSymbolRef(SymbolTable16 + index);
1044     if (SymbolTable32)
1045       return COFFSymbolRef(SymbolTable32 + index);
1046     return errorCodeToError(object_error::parse_failed);
1047   }
1048 
1049   template <typename T>
1050   Error getAuxSymbol(uint32_t index, const T *&Res) const {
1051     Expected<COFFSymbolRef> S = getSymbol(index);
1052     if (Error E = S.takeError())
1053       return E;
1054     Res = reinterpret_cast<const T *>(S->getRawPtr());
1055     return Error::success();
1056   }
1057 
1058   Expected<StringRef> getSymbolName(COFFSymbolRef Symbol) const;
1059   Expected<StringRef> getSymbolName(const coff_symbol_generic *Symbol) const;
1060 
1061   ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
1062 
1063   uint32_t getSymbolIndex(COFFSymbolRef Symbol) const;
1064 
1065   size_t getSymbolTableEntrySize() const {
1066     if (COFFHeader)
1067       return sizeof(coff_symbol16);
1068     if (COFFBigObjHeader)
1069       return sizeof(coff_symbol32);
1070     llvm_unreachable("null symbol table pointer!");
1071   }
1072 
1073   ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const;
1074 
1075   Expected<StringRef> getSectionName(const coff_section *Sec) const;
1076   uint64_t getSectionSize(const coff_section *Sec) const;
1077   Error getSectionContents(const coff_section *Sec,
1078                            ArrayRef<uint8_t> &Res) const;
1079 
1080   uint64_t getImageBase() const;
1081   Error getVaPtr(uint64_t VA, uintptr_t &Res) const;
1082   Error getRvaPtr(uint32_t Rva, uintptr_t &Res,
1083                   const char *ErrorContext = nullptr) const;
1084 
1085   /// Given an RVA base and size, returns a valid array of bytes or an error
1086   /// code if the RVA and size is not contained completely within a valid
1087   /// section.
1088   Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
1089                              ArrayRef<uint8_t> &Contents,
1090                              const char *ErrorContext = nullptr) const;
1091 
1092   Error getHintName(uint32_t Rva, uint16_t &Hint,
1093                               StringRef &Name) const;
1094 
1095   /// Get PDB information out of a codeview debug directory entry.
1096   Error getDebugPDBInfo(const debug_directory *DebugDir,
1097                         const codeview::DebugInfo *&Info,
1098                         StringRef &PDBFileName) const;
1099 
1100   /// Get PDB information from an executable. If the information is not present,
1101   /// Info will be set to nullptr and PDBFileName will be empty. An error is
1102   /// returned only on corrupt object files. Convenience accessor that can be
1103   /// used if the debug directory is not already handy.
1104   Error getDebugPDBInfo(const codeview::DebugInfo *&Info,
1105                         StringRef &PDBFileName) const;
1106 
1107   bool isRelocatableObject() const override;
1108   bool is64() const { return PE32PlusHeader; }
1109 
1110   StringRef mapDebugSectionName(StringRef Name) const override;
1111 
1112   static bool classof(const Binary *v) { return v->isCOFF(); }
1113 };
1114 
1115 // The iterator for the import directory table.
1116 class ImportDirectoryEntryRef {
1117 public:
1118   ImportDirectoryEntryRef() = default;
1119   ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
1120                           uint32_t I, const COFFObjectFile *Owner)
1121       : ImportTable(Table), Index(I), OwningObject(Owner) {}
1122 
1123   bool operator==(const ImportDirectoryEntryRef &Other) const;
1124   void moveNext();
1125 
1126   imported_symbol_iterator imported_symbol_begin() const;
1127   imported_symbol_iterator imported_symbol_end() const;
1128   iterator_range<imported_symbol_iterator> imported_symbols() const;
1129 
1130   imported_symbol_iterator lookup_table_begin() const;
1131   imported_symbol_iterator lookup_table_end() const;
1132   iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
1133 
1134   Error getName(StringRef &Result) const;
1135   Error getImportLookupTableRVA(uint32_t &Result) const;
1136   Error getImportAddressTableRVA(uint32_t &Result) const;
1137 
1138   Error
1139   getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
1140 
1141 private:
1142   const coff_import_directory_table_entry *ImportTable;
1143   uint32_t Index;
1144   const COFFObjectFile *OwningObject = nullptr;
1145 };
1146 
1147 class DelayImportDirectoryEntryRef {
1148 public:
1149   DelayImportDirectoryEntryRef() = default;
1150   DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
1151                                uint32_t I, const COFFObjectFile *Owner)
1152       : Table(T), Index(I), OwningObject(Owner) {}
1153 
1154   bool operator==(const DelayImportDirectoryEntryRef &Other) const;
1155   void moveNext();
1156 
1157   imported_symbol_iterator imported_symbol_begin() const;
1158   imported_symbol_iterator imported_symbol_end() const;
1159   iterator_range<imported_symbol_iterator> imported_symbols() const;
1160 
1161   Error getName(StringRef &Result) const;
1162   Error getDelayImportTable(
1163       const delay_import_directory_table_entry *&Result) const;
1164   Error getImportAddress(int AddrIndex, uint64_t &Result) const;
1165 
1166 private:
1167   const delay_import_directory_table_entry *Table;
1168   uint32_t Index;
1169   const COFFObjectFile *OwningObject = nullptr;
1170 };
1171 
1172 // The iterator for the export directory table entry.
1173 class ExportDirectoryEntryRef {
1174 public:
1175   ExportDirectoryEntryRef() = default;
1176   ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
1177                           const COFFObjectFile *Owner)
1178       : ExportTable(Table), Index(I), OwningObject(Owner) {}
1179 
1180   bool operator==(const ExportDirectoryEntryRef &Other) const;
1181   void moveNext();
1182 
1183   Error getDllName(StringRef &Result) const;
1184   Error getOrdinalBase(uint32_t &Result) const;
1185   Error getOrdinal(uint32_t &Result) const;
1186   Error getExportRVA(uint32_t &Result) const;
1187   Error getSymbolName(StringRef &Result) const;
1188 
1189   Error isForwarder(bool &Result) const;
1190   Error getForwardTo(StringRef &Result) const;
1191 
1192 private:
1193   const export_directory_table_entry *ExportTable;
1194   uint32_t Index;
1195   const COFFObjectFile *OwningObject = nullptr;
1196 };
1197 
1198 class ImportedSymbolRef {
1199 public:
1200   ImportedSymbolRef() = default;
1201   ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
1202                     const COFFObjectFile *Owner)
1203       : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
1204   ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
1205                     const COFFObjectFile *Owner)
1206       : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
1207 
1208   bool operator==(const ImportedSymbolRef &Other) const;
1209   void moveNext();
1210 
1211   Error getSymbolName(StringRef &Result) const;
1212   Error isOrdinal(bool &Result) const;
1213   Error getOrdinal(uint16_t &Result) const;
1214   Error getHintNameRVA(uint32_t &Result) const;
1215 
1216 private:
1217   const import_lookup_table_entry32 *Entry32;
1218   const import_lookup_table_entry64 *Entry64;
1219   uint32_t Index;
1220   const COFFObjectFile *OwningObject = nullptr;
1221 };
1222 
1223 class BaseRelocRef {
1224 public:
1225   BaseRelocRef() = default;
1226   BaseRelocRef(const coff_base_reloc_block_header *Header,
1227                const COFFObjectFile *Owner)
1228       : Header(Header), Index(0) {}
1229 
1230   bool operator==(const BaseRelocRef &Other) const;
1231   void moveNext();
1232 
1233   Error getType(uint8_t &Type) const;
1234   Error getRVA(uint32_t &Result) const;
1235 
1236 private:
1237   const coff_base_reloc_block_header *Header;
1238   uint32_t Index;
1239 };
1240 
1241 class ResourceSectionRef {
1242 public:
1243   ResourceSectionRef() = default;
1244   explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {}
1245 
1246   Error load(const COFFObjectFile *O);
1247   Error load(const COFFObjectFile *O, const SectionRef &S);
1248 
1249   Expected<ArrayRef<UTF16>>
1250   getEntryNameString(const coff_resource_dir_entry &Entry);
1251   Expected<const coff_resource_dir_table &>
1252   getEntrySubDir(const coff_resource_dir_entry &Entry);
1253   Expected<const coff_resource_data_entry &>
1254   getEntryData(const coff_resource_dir_entry &Entry);
1255   Expected<const coff_resource_dir_table &> getBaseTable();
1256   Expected<const coff_resource_dir_entry &>
1257   getTableEntry(const coff_resource_dir_table &Table, uint32_t Index);
1258 
1259   Expected<StringRef> getContents(const coff_resource_data_entry &Entry);
1260 
1261 private:
1262   BinaryByteStream BBS;
1263 
1264   SectionRef Section;
1265   const COFFObjectFile *Obj;
1266 
1267   std::vector<const coff_relocation *> Relocs;
1268 
1269   Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset);
1270   Expected<const coff_resource_dir_entry &>
1271   getTableEntryAtOffset(uint32_t Offset);
1272   Expected<const coff_resource_data_entry &>
1273   getDataEntryAtOffset(uint32_t Offset);
1274   Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset);
1275 };
1276 
1277 // Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
1278 struct FpoData {
1279   support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
1280   support::ulittle32_t Size;   // cbProcSize: # bytes in function
1281   support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
1282   support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
1283   support::ulittle16_t Attributes;
1284 
1285   // cbProlog: # bytes in prolog
1286   int getPrologSize() const { return Attributes & 0xF; }
1287 
1288   // cbRegs: # regs saved
1289   int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
1290 
1291   // fHasSEH: true if seh is func
1292   bool hasSEH() const { return (Attributes >> 9) & 1; }
1293 
1294   // fUseBP: true if EBP has been allocated
1295   bool useBP() const { return (Attributes >> 10) & 1; }
1296 
1297   // cbFrame: frame pointer
1298   frame_type getFP() const { return static_cast<frame_type>(Attributes >> 14); }
1299 };
1300 
1301 class SectionStrippedError
1302     : public ErrorInfo<SectionStrippedError, BinaryError> {
1303 public:
1304   SectionStrippedError() { setErrorCode(object_error::section_stripped); }
1305 };
1306 
1307 } // end namespace object
1308 
1309 } // end namespace llvm
1310 
1311 #endif // LLVM_OBJECT_COFF_H
1312