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