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