COFF.h 42 KB

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