COFFDump.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. // Returns the name of the unwind code.
  31. static StringRef getUnwindCodeTypeName(uint8_t Code) {
  32. switch(Code) {
  33. default: llvm_unreachable("Invalid unwind code");
  34. case UOP_PushNonVol: return "UOP_PushNonVol";
  35. case UOP_AllocLarge: return "UOP_AllocLarge";
  36. case UOP_AllocSmall: return "UOP_AllocSmall";
  37. case UOP_SetFPReg: return "UOP_SetFPReg";
  38. case UOP_SaveNonVol: return "UOP_SaveNonVol";
  39. case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
  40. case UOP_SaveXMM128: return "UOP_SaveXMM128";
  41. case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
  42. case UOP_PushMachFrame: return "UOP_PushMachFrame";
  43. }
  44. }
  45. // Returns the name of a referenced register.
  46. static StringRef getUnwindRegisterName(uint8_t Reg) {
  47. switch(Reg) {
  48. default: llvm_unreachable("Invalid register");
  49. case 0: return "RAX";
  50. case 1: return "RCX";
  51. case 2: return "RDX";
  52. case 3: return "RBX";
  53. case 4: return "RSP";
  54. case 5: return "RBP";
  55. case 6: return "RSI";
  56. case 7: return "RDI";
  57. case 8: return "R8";
  58. case 9: return "R9";
  59. case 10: return "R10";
  60. case 11: return "R11";
  61. case 12: return "R12";
  62. case 13: return "R13";
  63. case 14: return "R14";
  64. case 15: return "R15";
  65. }
  66. }
  67. // Calculates the number of array slots required for the unwind code.
  68. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
  69. switch (UnwindCode.getUnwindOp()) {
  70. default: llvm_unreachable("Invalid unwind code");
  71. case UOP_PushNonVol:
  72. case UOP_AllocSmall:
  73. case UOP_SetFPReg:
  74. case UOP_PushMachFrame:
  75. return 1;
  76. case UOP_SaveNonVol:
  77. case UOP_SaveXMM128:
  78. return 2;
  79. case UOP_SaveNonVolBig:
  80. case UOP_SaveXMM128Big:
  81. return 3;
  82. case UOP_AllocLarge:
  83. return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
  84. }
  85. }
  86. // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
  87. // the unwind codes array, this function requires that the correct number of
  88. // slots is provided.
  89. static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
  90. assert(UCs.size() >= getNumUsedSlots(UCs[0]));
  91. outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
  92. << getUnwindCodeTypeName(UCs[0].getUnwindOp());
  93. switch (UCs[0].getUnwindOp()) {
  94. case UOP_PushNonVol:
  95. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
  96. break;
  97. case UOP_AllocLarge:
  98. if (UCs[0].getOpInfo() == 0) {
  99. outs() << " " << UCs[1].FrameOffset;
  100. } else {
  101. outs() << " " << UCs[1].FrameOffset
  102. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
  103. }
  104. break;
  105. case UOP_AllocSmall:
  106. outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
  107. break;
  108. case UOP_SetFPReg:
  109. outs() << " ";
  110. break;
  111. case UOP_SaveNonVol:
  112. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  113. << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
  114. break;
  115. case UOP_SaveNonVolBig:
  116. outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
  117. << format(" [0x%08x]", UCs[1].FrameOffset
  118. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  119. break;
  120. case UOP_SaveXMM128:
  121. outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
  122. << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
  123. break;
  124. case UOP_SaveXMM128Big:
  125. outs() << " XMM" << UCs[0].getOpInfo()
  126. << format(" [0x%08x]", UCs[1].FrameOffset
  127. + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
  128. break;
  129. case UOP_PushMachFrame:
  130. outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
  131. << " error code";
  132. break;
  133. }
  134. outs() << "\n";
  135. }
  136. static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
  137. for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
  138. unsigned UsedSlots = getNumUsedSlots(*I);
  139. if (UsedSlots > UCs.size()) {
  140. outs() << "Unwind data corrupted: Encountered unwind op "
  141. << getUnwindCodeTypeName((*I).getUnwindOp())
  142. << " which requires " << UsedSlots
  143. << " slots, but only " << UCs.size()
  144. << " remaining in buffer";
  145. return ;
  146. }
  147. printUnwindCode(makeArrayRef(I, E));
  148. I += UsedSlots;
  149. }
  150. }
  151. // Given a symbol sym this functions returns the address and section of it.
  152. static Error resolveSectionAndAddress(const COFFObjectFile *Obj,
  153. const SymbolRef &Sym,
  154. const coff_section *&ResolvedSection,
  155. uint64_t &ResolvedAddr) {
  156. Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
  157. if (!ResolvedAddrOrErr)
  158. return ResolvedAddrOrErr.takeError();
  159. ResolvedAddr = *ResolvedAddrOrErr;
  160. Expected<section_iterator> Iter = Sym.getSection();
  161. if (!Iter)
  162. return Iter.takeError();
  163. ResolvedSection = Obj->getCOFFSection(**Iter);
  164. return Error::success();
  165. }
  166. // Given a vector of relocations for a section and an offset into this section
  167. // the function returns the symbol used for the relocation at the offset.
  168. static Error resolveSymbol(const std::vector<RelocationRef> &Rels,
  169. uint64_t Offset, SymbolRef &Sym) {
  170. for (auto &R : Rels) {
  171. uint64_t Ofs = R.getOffset();
  172. if (Ofs == Offset) {
  173. Sym = *R.getSymbol();
  174. return Error::success();
  175. }
  176. }
  177. return make_error<BinaryError>();
  178. }
  179. // Given a vector of relocations for a section and an offset into this section
  180. // the function resolves the symbol used for the relocation at the offset and
  181. // returns the section content and the address inside the content pointed to
  182. // by the symbol.
  183. static Error
  184. getSectionContents(const COFFObjectFile *Obj,
  185. const std::vector<RelocationRef> &Rels, uint64_t Offset,
  186. ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
  187. SymbolRef Sym;
  188. if (Error E = resolveSymbol(Rels, Offset, Sym))
  189. return E;
  190. const coff_section *Section;
  191. if (Error E = resolveSectionAndAddress(Obj, Sym, Section, Addr))
  192. return E;
  193. return Obj->getSectionContents(Section, Contents);
  194. }
  195. // Given a vector of relocations for a section and an offset into this section
  196. // the function returns the name of the symbol used for the relocation at the
  197. // offset.
  198. static Error resolveSymbolName(const std::vector<RelocationRef> &Rels,
  199. uint64_t Offset, StringRef &Name) {
  200. SymbolRef Sym;
  201. if (Error EC = resolveSymbol(Rels, Offset, Sym))
  202. return EC;
  203. Expected<StringRef> NameOrErr = Sym.getName();
  204. if (!NameOrErr)
  205. return NameOrErr.takeError();
  206. Name = *NameOrErr;
  207. return Error::success();
  208. }
  209. static void printCOFFSymbolAddress(raw_ostream &Out,
  210. const std::vector<RelocationRef> &Rels,
  211. uint64_t Offset, uint32_t Disp) {
  212. StringRef Sym;
  213. if (!resolveSymbolName(Rels, Offset, Sym)) {
  214. Out << Sym;
  215. if (Disp > 0)
  216. Out << format(" + 0x%04x", Disp);
  217. } else {
  218. Out << format("0x%04x", Disp);
  219. }
  220. }
  221. static void
  222. printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
  223. if (Count == 0)
  224. return;
  225. uintptr_t IntPtr = 0;
  226. if (Error E = Obj->getVaPtr(TableVA, IntPtr))
  227. reportError(std::move(E), Obj->getFileName());
  228. const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
  229. outs() << "SEH Table:";
  230. for (int I = 0; I < Count; ++I)
  231. outs() << format(" 0x%x", P[I] + Obj->getPE32Header()->ImageBase);
  232. outs() << "\n\n";
  233. }
  234. template <typename T>
  235. static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
  236. size_t FormatWidth = sizeof(T) * 2;
  237. outs() << "TLS directory:"
  238. << "\n StartAddressOfRawData: "
  239. << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
  240. << "\n EndAddressOfRawData: "
  241. << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
  242. << "\n AddressOfIndex: "
  243. << format_hex(TLSDir->AddressOfIndex, FormatWidth)
  244. << "\n AddressOfCallBacks: "
  245. << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
  246. << "\n SizeOfZeroFill: "
  247. << TLSDir->SizeOfZeroFill
  248. << "\n Characteristics: "
  249. << TLSDir->Characteristics
  250. << "\n Alignment: "
  251. << TLSDir->getAlignment()
  252. << "\n\n";
  253. }
  254. static void printTLSDirectory(const COFFObjectFile *Obj) {
  255. const pe32_header *PE32Header = Obj->getPE32Header();
  256. const pe32plus_header *PE32PlusHeader = Obj->getPE32PlusHeader();
  257. // Skip if it's not executable.
  258. if (!PE32Header && !PE32PlusHeader)
  259. return;
  260. const data_directory *DataDir = Obj->getDataDirectory(COFF::TLS_TABLE);
  261. if (!DataDir)
  262. reportError("missing data dir for TLS table", Obj->getFileName());
  263. if (DataDir->RelativeVirtualAddress == 0)
  264. return;
  265. uintptr_t IntPtr = 0;
  266. if (Error E =
  267. Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))
  268. reportError(std::move(E), Obj->getFileName());
  269. if (PE32Header) {
  270. auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
  271. printTLSDirectoryT(TLSDir);
  272. } else {
  273. auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
  274. printTLSDirectoryT(TLSDir);
  275. }
  276. outs() << "\n";
  277. }
  278. static void printLoadConfiguration(const COFFObjectFile *Obj) {
  279. // Skip if it's not executable.
  280. if (!Obj->getPE32Header())
  281. return;
  282. // Currently only x86 is supported
  283. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
  284. return;
  285. const data_directory *DataDir = Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE);
  286. if (!DataDir)
  287. reportError("no load config data dir", Obj->getFileName());
  288. uintptr_t IntPtr = 0;
  289. if (DataDir->RelativeVirtualAddress == 0)
  290. return;
  291. if (Error E =
  292. Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))
  293. reportError(std::move(E), Obj->getFileName());
  294. auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
  295. outs() << "Load configuration:"
  296. << "\n Timestamp: " << LoadConf->TimeDateStamp
  297. << "\n Major Version: " << LoadConf->MajorVersion
  298. << "\n Minor Version: " << LoadConf->MinorVersion
  299. << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
  300. << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
  301. << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
  302. << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
  303. << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
  304. << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
  305. << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
  306. << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
  307. << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
  308. << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
  309. << "\n CSD Version: " << LoadConf->CSDVersion
  310. << "\n Security Cookie: " << LoadConf->SecurityCookie
  311. << "\n SEH Table: " << LoadConf->SEHandlerTable
  312. << "\n SEH Count: " << LoadConf->SEHandlerCount
  313. << "\n\n";
  314. printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
  315. outs() << "\n";
  316. }
  317. // Prints import tables. The import table is a table containing the list of
  318. // DLL name and symbol names which will be linked by the loader.
  319. static void printImportTables(const COFFObjectFile *Obj) {
  320. import_directory_iterator I = Obj->import_directory_begin();
  321. import_directory_iterator E = Obj->import_directory_end();
  322. if (I == E)
  323. return;
  324. outs() << "The Import Tables:\n";
  325. for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
  326. const coff_import_directory_table_entry *Dir;
  327. StringRef Name;
  328. if (DirRef.getImportTableEntry(Dir)) return;
  329. if (DirRef.getName(Name)) return;
  330. outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
  331. static_cast<uint32_t>(Dir->ImportLookupTableRVA),
  332. static_cast<uint32_t>(Dir->TimeDateStamp),
  333. static_cast<uint32_t>(Dir->ForwarderChain),
  334. static_cast<uint32_t>(Dir->NameRVA),
  335. static_cast<uint32_t>(Dir->ImportAddressTableRVA));
  336. outs() << " DLL Name: " << Name << "\n";
  337. outs() << " Hint/Ord Name\n";
  338. for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
  339. bool IsOrdinal;
  340. if (Entry.isOrdinal(IsOrdinal))
  341. return;
  342. if (IsOrdinal) {
  343. uint16_t Ordinal;
  344. if (Entry.getOrdinal(Ordinal))
  345. return;
  346. outs() << format(" % 6d\n", Ordinal);
  347. continue;
  348. }
  349. uint32_t HintNameRVA;
  350. if (Entry.getHintNameRVA(HintNameRVA))
  351. return;
  352. uint16_t Hint;
  353. StringRef Name;
  354. if (Obj->getHintName(HintNameRVA, Hint, Name))
  355. return;
  356. outs() << format(" % 6d ", Hint) << Name << "\n";
  357. }
  358. outs() << "\n";
  359. }
  360. }
  361. // Prints export tables. The export table is a table containing the list of
  362. // exported symbol from the DLL.
  363. static void printExportTable(const COFFObjectFile *Obj) {
  364. outs() << "Export Table:\n";
  365. export_directory_iterator I = Obj->export_directory_begin();
  366. export_directory_iterator E = Obj->export_directory_end();
  367. if (I == E)
  368. return;
  369. StringRef DllName;
  370. uint32_t OrdinalBase;
  371. if (I->getDllName(DllName))
  372. return;
  373. if (I->getOrdinalBase(OrdinalBase))
  374. return;
  375. outs() << " DLL name: " << DllName << "\n";
  376. outs() << " Ordinal base: " << OrdinalBase << "\n";
  377. outs() << " Ordinal RVA Name\n";
  378. for (; I != E; I = ++I) {
  379. uint32_t Ordinal;
  380. if (I->getOrdinal(Ordinal))
  381. return;
  382. uint32_t RVA;
  383. if (I->getExportRVA(RVA))
  384. return;
  385. bool IsForwarder;
  386. if (I->isForwarder(IsForwarder))
  387. return;
  388. if (IsForwarder) {
  389. // Export table entries can be used to re-export symbols that
  390. // this COFF file is imported from some DLLs. This is rare.
  391. // In most cases IsForwarder is false.
  392. outs() << format(" % 4d ", Ordinal);
  393. } else {
  394. outs() << format(" % 4d %# 8x", Ordinal, RVA);
  395. }
  396. StringRef Name;
  397. if (I->getSymbolName(Name))
  398. continue;
  399. if (!Name.empty())
  400. outs() << " " << Name;
  401. if (IsForwarder) {
  402. StringRef S;
  403. if (I->getForwardTo(S))
  404. return;
  405. outs() << " (forwarded to " << S << ")";
  406. }
  407. outs() << "\n";
  408. }
  409. }
  410. // Given the COFF object file, this function returns the relocations for .pdata
  411. // and the pointer to "runtime function" structs.
  412. static bool getPDataSection(const COFFObjectFile *Obj,
  413. std::vector<RelocationRef> &Rels,
  414. const RuntimeFunction *&RFStart, int &NumRFs) {
  415. for (const SectionRef &Section : Obj->sections()) {
  416. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  417. if (Name != ".pdata")
  418. continue;
  419. const coff_section *Pdata = Obj->getCOFFSection(Section);
  420. for (const RelocationRef &Reloc : Section.relocations())
  421. Rels.push_back(Reloc);
  422. // Sort relocations by address.
  423. llvm::sort(Rels, isRelocAddressLess);
  424. ArrayRef<uint8_t> Contents;
  425. if (Error E = Obj->getSectionContents(Pdata, Contents))
  426. reportError(std::move(E), Obj->getFileName());
  427. if (Contents.empty())
  428. continue;
  429. RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
  430. NumRFs = Contents.size() / sizeof(RuntimeFunction);
  431. return true;
  432. }
  433. return false;
  434. }
  435. Error objdump::getCOFFRelocationValueString(const COFFObjectFile *Obj,
  436. const RelocationRef &Rel,
  437. SmallVectorImpl<char> &Result) {
  438. symbol_iterator SymI = Rel.getSymbol();
  439. Expected<StringRef> SymNameOrErr = SymI->getName();
  440. if (!SymNameOrErr)
  441. return SymNameOrErr.takeError();
  442. StringRef SymName = *SymNameOrErr;
  443. Result.append(SymName.begin(), SymName.end());
  444. return Error::success();
  445. }
  446. static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
  447. // The casts to int are required in order to output the value as number.
  448. // Without the casts the value would be interpreted as char data (which
  449. // results in garbage output).
  450. outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
  451. outs() << " Flags: " << static_cast<int>(UI->getFlags());
  452. if (UI->getFlags()) {
  453. if (UI->getFlags() & UNW_ExceptionHandler)
  454. outs() << " UNW_ExceptionHandler";
  455. if (UI->getFlags() & UNW_TerminateHandler)
  456. outs() << " UNW_TerminateHandler";
  457. if (UI->getFlags() & UNW_ChainInfo)
  458. outs() << " UNW_ChainInfo";
  459. }
  460. outs() << "\n";
  461. outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
  462. outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
  463. // Maybe this should move to output of UOP_SetFPReg?
  464. if (UI->getFrameRegister()) {
  465. outs() << " Frame register: "
  466. << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
  467. outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
  468. } else {
  469. outs() << " No frame pointer used\n";
  470. }
  471. if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
  472. // FIXME: Output exception handler data
  473. } else if (UI->getFlags() & UNW_ChainInfo) {
  474. // FIXME: Output chained unwind info
  475. }
  476. if (UI->NumCodes)
  477. outs() << " Unwind Codes:\n";
  478. printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
  479. outs() << "\n";
  480. outs().flush();
  481. }
  482. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  483. /// pointing to an executable file.
  484. static void printRuntimeFunction(const COFFObjectFile *Obj,
  485. const RuntimeFunction &RF) {
  486. if (!RF.StartAddress)
  487. return;
  488. outs() << "Function Table:\n"
  489. << format(" Start Address: 0x%04x\n",
  490. static_cast<uint32_t>(RF.StartAddress))
  491. << format(" End Address: 0x%04x\n",
  492. static_cast<uint32_t>(RF.EndAddress))
  493. << format(" Unwind Info Address: 0x%04x\n",
  494. static_cast<uint32_t>(RF.UnwindInfoOffset));
  495. uintptr_t addr;
  496. if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
  497. return;
  498. printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
  499. }
  500. /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
  501. /// pointing to an object file. Unlike executable, fields in RuntimeFunction
  502. /// struct are filled with zeros, but instead there are relocations pointing to
  503. /// them so that the linker will fill targets' RVAs to the fields at link
  504. /// time. This function interprets the relocations to find the data to be used
  505. /// in the resulting executable.
  506. static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
  507. const RuntimeFunction &RF,
  508. uint64_t SectionOffset,
  509. const std::vector<RelocationRef> &Rels) {
  510. outs() << "Function Table:\n";
  511. outs() << " Start Address: ";
  512. printCOFFSymbolAddress(outs(), Rels,
  513. SectionOffset +
  514. /*offsetof(RuntimeFunction, StartAddress)*/ 0,
  515. RF.StartAddress);
  516. outs() << "\n";
  517. outs() << " End Address: ";
  518. printCOFFSymbolAddress(outs(), Rels,
  519. SectionOffset +
  520. /*offsetof(RuntimeFunction, EndAddress)*/ 4,
  521. RF.EndAddress);
  522. outs() << "\n";
  523. outs() << " Unwind Info Address: ";
  524. printCOFFSymbolAddress(outs(), Rels,
  525. SectionOffset +
  526. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  527. RF.UnwindInfoOffset);
  528. outs() << "\n";
  529. ArrayRef<uint8_t> XContents;
  530. uint64_t UnwindInfoOffset = 0;
  531. if (Error E = getSectionContents(
  532. Obj, Rels,
  533. SectionOffset +
  534. /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
  535. XContents, UnwindInfoOffset))
  536. reportError(std::move(E), Obj->getFileName());
  537. if (XContents.empty())
  538. return;
  539. UnwindInfoOffset += RF.UnwindInfoOffset;
  540. if (UnwindInfoOffset > XContents.size())
  541. return;
  542. auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
  543. UnwindInfoOffset);
  544. printWin64EHUnwindInfo(UI);
  545. }
  546. void objdump::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
  547. if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
  548. WithColor::error(errs(), "llvm-objdump")
  549. << "unsupported image machine type "
  550. "(currently only AMD64 is supported).\n";
  551. return;
  552. }
  553. std::vector<RelocationRef> Rels;
  554. const RuntimeFunction *RFStart;
  555. int NumRFs;
  556. if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
  557. return;
  558. ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
  559. bool IsExecutable = Rels.empty();
  560. if (IsExecutable) {
  561. for (const RuntimeFunction &RF : RFs)
  562. printRuntimeFunction(Obj, RF);
  563. return;
  564. }
  565. for (const RuntimeFunction &RF : RFs) {
  566. uint64_t SectionOffset =
  567. std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
  568. printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
  569. }
  570. }
  571. void objdump::printCOFFFileHeader(const object::ObjectFile *Obj) {
  572. const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
  573. printTLSDirectory(file);
  574. printLoadConfiguration(file);
  575. printImportTables(file);
  576. printExportTable(file);
  577. }
  578. void objdump::printCOFFSymbolTable(const object::COFFImportFile *i) {
  579. unsigned Index = 0;
  580. bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
  581. for (const object::BasicSymbolRef &Sym : i->symbols()) {
  582. std::string Name;
  583. raw_string_ostream NS(Name);
  584. cantFail(Sym.printName(NS));
  585. NS.flush();
  586. outs() << "[" << format("%2d", Index) << "]"
  587. << "(sec " << format("%2d", 0) << ")"
  588. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  589. << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
  590. << "(scl " << format("%3x", 0) << ") "
  591. << "(nx " << 0 << ") "
  592. << "0x" << format("%08x", 0) << " " << Name << '\n';
  593. ++Index;
  594. }
  595. }
  596. void objdump::printCOFFSymbolTable(const COFFObjectFile *coff) {
  597. for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
  598. Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
  599. if (!Symbol)
  600. reportError(Symbol.takeError(), coff->getFileName());
  601. Expected<StringRef> NameOrErr = coff->getSymbolName(*Symbol);
  602. if (!NameOrErr)
  603. reportError(NameOrErr.takeError(), coff->getFileName());
  604. StringRef Name = *NameOrErr;
  605. outs() << "[" << format("%2d", SI) << "]"
  606. << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
  607. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  608. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
  609. << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
  610. << ") "
  611. << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
  612. << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
  613. << Name;
  614. if (Demangle && Name.startswith("?")) {
  615. int Status = -1;
  616. char *DemangledSymbol =
  617. microsoftDemangle(Name.data(), nullptr, nullptr, nullptr, &Status);
  618. if (Status == 0 && DemangledSymbol) {
  619. outs() << " (" << StringRef(DemangledSymbol) << ")";
  620. std::free(DemangledSymbol);
  621. } else {
  622. outs() << " (invalid mangled name)";
  623. }
  624. }
  625. outs() << "\n";
  626. for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
  627. if (Symbol->isSectionDefinition()) {
  628. const coff_aux_section_definition *asd;
  629. if (Error E =
  630. coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))
  631. reportError(std::move(E), coff->getFileName());
  632. int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
  633. outs() << "AUX "
  634. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  635. , unsigned(asd->Length)
  636. , unsigned(asd->NumberOfRelocations)
  637. , unsigned(asd->NumberOfLinenumbers)
  638. , unsigned(asd->CheckSum))
  639. << format("assoc %d comdat %d\n"
  640. , unsigned(AuxNumber)
  641. , unsigned(asd->Selection));
  642. } else if (Symbol->isFileRecord()) {
  643. const char *FileName;
  644. if (Error E = coff->getAuxSymbol<char>(SI + 1, FileName))
  645. reportError(std::move(E), coff->getFileName());
  646. StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
  647. coff->getSymbolTableEntrySize());
  648. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  649. SI = SI + Symbol->getNumberOfAuxSymbols();
  650. break;
  651. } else if (Symbol->isWeakExternal()) {
  652. const coff_aux_weak_external *awe;
  653. if (Error E = coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe))
  654. reportError(std::move(E), coff->getFileName());
  655. outs() << "AUX " << format("indx %d srch %d\n",
  656. static_cast<uint32_t>(awe->TagIndex),
  657. static_cast<uint32_t>(awe->Characteristics));
  658. } else {
  659. outs() << "AUX Unknown\n";
  660. }
  661. }
  662. }
  663. }