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