COFFDump.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. //===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file implements the COFF-specific dumper for llvm-objdump.
  11. /// It outputs the Win64 EH data structures as plain text.
  12. /// The encoding of the unwind codes is described in MSDN:
  13. /// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "COFFDump.h"
  17. #include "llvm-objdump.h"
  18. #include "llvm/Demangle/Demangle.h"
  19. #include "llvm/Object/COFF.h"
  20. #include "llvm/Object/COFFImportFile.h"
  21. #include "llvm/Object/ObjectFile.h"
  22. #include "llvm/Support/Format.h"
  23. #include "llvm/Support/Win64EH.h"
  24. #include "llvm/Support/WithColor.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace llvm;
  27. using namespace llvm::objdump;
  28. using namespace llvm::object;
  29. using namespace llvm::Win64EH;
  30. namespace {
  31. template <typename T> struct EnumEntry {
  32. T Value;
  33. StringRef Name;
  34. };
  35. class COFFDumper {
  36. public:
  37. explicit COFFDumper(const llvm::object::COFFObjectFile &Obj) : Obj(Obj) {
  38. Is64 = !Obj.getPE32Header();
  39. }
  40. template <class PEHeader> void printPEHeader(const PEHeader &Hdr) const;
  41. private:
  42. template <typename T> FormattedNumber formatAddr(T V) const {
  43. return format_hex_no_prefix(V, Is64 ? 16 : 8);
  44. }
  45. uint32_t getBaseOfData(const void *Hdr) const {
  46. return Is64 ? 0 : static_cast<const pe32_header *>(Hdr)->BaseOfData;
  47. }
  48. const llvm::object::COFFObjectFile &Obj;
  49. bool Is64;
  50. };
  51. } // namespace
  52. constexpr EnumEntry<uint16_t> PEHeaderMagic[] = {
  53. {uint16_t(COFF::PE32Header::PE32), "PE32"},
  54. {uint16_t(COFF::PE32Header::PE32_PLUS), "PE32+"},
  55. };
  56. constexpr EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
  57. {COFF::IMAGE_SUBSYSTEM_UNKNOWN, "unspecified"},
  58. {COFF::IMAGE_SUBSYSTEM_NATIVE, "NT native"},
  59. {COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI, "Windows GUI"},
  60. {COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI, "Windows CUI"},
  61. {COFF::IMAGE_SUBSYSTEM_POSIX_CUI, "POSIX CUI"},
  62. {COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI, "Wince CUI"},
  63. {COFF::IMAGE_SUBSYSTEM_EFI_APPLICATION, "EFI application"},
  64. {COFF::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, "EFI boot service driver"},
  65. {COFF::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, "EFI runtime driver"},
  66. {COFF::IMAGE_SUBSYSTEM_EFI_ROM, "SAL runtime driver"},
  67. {COFF::IMAGE_SUBSYSTEM_XBOX, "XBOX"},
  68. };
  69. template <typename T, typename TEnum>
  70. static void printOptionalEnumName(T Value,
  71. ArrayRef<EnumEntry<TEnum>> EnumValues) {
  72. for (const EnumEntry<TEnum> &I : EnumValues)
  73. if (I.Value == Value) {
  74. outs() << "\t(" << I.Name << ')';
  75. return;
  76. }
  77. }
  78. template <class PEHeader>
  79. void COFFDumper::printPEHeader(const PEHeader &Hdr) const {
  80. auto print = [](const char *K, auto V, const char *Fmt = "%d\n") {
  81. outs() << format("%-23s ", K) << format(Fmt, V);
  82. };
  83. auto printU16 = [&](const char *K, support::ulittle16_t V,
  84. const char *Fmt = "%d\n") { print(K, uint16_t(V), Fmt); };
  85. auto printU32 = [&](const char *K, support::ulittle32_t V,
  86. const char *Fmt = "%d\n") { print(K, uint32_t(V), Fmt); };
  87. auto printAddr = [=](const char *K, uint64_t V) {
  88. outs() << format("%-23s ", K) << formatAddr(V) << '\n';
  89. };
  90. printU16("Magic", Hdr.Magic, "%04x");
  91. printOptionalEnumName(Hdr.Magic, makeArrayRef(PEHeaderMagic));
  92. outs() << '\n';
  93. print("MajorLinkerVersion", Hdr.MajorLinkerVersion);
  94. print("MinorLinkerVersion", Hdr.MinorLinkerVersion);
  95. printAddr("SizeOfCode", Hdr.SizeOfCode);
  96. printAddr("SizeOfInitializedData", Hdr.SizeOfInitializedData);
  97. printAddr("SizeOfUninitializedData", Hdr.SizeOfUninitializedData);
  98. printAddr("AddressOfEntryPoint", Hdr.AddressOfEntryPoint);
  99. printAddr("BaseOfCode", Hdr.BaseOfCode);
  100. if (!Is64)
  101. printAddr("BaseOfData", getBaseOfData(&Hdr));
  102. printAddr("ImageBase", Hdr.ImageBase);
  103. printU32("SectionAlignment", Hdr.SectionAlignment, "%08x\n");
  104. printU32("FileAlignment", Hdr.FileAlignment, "%08x\n");
  105. printU16("MajorOSystemVersion", Hdr.MajorOperatingSystemVersion);
  106. printU16("MinorOSystemVersion", Hdr.MinorOperatingSystemVersion);
  107. printU16("MajorImageVersion", Hdr.MajorImageVersion);
  108. printU16("MinorImageVersion", Hdr.MinorImageVersion);
  109. printU16("MajorSubsystemVersion", Hdr.MajorSubsystemVersion);
  110. printU16("MinorSubsystemVersion", Hdr.MinorSubsystemVersion);
  111. printU32("Win32Version", Hdr.Win32VersionValue, "%08x\n");
  112. printU32("SizeOfImage", Hdr.SizeOfImage, "%08x\n");
  113. printU32("SizeOfHeaders", Hdr.SizeOfHeaders, "%08x\n");
  114. printU32("CheckSum", Hdr.CheckSum, "%08x\n");
  115. printU16("Subsystem", Hdr.Subsystem, "%08x");
  116. printOptionalEnumName(Hdr.Subsystem, makeArrayRef(PEWindowsSubsystem));
  117. outs() << '\n';
  118. printU16("DllCharacteristics", Hdr.DLLCharacteristics, "%08x\n");
  119. #define FLAG(Name) \
  120. if (Hdr.DLLCharacteristics & COFF::IMAGE_DLL_CHARACTERISTICS_##Name) \
  121. outs() << "\t\t\t\t\t" << #Name << '\n';
  122. FLAG(HIGH_ENTROPY_VA);
  123. FLAG(DYNAMIC_BASE);
  124. FLAG(FORCE_INTEGRITY);
  125. FLAG(NX_COMPAT);
  126. FLAG(NO_ISOLATION);
  127. FLAG(NO_SEH);
  128. FLAG(NO_BIND);
  129. FLAG(APPCONTAINER);
  130. FLAG(WDM_DRIVER);
  131. FLAG(GUARD_CF);
  132. FLAG(TERMINAL_SERVER_AWARE);
  133. #undef FLAG
  134. printAddr("SizeOfStackReserve", Hdr.SizeOfStackReserve);
  135. printAddr("SizeOfStackCommit", Hdr.SizeOfStackCommit);
  136. printAddr("SizeOfHeapReserve", Hdr.SizeOfHeapReserve);
  137. printAddr("SizeOfHeapCommit", Hdr.SizeOfHeapCommit);
  138. printU32("LoaderFlags", Hdr.LoaderFlags, "%08x\n");
  139. printU32("NumberOfRvaAndSizes", Hdr.NumberOfRvaAndSize, "%08x\n");
  140. static const char *DirName[COFF::NUM_DATA_DIRECTORIES + 1] = {
  141. "Export Directory [.edata (or where ever we found it)]",
  142. "Import Directory [parts of .idata]",
  143. "Resource Directory [.rsrc]",
  144. "Exception Directory [.pdata]",
  145. "Security Directory",
  146. "Base Relocation Directory [.reloc]",
  147. "Debug Directory",
  148. "Description Directory",
  149. "Special Directory",
  150. "Thread Storage Directory [.tls]",
  151. "Load Configuration Directory",
  152. "Bound Import Directory",
  153. "Import Address Table Directory",
  154. "Delay Import Directory",
  155. "CLR Runtime Header",
  156. "Reserved",
  157. };
  158. outs() << "\nThe Data Directory\n";
  159. for (uint32_t I = 0; I != array_lengthof(DirName); ++I) {
  160. uint32_t Addr = 0, Size = 0;
  161. if (const data_directory *Data = Obj.getDataDirectory(I)) {
  162. Addr = Data->RelativeVirtualAddress;
  163. Size = Data->Size;
  164. }
  165. outs() << format("Entry %x ", I) << formatAddr(Addr)
  166. << format(" %08x %s\n", uint32_t(Size), DirName[I]);
  167. }
  168. }
  169. // Returns the name of the unwind code.
  170. static StringRef getUnwindCodeTypeName(uint8_t Code) {
  171. switch(Code) {
  172. default: llvm_unreachable("Invalid unwind code");
  173. case UOP_PushNonVol: return "UOP_PushNonVol";
  174. case UOP_AllocLarge: return "UOP_AllocLarge";
  175. case UOP_AllocSmall: return "UOP_AllocSmall";
  176. case UOP_SetFPReg: return "UOP_SetFPReg";
  177. case UOP_SaveNonVol: return "UOP_SaveNonVol";
  178. case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
  179. case UOP_SaveXMM128: return "UOP_SaveXMM128";
  180. case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
  181. case UOP_PushMachFrame: return "UOP_PushMachFrame";
  182. }
  183. }
  184. // Returns the name of a referenced register.
  185. static StringRef getUnwindRegisterName(uint8_t Reg) {
  186. switch(Reg) {
  187. default: llvm_unreachable("Invalid register");
  188. case 0: return "RAX";
  189. case 1: return "RCX";
  190. case 2: return "RDX";
  191. case 3: return "RBX";
  192. case 4: return "RSP";
  193. case 5: return "RBP";
  194. case 6: return "RSI";
  195. case 7: return "RDI";
  196. case 8: return "R8";
  197. case 9: return "R9";
  198. case 10: return "R10";
  199. case 11: return "R11";
  200. case 12: return "R12";
  201. case 13: return "R13";
  202. case 14: return "R14";
  203. case 15: return "R15";
  204. }
  205. }
  206. // Calculates the number of array slots required for the unwind code.
  207. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
  208. switch (UnwindCode.getUnwindOp()) {
  209. default: llvm_unreachable("Invalid unwind code");
  210. case UOP_PushNonVol:
  211. case UOP_AllocSmall:
  212. case UOP_SetFPReg:
  213. case UOP_PushMachFrame:
  214. return 1;
  215. case UOP_SaveNonVol:
  216. case UOP_SaveXMM128:
  217. return 2;
  218. case UOP_SaveNonVolBig:
  219. case UOP_SaveXMM128Big:
  220. return 3;
  221. case UOP_AllocLarge:
  222. return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
  223. }
  224. }
  225. // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
  226. // the unwind codes array, this function requires that the correct number of
  227. // slots is provided.
  228. static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
  229. assert(UCs.size() >= getNumUsedSlots(UCs[0]));
  230. outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
  231. << getUnwindCodeTypeName(UCs[0].getUnwindOp());
  232. switch (UCs[0].getUnwindOp()) {
  233. case UOP_PushNonVol:
  234. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
  235. break;
  236. case UOP_AllocLarge:
  237. if (UCs[0].getOpInfo() == 0) {
  238. outs() << " " << UCs[1].FrameOffset;
  239. } else {
  240. outs() << " " << UCs[1].FrameOffset
  241. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
  242. }
  243. break;
  244. case UOP_AllocSmall:
  245. outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
  246. break;
  247. case UOP_SetFPReg:
  248. outs() << " ";
  249. break;
  250. case UOP_SaveNonVol:
  251. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  252. << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
  253. break;
  254. case UOP_SaveNonVolBig:
  255. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  256. << format(" [0x%08x]", UCs[1].FrameOffset
  257. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  258. break;
  259. case UOP_SaveXMM128:
  260. outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
  261. << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
  262. break;
  263. case UOP_SaveXMM128Big:
  264. outs() << " XMM" << UCs[0].getOpInfo()
  265. << format(" [0x%08x]", UCs[1].FrameOffset
  266. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  267. break;
  268. case UOP_PushMachFrame:
  269. outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
  270. << " error code";
  271. break;
  272. }
  273. outs() << "\n";
  274. }
  275. static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
  276. for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
  277. unsigned UsedSlots = getNumUsedSlots(*I);
  278. if (UsedSlots > UCs.size()) {
  279. outs() << "Unwind data corrupted: Encountered unwind op "
  280. << getUnwindCodeTypeName((*I).getUnwindOp())
  281. << " which requires " << UsedSlots
  282. << " slots, but only " << UCs.size()
  283. << " remaining in buffer";
  284. return ;
  285. }
  286. printUnwindCode(makeArrayRef(I, E));
  287. I += UsedSlots;
  288. }
  289. }
  290. // Given a symbol sym this functions returns the address and section of it.
  291. static Error resolveSectionAndAddress(const COFFObjectFile *Obj,
  292. const SymbolRef &Sym,
  293. const coff_section *&ResolvedSection,
  294. uint64_t &ResolvedAddr) {
  295. Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
  296. if (!ResolvedAddrOrErr)
  297. return ResolvedAddrOrErr.takeError();
  298. ResolvedAddr = *ResolvedAddrOrErr;
  299. Expected<section_iterator> Iter = Sym.getSection();
  300. if (!Iter)
  301. return Iter.takeError();
  302. ResolvedSection = Obj->getCOFFSection(**Iter);
  303. return Error::success();
  304. }
  305. // Given a vector of relocations for a section and an offset into this section
  306. // the function returns the symbol used for the relocation at the offset.
  307. static Error resolveSymbol(const std::vector<RelocationRef> &Rels,
  308. uint64_t Offset, SymbolRef &Sym) {
  309. for (auto &R : Rels) {
  310. uint64_t Ofs = R.getOffset();
  311. if (Ofs == Offset) {
  312. Sym = *R.getSymbol();
  313. return Error::success();
  314. }
  315. }
  316. return make_error<BinaryError>();
  317. }
  318. // Given a vector of relocations for a section and an offset into this section
  319. // the function resolves the symbol used for the relocation at the offset and
  320. // returns the section content and the address inside the content pointed to
  321. // by the symbol.
  322. static Error
  323. getSectionContents(const COFFObjectFile *Obj,
  324. const std::vector<RelocationRef> &Rels, uint64_t Offset,
  325. ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
  326. SymbolRef Sym;
  327. if (Error E = resolveSymbol(Rels, Offset, Sym))
  328. return E;
  329. const coff_section *Section;
  330. if (Error E = resolveSectionAndAddress(Obj, Sym, Section, Addr))
  331. return E;
  332. return Obj->getSectionContents(Section, Contents);
  333. }
  334. // Given a vector of relocations for a section and an offset into this section
  335. // the function returns the name of the symbol used for the relocation at the
  336. // offset.
  337. static Error resolveSymbolName(const std::vector<RelocationRef> &Rels,
  338. uint64_t Offset, StringRef &Name) {
  339. SymbolRef Sym;
  340. if (Error EC = resolveSymbol(Rels, Offset, Sym))
  341. return EC;
  342. Expected<StringRef> NameOrErr = Sym.getName();
  343. if (!NameOrErr)
  344. return NameOrErr.takeError();
  345. Name = *NameOrErr;
  346. return Error::success();
  347. }
  348. static void printCOFFSymbolAddress(raw_ostream &Out,
  349. const std::vector<RelocationRef> &Rels,
  350. uint64_t Offset, uint32_t Disp) {
  351. StringRef Sym;
  352. if (!resolveSymbolName(Rels, Offset, Sym)) {
  353. Out << Sym;
  354. if (Disp > 0)
  355. Out << format(" + 0x%04x", Disp);
  356. } else {
  357. Out << format("0x%04x", Disp);
  358. }
  359. }
  360. static void
  361. printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
  362. if (Count == 0)
  363. return;
  364. uintptr_t IntPtr = 0;
  365. if (Error E = Obj->getVaPtr(TableVA, IntPtr))
  366. reportError(std::move(E), Obj->getFileName());
  367. const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
  368. outs() << "SEH Table:";
  369. for (int I = 0; I < Count; ++I)
  370. outs() << format(" 0x%x", P[I] + Obj->getPE32Header()->ImageBase);
  371. outs() << "\n\n";
  372. }
  373. template <typename T>
  374. static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
  375. size_t FormatWidth = sizeof(T) * 2;
  376. outs() << "TLS directory:"
  377. << "\n StartAddressOfRawData: "
  378. << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
  379. << "\n EndAddressOfRawData: "
  380. << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
  381. << "\n AddressOfIndex: "
  382. << format_hex(TLSDir->AddressOfIndex, FormatWidth)
  383. << "\n AddressOfCallBacks: "
  384. << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
  385. << "\n SizeOfZeroFill: "
  386. << TLSDir->SizeOfZeroFill
  387. << "\n Characteristics: "
  388. << TLSDir->Characteristics
  389. << "\n Alignment: "
  390. << TLSDir->getAlignment()
  391. << "\n\n";
  392. }
  393. static void printTLSDirectory(const COFFObjectFile *Obj) {
  394. const pe32_header *PE32Header = Obj->getPE32Header();
  395. const pe32plus_header *PE32PlusHeader = Obj->getPE32PlusHeader();
  396. // Skip if it's not executable.
  397. if (!PE32Header && !PE32PlusHeader)
  398. return;
  399. const data_directory *DataDir = Obj->getDataDirectory(COFF::TLS_TABLE);
  400. if (!DataDir || DataDir->RelativeVirtualAddress == 0)
  401. return;
  402. uintptr_t IntPtr = 0;
  403. if (Error E =
  404. Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))
  405. reportError(std::move(E), Obj->getFileName());
  406. if (PE32Header) {
  407. auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
  408. printTLSDirectoryT(TLSDir);
  409. } else {
  410. auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
  411. printTLSDirectoryT(TLSDir);
  412. }
  413. outs() << "\n";
  414. }
  415. static void printLoadConfiguration(const COFFObjectFile *Obj) {
  416. // Skip if it's not executable.
  417. if (!Obj->getPE32Header())
  418. return;
  419. // Currently only x86 is supported
  420. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
  421. return;
  422. const data_directory *DataDir = Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE);
  423. if (!DataDir)
  424. reportError("no load config data dir", Obj->getFileName());
  425. uintptr_t IntPtr = 0;
  426. if (DataDir->RelativeVirtualAddress == 0)
  427. return;
  428. if (Error E =
  429. Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))
  430. reportError(std::move(E), Obj->getFileName());
  431. auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
  432. outs() << "Load configuration:"
  433. << "\n Timestamp: " << LoadConf->TimeDateStamp
  434. << "\n Major Version: " << LoadConf->MajorVersion
  435. << "\n Minor Version: " << LoadConf->MinorVersion
  436. << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
  437. << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
  438. << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
  439. << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
  440. << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
  441. << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
  442. << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
  443. << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
  444. << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
  445. << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
  446. << "\n CSD Version: " << LoadConf->CSDVersion
  447. << "\n Security Cookie: " << LoadConf->SecurityCookie
  448. << "\n SEH Table: " << LoadConf->SEHandlerTable
  449. << "\n SEH Count: " << LoadConf->SEHandlerCount
  450. << "\n\n";
  451. printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
  452. outs() << "\n";
  453. }
  454. // Prints import tables. The import table is a table containing the list of
  455. // DLL name and symbol names which will be linked by the loader.
  456. static void printImportTables(const COFFObjectFile *Obj) {
  457. import_directory_iterator I = Obj->import_directory_begin();
  458. import_directory_iterator E = Obj->import_directory_end();
  459. if (I == E)
  460. return;
  461. outs() << "The Import Tables:\n";
  462. for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
  463. const coff_import_directory_table_entry *Dir;
  464. StringRef Name;
  465. if (DirRef.getImportTableEntry(Dir)) return;
  466. if (DirRef.getName(Name)) return;
  467. outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
  468. static_cast<uint32_t>(Dir->ImportLookupTableRVA),
  469. static_cast<uint32_t>(Dir->TimeDateStamp),
  470. static_cast<uint32_t>(Dir->ForwarderChain),
  471. static_cast<uint32_t>(Dir->NameRVA),
  472. static_cast<uint32_t>(Dir->ImportAddressTableRVA));
  473. outs() << " DLL Name: " << Name << "\n";
  474. outs() << " Hint/Ord Name\n";
  475. for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
  476. bool IsOrdinal;
  477. if (Entry.isOrdinal(IsOrdinal))
  478. return;
  479. if (IsOrdinal) {
  480. uint16_t Ordinal;
  481. if (Entry.getOrdinal(Ordinal))
  482. return;
  483. outs() << format(" % 6d\n", Ordinal);
  484. continue;
  485. }
  486. uint32_t HintNameRVA;
  487. if (Entry.getHintNameRVA(HintNameRVA))
  488. return;
  489. uint16_t Hint;
  490. StringRef Name;
  491. if (Obj->getHintName(HintNameRVA, Hint, Name))
  492. return;
  493. outs() << format(" % 6d ", Hint) << Name << "\n";
  494. }
  495. outs() << "\n";
  496. }
  497. }
  498. // Prints export tables. The export table is a table containing the list of
  499. // exported symbol from the DLL.
  500. static void printExportTable(const COFFObjectFile *Obj) {
  501. outs() << "Export Table:\n";
  502. export_directory_iterator I = Obj->export_directory_begin();
  503. export_directory_iterator E = Obj->export_directory_end();
  504. if (I == E)
  505. return;
  506. StringRef DllName;
  507. uint32_t OrdinalBase;
  508. if (I->getDllName(DllName))
  509. return;
  510. if (I->getOrdinalBase(OrdinalBase))
  511. return;
  512. outs() << " DLL name: " << DllName << "\n";
  513. outs() << " Ordinal base: " << OrdinalBase << "\n";
  514. outs() << " Ordinal RVA Name\n";
  515. for (; I != E; I = ++I) {
  516. uint32_t Ordinal;
  517. if (I->getOrdinal(Ordinal))
  518. return;
  519. uint32_t RVA;
  520. if (I->getExportRVA(RVA))
  521. return;
  522. bool IsForwarder;
  523. if (I->isForwarder(IsForwarder))
  524. return;
  525. if (IsForwarder) {
  526. // Export table entries can be used to re-export symbols that
  527. // this COFF file is imported from some DLLs. This is rare.
  528. // In most cases IsForwarder is false.
  529. outs() << format(" % 4d ", Ordinal);
  530. } else {
  531. outs() << format(" % 4d %# 8x", Ordinal, RVA);
  532. }
  533. StringRef Name;
  534. if (I->getSymbolName(Name))
  535. continue;
  536. if (!Name.empty())
  537. outs() << " " << Name;
  538. if (IsForwarder) {
  539. StringRef S;
  540. if (I->getForwardTo(S))
  541. return;
  542. outs() << " (forwarded to " << S << ")";
  543. }
  544. outs() << "\n";
  545. }
  546. }
  547. // Given the COFF object file, this function returns the relocations for .pdata
  548. // and the pointer to "runtime function" structs.
  549. static bool getPDataSection(const COFFObjectFile *Obj,
  550. std::vector<RelocationRef> &Rels,
  551. const RuntimeFunction *&RFStart, int &NumRFs) {
  552. for (const SectionRef &Section : Obj->sections()) {
  553. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  554. if (Name != ".pdata")
  555. continue;
  556. const coff_section *Pdata = Obj->getCOFFSection(Section);
  557. append_range(Rels, Section.relocations());
  558. // Sort relocations by address.
  559. llvm::sort(Rels, isRelocAddressLess);
  560. ArrayRef<uint8_t> Contents;
  561. if (Error E = Obj->getSectionContents(Pdata, Contents))
  562. reportError(std::move(E), Obj->getFileName());
  563. if (Contents.empty())
  564. continue;
  565. RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
  566. NumRFs = Contents.size() / sizeof(RuntimeFunction);
  567. return true;
  568. }
  569. return false;
  570. }
  571. Error objdump::getCOFFRelocationValueString(const COFFObjectFile *Obj,
  572. const RelocationRef &Rel,
  573. SmallVectorImpl<char> &Result) {
  574. symbol_iterator SymI = Rel.getSymbol();
  575. Expected<StringRef> SymNameOrErr = SymI->getName();
  576. if (!SymNameOrErr)
  577. return SymNameOrErr.takeError();
  578. StringRef SymName = *SymNameOrErr;
  579. Result.append(SymName.begin(), SymName.end());
  580. return Error::success();
  581. }
  582. static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
  583. // The casts to int are required in order to output the value as number.
  584. // Without the casts the value would be interpreted as char data (which
  585. // results in garbage output).
  586. outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
  587. outs() << " Flags: " << static_cast<int>(UI->getFlags());
  588. if (UI->getFlags()) {
  589. if (UI->getFlags() & UNW_ExceptionHandler)
  590. outs() << " UNW_ExceptionHandler";
  591. if (UI->getFlags() & UNW_TerminateHandler)
  592. outs() << " UNW_TerminateHandler";
  593. if (UI->getFlags() & UNW_ChainInfo)
  594. outs() << " UNW_ChainInfo";
  595. }
  596. outs() << "\n";
  597. outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
  598. outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
  599. // Maybe this should move to output of UOP_SetFPReg?
  600. if (UI->getFrameRegister()) {
  601. outs() << " Frame register: "
  602. << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
  603. outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
  604. } else {
  605. outs() << " No frame pointer used\n";
  606. }
  607. if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
  608. // FIXME: Output exception handler data
  609. } else if (UI->getFlags() & UNW_ChainInfo) {
  610. // FIXME: Output chained unwind info
  611. }
  612. if (UI->NumCodes)
  613. outs() << " Unwind Codes:\n";
  614. printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
  615. outs() << "\n";
  616. outs().flush();
  617. }
  618. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  619. /// pointing to an executable file.
  620. static void printRuntimeFunction(const COFFObjectFile *Obj,
  621. const RuntimeFunction &RF) {
  622. if (!RF.StartAddress)
  623. return;
  624. outs() << "Function Table:\n"
  625. << format(" Start Address: 0x%04x\n",
  626. static_cast<uint32_t>(RF.StartAddress))
  627. << format(" End Address: 0x%04x\n",
  628. static_cast<uint32_t>(RF.EndAddress))
  629. << format(" Unwind Info Address: 0x%04x\n",
  630. static_cast<uint32_t>(RF.UnwindInfoOffset));
  631. uintptr_t addr;
  632. if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
  633. return;
  634. printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
  635. }
  636. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  637. /// pointing to an object file. Unlike executable, fields in RuntimeFunction
  638. /// struct are filled with zeros, but instead there are relocations pointing to
  639. /// them so that the linker will fill targets' RVAs to the fields at link
  640. /// time. This function interprets the relocations to find the data to be used
  641. /// in the resulting executable.
  642. static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
  643. const RuntimeFunction &RF,
  644. uint64_t SectionOffset,
  645. const std::vector<RelocationRef> &Rels) {
  646. outs() << "Function Table:\n";
  647. outs() << " Start Address: ";
  648. printCOFFSymbolAddress(outs(), Rels,
  649. SectionOffset +
  650. /*offsetof(RuntimeFunction, StartAddress)*/ 0,
  651. RF.StartAddress);
  652. outs() << "\n";
  653. outs() << " End Address: ";
  654. printCOFFSymbolAddress(outs(), Rels,
  655. SectionOffset +
  656. /*offsetof(RuntimeFunction, EndAddress)*/ 4,
  657. RF.EndAddress);
  658. outs() << "\n";
  659. outs() << " Unwind Info Address: ";
  660. printCOFFSymbolAddress(outs(), Rels,
  661. SectionOffset +
  662. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  663. RF.UnwindInfoOffset);
  664. outs() << "\n";
  665. ArrayRef<uint8_t> XContents;
  666. uint64_t UnwindInfoOffset = 0;
  667. if (Error E = getSectionContents(
  668. Obj, Rels,
  669. SectionOffset +
  670. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  671. XContents, UnwindInfoOffset))
  672. reportError(std::move(E), Obj->getFileName());
  673. if (XContents.empty())
  674. return;
  675. UnwindInfoOffset += RF.UnwindInfoOffset;
  676. if (UnwindInfoOffset > XContents.size())
  677. return;
  678. auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
  679. UnwindInfoOffset);
  680. printWin64EHUnwindInfo(UI);
  681. }
  682. void objdump::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
  683. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
  684. WithColor::error(errs(), "llvm-objdump")
  685. << "unsupported image machine type "
  686. "(currently only AMD64 is supported).\n";
  687. return;
  688. }
  689. std::vector<RelocationRef> Rels;
  690. const RuntimeFunction *RFStart;
  691. int NumRFs;
  692. if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
  693. return;
  694. ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
  695. bool IsExecutable = Rels.empty();
  696. if (IsExecutable) {
  697. for (const RuntimeFunction &RF : RFs)
  698. printRuntimeFunction(Obj, RF);
  699. return;
  700. }
  701. for (const RuntimeFunction &RF : RFs) {
  702. uint64_t SectionOffset =
  703. std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
  704. printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
  705. }
  706. }
  707. void objdump::printCOFFFileHeader(const COFFObjectFile &Obj) {
  708. COFFDumper CD(Obj);
  709. const uint16_t Cha = Obj.getCharacteristics();
  710. outs() << "Characteristics 0x" << Twine::utohexstr(Cha) << '\n';
  711. #define FLAG(F, Name) \
  712. if (Cha & F) \
  713. outs() << '\t' << Name << '\n';
  714. FLAG(COFF::IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
  715. FLAG(COFF::IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
  716. FLAG(COFF::IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
  717. FLAG(COFF::IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
  718. FLAG(COFF::IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
  719. FLAG(COFF::IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
  720. FLAG(COFF::IMAGE_FILE_32BIT_MACHINE, "32 bit words");
  721. FLAG(COFF::IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
  722. FLAG(COFF::IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP,
  723. "copy to swap file if on removable media");
  724. FLAG(COFF::IMAGE_FILE_NET_RUN_FROM_SWAP,
  725. "copy to swap file if on network media");
  726. FLAG(COFF::IMAGE_FILE_SYSTEM, "system file");
  727. FLAG(COFF::IMAGE_FILE_DLL, "DLL");
  728. FLAG(COFF::IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
  729. FLAG(COFF::IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
  730. #undef FLAG
  731. // TODO Support PE_IMAGE_DEBUG_TYPE_REPRO.
  732. // Since ctime(3) returns a 26 character string of the form:
  733. // "Sun Sep 16 01:03:52 1973\n\0"
  734. // just print 24 characters.
  735. const time_t Timestamp = Obj.getTimeDateStamp();
  736. outs() << format("\nTime/Date %.24s\n", ctime(&Timestamp));
  737. if (const pe32_header *Hdr = Obj.getPE32Header())
  738. CD.printPEHeader<pe32_header>(*Hdr);
  739. else if (const pe32plus_header *Hdr = Obj.getPE32PlusHeader())
  740. CD.printPEHeader<pe32plus_header>(*Hdr);
  741. printTLSDirectory(&Obj);
  742. printLoadConfiguration(&Obj);
  743. printImportTables(&Obj);
  744. printExportTable(&Obj);
  745. }
  746. void objdump::printCOFFSymbolTable(const object::COFFImportFile *i) {
  747. unsigned Index = 0;
  748. bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
  749. for (const object::BasicSymbolRef &Sym : i->symbols()) {
  750. std::string Name;
  751. raw_string_ostream NS(Name);
  752. cantFail(Sym.printName(NS));
  753. NS.flush();
  754. outs() << "[" << format("%2d", Index) << "]"
  755. << "(sec " << format("%2d", 0) << ")"
  756. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  757. << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
  758. << "(scl " << format("%3x", 0) << ") "
  759. << "(nx " << 0 << ") "
  760. << "0x" << format("%08x", 0) << " " << Name << '\n';
  761. ++Index;
  762. }
  763. }
  764. void objdump::printCOFFSymbolTable(const COFFObjectFile *coff) {
  765. for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
  766. Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
  767. if (!Symbol)
  768. reportError(Symbol.takeError(), coff->getFileName());
  769. Expected<StringRef> NameOrErr = coff->getSymbolName(*Symbol);
  770. if (!NameOrErr)
  771. reportError(NameOrErr.takeError(), coff->getFileName());
  772. StringRef Name = *NameOrErr;
  773. outs() << "[" << format("%2d", SI) << "]"
  774. << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
  775. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  776. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
  777. << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
  778. << ") "
  779. << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
  780. << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
  781. << Name;
  782. if (Demangle && Name.startswith("?")) {
  783. int Status = -1;
  784. char *DemangledSymbol =
  785. microsoftDemangle(Name.data(), nullptr, nullptr, nullptr, &Status);
  786. if (Status == 0 && DemangledSymbol) {
  787. outs() << " (" << StringRef(DemangledSymbol) << ")";
  788. std::free(DemangledSymbol);
  789. } else {
  790. outs() << " (invalid mangled name)";
  791. }
  792. }
  793. outs() << "\n";
  794. for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
  795. if (Symbol->isSectionDefinition()) {
  796. const coff_aux_section_definition *asd;
  797. if (Error E =
  798. coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))
  799. reportError(std::move(E), coff->getFileName());
  800. int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
  801. outs() << "AUX "
  802. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  803. , unsigned(asd->Length)
  804. , unsigned(asd->NumberOfRelocations)
  805. , unsigned(asd->NumberOfLinenumbers)
  806. , unsigned(asd->CheckSum))
  807. << format("assoc %d comdat %d\n"
  808. , unsigned(AuxNumber)
  809. , unsigned(asd->Selection));
  810. } else if (Symbol->isFileRecord()) {
  811. const char *FileName;
  812. if (Error E = coff->getAuxSymbol<char>(SI + 1, FileName))
  813. reportError(std::move(E), coff->getFileName());
  814. StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
  815. coff->getSymbolTableEntrySize());
  816. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  817. SI = SI + Symbol->getNumberOfAuxSymbols();
  818. break;
  819. } else if (Symbol->isWeakExternal()) {
  820. const coff_aux_weak_external *awe;
  821. if (Error E = coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe))
  822. reportError(std::move(E), coff->getFileName());
  823. outs() << "AUX " << format("indx %d srch %d\n",
  824. static_cast<uint32_t>(awe->TagIndex),
  825. static_cast<uint32_t>(awe->Characteristics));
  826. } else {
  827. outs() << "AUX Unknown\n";
  828. }
  829. }
  830. }
  831. }