OSDN Git Service

am cd06393a: Merge "Update LLVM for 3.5 rebase (r209712)."
[android-x86/external-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 "Win64EHDumper.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Object/COFF.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/COFF.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/DataExtractor.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/Win64EH.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/system_error.h"
33 #include <algorithm>
34 #include <cstring>
35 #include <time.h>
36
37 using namespace llvm;
38 using namespace llvm::object;
39 using namespace llvm::Win64EH;
40
41 namespace {
42
43 class COFFDumper : public ObjDumper {
44 public:
45   COFFDumper(const llvm::object::COFFObjectFile *Obj, StreamWriter& Writer)
46     : ObjDumper(Writer)
47     , Obj(Obj) {
48     cacheRelocations();
49   }
50
51   virtual void printFileHeaders() override;
52   virtual void printSections() override;
53   virtual void printRelocations() override;
54   virtual void printSymbols() override;
55   virtual void printDynamicSymbols() override;
56   virtual void printUnwindInfo() override;
57
58 private:
59   void printSymbol(const SymbolRef &Sym);
60   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc);
61   void printDataDirectory(uint32_t Index, const std::string &FieldName);
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 printCodeViewLineTables(const SectionRef &Section);
68
69   void cacheRelocations();
70
71   error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
72                            SymbolRef &Sym);
73   error_code resolveSymbolName(const coff_section *Section, uint64_t Offset,
74                                StringRef &Name);
75
76   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
77
78   const llvm::object::COFFObjectFile *Obj;
79   RelocMapTy RelocMap;
80 };
81
82 } // namespace
83
84
85 namespace llvm {
86
87 error_code createCOFFDumper(const object::ObjectFile *Obj, StreamWriter &Writer,
88                             std::unique_ptr<ObjDumper> &Result) {
89   const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
90   if (!COFFObj)
91     return readobj_error::unsupported_obj_file_format;
92
93   Result.reset(new COFFDumper(COFFObj, Writer));
94   return readobj_error::success;
95 }
96
97 } // namespace llvm
98
99 // Given a a section and an offset into this section the function returns the
100 // symbol used for the relocation at the offset.
101 error_code COFFDumper::resolveSymbol(const coff_section *Section,
102                                      uint64_t Offset, SymbolRef &Sym) {
103   const auto &Relocations = RelocMap[Section];
104   for (const auto &Relocation : Relocations) {
105     uint64_t RelocationOffset;
106     if (error_code EC = Relocation.getOffset(RelocationOffset))
107       return EC;
108
109     if (RelocationOffset == Offset) {
110       Sym = *Relocation.getSymbol();
111       return readobj_error::success;
112     }
113   }
114   return readobj_error::unknown_symbol;
115 }
116
117 // Given a section and an offset into this section the function returns the name
118 // of the symbol used for the relocation at the offset.
119 error_code COFFDumper::resolveSymbolName(const coff_section *Section,
120                                          uint64_t Offset, StringRef &Name) {
121   SymbolRef Symbol;
122   if (error_code EC = resolveSymbol(Section, Offset, Symbol))
123     return EC;
124   if (error_code EC = Symbol.getName(Name))
125     return EC;
126   return object_error::success;
127 }
128
129 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
130   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
131   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
132   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
133   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
134   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT    ),
135   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC      ),
136   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386     ),
137   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64     ),
138   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R     ),
139   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16   ),
140   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU  ),
141   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
142   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC  ),
143   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
144   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000    ),
145   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3      ),
146   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP   ),
147   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4      ),
148   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5      ),
149   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB    ),
150   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
151 };
152
153 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
154   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED        ),
155   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE       ),
156   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED     ),
157   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED    ),
158   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM     ),
159   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE    ),
160   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO      ),
161   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE          ),
162   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED         ),
163   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
164   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP      ),
165   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM                 ),
166   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL                    ),
167   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY         ),
168   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI      )
169 };
170
171 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
172   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN                ),
173   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE                 ),
174   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI            ),
175   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI            ),
176   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI              ),
177   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI         ),
178   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION        ),
179   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
180   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER     ),
181   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM                ),
182   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX                   ),
183 };
184
185 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
186   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA      ),
187   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE         ),
188   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY      ),
189   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT            ),
190   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION         ),
191   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH               ),
192   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND              ),
193   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER           ),
194   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
195 };
196
197 static const EnumEntry<COFF::SectionCharacteristics>
198 ImageSectionCharacteristics[] = {
199   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD           ),
200   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE              ),
201   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA  ),
202   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
203   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER             ),
204   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO              ),
205   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE            ),
206   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT            ),
207   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL                 ),
208   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE         ),
209   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT             ),
210   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED            ),
211   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD           ),
212   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES          ),
213   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES          ),
214   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES          ),
215   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES          ),
216   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES         ),
217   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES         ),
218   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES         ),
219   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES        ),
220   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES        ),
221   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES        ),
222   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES       ),
223   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES       ),
224   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES       ),
225   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES       ),
226   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL       ),
227   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE       ),
228   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED        ),
229   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED         ),
230   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED            ),
231   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE           ),
232   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ              ),
233   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE             )
234 };
235
236 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
237   { "Null"  , COFF::IMAGE_SYM_TYPE_NULL   },
238   { "Void"  , COFF::IMAGE_SYM_TYPE_VOID   },
239   { "Char"  , COFF::IMAGE_SYM_TYPE_CHAR   },
240   { "Short" , COFF::IMAGE_SYM_TYPE_SHORT  },
241   { "Int"   , COFF::IMAGE_SYM_TYPE_INT    },
242   { "Long"  , COFF::IMAGE_SYM_TYPE_LONG   },
243   { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT  },
244   { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
245   { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
246   { "Union" , COFF::IMAGE_SYM_TYPE_UNION  },
247   { "Enum"  , COFF::IMAGE_SYM_TYPE_ENUM   },
248   { "MOE"   , COFF::IMAGE_SYM_TYPE_MOE    },
249   { "Byte"  , COFF::IMAGE_SYM_TYPE_BYTE   },
250   { "Word"  , COFF::IMAGE_SYM_TYPE_WORD   },
251   { "UInt"  , COFF::IMAGE_SYM_TYPE_UINT   },
252   { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD  }
253 };
254
255 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
256   { "Null"    , COFF::IMAGE_SYM_DTYPE_NULL     },
257   { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER  },
258   { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
259   { "Array"   , COFF::IMAGE_SYM_DTYPE_ARRAY    }
260 };
261
262 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
263   { "EndOfFunction"  , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION  },
264   { "Null"           , COFF::IMAGE_SYM_CLASS_NULL             },
265   { "Automatic"      , COFF::IMAGE_SYM_CLASS_AUTOMATIC        },
266   { "External"       , COFF::IMAGE_SYM_CLASS_EXTERNAL         },
267   { "Static"         , COFF::IMAGE_SYM_CLASS_STATIC           },
268   { "Register"       , COFF::IMAGE_SYM_CLASS_REGISTER         },
269   { "ExternalDef"    , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF     },
270   { "Label"          , COFF::IMAGE_SYM_CLASS_LABEL            },
271   { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL  },
272   { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
273   { "Argument"       , COFF::IMAGE_SYM_CLASS_ARGUMENT         },
274   { "StructTag"      , COFF::IMAGE_SYM_CLASS_STRUCT_TAG       },
275   { "MemberOfUnion"  , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION  },
276   { "UnionTag"       , COFF::IMAGE_SYM_CLASS_UNION_TAG        },
277   { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION  },
278   { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
279   { "EnumTag"        , COFF::IMAGE_SYM_CLASS_ENUM_TAG         },
280   { "MemberOfEnum"   , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM   },
281   { "RegisterParam"  , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM   },
282   { "BitField"       , COFF::IMAGE_SYM_CLASS_BIT_FIELD        },
283   { "Block"          , COFF::IMAGE_SYM_CLASS_BLOCK            },
284   { "Function"       , COFF::IMAGE_SYM_CLASS_FUNCTION         },
285   { "EndOfStruct"    , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT    },
286   { "File"           , COFF::IMAGE_SYM_CLASS_FILE             },
287   { "Section"        , COFF::IMAGE_SYM_CLASS_SECTION          },
288   { "WeakExternal"   , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL    },
289   { "CLRToken"       , COFF::IMAGE_SYM_CLASS_CLR_TOKEN        }
290 };
291
292 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
293   { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
294   { "Any"         , COFF::IMAGE_COMDAT_SELECT_ANY          },
295   { "SameSize"    , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE    },
296   { "ExactMatch"  , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH  },
297   { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE  },
298   { "Largest"     , COFF::IMAGE_COMDAT_SELECT_LARGEST      },
299   { "Newest"      , COFF::IMAGE_COMDAT_SELECT_NEWEST       }
300 };
301
302 static const EnumEntry<COFF::WeakExternalCharacteristics>
303 WeakExternalCharacteristics[] = {
304   { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
305   { "Library"  , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY   },
306   { "Alias"    , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS     }
307 };
308
309 template<typename T>
310 static error_code getSymbolAuxData(const COFFObjectFile *Obj,
311                                    const coff_symbol *Symbol, const T* &Aux) {
312   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
313   Aux = reinterpret_cast<const T*>(AuxData.data());
314   return readobj_error::success;
315 }
316
317 void COFFDumper::cacheRelocations() {
318   for (const SectionRef &S : Obj->sections()) {
319     const coff_section *Section = Obj->getCOFFSection(S);
320
321     for (const RelocationRef &Reloc : S.relocations())
322       RelocMap[Section].push_back(Reloc);
323
324     // Sort relocations by address.
325     std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
326               relocAddressLess);
327   }
328 }
329
330 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
331   const data_directory *Data;
332   if (Obj->getDataDirectory(Index, Data))
333     return;
334   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
335   W.printHex(FieldName + "Size", Data->Size);
336 }
337
338 void COFFDumper::printFileHeaders() {
339   // Print COFF header
340   const coff_file_header *COFFHeader = nullptr;
341   if (error(Obj->getCOFFHeader(COFFHeader)))
342     return;
343
344   time_t TDS = COFFHeader->TimeDateStamp;
345   char FormattedTime[20] = { };
346   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
347
348   {
349     DictScope D(W, "ImageFileHeader");
350     W.printEnum  ("Machine", COFFHeader->Machine,
351                     makeArrayRef(ImageFileMachineType));
352     W.printNumber("SectionCount", COFFHeader->NumberOfSections);
353     W.printHex   ("TimeDateStamp", FormattedTime, COFFHeader->TimeDateStamp);
354     W.printHex   ("PointerToSymbolTable", COFFHeader->PointerToSymbolTable);
355     W.printNumber("SymbolCount", COFFHeader->NumberOfSymbols);
356     W.printNumber("OptionalHeaderSize", COFFHeader->SizeOfOptionalHeader);
357     W.printFlags ("Characteristics", COFFHeader->Characteristics,
358                     makeArrayRef(ImageFileCharacteristics));
359   }
360
361   // Print PE header. This header does not exist if this is an object file and
362   // not an executable.
363   const pe32_header *PEHeader = nullptr;
364   if (error(Obj->getPE32Header(PEHeader)))
365     return;
366   if (PEHeader)
367     printPEHeader<pe32_header>(PEHeader);
368
369   const pe32plus_header *PEPlusHeader = nullptr;
370   if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
371     return;
372   if (PEPlusHeader)
373     printPEHeader<pe32plus_header>(PEPlusHeader);
374 }
375
376 template <class PEHeader>
377 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
378   DictScope D(W, "ImageOptionalHeader");
379   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
380   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
381   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
382   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
383   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
384   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
385   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
386   printBaseOfDataField(Hdr);
387   W.printHex   ("ImageBase", Hdr->ImageBase);
388   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
389   W.printNumber("FileAlignment", Hdr->FileAlignment);
390   W.printNumber("MajorOperatingSystemVersion",
391                 Hdr->MajorOperatingSystemVersion);
392   W.printNumber("MinorOperatingSystemVersion",
393                 Hdr->MinorOperatingSystemVersion);
394   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
395   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
396   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
397   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
398   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
399   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
400   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
401   W.printFlags ("Subsystem", Hdr->DLLCharacteristics,
402                 makeArrayRef(PEDLLCharacteristics));
403   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
404   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
405   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
406   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
407   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
408
409   if (Hdr->NumberOfRvaAndSize > 0) {
410     DictScope D(W, "DataDirectory");
411     static const char * const directory[] = {
412       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
413       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
414       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
415       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
416     };
417
418     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
419       printDataDirectory(i, directory[i]);
420     }
421   }
422 }
423
424 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
425   W.printHex("BaseOfData", Hdr->BaseOfData);
426 }
427
428 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
429
430 void COFFDumper::printCodeViewLineTables(const SectionRef &Section) {
431   StringRef Data;
432   if (error(Section.getContents(Data)))
433     return;
434
435   SmallVector<StringRef, 10> FunctionNames;
436   StringMap<StringRef> FunctionLineTables;
437   StringRef FileIndexToStringOffsetTable;
438   StringRef StringTable;
439
440   ListScope D(W, "CodeViewLineTables");
441   {
442     DataExtractor DE(Data, true, 4);
443     uint32_t Offset = 0,
444              Magic = DE.getU32(&Offset);
445     W.printHex("Magic", Magic);
446     if (Magic != COFF::DEBUG_SECTION_MAGIC) {
447       error(object_error::parse_failed);
448       return;
449     }
450
451     bool Finished = false;
452     while (DE.isValidOffset(Offset) && !Finished) {
453       // The section consists of a number of subsection in the following format:
454       // |Type|PayloadSize|Payload...|
455       uint32_t SubSectionType = DE.getU32(&Offset),
456                PayloadSize = DE.getU32(&Offset);
457       ListScope S(W, "Subsection");
458       W.printHex("Type", SubSectionType);
459       W.printHex("PayloadSize", PayloadSize);
460       if (PayloadSize > Data.size() - Offset) {
461         error(object_error::parse_failed);
462         return;
463       }
464
465       // Print the raw contents to simplify debugging if anything goes wrong
466       // afterwards.
467       StringRef Contents = Data.substr(Offset, PayloadSize);
468       W.printBinaryBlock("Contents", Contents);
469
470       switch (SubSectionType) {
471       case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
472         // Holds a PC to file:line table.  Some data to parse this subsection is
473         // stored in the other subsections, so just check sanity and store the
474         // pointers for deferred processing.
475
476         if (PayloadSize < 12) {
477           // There should be at least three words to store two function
478           // relocations and size of the code.
479           error(object_error::parse_failed);
480           return;
481         }
482
483         StringRef FunctionName;
484         if (error(resolveSymbolName(Obj->getCOFFSection(Section), Offset,
485                                     FunctionName)))
486           return;
487         W.printString("FunctionName", FunctionName);
488         if (FunctionLineTables.count(FunctionName) != 0) {
489           // Saw debug info for this function already?
490           error(object_error::parse_failed);
491           return;
492         }
493
494         FunctionLineTables[FunctionName] = Contents;
495         FunctionNames.push_back(FunctionName);
496         break;
497       }
498       case COFF::DEBUG_STRING_TABLE_SUBSECTION:
499         if (PayloadSize == 0 || StringTable.data() != nullptr ||
500             Contents.back() != '\0') {
501           // Empty or duplicate or non-null-terminated subsection.
502           error(object_error::parse_failed);
503           return;
504         }
505         StringTable = Contents;
506         break;
507       case COFF::DEBUG_INDEX_SUBSECTION:
508         // Holds the translation table from file indices
509         // to offsets in the string table.
510
511         if (PayloadSize == 0 ||
512             FileIndexToStringOffsetTable.data() != nullptr) {
513           // Empty or duplicate subsection.
514           error(object_error::parse_failed);
515           return;
516         }
517         FileIndexToStringOffsetTable = Contents;
518         break;
519       }
520       Offset += PayloadSize;
521
522       // Align the reading pointer by 4.
523       Offset += (-Offset) % 4;
524     }
525   }
526
527   // Dump the line tables now that we've read all the subsections and know all
528   // the required information.
529   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
530     StringRef Name = FunctionNames[I];
531     ListScope S(W, "FunctionLineTable");
532     W.printString("FunctionName", Name);
533
534     DataExtractor DE(FunctionLineTables[Name], true, 4);
535     uint32_t Offset = 8;  // Skip relocations.
536     uint32_t FunctionSize = DE.getU32(&Offset);
537     W.printHex("CodeSize", FunctionSize);
538     while (DE.isValidOffset(Offset)) {
539       // For each range of lines with the same filename, we have a segment
540       // in the line table.  The filename string is accessed using double
541       // indirection to the string table subsection using the index subsection.
542       uint32_t OffsetInIndex = DE.getU32(&Offset),
543                SegmentLength   = DE.getU32(&Offset),
544                FullSegmentSize = DE.getU32(&Offset);
545       if (FullSegmentSize != 12 + 8 * SegmentLength) {
546         error(object_error::parse_failed);
547         return;
548       }
549
550       uint32_t FilenameOffset;
551       {
552         DataExtractor SDE(FileIndexToStringOffsetTable, true, 4);
553         uint32_t OffsetInSDE = OffsetInIndex;
554         if (!SDE.isValidOffset(OffsetInSDE)) {
555           error(object_error::parse_failed);
556           return;
557         }
558         FilenameOffset = SDE.getU32(&OffsetInSDE);
559       }
560
561       if (FilenameOffset == 0 || FilenameOffset + 1 >= StringTable.size() ||
562           StringTable.data()[FilenameOffset - 1] != '\0') {
563         // Each string in an F3 subsection should be preceded by a null
564         // character.
565         error(object_error::parse_failed);
566         return;
567       }
568
569       StringRef Filename(StringTable.data() + FilenameOffset);
570       ListScope S(W, "FilenameSegment");
571       W.printString("Filename", Filename);
572       for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
573            ++J) {
574         // Then go the (PC, LineNumber) pairs.  The line number is stored in the
575         // least significant 31 bits of the respective word in the table.
576         uint32_t PC = DE.getU32(&Offset),
577                  LineNumber = DE.getU32(&Offset) & 0x7fffffff;
578         if (PC >= FunctionSize) {
579           error(object_error::parse_failed);
580           return;
581         }
582         char Buffer[32];
583         format("+0x%X", PC).snprint(Buffer, 32);
584         W.printNumber(Buffer, LineNumber);
585       }
586     }
587   }
588 }
589
590 void COFFDumper::printSections() {
591   ListScope SectionsD(W, "Sections");
592   int SectionNumber = 0;
593   for (const SectionRef &Sec : Obj->sections()) {
594     ++SectionNumber;
595     const coff_section *Section = Obj->getCOFFSection(Sec);
596
597     StringRef Name;
598     if (error(Sec.getName(Name)))
599       Name = "";
600
601     DictScope D(W, "Section");
602     W.printNumber("Number", SectionNumber);
603     W.printBinary("Name", Name, Section->Name);
604     W.printHex   ("VirtualSize", Section->VirtualSize);
605     W.printHex   ("VirtualAddress", Section->VirtualAddress);
606     W.printNumber("RawDataSize", Section->SizeOfRawData);
607     W.printHex   ("PointerToRawData", Section->PointerToRawData);
608     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
609     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
610     W.printNumber("RelocationCount", Section->NumberOfRelocations);
611     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
612     W.printFlags ("Characteristics", Section->Characteristics,
613                     makeArrayRef(ImageSectionCharacteristics),
614                     COFF::SectionCharacteristics(0x00F00000));
615
616     if (opts::SectionRelocations) {
617       ListScope D(W, "Relocations");
618       for (const RelocationRef &Reloc : Sec.relocations())
619         printRelocation(Sec, Reloc);
620     }
621
622     if (opts::SectionSymbols) {
623       ListScope D(W, "Symbols");
624       for (const SymbolRef &Symbol : Obj->symbols()) {
625         bool Contained = false;
626         if (Sec.containsSymbol(Symbol, Contained) || !Contained)
627           continue;
628
629         printSymbol(Symbol);
630       }
631     }
632
633     if (Name == ".debug$S" && opts::CodeViewLineTables)
634       printCodeViewLineTables(Sec);
635
636     if (opts::SectionData) {
637       StringRef Data;
638       if (error(Sec.getContents(Data)))
639         break;
640
641       W.printBinaryBlock("SectionData", Data);
642     }
643   }
644 }
645
646 void COFFDumper::printRelocations() {
647   ListScope D(W, "Relocations");
648
649   int SectionNumber = 0;
650   for (const SectionRef &Section : Obj->sections()) {
651     ++SectionNumber;
652     StringRef Name;
653     if (error(Section.getName(Name)))
654       continue;
655
656     bool PrintedGroup = false;
657     for (const RelocationRef &Reloc : Section.relocations()) {
658       if (!PrintedGroup) {
659         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
660         W.indent();
661         PrintedGroup = true;
662       }
663
664       printRelocation(Section, Reloc);
665     }
666
667     if (PrintedGroup) {
668       W.unindent();
669       W.startLine() << "}\n";
670     }
671   }
672 }
673
674 void COFFDumper::printRelocation(const SectionRef &Section,
675                                  const RelocationRef &Reloc) {
676   uint64_t Offset;
677   uint64_t RelocType;
678   SmallString<32> RelocName;
679   StringRef SymbolName;
680   StringRef Contents;
681   if (error(Reloc.getOffset(Offset)))
682     return;
683   if (error(Reloc.getType(RelocType)))
684     return;
685   if (error(Reloc.getTypeName(RelocName)))
686     return;
687   symbol_iterator Symbol = Reloc.getSymbol();
688   if (error(Symbol->getName(SymbolName)))
689     return;
690   if (error(Section.getContents(Contents)))
691     return;
692
693   if (opts::ExpandRelocs) {
694     DictScope Group(W, "Relocation");
695     W.printHex("Offset", Offset);
696     W.printNumber("Type", RelocName, RelocType);
697     W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
698   } else {
699     raw_ostream& OS = W.startLine();
700     OS << W.hex(Offset)
701        << " " << RelocName
702        << " " << (SymbolName.size() > 0 ? SymbolName : "-")
703        << "\n";
704   }
705 }
706
707 void COFFDumper::printSymbols() {
708   ListScope Group(W, "Symbols");
709
710   for (const SymbolRef &Symbol : Obj->symbols())
711     printSymbol(Symbol);
712 }
713
714 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
715
716 void COFFDumper::printSymbol(const SymbolRef &Sym) {
717   DictScope D(W, "Symbol");
718
719   const coff_symbol *Symbol = Obj->getCOFFSymbol(Sym);
720   const coff_section *Section;
721   if (error_code EC = Obj->getSection(Symbol->SectionNumber, Section)) {
722     W.startLine() << "Invalid section number: " << EC.message() << "\n";
723     W.flush();
724     return;
725   }
726
727   StringRef SymbolName;
728   if (Obj->getSymbolName(Symbol, SymbolName))
729     SymbolName = "";
730
731   StringRef SectionName = "";
732   if (Section)
733     Obj->getSectionName(Section, SectionName);
734
735   W.printString("Name", SymbolName);
736   W.printNumber("Value", Symbol->Value);
737   W.printNumber("Section", SectionName, Symbol->SectionNumber);
738   W.printEnum  ("BaseType", Symbol->getBaseType(), makeArrayRef(ImageSymType));
739   W.printEnum  ("ComplexType", Symbol->getComplexType(),
740                                                    makeArrayRef(ImageSymDType));
741   W.printEnum  ("StorageClass", Symbol->StorageClass,
742                                                    makeArrayRef(ImageSymClass));
743   W.printNumber("AuxSymbolCount", Symbol->NumberOfAuxSymbols);
744
745   for (unsigned I = 0; I < Symbol->NumberOfAuxSymbols; ++I) {
746     if (Symbol->isFunctionDefinition()) {
747       const coff_aux_function_definition *Aux;
748       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
749         break;
750
751       DictScope AS(W, "AuxFunctionDef");
752       W.printNumber("TagIndex", Aux->TagIndex);
753       W.printNumber("TotalSize", Aux->TotalSize);
754       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
755       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
756       W.printBinary("Unused", makeArrayRef(Aux->Unused));
757
758     } else if (Symbol->isWeakExternal()) {
759       const coff_aux_weak_external *Aux;
760       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
761         break;
762
763       const coff_symbol *Linked;
764       StringRef LinkedName;
765       error_code EC;
766       if ((EC = Obj->getSymbol(Aux->TagIndex, Linked)) ||
767           (EC = Obj->getSymbolName(Linked, LinkedName))) {
768         LinkedName = "";
769         error(EC);
770       }
771
772       DictScope AS(W, "AuxWeakExternal");
773       W.printNumber("Linked", LinkedName, Aux->TagIndex);
774       W.printEnum  ("Search", Aux->Characteristics,
775                     makeArrayRef(WeakExternalCharacteristics));
776       W.printBinary("Unused", makeArrayRef(Aux->Unused));
777
778     } else if (Symbol->isFileRecord()) {
779       const coff_aux_file *Aux;
780       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
781         break;
782
783       DictScope AS(W, "AuxFileRecord");
784
785       StringRef Name(Aux->FileName,
786                      Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
787       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
788       break;
789     } else if (Symbol->isSectionDefinition()) {
790       const coff_aux_section_definition *Aux;
791       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
792         break;
793
794       DictScope AS(W, "AuxSectionDef");
795       W.printNumber("Length", Aux->Length);
796       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
797       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
798       W.printHex("Checksum", Aux->CheckSum);
799       W.printNumber("Number", Aux->Number);
800       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
801       W.printBinary("Unused", makeArrayRef(Aux->Unused));
802
803       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
804           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
805         const coff_section *Assoc;
806         StringRef AssocName;
807         error_code EC;
808         if ((EC = Obj->getSection(Aux->Number, Assoc)) ||
809             (EC = Obj->getSectionName(Assoc, AssocName))) {
810           AssocName = "";
811           error(EC);
812         }
813
814         W.printNumber("AssocSection", AssocName, Aux->Number);
815       }
816     } else if (Symbol->isCLRToken()) {
817       const coff_aux_clr_token *Aux;
818       if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
819         break;
820
821       const coff_symbol *ReferredSym;
822       StringRef ReferredName;
823       error_code EC;
824       if ((EC = Obj->getSymbol(Aux->SymbolTableIndex, ReferredSym)) ||
825           (EC = Obj->getSymbolName(ReferredSym, ReferredName))) {
826         ReferredName = "";
827         error(EC);
828       }
829
830       DictScope AS(W, "AuxCLRToken");
831       W.printNumber("AuxType", Aux->AuxType);
832       W.printNumber("Reserved", Aux->Reserved);
833       W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
834       W.printBinary("Unused", makeArrayRef(Aux->Unused));
835
836     } else {
837       W.startLine() << "<unhandled auxiliary record>\n";
838     }
839   }
840 }
841
842 void COFFDumper::printUnwindInfo() {
843   const coff_file_header *Header;
844   if (error(Obj->getCOFFHeader(Header)))
845     return;
846
847   ListScope D(W, "UnwindInformation");
848   switch (Header->Machine) {
849   case COFF::IMAGE_FILE_MACHINE_AMD64: {
850     Win64EH::Dumper Dumper(W);
851     Win64EH::Dumper::SymbolResolver Resolver =
852       [](const object::coff_section *Section, uint64_t Offset,
853          SymbolRef &Symbol, void *user_data) -> error_code {
854         COFFDumper *Dumper = reinterpret_cast<COFFDumper*>(user_data);
855         return Dumper->resolveSymbol(Section, Offset, Symbol);
856       };
857     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
858     Dumper.printData(Ctx);
859     break;
860   }
861   default:
862     W.printEnum("unsupported Image Machine", Header->Machine,
863                 makeArrayRef(ImageFileMachineType));
864     break;
865   }
866 }
867