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