COFF.h 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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. HasEHContTable = 0x00400000,
  526. FidTableHasFlags = 0x10000000, // Indicates that fid tables are 5 bytes
  527. };
  528. enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 };
  529. struct coff_load_config_code_integrity {
  530. support::ulittle16_t Flags;
  531. support::ulittle16_t Catalog;
  532. support::ulittle32_t CatalogOffset;
  533. support::ulittle32_t Reserved;
  534. };
  535. /// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32)
  536. struct coff_load_configuration32 {
  537. support::ulittle32_t Size;
  538. support::ulittle32_t TimeDateStamp;
  539. support::ulittle16_t MajorVersion;
  540. support::ulittle16_t MinorVersion;
  541. support::ulittle32_t GlobalFlagsClear;
  542. support::ulittle32_t GlobalFlagsSet;
  543. support::ulittle32_t CriticalSectionDefaultTimeout;
  544. support::ulittle32_t DeCommitFreeBlockThreshold;
  545. support::ulittle32_t DeCommitTotalFreeThreshold;
  546. support::ulittle32_t LockPrefixTable;
  547. support::ulittle32_t MaximumAllocationSize;
  548. support::ulittle32_t VirtualMemoryThreshold;
  549. support::ulittle32_t ProcessAffinityMask;
  550. support::ulittle32_t ProcessHeapFlags;
  551. support::ulittle16_t CSDVersion;
  552. support::ulittle16_t DependentLoadFlags;
  553. support::ulittle32_t EditList;
  554. support::ulittle32_t SecurityCookie;
  555. support::ulittle32_t SEHandlerTable;
  556. support::ulittle32_t SEHandlerCount;
  557. // Added in MSVC 2015 for /guard:cf.
  558. support::ulittle32_t GuardCFCheckFunction;
  559. support::ulittle32_t GuardCFCheckDispatch;
  560. support::ulittle32_t GuardCFFunctionTable;
  561. support::ulittle32_t GuardCFFunctionCount;
  562. support::ulittle32_t GuardFlags; // coff_guard_flags
  563. // Added in MSVC 2017
  564. coff_load_config_code_integrity CodeIntegrity;
  565. support::ulittle32_t GuardAddressTakenIatEntryTable;
  566. support::ulittle32_t GuardAddressTakenIatEntryCount;
  567. support::ulittle32_t GuardLongJumpTargetTable;
  568. support::ulittle32_t GuardLongJumpTargetCount;
  569. support::ulittle32_t DynamicValueRelocTable;
  570. support::ulittle32_t CHPEMetadataPointer;
  571. support::ulittle32_t GuardRFFailureRoutine;
  572. support::ulittle32_t GuardRFFailureRoutineFunctionPointer;
  573. support::ulittle32_t DynamicValueRelocTableOffset;
  574. support::ulittle16_t DynamicValueRelocTableSection;
  575. support::ulittle16_t Reserved2;
  576. support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer;
  577. support::ulittle32_t HotPatchTableOffset;
  578. // Added in MSVC 2019
  579. support::ulittle32_t Reserved3;
  580. support::ulittle32_t EnclaveConfigurationPointer;
  581. support::ulittle32_t VolatileMetadataPointer;
  582. support::ulittle32_t GuardEHContinuationTable;
  583. support::ulittle32_t GuardEHContinuationCount;
  584. support::ulittle32_t GuardXFGCheckFunctionPointer;
  585. support::ulittle32_t GuardXFGDispatchFunctionPointer;
  586. support::ulittle32_t GuardXFGTableDispatchFunctionPointer;
  587. support::ulittle32_t CastGuardOsDeterminedFailureMode;
  588. };
  589. /// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64)
  590. struct coff_load_configuration64 {
  591. support::ulittle32_t Size;
  592. support::ulittle32_t TimeDateStamp;
  593. support::ulittle16_t MajorVersion;
  594. support::ulittle16_t MinorVersion;
  595. support::ulittle32_t GlobalFlagsClear;
  596. support::ulittle32_t GlobalFlagsSet;
  597. support::ulittle32_t CriticalSectionDefaultTimeout;
  598. support::ulittle64_t DeCommitFreeBlockThreshold;
  599. support::ulittle64_t DeCommitTotalFreeThreshold;
  600. support::ulittle64_t LockPrefixTable;
  601. support::ulittle64_t MaximumAllocationSize;
  602. support::ulittle64_t VirtualMemoryThreshold;
  603. support::ulittle64_t ProcessAffinityMask;
  604. support::ulittle32_t ProcessHeapFlags;
  605. support::ulittle16_t CSDVersion;
  606. support::ulittle16_t DependentLoadFlags;
  607. support::ulittle64_t EditList;
  608. support::ulittle64_t SecurityCookie;
  609. support::ulittle64_t SEHandlerTable;
  610. support::ulittle64_t SEHandlerCount;
  611. // Added in MSVC 2015 for /guard:cf.
  612. support::ulittle64_t GuardCFCheckFunction;
  613. support::ulittle64_t GuardCFCheckDispatch;
  614. support::ulittle64_t GuardCFFunctionTable;
  615. support::ulittle64_t GuardCFFunctionCount;
  616. support::ulittle32_t GuardFlags;
  617. // Added in MSVC 2017
  618. coff_load_config_code_integrity CodeIntegrity;
  619. support::ulittle64_t GuardAddressTakenIatEntryTable;
  620. support::ulittle64_t GuardAddressTakenIatEntryCount;
  621. support::ulittle64_t GuardLongJumpTargetTable;
  622. support::ulittle64_t GuardLongJumpTargetCount;
  623. support::ulittle64_t DynamicValueRelocTable;
  624. support::ulittle64_t CHPEMetadataPointer;
  625. support::ulittle64_t GuardRFFailureRoutine;
  626. support::ulittle64_t GuardRFFailureRoutineFunctionPointer;
  627. support::ulittle32_t DynamicValueRelocTableOffset;
  628. support::ulittle16_t DynamicValueRelocTableSection;
  629. support::ulittle16_t Reserved2;
  630. support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer;
  631. support::ulittle32_t HotPatchTableOffset;
  632. // Added in MSVC 2019
  633. support::ulittle32_t Reserved3;
  634. support::ulittle64_t EnclaveConfigurationPointer;
  635. support::ulittle64_t VolatileMetadataPointer;
  636. support::ulittle64_t GuardEHContinuationTable;
  637. support::ulittle64_t GuardEHContinuationCount;
  638. support::ulittle64_t GuardXFGCheckFunctionPointer;
  639. support::ulittle64_t GuardXFGDispatchFunctionPointer;
  640. support::ulittle64_t GuardXFGTableDispatchFunctionPointer;
  641. support::ulittle64_t CastGuardOsDeterminedFailureMode;
  642. };
  643. struct coff_runtime_function_x64 {
  644. support::ulittle32_t BeginAddress;
  645. support::ulittle32_t EndAddress;
  646. support::ulittle32_t UnwindInformation;
  647. };
  648. struct coff_base_reloc_block_header {
  649. support::ulittle32_t PageRVA;
  650. support::ulittle32_t BlockSize;
  651. };
  652. struct coff_base_reloc_block_entry {
  653. support::ulittle16_t Data;
  654. int getType() const { return Data >> 12; }
  655. int getOffset() const { return Data & ((1 << 12) - 1); }
  656. };
  657. struct coff_resource_dir_entry {
  658. union {
  659. support::ulittle32_t NameOffset;
  660. support::ulittle32_t ID;
  661. uint32_t getNameOffset() const {
  662. return maskTrailingOnes<uint32_t>(31) & NameOffset;
  663. }
  664. // Even though the PE/COFF spec doesn't mention this, the high bit of a name
  665. // offset is set.
  666. void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); }
  667. } Identifier;
  668. union {
  669. support::ulittle32_t DataEntryOffset;
  670. support::ulittle32_t SubdirOffset;
  671. bool isSubDir() const { return SubdirOffset >> 31; }
  672. uint32_t value() const {
  673. return maskTrailingOnes<uint32_t>(31) & SubdirOffset;
  674. }
  675. } Offset;
  676. };
  677. struct coff_resource_data_entry {
  678. support::ulittle32_t DataRVA;
  679. support::ulittle32_t DataSize;
  680. support::ulittle32_t Codepage;
  681. support::ulittle32_t Reserved;
  682. };
  683. struct coff_resource_dir_table {
  684. support::ulittle32_t Characteristics;
  685. support::ulittle32_t TimeDateStamp;
  686. support::ulittle16_t MajorVersion;
  687. support::ulittle16_t MinorVersion;
  688. support::ulittle16_t NumberOfNameEntries;
  689. support::ulittle16_t NumberOfIDEntries;
  690. };
  691. struct debug_h_header {
  692. support::ulittle32_t Magic;
  693. support::ulittle16_t Version;
  694. support::ulittle16_t HashAlgorithm;
  695. };
  696. class COFFObjectFile : public ObjectFile {
  697. private:
  698. COFFObjectFile(MemoryBufferRef Object);
  699. friend class ImportDirectoryEntryRef;
  700. friend class ExportDirectoryEntryRef;
  701. const coff_file_header *COFFHeader;
  702. const coff_bigobj_file_header *COFFBigObjHeader;
  703. const pe32_header *PE32Header;
  704. const pe32plus_header *PE32PlusHeader;
  705. const data_directory *DataDirectory;
  706. const coff_section *SectionTable;
  707. const coff_symbol16 *SymbolTable16;
  708. const coff_symbol32 *SymbolTable32;
  709. const char *StringTable;
  710. uint32_t StringTableSize;
  711. const coff_import_directory_table_entry *ImportDirectory;
  712. const delay_import_directory_table_entry *DelayImportDirectory;
  713. uint32_t NumberOfDelayImportDirectory;
  714. const export_directory_table_entry *ExportDirectory;
  715. const coff_base_reloc_block_header *BaseRelocHeader;
  716. const coff_base_reloc_block_header *BaseRelocEnd;
  717. const debug_directory *DebugDirectoryBegin;
  718. const debug_directory *DebugDirectoryEnd;
  719. const coff_tls_directory32 *TLSDirectory32;
  720. const coff_tls_directory64 *TLSDirectory64;
  721. // Either coff_load_configuration32 or coff_load_configuration64.
  722. const void *LoadConfig = nullptr;
  723. Expected<StringRef> getString(uint32_t offset) const;
  724. template <typename coff_symbol_type>
  725. const coff_symbol_type *toSymb(DataRefImpl Symb) const;
  726. const coff_section *toSec(DataRefImpl Sec) const;
  727. const coff_relocation *toRel(DataRefImpl Rel) const;
  728. // Finish initializing the object and return success or an error.
  729. Error initialize();
  730. Error initSymbolTablePtr();
  731. Error initImportTablePtr();
  732. Error initDelayImportTablePtr();
  733. Error initExportTablePtr();
  734. Error initBaseRelocPtr();
  735. Error initDebugDirectoryPtr();
  736. Error initTLSDirectoryPtr();
  737. Error initLoadConfigPtr();
  738. public:
  739. static Expected<std::unique_ptr<COFFObjectFile>>
  740. create(MemoryBufferRef Object);
  741. uintptr_t getSymbolTable() const {
  742. if (SymbolTable16)
  743. return reinterpret_cast<uintptr_t>(SymbolTable16);
  744. if (SymbolTable32)
  745. return reinterpret_cast<uintptr_t>(SymbolTable32);
  746. return uintptr_t(0);
  747. }
  748. uint16_t getMachine() const {
  749. if (COFFHeader)
  750. return COFFHeader->Machine;
  751. if (COFFBigObjHeader)
  752. return COFFBigObjHeader->Machine;
  753. llvm_unreachable("no COFF header!");
  754. }
  755. uint16_t getSizeOfOptionalHeader() const {
  756. if (COFFHeader)
  757. return COFFHeader->isImportLibrary() ? 0
  758. : COFFHeader->SizeOfOptionalHeader;
  759. // bigobj doesn't have this field.
  760. if (COFFBigObjHeader)
  761. return 0;
  762. llvm_unreachable("no COFF header!");
  763. }
  764. uint16_t getCharacteristics() const {
  765. if (COFFHeader)
  766. return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
  767. // bigobj doesn't have characteristics to speak of,
  768. // editbin will silently lie to you if you attempt to set any.
  769. if (COFFBigObjHeader)
  770. return 0;
  771. llvm_unreachable("no COFF header!");
  772. }
  773. uint32_t getTimeDateStamp() const {
  774. if (COFFHeader)
  775. return COFFHeader->TimeDateStamp;
  776. if (COFFBigObjHeader)
  777. return COFFBigObjHeader->TimeDateStamp;
  778. llvm_unreachable("no COFF header!");
  779. }
  780. uint32_t getNumberOfSections() const {
  781. if (COFFHeader)
  782. return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
  783. if (COFFBigObjHeader)
  784. return COFFBigObjHeader->NumberOfSections;
  785. llvm_unreachable("no COFF header!");
  786. }
  787. uint32_t getPointerToSymbolTable() const {
  788. if (COFFHeader)
  789. return COFFHeader->isImportLibrary() ? 0
  790. : COFFHeader->PointerToSymbolTable;
  791. if (COFFBigObjHeader)
  792. return COFFBigObjHeader->PointerToSymbolTable;
  793. llvm_unreachable("no COFF header!");
  794. }
  795. uint32_t getRawNumberOfSymbols() const {
  796. if (COFFHeader)
  797. return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
  798. if (COFFBigObjHeader)
  799. return COFFBigObjHeader->NumberOfSymbols;
  800. llvm_unreachable("no COFF header!");
  801. }
  802. uint32_t getNumberOfSymbols() const {
  803. if (!SymbolTable16 && !SymbolTable32)
  804. return 0;
  805. return getRawNumberOfSymbols();
  806. }
  807. uint32_t getStringTableSize() const { return StringTableSize; }
  808. const coff_load_configuration32 *getLoadConfig32() const {
  809. assert(!is64());
  810. return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig);
  811. }
  812. const coff_load_configuration64 *getLoadConfig64() const {
  813. assert(is64());
  814. return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig);
  815. }
  816. StringRef getRelocationTypeName(uint16_t Type) const;
  817. protected:
  818. void moveSymbolNext(DataRefImpl &Symb) const override;
  819. Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
  820. Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
  821. uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
  822. uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
  823. uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
  824. Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
  825. Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
  826. Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
  827. void moveSectionNext(DataRefImpl &Sec) const override;
  828. Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
  829. uint64_t getSectionAddress(DataRefImpl Sec) const override;
  830. uint64_t getSectionIndex(DataRefImpl Sec) const override;
  831. uint64_t getSectionSize(DataRefImpl Sec) const override;
  832. Expected<ArrayRef<uint8_t>>
  833. getSectionContents(DataRefImpl Sec) const override;
  834. uint64_t getSectionAlignment(DataRefImpl Sec) const override;
  835. bool isSectionCompressed(DataRefImpl Sec) const override;
  836. bool isSectionText(DataRefImpl Sec) const override;
  837. bool isSectionData(DataRefImpl Sec) const override;
  838. bool isSectionBSS(DataRefImpl Sec) const override;
  839. bool isSectionVirtual(DataRefImpl Sec) const override;
  840. bool isDebugSection(DataRefImpl Sec) const override;
  841. relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
  842. relocation_iterator section_rel_end(DataRefImpl Sec) const override;
  843. void moveRelocationNext(DataRefImpl &Rel) const override;
  844. uint64_t getRelocationOffset(DataRefImpl Rel) const override;
  845. symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
  846. uint64_t getRelocationType(DataRefImpl Rel) const override;
  847. void getRelocationTypeName(DataRefImpl Rel,
  848. SmallVectorImpl<char> &Result) const override;
  849. public:
  850. basic_symbol_iterator symbol_begin() const override;
  851. basic_symbol_iterator symbol_end() const override;
  852. section_iterator section_begin() const override;
  853. section_iterator section_end() const override;
  854. const coff_section *getCOFFSection(const SectionRef &Section) const;
  855. COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
  856. COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
  857. const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
  858. unsigned getSectionID(SectionRef Sec) const;
  859. unsigned getSymbolSectionID(SymbolRef Sym) const;
  860. uint8_t getBytesInAddress() const override;
  861. StringRef getFileFormatName() const override;
  862. Triple::ArchType getArch() const override;
  863. Expected<uint64_t> getStartAddress() const override;
  864. SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
  865. import_directory_iterator import_directory_begin() const;
  866. import_directory_iterator import_directory_end() const;
  867. delay_import_directory_iterator delay_import_directory_begin() const;
  868. delay_import_directory_iterator delay_import_directory_end() const;
  869. export_directory_iterator export_directory_begin() const;
  870. export_directory_iterator export_directory_end() const;
  871. base_reloc_iterator base_reloc_begin() const;
  872. base_reloc_iterator base_reloc_end() const;
  873. const debug_directory *debug_directory_begin() const {
  874. return DebugDirectoryBegin;
  875. }
  876. const debug_directory *debug_directory_end() const {
  877. return DebugDirectoryEnd;
  878. }
  879. iterator_range<import_directory_iterator> import_directories() const;
  880. iterator_range<delay_import_directory_iterator>
  881. delay_import_directories() const;
  882. iterator_range<export_directory_iterator> export_directories() const;
  883. iterator_range<base_reloc_iterator> base_relocs() const;
  884. iterator_range<const debug_directory *> debug_directories() const {
  885. return make_range(debug_directory_begin(), debug_directory_end());
  886. }
  887. const coff_tls_directory32 *getTLSDirectory32() const {
  888. return TLSDirectory32;
  889. }
  890. const coff_tls_directory64 *getTLSDirectory64() const {
  891. return TLSDirectory64;
  892. }
  893. const dos_header *getDOSHeader() const {
  894. if (!PE32Header && !PE32PlusHeader)
  895. return nullptr;
  896. return reinterpret_cast<const dos_header *>(base());
  897. }
  898. const coff_file_header *getCOFFHeader() const { return COFFHeader; }
  899. const coff_bigobj_file_header *getCOFFBigObjHeader() const {
  900. return COFFBigObjHeader;
  901. }
  902. const pe32_header *getPE32Header() const { return PE32Header; }
  903. const pe32plus_header *getPE32PlusHeader() const { return PE32PlusHeader; }
  904. const data_directory *getDataDirectory(uint32_t index) const;
  905. Expected<const coff_section *> getSection(int32_t index) const;
  906. Expected<COFFSymbolRef> getSymbol(uint32_t index) const {
  907. if (index >= getNumberOfSymbols())
  908. return errorCodeToError(object_error::parse_failed);
  909. if (SymbolTable16)
  910. return COFFSymbolRef(SymbolTable16 + index);
  911. if (SymbolTable32)
  912. return COFFSymbolRef(SymbolTable32 + index);
  913. return errorCodeToError(object_error::parse_failed);
  914. }
  915. template <typename T>
  916. Error getAuxSymbol(uint32_t index, const T *&Res) const {
  917. Expected<COFFSymbolRef> S = getSymbol(index);
  918. if (Error E = S.takeError())
  919. return E;
  920. Res = reinterpret_cast<const T *>(S->getRawPtr());
  921. return Error::success();
  922. }
  923. Expected<StringRef> getSymbolName(COFFSymbolRef Symbol) const;
  924. Expected<StringRef> getSymbolName(const coff_symbol_generic *Symbol) const;
  925. ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
  926. uint32_t getSymbolIndex(COFFSymbolRef Symbol) const;
  927. size_t getSymbolTableEntrySize() const {
  928. if (COFFHeader)
  929. return sizeof(coff_symbol16);
  930. if (COFFBigObjHeader)
  931. return sizeof(coff_symbol32);
  932. llvm_unreachable("null symbol table pointer!");
  933. }
  934. ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const;
  935. Expected<StringRef> getSectionName(const coff_section *Sec) const;
  936. uint64_t getSectionSize(const coff_section *Sec) const;
  937. Error getSectionContents(const coff_section *Sec,
  938. ArrayRef<uint8_t> &Res) const;
  939. uint64_t getImageBase() const;
  940. Error getVaPtr(uint64_t VA, uintptr_t &Res) const;
  941. Error getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
  942. /// Given an RVA base and size, returns a valid array of bytes or an error
  943. /// code if the RVA and size is not contained completely within a valid
  944. /// section.
  945. Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
  946. ArrayRef<uint8_t> &Contents) const;
  947. Error getHintName(uint32_t Rva, uint16_t &Hint,
  948. StringRef &Name) const;
  949. /// Get PDB information out of a codeview debug directory entry.
  950. Error getDebugPDBInfo(const debug_directory *DebugDir,
  951. const codeview::DebugInfo *&Info,
  952. StringRef &PDBFileName) const;
  953. /// Get PDB information from an executable. If the information is not present,
  954. /// Info will be set to nullptr and PDBFileName will be empty. An error is
  955. /// returned only on corrupt object files. Convenience accessor that can be
  956. /// used if the debug directory is not already handy.
  957. Error getDebugPDBInfo(const codeview::DebugInfo *&Info,
  958. StringRef &PDBFileName) const;
  959. bool isRelocatableObject() const override;
  960. bool is64() const { return PE32PlusHeader; }
  961. StringRef mapDebugSectionName(StringRef Name) const override;
  962. static bool classof(const Binary *v) { return v->isCOFF(); }
  963. };
  964. // The iterator for the import directory table.
  965. class ImportDirectoryEntryRef {
  966. public:
  967. ImportDirectoryEntryRef() = default;
  968. ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
  969. uint32_t I, const COFFObjectFile *Owner)
  970. : ImportTable(Table), Index(I), OwningObject(Owner) {}
  971. bool operator==(const ImportDirectoryEntryRef &Other) const;
  972. void moveNext();
  973. imported_symbol_iterator imported_symbol_begin() const;
  974. imported_symbol_iterator imported_symbol_end() const;
  975. iterator_range<imported_symbol_iterator> imported_symbols() const;
  976. imported_symbol_iterator lookup_table_begin() const;
  977. imported_symbol_iterator lookup_table_end() const;
  978. iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
  979. Error getName(StringRef &Result) const;
  980. Error getImportLookupTableRVA(uint32_t &Result) const;
  981. Error getImportAddressTableRVA(uint32_t &Result) const;
  982. Error
  983. getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
  984. private:
  985. const coff_import_directory_table_entry *ImportTable;
  986. uint32_t Index;
  987. const COFFObjectFile *OwningObject = nullptr;
  988. };
  989. class DelayImportDirectoryEntryRef {
  990. public:
  991. DelayImportDirectoryEntryRef() = default;
  992. DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
  993. uint32_t I, const COFFObjectFile *Owner)
  994. : Table(T), Index(I), OwningObject(Owner) {}
  995. bool operator==(const DelayImportDirectoryEntryRef &Other) const;
  996. void moveNext();
  997. imported_symbol_iterator imported_symbol_begin() const;
  998. imported_symbol_iterator imported_symbol_end() const;
  999. iterator_range<imported_symbol_iterator> imported_symbols() const;
  1000. Error getName(StringRef &Result) const;
  1001. Error getDelayImportTable(
  1002. const delay_import_directory_table_entry *&Result) const;
  1003. Error getImportAddress(int AddrIndex, uint64_t &Result) const;
  1004. private:
  1005. const delay_import_directory_table_entry *Table;
  1006. uint32_t Index;
  1007. const COFFObjectFile *OwningObject = nullptr;
  1008. };
  1009. // The iterator for the export directory table entry.
  1010. class ExportDirectoryEntryRef {
  1011. public:
  1012. ExportDirectoryEntryRef() = default;
  1013. ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
  1014. const COFFObjectFile *Owner)
  1015. : ExportTable(Table), Index(I), OwningObject(Owner) {}
  1016. bool operator==(const ExportDirectoryEntryRef &Other) const;
  1017. void moveNext();
  1018. Error getDllName(StringRef &Result) const;
  1019. Error getOrdinalBase(uint32_t &Result) const;
  1020. Error getOrdinal(uint32_t &Result) const;
  1021. Error getExportRVA(uint32_t &Result) const;
  1022. Error getSymbolName(StringRef &Result) const;
  1023. Error isForwarder(bool &Result) const;
  1024. Error getForwardTo(StringRef &Result) const;
  1025. private:
  1026. const export_directory_table_entry *ExportTable;
  1027. uint32_t Index;
  1028. const COFFObjectFile *OwningObject = nullptr;
  1029. };
  1030. class ImportedSymbolRef {
  1031. public:
  1032. ImportedSymbolRef() = default;
  1033. ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
  1034. const COFFObjectFile *Owner)
  1035. : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
  1036. ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
  1037. const COFFObjectFile *Owner)
  1038. : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
  1039. bool operator==(const ImportedSymbolRef &Other) const;
  1040. void moveNext();
  1041. Error getSymbolName(StringRef &Result) const;
  1042. Error isOrdinal(bool &Result) const;
  1043. Error getOrdinal(uint16_t &Result) const;
  1044. Error getHintNameRVA(uint32_t &Result) const;
  1045. private:
  1046. const import_lookup_table_entry32 *Entry32;
  1047. const import_lookup_table_entry64 *Entry64;
  1048. uint32_t Index;
  1049. const COFFObjectFile *OwningObject = nullptr;
  1050. };
  1051. class BaseRelocRef {
  1052. public:
  1053. BaseRelocRef() = default;
  1054. BaseRelocRef(const coff_base_reloc_block_header *Header,
  1055. const COFFObjectFile *Owner)
  1056. : Header(Header), Index(0) {}
  1057. bool operator==(const BaseRelocRef &Other) const;
  1058. void moveNext();
  1059. Error getType(uint8_t &Type) const;
  1060. Error getRVA(uint32_t &Result) const;
  1061. private:
  1062. const coff_base_reloc_block_header *Header;
  1063. uint32_t Index;
  1064. };
  1065. class ResourceSectionRef {
  1066. public:
  1067. ResourceSectionRef() = default;
  1068. explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {}
  1069. Error load(const COFFObjectFile *O);
  1070. Error load(const COFFObjectFile *O, const SectionRef &S);
  1071. Expected<ArrayRef<UTF16>>
  1072. getEntryNameString(const coff_resource_dir_entry &Entry);
  1073. Expected<const coff_resource_dir_table &>
  1074. getEntrySubDir(const coff_resource_dir_entry &Entry);
  1075. Expected<const coff_resource_data_entry &>
  1076. getEntryData(const coff_resource_dir_entry &Entry);
  1077. Expected<const coff_resource_dir_table &> getBaseTable();
  1078. Expected<const coff_resource_dir_entry &>
  1079. getTableEntry(const coff_resource_dir_table &Table, uint32_t Index);
  1080. Expected<StringRef> getContents(const coff_resource_data_entry &Entry);
  1081. private:
  1082. BinaryByteStream BBS;
  1083. SectionRef Section;
  1084. const COFFObjectFile *Obj;
  1085. std::vector<const coff_relocation *> Relocs;
  1086. Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset);
  1087. Expected<const coff_resource_dir_entry &>
  1088. getTableEntryAtOffset(uint32_t Offset);
  1089. Expected<const coff_resource_data_entry &>
  1090. getDataEntryAtOffset(uint32_t Offset);
  1091. Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset);
  1092. };
  1093. // Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
  1094. struct FpoData {
  1095. support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
  1096. support::ulittle32_t Size; // cbProcSize: # bytes in function
  1097. support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
  1098. support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
  1099. support::ulittle16_t Attributes;
  1100. // cbProlog: # bytes in prolog
  1101. int getPrologSize() const { return Attributes & 0xF; }
  1102. // cbRegs: # regs saved
  1103. int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
  1104. // fHasSEH: true if seh is func
  1105. bool hasSEH() const { return (Attributes >> 9) & 1; }
  1106. // fUseBP: true if EBP has been allocated
  1107. bool useBP() const { return (Attributes >> 10) & 1; }
  1108. // cbFrame: frame pointer
  1109. frame_type getFP() const { return static_cast<frame_type>(Attributes >> 14); }
  1110. };
  1111. } // end namespace object
  1112. } // end namespace llvm
  1113. #endif // LLVM_OBJECT_COFF_H
  1114. #ifdef __GNUC__
  1115. #pragma GCC diagnostic pop
  1116. #endif