Introduce a string_ostream string builder facilty
[oota-llvm.git] / tools / llvm-readobj / ARMWinEHPrinter.cpp
1 //===-- ARMWinEHPrinter.cpp - Windows on ARM EH Data Printer ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // Windows on ARM uses a series of serialised data structures (RuntimeFunction)
11 // to create a table of information for unwinding.  In order to conserve space,
12 // there are two different ways that this data is represented.
13 //
14 // For functions with canonical forms for the prologue and epilogue, the data
15 // can be stored in a "packed" form.  In this case, the data is packed into the
16 // RuntimeFunction's remaining 30-bits and can fully describe the entire frame.
17 //
18 //        +---------------------------------------+
19 //        |         Function Entry Address        |
20 //        +---------------------------------------+
21 //        |           Packed Form Data            |
22 //        +---------------------------------------+
23 //
24 // This layout is parsed by Decoder::dumpPackedEntry.  No unwind bytecode is
25 // associated with such a frame as they can be derived from the provided data.
26 // The decoder does not synthesize this data as it is unnecessary for the
27 // purposes of validation, with the synthesis being required only by a proper
28 // unwinder.
29 //
30 // For functions that are large or do not match canonical forms, the data is
31 // split up into two portions, with the actual data residing in the "exception
32 // data" table (.xdata) with a reference to the entry from the "procedure data"
33 // (.pdata) entry.
34 //
35 // The exception data contains information about the frame setup, all of the
36 // epilouge scopes (for functions for which there are multiple exit points) and
37 // the associated exception handler.  Additionally, the entry contains byte-code
38 // describing how to unwind the function (c.f. Decoder::decodeOpcodes).
39 //
40 //        +---------------------------------------+
41 //        |         Function Entry Address        |
42 //        +---------------------------------------+
43 //        |      Exception Data Entry Address     |
44 //        +---------------------------------------+
45 //
46 // This layout is parsed by Decoder::dumpUnpackedEntry.  Such an entry must
47 // first resolve the exception data entry address.  This structure
48 // (ExceptionDataRecord) has a variable sized header
49 // (c.f. ARM::WinEH::HeaderWords) and encodes most of the same information as
50 // the packed form.  However, because this information is insufficient to
51 // synthesize the unwinding, there are associated unwinding bytecode which make
52 // up the bulk of the Decoder.
53 //
54 // The decoder itself is table-driven, using the first byte to determine the
55 // opcode and dispatching to the associated printing routine.  The bytecode
56 // itself is a variable length instruction encoding that can fully describe the
57 // state of the stack and the necessary operations for unwinding to the
58 // beginning of the frame.
59 //
60 // The byte-code maintains a 1-1 instruction mapping, indicating both the width
61 // of the instruction (Thumb2 instructions are variable length, 16 or 32 bits
62 // wide) allowing the program to unwind from any point in the prologue, body, or
63 // epilogue of the function.
64
65 #include "ARMWinEHPrinter.h"
66 #include "Error.h"
67 #include "llvm/ADT/StringExtras.h"
68 #include "llvm/ADT/STLExtras.h"
69 #include "llvm/Support/ARMWinEH.h"
70 #include "llvm/Support/Format.h"
71
72 using namespace llvm;
73 using namespace llvm::object;
74 using namespace llvm::support;
75
76 namespace llvm {
77 raw_ostream &operator<<(raw_ostream &OS, const ARM::WinEH::ReturnType &RT) {
78   switch (RT) {
79   case ARM::WinEH::ReturnType::RT_POP:
80     OS << "pop {pc}";
81     break;
82   case ARM::WinEH::ReturnType::RT_B:
83     OS << "b target";
84     break;
85   case ARM::WinEH::ReturnType::RT_BW:
86     OS << "b.w target";
87     break;
88   case ARM::WinEH::ReturnType::RT_NoEpilogue:
89     OS << "(no epilogue)";
90     break;
91   }
92   return OS;
93 }
94 }
95
96 static std::string formatSymbol(StringRef Name, uint64_t Address,
97                                 uint64_t Offset = 0) {
98   string_ostream OS;
99
100   if (!Name.empty())
101     OS << Name << " ";
102
103   if (Offset)
104     OS << format("+0x%X (0x%" PRIX64 ")", Offset, Address);
105   else if (!Name.empty())
106     OS << format("(0x%" PRIX64 ")", Address);
107   else
108     OS << format("0x%" PRIX64, Address);
109
110   return OS.str();
111 }
112
113 namespace llvm {
114 namespace ARM {
115 namespace WinEH {
116 const size_t Decoder::PDataEntrySize = sizeof(RuntimeFunction);
117
118 // TODO name the uops more appropriately
119 const Decoder::RingEntry Decoder::Ring[] = {
120   { 0x80, 0x00, &Decoder::opcode_0xxxxxxx },  // UOP_STACK_FREE (16-bit)
121   { 0xc0, 0x80, &Decoder::opcode_10Lxxxxx },  // UOP_POP (32-bit)
122   { 0xf0, 0xc0, &Decoder::opcode_1100xxxx },  // UOP_STACK_SAVE (16-bit)
123   { 0xf8, 0xd0, &Decoder::opcode_11010Lxx },  // UOP_POP (16-bit)
124   { 0xf8, 0xd8, &Decoder::opcode_11011Lxx },  // UOP_POP (32-bit)
125   { 0xf8, 0xe0, &Decoder::opcode_11100xxx },  // UOP_VPOP (32-bit)
126   { 0xfc, 0xe8, &Decoder::opcode_111010xx },  // UOP_STACK_FREE (32-bit)
127   { 0xfe, 0xec, &Decoder::opcode_1110110L },  // UOP_POP (16-bit)
128   { 0xff, 0xee, &Decoder::opcode_11101110 },  // UOP_MICROSOFT_SPECIFIC (16-bit)
129                                               // UOP_PUSH_MACHINE_FRAME
130                                               // UOP_PUSH_CONTEXT
131                                               // UOP_PUSH_TRAP_FRAME
132                                               // UOP_REDZONE_RESTORE_LR
133   { 0xff, 0xef, &Decoder::opcode_11101111 },  // UOP_LDRPC_POSTINC (32-bit)
134   { 0xff, 0xf5, &Decoder::opcode_11110101 },  // UOP_VPOP (32-bit)
135   { 0xff, 0xf6, &Decoder::opcode_11110110 },  // UOP_VPOP (32-bit)
136   { 0xff, 0xf7, &Decoder::opcode_11110111 },  // UOP_STACK_RESTORE (16-bit)
137   { 0xff, 0xf8, &Decoder::opcode_11111000 },  // UOP_STACK_RESTORE (16-bit)
138   { 0xff, 0xf9, &Decoder::opcode_11111001 },  // UOP_STACK_RESTORE (32-bit)
139   { 0xff, 0xfa, &Decoder::opcode_11111010 },  // UOP_STACK_RESTORE (32-bit)
140   { 0xff, 0xfb, &Decoder::opcode_11111011 },  // UOP_NOP (16-bit)
141   { 0xff, 0xfc, &Decoder::opcode_11111100 },  // UOP_NOP (32-bit)
142   { 0xff, 0xfd, &Decoder::opcode_11111101 },  // UOP_NOP (16-bit) / END
143   { 0xff, 0xfe, &Decoder::opcode_11111110 },  // UOP_NOP (32-bit) / END
144   { 0xff, 0xff, &Decoder::opcode_11111111 },  // UOP_END
145 };
146
147 void Decoder::printRegisters(const std::pair<uint16_t, uint32_t> &RegisterMask) {
148   static const char * const GPRRegisterNames[16] = {
149     "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
150     "r11", "ip", "sp", "lr", "pc",
151   };
152
153   const uint16_t GPRMask = std::get<0>(RegisterMask);
154   const uint16_t VFPMask = std::get<1>(RegisterMask);
155
156   OS << '{';
157   bool Comma = false;
158   for (unsigned RI = 0, RE = 11; RI < RE; ++RI) {
159     if (GPRMask & (1 << RI)) {
160       if (Comma)
161         OS << ", ";
162       OS << GPRRegisterNames[RI];
163       Comma = true;
164     }
165   }
166   for (unsigned RI = 0, RE = 32; RI < RE; ++RI) {
167     if (VFPMask & (1 << RI)) {
168       if (Comma)
169         OS << ", ";
170       OS << "d" << unsigned(RI);
171       Comma = true;
172     }
173   }
174   for (unsigned RI = 11, RE = 16; RI < RE; ++RI) {
175     if (GPRMask & (1 << RI)) {
176       if (Comma)
177         OS << ", ";
178       OS << GPRRegisterNames[RI];
179       Comma = true;
180     }
181   }
182   OS << '}';
183 }
184
185 ErrorOr<object::SectionRef>
186 Decoder::getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) {
187   for (const auto &Section : COFF.sections()) {
188     uint64_t Address;
189     uint64_t Size;
190
191     if (std::error_code EC = Section.getAddress(Address))
192       return EC;
193     if (std::error_code EC = Section.getSize(Size))
194       return EC;
195
196     if (VA >= Address && (VA - Address) <= Size)
197       return Section;
198   }
199   return readobj_error::unknown_symbol;
200 }
201
202 ErrorOr<object::SymbolRef> Decoder::getSymbol(const COFFObjectFile &COFF,
203                                               uint64_t VA, bool FunctionOnly) {
204   for (const auto &Symbol : COFF.symbols()) {
205     if (FunctionOnly) {
206       SymbolRef::Type Type;
207       if (std::error_code EC = Symbol.getType(Type))
208         return EC;
209       if (Type != SymbolRef::ST_Function)
210         continue;
211     }
212
213     uint64_t Address;
214     if (std::error_code EC = Symbol.getAddress(Address))
215       return EC;
216     if (Address == VA)
217       return Symbol;
218   }
219   return readobj_error::unknown_symbol;
220 }
221
222 ErrorOr<SymbolRef> Decoder::getRelocatedSymbol(const COFFObjectFile &,
223                                                const SectionRef &Section,
224                                                uint64_t Offset) {
225   for (const auto &Relocation : Section.relocations()) {
226     uint64_t RelocationOffset;
227     if (auto Error = Relocation.getOffset(RelocationOffset))
228       return Error;
229     if (RelocationOffset == Offset)
230       return *Relocation.getSymbol();
231   }
232   return readobj_error::unknown_symbol;
233 }
234
235 bool Decoder::opcode_0xxxxxxx(const ulittle8_t *OC, unsigned &Offset,
236                               unsigned Length, bool Prologue) {
237   uint8_t Imm = OC[Offset] & 0x7f;
238   SW.startLine() << format("0x%02x                ; %s sp, #(%u * 4)\n",
239                            OC[Offset],
240                            static_cast<const char *>(Prologue ? "sub" : "add"),
241                            Imm);
242   ++Offset;
243   return false;
244 }
245
246 bool Decoder::opcode_10Lxxxxx(const ulittle8_t *OC, unsigned &Offset,
247                               unsigned Length, bool Prologue) {
248   unsigned Link = (OC[Offset] & 0x20) >> 5;
249   uint16_t RegisterMask = (Link << (Prologue ? 14 : 15))
250                         | ((OC[Offset + 0] & 0x1f) << 8)
251                         | ((OC[Offset + 1] & 0xff) << 0);
252   assert((~RegisterMask & (1 << 13)) && "sp must not be set");
253   assert((~RegisterMask & (1 << (Prologue ? 15 : 14))) && "pc must not be set");
254
255   SW.startLine() << format("0x%02x 0x%02x           ; %s.w ",
256                            OC[Offset + 0], OC[Offset + 1],
257                            Prologue ? "push" : "pop");
258   printRegisters(std::make_pair(RegisterMask, 0));
259   OS << '\n';
260
261   ++Offset, ++Offset;
262   return false;
263 }
264
265 bool Decoder::opcode_1100xxxx(const ulittle8_t *OC, unsigned &Offset,
266                               unsigned Length, bool Prologue) {
267   if (Prologue)
268     SW.startLine() << format("0x%02x                ; mov r%u, sp\n",
269                              OC[Offset], OC[Offset] & 0xf);
270   else
271     SW.startLine() << format("0x%02x                ; mov sp, r%u\n",
272                              OC[Offset], OC[Offset] & 0xf);
273   ++Offset;
274   return false;
275 }
276
277 bool Decoder::opcode_11010Lxx(const ulittle8_t *OC, unsigned &Offset,
278                               unsigned Length, bool Prologue) {
279   unsigned Link = (OC[Offset] & 0x4) >> 3;
280   unsigned Count = (OC[Offset] & 0x3);
281
282   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
283                    | (((1 << (Count + 1)) - 1) << 4);
284
285   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
286                            Prologue ? "push" : "pop");
287   printRegisters(std::make_pair(GPRMask, 0));
288   OS << '\n';
289
290   ++Offset;
291   return false;
292 }
293
294 bool Decoder::opcode_11011Lxx(const ulittle8_t *OC, unsigned &Offset,
295                               unsigned Length, bool Prologue) {
296   unsigned Link = (OC[Offset] & 0x4) >> 2;
297   unsigned Count = (OC[Offset] & 0x3) + 4;
298
299   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
300                    | (((1 << (Count + 1)) - 1) << 4);
301
302   SW.startLine() << format("0x%02x                ; %s.w ", OC[Offset],
303                            Prologue ? "push" : "pop");
304   printRegisters(std::make_pair(GPRMask, 0));
305   OS << '\n';
306
307   ++Offset;
308   return false;
309 }
310
311 bool Decoder::opcode_11100xxx(const ulittle8_t *OC, unsigned &Offset,
312                               unsigned Length, bool Prologue) {
313   unsigned High = (OC[Offset] & 0x7);
314   uint32_t VFPMask = (((1 << (High + 1)) - 1) << 8);
315
316   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
317                            Prologue ? "vpush" : "vpop");
318   printRegisters(std::make_pair(0, VFPMask));
319   OS << '\n';
320
321   ++Offset;
322   return false;
323 }
324
325 bool Decoder::opcode_111010xx(const ulittle8_t *OC, unsigned &Offset,
326                               unsigned Length, bool Prologue) {
327   uint16_t Imm = ((OC[Offset + 0] & 0x03) << 8) | ((OC[Offset + 1] & 0xff) << 0);
328
329   SW.startLine() << format("0x%02x 0x%02x           ; %s.w sp, #(%u * 4)\n",
330                            OC[Offset + 0], OC[Offset + 1],
331                            static_cast<const char *>(Prologue ? "sub" : "add"),
332                            Imm);
333
334   ++Offset, ++Offset;
335   return false;
336 }
337
338 bool Decoder::opcode_1110110L(const ulittle8_t *OC, unsigned &Offset,
339                               unsigned Length, bool Prologue) {
340   uint8_t GPRMask = ((OC[Offset + 0] & 0x01) << (Prologue ? 14 : 15))
341                   | ((OC[Offset + 1] & 0xff) << 0);
342
343   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
344                            OC[Offset + 1], Prologue ? "push" : "pop");
345   printRegisters(std::make_pair(GPRMask, 0));
346   OS << '\n';
347
348   ++Offset, ++Offset;
349   return false;
350 }
351
352 bool Decoder::opcode_11101110(const ulittle8_t *OC, unsigned &Offset,
353                               unsigned Length, bool Prologue) {
354   assert(!Prologue && "may not be used in prologue");
355
356   if (OC[Offset + 1] & 0xf0)
357     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
358                              OC[Offset + 0], OC[Offset +  1]);
359   else
360     SW.startLine()
361       << format("0x%02x 0x%02x           ; microsoft-specific (type: %u)\n",
362                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] & 0x0f);
363
364   ++Offset, ++Offset;
365   return false;
366 }
367
368 bool Decoder::opcode_11101111(const ulittle8_t *OC, unsigned &Offset,
369                               unsigned Length, bool Prologue) {
370   assert(!Prologue && "may not be used in prologue");
371
372   if (OC[Offset + 1] & 0xf0)
373     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
374                              OC[Offset + 0], OC[Offset +  1]);
375   else
376     SW.startLine()
377       << format("0x%02x 0x%02x           ; ldr.w lr, [sp], #%u\n",
378                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] << 2);
379
380   ++Offset, ++Offset;
381   return false;
382 }
383
384 bool Decoder::opcode_11110101(const ulittle8_t *OC, unsigned &Offset,
385                               unsigned Length, bool Prologue) {
386   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
387   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
388   uint32_t VFPMask = ((1 << (End - Start)) - 1) << Start;
389
390   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
391                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
392   printRegisters(std::make_pair(0, VFPMask));
393   OS << '\n';
394
395   ++Offset, ++Offset;
396   return false;
397 }
398
399 bool Decoder::opcode_11110110(const ulittle8_t *OC, unsigned &Offset,
400                               unsigned Length, bool Prologue) {
401   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
402   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
403   uint32_t VFPMask = ((1 << (End - Start)) - 1) << 16;
404
405   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
406                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
407   printRegisters(std::make_pair(0, VFPMask));
408   OS << '\n';
409
410   ++Offset, ++Offset;
411   return false;
412 }
413
414 bool Decoder::opcode_11110111(const ulittle8_t *OC, unsigned &Offset,
415                               unsigned Length, bool Prologue) {
416   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
417
418   SW.startLine() << format("0x%02x 0x%02x 0x%02x      ; %s sp, sp, #(%u * 4)\n",
419                            OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
420                            static_cast<const char *>(Prologue ? "sub" : "add"),
421                            Imm);
422
423   ++Offset, ++Offset, ++Offset;
424   return false;
425 }
426
427 bool Decoder::opcode_11111000(const ulittle8_t *OC, unsigned &Offset,
428                               unsigned Length, bool Prologue) {
429   uint32_t Imm = (OC[Offset + 1] << 16)
430                | (OC[Offset + 2] << 8)
431                | (OC[Offset + 3] << 0);
432
433   SW.startLine()
434     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s sp, sp, #(%u * 4)\n",
435               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
436               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
437
438   ++Offset, ++Offset, ++Offset, ++Offset;
439   return false;
440 }
441
442 bool Decoder::opcode_11111001(const ulittle8_t *OC, unsigned &Offset,
443                               unsigned Length, bool Prologue) {
444   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
445
446   SW.startLine()
447     << format("0x%02x 0x%02x 0x%02x      ; %s.w sp, sp, #(%u * 4)\n",
448               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
449               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
450
451   ++Offset, ++Offset, ++Offset;
452   return false;
453 }
454
455 bool Decoder::opcode_11111010(const ulittle8_t *OC, unsigned &Offset,
456                               unsigned Length, bool Prologue) {
457   uint32_t Imm = (OC[Offset + 1] << 16)
458                | (OC[Offset + 2] << 8)
459                | (OC[Offset + 3] << 0);
460
461   SW.startLine()
462     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s.w sp, sp, #(%u * 4)\n",
463               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
464               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
465
466   ++Offset, ++Offset, ++Offset, ++Offset;
467   return false;
468 }
469
470 bool Decoder::opcode_11111011(const ulittle8_t *OC, unsigned &Offset,
471                               unsigned Length, bool Prologue) {
472   SW.startLine() << format("0x%02x                ; nop\n", OC[Offset]);
473   ++Offset;
474   return false;
475 }
476
477 bool Decoder::opcode_11111100(const ulittle8_t *OC, unsigned &Offset,
478                               unsigned Length, bool Prologue) {
479   SW.startLine() << format("0x%02x                ; nop.w\n", OC[Offset]);
480   ++Offset;
481   return false;
482 }
483
484 bool Decoder::opcode_11111101(const ulittle8_t *OC, unsigned &Offset,
485                               unsigned Length, bool Prologue) {
486   SW.startLine() << format("0x%02x                ; b\n", OC[Offset]);
487   ++Offset;
488   return true;
489 }
490
491 bool Decoder::opcode_11111110(const ulittle8_t *OC, unsigned &Offset,
492                               unsigned Length, bool Prologue) {
493   SW.startLine() << format("0x%02x                ; b.w\n", OC[Offset]);
494   ++Offset;
495   return true;
496 }
497
498 bool Decoder::opcode_11111111(const ulittle8_t *OC, unsigned &Offset,
499                               unsigned Length, bool Prologue) {
500   ++Offset;
501   return true;
502 }
503
504 void Decoder::decodeOpcodes(ArrayRef<ulittle8_t> Opcodes, unsigned Offset,
505                             bool Prologue) {
506   assert((!Prologue || Offset == 0) && "prologue should always use offset 0");
507
508   bool Terminated = false;
509   for (unsigned OI = Offset, OE = Opcodes.size(); !Terminated && OI < OE; ) {
510     bool Decoded = false;
511     for (unsigned DI = 0, DE = array_lengthof(Ring); DI < DE; ++DI) {
512       if ((Opcodes[OI] & Ring[DI].Mask) == Ring[DI].Value) {
513         Terminated = (this->*Ring[DI].Routine)(Opcodes.data(), OI, 0, Prologue);
514         Decoded = true;
515         break;
516       }
517     }
518     assert(Decoded && "unhandled opcode");
519   }
520 }
521
522 bool Decoder::dumpXDataRecord(const COFFObjectFile &COFF,
523                               const SectionRef &Section,
524                               uint64_t FunctionAddress, uint64_t VA) {
525   ArrayRef<uint8_t> Contents;
526   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
527     return false;
528
529   uint64_t SectionVA;
530   if (Section.getAddress(SectionVA))
531     return false;
532
533   uint64_t Offset = VA - SectionVA;
534   const ulittle32_t *Data =
535     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
536   const ExceptionDataRecord XData(Data);
537
538   DictScope XRS(SW, "ExceptionData");
539   SW.printNumber("FunctionLength", XData.FunctionLength() << 1);
540   SW.printNumber("Version", XData.Vers());
541   SW.printBoolean("ExceptionData", XData.X());
542   SW.printBoolean("EpiloguePacked", XData.E());
543   SW.printBoolean("Fragment", XData.F());
544   SW.printNumber(XData.E() ? "EpilogueOffset" : "EpilogueScopes",
545                  XData.EpilogueCount());
546   SW.printNumber("ByteCodeLength",
547                  static_cast<uint64_t>(XData.CodeWords() * sizeof(uint32_t)));
548
549   if (XData.E()) {
550     ArrayRef<ulittle8_t> UC = XData.UnwindByteCode();
551     if (!XData.F()) {
552       ListScope PS(SW, "Prologue");
553       decodeOpcodes(UC, 0, /*Prologue=*/true);
554     }
555     if (XData.EpilogueCount()) {
556       ListScope ES(SW, "Epilogue");
557       decodeOpcodes(UC, XData.EpilogueCount(), /*Prologue=*/false);
558     }
559   } else {
560     ArrayRef<ulittle32_t> EpilogueScopes = XData.EpilogueScopes();
561     ListScope ESS(SW, "EpilogueScopes");
562     for (const EpilogueScope ES : EpilogueScopes) {
563       DictScope ESES(SW, "EpilogueScope");
564       SW.printNumber("StartOffset", ES.EpilogueStartOffset());
565       SW.printNumber("Condition", ES.Condition());
566       SW.printNumber("EpilogueStartIndex", ES.EpilogueStartIndex());
567
568       ListScope Opcodes(SW, "Opcodes");
569       decodeOpcodes(XData.UnwindByteCode(), ES.EpilogueStartIndex(),
570                     /*Prologue=*/false);
571     }
572   }
573
574   if (XData.X()) {
575     const uint32_t Address = XData.ExceptionHandlerRVA();
576     const uint32_t Parameter = XData.ExceptionHandlerParameter();
577     const size_t HandlerOffset = HeaderWords(XData)
578                                + (XData.E() ? 0 : XData.EpilogueCount())
579                                + XData.CodeWords();
580
581     ErrorOr<SymbolRef> Symbol =
582       getRelocatedSymbol(COFF, Section, HandlerOffset * sizeof(uint32_t));
583     if (!Symbol)
584       Symbol = getSymbol(COFF, Address, /*FunctionOnly=*/true);
585
586     StringRef Name;
587     if (Symbol)
588       Symbol->getName(Name);
589
590     ListScope EHS(SW, "ExceptionHandler");
591     SW.printString("Routine", formatSymbol(Name, Address));
592     SW.printHex("Parameter", Parameter);
593   }
594
595   return true;
596 }
597
598 bool Decoder::dumpUnpackedEntry(const COFFObjectFile &COFF,
599                                 const SectionRef Section, uint64_t Offset,
600                                 unsigned Index, const RuntimeFunction &RF) {
601   assert(RF.Flag() == RuntimeFunctionFlag::RFF_Unpacked &&
602          "packed entry cannot be treated as an unpacked entry");
603
604   ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset);
605   if (!Function)
606     Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true);
607
608   ErrorOr<SymbolRef> XDataRecord = getRelocatedSymbol(COFF, Section, Offset + 4);
609   if (!XDataRecord)
610     XDataRecord = getSymbol(COFF, RF.ExceptionInformationRVA());
611
612   if (!RF.BeginAddress && !Function)
613     return false;
614   if (!RF.UnwindData && !XDataRecord)
615     return false;
616
617   StringRef FunctionName;
618   uint64_t FunctionAddress;
619   if (Function) {
620     Function->getName(FunctionName);
621     Function->getAddress(FunctionAddress);
622   } else {
623     const pe32_header *PEHeader;
624     if (COFF.getPE32Header(PEHeader))
625       return false;
626     FunctionAddress = PEHeader->ImageBase + RF.BeginAddress;
627   }
628
629   SW.printString("Function", formatSymbol(FunctionName, FunctionAddress));
630
631   if (XDataRecord) {
632     StringRef Name;
633     uint64_t Address;
634
635     XDataRecord->getName(Name);
636     XDataRecord->getAddress(Address);
637
638     SW.printString("ExceptionRecord", formatSymbol(Name, Address));
639
640     section_iterator SI = COFF.section_end();
641     if (XDataRecord->getSection(SI))
642       return false;
643
644     return dumpXDataRecord(COFF, *SI, FunctionAddress, Address);
645   } else {
646     const pe32_header *PEHeader;
647     if (COFF.getPE32Header(PEHeader))
648       return false;
649
650     uint64_t Address = PEHeader->ImageBase + RF.ExceptionInformationRVA();
651     SW.printString("ExceptionRecord", formatSymbol("", Address));
652
653     ErrorOr<SectionRef> Section =
654       getSectionContaining(COFF, RF.ExceptionInformationRVA());
655     if (!Section)
656       return false;
657
658     return dumpXDataRecord(COFF, *Section, FunctionAddress,
659                            RF.ExceptionInformationRVA());
660   }
661 }
662
663 bool Decoder::dumpPackedEntry(const object::COFFObjectFile &COFF,
664                               const SectionRef Section, uint64_t Offset,
665                               unsigned Index, const RuntimeFunction &RF) {
666   assert((RF.Flag() == RuntimeFunctionFlag::RFF_Packed ||
667           RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
668          "unpacked entry cannot be treated as a packed entry");
669
670   ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset);
671   if (!Function)
672     Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true);
673
674   StringRef FunctionName;
675   uint64_t FunctionAddress;
676   if (Function) {
677     Function->getName(FunctionName);
678     Function->getAddress(FunctionAddress);
679   } else {
680     const pe32_header *PEHeader;
681     if (COFF.getPE32Header(PEHeader))
682       return false;
683     FunctionAddress = PEHeader->ImageBase + RF.BeginAddress;
684   }
685
686   SW.printString("Function", formatSymbol(FunctionName, FunctionAddress));
687   SW.printBoolean("Fragment",
688                   RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment);
689   SW.printNumber("FunctionLength", RF.FunctionLength());
690   SW.startLine() << "ReturnType: " << RF.Ret() << '\n';
691   SW.printBoolean("HomedParameters", RF.H());
692   SW.startLine() << "SavedRegisters: ";
693                  printRegisters(SavedRegisterMask(RF));
694   OS << '\n';
695   SW.printNumber("StackAdjustment", StackAdjustment(RF) << 2);
696
697   return true;
698 }
699
700 bool Decoder::dumpProcedureDataEntry(const COFFObjectFile &COFF,
701                                      const SectionRef Section, unsigned Index,
702                                      ArrayRef<uint8_t> Contents) {
703   uint64_t Offset = PDataEntrySize * Index;
704   const ulittle32_t *Data =
705     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
706
707   const RuntimeFunction Entry(Data);
708   DictScope RFS(SW, "RuntimeFunction");
709   if (Entry.Flag() == RuntimeFunctionFlag::RFF_Unpacked)
710     return dumpUnpackedEntry(COFF, Section, Offset, Index, Entry);
711   return dumpPackedEntry(COFF, Section, Offset, Index, Entry);
712 }
713
714 void Decoder::dumpProcedureData(const COFFObjectFile &COFF,
715                                 const SectionRef Section) {
716   ArrayRef<uint8_t> Contents;
717   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
718     return;
719
720   if (Contents.size() % PDataEntrySize) {
721     errs() << ".pdata content is not " << PDataEntrySize << "-byte aligned\n";
722     return;
723   }
724
725   for (unsigned EI = 0, EE = Contents.size() / PDataEntrySize; EI < EE; ++EI)
726     if (!dumpProcedureDataEntry(COFF, Section, EI, Contents))
727       break;
728 }
729
730 std::error_code Decoder::dumpProcedureData(const COFFObjectFile &COFF) {
731   for (const auto &Section : COFF.sections()) {
732     StringRef SectionName;
733     if (std::error_code EC =
734             COFF.getSectionName(COFF.getCOFFSection(Section), SectionName))
735       return EC;
736
737     if (SectionName.startswith(".pdata"))
738       dumpProcedureData(COFF, Section);
739   }
740   return std::error_code();
741 }
742 }
743 }
744 }
745