]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Object/COFF.h
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Object / COFF.h
1 //===- COFF.h - COFF object file implementation -----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_OBJECT_COFF_H
15 #define LLVM_OBJECT_COFF_H
16
17 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
19 #include "llvm/MC/SubtargetFeature.h"
20 #include "llvm/Object/Binary.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorOr.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
44 using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>;
45 using delay_import_directory_iterator =
46     content_iterator<DelayImportDirectoryEntryRef>;
47 using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>;
48 using imported_symbol_iterator = content_iterator<ImportedSymbolRef>;
49 using base_reloc_iterator = content_iterator<BaseRelocRef>;
50
51 /// The DOS compatible header at the front of all PE/COFF executables.
52 struct dos_header {
53   char                 Magic[2];
54   support::ulittle16_t UsedBytesInTheLastPage;
55   support::ulittle16_t FileSizeInPages;
56   support::ulittle16_t NumberOfRelocationItems;
57   support::ulittle16_t HeaderSizeInParagraphs;
58   support::ulittle16_t MinimumExtraParagraphs;
59   support::ulittle16_t MaximumExtraParagraphs;
60   support::ulittle16_t InitialRelativeSS;
61   support::ulittle16_t InitialSP;
62   support::ulittle16_t Checksum;
63   support::ulittle16_t InitialIP;
64   support::ulittle16_t InitialRelativeCS;
65   support::ulittle16_t AddressOfRelocationTable;
66   support::ulittle16_t OverlayNumber;
67   support::ulittle16_t Reserved[4];
68   support::ulittle16_t OEMid;
69   support::ulittle16_t OEMinfo;
70   support::ulittle16_t Reserved2[10];
71   support::ulittle32_t AddressOfNewExeHeader;
72 };
73
74 struct coff_file_header {
75   support::ulittle16_t Machine;
76   support::ulittle16_t NumberOfSections;
77   support::ulittle32_t TimeDateStamp;
78   support::ulittle32_t PointerToSymbolTable;
79   support::ulittle32_t NumberOfSymbols;
80   support::ulittle16_t SizeOfOptionalHeader;
81   support::ulittle16_t Characteristics;
82
83   bool isImportLibrary() const { return NumberOfSections == 0xffff; }
84 };
85
86 struct coff_bigobj_file_header {
87   support::ulittle16_t Sig1;
88   support::ulittle16_t Sig2;
89   support::ulittle16_t Version;
90   support::ulittle16_t Machine;
91   support::ulittle32_t TimeDateStamp;
92   uint8_t              UUID[16];
93   support::ulittle32_t unused1;
94   support::ulittle32_t unused2;
95   support::ulittle32_t unused3;
96   support::ulittle32_t unused4;
97   support::ulittle32_t NumberOfSections;
98   support::ulittle32_t PointerToSymbolTable;
99   support::ulittle32_t NumberOfSymbols;
100 };
101
102 /// The 32-bit PE header that follows the COFF header.
103 struct pe32_header {
104   support::ulittle16_t Magic;
105   uint8_t MajorLinkerVersion;
106   uint8_t MinorLinkerVersion;
107   support::ulittle32_t SizeOfCode;
108   support::ulittle32_t SizeOfInitializedData;
109   support::ulittle32_t SizeOfUninitializedData;
110   support::ulittle32_t AddressOfEntryPoint;
111   support::ulittle32_t BaseOfCode;
112   support::ulittle32_t BaseOfData;
113   support::ulittle32_t ImageBase;
114   support::ulittle32_t SectionAlignment;
115   support::ulittle32_t FileAlignment;
116   support::ulittle16_t MajorOperatingSystemVersion;
117   support::ulittle16_t MinorOperatingSystemVersion;
118   support::ulittle16_t MajorImageVersion;
119   support::ulittle16_t MinorImageVersion;
120   support::ulittle16_t MajorSubsystemVersion;
121   support::ulittle16_t MinorSubsystemVersion;
122   support::ulittle32_t Win32VersionValue;
123   support::ulittle32_t SizeOfImage;
124   support::ulittle32_t SizeOfHeaders;
125   support::ulittle32_t CheckSum;
126   support::ulittle16_t Subsystem;
127   // FIXME: This should be DllCharacteristics.
128   support::ulittle16_t DLLCharacteristics;
129   support::ulittle32_t SizeOfStackReserve;
130   support::ulittle32_t SizeOfStackCommit;
131   support::ulittle32_t SizeOfHeapReserve;
132   support::ulittle32_t SizeOfHeapCommit;
133   support::ulittle32_t LoaderFlags;
134   // FIXME: This should be NumberOfRvaAndSizes.
135   support::ulittle32_t NumberOfRvaAndSize;
136 };
137
138 /// The 64-bit PE header that follows the COFF header.
139 struct pe32plus_header {
140   support::ulittle16_t Magic;
141   uint8_t MajorLinkerVersion;
142   uint8_t MinorLinkerVersion;
143   support::ulittle32_t SizeOfCode;
144   support::ulittle32_t SizeOfInitializedData;
145   support::ulittle32_t SizeOfUninitializedData;
146   support::ulittle32_t AddressOfEntryPoint;
147   support::ulittle32_t BaseOfCode;
148   support::ulittle64_t ImageBase;
149   support::ulittle32_t SectionAlignment;
150   support::ulittle32_t FileAlignment;
151   support::ulittle16_t MajorOperatingSystemVersion;
152   support::ulittle16_t MinorOperatingSystemVersion;
153   support::ulittle16_t MajorImageVersion;
154   support::ulittle16_t MinorImageVersion;
155   support::ulittle16_t MajorSubsystemVersion;
156   support::ulittle16_t MinorSubsystemVersion;
157   support::ulittle32_t Win32VersionValue;
158   support::ulittle32_t SizeOfImage;
159   support::ulittle32_t SizeOfHeaders;
160   support::ulittle32_t CheckSum;
161   support::ulittle16_t Subsystem;
162   support::ulittle16_t DLLCharacteristics;
163   support::ulittle64_t SizeOfStackReserve;
164   support::ulittle64_t SizeOfStackCommit;
165   support::ulittle64_t SizeOfHeapReserve;
166   support::ulittle64_t SizeOfHeapCommit;
167   support::ulittle32_t LoaderFlags;
168   support::ulittle32_t NumberOfRvaAndSize;
169 };
170
171 struct data_directory {
172   support::ulittle32_t RelativeVirtualAddress;
173   support::ulittle32_t Size;
174 };
175
176 struct debug_directory {
177   support::ulittle32_t Characteristics;
178   support::ulittle32_t TimeDateStamp;
179   support::ulittle16_t MajorVersion;
180   support::ulittle16_t MinorVersion;
181   support::ulittle32_t Type;
182   support::ulittle32_t SizeOfData;
183   support::ulittle32_t AddressOfRawData;
184   support::ulittle32_t PointerToRawData;
185 };
186
187 template <typename IntTy>
188 struct import_lookup_table_entry {
189   IntTy Data;
190
191   bool isOrdinal() const { return Data < 0; }
192
193   uint16_t getOrdinal() const {
194     assert(isOrdinal() && "ILT entry is not an ordinal!");
195     return Data & 0xFFFF;
196   }
197
198   uint32_t getHintNameRVA() const {
199     assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
200     return Data & 0xFFFFFFFF;
201   }
202 };
203
204 using import_lookup_table_entry32 =
205     import_lookup_table_entry<support::little32_t>;
206 using import_lookup_table_entry64 =
207     import_lookup_table_entry<support::little64_t>;
208
209 struct delay_import_directory_table_entry {
210   // dumpbin reports this field as "Characteristics" instead of "Attributes".
211   support::ulittle32_t Attributes;
212   support::ulittle32_t Name;
213   support::ulittle32_t ModuleHandle;
214   support::ulittle32_t DelayImportAddressTable;
215   support::ulittle32_t DelayImportNameTable;
216   support::ulittle32_t BoundDelayImportTable;
217   support::ulittle32_t UnloadDelayImportTable;
218   support::ulittle32_t TimeStamp;
219 };
220
221 struct export_directory_table_entry {
222   support::ulittle32_t ExportFlags;
223   support::ulittle32_t TimeDateStamp;
224   support::ulittle16_t MajorVersion;
225   support::ulittle16_t MinorVersion;
226   support::ulittle32_t NameRVA;
227   support::ulittle32_t OrdinalBase;
228   support::ulittle32_t AddressTableEntries;
229   support::ulittle32_t NumberOfNamePointers;
230   support::ulittle32_t ExportAddressTableRVA;
231   support::ulittle32_t NamePointerRVA;
232   support::ulittle32_t OrdinalTableRVA;
233 };
234
235 union export_address_table_entry {
236   support::ulittle32_t ExportRVA;
237   support::ulittle32_t ForwarderRVA;
238 };
239
240 using export_name_pointer_table_entry = support::ulittle32_t;
241 using export_ordinal_table_entry = support::ulittle16_t;
242
243 struct StringTableOffset {
244   support::ulittle32_t Zeroes;
245   support::ulittle32_t Offset;
246 };
247
248 template <typename SectionNumberType>
249 struct coff_symbol {
250   union {
251     char ShortName[COFF::NameSize];
252     StringTableOffset Offset;
253   } Name;
254
255   support::ulittle32_t Value;
256   SectionNumberType SectionNumber;
257
258   support::ulittle16_t Type;
259
260   uint8_t StorageClass;
261   uint8_t NumberOfAuxSymbols;
262 };
263
264 using coff_symbol16 = coff_symbol<support::ulittle16_t>;
265 using coff_symbol32 = coff_symbol<support::ulittle32_t>;
266
267 // Contains only common parts of coff_symbol16 and coff_symbol32.
268 struct coff_symbol_generic {
269   union {
270     char ShortName[COFF::NameSize];
271     StringTableOffset Offset;
272   } Name;
273   support::ulittle32_t Value;
274 };
275
276 class COFFSymbolRef {
277 public:
278   COFFSymbolRef() = default;
279   COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {}
280   COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {}
281
282   const void *getRawPtr() const {
283     return CS16 ? static_cast<const void *>(CS16) : CS32;
284   }
285
286   const coff_symbol_generic *getGeneric() const {
287     if (CS16)
288       return reinterpret_cast<const coff_symbol_generic *>(CS16);
289     return reinterpret_cast<const coff_symbol_generic *>(CS32);
290   }
291
292   friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
293     return A.getRawPtr() < B.getRawPtr();
294   }
295
296   bool isBigObj() const {
297     if (CS16)
298       return false;
299     if (CS32)
300       return true;
301     llvm_unreachable("COFFSymbolRef points to nothing!");
302   }
303
304   const char *getShortName() const {
305     return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
306   }
307
308   const StringTableOffset &getStringTableOffset() const {
309     assert(isSet() && "COFFSymbolRef points to nothing!");
310     return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
311   }
312
313   uint32_t getValue() const { return CS16 ? CS16->Value : CS32->Value; }
314
315   int32_t getSectionNumber() const {
316     assert(isSet() && "COFFSymbolRef points to nothing!");
317     if (CS16) {
318       // Reserved sections are returned as negative numbers.
319       if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
320         return CS16->SectionNumber;
321       return static_cast<int16_t>(CS16->SectionNumber);
322     }
323     return static_cast<int32_t>(CS32->SectionNumber);
324   }
325
326   uint16_t getType() const {
327     assert(isSet() && "COFFSymbolRef points to nothing!");
328     return CS16 ? CS16->Type : CS32->Type;
329   }
330
331   uint8_t getStorageClass() const {
332     assert(isSet() && "COFFSymbolRef points to nothing!");
333     return CS16 ? CS16->StorageClass : CS32->StorageClass;
334   }
335
336   uint8_t getNumberOfAuxSymbols() const {
337     assert(isSet() && "COFFSymbolRef points to nothing!");
338     return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols;
339   }
340
341   uint8_t getBaseType() const { return getType() & 0x0F; }
342
343   uint8_t getComplexType() const {
344     return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
345   }
346
347   bool isAbsolute() const {
348     return getSectionNumber() == -1;
349   }
350
351   bool isExternal() const {
352     return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
353   }
354
355   bool isCommon() const {
356     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
357            getValue() != 0;
358   }
359
360   bool isUndefined() const {
361     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
362            getValue() == 0;
363   }
364
365   bool isWeakExternal() const {
366     return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
367   }
368
369   bool isFunctionDefinition() const {
370     return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
371            getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
372            !COFF::isReservedSectionNumber(getSectionNumber());
373   }
374
375   bool isFunctionLineInfo() const {
376     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
377   }
378
379   bool isAnyUndefined() const {
380     return isUndefined() || isWeakExternal();
381   }
382
383   bool isFileRecord() const {
384     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
385   }
386
387   bool isSection() const {
388     return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
389   }
390
391   bool isSectionDefinition() const {
392     // C++/CLI creates external ABS symbols for non-const appdomain globals.
393     // These are also followed by an auxiliary section definition.
394     bool isAppdomainGlobal =
395         getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
396         getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE;
397     bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
398     if (!getNumberOfAuxSymbols())
399       return false;
400     return isAppdomainGlobal || isOrdinarySection;
401   }
402
403   bool isCLRToken() const {
404     return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
405   }
406
407 private:
408   bool isSet() const { return CS16 || CS32; }
409
410   const coff_symbol16 *CS16 = nullptr;
411   const coff_symbol32 *CS32 = nullptr;
412 };
413
414 struct coff_section {
415   char Name[COFF::NameSize];
416   support::ulittle32_t VirtualSize;
417   support::ulittle32_t VirtualAddress;
418   support::ulittle32_t SizeOfRawData;
419   support::ulittle32_t PointerToRawData;
420   support::ulittle32_t PointerToRelocations;
421   support::ulittle32_t PointerToLinenumbers;
422   support::ulittle16_t NumberOfRelocations;
423   support::ulittle16_t NumberOfLinenumbers;
424   support::ulittle32_t Characteristics;
425
426   // Returns true if the actual number of relocations is stored in
427   // VirtualAddress field of the first relocation table entry.
428   bool hasExtendedRelocations() const {
429     return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
430            NumberOfRelocations == UINT16_MAX;
431   }
432
433   uint32_t getAlignment() const {
434     // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to
435     // IMAGE_SCN_ALIGN_1BYTES.
436     if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD)
437       return 1;
438
439     // Bit [20:24] contains section alignment. Both 0 and 1 mean alignment 1.
440     uint32_t Shift = (Characteristics >> 20) & 0xF;
441     if (Shift > 0)
442       return 1U << (Shift - 1);
443     return 1;
444   }
445 };
446
447 struct coff_relocation {
448   support::ulittle32_t VirtualAddress;
449   support::ulittle32_t SymbolTableIndex;
450   support::ulittle16_t Type;
451 };
452
453 struct coff_aux_function_definition {
454   support::ulittle32_t TagIndex;
455   support::ulittle32_t TotalSize;
456   support::ulittle32_t PointerToLinenumber;
457   support::ulittle32_t PointerToNextFunction;
458   char Unused1[2];
459 };
460
461 static_assert(sizeof(coff_aux_function_definition) == 18,
462               "auxiliary entry must be 18 bytes");
463
464 struct coff_aux_bf_and_ef_symbol {
465   char Unused1[4];
466   support::ulittle16_t Linenumber;
467   char Unused2[6];
468   support::ulittle32_t PointerToNextFunction;
469   char Unused3[2];
470 };
471
472 static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18,
473               "auxiliary entry must be 18 bytes");
474
475 struct coff_aux_weak_external {
476   support::ulittle32_t TagIndex;
477   support::ulittle32_t Characteristics;
478   char Unused1[10];
479 };
480
481 static_assert(sizeof(coff_aux_weak_external) == 18,
482               "auxiliary entry must be 18 bytes");
483
484 struct coff_aux_section_definition {
485   support::ulittle32_t Length;
486   support::ulittle16_t NumberOfRelocations;
487   support::ulittle16_t NumberOfLinenumbers;
488   support::ulittle32_t CheckSum;
489   support::ulittle16_t NumberLowPart;
490   uint8_t              Selection;
491   uint8_t              Unused;
492   support::ulittle16_t NumberHighPart;
493   int32_t getNumber(bool IsBigObj) const {
494     uint32_t Number = static_cast<uint32_t>(NumberLowPart);
495     if (IsBigObj)
496       Number |= static_cast<uint32_t>(NumberHighPart) << 16;
497     return static_cast<int32_t>(Number);
498   }
499 };
500
501 static_assert(sizeof(coff_aux_section_definition) == 18,
502               "auxiliary entry must be 18 bytes");
503
504 struct coff_aux_clr_token {
505   uint8_t              AuxType;
506   uint8_t              Reserved;
507   support::ulittle32_t SymbolTableIndex;
508   char                 MBZ[12];
509 };
510
511 static_assert(sizeof(coff_aux_clr_token) == 18,
512               "auxiliary entry must be 18 bytes");
513
514 struct coff_import_header {
515   support::ulittle16_t Sig1;
516   support::ulittle16_t Sig2;
517   support::ulittle16_t Version;
518   support::ulittle16_t Machine;
519   support::ulittle32_t TimeDateStamp;
520   support::ulittle32_t SizeOfData;
521   support::ulittle16_t OrdinalHint;
522   support::ulittle16_t TypeInfo;
523
524   int getType() const { return TypeInfo & 0x3; }
525   int getNameType() const { return (TypeInfo >> 2) & 0x7; }
526 };
527
528 struct coff_import_directory_table_entry {
529   support::ulittle32_t ImportLookupTableRVA;
530   support::ulittle32_t TimeDateStamp;
531   support::ulittle32_t ForwarderChain;
532   support::ulittle32_t NameRVA;
533   support::ulittle32_t ImportAddressTableRVA;
534
535   bool isNull() const {
536     return ImportLookupTableRVA == 0 && TimeDateStamp == 0 &&
537            ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0;
538   }
539 };
540
541 template <typename IntTy>
542 struct coff_tls_directory {
543   IntTy StartAddressOfRawData;
544   IntTy EndAddressOfRawData;
545   IntTy AddressOfIndex;
546   IntTy AddressOfCallBacks;
547   support::ulittle32_t SizeOfZeroFill;
548   support::ulittle32_t Characteristics;
549
550   uint32_t getAlignment() const {
551     // Bit [20:24] contains section alignment.
552     uint32_t Shift = (Characteristics & 0x00F00000) >> 20;
553     if (Shift > 0)
554       return 1U << (Shift - 1);
555     return 0;
556   }
557 };
558
559 using coff_tls_directory32 = coff_tls_directory<support::little32_t>;
560 using coff_tls_directory64 = coff_tls_directory<support::little64_t>;
561
562 struct coff_load_configuration32 {
563   support::ulittle32_t Characteristics;
564   support::ulittle32_t TimeDateStamp;
565   support::ulittle16_t MajorVersion;
566   support::ulittle16_t MinorVersion;
567   support::ulittle32_t GlobalFlagsClear;
568   support::ulittle32_t GlobalFlagsSet;
569   support::ulittle32_t CriticalSectionDefaultTimeout;
570   support::ulittle32_t DeCommitFreeBlockThreshold;
571   support::ulittle32_t DeCommitTotalFreeThreshold;
572   support::ulittle32_t LockPrefixTable;
573   support::ulittle32_t MaximumAllocationSize;
574   support::ulittle32_t VirtualMemoryThreshold;
575   support::ulittle32_t ProcessAffinityMask;
576   support::ulittle32_t ProcessHeapFlags;
577   support::ulittle16_t CSDVersion;
578   support::ulittle16_t Reserved;
579   support::ulittle32_t EditList;
580   support::ulittle32_t SecurityCookie;
581   support::ulittle32_t SEHandlerTable;
582   support::ulittle32_t SEHandlerCount;
583 };
584
585 struct coff_load_configuration64 {
586   support::ulittle32_t Characteristics;
587   support::ulittle32_t TimeDateStamp;
588   support::ulittle16_t MajorVersion;
589   support::ulittle16_t MinorVersion;
590   support::ulittle32_t GlobalFlagsClear;
591   support::ulittle32_t GlobalFlagsSet;
592   support::ulittle32_t CriticalSectionDefaultTimeout;
593   support::ulittle32_t DeCommitFreeBlockThreshold;
594   support::ulittle32_t DeCommitTotalFreeThreshold;
595   support::ulittle32_t LockPrefixTable;
596   support::ulittle32_t MaximumAllocationSize;
597   support::ulittle32_t VirtualMemoryThreshold;
598   support::ulittle32_t ProcessAffinityMask;
599   support::ulittle32_t ProcessHeapFlags;
600   support::ulittle16_t CSDVersion;
601   support::ulittle16_t Reserved;
602   support::ulittle32_t EditList;
603   support::ulittle64_t SecurityCookie;
604   support::ulittle64_t SEHandlerTable;
605   support::ulittle64_t SEHandlerCount;
606 };
607
608 struct coff_runtime_function_x64 {
609   support::ulittle32_t BeginAddress;
610   support::ulittle32_t EndAddress;
611   support::ulittle32_t UnwindInformation;
612 };
613
614 struct coff_base_reloc_block_header {
615   support::ulittle32_t PageRVA;
616   support::ulittle32_t BlockSize;
617 };
618
619 struct coff_base_reloc_block_entry {
620   support::ulittle16_t Data;
621
622   int getType() const { return Data >> 12; }
623   int getOffset() const { return Data & ((1 << 12) - 1); }
624 };
625
626 class COFFObjectFile : public ObjectFile {
627 private:
628   friend class ImportDirectoryEntryRef;
629   friend class ExportDirectoryEntryRef;
630   const coff_file_header *COFFHeader;
631   const coff_bigobj_file_header *COFFBigObjHeader;
632   const pe32_header *PE32Header;
633   const pe32plus_header *PE32PlusHeader;
634   const data_directory *DataDirectory;
635   const coff_section *SectionTable;
636   const coff_symbol16 *SymbolTable16;
637   const coff_symbol32 *SymbolTable32;
638   const char *StringTable;
639   uint32_t StringTableSize;
640   const coff_import_directory_table_entry *ImportDirectory;
641   const delay_import_directory_table_entry *DelayImportDirectory;
642   uint32_t NumberOfDelayImportDirectory;
643   const export_directory_table_entry *ExportDirectory;
644   const coff_base_reloc_block_header *BaseRelocHeader;
645   const coff_base_reloc_block_header *BaseRelocEnd;
646   const debug_directory *DebugDirectoryBegin;
647   const debug_directory *DebugDirectoryEnd;
648
649   std::error_code getString(uint32_t offset, StringRef &Res) const;
650
651   template <typename coff_symbol_type>
652   const coff_symbol_type *toSymb(DataRefImpl Symb) const;
653   const coff_section *toSec(DataRefImpl Sec) const;
654   const coff_relocation *toRel(DataRefImpl Rel) const;
655
656   std::error_code initSymbolTablePtr();
657   std::error_code initImportTablePtr();
658   std::error_code initDelayImportTablePtr();
659   std::error_code initExportTablePtr();
660   std::error_code initBaseRelocPtr();
661   std::error_code initDebugDirectoryPtr();
662
663 public:
664   uintptr_t getSymbolTable() const {
665     if (SymbolTable16)
666       return reinterpret_cast<uintptr_t>(SymbolTable16);
667     if (SymbolTable32)
668       return reinterpret_cast<uintptr_t>(SymbolTable32);
669     return uintptr_t(0);
670   }
671
672   uint16_t getMachine() const {
673     if (COFFHeader)
674       return COFFHeader->Machine;
675     if (COFFBigObjHeader)
676       return COFFBigObjHeader->Machine;
677     llvm_unreachable("no COFF header!");
678   }
679
680   uint16_t getSizeOfOptionalHeader() const {
681     if (COFFHeader)
682       return COFFHeader->isImportLibrary() ? 0
683                                            : COFFHeader->SizeOfOptionalHeader;
684     // bigobj doesn't have this field.
685     if (COFFBigObjHeader)
686       return 0;
687     llvm_unreachable("no COFF header!");
688   }
689
690   uint16_t getCharacteristics() const {
691     if (COFFHeader)
692       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
693     // bigobj doesn't have characteristics to speak of,
694     // editbin will silently lie to you if you attempt to set any.
695     if (COFFBigObjHeader)
696       return 0;
697     llvm_unreachable("no COFF header!");
698   }
699
700   uint32_t getTimeDateStamp() const {
701     if (COFFHeader)
702       return COFFHeader->TimeDateStamp;
703     if (COFFBigObjHeader)
704       return COFFBigObjHeader->TimeDateStamp;
705     llvm_unreachable("no COFF header!");
706   }
707
708   uint32_t getNumberOfSections() const {
709     if (COFFHeader)
710       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
711     if (COFFBigObjHeader)
712       return COFFBigObjHeader->NumberOfSections;
713     llvm_unreachable("no COFF header!");
714   }
715
716   uint32_t getPointerToSymbolTable() const {
717     if (COFFHeader)
718       return COFFHeader->isImportLibrary() ? 0
719                                            : COFFHeader->PointerToSymbolTable;
720     if (COFFBigObjHeader)
721       return COFFBigObjHeader->PointerToSymbolTable;
722     llvm_unreachable("no COFF header!");
723   }
724
725   uint32_t getRawNumberOfSymbols() const {
726     if (COFFHeader)
727       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
728     if (COFFBigObjHeader)
729       return COFFBigObjHeader->NumberOfSymbols;
730     llvm_unreachable("no COFF header!");
731   }
732
733   uint32_t getNumberOfSymbols() const {
734     if (!SymbolTable16 && !SymbolTable32)
735       return 0;
736     return getRawNumberOfSymbols();
737   }
738
739 protected:
740   void moveSymbolNext(DataRefImpl &Symb) const override;
741   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
742   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
743   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
744   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
745   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
746   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
747   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
748   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
749   void moveSectionNext(DataRefImpl &Sec) const override;
750   std::error_code getSectionName(DataRefImpl Sec,
751                                  StringRef &Res) const override;
752   uint64_t getSectionAddress(DataRefImpl Sec) const override;
753   uint64_t getSectionSize(DataRefImpl Sec) const override;
754   std::error_code getSectionContents(DataRefImpl Sec,
755                                      StringRef &Res) const override;
756   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
757   bool isSectionCompressed(DataRefImpl Sec) const override;
758   bool isSectionText(DataRefImpl Sec) const override;
759   bool isSectionData(DataRefImpl Sec) const override;
760   bool isSectionBSS(DataRefImpl Sec) const override;
761   bool isSectionVirtual(DataRefImpl Sec) const override;
762   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
763   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
764
765   void moveRelocationNext(DataRefImpl &Rel) const override;
766   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
767   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
768   uint64_t getRelocationType(DataRefImpl Rel) const override;
769   void getRelocationTypeName(DataRefImpl Rel,
770                              SmallVectorImpl<char> &Result) const override;
771
772 public:
773   COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
774
775   basic_symbol_iterator symbol_begin() const override;
776   basic_symbol_iterator symbol_end() const override;
777   section_iterator section_begin() const override;
778   section_iterator section_end() const override;
779
780   const coff_section *getCOFFSection(const SectionRef &Section) const;
781   COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
782   COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
783   const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
784   unsigned getSectionID(SectionRef Sec) const;
785   unsigned getSymbolSectionID(SymbolRef Sym) const;
786
787   uint8_t getBytesInAddress() const override;
788   StringRef getFileFormatName() const override;
789   unsigned getArch() const override;
790   SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
791
792   import_directory_iterator import_directory_begin() const;
793   import_directory_iterator import_directory_end() const;
794   delay_import_directory_iterator delay_import_directory_begin() const;
795   delay_import_directory_iterator delay_import_directory_end() const;
796   export_directory_iterator export_directory_begin() const;
797   export_directory_iterator export_directory_end() const;
798   base_reloc_iterator base_reloc_begin() const;
799   base_reloc_iterator base_reloc_end() const;
800   const debug_directory *debug_directory_begin() const {
801     return DebugDirectoryBegin;
802   }
803   const debug_directory *debug_directory_end() const {
804     return DebugDirectoryEnd;
805   }
806
807   iterator_range<import_directory_iterator> import_directories() const;
808   iterator_range<delay_import_directory_iterator>
809       delay_import_directories() const;
810   iterator_range<export_directory_iterator> export_directories() const;
811   iterator_range<base_reloc_iterator> base_relocs() const;
812   iterator_range<const debug_directory *> debug_directories() const {
813     return make_range(debug_directory_begin(), debug_directory_end());
814   }
815
816   const dos_header *getDOSHeader() const {
817     if (!PE32Header && !PE32PlusHeader)
818       return nullptr;
819     return reinterpret_cast<const dos_header *>(base());
820   }
821   std::error_code getPE32Header(const pe32_header *&Res) const;
822   std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
823   std::error_code getDataDirectory(uint32_t index,
824                                    const data_directory *&Res) const;
825   std::error_code getSection(int32_t index, const coff_section *&Res) const;
826
827   template <typename coff_symbol_type>
828   std::error_code getSymbol(uint32_t Index,
829                             const coff_symbol_type *&Res) const {
830     if (Index >= getNumberOfSymbols())
831       return object_error::parse_failed;
832
833     Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
834     return std::error_code();
835   }
836   ErrorOr<COFFSymbolRef> getSymbol(uint32_t index) const {
837     if (SymbolTable16) {
838       const coff_symbol16 *Symb = nullptr;
839       if (std::error_code EC = getSymbol(index, Symb))
840         return EC;
841       return COFFSymbolRef(Symb);
842     }
843     if (SymbolTable32) {
844       const coff_symbol32 *Symb = nullptr;
845       if (std::error_code EC = getSymbol(index, Symb))
846         return EC;
847       return COFFSymbolRef(Symb);
848     }
849     return object_error::parse_failed;
850   }
851
852   template <typename T>
853   std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
854     ErrorOr<COFFSymbolRef> s = getSymbol(index);
855     if (std::error_code EC = s.getError())
856       return EC;
857     Res = reinterpret_cast<const T *>(s->getRawPtr());
858     return std::error_code();
859   }
860
861   std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
862   std::error_code getSymbolName(const coff_symbol_generic *Symbol,
863                                 StringRef &Res) const;
864
865   ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
866
867   size_t getSymbolTableEntrySize() const {
868     if (COFFHeader)
869       return sizeof(coff_symbol16);
870     if (COFFBigObjHeader)
871       return sizeof(coff_symbol32);
872     llvm_unreachable("null symbol table pointer!");
873   }
874
875   iterator_range<const coff_relocation *>
876   getRelocations(const coff_section *Sec) const;
877
878   std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
879   uint64_t getSectionSize(const coff_section *Sec) const;
880   std::error_code getSectionContents(const coff_section *Sec,
881                                      ArrayRef<uint8_t> &Res) const;
882
883   uint64_t getImageBase() const;
884   std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
885   std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
886
887   /// Given an RVA base and size, returns a valid array of bytes or an error
888   /// code if the RVA and size is not contained completely within a valid
889   /// section.
890   std::error_code getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
891                                        ArrayRef<uint8_t> &Contents) const;
892
893   std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
894                               StringRef &Name) const;
895
896   /// Get PDB information out of a codeview debug directory entry.
897   std::error_code getDebugPDBInfo(const debug_directory *DebugDir,
898                                   const codeview::DebugInfo *&Info,
899                                   StringRef &PDBFileName) const;
900
901   /// Get PDB information from an executable. If the information is not present,
902   /// Info will be set to nullptr and PDBFileName will be empty. An error is
903   /// returned only on corrupt object files. Convenience accessor that can be
904   /// used if the debug directory is not already handy.
905   std::error_code getDebugPDBInfo(const codeview::DebugInfo *&Info,
906                                   StringRef &PDBFileName) const;
907
908   bool isRelocatableObject() const override;
909   bool is64() const { return PE32PlusHeader; }
910
911   static inline bool classof(const Binary *v) { return v->isCOFF(); }
912 };
913
914 // The iterator for the import directory table.
915 class ImportDirectoryEntryRef {
916 public:
917   ImportDirectoryEntryRef() = default;
918   ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
919                           uint32_t I, const COFFObjectFile *Owner)
920       : ImportTable(Table), Index(I), OwningObject(Owner) {}
921
922   bool operator==(const ImportDirectoryEntryRef &Other) const;
923   void moveNext();
924
925   imported_symbol_iterator imported_symbol_begin() const;
926   imported_symbol_iterator imported_symbol_end() const;
927   iterator_range<imported_symbol_iterator> imported_symbols() const;
928
929   imported_symbol_iterator lookup_table_begin() const;
930   imported_symbol_iterator lookup_table_end() const;
931   iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
932
933   std::error_code getName(StringRef &Result) const;
934   std::error_code getImportLookupTableRVA(uint32_t &Result) const;
935   std::error_code getImportAddressTableRVA(uint32_t &Result) const;
936
937   std::error_code
938   getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
939
940 private:
941   const coff_import_directory_table_entry *ImportTable;
942   uint32_t Index;
943   const COFFObjectFile *OwningObject = nullptr;
944 };
945
946 class DelayImportDirectoryEntryRef {
947 public:
948   DelayImportDirectoryEntryRef() = default;
949   DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
950                                uint32_t I, const COFFObjectFile *Owner)
951       : Table(T), Index(I), OwningObject(Owner) {}
952
953   bool operator==(const DelayImportDirectoryEntryRef &Other) const;
954   void moveNext();
955
956   imported_symbol_iterator imported_symbol_begin() const;
957   imported_symbol_iterator imported_symbol_end() const;
958   iterator_range<imported_symbol_iterator> imported_symbols() const;
959
960   std::error_code getName(StringRef &Result) const;
961   std::error_code getDelayImportTable(
962       const delay_import_directory_table_entry *&Result) const;
963   std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
964
965 private:
966   const delay_import_directory_table_entry *Table;
967   uint32_t Index;
968   const COFFObjectFile *OwningObject = nullptr;
969 };
970
971 // The iterator for the export directory table entry.
972 class ExportDirectoryEntryRef {
973 public:
974   ExportDirectoryEntryRef() = default;
975   ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
976                           const COFFObjectFile *Owner)
977       : ExportTable(Table), Index(I), OwningObject(Owner) {}
978
979   bool operator==(const ExportDirectoryEntryRef &Other) const;
980   void moveNext();
981
982   std::error_code getDllName(StringRef &Result) const;
983   std::error_code getOrdinalBase(uint32_t &Result) const;
984   std::error_code getOrdinal(uint32_t &Result) const;
985   std::error_code getExportRVA(uint32_t &Result) const;
986   std::error_code getSymbolName(StringRef &Result) const;
987
988   std::error_code isForwarder(bool &Result) const;
989   std::error_code getForwardTo(StringRef &Result) const;
990
991 private:
992   const export_directory_table_entry *ExportTable;
993   uint32_t Index;
994   const COFFObjectFile *OwningObject = nullptr;
995 };
996
997 class ImportedSymbolRef {
998 public:
999   ImportedSymbolRef() = default;
1000   ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
1001                     const COFFObjectFile *Owner)
1002       : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
1003   ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
1004                     const COFFObjectFile *Owner)
1005       : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
1006
1007   bool operator==(const ImportedSymbolRef &Other) const;
1008   void moveNext();
1009
1010   std::error_code getSymbolName(StringRef &Result) const;
1011   std::error_code isOrdinal(bool &Result) const;
1012   std::error_code getOrdinal(uint16_t &Result) const;
1013   std::error_code getHintNameRVA(uint32_t &Result) const;
1014
1015 private:
1016   const import_lookup_table_entry32 *Entry32;
1017   const import_lookup_table_entry64 *Entry64;
1018   uint32_t Index;
1019   const COFFObjectFile *OwningObject = nullptr;
1020 };
1021
1022 class BaseRelocRef {
1023 public:
1024   BaseRelocRef() = default;
1025   BaseRelocRef(const coff_base_reloc_block_header *Header,
1026                const COFFObjectFile *Owner)
1027       : Header(Header), Index(0), OwningObject(Owner) {}
1028
1029   bool operator==(const BaseRelocRef &Other) const;
1030   void moveNext();
1031
1032   std::error_code getType(uint8_t &Type) const;
1033   std::error_code getRVA(uint32_t &Result) const;
1034
1035 private:
1036   const coff_base_reloc_block_header *Header;
1037   uint32_t Index;
1038   const COFFObjectFile *OwningObject = nullptr;
1039 };
1040
1041 // Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
1042 struct FpoData {
1043   support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
1044   support::ulittle32_t Size;   // cbProcSize: # bytes in function
1045   support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
1046   support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
1047   support::ulittle16_t Attributes;
1048
1049   // cbProlog: # bytes in prolog
1050   int getPrologSize() const { return Attributes & 0xF; }
1051
1052   // cbRegs: # regs saved
1053   int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
1054
1055   // fHasSEH: true if seh is func
1056   bool hasSEH() const { return (Attributes >> 9) & 1; }
1057
1058   // fUseBP: true if EBP has been allocated
1059   bool useBP() const { return (Attributes >> 10) & 1; }
1060
1061   // cbFrame: frame pointer
1062   int getFP() const { return Attributes >> 14; }
1063 };
1064
1065 } // end namespace object
1066
1067 } // end namespace llvm
1068
1069 #endif // LLVM_OBJECT_COFF_H