188e9f891339e15002424f9f5aed23725dd514e1
[oota-llvm.git] / tools / llvm-readobj / COFFDumper.cpp
1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- 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 /// \file
11 /// \brief This file implements the COFF-specific dumper for llvm-readobj.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm-readobj.h"
16 #include "Error.h"
17 #include "ObjDumper.h"
18 #include "StreamWriter.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/Win64EH.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/system_error.h"
32 #include <algorithm>
33 #include <cstring>
34 #include <time.h>
35
36 using namespace llvm;
37 using namespace llvm::object;
38 using namespace llvm::Win64EH;
39
40 namespace {
41
42 class COFFDumper : public ObjDumper {
43 public:
44   COFFDumper(const llvm::object::COFFObjectFile *Obj, StreamWriter& Writer)
45     : ObjDumper(Writer)
46     , Obj(Obj) {
47     cacheRelocations();
48   }
49
50   virtual void printFileHeaders() override;
51   virtual void printSections() override;
52   virtual void printRelocations() override;
53   virtual void printSymbols() override;
54   virtual void printDynamicSymbols() override;
55   virtual void printUnwindInfo() override;
56
57 private:
58   void printSymbol(const SymbolRef &Sym);
59   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc);
60   void printDataDirectory(uint32_t Index, const std::string &FieldName);
61   void printX64UnwindInfo();
62
63   template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
64   void printBaseOfDataField(const pe32_header *Hdr);
65   void printBaseOfDataField(const pe32plus_header *Hdr);
66
67   void printRuntimeFunction(
68     const RuntimeFunction& RTF,
69     uint64_t OffsetInSection,
70     const std::vector<RelocationRef> &Rels);
71
72   void printUnwindInfo(
73     const Win64EH::UnwindInfo& UI,
74     uint64_t OffsetInSection,
75     const std::vector<RelocationRef> &Rels);
76
77   void printUnwindCode(const Win64EH::UnwindInfo &UI, ArrayRef<UnwindCode> UCs);
78
79   void printCodeViewLineTables(const SectionRef &Section);
80
81   void cacheRelocations();
82
83   error_code getSection(
84     const std::vector<RelocationRef> &Rels,
85     uint64_t Offset,
86     const coff_section **Section,
87     uint64_t *AddrPtr);
88
89   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
90
91   const llvm::object::COFFObjectFile *Obj;
92   RelocMapTy RelocMap;
93 };
94
95 } // namespace
96
97
98 namespace llvm {
99
100 error_code createCOFFDumper(const object::ObjectFile *Obj, StreamWriter &Writer,
101                             std::unique_ptr<ObjDumper> &Result) {
102   const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
103   if (!COFFObj)
104     return readobj_error::unsupported_obj_file_format;
105
106   Result.reset(new COFFDumper(COFFObj, Writer));
107   return readobj_error::success;
108 }
109
110 } // namespace llvm
111
112
113 // Returns the name of the unwind code.
114 static StringRef getUnwindCodeTypeName(uint8_t Code) {
115   switch(Code) {
116   default: llvm_unreachable("Invalid unwind code");
117   case UOP_PushNonVol: return "PUSH_NONVOL";
118   case UOP_AllocLarge: return "ALLOC_LARGE";
119   case UOP_AllocSmall: return "ALLOC_SMALL";
120   case UOP_SetFPReg: return "SET_FPREG";
121   case UOP_SaveNonVol: return "SAVE_NONVOL";
122   case UOP_SaveNonVolBig: return "SAVE_NONVOL_FAR";
123   case UOP_SaveXMM128: return "SAVE_XMM128";
124   case UOP_SaveXMM128Big: return "SAVE_XMM128_FAR";
125   case UOP_PushMachFrame: return "PUSH_MACHFRAME";
126   }
127 }
128
129 // Returns the name of a referenced register.
130 static StringRef getUnwindRegisterName(uint8_t Reg) {
131   switch(Reg) {
132   default: llvm_unreachable("Invalid register");
133   case 0: return "RAX";
134   case 1: return "RCX";
135   case 2: return "RDX";
136   case 3: return "RBX";
137   case 4: return "RSP";
138   case 5: return "RBP";
139   case 6: return "RSI";
140   case 7: return "RDI";
141   case 8: return "R8";
142   case 9: return "R9";
143   case 10: return "R10";
144   case 11: return "R11";
145   case 12: return "R12";
146   case 13: return "R13";
147   case 14: return "R14";
148   case 15: return "R15";
149   }
150 }
151
152 // Calculates the number of array slots required for the unwind code.
153 static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
154   switch (UnwindCode.getUnwindOp()) {
155   default: llvm_unreachable("Invalid unwind code");
156   case UOP_PushNonVol:
157   case UOP_AllocSmall:
158   case UOP_SetFPReg:
159   case UOP_PushMachFrame:
160     return 1;
161   case UOP_SaveNonVol:
162   case UOP_SaveXMM128:
163     return 2;
164   case UOP_SaveNonVolBig:
165   case UOP_SaveXMM128Big:
166     return 3;
167   case UOP_AllocLarge:
168     return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
169   }
170 }
171
172 // Given a symbol sym this functions returns the address and section of it.
173 static error_code resolveSectionAndAddress(const COFFObjectFile *Obj,
174                                            const SymbolRef &Sym,
175                                            const coff_section *&ResolvedSection,
176                                            uint64_t &ResolvedAddr) {
177   if (error_code EC = Sym.getAddress(ResolvedAddr))
178     return EC;
179
180   section_iterator iter(Obj->section_begin());
181   if (error_code EC = Sym.getSection(iter))
182     return EC;
183
184   ResolvedSection = Obj->getCOFFSection(*iter);
185   return object_error::success;
186 }
187
188 // Given a vector of relocations for a section and an offset into this section
189 // the function returns the symbol used for the relocation at the offset.
190 static error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
191                                 uint64_t Offset, SymbolRef &Sym) {
192   for (const auto &Relocation : Rels) {
193     uint64_t Ofs;
194     if (error_code EC = Relocation.getOffset(Ofs))
195       return EC;
196
197     if (Ofs == Offset) {
198       Sym = *Relocation.getSymbol();
199       return readobj_error::success;
200     }
201   }
202
203   return readobj_error::unknown_symbol;
204 }
205
206 // Given a vector of relocations for a section and an offset into this section
207 // the function returns the name of the symbol used for the relocation at the
208 // offset.
209 static error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
210                                     uint64_t Offset, StringRef &Name) {
211   SymbolRef Sym;
212   if (error_code EC = resolveSymbol(Rels, Offset, Sym)) return EC;
213   if (error_code EC = Sym.getName(Name)) return EC;
214   return object_error::success;
215 }
216
217 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
218   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
219   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
220   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
221   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
222   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT    ),
223   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC      ),
224   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386     ),
225   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64     ),
226   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R     ),
227   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16   ),
228   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU  ),
229   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
230   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC  ),
231   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
232   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000    ),
233   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3      ),
234   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP   ),
235   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4      ),
236   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5      ),
237   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB    ),
238   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
239 };
240
241 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
242   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED        ),
243   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE       ),
244   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED     ),
245   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED    ),
246   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM     ),
247   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE    ),
248   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO      ),
249   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE          ),
250   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED         ),
251   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
252   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP      ),
253   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM                 ),
254   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL                    ),
255   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY         ),
256   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI      )
257 };
258
259 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
260   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN                ),
261   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE                 ),
262   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI            ),
263   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI            ),
264   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI              ),
265   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI         ),
266   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION        ),
267   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
268   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER     ),
269   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM                ),
270   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX                   ),
271 };
272
273 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
274   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA      ),
275   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE         ),
276   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY      ),
277   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT            ),
278   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION         ),
279   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH               ),
280   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND              ),
281   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER           ),
282   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
283 };
284
285 static const EnumEntry<COFF::SectionCharacteristics>
286 ImageSectionCharacteristics[] = {
287   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD           ),
288   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE              ),
289   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA  ),
290   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
291   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER             ),
292   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO              ),
293   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE            ),
294   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT            ),
295   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL                 ),
296   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE         ),
297   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT             ),
298   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED            ),
299   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD           ),
300   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES          ),
301   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES          ),
302   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES          ),
303   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES          ),
304   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES         ),
305   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES         ),
306   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES         ),
307   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES        ),
308   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES        ),
309   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES        ),
310   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES       ),
311   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES       ),
312   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES       ),
313   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES       ),
314   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL       ),
315   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE       ),
316   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED        ),
317   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED         ),
318   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED            ),
319   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE           ),
320   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ              ),
321   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE             )
322 };
323
324 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
325   { "Null"  , COFF::IMAGE_SYM_TYPE_NULL   },
326   { "Void"  , COFF::IMAGE_SYM_TYPE_VOID   },
327   { "Char"  , COFF::IMAGE_SYM_TYPE_CHAR   },
328   { "Short" , COFF::IMAGE_SYM_TYPE_SHORT  },
329   { "Int"   , COFF::IMAGE_SYM_TYPE_INT    },
330   { "Long"  , COFF::IMAGE_SYM_TYPE_LONG   },
331   { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT  },
332   { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
333   { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
334   { "Union" , COFF::IMAGE_SYM_TYPE_UNION  },
335   { "Enum"  , COFF::IMAGE_SYM_TYPE_ENUM   },
336   { "MOE"   , COFF::IMAGE_SYM_TYPE_MOE    },
337   { "Byte"  , COFF::IMAGE_SYM_TYPE_BYTE   },
338   { "Word"  , COFF::IMAGE_SYM_TYPE_WORD   },
339   { "UInt"  , COFF::IMAGE_SYM_TYPE_UINT   },
340   { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD  }
341 };
342
343 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
344   { "Null"    , COFF::IMAGE_SYM_DTYPE_NULL     },
345   { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER  },
346   { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
347   { "Array"   , COFF::IMAGE_SYM_DTYPE_ARRAY    }
348 };
349
350 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
351   { "EndOfFunction"  , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION  },
352   { "Null"           , COFF::IMAGE_SYM_CLASS_NULL             },
353   { "Automatic"      , COFF::IMAGE_SYM_CLASS_AUTOMATIC        },
354   { "External"       , COFF::IMAGE_SYM_CLASS_EXTERNAL         },
355   { "Static"         , COFF::IMAGE_SYM_CLASS_STATIC           },
356   { "Register"       , COFF::IMAGE_SYM_CLASS_REGISTER         },
357   { "ExternalDef"    , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF     },
358   { "Label"          , COFF::IMAGE_SYM_CLASS_LABEL            },
359   { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL  },
360   { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
361   { "Argument"       , COFF::IMAGE_SYM_CLASS_ARGUMENT         },
362   { "StructTag"      , COFF::IMAGE_SYM_CLASS_STRUCT_TAG       },
363   { "MemberOfUnion"  , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION  },
364   { "UnionTag"       , COFF::IMAGE_SYM_CLASS_UNION_TAG        },
365   { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION  },
366   { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
367   { "EnumTag"        , COFF::IMAGE_SYM_CLASS_ENUM_TAG         },
368   { "MemberOfEnum"   , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM   },
369   { "RegisterParam"  , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM   },
370   { "BitField"       , COFF::IMAGE_SYM_CLASS_BIT_FIELD        },
371   { "Block"          , COFF::IMAGE_SYM_CLASS_BLOCK            },
372   { "Function"       , COFF::IMAGE_SYM_CLASS_FUNCTION         },
373   { "EndOfStruct"    , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT    },
374   { "File"           , COFF::IMAGE_SYM_CLASS_FILE             },
375   { "Section"        , COFF::IMAGE_SYM_CLASS_SECTION          },
376   { "WeakExternal"   , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL    },
377   { "CLRToken"       , COFF::IMAGE_SYM_CLASS_CLR_TOKEN        }
378 };
379
380 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
381   { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
382   { "Any"         , COFF::IMAGE_COMDAT_SELECT_ANY          },
383   { "SameSize"    , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE    },
384   { "ExactMatch"  , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH  },
385   { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE  },
386   { "Largest"     , COFF::IMAGE_COMDAT_SELECT_LARGEST      },
387   { "Newest"      , COFF::IMAGE_COMDAT_SELECT_NEWEST       }
388 };
389
390 static const EnumEntry<COFF::WeakExternalCharacteristics>
391 WeakExternalCharacteristics[] = {
392   { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
393   { "Library"  , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY   },
394   { "Alias"    , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS     }
395 };
396
397 static const EnumEntry<unsigned> UnwindFlags[] = {
398   { "ExceptionHandler", Win64EH::UNW_ExceptionHandler },
399   { "TerminateHandler", Win64EH::UNW_TerminateHandler },
400   { "ChainInfo"       , Win64EH::UNW_ChainInfo        }
401 };
402
403 static const EnumEntry<unsigned> UnwindOpInfo[] = {
404   { "RAX",  0 },
405   { "RCX",  1 },
406   { "RDX",  2 },
407   { "RBX",  3 },
408   { "RSP",  4 },
409   { "RBP",  5 },
410   { "RSI",  6 },
411   { "RDI",  7 },
412   { "R8",   8 },
413   { "R9",   9 },
414   { "R10", 10 },
415   { "R11", 11 },
416   { "R12", 12 },
417   { "R13", 13 },
418   { "R14", 14 },
419   { "R15", 15 }
420 };
421
422 static uint64_t getOffsetOfLSDA(const Win64EH::UnwindInfo& UI) {
423   return static_cast<const char*>(UI.getLanguageSpecificData())
424          - reinterpret_cast<const char*>(&UI);
425 }
426
427 static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UCs) {
428   if (UCs.size() < 3)
429     return 0;
430
431   return UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
432 }
433
434 template<typename T>
435 static error_code getSymbolAuxData(const COFFObjectFile *Obj,
436                                    const coff_symbol *Symbol, const T* &Aux) {
437   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
438   Aux = reinterpret_cast<const T*>(AuxData.data());
439   return readobj_error::success;
440 }
441
442 static std::string formatSymbol(const std::vector<RelocationRef> &Rels,
443                                 uint64_t Offset, uint32_t Disp) {
444   std::string Buffer;
445   raw_string_ostream Str(Buffer);
446
447   StringRef Sym;
448   if (resolveSymbolName(Rels, Offset, Sym)) {
449     Str << format(" (0x%" PRIX64 ")", Offset);
450     return Str.str();
451   }
452
453   Str << Sym;
454   if (Disp > 0) {
455     Str << format(" +0x%X (0x%" PRIX64 ")", Disp, Offset);
456   } else {
457     Str << format(" (0x%" PRIX64 ")", Offset);
458   }
459
460   return Str.str();
461 }
462
463 error_code COFFDumper::getSection(
464     const std::vector<RelocationRef> &Rels, uint64_t Offset,
465     const coff_section **SectionPtr, uint64_t *AddrPtr) {
466
467   SymbolRef Sym;
468   if (error_code EC = resolveSymbol(Rels, Offset, Sym))
469     return EC;
470
471   const coff_section *Section;
472   uint64_t Addr;
473   if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
474     return EC;
475
476   if (SectionPtr)
477     *SectionPtr = Section;
478   if (AddrPtr)
479     *AddrPtr = Addr;
480
481   return object_error::success;
482 }
483
484 void COFFDumper::cacheRelocations() {
485   for (const SectionRef &S : Obj->sections()) {
486     const coff_section *Section = Obj->getCOFFSection(S);
487
488     for (const RelocationRef &Reloc : S.relocations())
489       RelocMap[Section].push_back(Reloc);
490
491     // Sort relocations by address.
492     std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
493               relocAddressLess);
494   }
495 }
496
497 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
498   const data_directory *Data;
499   if (Obj->getDataDirectory(Index, Data))
500     return;
501   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
502   W.printHex(FieldName + "Size", Data->Size);
503 }
504
505 void COFFDumper::printFileHeaders() {
506   // Print COFF header
507   const coff_file_header *COFFHeader = nullptr;
508   if (error(Obj->getCOFFHeader(COFFHeader)))
509     return;
510
511   time_t TDS = COFFHeader->TimeDateStamp;
512   char FormattedTime[20] = { };
513   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
514
515   {
516     DictScope D(W, "ImageFileHeader");
517     W.printEnum  ("Machine", COFFHeader->Machine,
518                     makeArrayRef(ImageFileMachineType));
519     W.printNumber("SectionCount", COFFHeader->NumberOfSections);
520     W.printHex   ("TimeDateStamp", FormattedTime, COFFHeader->TimeDateStamp);
521     W.printHex   ("PointerToSymbolTable", COFFHeader->PointerToSymbolTable);
522     W.printNumber("SymbolCount", COFFHeader->NumberOfSymbols);
523     W.printNumber("OptionalHeaderSize", COFFHeader->SizeOfOptionalHeader);
524     W.printFlags ("Characteristics", COFFHeader->Characteristics,
525                     makeArrayRef(ImageFileCharacteristics));
526   }
527
528   // Print PE header. This header does not exist if this is an object file and
529   // not an executable.
530   const pe32_header *PEHeader = nullptr;
531   if (error(Obj->getPE32Header(PEHeader)))
532     return;
533   if (PEHeader)
534     printPEHeader<pe32_header>(PEHeader);
535
536   const pe32plus_header *PEPlusHeader = nullptr;
537   if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
538     return;
539   if (PEPlusHeader)
540     printPEHeader<pe32plus_header>(PEPlusHeader);
541 }
542
543 template <class PEHeader>
544 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
545   DictScope D(W, "ImageOptionalHeader");
546   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
547   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
548   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
549   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
550   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
551   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
552   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
553   printBaseOfDataField(Hdr);
554   W.printHex   ("ImageBase", Hdr->ImageBase);
555   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
556   W.printNumber("FileAlignment", Hdr->FileAlignment);
557   W.printNumber("MajorOperatingSystemVersion",
558                 Hdr->MajorOperatingSystemVersion);
559   W.printNumber("MinorOperatingSystemVersion",
560                 Hdr->MinorOperatingSystemVersion);
561   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
562   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
563   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
564   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
565   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
566   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
567   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
568   W.printFlags ("Subsystem", Hdr->DLLCharacteristics,
569                 makeArrayRef(PEDLLCharacteristics));
570   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
571   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
572   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
573   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
574   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
575
576   if (Hdr->NumberOfRvaAndSize > 0) {
577     DictScope D(W, "DataDirectory");
578     static const char * const directory[] = {
579       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
580       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
581       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
582       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
583     };
584
585     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
586       printDataDirectory(i, directory[i]);
587     }
588   }
589 }
590
591 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
592   W.printHex("BaseOfData", Hdr->BaseOfData);
593 }
594
595 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
596
597 void COFFDumper::printCodeViewLineTables(const SectionRef &Section) {
598   StringRef Data;
599   if (error(Section.getContents(Data)))
600     return;
601
602   SmallVector<StringRef, 10> FunctionNames;
603   StringMap<StringRef> FunctionLineTables;
604   StringRef FileIndexToStringOffsetTable;
605   StringRef StringTable;
606
607   ListScope D(W, "CodeViewLineTables");
608   {
609     DataExtractor DE(Data, true, 4);
610     uint32_t Offset = 0,
611              Magic = DE.getU32(&Offset);
612     W.printHex("Magic", Magic);
613     if (Magic != COFF::DEBUG_SECTION_MAGIC) {
614       error(object_error::parse_failed);
615       return;
616     }
617
618     bool Finished = false;
619     while (DE.isValidOffset(Offset) && !Finished) {
620       // The section consists of a number of subsection in the following format:
621       // |Type|PayloadSize|Payload...|
622       uint32_t SubSectionType = DE.getU32(&Offset),
623                PayloadSize = DE.getU32(&Offset);
624       ListScope S(W, "Subsection");
625       W.printHex("Type", SubSectionType);
626       W.printHex("PayloadSize", PayloadSize);
627       if (PayloadSize > Data.size() - Offset) {
628         error(object_error::parse_failed);
629         return;
630       }
631
632       // Print the raw contents to simplify debugging if anything goes wrong
633       // afterwards.
634       StringRef Contents = Data.substr(Offset, PayloadSize);
635       W.printBinaryBlock("Contents", Contents);
636
637       switch (SubSectionType) {
638       case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
639         // Holds a PC to file:line table.  Some data to parse this subsection is
640         // stored in the other subsections, so just check sanity and store the
641         // pointers for deferred processing.
642
643         if (PayloadSize < 12) {
644           // There should be at least three words to store two function
645           // relocations and size of the code.
646           error(object_error::parse_failed);
647           return;
648         }
649
650         StringRef FunctionName;
651         if (error(resolveSymbolName(RelocMap[Obj->getCOFFSection(Section)],
652                                     Offset, FunctionName)))
653           return;
654         W.printString("FunctionName", FunctionName);
655         if (FunctionLineTables.count(FunctionName) != 0) {
656           // Saw debug info for this function already?
657           error(object_error::parse_failed);
658           return;
659         }
660
661         FunctionLineTables[FunctionName] = Contents;
662         FunctionNames.push_back(FunctionName);
663         break;
664       }
665       case COFF::DEBUG_STRING_TABLE_SUBSECTION:
666         if (PayloadSize == 0 || StringTable.data() != nullptr ||
667             Contents.back() != '\0') {
668           // Empty or duplicate or non-null-terminated subsection.
669           error(object_error::parse_failed);
670           return;
671         }
672         StringTable = Contents;
673         break;
674       case COFF::DEBUG_INDEX_SUBSECTION:
675         // Holds the translation table from file indices
676         // to offsets in the string table.
677
678         if (PayloadSize == 0 ||
679             FileIndexToStringOffsetTable.data() != nullptr) {
680           // Empty or duplicate subsection.
681           error(object_error::parse_failed);
682           return;
683         }
684         FileIndexToStringOffsetTable = Contents;
685         break;
686       }
687       Offset += PayloadSize;
688
689       // Align the reading pointer by 4.
690       Offset += (-Offset) % 4;
691     }
692   }
693
694   // Dump the line tables now that we've read all the subsections and know all
695   // the required information.
696   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
697     StringRef Name = FunctionNames[I];
698     ListScope S(W, "FunctionLineTable");
699     W.printString("FunctionName", Name);
700
701     DataExtractor DE(FunctionLineTables[Name], true, 4);
702     uint32_t Offset = 8;  // Skip relocations.
703     uint32_t FunctionSize = DE.getU32(&Offset);
704     W.printHex("CodeSize", FunctionSize);
705     while (DE.isValidOffset(Offset)) {
706       // For each range of lines with the same filename, we have a segment
707       // in the line table.  The filename string is accessed using double
708       // indirection to the string table subsection using the index subsection.
709       uint32_t OffsetInIndex = DE.getU32(&Offset),
710                SegmentLength   = DE.getU32(&Offset),
711                FullSegmentSize = DE.getU32(&Offset);
712       if (FullSegmentSize != 12 + 8 * SegmentLength) {
713         error(object_error::parse_failed);
714         return;
715       }
716
717       uint32_t FilenameOffset;
718       {
719         DataExtractor SDE(FileIndexToStringOffsetTable, true, 4);
720         uint32_t OffsetInSDE = OffsetInIndex;
721         if (!SDE.isValidOffset(OffsetInSDE)) {
722           error(object_error::parse_failed);
723           return;
724         }
725         FilenameOffset = SDE.getU32(&OffsetInSDE);
726       }
727
728       if (FilenameOffset == 0 || FilenameOffset + 1 >= StringTable.size() ||
729           StringTable.data()[FilenameOffset - 1] != '\0') {
730         // Each string in an F3 subsection should be preceded by a null
731         // character.
732         error(object_error::parse_failed);
733         return;
734       }
735
736       StringRef Filename(StringTable.data() + FilenameOffset);
737       ListScope S(W, "FilenameSegment");
738       W.printString("Filename", Filename);
739       for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
740            ++J) {
741         // Then go the (PC, LineNumber) pairs.  The line number is stored in the
742         // least significant 31 bits of the respective word in the table.
743         uint32_t PC = DE.getU32(&Offset),
744                  LineNumber = DE.getU32(&Offset) & 0x7fffffff;
745         if (PC >= FunctionSize) {
746           error(object_error::parse_failed);
747           return;
748         }
749         char Buffer[32];
750         format("+0x%X", PC).snprint(Buffer, 32);
751         W.printNumber(Buffer, LineNumber);
752       }
753     }
754   }
755 }
756
757 void COFFDumper::printSections() {
758   ListScope SectionsD(W, "Sections");
759   int SectionNumber = 0;
760   for (const SectionRef &Sec : Obj->sections()) {
761     ++SectionNumber;
762     const coff_section *Section = Obj->getCOFFSection(Sec);
763
764     StringRef Name;
765     if (error(Sec.getName(Name)))
766       Name = "";
767
768     DictScope D(W, "Section");
769     W.printNumber("Number", SectionNumber);
770     W.printBinary("Name", Name, Section->Name);
771     W.printHex   ("VirtualSize", Section->VirtualSize);
772     W.printHex   ("VirtualAddress", Section->VirtualAddress);
773     W.printNumber("RawDataSize", Section->SizeOfRawData);
774     W.printHex   ("PointerToRawData", Section->PointerToRawData);
775     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
776     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
777     W.printNumber("RelocationCount", Section->NumberOfRelocations);
778     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
779     W.printFlags ("Characteristics", Section->Characteristics,
780                     makeArrayRef(ImageSectionCharacteristics),
781                     COFF::SectionCharacteristics(0x00F00000));
782
783     if (opts::SectionRelocations) {
784       ListScope D(W, "Relocations");
785       for (const RelocationRef &Reloc : Sec.relocations())
786         printRelocation(Sec, Reloc);
787     }
788
789     if (opts::SectionSymbols) {
790       ListScope D(W, "Symbols");
791       for (const SymbolRef &Symbol : Obj->symbols()) {
792         bool Contained = false;
793         if (Sec.containsSymbol(Symbol, Contained) || !Contained)
794           continue;
795
796         printSymbol(Symbol);
797       }
798     }
799
800     if (Name == ".debug$S" && opts::CodeViewLineTables)
801       printCodeViewLineTables(Sec);
802
803     if (opts::SectionData) {
804       StringRef Data;
805       if (error(Sec.getContents(Data)))
806         break;
807
808       W.printBinaryBlock("SectionData", Data);
809     }
810   }
811 }
812
813 void COFFDumper::printRelocations() {
814   ListScope D(W, "Relocations");
815
816   int SectionNumber = 0;
817   for (const SectionRef &Section : Obj->sections()) {
818     ++SectionNumber;
819     StringRef Name;
820     if (error(Section.getName(Name)))
821       continue;
822
823     bool PrintedGroup = false;
824     for (const RelocationRef &Reloc : Section.relocations()) {
825       if (!PrintedGroup) {
826         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
827         W.indent();
828         PrintedGroup = true;
829       }
830
831       printRelocation(Section, Reloc);
832     }
833
834     if (PrintedGroup) {
835       W.unindent();
836       W.startLine() << "}\n";
837     }
838   }
839 }
840
841 void COFFDumper::printRelocation(const SectionRef &Section,
842                                  const RelocationRef &Reloc) {
843   uint64_t Offset;
844   uint64_t RelocType;
845   SmallString<32> RelocName;
846   StringRef SymbolName;
847   StringRef Contents;
848   if (error(Reloc.getOffset(Offset)))
849     return;
850   if (error(Reloc.getType(RelocType)))
851     return;
852   if (error(Reloc.getTypeName(RelocName)))
853     return;
854   symbol_iterator Symbol = Reloc.getSymbol();
855   if (error(Symbol->getName(SymbolName)))
856     return;
857   if (error(Section.getContents(Contents)))
858     return;
859
860   if (opts::ExpandRelocs) {
861     DictScope Group(W, "Relocation");
862     W.printHex("Offset", Offset);
863     W.printNumber("Type", RelocName, RelocType);
864     W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
865   } else {
866     raw_ostream& OS = W.startLine();
867     OS << W.hex(Offset)
868        << " " << RelocName
869        << " " << (SymbolName.size() > 0 ? SymbolName : "-")
870        << "\n";
871   }
872 }
873
874 void COFFDumper::printSymbols() {
875   ListScope Group(W, "Symbols");
876
877   for (const SymbolRef &Symbol : Obj->symbols())
878     printSymbol(Symbol);
879 }
880
881 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
882
883 void COFFDumper::printSymbol(const SymbolRef &Sym) {
884   DictScope D(W, "Symbol");
885
886   const coff_symbol *Symbol = Obj->getCOFFSymbol(Sym);
887   const coff_section *Section;
888   if (error_code EC = Obj->getSection(Symbol->SectionNumber, Section)) {
889     W.startLine() << "Invalid section number: " << EC.message() << "\n";
890     W.flush();
891     return;
892   }
893
894   StringRef SymbolName;
895   if (Obj->getSymbolName(Symbol, SymbolName))
896     SymbolName = "";
897
898   StringRef SectionName = "";
899   if (Section)
900     Obj->getSectionName(Section, SectionName);
901
902   W.printString("Name", SymbolName);
903   W.printNumber("Value", Symbol->Value);
904   W.printNumber("Section", SectionName, Symbol->SectionNumber);
905   W.printEnum  ("BaseType", Symbol->getBaseType(), makeArrayRef(ImageSymType));
906   W.printEnum  ("ComplexType", Symbol->getComplexType(),
907                                                    makeArrayRef(ImageSymDType));
908   W.printEnum  ("StorageClass", Symbol->StorageClass,
909                                                    makeArrayRef(ImageSymClass));
910   W.printNumber("AuxSymbolCount", Symbol->NumberOfAuxSymbols);
911
912   for (unsigned I = 0; I < Symbol->NumberOfAuxSymbols; ++I) {
913     if (Symbol->isFunctionDefinition()) {
914       const coff_aux_function_definition *Aux;
915       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
916         break;
917
918       DictScope AS(W, "AuxFunctionDef");
919       W.printNumber("TagIndex", Aux->TagIndex);
920       W.printNumber("TotalSize", Aux->TotalSize);
921       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
922       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
923       W.printBinary("Unused", makeArrayRef(Aux->Unused));
924
925     } else if (Symbol->isWeakExternal()) {
926       const coff_aux_weak_external *Aux;
927       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
928         break;
929
930       const coff_symbol *Linked;
931       StringRef LinkedName;
932       error_code EC;
933       if ((EC = Obj->getSymbol(Aux->TagIndex, Linked)) ||
934           (EC = Obj->getSymbolName(Linked, LinkedName))) {
935         LinkedName = "";
936         error(EC);
937       }
938
939       DictScope AS(W, "AuxWeakExternal");
940       W.printNumber("Linked", LinkedName, Aux->TagIndex);
941       W.printEnum  ("Search", Aux->Characteristics,
942                     makeArrayRef(WeakExternalCharacteristics));
943       W.printBinary("Unused", makeArrayRef(Aux->Unused));
944
945     } else if (Symbol->isFileRecord()) {
946       const coff_aux_file *Aux;
947       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
948         break;
949
950       DictScope AS(W, "AuxFileRecord");
951
952       StringRef Name(Aux->FileName,
953                      Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
954       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
955       break;
956     } else if (Symbol->isSectionDefinition()) {
957       const coff_aux_section_definition *Aux;
958       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
959         break;
960
961       DictScope AS(W, "AuxSectionDef");
962       W.printNumber("Length", Aux->Length);
963       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
964       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
965       W.printHex("Checksum", Aux->CheckSum);
966       W.printNumber("Number", Aux->Number);
967       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
968       W.printBinary("Unused", makeArrayRef(Aux->Unused));
969
970       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
971           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
972         const coff_section *Assoc;
973         StringRef AssocName;
974         error_code EC;
975         if ((EC = Obj->getSection(Aux->Number, Assoc)) ||
976             (EC = Obj->getSectionName(Assoc, AssocName))) {
977           AssocName = "";
978           error(EC);
979         }
980
981         W.printNumber("AssocSection", AssocName, Aux->Number);
982       }
983     } else if (Symbol->isCLRToken()) {
984       const coff_aux_clr_token *Aux;
985       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
986         break;
987
988       const coff_symbol *ReferredSym;
989       StringRef ReferredName;
990       error_code EC;
991       if ((EC = Obj->getSymbol(Aux->SymbolTableIndex, ReferredSym)) ||
992           (EC = Obj->getSymbolName(ReferredSym, ReferredName))) {
993         ReferredName = "";
994         error(EC);
995       }
996
997       DictScope AS(W, "AuxCLRToken");
998       W.printNumber("AuxType", Aux->AuxType);
999       W.printNumber("Reserved", Aux->Reserved);
1000       W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1001       W.printBinary("Unused", makeArrayRef(Aux->Unused));
1002
1003     } else {
1004       W.startLine() << "<unhandled auxiliary record>\n";
1005     }
1006   }
1007 }
1008
1009 void COFFDumper::printUnwindInfo() {
1010   const coff_file_header *Header;
1011   if (error(Obj->getCOFFHeader(Header)))
1012     return;
1013
1014   ListScope D(W, "UnwindInformation");
1015   if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
1016     W.startLine() << "Unsupported image machine type "
1017               "(currently only AMD64 is supported).\n";
1018     return;
1019   }
1020
1021   printX64UnwindInfo();
1022 }
1023
1024 void COFFDumper::printX64UnwindInfo() {
1025   for (const SectionRef &Section : Obj->sections()) {
1026     StringRef Name;
1027     if (error(Section.getName(Name)))
1028       continue;
1029     if (Name != ".pdata" && !Name.startswith(".pdata$"))
1030       continue;
1031
1032     const coff_section *PData = Obj->getCOFFSection(Section);
1033
1034     ArrayRef<uint8_t> Contents;
1035     if (error(Obj->getSectionContents(PData, Contents)) || Contents.empty())
1036       continue;
1037
1038     ArrayRef<RuntimeFunction> RFs(
1039       reinterpret_cast<const RuntimeFunction *>(Contents.data()),
1040       Contents.size() / sizeof(RuntimeFunction));
1041
1042     for (const RuntimeFunction *I = RFs.begin(), *E = RFs.end(); I < E; ++I) {
1043       const uint64_t OffsetInSection = std::distance(RFs.begin(), I)
1044                                      * sizeof(RuntimeFunction);
1045
1046       printRuntimeFunction(*I, OffsetInSection, RelocMap[PData]);
1047     }
1048   }
1049 }
1050
1051 void COFFDumper::printRuntimeFunction(
1052     const RuntimeFunction& RTF,
1053     uint64_t OffsetInSection,
1054     const std::vector<RelocationRef> &Rels) {
1055
1056   DictScope D(W, "RuntimeFunction");
1057   W.printString("StartAddress",
1058                 formatSymbol(Rels, OffsetInSection + 0, RTF.StartAddress));
1059   W.printString("EndAddress",
1060                 formatSymbol(Rels, OffsetInSection + 4, RTF.EndAddress));
1061   W.printString("UnwindInfoAddress",
1062                 formatSymbol(Rels, OffsetInSection + 8, RTF.UnwindInfoOffset));
1063
1064   const coff_section* XData = nullptr;
1065   uint64_t UnwindInfoOffset = 0;
1066   if (error(getSection(Rels, OffsetInSection + 8, &XData, &UnwindInfoOffset)))
1067     return;
1068
1069   ArrayRef<uint8_t> XContents;
1070   if (error(Obj->getSectionContents(XData, XContents)) || XContents.empty())
1071     return;
1072
1073   UnwindInfoOffset += RTF.UnwindInfoOffset;
1074   if (UnwindInfoOffset > XContents.size())
1075     return;
1076
1077   const Win64EH::UnwindInfo *UI =
1078     reinterpret_cast<const Win64EH::UnwindInfo *>(
1079       XContents.data() + UnwindInfoOffset);
1080
1081   printUnwindInfo(*UI, UnwindInfoOffset, RelocMap[XData]);
1082 }
1083
1084 void COFFDumper::printUnwindInfo(
1085     const Win64EH::UnwindInfo& UI,
1086     uint64_t OffsetInSection,
1087     const std::vector<RelocationRef> &Rels) {
1088   DictScope D(W, "UnwindInfo");
1089   W.printNumber("Version", UI.getVersion());
1090   W.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags));
1091   W.printNumber("PrologSize", UI.PrologSize);
1092   if (UI.getFrameRegister() != 0) {
1093     W.printEnum("FrameRegister", UI.getFrameRegister(),
1094                 makeArrayRef(UnwindOpInfo));
1095     W.printHex("FrameOffset", UI.getFrameOffset());
1096   } else {
1097     W.printString("FrameRegister", StringRef("-"));
1098     W.printString("FrameOffset", StringRef("-"));
1099   }
1100
1101   W.printNumber("UnwindCodeCount", UI.NumCodes);
1102   {
1103     ListScope CodesD(W, "UnwindCodes");
1104     ArrayRef<UnwindCode> UCs(&UI.UnwindCodes[0], UI.NumCodes);
1105     for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ++I) {
1106       unsigned UsedSlots = getNumUsedSlots(*I);
1107       if (UsedSlots > UCs.size()) {
1108         errs() << "Corrupt unwind data";
1109         return;
1110       }
1111       printUnwindCode(UI, ArrayRef<UnwindCode>(I, E));
1112       I += UsedSlots - 1;
1113     }
1114   }
1115
1116   uint64_t LSDAOffset = OffsetInSection + getOffsetOfLSDA(UI);
1117   if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
1118     W.printString("Handler", formatSymbol(Rels, LSDAOffset,
1119                                         UI.getLanguageSpecificHandlerOffset()));
1120   } else if (UI.getFlags() & UNW_ChainInfo) {
1121     const RuntimeFunction *Chained = UI.getChainedFunctionEntry();
1122     if (Chained) {
1123       DictScope D(W, "Chained");
1124       W.printString("StartAddress", formatSymbol(Rels, LSDAOffset + 0,
1125                                                         Chained->StartAddress));
1126       W.printString("EndAddress", formatSymbol(Rels, LSDAOffset + 4,
1127                                                           Chained->EndAddress));
1128       W.printString("UnwindInfoAddress", formatSymbol(Rels, LSDAOffset + 8,
1129                                                     Chained->UnwindInfoOffset));
1130     }
1131   }
1132 }
1133
1134 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
1135 // the unwind codes array, this function requires that the correct number of
1136 // slots is provided.
1137 void COFFDumper::printUnwindCode(const Win64EH::UnwindInfo& UI,
1138                                  ArrayRef<UnwindCode> UCs) {
1139   assert(UCs.size() >= getNumUsedSlots(UCs[0]));
1140
1141   W.startLine() << format("0x%02X: ", unsigned(UCs[0].u.CodeOffset))
1142                 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
1143
1144   uint32_t AllocSize = 0;
1145
1146   switch (UCs[0].getUnwindOp()) {
1147   case UOP_PushNonVol:
1148     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo());
1149     break;
1150
1151   case UOP_AllocLarge:
1152     if (UCs[0].getOpInfo() == 0) {
1153       AllocSize = UCs[1].FrameOffset * 8;
1154     } else {
1155       AllocSize = getLargeSlotValue(UCs);
1156     }
1157     outs() << " size=" << AllocSize;
1158     break;
1159   case UOP_AllocSmall:
1160     outs() << " size=" << ((UCs[0].getOpInfo() + 1) * 8);
1161     break;
1162   case UOP_SetFPReg:
1163     if (UI.getFrameRegister() == 0) {
1164       outs() << " reg=<invalid>";
1165     } else {
1166       outs() << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
1167              << format(", offset=0x%X", UI.getFrameOffset() * 16);
1168     }
1169     break;
1170   case UOP_SaveNonVol:
1171     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1172            << format(", offset=0x%X", UCs[1].FrameOffset * 8);
1173     break;
1174   case UOP_SaveNonVolBig:
1175     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1176            << format(", offset=0x%X", getLargeSlotValue(UCs));
1177     break;
1178   case UOP_SaveXMM128:
1179     outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1180            << format(", offset=0x%X", UCs[1].FrameOffset * 16);
1181     break;
1182   case UOP_SaveXMM128Big:
1183     outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1184            << format(", offset=0x%X", getLargeSlotValue(UCs));
1185     break;
1186   case UOP_PushMachFrame:
1187     outs() << " errcode=" << (UCs[0].getOpInfo() == 0 ? "no" : "yes");
1188     break;
1189   }
1190
1191   outs() << "\n";
1192 }