COFFDump.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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. /// https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64
  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, ArrayRef(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, ArrayRef(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 != std::size(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_Epilog: return "UOP_Epilog";
  180. case UOP_SpareCode: return "UOP_SpareCode";
  181. case UOP_SaveXMM128: return "UOP_SaveXMM128";
  182. case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
  183. case UOP_PushMachFrame: return "UOP_PushMachFrame";
  184. }
  185. }
  186. // Returns the name of a referenced register.
  187. static StringRef getUnwindRegisterName(uint8_t Reg) {
  188. switch(Reg) {
  189. default: llvm_unreachable("Invalid register");
  190. case 0: return "RAX";
  191. case 1: return "RCX";
  192. case 2: return "RDX";
  193. case 3: return "RBX";
  194. case 4: return "RSP";
  195. case 5: return "RBP";
  196. case 6: return "RSI";
  197. case 7: return "RDI";
  198. case 8: return "R8";
  199. case 9: return "R9";
  200. case 10: return "R10";
  201. case 11: return "R11";
  202. case 12: return "R12";
  203. case 13: return "R13";
  204. case 14: return "R14";
  205. case 15: return "R15";
  206. }
  207. }
  208. // Calculates the number of array slots required for the unwind code.
  209. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
  210. switch (UnwindCode.getUnwindOp()) {
  211. default: llvm_unreachable("Invalid unwind code");
  212. case UOP_PushNonVol:
  213. case UOP_AllocSmall:
  214. case UOP_SetFPReg:
  215. case UOP_PushMachFrame:
  216. return 1;
  217. case UOP_SaveNonVol:
  218. case UOP_SaveXMM128:
  219. case UOP_Epilog:
  220. return 2;
  221. case UOP_SaveNonVolBig:
  222. case UOP_SaveXMM128Big:
  223. case UOP_SpareCode:
  224. return 3;
  225. case UOP_AllocLarge:
  226. return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
  227. }
  228. }
  229. // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
  230. // the unwind codes array, this function requires that the correct number of
  231. // slots is provided.
  232. static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
  233. assert(UCs.size() >= getNumUsedSlots(UCs[0]));
  234. outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
  235. << getUnwindCodeTypeName(UCs[0].getUnwindOp());
  236. switch (UCs[0].getUnwindOp()) {
  237. case UOP_PushNonVol:
  238. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
  239. break;
  240. case UOP_AllocLarge:
  241. if (UCs[0].getOpInfo() == 0) {
  242. outs() << " " << UCs[1].FrameOffset;
  243. } else {
  244. outs() << " " << UCs[1].FrameOffset
  245. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
  246. }
  247. break;
  248. case UOP_AllocSmall:
  249. outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
  250. break;
  251. case UOP_SetFPReg:
  252. outs() << " ";
  253. break;
  254. case UOP_SaveNonVol:
  255. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  256. << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
  257. break;
  258. case UOP_SaveNonVolBig:
  259. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  260. << format(" [0x%08x]", UCs[1].FrameOffset
  261. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  262. break;
  263. case UOP_SaveXMM128:
  264. outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
  265. << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
  266. break;
  267. case UOP_SaveXMM128Big:
  268. outs() << " XMM" << UCs[0].getOpInfo()
  269. << format(" [0x%08x]", UCs[1].FrameOffset
  270. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  271. break;
  272. case UOP_PushMachFrame:
  273. outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
  274. << " error code";
  275. break;
  276. }
  277. outs() << "\n";
  278. }
  279. static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
  280. for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
  281. unsigned UsedSlots = getNumUsedSlots(*I);
  282. if (UsedSlots > UCs.size()) {
  283. outs() << "Unwind data corrupted: Encountered unwind op "
  284. << getUnwindCodeTypeName((*I).getUnwindOp())
  285. << " which requires " << UsedSlots
  286. << " slots, but only " << UCs.size()
  287. << " remaining in buffer";
  288. return ;
  289. }
  290. printUnwindCode(ArrayRef(I, E));
  291. I += UsedSlots;
  292. }
  293. }
  294. // Given a symbol sym this functions returns the address and section of it.
  295. static Error resolveSectionAndAddress(const COFFObjectFile *Obj,
  296. const SymbolRef &Sym,
  297. const coff_section *&ResolvedSection,
  298. uint64_t &ResolvedAddr) {
  299. Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
  300. if (!ResolvedAddrOrErr)
  301. return ResolvedAddrOrErr.takeError();
  302. ResolvedAddr = *ResolvedAddrOrErr;
  303. Expected<section_iterator> Iter = Sym.getSection();
  304. if (!Iter)
  305. return Iter.takeError();
  306. ResolvedSection = Obj->getCOFFSection(**Iter);
  307. return Error::success();
  308. }
  309. // Given a vector of relocations for a section and an offset into this section
  310. // the function returns the symbol used for the relocation at the offset.
  311. static Error resolveSymbol(const std::vector<RelocationRef> &Rels,
  312. uint64_t Offset, SymbolRef &Sym) {
  313. for (auto &R : Rels) {
  314. uint64_t Ofs = R.getOffset();
  315. if (Ofs == Offset) {
  316. Sym = *R.getSymbol();
  317. return Error::success();
  318. }
  319. }
  320. return make_error<BinaryError>();
  321. }
  322. // Given a vector of relocations for a section and an offset into this section
  323. // the function resolves the symbol used for the relocation at the offset and
  324. // returns the section content and the address inside the content pointed to
  325. // by the symbol.
  326. static Error
  327. getSectionContents(const COFFObjectFile *Obj,
  328. const std::vector<RelocationRef> &Rels, uint64_t Offset,
  329. ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
  330. SymbolRef Sym;
  331. if (Error E = resolveSymbol(Rels, Offset, Sym))
  332. return E;
  333. const coff_section *Section;
  334. if (Error E = resolveSectionAndAddress(Obj, Sym, Section, Addr))
  335. return E;
  336. return Obj->getSectionContents(Section, Contents);
  337. }
  338. // Given a vector of relocations for a section and an offset into this section
  339. // the function returns the name of the symbol used for the relocation at the
  340. // offset.
  341. static Error resolveSymbolName(const std::vector<RelocationRef> &Rels,
  342. uint64_t Offset, StringRef &Name) {
  343. SymbolRef Sym;
  344. if (Error EC = resolveSymbol(Rels, Offset, Sym))
  345. return EC;
  346. Expected<StringRef> NameOrErr = Sym.getName();
  347. if (!NameOrErr)
  348. return NameOrErr.takeError();
  349. Name = *NameOrErr;
  350. return Error::success();
  351. }
  352. static void printCOFFSymbolAddress(raw_ostream &Out,
  353. const std::vector<RelocationRef> &Rels,
  354. uint64_t Offset, uint32_t Disp) {
  355. StringRef Sym;
  356. if (!resolveSymbolName(Rels, Offset, Sym)) {
  357. Out << Sym;
  358. if (Disp > 0)
  359. Out << format(" + 0x%04x", Disp);
  360. } else {
  361. Out << format("0x%04x", Disp);
  362. }
  363. }
  364. static void
  365. printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
  366. if (Count == 0)
  367. return;
  368. uintptr_t IntPtr = 0;
  369. if (Error E = Obj->getVaPtr(TableVA, IntPtr))
  370. reportError(std::move(E), Obj->getFileName());
  371. const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
  372. outs() << "SEH Table:";
  373. for (int I = 0; I < Count; ++I)
  374. outs() << format(" 0x%x", P[I] + Obj->getPE32Header()->ImageBase);
  375. outs() << "\n\n";
  376. }
  377. template <typename T>
  378. static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
  379. size_t FormatWidth = sizeof(T) * 2;
  380. outs() << "TLS directory:"
  381. << "\n StartAddressOfRawData: "
  382. << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
  383. << "\n EndAddressOfRawData: "
  384. << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
  385. << "\n AddressOfIndex: "
  386. << format_hex(TLSDir->AddressOfIndex, FormatWidth)
  387. << "\n AddressOfCallBacks: "
  388. << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
  389. << "\n SizeOfZeroFill: "
  390. << TLSDir->SizeOfZeroFill
  391. << "\n Characteristics: "
  392. << TLSDir->Characteristics
  393. << "\n Alignment: "
  394. << TLSDir->getAlignment()
  395. << "\n\n";
  396. }
  397. static void printTLSDirectory(const COFFObjectFile *Obj) {
  398. const pe32_header *PE32Header = Obj->getPE32Header();
  399. const pe32plus_header *PE32PlusHeader = Obj->getPE32PlusHeader();
  400. // Skip if it's not executable.
  401. if (!PE32Header && !PE32PlusHeader)
  402. return;
  403. if (PE32Header) {
  404. if (auto *TLSDir = Obj->getTLSDirectory32())
  405. printTLSDirectoryT(TLSDir);
  406. } else {
  407. if (auto *TLSDir = Obj->getTLSDirectory64())
  408. printTLSDirectoryT(TLSDir);
  409. }
  410. outs() << "\n";
  411. }
  412. static void printLoadConfiguration(const COFFObjectFile *Obj) {
  413. // Skip if it's not executable.
  414. if (!Obj->getPE32Header())
  415. return;
  416. // Currently only x86 is supported
  417. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
  418. return;
  419. auto *LoadConf = Obj->getLoadConfig32();
  420. if (!LoadConf)
  421. return;
  422. outs() << "Load configuration:"
  423. << "\n Timestamp: " << LoadConf->TimeDateStamp
  424. << "\n Major Version: " << LoadConf->MajorVersion
  425. << "\n Minor Version: " << LoadConf->MinorVersion
  426. << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
  427. << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
  428. << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
  429. << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
  430. << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
  431. << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
  432. << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
  433. << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
  434. << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
  435. << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
  436. << "\n CSD Version: " << LoadConf->CSDVersion
  437. << "\n Security Cookie: " << LoadConf->SecurityCookie
  438. << "\n SEH Table: " << LoadConf->SEHandlerTable
  439. << "\n SEH Count: " << LoadConf->SEHandlerCount
  440. << "\n\n";
  441. printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
  442. outs() << "\n";
  443. }
  444. // Prints import tables. The import table is a table containing the list of
  445. // DLL name and symbol names which will be linked by the loader.
  446. static void printImportTables(const COFFObjectFile *Obj) {
  447. import_directory_iterator I = Obj->import_directory_begin();
  448. import_directory_iterator E = Obj->import_directory_end();
  449. if (I == E)
  450. return;
  451. outs() << "The Import Tables:\n";
  452. for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
  453. const coff_import_directory_table_entry *Dir;
  454. StringRef Name;
  455. if (DirRef.getImportTableEntry(Dir)) return;
  456. if (DirRef.getName(Name)) return;
  457. outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
  458. static_cast<uint32_t>(Dir->ImportLookupTableRVA),
  459. static_cast<uint32_t>(Dir->TimeDateStamp),
  460. static_cast<uint32_t>(Dir->ForwarderChain),
  461. static_cast<uint32_t>(Dir->NameRVA),
  462. static_cast<uint32_t>(Dir->ImportAddressTableRVA));
  463. outs() << " DLL Name: " << Name << "\n";
  464. outs() << " Hint/Ord Name\n";
  465. for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
  466. bool IsOrdinal;
  467. if (Entry.isOrdinal(IsOrdinal))
  468. return;
  469. if (IsOrdinal) {
  470. uint16_t Ordinal;
  471. if (Entry.getOrdinal(Ordinal))
  472. return;
  473. outs() << format(" % 6d\n", Ordinal);
  474. continue;
  475. }
  476. uint32_t HintNameRVA;
  477. if (Entry.getHintNameRVA(HintNameRVA))
  478. return;
  479. uint16_t Hint;
  480. StringRef Name;
  481. if (Obj->getHintName(HintNameRVA, Hint, Name))
  482. return;
  483. outs() << format(" % 6d ", Hint) << Name << "\n";
  484. }
  485. outs() << "\n";
  486. }
  487. }
  488. // Prints export tables. The export table is a table containing the list of
  489. // exported symbol from the DLL.
  490. static void printExportTable(const COFFObjectFile *Obj) {
  491. export_directory_iterator I = Obj->export_directory_begin();
  492. export_directory_iterator E = Obj->export_directory_end();
  493. if (I == E)
  494. return;
  495. outs() << "Export Table:\n";
  496. StringRef DllName;
  497. uint32_t OrdinalBase;
  498. if (I->getDllName(DllName))
  499. return;
  500. if (I->getOrdinalBase(OrdinalBase))
  501. return;
  502. outs() << " DLL name: " << DllName << "\n";
  503. outs() << " Ordinal base: " << OrdinalBase << "\n";
  504. outs() << " Ordinal RVA Name\n";
  505. for (; I != E; I = ++I) {
  506. uint32_t Ordinal;
  507. if (I->getOrdinal(Ordinal))
  508. return;
  509. uint32_t RVA;
  510. if (I->getExportRVA(RVA))
  511. return;
  512. bool IsForwarder;
  513. if (I->isForwarder(IsForwarder))
  514. return;
  515. if (IsForwarder) {
  516. // Export table entries can be used to re-export symbols that
  517. // this COFF file is imported from some DLLs. This is rare.
  518. // In most cases IsForwarder is false.
  519. outs() << format(" % 4d ", Ordinal);
  520. } else {
  521. outs() << format(" % 4d %# 8x", Ordinal, RVA);
  522. }
  523. StringRef Name;
  524. if (I->getSymbolName(Name))
  525. continue;
  526. if (!Name.empty())
  527. outs() << " " << Name;
  528. if (IsForwarder) {
  529. StringRef S;
  530. if (I->getForwardTo(S))
  531. return;
  532. outs() << " (forwarded to " << S << ")";
  533. }
  534. outs() << "\n";
  535. }
  536. }
  537. // Given the COFF object file, this function returns the relocations for .pdata
  538. // and the pointer to "runtime function" structs.
  539. static bool getPDataSection(const COFFObjectFile *Obj,
  540. std::vector<RelocationRef> &Rels,
  541. const RuntimeFunction *&RFStart, int &NumRFs) {
  542. for (const SectionRef &Section : Obj->sections()) {
  543. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  544. if (Name != ".pdata")
  545. continue;
  546. const coff_section *Pdata = Obj->getCOFFSection(Section);
  547. append_range(Rels, Section.relocations());
  548. // Sort relocations by address.
  549. llvm::sort(Rels, isRelocAddressLess);
  550. ArrayRef<uint8_t> Contents;
  551. if (Error E = Obj->getSectionContents(Pdata, Contents))
  552. reportError(std::move(E), Obj->getFileName());
  553. if (Contents.empty())
  554. continue;
  555. RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
  556. NumRFs = Contents.size() / sizeof(RuntimeFunction);
  557. return true;
  558. }
  559. return false;
  560. }
  561. Error objdump::getCOFFRelocationValueString(const COFFObjectFile *Obj,
  562. const RelocationRef &Rel,
  563. SmallVectorImpl<char> &Result) {
  564. symbol_iterator SymI = Rel.getSymbol();
  565. Expected<StringRef> SymNameOrErr = SymI->getName();
  566. if (!SymNameOrErr)
  567. return SymNameOrErr.takeError();
  568. StringRef SymName = *SymNameOrErr;
  569. Result.append(SymName.begin(), SymName.end());
  570. return Error::success();
  571. }
  572. static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
  573. // The casts to int are required in order to output the value as number.
  574. // Without the casts the value would be interpreted as char data (which
  575. // results in garbage output).
  576. outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
  577. outs() << " Flags: " << static_cast<int>(UI->getFlags());
  578. if (UI->getFlags()) {
  579. if (UI->getFlags() & UNW_ExceptionHandler)
  580. outs() << " UNW_ExceptionHandler";
  581. if (UI->getFlags() & UNW_TerminateHandler)
  582. outs() << " UNW_TerminateHandler";
  583. if (UI->getFlags() & UNW_ChainInfo)
  584. outs() << " UNW_ChainInfo";
  585. }
  586. outs() << "\n";
  587. outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
  588. outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
  589. // Maybe this should move to output of UOP_SetFPReg?
  590. if (UI->getFrameRegister()) {
  591. outs() << " Frame register: "
  592. << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
  593. outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
  594. } else {
  595. outs() << " No frame pointer used\n";
  596. }
  597. if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
  598. // FIXME: Output exception handler data
  599. } else if (UI->getFlags() & UNW_ChainInfo) {
  600. // FIXME: Output chained unwind info
  601. }
  602. if (UI->NumCodes)
  603. outs() << " Unwind Codes:\n";
  604. printAllUnwindCodes(ArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
  605. outs() << "\n";
  606. outs().flush();
  607. }
  608. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  609. /// pointing to an executable file.
  610. static void printRuntimeFunction(const COFFObjectFile *Obj,
  611. const RuntimeFunction &RF) {
  612. if (!RF.StartAddress)
  613. return;
  614. outs() << "Function Table:\n"
  615. << format(" Start Address: 0x%04x\n",
  616. static_cast<uint32_t>(RF.StartAddress))
  617. << format(" End Address: 0x%04x\n",
  618. static_cast<uint32_t>(RF.EndAddress))
  619. << format(" Unwind Info Address: 0x%04x\n",
  620. static_cast<uint32_t>(RF.UnwindInfoOffset));
  621. uintptr_t addr;
  622. if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
  623. return;
  624. printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
  625. }
  626. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  627. /// pointing to an object file. Unlike executable, fields in RuntimeFunction
  628. /// struct are filled with zeros, but instead there are relocations pointing to
  629. /// them so that the linker will fill targets' RVAs to the fields at link
  630. /// time. This function interprets the relocations to find the data to be used
  631. /// in the resulting executable.
  632. static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
  633. const RuntimeFunction &RF,
  634. uint64_t SectionOffset,
  635. const std::vector<RelocationRef> &Rels) {
  636. outs() << "Function Table:\n";
  637. outs() << " Start Address: ";
  638. printCOFFSymbolAddress(outs(), Rels,
  639. SectionOffset +
  640. /*offsetof(RuntimeFunction, StartAddress)*/ 0,
  641. RF.StartAddress);
  642. outs() << "\n";
  643. outs() << " End Address: ";
  644. printCOFFSymbolAddress(outs(), Rels,
  645. SectionOffset +
  646. /*offsetof(RuntimeFunction, EndAddress)*/ 4,
  647. RF.EndAddress);
  648. outs() << "\n";
  649. outs() << " Unwind Info Address: ";
  650. printCOFFSymbolAddress(outs(), Rels,
  651. SectionOffset +
  652. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  653. RF.UnwindInfoOffset);
  654. outs() << "\n";
  655. ArrayRef<uint8_t> XContents;
  656. uint64_t UnwindInfoOffset = 0;
  657. if (Error E = getSectionContents(
  658. Obj, Rels,
  659. SectionOffset +
  660. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  661. XContents, UnwindInfoOffset))
  662. reportError(std::move(E), Obj->getFileName());
  663. if (XContents.empty())
  664. return;
  665. UnwindInfoOffset += RF.UnwindInfoOffset;
  666. if (UnwindInfoOffset > XContents.size())
  667. return;
  668. auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
  669. UnwindInfoOffset);
  670. printWin64EHUnwindInfo(UI);
  671. }
  672. void objdump::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
  673. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
  674. WithColor::error(errs(), "llvm-objdump")
  675. << "unsupported image machine type "
  676. "(currently only AMD64 is supported).\n";
  677. return;
  678. }
  679. std::vector<RelocationRef> Rels;
  680. const RuntimeFunction *RFStart;
  681. int NumRFs;
  682. if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
  683. return;
  684. ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
  685. bool IsExecutable = Rels.empty();
  686. if (IsExecutable) {
  687. for (const RuntimeFunction &RF : RFs)
  688. printRuntimeFunction(Obj, RF);
  689. return;
  690. }
  691. for (const RuntimeFunction &RF : RFs) {
  692. uint64_t SectionOffset =
  693. std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
  694. printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
  695. }
  696. }
  697. void objdump::printCOFFFileHeader(const COFFObjectFile &Obj) {
  698. COFFDumper CD(Obj);
  699. const uint16_t Cha = Obj.getCharacteristics();
  700. outs() << "Characteristics 0x" << Twine::utohexstr(Cha) << '\n';
  701. #define FLAG(F, Name) \
  702. if (Cha & F) \
  703. outs() << '\t' << Name << '\n';
  704. FLAG(COFF::IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
  705. FLAG(COFF::IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
  706. FLAG(COFF::IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
  707. FLAG(COFF::IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
  708. FLAG(COFF::IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
  709. FLAG(COFF::IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
  710. FLAG(COFF::IMAGE_FILE_32BIT_MACHINE, "32 bit words");
  711. FLAG(COFF::IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
  712. FLAG(COFF::IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP,
  713. "copy to swap file if on removable media");
  714. FLAG(COFF::IMAGE_FILE_NET_RUN_FROM_SWAP,
  715. "copy to swap file if on network media");
  716. FLAG(COFF::IMAGE_FILE_SYSTEM, "system file");
  717. FLAG(COFF::IMAGE_FILE_DLL, "DLL");
  718. FLAG(COFF::IMAGE_FILE_UP_SYSTEM_ONLY, "run only on uniprocessor machine");
  719. FLAG(COFF::IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
  720. #undef FLAG
  721. // TODO Support PE_IMAGE_DEBUG_TYPE_REPRO.
  722. // Since ctime(3) returns a 26 character string of the form:
  723. // "Sun Sep 16 01:03:52 1973\n\0"
  724. // just print 24 characters.
  725. const time_t Timestamp = Obj.getTimeDateStamp();
  726. outs() << format("\nTime/Date %.24s\n", ctime(&Timestamp));
  727. if (const pe32_header *Hdr = Obj.getPE32Header())
  728. CD.printPEHeader<pe32_header>(*Hdr);
  729. else if (const pe32plus_header *Hdr = Obj.getPE32PlusHeader())
  730. CD.printPEHeader<pe32plus_header>(*Hdr);
  731. printTLSDirectory(&Obj);
  732. printLoadConfiguration(&Obj);
  733. printImportTables(&Obj);
  734. printExportTable(&Obj);
  735. }
  736. void objdump::printCOFFSymbolTable(const object::COFFImportFile &i) {
  737. unsigned Index = 0;
  738. bool IsCode = i.getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
  739. for (const object::BasicSymbolRef &Sym : i.symbols()) {
  740. std::string Name;
  741. raw_string_ostream NS(Name);
  742. cantFail(Sym.printName(NS));
  743. NS.flush();
  744. outs() << "[" << format("%2d", Index) << "]"
  745. << "(sec " << format("%2d", 0) << ")"
  746. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  747. << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
  748. << "(scl " << format("%3x", 0) << ") "
  749. << "(nx " << 0 << ") "
  750. << "0x" << format("%08x", 0) << " " << Name << '\n';
  751. ++Index;
  752. }
  753. }
  754. void objdump::printCOFFSymbolTable(const COFFObjectFile &coff) {
  755. for (unsigned SI = 0, SE = coff.getNumberOfSymbols(); SI != SE; ++SI) {
  756. Expected<COFFSymbolRef> Symbol = coff.getSymbol(SI);
  757. if (!Symbol)
  758. reportError(Symbol.takeError(), coff.getFileName());
  759. Expected<StringRef> NameOrErr = coff.getSymbolName(*Symbol);
  760. if (!NameOrErr)
  761. reportError(NameOrErr.takeError(), coff.getFileName());
  762. StringRef Name = *NameOrErr;
  763. outs() << "[" << format("%2d", SI) << "]"
  764. << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
  765. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  766. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
  767. << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
  768. << ") "
  769. << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
  770. << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
  771. << Name;
  772. if (Demangle && Name.startswith("?")) {
  773. int Status = -1;
  774. char *DemangledSymbol =
  775. microsoftDemangle(Name.data(), nullptr, nullptr, nullptr, &Status);
  776. if (Status == 0 && DemangledSymbol) {
  777. outs() << " (" << StringRef(DemangledSymbol) << ")";
  778. std::free(DemangledSymbol);
  779. } else {
  780. outs() << " (invalid mangled name)";
  781. }
  782. }
  783. outs() << "\n";
  784. for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
  785. if (Symbol->isSectionDefinition()) {
  786. const coff_aux_section_definition *asd;
  787. if (Error E =
  788. coff.getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))
  789. reportError(std::move(E), coff.getFileName());
  790. int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
  791. outs() << "AUX "
  792. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  793. , unsigned(asd->Length)
  794. , unsigned(asd->NumberOfRelocations)
  795. , unsigned(asd->NumberOfLinenumbers)
  796. , unsigned(asd->CheckSum))
  797. << format("assoc %d comdat %d\n"
  798. , unsigned(AuxNumber)
  799. , unsigned(asd->Selection));
  800. } else if (Symbol->isFileRecord()) {
  801. const char *FileName;
  802. if (Error E = coff.getAuxSymbol<char>(SI + 1, FileName))
  803. reportError(std::move(E), coff.getFileName());
  804. StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
  805. coff.getSymbolTableEntrySize());
  806. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  807. SI = SI + Symbol->getNumberOfAuxSymbols();
  808. break;
  809. } else if (Symbol->isWeakExternal()) {
  810. const coff_aux_weak_external *awe;
  811. if (Error E = coff.getAuxSymbol<coff_aux_weak_external>(SI + 1, awe))
  812. reportError(std::move(E), coff.getFileName());
  813. outs() << "AUX " << format("indx %d srch %d\n",
  814. static_cast<uint32_t>(awe->TagIndex),
  815. static_cast<uint32_t>(awe->Characteristics));
  816. } else {
  817. outs() << "AUX Unknown\n";
  818. }
  819. }
  820. }
  821. }