Simplify getSymbolType.
[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/STLExtras.h"
68 #include "llvm/ADT/StringExtras.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   std::string Buffer;
99   raw_string_ostream OS(Buffer);
100
101   if (!Name.empty())
102     OS << Name << " ";
103
104   if (Offset)
105     OS << format("+0x%X (0x%" PRIX64 ")", Offset, Address);
106   else if (!Name.empty())
107     OS << format("(0x%" PRIX64 ")", Address);
108   else
109     OS << format("0x%" PRIX64, Address);
110
111   return OS.str();
112 }
113
114 namespace llvm {
115 namespace ARM {
116 namespace WinEH {
117 const size_t Decoder::PDataEntrySize = sizeof(RuntimeFunction);
118
119 // TODO name the uops more appropriately
120 const Decoder::RingEntry Decoder::Ring[] = {
121   { 0x80, 0x00, &Decoder::opcode_0xxxxxxx },  // UOP_STACK_FREE (16-bit)
122   { 0xc0, 0x80, &Decoder::opcode_10Lxxxxx },  // UOP_POP (32-bit)
123   { 0xf0, 0xc0, &Decoder::opcode_1100xxxx },  // UOP_STACK_SAVE (16-bit)
124   { 0xf8, 0xd0, &Decoder::opcode_11010Lxx },  // UOP_POP (16-bit)
125   { 0xf8, 0xd8, &Decoder::opcode_11011Lxx },  // UOP_POP (32-bit)
126   { 0xf8, 0xe0, &Decoder::opcode_11100xxx },  // UOP_VPOP (32-bit)
127   { 0xfc, 0xe8, &Decoder::opcode_111010xx },  // UOP_STACK_FREE (32-bit)
128   { 0xfe, 0xec, &Decoder::opcode_1110110L },  // UOP_POP (16-bit)
129   { 0xff, 0xee, &Decoder::opcode_11101110 },  // UOP_MICROSOFT_SPECIFIC (16-bit)
130                                               // UOP_PUSH_MACHINE_FRAME
131                                               // UOP_PUSH_CONTEXT
132                                               // UOP_PUSH_TRAP_FRAME
133                                               // UOP_REDZONE_RESTORE_LR
134   { 0xff, 0xef, &Decoder::opcode_11101111 },  // UOP_LDRPC_POSTINC (32-bit)
135   { 0xff, 0xf5, &Decoder::opcode_11110101 },  // UOP_VPOP (32-bit)
136   { 0xff, 0xf6, &Decoder::opcode_11110110 },  // UOP_VPOP (32-bit)
137   { 0xff, 0xf7, &Decoder::opcode_11110111 },  // UOP_STACK_RESTORE (16-bit)
138   { 0xff, 0xf8, &Decoder::opcode_11111000 },  // UOP_STACK_RESTORE (16-bit)
139   { 0xff, 0xf9, &Decoder::opcode_11111001 },  // UOP_STACK_RESTORE (32-bit)
140   { 0xff, 0xfa, &Decoder::opcode_11111010 },  // UOP_STACK_RESTORE (32-bit)
141   { 0xff, 0xfb, &Decoder::opcode_11111011 },  // UOP_NOP (16-bit)
142   { 0xff, 0xfc, &Decoder::opcode_11111100 },  // UOP_NOP (32-bit)
143   { 0xff, 0xfd, &Decoder::opcode_11111101 },  // UOP_NOP (16-bit) / END
144   { 0xff, 0xfe, &Decoder::opcode_11111110 },  // UOP_NOP (32-bit) / END
145   { 0xff, 0xff, &Decoder::opcode_11111111 },  // UOP_END
146 };
147
148 void Decoder::printRegisters(const std::pair<uint16_t, uint32_t> &RegisterMask) {
149   static const char * const GPRRegisterNames[16] = {
150     "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10",
151     "r11", "ip", "sp", "lr", "pc",
152   };
153
154   const uint16_t GPRMask = std::get<0>(RegisterMask);
155   const uint16_t VFPMask = std::get<1>(RegisterMask);
156
157   OS << '{';
158   bool Comma = false;
159   for (unsigned RI = 0, RE = 11; RI < RE; ++RI) {
160     if (GPRMask & (1 << RI)) {
161       if (Comma)
162         OS << ", ";
163       OS << GPRRegisterNames[RI];
164       Comma = true;
165     }
166   }
167   for (unsigned RI = 0, RE = 32; RI < RE; ++RI) {
168     if (VFPMask & (1 << RI)) {
169       if (Comma)
170         OS << ", ";
171       OS << "d" << unsigned(RI);
172       Comma = true;
173     }
174   }
175   for (unsigned RI = 11, RE = 16; RI < RE; ++RI) {
176     if (GPRMask & (1 << RI)) {
177       if (Comma)
178         OS << ", ";
179       OS << GPRRegisterNames[RI];
180       Comma = true;
181     }
182   }
183   OS << '}';
184 }
185
186 ErrorOr<object::SectionRef>
187 Decoder::getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) {
188   for (const auto &Section : COFF.sections()) {
189     uint64_t Address = Section.getAddress();
190     uint64_t Size = Section.getSize();
191
192     if (VA >= Address && (VA - Address) <= Size)
193       return Section;
194   }
195   return readobj_error::unknown_symbol;
196 }
197
198 ErrorOr<object::SymbolRef> Decoder::getSymbol(const COFFObjectFile &COFF,
199                                               uint64_t VA, bool FunctionOnly) {
200   for (const auto &Symbol : COFF.symbols()) {
201     if (FunctionOnly && Symbol.getType() != SymbolRef::ST_Function)
202       continue;
203
204     uint64_t Address;
205     if (std::error_code EC = Symbol.getAddress(Address))
206       return EC;
207     if (Address == VA)
208       return Symbol;
209   }
210   return readobj_error::unknown_symbol;
211 }
212
213 ErrorOr<SymbolRef> Decoder::getRelocatedSymbol(const COFFObjectFile &,
214                                                const SectionRef &Section,
215                                                uint64_t Offset) {
216   for (const auto &Relocation : Section.relocations()) {
217     uint64_t RelocationOffset;
218     if (auto Error = Relocation.getOffset(RelocationOffset))
219       return Error;
220     if (RelocationOffset == Offset)
221       return *Relocation.getSymbol();
222   }
223   return readobj_error::unknown_symbol;
224 }
225
226 bool Decoder::opcode_0xxxxxxx(const uint8_t *OC, unsigned &Offset,
227                               unsigned Length, bool Prologue) {
228   uint8_t Imm = OC[Offset] & 0x7f;
229   SW.startLine() << format("0x%02x                ; %s sp, #(%u * 4)\n",
230                            OC[Offset],
231                            static_cast<const char *>(Prologue ? "sub" : "add"),
232                            Imm);
233   ++Offset;
234   return false;
235 }
236
237 bool Decoder::opcode_10Lxxxxx(const uint8_t *OC, unsigned &Offset,
238                               unsigned Length, bool Prologue) {
239   unsigned Link = (OC[Offset] & 0x20) >> 5;
240   uint16_t RegisterMask = (Link << (Prologue ? 14 : 15))
241                         | ((OC[Offset + 0] & 0x1f) << 8)
242                         | ((OC[Offset + 1] & 0xff) << 0);
243   assert((~RegisterMask & (1 << 13)) && "sp must not be set");
244   assert((~RegisterMask & (1 << (Prologue ? 15 : 14))) && "pc must not be set");
245
246   SW.startLine() << format("0x%02x 0x%02x           ; %s.w ",
247                            OC[Offset + 0], OC[Offset + 1],
248                            Prologue ? "push" : "pop");
249   printRegisters(std::make_pair(RegisterMask, 0));
250   OS << '\n';
251
252   ++Offset, ++Offset;
253   return false;
254 }
255
256 bool Decoder::opcode_1100xxxx(const uint8_t *OC, unsigned &Offset,
257                               unsigned Length, bool Prologue) {
258   if (Prologue)
259     SW.startLine() << format("0x%02x                ; mov r%u, sp\n",
260                              OC[Offset], OC[Offset] & 0xf);
261   else
262     SW.startLine() << format("0x%02x                ; mov sp, r%u\n",
263                              OC[Offset], OC[Offset] & 0xf);
264   ++Offset;
265   return false;
266 }
267
268 bool Decoder::opcode_11010Lxx(const uint8_t *OC, unsigned &Offset,
269                               unsigned Length, bool Prologue) {
270   unsigned Link = (OC[Offset] & 0x4) >> 3;
271   unsigned Count = (OC[Offset] & 0x3);
272
273   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
274                    | (((1 << (Count + 1)) - 1) << 4);
275
276   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
277                            Prologue ? "push" : "pop");
278   printRegisters(std::make_pair(GPRMask, 0));
279   OS << '\n';
280
281   ++Offset;
282   return false;
283 }
284
285 bool Decoder::opcode_11011Lxx(const uint8_t *OC, unsigned &Offset,
286                               unsigned Length, bool Prologue) {
287   unsigned Link = (OC[Offset] & 0x4) >> 2;
288   unsigned Count = (OC[Offset] & 0x3) + 4;
289
290   uint16_t GPRMask = (Link << (Prologue ? 14 : 15))
291                    | (((1 << (Count + 1)) - 1) << 4);
292
293   SW.startLine() << format("0x%02x                ; %s.w ", OC[Offset],
294                            Prologue ? "push" : "pop");
295   printRegisters(std::make_pair(GPRMask, 0));
296   OS << '\n';
297
298   ++Offset;
299   return false;
300 }
301
302 bool Decoder::opcode_11100xxx(const uint8_t *OC, unsigned &Offset,
303                               unsigned Length, bool Prologue) {
304   unsigned High = (OC[Offset] & 0x7);
305   uint32_t VFPMask = (((1 << (High + 1)) - 1) << 8);
306
307   SW.startLine() << format("0x%02x                ; %s ", OC[Offset],
308                            Prologue ? "vpush" : "vpop");
309   printRegisters(std::make_pair(0, VFPMask));
310   OS << '\n';
311
312   ++Offset;
313   return false;
314 }
315
316 bool Decoder::opcode_111010xx(const uint8_t *OC, unsigned &Offset,
317                               unsigned Length, bool Prologue) {
318   uint16_t Imm = ((OC[Offset + 0] & 0x03) << 8) | ((OC[Offset + 1] & 0xff) << 0);
319
320   SW.startLine() << format("0x%02x 0x%02x           ; %s.w sp, #(%u * 4)\n",
321                            OC[Offset + 0], OC[Offset + 1],
322                            static_cast<const char *>(Prologue ? "sub" : "add"),
323                            Imm);
324
325   ++Offset, ++Offset;
326   return false;
327 }
328
329 bool Decoder::opcode_1110110L(const uint8_t *OC, unsigned &Offset,
330                               unsigned Length, bool Prologue) {
331   uint8_t GPRMask = ((OC[Offset + 0] & 0x01) << (Prologue ? 14 : 15))
332                   | ((OC[Offset + 1] & 0xff) << 0);
333
334   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
335                            OC[Offset + 1], Prologue ? "push" : "pop");
336   printRegisters(std::make_pair(GPRMask, 0));
337   OS << '\n';
338
339   ++Offset, ++Offset;
340   return false;
341 }
342
343 bool Decoder::opcode_11101110(const uint8_t *OC, unsigned &Offset,
344                               unsigned Length, bool Prologue) {
345   assert(!Prologue && "may not be used in prologue");
346
347   if (OC[Offset + 1] & 0xf0)
348     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
349                              OC[Offset + 0], OC[Offset +  1]);
350   else
351     SW.startLine()
352       << format("0x%02x 0x%02x           ; microsoft-specific (type: %u)\n",
353                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] & 0x0f);
354
355   ++Offset, ++Offset;
356   return false;
357 }
358
359 bool Decoder::opcode_11101111(const uint8_t *OC, unsigned &Offset,
360                               unsigned Length, bool Prologue) {
361   assert(!Prologue && "may not be used in prologue");
362
363   if (OC[Offset + 1] & 0xf0)
364     SW.startLine() << format("0x%02x 0x%02x           ; reserved\n",
365                              OC[Offset + 0], OC[Offset +  1]);
366   else
367     SW.startLine()
368       << format("0x%02x 0x%02x           ; ldr.w lr, [sp], #%u\n",
369                 OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] << 2);
370
371   ++Offset, ++Offset;
372   return false;
373 }
374
375 bool Decoder::opcode_11110101(const uint8_t *OC, unsigned &Offset,
376                               unsigned Length, bool Prologue) {
377   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
378   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
379   uint32_t VFPMask = ((1 << (End - Start)) - 1) << Start;
380
381   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
382                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
383   printRegisters(std::make_pair(0, VFPMask));
384   OS << '\n';
385
386   ++Offset, ++Offset;
387   return false;
388 }
389
390 bool Decoder::opcode_11110110(const uint8_t *OC, unsigned &Offset,
391                               unsigned Length, bool Prologue) {
392   unsigned Start = (OC[Offset + 1] & 0xf0) >> 4;
393   unsigned End = (OC[Offset + 1] & 0x0f) >> 0;
394   uint32_t VFPMask = ((1 << (End - Start)) - 1) << 16;
395
396   SW.startLine() << format("0x%02x 0x%02x           ; %s ", OC[Offset + 0],
397                            OC[Offset + 1], Prologue ? "vpush" : "vpop");
398   printRegisters(std::make_pair(0, VFPMask));
399   OS << '\n';
400
401   ++Offset, ++Offset;
402   return false;
403 }
404
405 bool Decoder::opcode_11110111(const uint8_t *OC, unsigned &Offset,
406                               unsigned Length, bool Prologue) {
407   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
408
409   SW.startLine() << format("0x%02x 0x%02x 0x%02x      ; %s sp, sp, #(%u * 4)\n",
410                            OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
411                            static_cast<const char *>(Prologue ? "sub" : "add"),
412                            Imm);
413
414   ++Offset, ++Offset, ++Offset;
415   return false;
416 }
417
418 bool Decoder::opcode_11111000(const uint8_t *OC, unsigned &Offset,
419                               unsigned Length, bool Prologue) {
420   uint32_t Imm = (OC[Offset + 1] << 16)
421                | (OC[Offset + 2] << 8)
422                | (OC[Offset + 3] << 0);
423
424   SW.startLine()
425     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s sp, sp, #(%u * 4)\n",
426               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
427               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
428
429   ++Offset, ++Offset, ++Offset, ++Offset;
430   return false;
431 }
432
433 bool Decoder::opcode_11111001(const uint8_t *OC, unsigned &Offset,
434                               unsigned Length, bool Prologue) {
435   uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0);
436
437   SW.startLine()
438     << format("0x%02x 0x%02x 0x%02x      ; %s.w sp, sp, #(%u * 4)\n",
439               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2],
440               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
441
442   ++Offset, ++Offset, ++Offset;
443   return false;
444 }
445
446 bool Decoder::opcode_11111010(const uint8_t *OC, unsigned &Offset,
447                               unsigned Length, bool Prologue) {
448   uint32_t Imm = (OC[Offset + 1] << 16)
449                | (OC[Offset + 2] << 8)
450                | (OC[Offset + 3] << 0);
451
452   SW.startLine()
453     << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s.w sp, sp, #(%u * 4)\n",
454               OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3],
455               static_cast<const char *>(Prologue ? "sub" : "add"), Imm);
456
457   ++Offset, ++Offset, ++Offset, ++Offset;
458   return false;
459 }
460
461 bool Decoder::opcode_11111011(const uint8_t *OC, unsigned &Offset,
462                               unsigned Length, bool Prologue) {
463   SW.startLine() << format("0x%02x                ; nop\n", OC[Offset]);
464   ++Offset;
465   return false;
466 }
467
468 bool Decoder::opcode_11111100(const uint8_t *OC, unsigned &Offset,
469                               unsigned Length, bool Prologue) {
470   SW.startLine() << format("0x%02x                ; nop.w\n", OC[Offset]);
471   ++Offset;
472   return false;
473 }
474
475 bool Decoder::opcode_11111101(const uint8_t *OC, unsigned &Offset,
476                               unsigned Length, bool Prologue) {
477   SW.startLine() << format("0x%02x                ; b\n", OC[Offset]);
478   ++Offset;
479   return true;
480 }
481
482 bool Decoder::opcode_11111110(const uint8_t *OC, unsigned &Offset,
483                               unsigned Length, bool Prologue) {
484   SW.startLine() << format("0x%02x                ; b.w\n", OC[Offset]);
485   ++Offset;
486   return true;
487 }
488
489 bool Decoder::opcode_11111111(const uint8_t *OC, unsigned &Offset,
490                               unsigned Length, bool Prologue) {
491   ++Offset;
492   return true;
493 }
494
495 void Decoder::decodeOpcodes(ArrayRef<uint8_t> Opcodes, unsigned Offset,
496                             bool Prologue) {
497   assert((!Prologue || Offset == 0) && "prologue should always use offset 0");
498
499   bool Terminated = false;
500   for (unsigned OI = Offset, OE = Opcodes.size(); !Terminated && OI < OE; ) {
501     for (unsigned DI = 0;; ++DI) {
502       if ((Opcodes[OI] & Ring[DI].Mask) == Ring[DI].Value) {
503         Terminated = (this->*Ring[DI].Routine)(Opcodes.data(), OI, 0, Prologue);
504         break;
505       }
506       assert(DI < array_lengthof(Ring) && "unhandled opcode");
507     }
508   }
509 }
510
511 bool Decoder::dumpXDataRecord(const COFFObjectFile &COFF,
512                               const SectionRef &Section,
513                               uint64_t FunctionAddress, uint64_t VA) {
514   ArrayRef<uint8_t> Contents;
515   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
516     return false;
517
518   uint64_t SectionVA = Section.getAddress();
519   uint64_t Offset = VA - SectionVA;
520   const ulittle32_t *Data =
521     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
522   const ExceptionDataRecord XData(Data);
523
524   DictScope XRS(SW, "ExceptionData");
525   SW.printNumber("FunctionLength", XData.FunctionLength() << 1);
526   SW.printNumber("Version", XData.Vers());
527   SW.printBoolean("ExceptionData", XData.X());
528   SW.printBoolean("EpiloguePacked", XData.E());
529   SW.printBoolean("Fragment", XData.F());
530   SW.printNumber(XData.E() ? "EpilogueOffset" : "EpilogueScopes",
531                  XData.EpilogueCount());
532   SW.printNumber("ByteCodeLength",
533                  static_cast<uint64_t>(XData.CodeWords() * sizeof(uint32_t)));
534
535   if (XData.E()) {
536     ArrayRef<uint8_t> UC = XData.UnwindByteCode();
537     if (!XData.F()) {
538       ListScope PS(SW, "Prologue");
539       decodeOpcodes(UC, 0, /*Prologue=*/true);
540     }
541     if (XData.EpilogueCount()) {
542       ListScope ES(SW, "Epilogue");
543       decodeOpcodes(UC, XData.EpilogueCount(), /*Prologue=*/false);
544     }
545   } else {
546     ArrayRef<ulittle32_t> EpilogueScopes = XData.EpilogueScopes();
547     ListScope ESS(SW, "EpilogueScopes");
548     for (const EpilogueScope ES : EpilogueScopes) {
549       DictScope ESES(SW, "EpilogueScope");
550       SW.printNumber("StartOffset", ES.EpilogueStartOffset());
551       SW.printNumber("Condition", ES.Condition());
552       SW.printNumber("EpilogueStartIndex", ES.EpilogueStartIndex());
553
554       ListScope Opcodes(SW, "Opcodes");
555       decodeOpcodes(XData.UnwindByteCode(), ES.EpilogueStartIndex(),
556                     /*Prologue=*/false);
557     }
558   }
559
560   if (XData.X()) {
561     const uint32_t Address = XData.ExceptionHandlerRVA();
562     const uint32_t Parameter = XData.ExceptionHandlerParameter();
563     const size_t HandlerOffset = HeaderWords(XData)
564                                + (XData.E() ? 0 : XData.EpilogueCount())
565                                + XData.CodeWords();
566
567     ErrorOr<SymbolRef> Symbol =
568       getRelocatedSymbol(COFF, Section, HandlerOffset * sizeof(uint32_t));
569     if (!Symbol)
570       Symbol = getSymbol(COFF, Address, /*FunctionOnly=*/true);
571
572     StringRef Name;
573     if (Symbol)
574       Symbol->getName(Name);
575
576     ListScope EHS(SW, "ExceptionHandler");
577     SW.printString("Routine", formatSymbol(Name, Address));
578     SW.printHex("Parameter", Parameter);
579   }
580
581   return true;
582 }
583
584 bool Decoder::dumpUnpackedEntry(const COFFObjectFile &COFF,
585                                 const SectionRef Section, uint64_t Offset,
586                                 unsigned Index, const RuntimeFunction &RF) {
587   assert(RF.Flag() == RuntimeFunctionFlag::RFF_Unpacked &&
588          "packed entry cannot be treated as an unpacked entry");
589
590   ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset);
591   if (!Function)
592     Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true);
593
594   ErrorOr<SymbolRef> XDataRecord = getRelocatedSymbol(COFF, Section, Offset + 4);
595   if (!XDataRecord)
596     XDataRecord = getSymbol(COFF, RF.ExceptionInformationRVA());
597
598   if (!RF.BeginAddress && !Function)
599     return false;
600   if (!RF.UnwindData && !XDataRecord)
601     return false;
602
603   StringRef FunctionName;
604   uint64_t FunctionAddress;
605   if (Function) {
606     Function->getName(FunctionName);
607     Function->getAddress(FunctionAddress);
608   } else {
609     const pe32_header *PEHeader;
610     if (COFF.getPE32Header(PEHeader))
611       return false;
612     FunctionAddress = PEHeader->ImageBase + RF.BeginAddress;
613   }
614
615   SW.printString("Function", formatSymbol(FunctionName, FunctionAddress));
616
617   if (XDataRecord) {
618     StringRef Name;
619     uint64_t Address;
620
621     XDataRecord->getName(Name);
622     XDataRecord->getAddress(Address);
623
624     SW.printString("ExceptionRecord", formatSymbol(Name, Address));
625
626     section_iterator SI = COFF.section_end();
627     if (XDataRecord->getSection(SI))
628       return false;
629
630     return dumpXDataRecord(COFF, *SI, FunctionAddress, Address);
631   } else {
632     const pe32_header *PEHeader;
633     if (COFF.getPE32Header(PEHeader))
634       return false;
635
636     uint64_t Address = PEHeader->ImageBase + RF.ExceptionInformationRVA();
637     SW.printString("ExceptionRecord", formatSymbol("", Address));
638
639     ErrorOr<SectionRef> Section =
640       getSectionContaining(COFF, RF.ExceptionInformationRVA());
641     if (!Section)
642       return false;
643
644     return dumpXDataRecord(COFF, *Section, FunctionAddress,
645                            RF.ExceptionInformationRVA());
646   }
647 }
648
649 bool Decoder::dumpPackedEntry(const object::COFFObjectFile &COFF,
650                               const SectionRef Section, uint64_t Offset,
651                               unsigned Index, const RuntimeFunction &RF) {
652   assert((RF.Flag() == RuntimeFunctionFlag::RFF_Packed ||
653           RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
654          "unpacked entry cannot be treated as a packed entry");
655
656   ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset);
657   if (!Function)
658     Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true);
659
660   StringRef FunctionName;
661   uint64_t FunctionAddress;
662   if (Function) {
663     Function->getName(FunctionName);
664     Function->getAddress(FunctionAddress);
665   } else {
666     const pe32_header *PEHeader;
667     if (COFF.getPE32Header(PEHeader))
668       return false;
669     FunctionAddress = PEHeader->ImageBase + RF.BeginAddress;
670   }
671
672   SW.printString("Function", formatSymbol(FunctionName, FunctionAddress));
673   SW.printBoolean("Fragment",
674                   RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment);
675   SW.printNumber("FunctionLength", RF.FunctionLength());
676   SW.startLine() << "ReturnType: " << RF.Ret() << '\n';
677   SW.printBoolean("HomedParameters", RF.H());
678   SW.startLine() << "SavedRegisters: ";
679                  printRegisters(SavedRegisterMask(RF));
680   OS << '\n';
681   SW.printNumber("StackAdjustment", StackAdjustment(RF) << 2);
682
683   return true;
684 }
685
686 bool Decoder::dumpProcedureDataEntry(const COFFObjectFile &COFF,
687                                      const SectionRef Section, unsigned Index,
688                                      ArrayRef<uint8_t> Contents) {
689   uint64_t Offset = PDataEntrySize * Index;
690   const ulittle32_t *Data =
691     reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset);
692
693   const RuntimeFunction Entry(Data);
694   DictScope RFS(SW, "RuntimeFunction");
695   if (Entry.Flag() == RuntimeFunctionFlag::RFF_Unpacked)
696     return dumpUnpackedEntry(COFF, Section, Offset, Index, Entry);
697   return dumpPackedEntry(COFF, Section, Offset, Index, Entry);
698 }
699
700 void Decoder::dumpProcedureData(const COFFObjectFile &COFF,
701                                 const SectionRef Section) {
702   ArrayRef<uint8_t> Contents;
703   if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents))
704     return;
705
706   if (Contents.size() % PDataEntrySize) {
707     errs() << ".pdata content is not " << PDataEntrySize << "-byte aligned\n";
708     return;
709   }
710
711   for (unsigned EI = 0, EE = Contents.size() / PDataEntrySize; EI < EE; ++EI)
712     if (!dumpProcedureDataEntry(COFF, Section, EI, Contents))
713       break;
714 }
715
716 std::error_code Decoder::dumpProcedureData(const COFFObjectFile &COFF) {
717   for (const auto &Section : COFF.sections()) {
718     StringRef SectionName;
719     if (std::error_code EC =
720             COFF.getSectionName(COFF.getCOFFSection(Section), SectionName))
721       return EC;
722
723     if (SectionName.startswith(".pdata"))
724       dumpProcedureData(COFF, Section);
725   }
726   return std::error_code();
727 }
728 }
729 }
730 }