OSDN Git Service

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