1 //===-- ARMWinEHPrinter.cpp - Windows on ARM EH Data 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 // Windows on ARM uses a series of serialised data structures (RuntimeFunction)
10 // to create a table of information for unwinding.  In order to conserve space,
11 // there are two different ways that this data is represented.
12 //
13 // For functions with canonical forms for the prologue and epilogue, the data
14 // can be stored in a "packed" form.  In this case, the data is packed into the
15 // RuntimeFunction's remaining 30-bits and can fully describe the entire frame.
16 //
17 //        +---------------------------------------+
18 //        |         Function Entry Address        |
19 //        +---------------------------------------+
20 //        |           Packed Form Data            |
21 //        +---------------------------------------+
22 //
23 // This layout is parsed by Decoder::dumpPackedEntry.  No unwind bytecode is
24 // associated with such a frame as they can be derived from the provided data.
25 // The decoder does not synthesize this data as it is unnecessary for the
26 // purposes of validation, with the synthesis being required only by a proper
27 // unwinder.
28 //
29 // For functions that are large or do not match canonical forms, the data is
30 // split up into two portions, with the actual data residing in the "exception
31 // data" table (.xdata) with a reference to the entry from the "procedure data"
32 // (.pdata) entry.
33 //
34 // The exception data contains information about the frame setup, all of the
35 // epilogue scopes (for functions for which there are multiple exit points) and
36 // the associated exception handler.  Additionally, the entry contains byte-code
37 // describing how to unwind the function (c.f. Decoder::decodeOpcodes).
38 //
39 //        +---------------------------------------+
40 //        |         Function Entry Address        |
41 //        +---------------------------------------+
42 //        |      Exception Data Entry Address     |
43 //        +---------------------------------------+
44 //
45 // This layout is parsed by Decoder::dumpUnpackedEntry.  Such an entry must
46 // first resolve the exception data entry address.  This structure
47 // (ExceptionDataRecord) has a variable sized header
48 // (c.f. ARM::WinEH::HeaderWords) and encodes most of the same information as
49 // the packed form.  However, because this information is insufficient to
50 // synthesize the unwinding, there are associated unwinding bytecode which make
51 // up the bulk of the Decoder.
52 //
53 // The decoder itself is table-driven, using the first byte to determine the
54 // opcode and dispatching to the associated printing routine.  The bytecode
55 // itself is a variable length instruction encoding that can fully describe the
56 // state of the stack and the necessary operations for unwinding to the
57 // beginning of the frame.
58 //
59 // The byte-code maintains a 1-1 instruction mapping, indicating both the width
60 // of the instruction (Thumb2 instructions are variable length, 16 or 32 bits
61 // wide) allowing the program to unwind from any point in the prologue, body, or
62 // epilogue of the function.
63 
64 #include "ARMWinEHPrinter.h"
65 #include "llvm/ADT/STLExtras.h"
66 #include "llvm/ADT/StringExtras.h"
67 #include "llvm/Support/ARMWinEH.h"
68 #include "llvm/Support/Format.h"
69 
70 using namespace llvm;
71 using namespace llvm::object;
72 using namespace llvm::support;
73 
74 namespace llvm {
75 raw_ostream &operator<<(raw_ostream &OS, const ARM::WinEH::ReturnType &RT) {
76   switch (RT) {
77   case ARM::WinEH::ReturnType::RT_POP:
78     OS << "pop {pc}";
79     break;
80   case ARM::WinEH::ReturnType::RT_B:
81     OS << "b target";
82     break;
83   case ARM::WinEH::ReturnType::RT_BW:
84     OS << "b.w target";
85     break;
86   case ARM::WinEH::ReturnType::RT_NoEpilogue:
87     OS << "(no epilogue)";
88     break;
89   }
90   return OS;
91 }
92 }
93 
94 static std::string formatSymbol(StringRef Name, uint64_t Address,
95                                 uint64_t Offset = 0) {
96   std::string Buffer;
97   raw_string_ostream OS(Buffer);
98 
99   if (!Name.empty())
100     OS << Name << " ";
101 
102   if (Offset)
103     OS << format("+0x%" PRIX64 " (0x%" PRIX64 ")", Offset, Address);
104   else if (!Name.empty())
105     OS << format("(0x%" PRIX64 ")", Address);
106   else
107     OS << format("0x%" PRIX64, Address);
108 
109   return OS.str();
110 }
111 
112 namespace llvm {
113 namespace ARM {
114 namespace WinEH {
115 const size_t Decoder::PDataEntrySize = sizeof(RuntimeFunction);
116 
117 // TODO name the uops more appropriately
118 const Decoder::RingEntry Decoder::Ring[] = {
119   { 0x80, 0x00, 1, &Decoder::opcode_0xxxxxxx },  // UOP_STACK_FREE (16-bit)
120   { 0xc0, 0x80, 2, &Decoder::opcode_10Lxxxxx },  // UOP_POP (32-bit)
121   { 0xf0, 0xc0, 1, &Decoder::opcode_1100xxxx },  // UOP_STACK_SAVE (16-bit)
122   { 0xf8, 0xd0, 1, &Decoder::opcode_11010Lxx },  // UOP_POP (16-bit)
123   { 0xf8, 0xd8, 1, &Decoder::opcode_11011Lxx },  // UOP_POP (32-bit)
124   { 0xf8, 0xe0, 1, &Decoder::opcode_11100xxx },  // UOP_VPOP (32-bit)
125   { 0xfc, 0xe8, 2, &Decoder::opcode_111010xx },  // UOP_STACK_FREE (32-bit)
126   { 0xfe, 0xec, 2, &Decoder::opcode_1110110L },  // UOP_POP (16-bit)
127   { 0xff, 0xee, 2, &Decoder::opcode_11101110 },  // UOP_MICROSOFT_SPECIFIC (16-bit)
128                                               // UOP_PUSH_MACHINE_FRAME
129                                               // UOP_PUSH_CONTEXT
130                                               // UOP_PUSH_TRAP_FRAME
131                                               // UOP_REDZONE_RESTORE_LR
132   { 0xff, 0xef, 2, &Decoder::opcode_11101111 },  // UOP_LDRPC_POSTINC (32-bit)
133   { 0xff, 0xf5, 2, &Decoder::opcode_11110101 },  // UOP_VPOP (32-bit)
134   { 0xff, 0xf6, 2, &Decoder::opcode_11110110 },  // UOP_VPOP (32-bit)
135   { 0xff, 0xf7, 3, &Decoder::opcode_11110111 },  // UOP_STACK_RESTORE (16-bit)
136   { 0xff, 0xf8, 4, &Decoder::opcode_11111000 },  // UOP_STACK_RESTORE (16-bit)
137   { 0xff, 0xf9, 3, &Decoder::opcode_11111001 },  // UOP_STACK_RESTORE (32-bit)
138   { 0xff, 0xfa, 4, &Decoder::opcode_11111010 },  // UOP_STACK_RESTORE (32-bit)
139   { 0xff, 0xfb, 1, &Decoder::opcode_11111011 },  // UOP_NOP (16-bit)
140   { 0xff, 0xfc, 1, &Decoder::opcode_11111100 },  // UOP_NOP (32-bit)
141   { 0xff, 0xfd, 1, &Decoder::opcode_11111101 },  // UOP_NOP (16-bit) / END
142   { 0xff, 0xfe, 1, &Decoder::opcode_11111110 },  // UOP_NOP (32-bit) / END
143   { 0xff, 0xff, 1, &Decoder::opcode_11111111 },  // UOP_END
144 };
145 
146 
147 // Unwind opcodes for ARM64.
148 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
149 const Decoder::RingEntry Decoder::Ring64[] = {
150   { 0xe0, 0x00, 1, &Decoder::opcode_alloc_s },
151   { 0xe0, 0x20, 1, &Decoder::opcode_save_r19r20_x },
152   { 0xc0, 0x40, 1, &Decoder::opcode_save_fplr },
153   { 0xc0, 0x80, 1, &Decoder::opcode_save_fplr_x },
154   { 0xf8, 0xc0, 2, &Decoder::opcode_alloc_m },
155   { 0xfc, 0xc8, 2, &Decoder::opcode_save_regp },
156   { 0xfc, 0xcc, 2, &Decoder::opcode_save_regp_x },
157   { 0xfc, 0xd0, 2, &Decoder::opcode_save_reg },
158   { 0xfe, 0xd4, 2, &Decoder::opcode_save_reg_x },
159   { 0xfe, 0xd6, 2, &Decoder::opcode_save_lrpair },
160   { 0xfe, 0xd8, 2, &Decoder::opcode_save_fregp },
161   { 0xfe, 0xda, 2, &Decoder::opcode_save_fregp_x },
162   { 0xfe, 0xdc, 2, &Decoder::opcode_save_freg },
163   { 0xff, 0xde, 2, &Decoder::opcode_save_freg_x },
164   { 0xff, 0xe0, 4, &Decoder::opcode_alloc_l },
165   { 0xff, 0xe1, 1, &Decoder::opcode_setfp },
166   { 0xff, 0xe2, 2, &Decoder::opcode_addfp },
167   { 0xff, 0xe3, 1, &Decoder::opcode_nop },
168   { 0xff, 0xe4, 1, &Decoder::opcode_end },
169   { 0xff, 0xe5, 1, &Decoder::opcode_end_c },
170   { 0xff, 0xe6, 1, &Decoder::opcode_save_next },
171   { 0xff, 0xe8, 1, &Decoder::opcode_trap_frame },
172   { 0xff, 0xe9, 1, &Decoder::opcode_machine_frame },
173   { 0xff, 0xea, 1, &Decoder::opcode_context },
174   { 0xff, 0xec, 1, &Decoder::opcode_clear_unwound_to_call },
175 };
176 
177 void Decoder::printRegisters(const std::pair<uint16_t, uint32_t> &RegisterMask) {
178   static const char * const GPRRegisterNames[16] = {
179     "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
180     "r11", "ip", "sp", "lr", "pc",
181   };
182 
183   const uint16_t GPRMask = std::get<0>(RegisterMask);
184   const uint16_t VFPMask = std::get<1>(RegisterMask);
185 
186   OS << '{';
187   ListSeparator LS;
188   for (unsigned RI = 0, RE = 11; RI < RE; ++RI)
189     if (GPRMask & (1 << RI))
190       OS << LS << GPRRegisterNames[RI];
191   for (unsigned RI = 0, RE = 32; RI < RE; ++RI)
192     if (VFPMask & (1 << RI))
193       OS << LS << "d" << unsigned(RI);
194   for (unsigned RI = 11, RE = 16; RI < RE; ++RI)
195     if (GPRMask & (1 << RI))
196       OS << LS << GPRRegisterNames[RI];
197   OS << '}';
198 }
199 
200 ErrorOr<object::SectionRef>
201 Decoder::getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) {
202   for (const auto &Section : COFF.sections()) {
203     uint64_t Address = Section.getAddress();
204     uint64_t Size = Section.getSize();
205 
206     if (VA >= Address && (VA - Address) <= Size)
207       return Section;
208   }
209   return inconvertibleErrorCode();
210 }
211 
212 ErrorOr<object::SymbolRef> Decoder::getSymbol(const COFFObjectFile &COFF,
213                                               uint64_t VA, bool FunctionOnly) {
214   for (const auto &Symbol : COFF.symbols()) {
215     Expected<SymbolRef::Type> Type = Symbol.getType();
216     if (!Type)
217       return errorToErrorCode(Type.takeError());
218     if (FunctionOnly && *Type != SymbolRef::ST_Function)
219       continue;
220 
221     Expected<uint64_t> Address = Symbol.getAddress();
222     if (!Address)
223       return errorToErrorCode(Address.takeError());
224     if (*Address == VA)
225       return Symbol;
226   }
227   return inconvertibleErrorCode();
228 }
229 
230 ErrorOr<SymbolRef> Decoder::getRelocatedSymbol(const COFFObjectFile &,
231                                                const SectionRef &Section,
232                                                uint64_t Offset) {
233   for (const auto &Relocation : Section.relocations()) {
234     uint64_t RelocationOffset = Relocation.getOffset();
235     if (RelocationOffset == Offset)
236       return *Relocation.getSymbol();
237   }
238   return inconvertibleErrorCode();
239 }
240 
241 ErrorOr<SymbolRef> Decoder::getSymbolForLocation(
242     const COFFObjectFile &COFF, const SectionRef &Section,
243     uint64_t OffsetInSection, uint64_t ImmediateOffset, uint64_t &SymbolAddress,
244     uint64_t &SymbolOffset, bool FunctionOnly) {
245   // Try to locate a relocation that points at the offset in the section
246   ErrorOr<SymbolRef> SymOrErr =
247       getRelocatedSymbol(COFF, Section, OffsetInSection);
248   if (SymOrErr) {
249     // We found a relocation symbol; the immediate offset needs to be added
250     // to the symbol address.
251     SymbolOffset = ImmediateOffset;
252 
253     Expected<uint64_t> AddressOrErr = SymOrErr->getAddress();
254     if (!AddressOrErr) {
255       std::string Buf;
256       llvm::raw_string_ostream OS(Buf);
257       logAllUnhandledErrors(AddressOrErr.takeError(), OS);
258       OS.flush();
259       report_fatal_error(Buf);
260     }
261     // We apply SymbolOffset here directly. We return it separately to allow
262     // the caller to print it as an offset on the symbol name.
263     SymbolAddress = *AddressOrErr + SymbolOffset;
264   } else {
265     // No matching relocation found; operating on a linked image. Try to
266     // find a descriptive symbol if possible. The immediate offset contains
267     // the image relative address, and we shouldn't add any offset to the
268     // symbol.
269     SymbolAddress = COFF.getImageBase() + ImmediateOffset;
270     SymbolOffset = 0;
271     SymOrErr = getSymbol(COFF, SymbolAddress, FunctionOnly);
272   }
273   return SymOrErr;
274 }
275 
276 bool Decoder::opcode_0xxxxxxx(const uint8_t *OC, unsigned &Offset,
277                               unsigned Length, bool Prologue) {
278   uint8_t Imm = OC[Offset] & 0x7f;
279   SW.startLine() << format("0x%02x                ; %s sp, #(%u * 4)\n",
280                            OC[Offset],
281                            static_cast<const char *>(Prologue ? "sub" : "add"),
282                            Imm);
283   ++Offset;
284   return false;
285 }
286 
287 bool Decoder::opcode_10Lxxxxx(const uint8_t *OC, unsigned &Offset,
288                               unsigned Length, bool Prologue) {
289   unsigned Link = (OC[Offset] & 0x20) >> 5;
290   uint16_t RegisterMask = (Link << (Prologue ? 14 : 15))
291                         | ((OC[Offset + 0] & 0x1f) << 8)
292                         | ((OC[Offset + 1] & 0xff) << 0);
293   assert((~RegisterMask & (1 << 13)) && "sp must not be set");
294   assert((~RegisterMask & (1 << (Prologue ? 15 : 14))) && "pc must not be set");
295 
296   SW.startLine() << format("0x%02x 0x%02x           ; %s.w ",
297                            OC[Offset + 0], OC[Offset + 1],
298                            Prologue ? "push" : "pop");
299   printRegisters(std::make_pair(RegisterMask, 0));
300   OS << '\n';
301 
302   Offset += 2;
303   return false;
304 }
305 
306 bool Decoder::opcode_1100xxxx(const uint8_t *OC, unsigned &Offset,
307                               unsigned Length, bool Prologue) {
308   if (Prologue)
309     SW.startLine() << format("0x%02x                ; mov r%u, sp\n",
310                              OC[Offset], OC[Offset] & 0xf);
311   else
312     SW.startLine() << format("0x%02x                ; mov sp, r%u\n",
313                              OC[Offset], OC[Offset] & 0xf);
314   ++Offset;
315   return false;
316 }
317 
318 bool Decoder::opcode_11010Lxx(const uint8_t *OC, unsigned &Offset,
319                               unsigned Length, bool Prologue) {
320   unsigned Link = (OC[Offset] & 0x4) >> 3;
321   unsigned Count = (OC[Offset] & 0x3);
322 
323   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
324                    | (((1 << (Count + 1)) - 1) << 4);
325 
326   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
327                            Prologue ? "push" : "pop");
328   printRegisters(std::make_pair(GPRMask, 0));
329   OS << '\n';
330 
331   ++Offset;
332   return false;
333 }
334 
335 bool Decoder::opcode_11011Lxx(const uint8_t *OC, unsigned &Offset,
336                               unsigned Length, bool Prologue) {
337   unsigned Link = (OC[Offset] & 0x4) >> 2;
338   unsigned Count = (OC[Offset] & 0x3) + 4;
339 
340   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
341                    | (((1 << (Count + 1)) - 1) << 4);
342 
343   SW.startLine() << format("0x%02x                ; %s.w ", OC[Offset],
344                            Prologue ? "push" : "pop");
345   printRegisters(std::make_pair(GPRMask, 0));
346   OS << '\n';
347 
348   ++Offset;
349   return false;
350 }
351 
352 bool Decoder::opcode_11100xxx(const uint8_t *OC, unsigned &Offset,
353                               unsigned Length, bool Prologue) {
354   unsigned High = (OC[Offset] & 0x7);
355   uint32_t VFPMask = (((1 << (High + 1)) - 1) << 8);
356 
357   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
358                            Prologue ? "vpush" : "vpop");
359   printRegisters(std::make_pair(0, VFPMask));
360   OS << '\n';
361 
362   ++Offset;
363   return false;
364 }
365 
366 bool Decoder::opcode_111010xx(const uint8_t *OC, unsigned &Offset,
367                               unsigned Length, bool Prologue) {
368   uint16_t Imm = ((OC[Offset + 0] & 0x03) << 8) | ((OC[Offset + 1] & 0xff) << 0);
369 
370   SW.startLine() << format("0x%02x 0x%02x           ; %s.w sp, #(%u * 4)\n",
371                            OC[Offset + 0], OC[Offset + 1],
372                            static_cast<const char *>(Prologue ? "sub" : "add"),
373                            Imm);
374 
375   Offset += 2;
376   return false;
377 }
378 
379 bool Decoder::opcode_1110110L(const uint8_t *OC, unsigned &Offset,
380                               unsigned Length, bool Prologue) {
381   uint8_t GPRMask = ((OC[Offset + 0] & 0x01) << (Prologue ? 14 : 15))
382                   | ((OC[Offset + 1] & 0xff) << 0);
383 
384   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
385                            OC[Offset + 1], Prologue ? "push" : "pop");
386   printRegisters(std::make_pair(GPRMask, 0));
387   OS << '\n';
388 
389   Offset += 2;
390   return false;
391 }
392 
393 bool Decoder::opcode_11101110(const uint8_t *OC, unsigned &Offset,
394                               unsigned Length, bool Prologue) {
395   assert(!Prologue && "may not be used in prologue");
396 
397   if (OC[Offset + 1] & 0xf0)
398     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
399                              OC[Offset + 0], OC[Offset +  1]);
400   else
401     SW.startLine()
402       << format("0x%02x 0x%02x           ; microsoft-specific (type: %u)\n",
403                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] & 0x0f);
404 
405   Offset += 2;
406   return false;
407 }
408 
409 bool Decoder::opcode_11101111(const uint8_t *OC, unsigned &Offset,
410                               unsigned Length, bool Prologue) {
411   assert(!Prologue && "may not be used in prologue");
412 
413   if (OC[Offset + 1] & 0xf0)
414     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
415                              OC[Offset + 0], OC[Offset +  1]);
416   else
417     SW.startLine()
418       << format("0x%02x 0x%02x           ; ldr.w lr, [sp], #%u\n",
419                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] << 2);
420 
421   Offset += 2;
422   return false;
423 }
424 
425 bool Decoder::opcode_11110101(const uint8_t *OC, unsigned &Offset,
426                               unsigned Length, bool Prologue) {
427   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
428   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
429   uint32_t VFPMask = ((1 << (End - Start)) - 1) << Start;
430 
431   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
432                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
433   printRegisters(std::make_pair(0, VFPMask));
434   OS << '\n';
435 
436   Offset += 2;
437   return false;
438 }
439 
440 bool Decoder::opcode_11110110(const uint8_t *OC, unsigned &Offset,
441                               unsigned Length, bool Prologue) {
442   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
443   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
444   uint32_t VFPMask = ((1 << (End - Start)) - 1) << 16;
445 
446   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
447                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
448   printRegisters(std::make_pair(0, VFPMask));
449   OS << '\n';
450 
451   Offset += 2;
452   return false;
453 }
454 
455 bool Decoder::opcode_11110111(const uint8_t *OC, unsigned &Offset,
456                               unsigned Length, bool Prologue) {
457   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
458 
459   SW.startLine() << format("0x%02x 0x%02x 0x%02x      ; %s sp, sp, #(%u * 4)\n",
460                            OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
461                            static_cast<const char *>(Prologue ? "sub" : "add"),
462                            Imm);
463 
464   Offset += 3;
465   return false;
466 }
467 
468 bool Decoder::opcode_11111000(const uint8_t *OC, unsigned &Offset,
469                               unsigned Length, bool Prologue) {
470   uint32_t Imm = (OC[Offset + 1] << 16)
471                | (OC[Offset + 2] << 8)
472                | (OC[Offset + 3] << 0);
473 
474   SW.startLine()
475     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s sp, sp, #(%u * 4)\n",
476               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
477               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
478 
479   Offset += 4;
480   return false;
481 }
482 
483 bool Decoder::opcode_11111001(const uint8_t *OC, unsigned &Offset,
484                               unsigned Length, bool Prologue) {
485   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
486 
487   SW.startLine()
488     << format("0x%02x 0x%02x 0x%02x      ; %s.w sp, sp, #(%u * 4)\n",
489               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
490               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
491 
492   Offset += 3;
493   return false;
494 }
495 
496 bool Decoder::opcode_11111010(const uint8_t *OC, unsigned &Offset,
497                               unsigned Length, bool Prologue) {
498   uint32_t Imm = (OC[Offset + 1] << 16)
499                | (OC[Offset + 2] << 8)
500                | (OC[Offset + 3] << 0);
501 
502   SW.startLine()
503     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s.w sp, sp, #(%u * 4)\n",
504               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
505               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
506 
507   Offset += 4;
508   return false;
509 }
510 
511 bool Decoder::opcode_11111011(const uint8_t *OC, unsigned &Offset,
512                               unsigned Length, bool Prologue) {
513   SW.startLine() << format("0x%02x                ; nop\n", OC[Offset]);
514   ++Offset;
515   return false;
516 }
517 
518 bool Decoder::opcode_11111100(const uint8_t *OC, unsigned &Offset,
519                               unsigned Length, bool Prologue) {
520   SW.startLine() << format("0x%02x                ; nop.w\n", OC[Offset]);
521   ++Offset;
522   return false;
523 }
524 
525 bool Decoder::opcode_11111101(const uint8_t *OC, unsigned &Offset,
526                               unsigned Length, bool Prologue) {
527   SW.startLine() << format("0x%02x                ; b\n", OC[Offset]);
528   ++Offset;
529   return true;
530 }
531 
532 bool Decoder::opcode_11111110(const uint8_t *OC, unsigned &Offset,
533                               unsigned Length, bool Prologue) {
534   SW.startLine() << format("0x%02x                ; b.w\n", OC[Offset]);
535   ++Offset;
536   return true;
537 }
538 
539 bool Decoder::opcode_11111111(const uint8_t *OC, unsigned &Offset,
540                               unsigned Length, bool Prologue) {
541   ++Offset;
542   return true;
543 }
544 
545 // ARM64 unwind codes start here.
546 bool Decoder::opcode_alloc_s(const uint8_t *OC, unsigned &Offset,
547                              unsigned Length, bool Prologue) {
548   uint32_t NumBytes = (OC[Offset] & 0x1F) << 4;
549   SW.startLine() << format("0x%02x                ; %s sp, #%u\n", OC[Offset],
550                            static_cast<const char *>(Prologue ? "sub" : "add"),
551                            NumBytes);
552   ++Offset;
553   return false;
554 }
555 
556 bool Decoder::opcode_save_r19r20_x(const uint8_t *OC, unsigned &Offset,
557                                    unsigned Length, bool Prologue) {
558   uint32_t Off = (OC[Offset] & 0x1F) << 3;
559   if (Prologue)
560     SW.startLine() << format(
561         "0x%02x                ; stp x19, x20, [sp, #-%u]!\n", OC[Offset], Off);
562   else
563     SW.startLine() << format(
564         "0x%02x                ; ldp x19, x20, [sp], #%u\n", OC[Offset], Off);
565   ++Offset;
566   return false;
567 }
568 
569 bool Decoder::opcode_save_fplr(const uint8_t *OC, unsigned &Offset,
570                                unsigned Length, bool Prologue) {
571   uint32_t Off = (OC[Offset] & 0x3F) << 3;
572   SW.startLine() << format(
573       "0x%02x                ; %s x29, x30, [sp, #%u]\n", OC[Offset],
574       static_cast<const char *>(Prologue ? "stp" : "ldp"), Off);
575   ++Offset;
576   return false;
577 }
578 
579 bool Decoder::opcode_save_fplr_x(const uint8_t *OC, unsigned &Offset,
580                                  unsigned Length, bool Prologue) {
581   uint32_t Off = ((OC[Offset] & 0x3F) + 1) << 3;
582   if (Prologue)
583     SW.startLine() << format(
584         "0x%02x                ; stp x29, x30, [sp, #-%u]!\n", OC[Offset], Off);
585   else
586     SW.startLine() << format(
587         "0x%02x                ; ldp x29, x30, [sp], #%u\n", OC[Offset], Off);
588   ++Offset;
589   return false;
590 }
591 
592 bool Decoder::opcode_alloc_m(const uint8_t *OC, unsigned &Offset,
593                              unsigned Length, bool Prologue) {
594   uint32_t NumBytes = ((OC[Offset] & 0x07) << 8);
595   NumBytes |= (OC[Offset + 1] & 0xFF);
596   NumBytes <<= 4;
597   SW.startLine() << format("0x%02x%02x              ; %s sp, #%u\n",
598                            OC[Offset], OC[Offset + 1],
599                            static_cast<const char *>(Prologue ? "sub" : "add"),
600                            NumBytes);
601   Offset += 2;
602   return false;
603 }
604 
605 bool Decoder::opcode_save_regp(const uint8_t *OC, unsigned &Offset,
606                                unsigned Length, bool Prologue) {
607   uint32_t Reg = ((OC[Offset] & 0x03) << 8);
608   Reg |= (OC[Offset + 1] & 0xC0);
609   Reg >>= 6;
610   Reg += 19;
611   uint32_t Off = (OC[Offset + 1] & 0x3F) << 3;
612   SW.startLine() << format(
613       "0x%02x%02x              ; %s x%u, x%u, [sp, #%u]\n",
614       OC[Offset], OC[Offset + 1],
615       static_cast<const char *>(Prologue ? "stp" : "ldp"), Reg, Reg + 1, Off);
616   Offset += 2;
617   return false;
618 }
619 
620 bool Decoder::opcode_save_regp_x(const uint8_t *OC, unsigned &Offset,
621                                  unsigned Length, bool Prologue) {
622   uint32_t Reg = ((OC[Offset] & 0x03) << 8);
623   Reg |= (OC[Offset + 1] & 0xC0);
624   Reg >>= 6;
625   Reg += 19;
626   uint32_t Off = ((OC[Offset + 1] & 0x3F) + 1) << 3;
627   if (Prologue)
628     SW.startLine() << format(
629         "0x%02x%02x              ; stp x%u, x%u, [sp, #-%u]!\n",
630         OC[Offset], OC[Offset + 1], Reg,
631         Reg + 1, Off);
632   else
633     SW.startLine() << format(
634         "0x%02x%02x              ; ldp x%u, x%u, [sp], #%u\n",
635         OC[Offset], OC[Offset + 1], Reg,
636         Reg + 1, Off);
637   Offset += 2;
638   return false;
639 }
640 
641 bool Decoder::opcode_save_reg(const uint8_t *OC, unsigned &Offset,
642                               unsigned Length, bool Prologue) {
643   uint32_t Reg = (OC[Offset] & 0x03) << 8;
644   Reg |= (OC[Offset + 1] & 0xC0);
645   Reg >>= 6;
646   Reg += 19;
647   uint32_t Off = (OC[Offset + 1] & 0x3F) << 3;
648   SW.startLine() << format("0x%02x%02x              ; %s x%u, [sp, #%u]\n",
649                            OC[Offset], OC[Offset + 1],
650                            static_cast<const char *>(Prologue ? "str" : "ldr"),
651                            Reg, Off);
652   Offset += 2;
653   return false;
654 }
655 
656 bool Decoder::opcode_save_reg_x(const uint8_t *OC, unsigned &Offset,
657                                 unsigned Length, bool Prologue) {
658   uint32_t Reg = (OC[Offset] & 0x01) << 8;
659   Reg |= (OC[Offset + 1] & 0xE0);
660   Reg >>= 5;
661   Reg += 19;
662   uint32_t Off = ((OC[Offset + 1] & 0x1F) + 1) << 3;
663   if (Prologue)
664     SW.startLine() << format("0x%02x%02x              ; str x%u, [sp, #-%u]!\n",
665                              OC[Offset], OC[Offset + 1], Reg, Off);
666   else
667     SW.startLine() << format("0x%02x%02x              ; ldr x%u, [sp], #%u\n",
668                              OC[Offset], OC[Offset + 1], Reg, Off);
669   Offset += 2;
670   return false;
671 }
672 
673 bool Decoder::opcode_save_lrpair(const uint8_t *OC, unsigned &Offset,
674                                  unsigned Length, bool Prologue) {
675   uint32_t Reg = (OC[Offset] & 0x01) << 8;
676   Reg |= (OC[Offset + 1] & 0xC0);
677   Reg >>= 6;
678   Reg *= 2;
679   Reg += 19;
680   uint32_t Off = (OC[Offset + 1] & 0x3F) << 3;
681   SW.startLine() << format("0x%02x%02x              ; %s x%u, lr, [sp, #%u]\n",
682                            OC[Offset], OC[Offset + 1],
683                            static_cast<const char *>(Prologue ? "stp" : "ldp"),
684                            Reg, Off);
685   Offset += 2;
686   return false;
687 }
688 
689 bool Decoder::opcode_save_fregp(const uint8_t *OC, unsigned &Offset,
690                                 unsigned Length, bool Prologue) {
691   uint32_t Reg = (OC[Offset] & 0x01) << 8;
692   Reg |= (OC[Offset + 1] & 0xC0);
693   Reg >>= 6;
694   Reg += 8;
695   uint32_t Off = (OC[Offset + 1] & 0x3F) << 3;
696   SW.startLine() << format("0x%02x%02x              ; %s d%u, d%u, [sp, #%u]\n",
697                            OC[Offset], OC[Offset + 1],
698                            static_cast<const char *>(Prologue ? "stp" : "ldp"),
699                            Reg, Reg + 1, Off);
700   Offset += 2;
701   return false;
702 }
703 
704 bool Decoder::opcode_save_fregp_x(const uint8_t *OC, unsigned &Offset,
705                                   unsigned Length, bool Prologue) {
706   uint32_t Reg = (OC[Offset] & 0x01) << 8;
707   Reg |= (OC[Offset + 1] & 0xC0);
708   Reg >>= 6;
709   Reg += 8;
710   uint32_t Off = ((OC[Offset + 1] & 0x3F) + 1) << 3;
711   if (Prologue)
712     SW.startLine() << format(
713         "0x%02x%02x              ; stp d%u, d%u, [sp, #-%u]!\n", OC[Offset],
714         OC[Offset + 1], Reg, Reg + 1, Off);
715   else
716     SW.startLine() << format(
717         "0x%02x%02x              ; ldp d%u, d%u, [sp], #%u\n", OC[Offset],
718         OC[Offset + 1], Reg, Reg + 1, Off);
719   Offset += 2;
720   return false;
721 }
722 
723 bool Decoder::opcode_save_freg(const uint8_t *OC, unsigned &Offset,
724                                unsigned Length, bool Prologue) {
725   uint32_t Reg = (OC[Offset] & 0x01) << 8;
726   Reg |= (OC[Offset + 1] & 0xC0);
727   Reg >>= 6;
728   Reg += 8;
729   uint32_t Off = (OC[Offset + 1] & 0x3F) << 3;
730   SW.startLine() << format("0x%02x%02x              ; %s d%u, [sp, #%u]\n",
731                            OC[Offset], OC[Offset + 1],
732                            static_cast<const char *>(Prologue ? "str" : "ldr"),
733                            Reg, Off);
734   Offset += 2;
735   return false;
736 }
737 
738 bool Decoder::opcode_save_freg_x(const uint8_t *OC, unsigned &Offset,
739                                  unsigned Length, bool Prologue) {
740   uint32_t Reg = ((OC[Offset + 1] & 0xE0) >> 5) + 8;
741   uint32_t Off = ((OC[Offset + 1] & 0x1F) + 1) << 3;
742   if (Prologue)
743     SW.startLine() << format(
744         "0x%02x%02x              ; str d%u, [sp, #-%u]!\n", OC[Offset],
745         OC[Offset + 1], Reg, Off);
746   else
747     SW.startLine() << format(
748         "0x%02x%02x              ; ldr d%u, [sp], #%u\n", OC[Offset],
749         OC[Offset + 1], Reg, Off);
750   Offset += 2;
751   return false;
752 }
753 
754 bool Decoder::opcode_alloc_l(const uint8_t *OC, unsigned &Offset,
755                              unsigned Length, bool Prologue) {
756   unsigned Off =
757       (OC[Offset + 1] << 16) | (OC[Offset + 2] << 8) | (OC[Offset + 3] << 0);
758   Off <<= 4;
759   SW.startLine() << format(
760       "0x%02x%02x%02x%02x          ; %s sp, #%u\n", OC[Offset], OC[Offset + 1],
761       OC[Offset + 2], OC[Offset + 3],
762       static_cast<const char *>(Prologue ? "sub" : "add"), Off);
763   Offset += 4;
764   return false;
765 }
766 
767 bool Decoder::opcode_setfp(const uint8_t *OC, unsigned &Offset, unsigned Length,
768                            bool Prologue) {
769   SW.startLine() << format("0x%02x                ; mov %s, %s\n", OC[Offset],
770                            static_cast<const char *>(Prologue ? "fp" : "sp"),
771                            static_cast<const char *>(Prologue ? "sp" : "fp"));
772   ++Offset;
773   return false;
774 }
775 
776 bool Decoder::opcode_addfp(const uint8_t *OC, unsigned &Offset, unsigned Length,
777                            bool Prologue) {
778   unsigned NumBytes = OC[Offset + 1] << 3;
779   SW.startLine() << format(
780       "0x%02x%02x              ; %s %s, %s, #%u\n", OC[Offset], OC[Offset + 1],
781       static_cast<const char *>(Prologue ? "add" : "sub"),
782       static_cast<const char *>(Prologue ? "fp" : "sp"),
783       static_cast<const char *>(Prologue ? "sp" : "fp"), NumBytes);
784   Offset += 2;
785   return false;
786 }
787 
788 bool Decoder::opcode_nop(const uint8_t *OC, unsigned &Offset, unsigned Length,
789                          bool Prologue) {
790   SW.startLine() << format("0x%02x                ; nop\n", OC[Offset]);
791   ++Offset;
792   return false;
793 }
794 
795 bool Decoder::opcode_end(const uint8_t *OC, unsigned &Offset, unsigned Length,
796                          bool Prologue) {
797   SW.startLine() << format("0x%02x                ; end\n", OC[Offset]);
798   ++Offset;
799   return true;
800 }
801 
802 bool Decoder::opcode_end_c(const uint8_t *OC, unsigned &Offset, unsigned Length,
803                            bool Prologue) {
804   SW.startLine() << format("0x%02x                ; end_c\n", OC[Offset]);
805   ++Offset;
806   return true;
807 }
808 
809 bool Decoder::opcode_save_next(const uint8_t *OC, unsigned &Offset,
810                                unsigned Length, bool Prologue) {
811   if (Prologue)
812     SW.startLine() << format("0x%02x                ; save next\n", OC[Offset]);
813   else
814     SW.startLine() << format("0x%02x                ; restore next\n",
815                              OC[Offset]);
816   ++Offset;
817   return false;
818 }
819 
820 bool Decoder::opcode_trap_frame(const uint8_t *OC, unsigned &Offset,
821                                 unsigned Length, bool Prologue) {
822   SW.startLine() << format("0x%02x                ; trap frame\n", OC[Offset]);
823   ++Offset;
824   return false;
825 }
826 
827 bool Decoder::opcode_machine_frame(const uint8_t *OC, unsigned &Offset,
828                                    unsigned Length, bool Prologue) {
829   SW.startLine() << format("0x%02x                ; machine frame\n",
830                            OC[Offset]);
831   ++Offset;
832   return false;
833 }
834 
835 bool Decoder::opcode_context(const uint8_t *OC, unsigned &Offset,
836                              unsigned Length, bool Prologue) {
837   SW.startLine() << format("0x%02x                ; context\n", OC[Offset]);
838   ++Offset;
839   return false;
840 }
841 
842 bool Decoder::opcode_clear_unwound_to_call(const uint8_t *OC, unsigned &Offset,
843                                            unsigned Length, bool Prologue) {
844   SW.startLine() << format("0x%02x                ; clear unwound to call\n",
845                            OC[Offset]);
846   ++Offset;
847   return false;
848 }
849 
850 void Decoder::decodeOpcodes(ArrayRef<uint8_t> Opcodes, unsigned Offset,
851                             bool Prologue) {
852   assert((!Prologue || Offset == 0) && "prologue should always use offset 0");
853   const RingEntry* DecodeRing = isAArch64 ? Ring64 : Ring;
854   bool Terminated = false;
855   for (unsigned OI = Offset, OE = Opcodes.size(); !Terminated && OI < OE; ) {
856     for (unsigned DI = 0;; ++DI) {
857       if ((isAArch64 && (DI >= array_lengthof(Ring64))) ||
858           (!isAArch64 && (DI >= array_lengthof(Ring)))) {
859         SW.startLine() << format("0x%02x                ; Bad opcode!\n",
860                                  Opcodes.data()[OI]);
861         ++OI;
862         break;
863       }
864 
865       if ((Opcodes[OI] & DecodeRing[DI].Mask) == DecodeRing[DI].Value) {
866         if (OI + DecodeRing[DI].Length > OE) {
867           SW.startLine() << format("Opcode 0x%02x goes past the unwind data\n",
868                                     Opcodes[OI]);
869           OI += DecodeRing[DI].Length;
870           break;
871         }
872         Terminated =
873             (this->*DecodeRing[DI].Routine)(Opcodes.data(), OI, 0, Prologue);
874         break;
875       }
876     }
877   }
878 }
879 
880 bool Decoder::dumpXDataRecord(const COFFObjectFile &COFF,
881                               const SectionRef &Section,
882                               uint64_t FunctionAddress, uint64_t VA) {
883   ArrayRef<uint8_t> Contents;
884   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
885     return false;
886 
887   uint64_t SectionVA = Section.getAddress();
888   uint64_t Offset = VA - SectionVA;
889   const ulittle32_t *Data =
890     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
891 
892   // Sanity check to ensure that the .xdata header is present.
893   // A header is one or two words, followed by at least one word to describe
894   // the unwind codes. Applicable to both ARM and AArch64.
895   if (Contents.size() - Offset < 8)
896     report_fatal_error(".xdata must be at least 8 bytes in size");
897 
898   const ExceptionDataRecord XData(Data, isAArch64);
899   DictScope XRS(SW, "ExceptionData");
900   SW.printNumber("FunctionLength",
901                  isAArch64 ? XData.FunctionLengthInBytesAArch64() :
902                  XData.FunctionLengthInBytesARM());
903   SW.printNumber("Version", XData.Vers());
904   SW.printBoolean("ExceptionData", XData.X());
905   SW.printBoolean("EpiloguePacked", XData.E());
906   if (!isAArch64)
907     SW.printBoolean("Fragment", XData.F());
908   SW.printNumber(XData.E() ? "EpilogueOffset" : "EpilogueScopes",
909                  XData.EpilogueCount());
910   uint64_t ByteCodeLength = XData.CodeWords() * sizeof(uint32_t);
911   SW.printNumber("ByteCodeLength", ByteCodeLength);
912 
913   if ((int64_t)(Contents.size() - Offset - 4 * HeaderWords(XData) -
914                 (XData.E() ? 0 : XData.EpilogueCount() * 4) -
915                 (XData.X() ? 8 : 0)) < (int64_t)ByteCodeLength) {
916     SW.flush();
917     report_fatal_error("Malformed unwind data");
918   }
919 
920   if (XData.E()) {
921     ArrayRef<uint8_t> UC = XData.UnwindByteCode();
922     if (isAArch64 || !XData.F()) {
923       ListScope PS(SW, "Prologue");
924       decodeOpcodes(UC, 0, /*Prologue=*/true);
925     }
926     if (XData.EpilogueCount()) {
927       ListScope ES(SW, "Epilogue");
928       decodeOpcodes(UC, XData.EpilogueCount(), /*Prologue=*/false);
929     }
930   } else {
931     {
932       ListScope PS(SW, "Prologue");
933       decodeOpcodes(XData.UnwindByteCode(), 0, /*Prologue=*/true);
934     }
935     ArrayRef<ulittle32_t> EpilogueScopes = XData.EpilogueScopes();
936     ListScope ESS(SW, "EpilogueScopes");
937     for (const EpilogueScope ES : EpilogueScopes) {
938       DictScope ESES(SW, "EpilogueScope");
939       SW.printNumber("StartOffset", ES.EpilogueStartOffset());
940       if (!isAArch64)
941         SW.printNumber("Condition", ES.Condition());
942       SW.printNumber("EpilogueStartIndex",
943                      isAArch64 ? ES.EpilogueStartIndexAArch64()
944                                : ES.EpilogueStartIndexARM());
945       if (ES.ES & ~0xffc3ffff)
946         SW.printNumber("ReservedBits", (ES.ES >> 18) & 0xF);
947 
948       ListScope Opcodes(SW, "Opcodes");
949       decodeOpcodes(XData.UnwindByteCode(),
950                     isAArch64 ? ES.EpilogueStartIndexAArch64()
951                               : ES.EpilogueStartIndexARM(),
952                     /*Prologue=*/false);
953     }
954   }
955 
956   if (XData.X()) {
957     const uint32_t Parameter = XData.ExceptionHandlerParameter();
958     const size_t HandlerOffset = HeaderWords(XData) +
959                                  (XData.E() ? 0 : XData.EpilogueCount()) +
960                                  XData.CodeWords();
961 
962     uint64_t Address, SymbolOffset;
963     ErrorOr<SymbolRef> Symbol = getSymbolForLocation(
964         COFF, Section, Offset + HandlerOffset * sizeof(uint32_t),
965         XData.ExceptionHandlerRVA(), Address, SymbolOffset,
966         /*FunctionOnly=*/true);
967     if (!Symbol) {
968       ListScope EHS(SW, "ExceptionHandler");
969       SW.printHex("Routine", Address);
970       SW.printHex("Parameter", Parameter);
971       return true;
972     }
973 
974     Expected<StringRef> Name = Symbol->getName();
975     if (!Name) {
976       std::string Buf;
977       llvm::raw_string_ostream OS(Buf);
978       logAllUnhandledErrors(Name.takeError(), OS);
979       OS.flush();
980       report_fatal_error(Buf);
981     }
982 
983     ListScope EHS(SW, "ExceptionHandler");
984     SW.printString("Routine", formatSymbol(*Name, Address, SymbolOffset));
985     SW.printHex("Parameter", Parameter);
986   }
987 
988   return true;
989 }
990 
991 bool Decoder::dumpUnpackedEntry(const COFFObjectFile &COFF,
992                                 const SectionRef Section, uint64_t Offset,
993                                 unsigned Index, const RuntimeFunction &RF) {
994   assert(RF.Flag() == RuntimeFunctionFlag::RFF_Unpacked &&
995          "packed entry cannot be treated as an unpacked entry");
996 
997   uint64_t FunctionAddress, FunctionOffset;
998   ErrorOr<SymbolRef> Function = getSymbolForLocation(
999       COFF, Section, Offset, RF.BeginAddress, FunctionAddress, FunctionOffset,
1000       /*FunctionOnly=*/true);
1001 
1002   uint64_t XDataAddress, XDataOffset;
1003   ErrorOr<SymbolRef> XDataRecord = getSymbolForLocation(
1004       COFF, Section, Offset + 4, RF.ExceptionInformationRVA(), XDataAddress,
1005       XDataOffset);
1006 
1007   if (!RF.BeginAddress && !Function)
1008     return false;
1009   if (!RF.UnwindData && !XDataRecord)
1010     return false;
1011 
1012   StringRef FunctionName;
1013   if (Function) {
1014     Expected<StringRef> FunctionNameOrErr = Function->getName();
1015     if (!FunctionNameOrErr) {
1016       std::string Buf;
1017       llvm::raw_string_ostream OS(Buf);
1018       logAllUnhandledErrors(FunctionNameOrErr.takeError(), OS);
1019       OS.flush();
1020       report_fatal_error(Buf);
1021     }
1022     FunctionName = *FunctionNameOrErr;
1023   }
1024 
1025   SW.printString("Function",
1026                  formatSymbol(FunctionName, FunctionAddress, FunctionOffset));
1027 
1028   if (XDataRecord) {
1029     Expected<StringRef> Name = XDataRecord->getName();
1030     if (!Name) {
1031       std::string Buf;
1032       llvm::raw_string_ostream OS(Buf);
1033       logAllUnhandledErrors(Name.takeError(), OS);
1034       OS.flush();
1035       report_fatal_error(Buf);
1036     }
1037 
1038     SW.printString("ExceptionRecord",
1039                    formatSymbol(*Name, XDataAddress, XDataOffset));
1040 
1041     Expected<section_iterator> SIOrErr = XDataRecord->getSection();
1042     if (!SIOrErr) {
1043       // TODO: Actually report errors helpfully.
1044       consumeError(SIOrErr.takeError());
1045       return false;
1046     }
1047     section_iterator SI = *SIOrErr;
1048 
1049     return dumpXDataRecord(COFF, *SI, FunctionAddress, XDataAddress);
1050   } else {
1051     SW.printString("ExceptionRecord", formatSymbol("", XDataAddress));
1052 
1053     ErrorOr<SectionRef> Section = getSectionContaining(COFF, XDataAddress);
1054     if (!Section)
1055       return false;
1056 
1057     return dumpXDataRecord(COFF, *Section, FunctionAddress, XDataAddress);
1058   }
1059 }
1060 
1061 bool Decoder::dumpPackedEntry(const object::COFFObjectFile &COFF,
1062                               const SectionRef Section, uint64_t Offset,
1063                               unsigned Index, const RuntimeFunction &RF) {
1064   assert((RF.Flag() == RuntimeFunctionFlag::RFF_Packed ||
1065           RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
1066          "unpacked entry cannot be treated as a packed entry");
1067 
1068   uint64_t FunctionAddress, FunctionOffset;
1069   ErrorOr<SymbolRef> Function = getSymbolForLocation(
1070       COFF, Section, Offset, RF.BeginAddress, FunctionAddress, FunctionOffset,
1071       /*FunctionOnly=*/true);
1072 
1073   StringRef FunctionName;
1074   if (Function) {
1075     Expected<StringRef> FunctionNameOrErr = Function->getName();
1076     if (!FunctionNameOrErr) {
1077       std::string Buf;
1078       llvm::raw_string_ostream OS(Buf);
1079       logAllUnhandledErrors(FunctionNameOrErr.takeError(), OS);
1080       OS.flush();
1081       report_fatal_error(Buf);
1082     }
1083     FunctionName = *FunctionNameOrErr;
1084   }
1085 
1086   SW.printString("Function",
1087                  formatSymbol(FunctionName, FunctionAddress, FunctionOffset));
1088   if (!isAArch64)
1089     SW.printBoolean("Fragment",
1090                     RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment);
1091   SW.printNumber("FunctionLength", RF.FunctionLength());
1092   SW.startLine() << "ReturnType: " << RF.Ret() << '\n';
1093   SW.printBoolean("HomedParameters", RF.H());
1094   SW.startLine() << "SavedRegisters: ";
1095                  printRegisters(SavedRegisterMask(RF));
1096   OS << '\n';
1097   SW.printNumber("StackAdjustment", StackAdjustment(RF) << 2);
1098 
1099   return true;
1100 }
1101 
1102 bool Decoder::dumpPackedARM64Entry(const object::COFFObjectFile &COFF,
1103                                    const SectionRef Section, uint64_t Offset,
1104                                    unsigned Index,
1105                                    const RuntimeFunctionARM64 &RF) {
1106   assert((RF.Flag() == RuntimeFunctionFlag::RFF_Packed ||
1107           RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
1108          "unpacked entry cannot be treated as a packed entry");
1109 
1110   uint64_t FunctionAddress, FunctionOffset;
1111   ErrorOr<SymbolRef> Function = getSymbolForLocation(
1112       COFF, Section, Offset, RF.BeginAddress, FunctionAddress, FunctionOffset,
1113       /*FunctionOnly=*/true);
1114 
1115   StringRef FunctionName;
1116   if (Function) {
1117     Expected<StringRef> FunctionNameOrErr = Function->getName();
1118     if (!FunctionNameOrErr) {
1119       std::string Buf;
1120       llvm::raw_string_ostream OS(Buf);
1121       logAllUnhandledErrors(FunctionNameOrErr.takeError(), OS);
1122       OS.flush();
1123       report_fatal_error(Buf);
1124     }
1125     FunctionName = *FunctionNameOrErr;
1126   }
1127 
1128   SW.printString("Function",
1129                  formatSymbol(FunctionName, FunctionAddress, FunctionOffset));
1130   SW.printBoolean("Fragment",
1131                   RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment);
1132   SW.printNumber("FunctionLength", RF.FunctionLength());
1133   SW.printNumber("RegF", RF.RegF());
1134   SW.printNumber("RegI", RF.RegI());
1135   SW.printBoolean("HomedParameters", RF.H());
1136   SW.printNumber("CR", RF.CR());
1137   SW.printNumber("FrameSize", RF.FrameSize() << 4);
1138   ListScope PS(SW, "Prologue");
1139 
1140   // Synthesize the equivalent prologue according to the documentation
1141   // at https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling,
1142   // printed in reverse order compared to the docs, to match how prologues
1143   // are printed for the non-packed case.
1144   int IntSZ = 8 * RF.RegI();
1145   if (RF.CR() == 1)
1146     IntSZ += 8;
1147   int FpSZ = 8 * RF.RegF();
1148   if (RF.RegF())
1149     FpSZ += 8;
1150   int SavSZ = (IntSZ + FpSZ + 8 * 8 * RF.H() + 0xf) & ~0xf;
1151   int LocSZ = (RF.FrameSize() << 4) - SavSZ;
1152 
1153   if (RF.CR() == 3) {
1154     SW.startLine() << "mov x29, sp\n";
1155     if (LocSZ <= 512) {
1156       SW.startLine() << format("stp x29, lr, [sp, #-%d]!\n", LocSZ);
1157     } else {
1158       SW.startLine() << "stp x29, lr, [sp, #0]\n";
1159     }
1160   }
1161   if (LocSZ > 4080) {
1162     SW.startLine() << format("sub sp, sp, #%d\n", LocSZ - 4080);
1163     SW.startLine() << "sub sp, sp, #4080\n";
1164   } else if ((RF.CR() != 3 && LocSZ > 0) || LocSZ > 512) {
1165     SW.startLine() << format("sub sp, sp, #%d\n", LocSZ);
1166   }
1167   if (RF.H()) {
1168     SW.startLine() << format("stp x6, x7, [sp, #%d]\n", IntSZ + FpSZ + 48);
1169     SW.startLine() << format("stp x4, x5, [sp, #%d]\n", IntSZ + FpSZ + 32);
1170     SW.startLine() << format("stp x2, x3, [sp, #%d]\n", IntSZ + FpSZ + 16);
1171     if (RF.RegI() > 0 || RF.RegF() > 0 || RF.CR() == 1) {
1172       SW.startLine() << format("stp x0, x1, [sp, #%d]\n", IntSZ + FpSZ);
1173     } else {
1174       // This case isn't documented; if neither RegI nor RegF nor CR=1
1175       // have decremented the stack pointer by SavSZ, we need to do it here
1176       // (as the final stack adjustment of LocSZ excludes SavSZ).
1177       SW.startLine() << format("stp x0, x1, [sp, #-%d]!\n", SavSZ);
1178     }
1179   }
1180   int FloatRegs = RF.RegF() > 0 ? RF.RegF() + 1 : 0;
1181   for (int I = (FloatRegs + 1) / 2 - 1; I >= 0; I--) {
1182     if (I == (FloatRegs + 1) / 2 - 1 && FloatRegs % 2 == 1) {
1183       // The last register, an odd register without a pair
1184       SW.startLine() << format("str d%d, [sp, #%d]\n", 8 + 2 * I,
1185                                IntSZ + 16 * I);
1186     } else if (I == 0 && RF.RegI() == 0 && RF.CR() != 1) {
1187       SW.startLine() << format("stp d%d, d%d, [sp, #-%d]!\n", 8 + 2 * I,
1188                                8 + 2 * I + 1, SavSZ);
1189     } else {
1190       SW.startLine() << format("stp d%d, d%d, [sp, #%d]\n", 8 + 2 * I,
1191                                8 + 2 * I + 1, IntSZ + 16 * I);
1192     }
1193   }
1194   if (RF.CR() == 1 && (RF.RegI() % 2) == 0) {
1195     if (RF.RegI() == 0)
1196       SW.startLine() << format("str lr, [sp, #-%d]!\n", SavSZ);
1197     else
1198       SW.startLine() << format("str lr, [sp, #%d]\n", IntSZ - 8);
1199   }
1200   for (int I = (RF.RegI() + 1) / 2 - 1; I >= 0; I--) {
1201     if (I == (RF.RegI() + 1) / 2 - 1 && RF.RegI() % 2 == 1) {
1202       // The last register, an odd register without a pair
1203       if (RF.CR() == 1) {
1204         if (I == 0) { // If this is the only register pair
1205           // CR=1 combined with RegI=1 doesn't map to a documented case;
1206           // it doesn't map to any regular unwind info opcode, and the
1207           // actual unwinder doesn't support it.
1208           SW.startLine() << "INVALID!\n";
1209         } else
1210           SW.startLine() << format("stp x%d, lr, [sp, #%d]\n", 19 + 2 * I,
1211                                    16 * I);
1212       } else {
1213         if (I == 0)
1214           SW.startLine() << format("str x%d, [sp, #-%d]!\n", 19 + 2 * I, SavSZ);
1215         else
1216           SW.startLine() << format("str x%d, [sp, #%d]\n", 19 + 2 * I, 16 * I);
1217       }
1218     } else if (I == 0) {
1219       // The first register pair
1220       SW.startLine() << format("stp x19, x20, [sp, #-%d]!\n", SavSZ);
1221     } else {
1222       SW.startLine() << format("stp x%d, x%d, [sp, #%d]\n", 19 + 2 * I,
1223                                19 + 2 * I + 1, 16 * I);
1224     }
1225   }
1226   SW.startLine() << "end\n";
1227 
1228   return true;
1229 }
1230 
1231 bool Decoder::dumpProcedureDataEntry(const COFFObjectFile &COFF,
1232                                      const SectionRef Section, unsigned Index,
1233                                      ArrayRef<uint8_t> Contents) {
1234   uint64_t Offset = PDataEntrySize * Index;
1235   const ulittle32_t *Data =
1236     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
1237 
1238   const RuntimeFunction Entry(Data);
1239   DictScope RFS(SW, "RuntimeFunction");
1240   if (Entry.Flag() == RuntimeFunctionFlag::RFF_Unpacked)
1241     return dumpUnpackedEntry(COFF, Section, Offset, Index, Entry);
1242   if (isAArch64) {
1243     const RuntimeFunctionARM64 EntryARM64(Data);
1244     return dumpPackedARM64Entry(COFF, Section, Offset, Index, EntryARM64);
1245   }
1246   return dumpPackedEntry(COFF, Section, Offset, Index, Entry);
1247 }
1248 
1249 void Decoder::dumpProcedureData(const COFFObjectFile &COFF,
1250                                 const SectionRef Section) {
1251   ArrayRef<uint8_t> Contents;
1252   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
1253     return;
1254 
1255   if (Contents.size() % PDataEntrySize) {
1256     errs() << ".pdata content is not " << PDataEntrySize << "-byte aligned\n";
1257     return;
1258   }
1259 
1260   for (unsigned EI = 0, EE = Contents.size() / PDataEntrySize; EI < EE; ++EI)
1261     if (!dumpProcedureDataEntry(COFF, Section, EI, Contents))
1262       break;
1263 }
1264 
1265 Error Decoder::dumpProcedureData(const COFFObjectFile &COFF) {
1266   for (const auto &Section : COFF.sections()) {
1267     Expected<StringRef> NameOrErr =
1268         COFF.getSectionName(COFF.getCOFFSection(Section));
1269     if (!NameOrErr)
1270       return NameOrErr.takeError();
1271 
1272     if (NameOrErr->startswith(".pdata"))
1273       dumpProcedureData(COFF, Section);
1274   }
1275   return Error::success();
1276 }
1277 }
1278 }
1279 }
1280