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