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