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