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