Win64EHDumper.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. //===- Win64EHDumper.cpp - Win64 EH Printer ---------------------*- 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. #include "Win64EHDumper.h"
  9. #include "llvm-readobj.h"
  10. #include "llvm/Object/COFF.h"
  11. #include "llvm/Support/ErrorHandling.h"
  12. #include "llvm/Support/Format.h"
  13. using namespace llvm;
  14. using namespace llvm::object;
  15. using namespace llvm::Win64EH;
  16. const EnumEntry<unsigned> UnwindFlags[] = {
  17. { "ExceptionHandler", UNW_ExceptionHandler },
  18. { "TerminateHandler", UNW_TerminateHandler },
  19. { "ChainInfo" , UNW_ChainInfo }
  20. };
  21. const EnumEntry<unsigned> UnwindOpInfo[] = {
  22. { "RAX", 0 },
  23. { "RCX", 1 },
  24. { "RDX", 2 },
  25. { "RBX", 3 },
  26. { "RSP", 4 },
  27. { "RBP", 5 },
  28. { "RSI", 6 },
  29. { "RDI", 7 },
  30. { "R8", 8 },
  31. { "R9", 9 },
  32. { "R10", 10 },
  33. { "R11", 11 },
  34. { "R12", 12 },
  35. { "R13", 13 },
  36. { "R14", 14 },
  37. { "R15", 15 }
  38. };
  39. static uint64_t getOffsetOfLSDA(const UnwindInfo& UI) {
  40. return static_cast<const char*>(UI.getLanguageSpecificData())
  41. - reinterpret_cast<const char*>(&UI);
  42. }
  43. static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UC) {
  44. if (UC.size() < 3)
  45. return 0;
  46. return UC[1].FrameOffset + (static_cast<uint32_t>(UC[2].FrameOffset) << 16);
  47. }
  48. // Returns the name of the unwind code.
  49. static StringRef getUnwindCodeTypeName(uint8_t Code) {
  50. switch (Code) {
  51. default: llvm_unreachable("Invalid unwind code");
  52. case UOP_PushNonVol: return "PUSH_NONVOL";
  53. case UOP_AllocLarge: return "ALLOC_LARGE";
  54. case UOP_AllocSmall: return "ALLOC_SMALL";
  55. case UOP_SetFPReg: return "SET_FPREG";
  56. case UOP_SaveNonVol: return "SAVE_NONVOL";
  57. case UOP_SaveNonVolBig: return "SAVE_NONVOL_FAR";
  58. case UOP_SaveXMM128: return "SAVE_XMM128";
  59. case UOP_SaveXMM128Big: return "SAVE_XMM128_FAR";
  60. case UOP_PushMachFrame: return "PUSH_MACHFRAME";
  61. }
  62. }
  63. // Returns the name of a referenced register.
  64. static StringRef getUnwindRegisterName(uint8_t Reg) {
  65. switch (Reg) {
  66. default: llvm_unreachable("Invalid register");
  67. case 0: return "RAX";
  68. case 1: return "RCX";
  69. case 2: return "RDX";
  70. case 3: return "RBX";
  71. case 4: return "RSP";
  72. case 5: return "RBP";
  73. case 6: return "RSI";
  74. case 7: return "RDI";
  75. case 8: return "R8";
  76. case 9: return "R9";
  77. case 10: return "R10";
  78. case 11: return "R11";
  79. case 12: return "R12";
  80. case 13: return "R13";
  81. case 14: return "R14";
  82. case 15: return "R15";
  83. }
  84. }
  85. // Calculates the number of array slots required for the unwind code.
  86. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
  87. switch (UnwindCode.getUnwindOp()) {
  88. default: llvm_unreachable("Invalid unwind code");
  89. case UOP_PushNonVol:
  90. case UOP_AllocSmall:
  91. case UOP_SetFPReg:
  92. case UOP_PushMachFrame:
  93. return 1;
  94. case UOP_SaveNonVol:
  95. case UOP_SaveXMM128:
  96. return 2;
  97. case UOP_SaveNonVolBig:
  98. case UOP_SaveXMM128Big:
  99. return 3;
  100. case UOP_AllocLarge:
  101. return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
  102. }
  103. }
  104. static std::error_code getSymbol(const COFFObjectFile &COFF, uint64_t VA,
  105. object::SymbolRef &Sym) {
  106. for (const auto &Symbol : COFF.symbols()) {
  107. Expected<uint64_t> Address = Symbol.getAddress();
  108. if (!Address)
  109. return errorToErrorCode(Address.takeError());
  110. if (*Address == VA) {
  111. Sym = Symbol;
  112. return std::error_code();
  113. }
  114. }
  115. return inconvertibleErrorCode();
  116. }
  117. static object::SymbolRef getPreferredSymbol(const COFFObjectFile &COFF,
  118. object::SymbolRef Sym,
  119. uint32_t &SymbolOffset,
  120. bool IsRangeEnd) {
  121. // The symbol resolved by ResolveSymbol can be any internal
  122. // nondescriptive symbol; try to resolve a more descriptive one.
  123. COFFSymbolRef CoffSym = COFF.getCOFFSymbol(Sym);
  124. if (CoffSym.getStorageClass() != COFF::IMAGE_SYM_CLASS_LABEL &&
  125. CoffSym.getSectionDefinition() == nullptr)
  126. return Sym;
  127. for (const auto &S : COFF.symbols()) {
  128. COFFSymbolRef CS = COFF.getCOFFSymbol(S);
  129. if (CS.getSectionNumber() == CoffSym.getSectionNumber() &&
  130. CS.getValue() <= CoffSym.getValue() + SymbolOffset &&
  131. CS.getStorageClass() != COFF::IMAGE_SYM_CLASS_LABEL &&
  132. CS.getSectionDefinition() == nullptr) {
  133. uint32_t Offset = CoffSym.getValue() + SymbolOffset - CS.getValue();
  134. // For the end of a range, don't pick a symbol with a zero offset;
  135. // prefer a symbol with a small positive offset.
  136. if (Offset <= SymbolOffset && (!IsRangeEnd || Offset > 0)) {
  137. SymbolOffset = Offset;
  138. Sym = S;
  139. CoffSym = CS;
  140. if (CS.isExternal() && SymbolOffset == 0)
  141. return Sym;
  142. }
  143. }
  144. }
  145. return Sym;
  146. }
  147. static std::string formatSymbol(const Dumper::Context &Ctx,
  148. const coff_section *Section, uint64_t Offset,
  149. uint32_t Displacement,
  150. bool IsRangeEnd = false) {
  151. std::string Buffer;
  152. raw_string_ostream OS(Buffer);
  153. SymbolRef Symbol;
  154. if (!Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) {
  155. // We found a relocation at the given offset in the section, pointing
  156. // at a symbol.
  157. // Try to resolve label/section symbols into function names.
  158. Symbol = getPreferredSymbol(Ctx.COFF, Symbol, Displacement, IsRangeEnd);
  159. Expected<StringRef> Name = Symbol.getName();
  160. if (Name) {
  161. OS << *Name;
  162. if (Displacement > 0)
  163. OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
  164. else
  165. OS << format(" (0x%" PRIX64 ")", Offset);
  166. return OS.str();
  167. } else {
  168. // TODO: Actually report errors helpfully.
  169. consumeError(Name.takeError());
  170. }
  171. } else if (!getSymbol(Ctx.COFF, Ctx.COFF.getImageBase() + Displacement,
  172. Symbol)) {
  173. Expected<StringRef> Name = Symbol.getName();
  174. if (Name) {
  175. OS << *Name;
  176. OS << format(" (0x%" PRIX64 ")", Ctx.COFF.getImageBase() + Displacement);
  177. return OS.str();
  178. } else {
  179. consumeError(Name.takeError());
  180. }
  181. }
  182. if (Displacement > 0)
  183. OS << format("(0x%" PRIX64 ")", Ctx.COFF.getImageBase() + Displacement);
  184. else
  185. OS << format("(0x%" PRIX64 ")", Offset);
  186. return OS.str();
  187. }
  188. static std::error_code resolveRelocation(const Dumper::Context &Ctx,
  189. const coff_section *Section,
  190. uint64_t Offset,
  191. const coff_section *&ResolvedSection,
  192. uint64_t &ResolvedAddress) {
  193. SymbolRef Symbol;
  194. if (std::error_code EC =
  195. Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData))
  196. return EC;
  197. Expected<uint64_t> ResolvedAddressOrErr = Symbol.getAddress();
  198. if (!ResolvedAddressOrErr)
  199. return errorToErrorCode(ResolvedAddressOrErr.takeError());
  200. ResolvedAddress = *ResolvedAddressOrErr;
  201. Expected<section_iterator> SI = Symbol.getSection();
  202. if (!SI)
  203. return errorToErrorCode(SI.takeError());
  204. ResolvedSection = Ctx.COFF.getCOFFSection(**SI);
  205. return std::error_code();
  206. }
  207. static const object::coff_section *
  208. getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) {
  209. for (const auto &Section : COFF.sections()) {
  210. uint64_t Address = Section.getAddress();
  211. uint64_t Size = Section.getSize();
  212. if (VA >= Address && (VA - Address) <= Size)
  213. return COFF.getCOFFSection(Section);
  214. }
  215. return nullptr;
  216. }
  217. namespace llvm {
  218. namespace Win64EH {
  219. void Dumper::printRuntimeFunctionEntry(const Context &Ctx,
  220. const coff_section *Section,
  221. uint64_t Offset,
  222. const RuntimeFunction &RF) {
  223. SW.printString("StartAddress",
  224. formatSymbol(Ctx, Section, Offset + 0, RF.StartAddress));
  225. SW.printString("EndAddress",
  226. formatSymbol(Ctx, Section, Offset + 4, RF.EndAddress,
  227. /*IsRangeEnd=*/true));
  228. SW.printString("UnwindInfoAddress",
  229. formatSymbol(Ctx, Section, Offset + 8, RF.UnwindInfoOffset));
  230. }
  231. // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
  232. // the unwind codes array, this function requires that the correct number of
  233. // slots is provided.
  234. void Dumper::printUnwindCode(const UnwindInfo& UI, ArrayRef<UnwindCode> UC) {
  235. assert(UC.size() >= getNumUsedSlots(UC[0]));
  236. SW.startLine() << format("0x%02X: ", unsigned(UC[0].u.CodeOffset))
  237. << getUnwindCodeTypeName(UC[0].getUnwindOp());
  238. switch (UC[0].getUnwindOp()) {
  239. case UOP_PushNonVol:
  240. OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo());
  241. break;
  242. case UOP_AllocLarge:
  243. OS << " size="
  244. << ((UC[0].getOpInfo() == 0) ? UC[1].FrameOffset * 8
  245. : getLargeSlotValue(UC));
  246. break;
  247. case UOP_AllocSmall:
  248. OS << " size=" << (UC[0].getOpInfo() + 1) * 8;
  249. break;
  250. case UOP_SetFPReg:
  251. if (UI.getFrameRegister() == 0)
  252. OS << " reg=<invalid>";
  253. else
  254. OS << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
  255. << format(", offset=0x%X", UI.getFrameOffset() * 16);
  256. break;
  257. case UOP_SaveNonVol:
  258. OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo())
  259. << format(", offset=0x%X", UC[1].FrameOffset * 8);
  260. break;
  261. case UOP_SaveNonVolBig:
  262. OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo())
  263. << format(", offset=0x%X", getLargeSlotValue(UC));
  264. break;
  265. case UOP_SaveXMM128:
  266. OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo())
  267. << format(", offset=0x%X", UC[1].FrameOffset * 16);
  268. break;
  269. case UOP_SaveXMM128Big:
  270. OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo())
  271. << format(", offset=0x%X", getLargeSlotValue(UC));
  272. break;
  273. case UOP_PushMachFrame:
  274. OS << " errcode=" << (UC[0].getOpInfo() == 0 ? "no" : "yes");
  275. break;
  276. }
  277. OS << "\n";
  278. }
  279. void Dumper::printUnwindInfo(const Context &Ctx, const coff_section *Section,
  280. off_t Offset, const UnwindInfo &UI) {
  281. DictScope UIS(SW, "UnwindInfo");
  282. SW.printNumber("Version", UI.getVersion());
  283. SW.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags));
  284. SW.printNumber("PrologSize", UI.PrologSize);
  285. if (UI.getFrameRegister()) {
  286. SW.printEnum("FrameRegister", UI.getFrameRegister(),
  287. makeArrayRef(UnwindOpInfo));
  288. SW.printHex("FrameOffset", UI.getFrameOffset());
  289. } else {
  290. SW.printString("FrameRegister", StringRef("-"));
  291. SW.printString("FrameOffset", StringRef("-"));
  292. }
  293. SW.printNumber("UnwindCodeCount", UI.NumCodes);
  294. {
  295. ListScope UCS(SW, "UnwindCodes");
  296. ArrayRef<UnwindCode> UC(&UI.UnwindCodes[0], UI.NumCodes);
  297. for (const UnwindCode *UCI = UC.begin(), *UCE = UC.end(); UCI < UCE; ++UCI) {
  298. unsigned UsedSlots = getNumUsedSlots(*UCI);
  299. if (UsedSlots > UC.size()) {
  300. errs() << "corrupt unwind data";
  301. return;
  302. }
  303. printUnwindCode(UI, makeArrayRef(UCI, UCE));
  304. UCI = UCI + UsedSlots - 1;
  305. }
  306. }
  307. uint64_t LSDAOffset = Offset + getOffsetOfLSDA(UI);
  308. if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
  309. SW.printString("Handler",
  310. formatSymbol(Ctx, Section, LSDAOffset,
  311. UI.getLanguageSpecificHandlerOffset()));
  312. } else if (UI.getFlags() & UNW_ChainInfo) {
  313. if (const RuntimeFunction *Chained = UI.getChainedFunctionEntry()) {
  314. DictScope CS(SW, "Chained");
  315. printRuntimeFunctionEntry(Ctx, Section, LSDAOffset, *Chained);
  316. }
  317. }
  318. }
  319. void Dumper::printRuntimeFunction(const Context &Ctx,
  320. const coff_section *Section,
  321. uint64_t SectionOffset,
  322. const RuntimeFunction &RF) {
  323. DictScope RFS(SW, "RuntimeFunction");
  324. printRuntimeFunctionEntry(Ctx, Section, SectionOffset, RF);
  325. const coff_section *XData = nullptr;
  326. uint64_t Offset;
  327. resolveRelocation(Ctx, Section, SectionOffset + 8, XData, Offset);
  328. Offset = Offset + RF.UnwindInfoOffset;
  329. if (!XData) {
  330. uint64_t Address = Ctx.COFF.getImageBase() + RF.UnwindInfoOffset;
  331. XData = getSectionContaining(Ctx.COFF, Address);
  332. if (!XData)
  333. return;
  334. Offset = RF.UnwindInfoOffset - XData->VirtualAddress;
  335. }
  336. ArrayRef<uint8_t> Contents;
  337. if (Error E = Ctx.COFF.getSectionContents(XData, Contents))
  338. reportError(std::move(E), Ctx.COFF.getFileName());
  339. if (Contents.empty())
  340. return;
  341. if (Offset > Contents.size())
  342. return;
  343. const auto UI = reinterpret_cast<const UnwindInfo*>(Contents.data() + Offset);
  344. printUnwindInfo(Ctx, XData, Offset, *UI);
  345. }
  346. void Dumper::printData(const Context &Ctx) {
  347. for (const auto &Section : Ctx.COFF.sections()) {
  348. StringRef Name;
  349. if (Expected<StringRef> NameOrErr = Section.getName())
  350. Name = *NameOrErr;
  351. else
  352. consumeError(NameOrErr.takeError());
  353. if (Name != ".pdata" && !Name.startswith(".pdata$"))
  354. continue;
  355. const coff_section *PData = Ctx.COFF.getCOFFSection(Section);
  356. ArrayRef<uint8_t> Contents;
  357. if (Error E = Ctx.COFF.getSectionContents(PData, Contents))
  358. reportError(std::move(E), Ctx.COFF.getFileName());
  359. if (Contents.empty())
  360. continue;
  361. const RuntimeFunction *Entries =
  362. reinterpret_cast<const RuntimeFunction *>(Contents.data());
  363. const size_t Count = Contents.size() / sizeof(RuntimeFunction);
  364. ArrayRef<RuntimeFunction> RuntimeFunctions(Entries, Count);
  365. size_t Index = 0;
  366. for (const auto &RF : RuntimeFunctions) {
  367. printRuntimeFunction(Ctx, Ctx.COFF.getCOFFSection(Section),
  368. Index * sizeof(RuntimeFunction), RF);
  369. ++Index;
  370. }
  371. }
  372. }
  373. }
  374. }