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 const EnumEntry<unsigned> UnwindFlags[] = {
20   { "ExceptionHandler", UNW_ExceptionHandler },
21   { "TerminateHandler", UNW_TerminateHandler },
22   { "ChainInfo"       , UNW_ChainInfo        }
23 };
24 
25 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 object::SymbolRef getPreferredSymbol(const COFFObjectFile &COFF,
129                                             object::SymbolRef Sym,
130                                             uint32_t &SymbolOffset,
131                                             bool IsRangeEnd) {
132   // The symbol resolved by ResolveSymbol can be any internal
133   // nondescriptive symbol; try to resolve a more descriptive one.
134   COFFSymbolRef CoffSym = COFF.getCOFFSymbol(Sym);
135   if (CoffSym.getStorageClass() != COFF::IMAGE_SYM_CLASS_LABEL &&
136       CoffSym.getSectionDefinition() == nullptr)
137     return Sym;
138   for (const auto &S : COFF.symbols()) {
139     COFFSymbolRef CS = COFF.getCOFFSymbol(S);
140     if (CS.getSectionNumber() == CoffSym.getSectionNumber() &&
141         CS.getValue() <= CoffSym.getValue() + SymbolOffset &&
142         CS.getStorageClass() != COFF::IMAGE_SYM_CLASS_LABEL &&
143         CS.getSectionDefinition() == nullptr) {
144       uint32_t Offset = CoffSym.getValue() + SymbolOffset - CS.getValue();
145       // For the end of a range, don't pick a symbol with a zero offset;
146       // prefer a symbol with a small positive offset.
147       if (Offset <= SymbolOffset && (!IsRangeEnd || Offset > 0)) {
148         SymbolOffset = Offset;
149         Sym = S;
150         CoffSym = CS;
151         if (CS.isExternal() && SymbolOffset == 0)
152           return Sym;
153       }
154     }
155   }
156   return Sym;
157 }
158 
159 static std::string formatSymbol(const Dumper::Context &Ctx,
160                                 const coff_section *Section, uint64_t Offset,
161                                 uint32_t Displacement,
162                                 bool IsRangeEnd = false) {
163   std::string Buffer;
164   raw_string_ostream OS(Buffer);
165 
166   SymbolRef Symbol;
167   if (!Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) {
168     // We found a relocation at the given offset in the section, pointing
169     // at a symbol.
170 
171     // Try to resolve label/section symbols into function names.
172     Symbol = getPreferredSymbol(Ctx.COFF, Symbol, Displacement, IsRangeEnd);
173 
174     Expected<StringRef> Name = Symbol.getName();
175     if (Name) {
176       OS << *Name;
177       if (Displacement > 0)
178         OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
179       else
180         OS << format(" (0x%" PRIX64 ")", Offset);
181       return OS.str();
182     } else {
183       // TODO: Actually report errors helpfully.
184       consumeError(Name.takeError());
185     }
186   } else if (!getSymbol(Ctx.COFF, Ctx.COFF.getImageBase() + Displacement,
187                         Symbol)) {
188     Expected<StringRef> Name = Symbol.getName();
189     if (Name) {
190       OS << *Name;
191       OS << format(" (0x%" PRIX64 ")", Ctx.COFF.getImageBase() + Displacement);
192       return OS.str();
193     } else {
194       consumeError(Name.takeError());
195     }
196   }
197 
198   if (Displacement > 0)
199     OS << format("(0x%" PRIX64 ")", Ctx.COFF.getImageBase() + Displacement);
200   else
201     OS << format("(0x%" PRIX64 ")", Offset);
202   return OS.str();
203 }
204 
205 static std::error_code resolveRelocation(const Dumper::Context &Ctx,
206                                          const coff_section *Section,
207                                          uint64_t Offset,
208                                          const coff_section *&ResolvedSection,
209                                          uint64_t &ResolvedAddress) {
210   SymbolRef Symbol;
211   if (std::error_code EC =
212           Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData))
213     return EC;
214 
215   Expected<uint64_t> ResolvedAddressOrErr = Symbol.getAddress();
216   if (!ResolvedAddressOrErr)
217     return errorToErrorCode(ResolvedAddressOrErr.takeError());
218   ResolvedAddress = *ResolvedAddressOrErr;
219 
220   Expected<section_iterator> SI = Symbol.getSection();
221   if (!SI)
222     return errorToErrorCode(SI.takeError());
223   ResolvedSection = Ctx.COFF.getCOFFSection(**SI);
224   return std::error_code();
225 }
226 
227 static const object::coff_section *
228 getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) {
229   for (const auto &Section : COFF.sections()) {
230     uint64_t Address = Section.getAddress();
231     uint64_t Size = Section.getSize();
232 
233     if (VA >= Address && (VA - Address) <= Size)
234       return COFF.getCOFFSection(Section);
235   }
236   return nullptr;
237 }
238 
239 namespace llvm {
240 namespace Win64EH {
241 void Dumper::printRuntimeFunctionEntry(const Context &Ctx,
242                                        const coff_section *Section,
243                                        uint64_t Offset,
244                                        const RuntimeFunction &RF) {
245   SW.printString("StartAddress",
246                  formatSymbol(Ctx, Section, Offset + 0, RF.StartAddress));
247   SW.printString("EndAddress",
248                  formatSymbol(Ctx, Section, Offset + 4, RF.EndAddress,
249                               /*IsRangeEnd=*/true));
250   SW.printString("UnwindInfoAddress",
251                  formatSymbol(Ctx, Section, Offset + 8, RF.UnwindInfoOffset));
252 }
253 
254 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
255 // the unwind codes array, this function requires that the correct number of
256 // slots is provided.
257 void Dumper::printUnwindCode(const UnwindInfo& UI, ArrayRef<UnwindCode> UC) {
258   assert(UC.size() >= getNumUsedSlots(UC[0]));
259 
260   SW.startLine() << format("0x%02X: ", unsigned(UC[0].u.CodeOffset))
261                  << getUnwindCodeTypeName(UC[0].getUnwindOp());
262 
263   switch (UC[0].getUnwindOp()) {
264   case UOP_PushNonVol:
265     OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo());
266     break;
267 
268   case UOP_AllocLarge:
269     OS << " size="
270        << ((UC[0].getOpInfo() == 0) ? UC[1].FrameOffset * 8
271                                     : getLargeSlotValue(UC));
272     break;
273 
274   case UOP_AllocSmall:
275     OS << " size=" << (UC[0].getOpInfo() + 1) * 8;
276     break;
277 
278   case UOP_SetFPReg:
279     if (UI.getFrameRegister() == 0)
280       OS << " reg=<invalid>";
281     else
282       OS << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
283          << format(", offset=0x%X", UI.getFrameOffset() * 16);
284     break;
285 
286   case UOP_SaveNonVol:
287     OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo())
288        << format(", offset=0x%X", UC[1].FrameOffset * 8);
289     break;
290 
291   case UOP_SaveNonVolBig:
292     OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo())
293        << format(", offset=0x%X", getLargeSlotValue(UC));
294     break;
295 
296   case UOP_SaveXMM128:
297     OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo())
298        << format(", offset=0x%X", UC[1].FrameOffset * 16);
299     break;
300 
301   case UOP_SaveXMM128Big:
302     OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo())
303        << format(", offset=0x%X", getLargeSlotValue(UC));
304     break;
305 
306   case UOP_PushMachFrame:
307     OS << " errcode=" << (UC[0].getOpInfo() == 0 ? "no" : "yes");
308     break;
309   }
310 
311   OS << "\n";
312 }
313 
314 void Dumper::printUnwindInfo(const Context &Ctx, const coff_section *Section,
315                              off_t Offset, const UnwindInfo &UI) {
316   DictScope UIS(SW, "UnwindInfo");
317   SW.printNumber("Version", UI.getVersion());
318   SW.printFlags("Flags", UI.getFlags(), ArrayRef(UnwindFlags));
319   SW.printNumber("PrologSize", UI.PrologSize);
320   if (UI.getFrameRegister()) {
321     SW.printEnum("FrameRegister", UI.getFrameRegister(),
322                  ArrayRef(UnwindOpInfo));
323     SW.printHex("FrameOffset", UI.getFrameOffset());
324   } else {
325     SW.printString("FrameRegister", StringRef("-"));
326     SW.printString("FrameOffset", StringRef("-"));
327   }
328 
329   SW.printNumber("UnwindCodeCount", UI.NumCodes);
330   {
331     ListScope UCS(SW, "UnwindCodes");
332     ArrayRef<UnwindCode> UC(&UI.UnwindCodes[0], UI.NumCodes);
333     for (const UnwindCode *UCI = UC.begin(), *UCE = UC.end(); UCI < UCE; ++UCI) {
334       unsigned UsedSlots = getNumUsedSlots(*UCI);
335       if (UsedSlots > UC.size()) {
336         errs() << "corrupt unwind data";
337         return;
338       }
339 
340       printUnwindCode(UI, ArrayRef(UCI, UCE));
341       UCI = UCI + UsedSlots - 1;
342     }
343   }
344 
345   uint64_t LSDAOffset = Offset + getOffsetOfLSDA(UI);
346   if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
347     SW.printString("Handler",
348                    formatSymbol(Ctx, Section, LSDAOffset,
349                                 UI.getLanguageSpecificHandlerOffset()));
350   } else if (UI.getFlags() & UNW_ChainInfo) {
351     if (const RuntimeFunction *Chained = UI.getChainedFunctionEntry()) {
352       DictScope CS(SW, "Chained");
353       printRuntimeFunctionEntry(Ctx, Section, LSDAOffset, *Chained);
354     }
355   }
356 }
357 
358 void Dumper::printRuntimeFunction(const Context &Ctx,
359                                   const coff_section *Section,
360                                   uint64_t SectionOffset,
361                                   const RuntimeFunction &RF) {
362   DictScope RFS(SW, "RuntimeFunction");
363   printRuntimeFunctionEntry(Ctx, Section, SectionOffset, RF);
364 
365   const coff_section *XData = nullptr;
366   uint64_t Offset;
367   resolveRelocation(Ctx, Section, SectionOffset + 8, XData, Offset);
368   Offset = Offset + RF.UnwindInfoOffset;
369 
370   if (!XData) {
371     uint64_t Address = Ctx.COFF.getImageBase() + RF.UnwindInfoOffset;
372     XData = getSectionContaining(Ctx.COFF, Address);
373     if (!XData)
374       return;
375     Offset = RF.UnwindInfoOffset - XData->VirtualAddress;
376   }
377 
378   ArrayRef<uint8_t> Contents;
379   if (Error E = Ctx.COFF.getSectionContents(XData, Contents))
380     reportError(std::move(E), Ctx.COFF.getFileName());
381 
382   if (Contents.empty())
383     return;
384 
385   if (Offset > Contents.size())
386     return;
387 
388   const auto UI = reinterpret_cast<const UnwindInfo*>(Contents.data() + Offset);
389   printUnwindInfo(Ctx, XData, Offset, *UI);
390 }
391 
392 void Dumper::printData(const Context &Ctx) {
393   for (const auto &Section : Ctx.COFF.sections()) {
394     StringRef Name;
395     if (Expected<StringRef> NameOrErr = Section.getName())
396       Name = *NameOrErr;
397     else
398       consumeError(NameOrErr.takeError());
399 
400     if (Name != ".pdata" && !Name.startswith(".pdata$"))
401       continue;
402 
403     const coff_section *PData = Ctx.COFF.getCOFFSection(Section);
404     ArrayRef<uint8_t> Contents;
405 
406     if (Error E = Ctx.COFF.getSectionContents(PData, Contents))
407       reportError(std::move(E), Ctx.COFF.getFileName());
408     if (Contents.empty())
409       continue;
410 
411     const RuntimeFunction *Entries =
412       reinterpret_cast<const RuntimeFunction *>(Contents.data());
413     const size_t Count = Contents.size() / sizeof(RuntimeFunction);
414     ArrayRef<RuntimeFunction> RuntimeFunctions(Entries, Count);
415 
416     size_t Index = 0;
417     for (const auto &RF : RuntimeFunctions) {
418       printRuntimeFunction(Ctx, Ctx.COFF.getCOFFSection(Section),
419                            Index * sizeof(RuntimeFunction), RF);
420       ++Index;
421     }
422   }
423 }
424 }
425 }
426 
427