LLVM  mainline
COFF.h
Go to the documentation of this file.
00001 //===- COFF.h - COFF object file implementation -----------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file declares the COFFObjectFile class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_OBJECT_COFF_H
00015 #define LLVM_OBJECT_COFF_H
00016 
00017 #include "llvm/ADT/PointerUnion.h"
00018 #include "llvm/Object/ObjectFile.h"
00019 #include "llvm/Support/COFF.h"
00020 #include "llvm/Support/Endian.h"
00021 #include "llvm/Support/ErrorOr.h"
00022 
00023 namespace llvm {
00024 template <typename T> class ArrayRef;
00025 
00026 namespace object {
00027 class ImportDirectoryEntryRef;
00028 class DelayImportDirectoryEntryRef;
00029 class ExportDirectoryEntryRef;
00030 class ImportedSymbolRef;
00031 class BaseRelocRef;
00032 typedef content_iterator<ImportDirectoryEntryRef> import_directory_iterator;
00033 typedef content_iterator<DelayImportDirectoryEntryRef>
00034     delay_import_directory_iterator;
00035 typedef content_iterator<ExportDirectoryEntryRef> export_directory_iterator;
00036 typedef content_iterator<ImportedSymbolRef> imported_symbol_iterator;
00037 typedef content_iterator<BaseRelocRef> base_reloc_iterator;
00038 
00039 /// The DOS compatible header at the front of all PE/COFF executables.
00040 struct dos_header {
00041   char                 Magic[2];
00042   support::ulittle16_t UsedBytesInTheLastPage;
00043   support::ulittle16_t FileSizeInPages;
00044   support::ulittle16_t NumberOfRelocationItems;
00045   support::ulittle16_t HeaderSizeInParagraphs;
00046   support::ulittle16_t MinimumExtraParagraphs;
00047   support::ulittle16_t MaximumExtraParagraphs;
00048   support::ulittle16_t InitialRelativeSS;
00049   support::ulittle16_t InitialSP;
00050   support::ulittle16_t Checksum;
00051   support::ulittle16_t InitialIP;
00052   support::ulittle16_t InitialRelativeCS;
00053   support::ulittle16_t AddressOfRelocationTable;
00054   support::ulittle16_t OverlayNumber;
00055   support::ulittle16_t Reserved[4];
00056   support::ulittle16_t OEMid;
00057   support::ulittle16_t OEMinfo;
00058   support::ulittle16_t Reserved2[10];
00059   support::ulittle32_t AddressOfNewExeHeader;
00060 };
00061 
00062 struct coff_file_header {
00063   support::ulittle16_t Machine;
00064   support::ulittle16_t NumberOfSections;
00065   support::ulittle32_t TimeDateStamp;
00066   support::ulittle32_t PointerToSymbolTable;
00067   support::ulittle32_t NumberOfSymbols;
00068   support::ulittle16_t SizeOfOptionalHeader;
00069   support::ulittle16_t Characteristics;
00070 
00071   bool isImportLibrary() const { return NumberOfSections == 0xffff; }
00072 };
00073 
00074 struct coff_bigobj_file_header {
00075   support::ulittle16_t Sig1;
00076   support::ulittle16_t Sig2;
00077   support::ulittle16_t Version;
00078   support::ulittle16_t Machine;
00079   support::ulittle32_t TimeDateStamp;
00080   uint8_t              UUID[16];
00081   support::ulittle32_t unused1;
00082   support::ulittle32_t unused2;
00083   support::ulittle32_t unused3;
00084   support::ulittle32_t unused4;
00085   support::ulittle32_t NumberOfSections;
00086   support::ulittle32_t PointerToSymbolTable;
00087   support::ulittle32_t NumberOfSymbols;
00088 };
00089 
00090 /// The 32-bit PE header that follows the COFF header.
00091 struct pe32_header {
00092   support::ulittle16_t Magic;
00093   uint8_t MajorLinkerVersion;
00094   uint8_t MinorLinkerVersion;
00095   support::ulittle32_t SizeOfCode;
00096   support::ulittle32_t SizeOfInitializedData;
00097   support::ulittle32_t SizeOfUninitializedData;
00098   support::ulittle32_t AddressOfEntryPoint;
00099   support::ulittle32_t BaseOfCode;
00100   support::ulittle32_t BaseOfData;
00101   support::ulittle32_t ImageBase;
00102   support::ulittle32_t SectionAlignment;
00103   support::ulittle32_t FileAlignment;
00104   support::ulittle16_t MajorOperatingSystemVersion;
00105   support::ulittle16_t MinorOperatingSystemVersion;
00106   support::ulittle16_t MajorImageVersion;
00107   support::ulittle16_t MinorImageVersion;
00108   support::ulittle16_t MajorSubsystemVersion;
00109   support::ulittle16_t MinorSubsystemVersion;
00110   support::ulittle32_t Win32VersionValue;
00111   support::ulittle32_t SizeOfImage;
00112   support::ulittle32_t SizeOfHeaders;
00113   support::ulittle32_t CheckSum;
00114   support::ulittle16_t Subsystem;
00115   // FIXME: This should be DllCharacteristics.
00116   support::ulittle16_t DLLCharacteristics;
00117   support::ulittle32_t SizeOfStackReserve;
00118   support::ulittle32_t SizeOfStackCommit;
00119   support::ulittle32_t SizeOfHeapReserve;
00120   support::ulittle32_t SizeOfHeapCommit;
00121   support::ulittle32_t LoaderFlags;
00122   // FIXME: This should be NumberOfRvaAndSizes.
00123   support::ulittle32_t NumberOfRvaAndSize;
00124 };
00125 
00126 /// The 64-bit PE header that follows the COFF header.
00127 struct pe32plus_header {
00128   support::ulittle16_t Magic;
00129   uint8_t MajorLinkerVersion;
00130   uint8_t MinorLinkerVersion;
00131   support::ulittle32_t SizeOfCode;
00132   support::ulittle32_t SizeOfInitializedData;
00133   support::ulittle32_t SizeOfUninitializedData;
00134   support::ulittle32_t AddressOfEntryPoint;
00135   support::ulittle32_t BaseOfCode;
00136   support::ulittle64_t ImageBase;
00137   support::ulittle32_t SectionAlignment;
00138   support::ulittle32_t FileAlignment;
00139   support::ulittle16_t MajorOperatingSystemVersion;
00140   support::ulittle16_t MinorOperatingSystemVersion;
00141   support::ulittle16_t MajorImageVersion;
00142   support::ulittle16_t MinorImageVersion;
00143   support::ulittle16_t MajorSubsystemVersion;
00144   support::ulittle16_t MinorSubsystemVersion;
00145   support::ulittle32_t Win32VersionValue;
00146   support::ulittle32_t SizeOfImage;
00147   support::ulittle32_t SizeOfHeaders;
00148   support::ulittle32_t CheckSum;
00149   support::ulittle16_t Subsystem;
00150   support::ulittle16_t DLLCharacteristics;
00151   support::ulittle64_t SizeOfStackReserve;
00152   support::ulittle64_t SizeOfStackCommit;
00153   support::ulittle64_t SizeOfHeapReserve;
00154   support::ulittle64_t SizeOfHeapCommit;
00155   support::ulittle32_t LoaderFlags;
00156   support::ulittle32_t NumberOfRvaAndSize;
00157 };
00158 
00159 struct data_directory {
00160   support::ulittle32_t RelativeVirtualAddress;
00161   support::ulittle32_t Size;
00162 };
00163 
00164 struct import_directory_table_entry {
00165   support::ulittle32_t ImportLookupTableRVA;
00166   support::ulittle32_t TimeDateStamp;
00167   support::ulittle32_t ForwarderChain;
00168   support::ulittle32_t NameRVA;
00169   support::ulittle32_t ImportAddressTableRVA;
00170 };
00171 
00172 template <typename IntTy>
00173 struct import_lookup_table_entry {
00174   IntTy Data;
00175 
00176   bool isOrdinal() const { return Data < 0; }
00177 
00178   uint16_t getOrdinal() const {
00179     assert(isOrdinal() && "ILT entry is not an ordinal!");
00180     return Data & 0xFFFF;
00181   }
00182 
00183   uint32_t getHintNameRVA() const {
00184     assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
00185     return Data & 0xFFFFFFFF;
00186   }
00187 };
00188 
00189 typedef import_lookup_table_entry<support::little32_t>
00190     import_lookup_table_entry32;
00191 typedef import_lookup_table_entry<support::little64_t>
00192     import_lookup_table_entry64;
00193 
00194 struct delay_import_directory_table_entry {
00195   // dumpbin reports this field as "Characteristics" instead of "Attributes".
00196   support::ulittle32_t Attributes;
00197   support::ulittle32_t Name;
00198   support::ulittle32_t ModuleHandle;
00199   support::ulittle32_t DelayImportAddressTable;
00200   support::ulittle32_t DelayImportNameTable;
00201   support::ulittle32_t BoundDelayImportTable;
00202   support::ulittle32_t UnloadDelayImportTable;
00203   support::ulittle32_t TimeStamp;
00204 };
00205 
00206 struct export_directory_table_entry {
00207   support::ulittle32_t ExportFlags;
00208   support::ulittle32_t TimeDateStamp;
00209   support::ulittle16_t MajorVersion;
00210   support::ulittle16_t MinorVersion;
00211   support::ulittle32_t NameRVA;
00212   support::ulittle32_t OrdinalBase;
00213   support::ulittle32_t AddressTableEntries;
00214   support::ulittle32_t NumberOfNamePointers;
00215   support::ulittle32_t ExportAddressTableRVA;
00216   support::ulittle32_t NamePointerRVA;
00217   support::ulittle32_t OrdinalTableRVA;
00218 };
00219 
00220 union export_address_table_entry {
00221   support::ulittle32_t ExportRVA;
00222   support::ulittle32_t ForwarderRVA;
00223 };
00224 
00225 typedef support::ulittle32_t export_name_pointer_table_entry;
00226 typedef support::ulittle16_t export_ordinal_table_entry;
00227 
00228 struct StringTableOffset {
00229   support::ulittle32_t Zeroes;
00230   support::ulittle32_t Offset;
00231 };
00232 
00233 template <typename SectionNumberType>
00234 struct coff_symbol {
00235   union {
00236     char ShortName[COFF::NameSize];
00237     StringTableOffset Offset;
00238   } Name;
00239 
00240   support::ulittle32_t Value;
00241   SectionNumberType SectionNumber;
00242 
00243   support::ulittle16_t Type;
00244 
00245   uint8_t StorageClass;
00246   uint8_t NumberOfAuxSymbols;
00247 };
00248 
00249 typedef coff_symbol<support::ulittle16_t> coff_symbol16;
00250 typedef coff_symbol<support::ulittle32_t> coff_symbol32;
00251 
00252 // Contains only common parts of coff_symbol16 and coff_symbol32.
00253 struct coff_symbol_generic {
00254   union {
00255     char ShortName[COFF::NameSize];
00256     StringTableOffset Offset;
00257   } Name;
00258   support::ulittle32_t Value;
00259 };
00260 
00261 class COFFSymbolRef {
00262 public:
00263   COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS), CS32(nullptr) {}
00264   COFFSymbolRef(const coff_symbol32 *CS) : CS16(nullptr), CS32(CS) {}
00265   COFFSymbolRef() : CS16(nullptr), CS32(nullptr) {}
00266 
00267   const void *getRawPtr() const {
00268     return CS16 ? static_cast<const void *>(CS16) : CS32;
00269   }
00270 
00271   const coff_symbol_generic *getGeneric() const {
00272     if (CS16)
00273       return reinterpret_cast<const coff_symbol_generic *>(CS16);
00274     return reinterpret_cast<const coff_symbol_generic *>(CS32);
00275   }
00276 
00277   friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
00278     return A.getRawPtr() < B.getRawPtr();
00279   }
00280 
00281   bool isBigObj() const {
00282     if (CS16)
00283       return false;
00284     if (CS32)
00285       return true;
00286     llvm_unreachable("COFFSymbolRef points to nothing!");
00287   }
00288 
00289   const char *getShortName() const {
00290     return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
00291   }
00292 
00293   const StringTableOffset &getStringTableOffset() const {
00294     assert(isSet() && "COFFSymbolRef points to nothing!");
00295     return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
00296   }
00297 
00298   uint32_t getValue() const { return CS16 ? CS16->Value : CS32->Value; }
00299 
00300   int32_t getSectionNumber() const {
00301     assert(isSet() && "COFFSymbolRef points to nothing!");
00302     if (CS16) {
00303       // Reserved sections are returned as negative numbers.
00304       if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
00305         return CS16->SectionNumber;
00306       return static_cast<int16_t>(CS16->SectionNumber);
00307     }
00308     return static_cast<int32_t>(CS32->SectionNumber);
00309   }
00310 
00311   uint16_t getType() const {
00312     assert(isSet() && "COFFSymbolRef points to nothing!");
00313     return CS16 ? CS16->Type : CS32->Type;
00314   }
00315 
00316   uint8_t getStorageClass() const {
00317     assert(isSet() && "COFFSymbolRef points to nothing!");
00318     return CS16 ? CS16->StorageClass : CS32->StorageClass;
00319   }
00320 
00321   uint8_t getNumberOfAuxSymbols() const {
00322     assert(isSet() && "COFFSymbolRef points to nothing!");
00323     return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols;
00324   }
00325 
00326   uint8_t getBaseType() const { return getType() & 0x0F; }
00327 
00328   uint8_t getComplexType() const {
00329     return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
00330   }
00331 
00332   bool isAbsolute() const {
00333     return getSectionNumber() == -1;
00334   }
00335 
00336   bool isExternal() const {
00337     return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
00338   }
00339 
00340   bool isCommon() const {
00341     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
00342            getValue() != 0;
00343   }
00344 
00345   bool isUndefined() const {
00346     return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
00347            getValue() == 0;
00348   }
00349 
00350   bool isWeakExternal() const {
00351     return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
00352   }
00353 
00354   bool isFunctionDefinition() const {
00355     return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
00356            getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
00357            !COFF::isReservedSectionNumber(getSectionNumber());
00358   }
00359 
00360   bool isFunctionLineInfo() const {
00361     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
00362   }
00363 
00364   bool isAnyUndefined() const {
00365     return isUndefined() || isWeakExternal();
00366   }
00367 
00368   bool isFileRecord() const {
00369     return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
00370   }
00371 
00372   bool isSection() const {
00373     return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
00374   }
00375 
00376   bool isSectionDefinition() const {
00377     // C++/CLI creates external ABS symbols for non-const appdomain globals.
00378     // These are also followed by an auxiliary section definition.
00379     bool isAppdomainGlobal =
00380         getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
00381         getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE;
00382     bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
00383     if (!getNumberOfAuxSymbols())
00384       return false;
00385     return isAppdomainGlobal || isOrdinarySection;
00386   }
00387 
00388   bool isCLRToken() const {
00389     return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
00390   }
00391 
00392 private:
00393   bool isSet() const { return CS16 || CS32; }
00394 
00395   const coff_symbol16 *CS16;
00396   const coff_symbol32 *CS32;
00397 };
00398 
00399 struct coff_section {
00400   char Name[COFF::NameSize];
00401   support::ulittle32_t VirtualSize;
00402   support::ulittle32_t VirtualAddress;
00403   support::ulittle32_t SizeOfRawData;
00404   support::ulittle32_t PointerToRawData;
00405   support::ulittle32_t PointerToRelocations;
00406   support::ulittle32_t PointerToLinenumbers;
00407   support::ulittle16_t NumberOfRelocations;
00408   support::ulittle16_t NumberOfLinenumbers;
00409   support::ulittle32_t Characteristics;
00410 
00411   // Returns true if the actual number of relocations is stored in
00412   // VirtualAddress field of the first relocation table entry.
00413   bool hasExtendedRelocations() const {
00414     return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
00415            NumberOfRelocations == UINT16_MAX;
00416   }
00417 };
00418 
00419 struct coff_relocation {
00420   support::ulittle32_t VirtualAddress;
00421   support::ulittle32_t SymbolTableIndex;
00422   support::ulittle16_t Type;
00423 };
00424 
00425 struct coff_aux_function_definition {
00426   support::ulittle32_t TagIndex;
00427   support::ulittle32_t TotalSize;
00428   support::ulittle32_t PointerToLinenumber;
00429   support::ulittle32_t PointerToNextFunction;
00430 };
00431 
00432 struct coff_aux_bf_and_ef_symbol {
00433   char Unused1[4];
00434   support::ulittle16_t Linenumber;
00435   char Unused2[6];
00436   support::ulittle32_t PointerToNextFunction;
00437 };
00438 
00439 struct coff_aux_weak_external {
00440   support::ulittle32_t TagIndex;
00441   support::ulittle32_t Characteristics;
00442 };
00443 
00444 struct coff_aux_section_definition {
00445   support::ulittle32_t Length;
00446   support::ulittle16_t NumberOfRelocations;
00447   support::ulittle16_t NumberOfLinenumbers;
00448   support::ulittle32_t CheckSum;
00449   support::ulittle16_t NumberLowPart;
00450   uint8_t              Selection;
00451   uint8_t              Unused;
00452   support::ulittle16_t NumberHighPart;
00453   int32_t getNumber(bool IsBigObj) const {
00454     uint32_t Number = static_cast<uint32_t>(NumberLowPart);
00455     if (IsBigObj)
00456       Number |= static_cast<uint32_t>(NumberHighPart) << 16;
00457     return static_cast<int32_t>(Number);
00458   }
00459 };
00460 
00461 struct coff_aux_clr_token {
00462   uint8_t              AuxType;
00463   uint8_t              Reserved;
00464   support::ulittle32_t SymbolTableIndex;
00465 };
00466 
00467 struct coff_import_header {
00468   support::ulittle16_t Sig1;
00469   support::ulittle16_t Sig2;
00470   support::ulittle16_t Version;
00471   support::ulittle16_t Machine;
00472   support::ulittle32_t TimeDateStamp;
00473   support::ulittle32_t SizeOfData;
00474   support::ulittle16_t OrdinalHint;
00475   support::ulittle16_t TypeInfo;
00476   int getType() const { return TypeInfo & 0x3; }
00477   int getNameType() const { return (TypeInfo >> 2) & 0x7; }
00478 };
00479 
00480 struct coff_import_directory_table_entry {
00481   support::ulittle32_t ImportLookupTableRVA;
00482   support::ulittle32_t TimeDateStamp;
00483   support::ulittle32_t ForwarderChain;
00484   support::ulittle32_t NameRVA;
00485   support::ulittle32_t ImportAddressTableRVA;
00486 };
00487 
00488 struct coff_load_configuration32 {
00489   support::ulittle32_t Characteristics;
00490   support::ulittle32_t TimeDateStamp;
00491   support::ulittle16_t MajorVersion;
00492   support::ulittle16_t MinorVersion;
00493   support::ulittle32_t GlobalFlagsClear;
00494   support::ulittle32_t GlobalFlagsSet;
00495   support::ulittle32_t CriticalSectionDefaultTimeout;
00496   support::ulittle32_t DeCommitFreeBlockThreshold;
00497   support::ulittle32_t DeCommitTotalFreeThreshold;
00498   support::ulittle32_t LockPrefixTable;
00499   support::ulittle32_t MaximumAllocationSize;
00500   support::ulittle32_t VirtualMemoryThreshold;
00501   support::ulittle32_t ProcessAffinityMask;
00502   support::ulittle32_t ProcessHeapFlags;
00503   support::ulittle16_t CSDVersion;
00504   support::ulittle16_t Reserved;
00505   support::ulittle32_t EditList;
00506   support::ulittle32_t SecurityCookie;
00507   support::ulittle32_t SEHandlerTable;
00508   support::ulittle32_t SEHandlerCount;
00509 };
00510 
00511 struct coff_load_configuration64 {
00512   support::ulittle32_t Characteristics;
00513   support::ulittle32_t TimeDateStamp;
00514   support::ulittle16_t MajorVersion;
00515   support::ulittle16_t MinorVersion;
00516   support::ulittle32_t GlobalFlagsClear;
00517   support::ulittle32_t GlobalFlagsSet;
00518   support::ulittle32_t CriticalSectionDefaultTimeout;
00519   support::ulittle32_t DeCommitFreeBlockThreshold;
00520   support::ulittle32_t DeCommitTotalFreeThreshold;
00521   support::ulittle32_t LockPrefixTable;
00522   support::ulittle32_t MaximumAllocationSize;
00523   support::ulittle32_t VirtualMemoryThreshold;
00524   support::ulittle32_t ProcessAffinityMask;
00525   support::ulittle32_t ProcessHeapFlags;
00526   support::ulittle16_t CSDVersion;
00527   support::ulittle16_t Reserved;
00528   support::ulittle32_t EditList;
00529   support::ulittle64_t SecurityCookie;
00530   support::ulittle64_t SEHandlerTable;
00531   support::ulittle64_t SEHandlerCount;
00532 };
00533 
00534 struct coff_runtime_function_x64 {
00535   support::ulittle32_t BeginAddress;
00536   support::ulittle32_t EndAddress;
00537   support::ulittle32_t UnwindInformation;
00538 };
00539 
00540 struct coff_base_reloc_block_header {
00541   support::ulittle32_t PageRVA;
00542   support::ulittle32_t BlockSize;
00543 };
00544 
00545 struct coff_base_reloc_block_entry {
00546   support::ulittle16_t Data;
00547   int getType() const { return Data >> 12; }
00548   int getOffset() const { return Data & ((1 << 12) - 1); }
00549 };
00550 
00551 class COFFObjectFile : public ObjectFile {
00552 private:
00553   friend class ImportDirectoryEntryRef;
00554   friend class ExportDirectoryEntryRef;
00555   const coff_file_header *COFFHeader;
00556   const coff_bigobj_file_header *COFFBigObjHeader;
00557   const pe32_header *PE32Header;
00558   const pe32plus_header *PE32PlusHeader;
00559   const data_directory *DataDirectory;
00560   const coff_section *SectionTable;
00561   const coff_symbol16 *SymbolTable16;
00562   const coff_symbol32 *SymbolTable32;
00563   const char *StringTable;
00564   uint32_t StringTableSize;
00565   const import_directory_table_entry *ImportDirectory;
00566   uint32_t NumberOfImportDirectory;
00567   const delay_import_directory_table_entry *DelayImportDirectory;
00568   uint32_t NumberOfDelayImportDirectory;
00569   const export_directory_table_entry *ExportDirectory;
00570   const coff_base_reloc_block_header *BaseRelocHeader;
00571   const coff_base_reloc_block_header *BaseRelocEnd;
00572 
00573   std::error_code getString(uint32_t offset, StringRef &Res) const;
00574 
00575   template <typename coff_symbol_type>
00576   const coff_symbol_type *toSymb(DataRefImpl Symb) const;
00577   const coff_section *toSec(DataRefImpl Sec) const;
00578   const coff_relocation *toRel(DataRefImpl Rel) const;
00579 
00580   std::error_code initSymbolTablePtr();
00581   std::error_code initImportTablePtr();
00582   std::error_code initDelayImportTablePtr();
00583   std::error_code initExportTablePtr();
00584   std::error_code initBaseRelocPtr();
00585 
00586 public:
00587   uintptr_t getSymbolTable() const {
00588     if (SymbolTable16)
00589       return reinterpret_cast<uintptr_t>(SymbolTable16);
00590     if (SymbolTable32)
00591       return reinterpret_cast<uintptr_t>(SymbolTable32);
00592     return uintptr_t(0);
00593   }
00594   uint16_t getMachine() const {
00595     if (COFFHeader)
00596       return COFFHeader->Machine;
00597     if (COFFBigObjHeader)
00598       return COFFBigObjHeader->Machine;
00599     llvm_unreachable("no COFF header!");
00600   }
00601   uint16_t getSizeOfOptionalHeader() const {
00602     if (COFFHeader)
00603       return COFFHeader->isImportLibrary() ? 0
00604                                            : COFFHeader->SizeOfOptionalHeader;
00605     // bigobj doesn't have this field.
00606     if (COFFBigObjHeader)
00607       return 0;
00608     llvm_unreachable("no COFF header!");
00609   }
00610   uint16_t getCharacteristics() const {
00611     if (COFFHeader)
00612       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
00613     // bigobj doesn't have characteristics to speak of,
00614     // editbin will silently lie to you if you attempt to set any.
00615     if (COFFBigObjHeader)
00616       return 0;
00617     llvm_unreachable("no COFF header!");
00618   }
00619   uint32_t getTimeDateStamp() const {
00620     if (COFFHeader)
00621       return COFFHeader->TimeDateStamp;
00622     if (COFFBigObjHeader)
00623       return COFFBigObjHeader->TimeDateStamp;
00624     llvm_unreachable("no COFF header!");
00625   }
00626   uint32_t getNumberOfSections() const {
00627     if (COFFHeader)
00628       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
00629     if (COFFBigObjHeader)
00630       return COFFBigObjHeader->NumberOfSections;
00631     llvm_unreachable("no COFF header!");
00632   }
00633   uint32_t getPointerToSymbolTable() const {
00634     if (COFFHeader)
00635       return COFFHeader->isImportLibrary() ? 0
00636                                            : COFFHeader->PointerToSymbolTable;
00637     if (COFFBigObjHeader)
00638       return COFFBigObjHeader->PointerToSymbolTable;
00639     llvm_unreachable("no COFF header!");
00640   }
00641   uint32_t getNumberOfSymbols() const {
00642     if (COFFHeader)
00643       return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
00644     if (COFFBigObjHeader)
00645       return COFFBigObjHeader->NumberOfSymbols;
00646     llvm_unreachable("no COFF header!");
00647   }
00648 protected:
00649   void moveSymbolNext(DataRefImpl &Symb) const override;
00650   ErrorOr<StringRef> getSymbolName(DataRefImpl Symb) const override;
00651   ErrorOr<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
00652   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
00653   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
00654   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
00655   SymbolRef::Type getSymbolType(DataRefImpl Symb) const override;
00656   ErrorOr<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
00657   void moveSectionNext(DataRefImpl &Sec) const override;
00658   std::error_code getSectionName(DataRefImpl Sec,
00659                                  StringRef &Res) const override;
00660   uint64_t getSectionAddress(DataRefImpl Sec) const override;
00661   uint64_t getSectionSize(DataRefImpl Sec) const override;
00662   std::error_code getSectionContents(DataRefImpl Sec,
00663                                      StringRef &Res) const override;
00664   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
00665   bool isSectionText(DataRefImpl Sec) const override;
00666   bool isSectionData(DataRefImpl Sec) const override;
00667   bool isSectionBSS(DataRefImpl Sec) const override;
00668   bool isSectionVirtual(DataRefImpl Sec) const override;
00669   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
00670   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
00671 
00672   void moveRelocationNext(DataRefImpl &Rel) const override;
00673   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
00674   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
00675   uint64_t getRelocationType(DataRefImpl Rel) const override;
00676   void getRelocationTypeName(DataRefImpl Rel,
00677                              SmallVectorImpl<char> &Result) const override;
00678 
00679 public:
00680   COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
00681   basic_symbol_iterator symbol_begin_impl() const override;
00682   basic_symbol_iterator symbol_end_impl() const override;
00683   section_iterator section_begin() const override;
00684   section_iterator section_end() const override;
00685 
00686   const coff_section *getCOFFSection(const SectionRef &Section) const;
00687   COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
00688   COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
00689   const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
00690   unsigned getSectionID(SectionRef Sec) const;
00691   unsigned getSymbolSectionID(SymbolRef Sym) const;
00692 
00693   uint8_t getBytesInAddress() const override;
00694   StringRef getFileFormatName() const override;
00695   unsigned getArch() const override;
00696 
00697   import_directory_iterator import_directory_begin() const;
00698   import_directory_iterator import_directory_end() const;
00699   delay_import_directory_iterator delay_import_directory_begin() const;
00700   delay_import_directory_iterator delay_import_directory_end() const;
00701   export_directory_iterator export_directory_begin() const;
00702   export_directory_iterator export_directory_end() const;
00703   base_reloc_iterator base_reloc_begin() const;
00704   base_reloc_iterator base_reloc_end() const;
00705 
00706   iterator_range<import_directory_iterator> import_directories() const;
00707   iterator_range<delay_import_directory_iterator>
00708       delay_import_directories() const;
00709   iterator_range<export_directory_iterator> export_directories() const;
00710   iterator_range<base_reloc_iterator> base_relocs() const;
00711 
00712   const dos_header *getDOSHeader() const {
00713     if (!PE32Header && !PE32PlusHeader)
00714       return nullptr;
00715     return reinterpret_cast<const dos_header *>(base());
00716   }
00717   std::error_code getPE32Header(const pe32_header *&Res) const;
00718   std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
00719   std::error_code getDataDirectory(uint32_t index,
00720                                    const data_directory *&Res) const;
00721   std::error_code getSection(int32_t index, const coff_section *&Res) const;
00722   template <typename coff_symbol_type>
00723   std::error_code getSymbol(uint32_t Index,
00724                             const coff_symbol_type *&Res) const {
00725     if (Index >= getNumberOfSymbols())
00726       return object_error::parse_failed;
00727 
00728     Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
00729     return std::error_code();
00730   }
00731   ErrorOr<COFFSymbolRef> getSymbol(uint32_t index) const {
00732     if (SymbolTable16) {
00733       const coff_symbol16 *Symb = nullptr;
00734       if (std::error_code EC = getSymbol(index, Symb))
00735         return EC;
00736       return COFFSymbolRef(Symb);
00737     }
00738     if (SymbolTable32) {
00739       const coff_symbol32 *Symb = nullptr;
00740       if (std::error_code EC = getSymbol(index, Symb))
00741         return EC;
00742       return COFFSymbolRef(Symb);
00743     }
00744     return object_error::parse_failed;
00745   }
00746   template <typename T>
00747   std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
00748     ErrorOr<COFFSymbolRef> s = getSymbol(index);
00749     if (std::error_code EC = s.getError())
00750       return EC;
00751     Res = reinterpret_cast<const T *>(s->getRawPtr());
00752     return std::error_code();
00753   }
00754   std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
00755   std::error_code getSymbolName(const coff_symbol_generic *Symbol,
00756                                 StringRef &Res) const;
00757 
00758   ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
00759 
00760   size_t getSymbolTableEntrySize() const {
00761     if (COFFHeader)
00762       return sizeof(coff_symbol16);
00763     if (COFFBigObjHeader)
00764       return sizeof(coff_symbol32);
00765     llvm_unreachable("null symbol table pointer!");
00766   }
00767 
00768   iterator_range<const coff_relocation *>
00769   getRelocations(const coff_section *Sec) const;
00770 
00771   std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
00772   uint64_t getSectionSize(const coff_section *Sec) const;
00773   std::error_code getSectionContents(const coff_section *Sec,
00774                                      ArrayRef<uint8_t> &Res) const;
00775 
00776   uint64_t getImageBase() const;
00777   std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
00778   std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
00779   std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
00780                               StringRef &Name) const;
00781 
00782   bool isRelocatableObject() const override;
00783   bool is64() const { return PE32PlusHeader; }
00784 
00785   static inline bool classof(const Binary *v) { return v->isCOFF(); }
00786 };
00787 
00788 // The iterator for the import directory table.
00789 class ImportDirectoryEntryRef {
00790 public:
00791   ImportDirectoryEntryRef() : OwningObject(nullptr) {}
00792   ImportDirectoryEntryRef(const import_directory_table_entry *Table, uint32_t I,
00793                           const COFFObjectFile *Owner)
00794       : ImportTable(Table), Index(I), OwningObject(Owner) {}
00795 
00796   bool operator==(const ImportDirectoryEntryRef &Other) const;
00797   void moveNext();
00798 
00799   imported_symbol_iterator imported_symbol_begin() const;
00800   imported_symbol_iterator imported_symbol_end() const;
00801   iterator_range<imported_symbol_iterator> imported_symbols() const;
00802 
00803   std::error_code getName(StringRef &Result) const;
00804   std::error_code getImportLookupTableRVA(uint32_t &Result) const;
00805   std::error_code getImportAddressTableRVA(uint32_t &Result) const;
00806 
00807   std::error_code
00808   getImportTableEntry(const import_directory_table_entry *&Result) const;
00809 
00810   std::error_code
00811   getImportLookupEntry(const import_lookup_table_entry32 *&Result) const;
00812 
00813 private:
00814   const import_directory_table_entry *ImportTable;
00815   uint32_t Index;
00816   const COFFObjectFile *OwningObject;
00817 };
00818 
00819 class DelayImportDirectoryEntryRef {
00820 public:
00821   DelayImportDirectoryEntryRef() : OwningObject(nullptr) {}
00822   DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
00823                                uint32_t I, const COFFObjectFile *Owner)
00824       : Table(T), Index(I), OwningObject(Owner) {}
00825 
00826   bool operator==(const DelayImportDirectoryEntryRef &Other) const;
00827   void moveNext();
00828 
00829   imported_symbol_iterator imported_symbol_begin() const;
00830   imported_symbol_iterator imported_symbol_end() const;
00831   iterator_range<imported_symbol_iterator> imported_symbols() const;
00832 
00833   std::error_code getName(StringRef &Result) const;
00834   std::error_code getDelayImportTable(
00835       const delay_import_directory_table_entry *&Result) const;
00836   std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
00837 
00838 private:
00839   const delay_import_directory_table_entry *Table;
00840   uint32_t Index;
00841   const COFFObjectFile *OwningObject;
00842 };
00843 
00844 // The iterator for the export directory table entry.
00845 class ExportDirectoryEntryRef {
00846 public:
00847   ExportDirectoryEntryRef() : OwningObject(nullptr) {}
00848   ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
00849                           const COFFObjectFile *Owner)
00850       : ExportTable(Table), Index(I), OwningObject(Owner) {}
00851 
00852   bool operator==(const ExportDirectoryEntryRef &Other) const;
00853   void moveNext();
00854 
00855   std::error_code getDllName(StringRef &Result) const;
00856   std::error_code getOrdinalBase(uint32_t &Result) const;
00857   std::error_code getOrdinal(uint32_t &Result) const;
00858   std::error_code getExportRVA(uint32_t &Result) const;
00859   std::error_code getSymbolName(StringRef &Result) const;
00860 
00861   std::error_code isForwarder(bool &Result) const;
00862   std::error_code getForwardTo(StringRef &Result) const;
00863 
00864 private:
00865   const export_directory_table_entry *ExportTable;
00866   uint32_t Index;
00867   const COFFObjectFile *OwningObject;
00868 };
00869 
00870 class ImportedSymbolRef {
00871 public:
00872   ImportedSymbolRef() : OwningObject(nullptr) {}
00873   ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
00874                     const COFFObjectFile *Owner)
00875       : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
00876   ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
00877                     const COFFObjectFile *Owner)
00878       : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
00879 
00880   bool operator==(const ImportedSymbolRef &Other) const;
00881   void moveNext();
00882 
00883   std::error_code getSymbolName(StringRef &Result) const;
00884   std::error_code getOrdinal(uint16_t &Result) const;
00885 
00886 private:
00887   const import_lookup_table_entry32 *Entry32;
00888   const import_lookup_table_entry64 *Entry64;
00889   uint32_t Index;
00890   const COFFObjectFile *OwningObject;
00891 };
00892 
00893 class BaseRelocRef {
00894 public:
00895   BaseRelocRef() : OwningObject(nullptr) {}
00896   BaseRelocRef(const coff_base_reloc_block_header *Header,
00897                const COFFObjectFile *Owner)
00898       : Header(Header), Index(0), OwningObject(Owner) {}
00899 
00900   bool operator==(const BaseRelocRef &Other) const;
00901   void moveNext();
00902 
00903   std::error_code getType(uint8_t &Type) const;
00904   std::error_code getRVA(uint32_t &Result) const;
00905 
00906 private:
00907   const coff_base_reloc_block_header *Header;
00908   uint32_t Index;
00909   const COFFObjectFile *OwningObject;
00910 };
00911 
00912 } // end namespace object
00913 } // end namespace llvm
00914 
00915 #endif