dd6f3d6ba817d3de5b258deb946f3c68b6736ec0
[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,
285                         IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VIRTUAL_ADDRESS),
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   if (PEHeader)
606     printPEHeader<pe32_header>(PEHeader);
607
608   const pe32plus_header *PEPlusHeader = 0;
609   if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
610     return;
611   if (PEPlusHeader)
612     printPEHeader<pe32plus_header>(PEPlusHeader);
613 }
614
615 template <class PEHeader>
616 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
617   DictScope D(W, "ImageOptionalHeader");
618   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
619   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
620   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
621   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
622   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
623   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
624   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
625   printBaseOfDataField(Hdr);
626   W.printHex   ("ImageBase", Hdr->ImageBase);
627   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
628   W.printNumber("FileAlignment", Hdr->FileAlignment);
629   W.printNumber("MajorOperatingSystemVersion",
630                 Hdr->MajorOperatingSystemVersion);
631   W.printNumber("MinorOperatingSystemVersion",
632                 Hdr->MinorOperatingSystemVersion);
633   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
634   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
635   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
636   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
637   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
638   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
639   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
640   W.printFlags ("Subsystem", Hdr->DLLCharacteristics,
641                 makeArrayRef(PEDLLCharacteristics));
642   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
643   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
644   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
645   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
646   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
647
648   if (Hdr->NumberOfRvaAndSize > 0) {
649     DictScope D(W, "DataDirectory");
650     static const char * const directory[] = {
651       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
652       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
653       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
654       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
655     };
656
657     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
658       printDataDirectory(i, directory[i]);
659     }
660   }
661 }
662
663 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
664   W.printHex("BaseOfData", Hdr->BaseOfData);
665 }
666
667 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
668
669 void COFFDumper::printCodeViewLineTables(section_iterator SecI) {
670   StringRef Data;
671   if (error(SecI->getContents(Data))) return;
672
673   SmallVector<StringRef, 10> FunctionNames;
674   StringMap<StringRef> FunctionLineTables;
675   StringRef FileIndexToStringOffsetTable;
676   StringRef StringTable;
677
678   ListScope D(W, "CodeViewLineTables");
679   {
680     DataExtractor DE(Data, true, 4);
681     uint32_t Offset = 0,
682              Magic = DE.getU32(&Offset);
683     W.printHex("Magic", Magic);
684     if (Magic != COFF::DEBUG_SECTION_MAGIC) {
685       error(object_error::parse_failed);
686       return;
687     }
688
689     bool Finished = false;
690     while (DE.isValidOffset(Offset) && !Finished) {
691       // The section consists of a number of subsection in the following format:
692       // |Type|PayloadSize|Payload...|
693       uint32_t SubSectionType = DE.getU32(&Offset),
694                PayloadSize = DE.getU32(&Offset);
695       ListScope S(W, "Subsection");
696       W.printHex("Type", SubSectionType);
697       W.printHex("PayloadSize", PayloadSize);
698       if (PayloadSize > Data.size() - Offset) {
699         error(object_error::parse_failed);
700         return;
701       }
702
703       // Print the raw contents to simplify debugging if anything goes wrong
704       // afterwards.
705       StringRef Contents = Data.substr(Offset, PayloadSize);
706       W.printBinaryBlock("Contents", Contents);
707
708       switch (SubSectionType) {
709       case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
710         // Holds a PC to file:line table.  Some data to parse this subsection is
711         // stored in the other subsections, so just check sanity and store the
712         // pointers for deferred processing.
713
714         if (PayloadSize < 12) {
715           // There should be at least three words to store two function
716           // relocations and size of the code.
717           error(object_error::parse_failed);
718           return;
719         }
720
721         StringRef FunctionName;
722         if (error(resolveSymbolName(RelocMap[Obj->getCOFFSection(SecI)], Offset,
723                                     FunctionName)))
724           return;
725         W.printString("FunctionName", FunctionName);
726         if (FunctionLineTables.count(FunctionName) != 0) {
727           // Saw debug info for this function already?
728           error(object_error::parse_failed);
729           return;
730         }
731
732         FunctionLineTables[FunctionName] = Contents;
733         FunctionNames.push_back(FunctionName);
734         break;
735       }
736       case COFF::DEBUG_STRING_TABLE_SUBSECTION:
737         if (PayloadSize == 0 || StringTable.data() != 0 ||
738             Contents.back() != '\0') {
739           // Empty or duplicate or non-null-terminated subsection.
740           error(object_error::parse_failed);
741           return;
742         }
743         StringTable = Contents;
744         break;
745       case COFF::DEBUG_INDEX_SUBSECTION:
746         // Holds the translation table from file indices
747         // to offsets in the string table.
748
749         if (PayloadSize == 0 || FileIndexToStringOffsetTable.data() != 0) {
750           // Empty or duplicate subsection.
751           error(object_error::parse_failed);
752           return;
753         }
754         FileIndexToStringOffsetTable = Contents;
755         break;
756       }
757       Offset += PayloadSize;
758
759       // Align the reading pointer by 4.
760       Offset += (-Offset) % 4;
761     }
762   }
763
764   // Dump the line tables now that we've read all the subsections and know all
765   // the required information.
766   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
767     StringRef Name = FunctionNames[I];
768     ListScope S(W, "FunctionLineTable");
769     W.printString("FunctionName", Name);
770
771     DataExtractor DE(FunctionLineTables[Name], true, 4);
772     uint32_t Offset = 8;  // Skip relocations.
773     uint32_t FunctionSize = DE.getU32(&Offset);
774     W.printHex("CodeSize", FunctionSize);
775     while (DE.isValidOffset(Offset)) {
776       // For each range of lines with the same filename, we have a segment
777       // in the line table.  The filename string is accessed using double
778       // indirection to the string table subsection using the index subsection.
779       uint32_t OffsetInIndex = DE.getU32(&Offset),
780                SegmentLength   = DE.getU32(&Offset),
781                FullSegmentSize = DE.getU32(&Offset);
782       if (FullSegmentSize != 12 + 8 * SegmentLength) {
783         error(object_error::parse_failed);
784         return;
785       }
786
787       uint32_t FilenameOffset;
788       {
789         DataExtractor SDE(FileIndexToStringOffsetTable, true, 4);
790         uint32_t OffsetInSDE = OffsetInIndex;
791         if (!SDE.isValidOffset(OffsetInSDE)) {
792           error(object_error::parse_failed);
793           return;
794         }
795         FilenameOffset = SDE.getU32(&OffsetInSDE);
796       }
797
798       if (FilenameOffset == 0 || FilenameOffset + 1 >= StringTable.size() ||
799           StringTable.data()[FilenameOffset - 1] != '\0') {
800         // Each string in an F3 subsection should be preceded by a null
801         // character.
802         error(object_error::parse_failed);
803         return;
804       }
805
806       StringRef Filename(StringTable.data() + FilenameOffset);
807       ListScope S(W, "FilenameSegment");
808       W.printString("Filename", Filename);
809       for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
810            ++J) {
811         // Then go the (PC, LineNumber) pairs.  The line number is stored in the
812         // least significant 31 bits of the respective word in the table.
813         uint32_t PC = DE.getU32(&Offset),
814                  LineNumber = DE.getU32(&Offset) & 0x7fffffff;
815         if (PC >= FunctionSize) {
816           error(object_error::parse_failed);
817           return;
818         }
819         char Buffer[32];
820         format("+0x%X", PC).snprint(Buffer, 32);
821         W.printNumber(Buffer, LineNumber);
822       }
823     }
824   }
825 }
826
827 void COFFDumper::printSections() {
828   error_code EC;
829
830   ListScope SectionsD(W, "Sections");
831   int SectionNumber = 0;
832   for (section_iterator SecI = Obj->begin_sections(),
833                         SecE = Obj->end_sections();
834                         SecI != SecE; SecI.increment(EC)) {
835     if (error(EC))
836       break;
837
838     ++SectionNumber;
839     const coff_section *Section = Obj->getCOFFSection(SecI);
840
841     StringRef Name;
842     if (error(SecI->getName(Name)))
843         Name = "";
844
845     DictScope D(W, "Section");
846     W.printNumber("Number", SectionNumber);
847     W.printBinary("Name", Name, Section->Name);
848     W.printHex   ("VirtualSize", Section->VirtualSize);
849     W.printHex   ("VirtualAddress", Section->VirtualAddress);
850     W.printNumber("RawDataSize", Section->SizeOfRawData);
851     W.printHex   ("PointerToRawData", Section->PointerToRawData);
852     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
853     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
854     W.printNumber("RelocationCount", Section->NumberOfRelocations);
855     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
856     W.printFlags ("Characteristics", Section->Characteristics,
857                     makeArrayRef(ImageSectionCharacteristics),
858                     COFF::SectionCharacteristics(0x00F00000));
859
860     if (opts::SectionRelocations) {
861       ListScope D(W, "Relocations");
862       for (relocation_iterator RelI = SecI->begin_relocations(),
863                                RelE = SecI->end_relocations();
864                                RelI != RelE; RelI.increment(EC)) {
865         if (error(EC)) break;
866
867         printRelocation(SecI, RelI);
868       }
869     }
870
871     if (opts::SectionSymbols) {
872       ListScope D(W, "Symbols");
873       for (symbol_iterator SymI = Obj->begin_symbols(),
874                            SymE = Obj->end_symbols();
875                            SymI != SymE; SymI.increment(EC)) {
876         if (error(EC)) break;
877
878         bool Contained = false;
879         if (SecI->containsSymbol(*SymI, Contained) || !Contained)
880           continue;
881
882         printSymbol(SymI);
883       }
884     }
885
886     if (Name == ".debug$S" && opts::CodeViewLineTables)
887       printCodeViewLineTables(SecI);
888
889     if (opts::SectionData) {
890       StringRef Data;
891       if (error(SecI->getContents(Data))) break;
892
893       W.printBinaryBlock("SectionData", Data);
894     }
895   }
896 }
897
898 void COFFDumper::printRelocations() {
899   ListScope D(W, "Relocations");
900
901   error_code EC;
902   int SectionNumber = 0;
903   for (section_iterator SecI = Obj->begin_sections(),
904                         SecE = Obj->end_sections();
905                         SecI != SecE; SecI.increment(EC)) {
906     ++SectionNumber;
907     if (error(EC))
908       break;
909
910     StringRef Name;
911     if (error(SecI->getName(Name)))
912       continue;
913
914     bool PrintedGroup = false;
915     for (relocation_iterator RelI = SecI->begin_relocations(),
916                              RelE = SecI->end_relocations();
917                              RelI != RelE; RelI.increment(EC)) {
918       if (error(EC)) break;
919
920       if (!PrintedGroup) {
921         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
922         W.indent();
923         PrintedGroup = true;
924       }
925
926       printRelocation(SecI, RelI);
927     }
928
929     if (PrintedGroup) {
930       W.unindent();
931       W.startLine() << "}\n";
932     }
933   }
934 }
935
936 void COFFDumper::printRelocation(section_iterator SecI,
937                                  relocation_iterator RelI) {
938   uint64_t Offset;
939   uint64_t RelocType;
940   SmallString<32> RelocName;
941   StringRef SymbolName;
942   StringRef Contents;
943   if (error(RelI->getOffset(Offset))) return;
944   if (error(RelI->getType(RelocType))) return;
945   if (error(RelI->getTypeName(RelocName))) return;
946   symbol_iterator Symbol = RelI->getSymbol();
947   if (error(Symbol->getName(SymbolName))) return;
948   if (error(SecI->getContents(Contents))) return;
949
950   if (opts::ExpandRelocs) {
951     DictScope Group(W, "Relocation");
952     W.printHex("Offset", Offset);
953     W.printNumber("Type", RelocName, RelocType);
954     W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
955   } else {
956     raw_ostream& OS = W.startLine();
957     OS << W.hex(Offset)
958        << " " << RelocName
959        << " " << (SymbolName.size() > 0 ? SymbolName : "-")
960        << "\n";
961   }
962 }
963
964 void COFFDumper::printSymbols() {
965   ListScope Group(W, "Symbols");
966
967   error_code EC;
968   for (symbol_iterator SymI = Obj->begin_symbols(),
969                        SymE = Obj->end_symbols();
970                        SymI != SymE; SymI.increment(EC)) {
971     if (error(EC)) break;
972
973     printSymbol(SymI);
974   }
975 }
976
977 void COFFDumper::printDynamicSymbols() {
978   ListScope Group(W, "DynamicSymbols");
979 }
980
981 void COFFDumper::printSymbol(symbol_iterator SymI) {
982   DictScope D(W, "Symbol");
983
984   const coff_symbol *Symbol = Obj->getCOFFSymbol(SymI);
985   const coff_section *Section;
986   if (error_code EC = Obj->getSection(Symbol->SectionNumber, Section)) {
987     W.startLine() << "Invalid section number: " << EC.message() << "\n";
988     W.flush();
989     return;
990   }
991
992   StringRef SymbolName;
993   if (Obj->getSymbolName(Symbol, SymbolName))
994     SymbolName = "";
995
996   StringRef SectionName = "";
997   if (Section)
998     Obj->getSectionName(Section, SectionName);
999
1000   W.printString("Name", SymbolName);
1001   W.printNumber("Value", Symbol->Value);
1002   W.printNumber("Section", SectionName, Symbol->SectionNumber);
1003   W.printEnum  ("BaseType", Symbol->getBaseType(), makeArrayRef(ImageSymType));
1004   W.printEnum  ("ComplexType", Symbol->getComplexType(),
1005                                                    makeArrayRef(ImageSymDType));
1006   W.printEnum  ("StorageClass", Symbol->StorageClass,
1007                                                    makeArrayRef(ImageSymClass));
1008   W.printNumber("AuxSymbolCount", Symbol->NumberOfAuxSymbols);
1009
1010   for (unsigned I = 0; I < Symbol->NumberOfAuxSymbols; ++I) {
1011     if (Symbol->StorageClass     == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
1012         Symbol->getBaseType()    == COFF::IMAGE_SYM_TYPE_NULL &&
1013         Symbol->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
1014         Symbol->SectionNumber > 0) {
1015       const coff_aux_function_definition *Aux;
1016       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1017         break;
1018
1019       DictScope AS(W, "AuxFunctionDef");
1020       W.printNumber("TagIndex", Aux->TagIndex);
1021       W.printNumber("TotalSize", Aux->TotalSize);
1022       W.printHex("PointerToLineNumber", Aux->PointerToLineNumber);
1023       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1024       W.printBinary("Unused", makeArrayRef(Aux->Unused));
1025
1026     } else if (
1027         Symbol->StorageClass   == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL ||
1028         (Symbol->StorageClass  == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
1029          Symbol->SectionNumber == 0 &&
1030          Symbol->Value         == 0)) {
1031       const coff_aux_weak_external_definition *Aux;
1032       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1033         break;
1034
1035       const coff_symbol *Linked;
1036       StringRef LinkedName;
1037       error_code EC;
1038       if ((EC = Obj->getSymbol(Aux->TagIndex, Linked)) ||
1039           (EC = Obj->getSymbolName(Linked, LinkedName))) {
1040         LinkedName = "";
1041         error(EC);
1042       }
1043
1044       DictScope AS(W, "AuxWeakExternal");
1045       W.printNumber("Linked", LinkedName, Aux->TagIndex);
1046       W.printEnum  ("Search", Aux->Characteristics,
1047                     makeArrayRef(WeakExternalCharacteristics));
1048       W.printBinary("Unused", Aux->Unused);
1049
1050     } else if (Symbol->StorageClass == COFF::IMAGE_SYM_CLASS_FILE) {
1051       const coff_aux_file_record *Aux;
1052       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1053         break;
1054
1055       DictScope AS(W, "AuxFileRecord");
1056       W.printString("FileName", StringRef(Aux->FileName));
1057
1058     } else if (Symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC ||
1059                (Symbol->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
1060                 Symbol->SectionNumber != COFF::IMAGE_SYM_UNDEFINED)) {
1061       const coff_aux_section_definition *Aux;
1062       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1063         break;
1064
1065       DictScope AS(W, "AuxSectionDef");
1066       W.printNumber("Length", Aux->Length);
1067       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1068       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1069       W.printHex("Checksum", Aux->CheckSum);
1070       W.printNumber("Number", Aux->Number);
1071       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1072       W.printBinary("Unused", makeArrayRef(Aux->Unused));
1073
1074       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1075           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1076         const coff_section *Assoc;
1077         StringRef AssocName;
1078         error_code EC;
1079         if ((EC = Obj->getSection(Aux->Number, Assoc)) ||
1080             (EC = Obj->getSectionName(Assoc, AssocName))) {
1081           AssocName = "";
1082           error(EC);
1083         }
1084
1085         W.printNumber("AssocSection", AssocName, Aux->Number);
1086       }
1087     } else if (Symbol->StorageClass == COFF::IMAGE_SYM_CLASS_CLR_TOKEN) {
1088       const coff_aux_clr_token *Aux;
1089       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1090         break;
1091
1092       DictScope AS(W, "AuxCLRToken");
1093       W.printNumber("AuxType", Aux->AuxType);
1094       W.printNumber("Reserved", Aux->Reserved);
1095       W.printNumber("SymbolTableIndex", Aux->SymbolTableIndex);
1096       W.printBinary("Unused", Aux->Unused);
1097
1098     } else {
1099       W.startLine() << "<unhandled auxiliary record>\n";
1100     }
1101   }
1102 }
1103
1104 void COFFDumper::printUnwindInfo() {
1105   const coff_file_header *Header;
1106   if (error(Obj->getCOFFHeader(Header)))
1107     return;
1108
1109   ListScope D(W, "UnwindInformation");
1110   if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
1111     W.startLine() << "Unsupported image machine type "
1112               "(currently only AMD64 is supported).\n";
1113     return;
1114   }
1115
1116   printX64UnwindInfo();
1117 }
1118
1119 void COFFDumper::printX64UnwindInfo() {
1120   error_code EC;
1121   for (section_iterator SecI = Obj->begin_sections(),
1122                         SecE = Obj->end_sections();
1123                         SecI != SecE; SecI.increment(EC)) {
1124     if (error(EC)) break;
1125
1126     StringRef Name;
1127     if (error(SecI->getName(Name)))
1128       continue;
1129     if (Name != ".pdata" && !Name.startswith(".pdata$"))
1130       continue;
1131
1132     const coff_section *PData = Obj->getCOFFSection(SecI);
1133
1134     ArrayRef<uint8_t> Contents;
1135     if (error(Obj->getSectionContents(PData, Contents)) ||
1136         Contents.empty())
1137       continue;
1138
1139     ArrayRef<RuntimeFunction> RFs(
1140       reinterpret_cast<const RuntimeFunction *>(Contents.data()),
1141       Contents.size() / sizeof(RuntimeFunction));
1142
1143     for (const RuntimeFunction *I = RFs.begin(), *E = RFs.end(); I < E; ++I) {
1144       const uint64_t OffsetInSection = std::distance(RFs.begin(), I)
1145                                      * sizeof(RuntimeFunction);
1146
1147       printRuntimeFunction(*I, OffsetInSection, RelocMap[PData]);
1148     }
1149   }
1150 }
1151
1152 void COFFDumper::printRuntimeFunction(
1153     const RuntimeFunction& RTF,
1154     uint64_t OffsetInSection,
1155     const std::vector<RelocationRef> &Rels) {
1156
1157   DictScope D(W, "RuntimeFunction");
1158   W.printString("StartAddress",
1159                 formatSymbol(Rels, OffsetInSection + 0, RTF.StartAddress));
1160   W.printString("EndAddress",
1161                 formatSymbol(Rels, OffsetInSection + 4, RTF.EndAddress));
1162   W.printString("UnwindInfoAddress",
1163                 formatSymbol(Rels, OffsetInSection + 8, RTF.UnwindInfoOffset));
1164
1165   const coff_section* XData = 0;
1166   uint64_t UnwindInfoOffset = 0;
1167   if (error(getSection(Rels, OffsetInSection + 8, &XData, &UnwindInfoOffset)))
1168     return;
1169
1170   ArrayRef<uint8_t> XContents;
1171   if (error(Obj->getSectionContents(XData, XContents)) || XContents.empty())
1172     return;
1173
1174   UnwindInfoOffset += RTF.UnwindInfoOffset;
1175   if (UnwindInfoOffset > XContents.size())
1176     return;
1177
1178   const Win64EH::UnwindInfo *UI =
1179     reinterpret_cast<const Win64EH::UnwindInfo *>(
1180       XContents.data() + UnwindInfoOffset);
1181
1182   printUnwindInfo(*UI, UnwindInfoOffset, RelocMap[XData]);
1183 }
1184
1185 void COFFDumper::printUnwindInfo(
1186     const Win64EH::UnwindInfo& UI,
1187     uint64_t OffsetInSection,
1188     const std::vector<RelocationRef> &Rels) {
1189   DictScope D(W, "UnwindInfo");
1190   W.printNumber("Version", UI.getVersion());
1191   W.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags));
1192   W.printNumber("PrologSize", UI.PrologSize);
1193   if (UI.getFrameRegister() != 0) {
1194     W.printEnum("FrameRegister", UI.getFrameRegister(),
1195                 makeArrayRef(UnwindOpInfo));
1196     W.printHex("FrameOffset", UI.getFrameOffset());
1197   } else {
1198     W.printString("FrameRegister", StringRef("-"));
1199     W.printString("FrameOffset", StringRef("-"));
1200   }
1201
1202   W.printNumber("UnwindCodeCount", UI.NumCodes);
1203   {
1204     ListScope CodesD(W, "UnwindCodes");
1205     ArrayRef<UnwindCode> UCs(&UI.UnwindCodes[0], UI.NumCodes);
1206     for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ++I) {
1207       unsigned UsedSlots = getNumUsedSlots(*I);
1208       if (UsedSlots > UCs.size()) {
1209         errs() << "Corrupt unwind data";
1210         return;
1211       }
1212       printUnwindCode(UI, ArrayRef<UnwindCode>(I, E));
1213       I += UsedSlots - 1;
1214     }
1215   }
1216
1217   uint64_t LSDAOffset = OffsetInSection + getOffsetOfLSDA(UI);
1218   if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
1219     W.printString("Handler", formatSymbol(Rels, LSDAOffset,
1220                                         UI.getLanguageSpecificHandlerOffset()));
1221   } else if (UI.getFlags() & UNW_ChainInfo) {
1222     const RuntimeFunction *Chained = UI.getChainedFunctionEntry();
1223     if (Chained) {
1224       DictScope D(W, "Chained");
1225       W.printString("StartAddress", formatSymbol(Rels, LSDAOffset + 0,
1226                                                         Chained->StartAddress));
1227       W.printString("EndAddress", formatSymbol(Rels, LSDAOffset + 4,
1228                                                           Chained->EndAddress));
1229       W.printString("UnwindInfoAddress", formatSymbol(Rels, LSDAOffset + 8,
1230                                                     Chained->UnwindInfoOffset));
1231     }
1232   }
1233 }
1234
1235 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
1236 // the unwind codes array, this function requires that the correct number of
1237 // slots is provided.
1238 void COFFDumper::printUnwindCode(const Win64EH::UnwindInfo& UI,
1239                                  ArrayRef<UnwindCode> UCs) {
1240   assert(UCs.size() >= getNumUsedSlots(UCs[0]));
1241
1242   W.startLine() << format("0x%02X: ", unsigned(UCs[0].u.CodeOffset))
1243                 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
1244
1245   uint32_t AllocSize = 0;
1246
1247   switch (UCs[0].getUnwindOp()) {
1248   case UOP_PushNonVol:
1249     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo());
1250     break;
1251
1252   case UOP_AllocLarge:
1253     if (UCs[0].getOpInfo() == 0) {
1254       AllocSize = UCs[1].FrameOffset * 8;
1255     } else {
1256       AllocSize = getLargeSlotValue(UCs);
1257     }
1258     outs() << " size=" << AllocSize;
1259     break;
1260   case UOP_AllocSmall:
1261     outs() << " size=" << ((UCs[0].getOpInfo() + 1) * 8);
1262     break;
1263   case UOP_SetFPReg:
1264     if (UI.getFrameRegister() == 0) {
1265       outs() << " reg=<invalid>";
1266     } else {
1267       outs() << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
1268              << format(", offset=0x%X", UI.getFrameOffset() * 16);
1269     }
1270     break;
1271   case UOP_SaveNonVol:
1272     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1273            << format(", offset=0x%X", UCs[1].FrameOffset * 8);
1274     break;
1275   case UOP_SaveNonVolBig:
1276     outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1277            << format(", offset=0x%X", getLargeSlotValue(UCs));
1278     break;
1279   case UOP_SaveXMM128:
1280     outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1281            << format(", offset=0x%X", UCs[1].FrameOffset * 16);
1282     break;
1283   case UOP_SaveXMM128Big:
1284     outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1285            << format(", offset=0x%X", getLargeSlotValue(UCs));
1286     break;
1287   case UOP_PushMachFrame:
1288     outs() << " errcode=" << (UCs[0].getOpInfo() == 0 ? "no" : "yes");
1289     break;
1290   }
1291
1292   outs() << "\n";
1293 }