Add a SymbolRef::getValue.
[oota-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 template <typename IntTy>
173 struct import_lookup_table_entry {
174   IntTy Data;
175
176   bool isOrdinal() const { return Data < 0; }
177
178   uint16_t getOrdinal() const {
179     assert(isOrdinal() && "ILT entry is not an ordinal!");
180     return Data & 0xFFFF;
181   }
182
183   uint32_t getHintNameRVA() const {
184     assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
185     return Data & 0xFFFFFFFF;
186   }
187 };
188
189 typedef import_lookup_table_entry<support::little32_t>
190     import_lookup_table_entry32;
191 typedef import_lookup_table_entry<support::little64_t>
192     import_lookup_table_entry64;
193
194 struct delay_import_directory_table_entry {
195   // dumpbin reports this field as "Characteristics" instead of "Attributes".
196   support::ulittle32_t Attributes;
197   support::ulittle32_t Name;
198   support::ulittle32_t ModuleHandle;
199   support::ulittle32_t DelayImportAddressTable;
200   support::ulittle32_t DelayImportNameTable;
201   support::ulittle32_t BoundDelayImportTable;
202   support::ulittle32_t UnloadDelayImportTable;
203   support::ulittle32_t TimeStamp;
204 };
205
206 struct export_directory_table_entry {
207   support::ulittle32_t ExportFlags;
208   support::ulittle32_t TimeDateStamp;
209   support::ulittle16_t MajorVersion;
210   support::ulittle16_t MinorVersion;
211   support::ulittle32_t NameRVA;
212   support::ulittle32_t OrdinalBase;
213   support::ulittle32_t AddressTableEntries;
214   support::ulittle32_t NumberOfNamePointers;
215   support::ulittle32_t ExportAddressTableRVA;
216   support::ulittle32_t NamePointerRVA;
217   support::ulittle32_t OrdinalTableRVA;
218 };
219
220 union export_address_table_entry {
221   support::ulittle32_t ExportRVA;
222   support::ulittle32_t ForwarderRVA;
223 };
224
225 typedef support::ulittle32_t export_name_pointer_table_entry;
226 typedef support::ulittle16_t export_ordinal_table_entry;
227
228 struct StringTableOffset {
229   support::ulittle32_t Zeroes;
230   support::ulittle32_t Offset;
231 };
232
233 template <typename SectionNumberType>
234 struct coff_symbol {
235   union {
236     char ShortName[COFF::NameSize];
237     StringTableOffset Offset;
238   } Name;
239
240   support::ulittle32_t Value;
241   SectionNumberType SectionNumber;
242
243   support::ulittle16_t Type;
244
245   uint8_t StorageClass;
246   uint8_t NumberOfAuxSymbols;
247 };
248
249 typedef coff_symbol<support::ulittle16_t> coff_symbol16;
250 typedef coff_symbol<support::ulittle32_t> coff_symbol32;
251
252 class COFFSymbolRef {
253 public:
254   COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS), CS32(nullptr) {}
255   COFFSymbolRef(const coff_symbol32 *CS) : CS16(nullptr), CS32(CS) {}
256   COFFSymbolRef() : CS16(nullptr), CS32(nullptr) {}
257
258   const void *getRawPtr() const {
259     return CS16 ? static_cast<const void *>(CS16) : CS32;
260   }
261
262   friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
263     return A.getRawPtr() < B.getRawPtr();
264   }
265
266   bool isBigObj() const {
267     if (CS16)
268       return false;
269     if (CS32)
270       return true;
271     llvm_unreachable("COFFSymbolRef points to nothing!");
272   }
273
274   const char *getShortName() const {
275     return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
276   }
277
278   const StringTableOffset &getStringTableOffset() const {
279     assert(isSet() && "COFFSymbolRef points to nothing!");
280     return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
281   }
282
283   uint32_t getValue() const { return CS16 ? CS16->Value : CS32->Value; }
284
285   int32_t getSectionNumber() const {
286     assert(isSet() && "COFFSymbolRef points to nothing!");
287     if (CS16) {
288       // Reserved sections are returned as negative numbers.
289       if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
290         return CS16->SectionNumber;
291       return static_cast<int16_t>(CS16->SectionNumber);
292     }
293     return static_cast<int32_t>(CS32->SectionNumber);
294   }
295
296   uint16_t getType() const {
297     assert(isSet() && "COFFSymbolRef points to nothing!");
298     return CS16 ? CS16->Type : CS32->Type;
299   }
300
301   uint8_t getStorageClass() const {
302     assert(isSet() && "COFFSymbolRef points to nothing!");
303     return CS16 ? CS16->StorageClass : CS32->StorageClass;
304   }
305
306   uint8_t getNumberOfAuxSymbols() const {
307     assert(isSet() && "COFFSymbolRef points to nothing!");
308     return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols;
309   }
310
311   uint8_t getBaseType() const { return getType() & 0x0F; }
312
313   uint8_t getComplexType() const {
314     return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
315   }
316
317   bool isAbsolute() const {
318     return getSectionNumber() == -1;
319   }
320
321   bool isExternal() const {
322     return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
323   }
324
325   bool isCommon() const {
326     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
327            getValue() != 0;
328   }
329
330   bool isUndefined() const {
331     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
332            getValue() == 0;
333   }
334
335   bool isWeakExternal() const {
336     return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
337   }
338
339   bool isFunctionDefinition() const {
340     return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
341            getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
342            !COFF::isReservedSectionNumber(getSectionNumber());
343   }
344
345   bool isFunctionLineInfo() const {
346     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
347   }
348
349   bool isAnyUndefined() const {
350     return isUndefined() || isWeakExternal();
351   }
352
353   bool isFileRecord() const {
354     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
355   }
356
357   bool isSection() const {
358     return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
359   }
360
361   bool isSectionDefinition() const {
362     // C++/CLI creates external ABS symbols for non-const appdomain globals.
363     // These are also followed by an auxiliary section definition.
364     bool isAppdomainGlobal =
365         getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
366         getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE;
367     bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
368     if (!getNumberOfAuxSymbols())
369       return false;
370     return isAppdomainGlobal || isOrdinarySection;
371   }
372
373   bool isCLRToken() const {
374     return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
375   }
376
377 private:
378   bool isSet() const { return CS16 || CS32; }
379
380   const coff_symbol16 *CS16;
381   const coff_symbol32 *CS32;
382 };
383
384 struct coff_section {
385   char Name[COFF::NameSize];
386   support::ulittle32_t VirtualSize;
387   support::ulittle32_t VirtualAddress;
388   support::ulittle32_t SizeOfRawData;
389   support::ulittle32_t PointerToRawData;
390   support::ulittle32_t PointerToRelocations;
391   support::ulittle32_t PointerToLinenumbers;
392   support::ulittle16_t NumberOfRelocations;
393   support::ulittle16_t NumberOfLinenumbers;
394   support::ulittle32_t Characteristics;
395
396   // Returns true if the actual number of relocations is stored in
397   // VirtualAddress field of the first relocation table entry.
398   bool hasExtendedRelocations() const {
399     return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
400            NumberOfRelocations == UINT16_MAX;
401   }
402 };
403
404 struct coff_relocation {
405   support::ulittle32_t VirtualAddress;
406   support::ulittle32_t SymbolTableIndex;
407   support::ulittle16_t Type;
408 };
409
410 struct coff_aux_function_definition {
411   support::ulittle32_t TagIndex;
412   support::ulittle32_t TotalSize;
413   support::ulittle32_t PointerToLinenumber;
414   support::ulittle32_t PointerToNextFunction;
415 };
416
417 struct coff_aux_bf_and_ef_symbol {
418   char Unused1[4];
419   support::ulittle16_t Linenumber;
420   char Unused2[6];
421   support::ulittle32_t PointerToNextFunction;
422 };
423
424 struct coff_aux_weak_external {
425   support::ulittle32_t TagIndex;
426   support::ulittle32_t Characteristics;
427 };
428
429 struct coff_aux_section_definition {
430   support::ulittle32_t Length;
431   support::ulittle16_t NumberOfRelocations;
432   support::ulittle16_t NumberOfLinenumbers;
433   support::ulittle32_t CheckSum;
434   support::ulittle16_t NumberLowPart;
435   uint8_t              Selection;
436   uint8_t              Unused;
437   support::ulittle16_t NumberHighPart;
438   int32_t getNumber(bool IsBigObj) const {
439     uint32_t Number = static_cast<uint32_t>(NumberLowPart);
440     if (IsBigObj)
441       Number |= static_cast<uint32_t>(NumberHighPart) << 16;
442     return static_cast<int32_t>(Number);
443   }
444 };
445
446 struct coff_aux_clr_token {
447   uint8_t              AuxType;
448   uint8_t              Reserved;
449   support::ulittle32_t SymbolTableIndex;
450 };
451
452 struct coff_import_header {
453   support::ulittle16_t Sig1;
454   support::ulittle16_t Sig2;
455   support::ulittle16_t Version;
456   support::ulittle16_t Machine;
457   support::ulittle32_t TimeDateStamp;
458   support::ulittle32_t SizeOfData;
459   support::ulittle16_t OrdinalHint;
460   support::ulittle16_t TypeInfo;
461   int getType() const { return TypeInfo & 0x3; }
462   int getNameType() const { return (TypeInfo & 0x7) >> 2; }
463 };
464
465 struct coff_import_directory_table_entry {
466   support::ulittle32_t ImportLookupTableRVA;
467   support::ulittle32_t TimeDateStamp;
468   support::ulittle32_t ForwarderChain;
469   support::ulittle32_t NameRVA;
470   support::ulittle32_t ImportAddressTableRVA;
471 };
472
473 struct coff_load_configuration32 {
474   support::ulittle32_t Characteristics;
475   support::ulittle32_t TimeDateStamp;
476   support::ulittle16_t MajorVersion;
477   support::ulittle16_t MinorVersion;
478   support::ulittle32_t GlobalFlagsClear;
479   support::ulittle32_t GlobalFlagsSet;
480   support::ulittle32_t CriticalSectionDefaultTimeout;
481   support::ulittle32_t DeCommitFreeBlockThreshold;
482   support::ulittle32_t DeCommitTotalFreeThreshold;
483   support::ulittle32_t LockPrefixTable;
484   support::ulittle32_t MaximumAllocationSize;
485   support::ulittle32_t VirtualMemoryThreshold;
486   support::ulittle32_t ProcessAffinityMask;
487   support::ulittle32_t ProcessHeapFlags;
488   support::ulittle16_t CSDVersion;
489   support::ulittle16_t Reserved;
490   support::ulittle32_t EditList;
491   support::ulittle32_t SecurityCookie;
492   support::ulittle32_t SEHandlerTable;
493   support::ulittle32_t SEHandlerCount;
494 };
495
496 struct coff_load_configuration64 {
497   support::ulittle32_t Characteristics;
498   support::ulittle32_t TimeDateStamp;
499   support::ulittle16_t MajorVersion;
500   support::ulittle16_t MinorVersion;
501   support::ulittle32_t GlobalFlagsClear;
502   support::ulittle32_t GlobalFlagsSet;
503   support::ulittle32_t CriticalSectionDefaultTimeout;
504   support::ulittle32_t DeCommitFreeBlockThreshold;
505   support::ulittle32_t DeCommitTotalFreeThreshold;
506   support::ulittle32_t LockPrefixTable;
507   support::ulittle32_t MaximumAllocationSize;
508   support::ulittle32_t VirtualMemoryThreshold;
509   support::ulittle32_t ProcessAffinityMask;
510   support::ulittle32_t ProcessHeapFlags;
511   support::ulittle16_t CSDVersion;
512   support::ulittle16_t Reserved;
513   support::ulittle32_t EditList;
514   support::ulittle64_t SecurityCookie;
515   support::ulittle64_t SEHandlerTable;
516   support::ulittle64_t SEHandlerCount;
517 };
518
519 struct coff_runtime_function_x64 {
520   support::ulittle32_t BeginAddress;
521   support::ulittle32_t EndAddress;
522   support::ulittle32_t UnwindInformation;
523 };
524
525 struct coff_base_reloc_block_header {
526   support::ulittle32_t PageRVA;
527   support::ulittle32_t BlockSize;
528 };
529
530 struct coff_base_reloc_block_entry {
531   support::ulittle16_t Data;
532   int getType() const { return Data >> 12; }
533   int getOffset() const { return Data & ((1 << 12) - 1); }
534 };
535
536 class COFFObjectFile : public ObjectFile {
537 private:
538   friend class ImportDirectoryEntryRef;
539   friend class ExportDirectoryEntryRef;
540   const coff_file_header *COFFHeader;
541   const coff_bigobj_file_header *COFFBigObjHeader;
542   const pe32_header *PE32Header;
543   const pe32plus_header *PE32PlusHeader;
544   const data_directory *DataDirectory;
545   const coff_section *SectionTable;
546   const coff_symbol16 *SymbolTable16;
547   const coff_symbol32 *SymbolTable32;
548   const char *StringTable;
549   uint32_t StringTableSize;
550   const import_directory_table_entry *ImportDirectory;
551   uint32_t NumberOfImportDirectory;
552   const delay_import_directory_table_entry *DelayImportDirectory;
553   uint32_t NumberOfDelayImportDirectory;
554   const export_directory_table_entry *ExportDirectory;
555   const coff_base_reloc_block_header *BaseRelocHeader;
556   const coff_base_reloc_block_header *BaseRelocEnd;
557
558   std::error_code getString(uint32_t offset, StringRef &Res) const;
559
560   template <typename coff_symbol_type>
561   const coff_symbol_type *toSymb(DataRefImpl Symb) const;
562   const coff_section *toSec(DataRefImpl Sec) const;
563   const coff_relocation *toRel(DataRefImpl Rel) const;
564
565   std::error_code initSymbolTablePtr();
566   std::error_code initImportTablePtr();
567   std::error_code initDelayImportTablePtr();
568   std::error_code initExportTablePtr();
569   std::error_code initBaseRelocPtr();
570
571 public:
572   uintptr_t getSymbolTable() const {
573     if (SymbolTable16)
574       return reinterpret_cast<uintptr_t>(SymbolTable16);
575     if (SymbolTable32)
576       return reinterpret_cast<uintptr_t>(SymbolTable32);
577     return uintptr_t(0);
578   }
579   uint16_t getMachine() const {
580     if (COFFHeader)
581       return COFFHeader->Machine;
582     if (COFFBigObjHeader)
583       return COFFBigObjHeader->Machine;
584     llvm_unreachable("no COFF header!");
585   }
586   uint16_t getSizeOfOptionalHeader() const {
587     if (COFFHeader)
588       return COFFHeader->isImportLibrary() ? 0
589                                            : COFFHeader->SizeOfOptionalHeader;
590     // bigobj doesn't have this field.
591     if (COFFBigObjHeader)
592       return 0;
593     llvm_unreachable("no COFF header!");
594   }
595   uint16_t getCharacteristics() const {
596     if (COFFHeader)
597       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
598     // bigobj doesn't have characteristics to speak of,
599     // editbin will silently lie to you if you attempt to set any.
600     if (COFFBigObjHeader)
601       return 0;
602     llvm_unreachable("no COFF header!");
603   }
604   uint32_t getTimeDateStamp() const {
605     if (COFFHeader)
606       return COFFHeader->TimeDateStamp;
607     if (COFFBigObjHeader)
608       return COFFBigObjHeader->TimeDateStamp;
609     llvm_unreachable("no COFF header!");
610   }
611   uint32_t getNumberOfSections() const {
612     if (COFFHeader)
613       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
614     if (COFFBigObjHeader)
615       return COFFBigObjHeader->NumberOfSections;
616     llvm_unreachable("no COFF header!");
617   }
618   uint32_t getPointerToSymbolTable() const {
619     if (COFFHeader)
620       return COFFHeader->isImportLibrary() ? 0
621                                            : COFFHeader->PointerToSymbolTable;
622     if (COFFBigObjHeader)
623       return COFFBigObjHeader->PointerToSymbolTable;
624     llvm_unreachable("no COFF header!");
625   }
626   uint32_t getNumberOfSymbols() const {
627     if (COFFHeader)
628       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
629     if (COFFBigObjHeader)
630       return COFFBigObjHeader->NumberOfSymbols;
631     llvm_unreachable("no COFF header!");
632   }
633 protected:
634   void moveSymbolNext(DataRefImpl &Symb) const override;
635   std::error_code getSymbolName(DataRefImpl Symb,
636                                 StringRef &Res) const override;
637   std::error_code getSymbolAddress(DataRefImpl Symb,
638                                    uint64_t &Res) const override;
639   uint64_t getSymbolValue(DataRefImpl Symb) const override;
640   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
641   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
642   std::error_code getSymbolType(DataRefImpl Symb,
643                                 SymbolRef::Type &Res) const override;
644   std::error_code getSymbolSection(DataRefImpl Symb,
645                                    section_iterator &Res) const override;
646   void moveSectionNext(DataRefImpl &Sec) const override;
647   std::error_code getSectionName(DataRefImpl Sec,
648                                  StringRef &Res) const override;
649   uint64_t getSectionAddress(DataRefImpl Sec) const override;
650   uint64_t getSectionSize(DataRefImpl Sec) const override;
651   std::error_code getSectionContents(DataRefImpl Sec,
652                                      StringRef &Res) const override;
653   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
654   bool isSectionText(DataRefImpl Sec) const override;
655   bool isSectionData(DataRefImpl Sec) const override;
656   bool isSectionBSS(DataRefImpl Sec) const override;
657   bool isSectionVirtual(DataRefImpl Sec) const override;
658   bool sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb) const override;
659   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
660   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
661
662   void moveRelocationNext(DataRefImpl &Rel) const override;
663   std::error_code getRelocationAddress(DataRefImpl Rel,
664                                        uint64_t &Res) const override;
665   std::error_code getRelocationOffset(DataRefImpl Rel,
666                                       uint64_t &Res) const override;
667   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
668   std::error_code getRelocationType(DataRefImpl Rel,
669                                     uint64_t &Res) const override;
670   std::error_code
671   getRelocationTypeName(DataRefImpl Rel,
672                         SmallVectorImpl<char> &Result) const override;
673 public:
674   COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
675   basic_symbol_iterator symbol_begin_impl() const override;
676   basic_symbol_iterator symbol_end_impl() const override;
677   section_iterator section_begin() const override;
678   section_iterator section_end() const override;
679
680   const coff_section *getCOFFSection(const SectionRef &Section) const;
681   COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
682   COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
683   const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
684
685   uint8_t getBytesInAddress() const override;
686   StringRef getFileFormatName() const override;
687   unsigned getArch() const override;
688
689   import_directory_iterator import_directory_begin() const;
690   import_directory_iterator import_directory_end() const;
691   delay_import_directory_iterator delay_import_directory_begin() const;
692   delay_import_directory_iterator delay_import_directory_end() const;
693   export_directory_iterator export_directory_begin() const;
694   export_directory_iterator export_directory_end() const;
695   base_reloc_iterator base_reloc_begin() const;
696   base_reloc_iterator base_reloc_end() const;
697
698   iterator_range<import_directory_iterator> import_directories() const;
699   iterator_range<delay_import_directory_iterator>
700       delay_import_directories() const;
701   iterator_range<export_directory_iterator> export_directories() const;
702   iterator_range<base_reloc_iterator> base_relocs() const;
703
704   const dos_header *getDOSHeader() const {
705     if (!PE32Header && !PE32PlusHeader)
706       return nullptr;
707     return reinterpret_cast<const dos_header *>(base());
708   }
709   std::error_code getPE32Header(const pe32_header *&Res) const;
710   std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
711   std::error_code getDataDirectory(uint32_t index,
712                                    const data_directory *&Res) const;
713   std::error_code getSection(int32_t index, const coff_section *&Res) const;
714   template <typename coff_symbol_type>
715   std::error_code getSymbol(uint32_t Index,
716                             const coff_symbol_type *&Res) const {
717     if (Index >= getNumberOfSymbols())
718       return object_error::parse_failed;
719
720     Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
721     return std::error_code();
722   }
723   ErrorOr<COFFSymbolRef> getSymbol(uint32_t index) const {
724     if (SymbolTable16) {
725       const coff_symbol16 *Symb = nullptr;
726       if (std::error_code EC = getSymbol(index, Symb))
727         return EC;
728       return COFFSymbolRef(Symb);
729     }
730     if (SymbolTable32) {
731       const coff_symbol32 *Symb = nullptr;
732       if (std::error_code EC = getSymbol(index, Symb))
733         return EC;
734       return COFFSymbolRef(Symb);
735     }
736     return object_error::parse_failed;
737   }
738   template <typename T>
739   std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
740     ErrorOr<COFFSymbolRef> s = getSymbol(index);
741     if (std::error_code EC = s.getError())
742       return EC;
743     Res = reinterpret_cast<const T *>(s->getRawPtr());
744     return std::error_code();
745   }
746   std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
747
748   ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
749
750   size_t getSymbolTableEntrySize() const {
751     if (COFFHeader)
752       return sizeof(coff_symbol16);
753     if (COFFBigObjHeader)
754       return sizeof(coff_symbol32);
755     llvm_unreachable("null symbol table pointer!");
756   }
757
758   std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
759   uint64_t getSectionSize(const coff_section *Sec) const;
760   std::error_code getSectionContents(const coff_section *Sec,
761                                      ArrayRef<uint8_t> &Res) const;
762
763   std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
764   std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
765   std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
766                               StringRef &Name) const;
767
768   bool isRelocatableObject() const override;
769   bool is64() const { return PE32PlusHeader; }
770
771   static inline bool classof(const Binary *v) { return v->isCOFF(); }
772 };
773
774 // The iterator for the import directory table.
775 class ImportDirectoryEntryRef {
776 public:
777   ImportDirectoryEntryRef() : OwningObject(nullptr) {}
778   ImportDirectoryEntryRef(const import_directory_table_entry *Table, uint32_t I,
779                           const COFFObjectFile *Owner)
780       : ImportTable(Table), Index(I), OwningObject(Owner) {}
781
782   bool operator==(const ImportDirectoryEntryRef &Other) const;
783   void moveNext();
784
785   imported_symbol_iterator imported_symbol_begin() const;
786   imported_symbol_iterator imported_symbol_end() const;
787   iterator_range<imported_symbol_iterator> imported_symbols() const;
788
789   std::error_code getName(StringRef &Result) const;
790   std::error_code getImportLookupTableRVA(uint32_t &Result) const;
791   std::error_code getImportAddressTableRVA(uint32_t &Result) const;
792
793   std::error_code
794   getImportTableEntry(const import_directory_table_entry *&Result) const;
795
796   std::error_code
797   getImportLookupEntry(const import_lookup_table_entry32 *&Result) const;
798
799 private:
800   const import_directory_table_entry *ImportTable;
801   uint32_t Index;
802   const COFFObjectFile *OwningObject;
803 };
804
805 class DelayImportDirectoryEntryRef {
806 public:
807   DelayImportDirectoryEntryRef() : OwningObject(nullptr) {}
808   DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
809                                uint32_t I, const COFFObjectFile *Owner)
810       : Table(T), Index(I), OwningObject(Owner) {}
811
812   bool operator==(const DelayImportDirectoryEntryRef &Other) const;
813   void moveNext();
814
815   imported_symbol_iterator imported_symbol_begin() const;
816   imported_symbol_iterator imported_symbol_end() const;
817   iterator_range<imported_symbol_iterator> imported_symbols() const;
818
819   std::error_code getName(StringRef &Result) const;
820   std::error_code getDelayImportTable(
821       const delay_import_directory_table_entry *&Result) const;
822   std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
823
824 private:
825   const delay_import_directory_table_entry *Table;
826   uint32_t Index;
827   const COFFObjectFile *OwningObject;
828 };
829
830 // The iterator for the export directory table entry.
831 class ExportDirectoryEntryRef {
832 public:
833   ExportDirectoryEntryRef() : OwningObject(nullptr) {}
834   ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
835                           const COFFObjectFile *Owner)
836       : ExportTable(Table), Index(I), OwningObject(Owner) {}
837
838   bool operator==(const ExportDirectoryEntryRef &Other) const;
839   void moveNext();
840
841   std::error_code getDllName(StringRef &Result) const;
842   std::error_code getOrdinalBase(uint32_t &Result) const;
843   std::error_code getOrdinal(uint32_t &Result) const;
844   std::error_code getExportRVA(uint32_t &Result) const;
845   std::error_code getSymbolName(StringRef &Result) const;
846
847 private:
848   const export_directory_table_entry *ExportTable;
849   uint32_t Index;
850   const COFFObjectFile *OwningObject;
851 };
852
853 class ImportedSymbolRef {
854 public:
855   ImportedSymbolRef() : OwningObject(nullptr) {}
856   ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
857                     const COFFObjectFile *Owner)
858       : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
859   ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
860                     const COFFObjectFile *Owner)
861       : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
862
863   bool operator==(const ImportedSymbolRef &Other) const;
864   void moveNext();
865
866   std::error_code getSymbolName(StringRef &Result) const;
867   std::error_code getOrdinal(uint16_t &Result) const;
868
869 private:
870   const import_lookup_table_entry32 *Entry32;
871   const import_lookup_table_entry64 *Entry64;
872   uint32_t Index;
873   const COFFObjectFile *OwningObject;
874 };
875
876 class BaseRelocRef {
877 public:
878   BaseRelocRef() : OwningObject(nullptr) {}
879   BaseRelocRef(const coff_base_reloc_block_header *Header,
880                const COFFObjectFile *Owner)
881       : Header(Header), Index(0), OwningObject(Owner) {}
882
883   bool operator==(const BaseRelocRef &Other) const;
884   void moveNext();
885
886   std::error_code getType(uint8_t &Type) const;
887   std::error_code getRVA(uint32_t &Result) const;
888
889 private:
890   const coff_base_reloc_block_header *Header;
891   uint32_t Index;
892   const COFFObjectFile *OwningObject;
893 };
894
895 } // end namespace object
896 } // end namespace llvm
897
898 #endif