]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-readobj/COFFDumper.cpp
Merge llvm trunk r321017 to contrib/llvm.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "ARMWinEHPrinter.h"
16 #include "Error.h"
17 #include "ObjDumper.h"
18 #include "StackMapPrinter.h"
19 #include "Win64EHDumper.h"
20 #include "llvm-readobj.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/BinaryFormat/COFF.h"
25 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
26 #include "llvm/DebugInfo/CodeView/CodeView.h"
27 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
31 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
32 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
33 #include "llvm/DebugInfo/CodeView/Line.h"
34 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
35 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
37 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
38 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
39 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
40 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
41 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
42 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
43 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
44 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
45 #include "llvm/Object/COFF.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Support/BinaryStreamReader.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/Win64EH.h"
54 #include "llvm/Support/raw_ostream.h"
55
56 using namespace llvm;
57 using namespace llvm::object;
58 using namespace llvm::codeview;
59 using namespace llvm::support;
60 using namespace llvm::Win64EH;
61
62 namespace {
63
64 struct LoadConfigTables {
65   uint64_t SEHTableVA = 0;
66   uint64_t SEHTableCount = 0;
67   uint32_t GuardFlags = 0;
68   uint64_t GuardFidTableVA = 0;
69   uint64_t GuardFidTableCount = 0;
70 };
71
72 class COFFDumper : public ObjDumper {
73 public:
74   friend class COFFObjectDumpDelegate;
75   COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
76       : ObjDumper(Writer), Obj(Obj), Writer(Writer), Types(100) {}
77
78   void printFileHeaders() override;
79   void printSections() override;
80   void printRelocations() override;
81   void printSymbols() override;
82   void printDynamicSymbols() override;
83   void printUnwindInfo() override;
84   void printCOFFImports() override;
85   void printCOFFExports() override;
86   void printCOFFDirectives() override;
87   void printCOFFBaseReloc() override;
88   void printCOFFDebugDirectory() override;
89   void printCOFFResources() override;
90   void printCOFFLoadConfig() override;
91   void printCodeViewDebugInfo() override;
92   void
93   mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
94                      llvm::codeview::MergingTypeTableBuilder &CVTypes) override;
95   void printStackMap() const override;
96 private:
97   void printSymbol(const SymbolRef &Sym);
98   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
99                        uint64_t Bias = 0);
100   void printDataDirectory(uint32_t Index, const std::string &FieldName);
101
102   void printDOSHeader(const dos_header *DH);
103   template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
104   void printBaseOfDataField(const pe32_header *Hdr);
105   void printBaseOfDataField(const pe32plus_header *Hdr);
106   template <typename T>
107   void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
108   typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
109   void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
110                      PrintExtraCB PrintExtra = 0);
111
112   void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
113   void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
114   StringRef getTypeName(TypeIndex Ty);
115   StringRef getFileNameForFileOffset(uint32_t FileOffset);
116   void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
117   void printTypeIndex(StringRef FieldName, TypeIndex TI) {
118     // Forward to CVTypeDumper for simplicity.
119     codeview::printTypeIndex(Writer, FieldName, TI, Types);
120   }
121
122   void printCodeViewSymbolsSubsection(StringRef Subsection,
123                                       const SectionRef &Section,
124                                       StringRef SectionContents);
125
126   void printCodeViewFileChecksums(StringRef Subsection);
127
128   void printCodeViewInlineeLines(StringRef Subsection);
129
130   void printRelocatedField(StringRef Label, const coff_section *Sec,
131                            uint32_t RelocOffset, uint32_t Offset,
132                            StringRef *RelocSym = nullptr);
133
134   uint32_t countTotalTableEntries(ResourceSectionRef RSF,
135                                   const coff_resource_dir_table &Table,
136                                   StringRef Level);
137
138   void printResourceDirectoryTable(ResourceSectionRef RSF,
139                                    const coff_resource_dir_table &Table,
140                                    StringRef Level);
141
142   void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
143                                   StringRef SectionContents, StringRef Block);
144
145   /// Given a .debug$S section, find the string table and file checksum table.
146   void initializeFileAndStringTables(BinaryStreamReader &Reader);
147
148   void cacheRelocations();
149
150   std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
151                                 SymbolRef &Sym);
152   std::error_code resolveSymbolName(const coff_section *Section,
153                                     uint64_t Offset, StringRef &Name);
154   std::error_code resolveSymbolName(const coff_section *Section,
155                                     StringRef SectionContents,
156                                     const void *RelocPtr, StringRef &Name);
157   void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
158   void printDelayImportedSymbols(
159       const DelayImportDirectoryEntryRef &I,
160       iterator_range<imported_symbol_iterator> Range);
161   ErrorOr<const coff_resource_dir_entry &>
162   getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
163                                  uint32_t Index);
164
165   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
166
167   const llvm::object::COFFObjectFile *Obj;
168   bool RelocCached = false;
169   RelocMapTy RelocMap;
170
171   DebugChecksumsSubsectionRef CVFileChecksumTable;
172
173   DebugStringTableSubsectionRef CVStringTable;
174
175   ScopedPrinter &Writer;
176   BinaryByteStream TypeContents;
177   LazyRandomTypeCollection Types;
178 };
179
180 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
181 public:
182   COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
183                          const COFFObjectFile *Obj, StringRef SectionContents)
184       : CD(CD), SR(SR), SectionContents(SectionContents) {
185     Sec = Obj->getCOFFSection(SR);
186   }
187
188   uint32_t getRecordOffset(BinaryStreamReader Reader) override {
189     ArrayRef<uint8_t> Data;
190     if (auto EC = Reader.readLongestContiguousChunk(Data)) {
191       llvm::consumeError(std::move(EC));
192       return 0;
193     }
194     return Data.data() - SectionContents.bytes_begin();
195   }
196
197   void printRelocatedField(StringRef Label, uint32_t RelocOffset,
198                            uint32_t Offset, StringRef *RelocSym) override {
199     CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
200   }
201
202   void printBinaryBlockWithRelocs(StringRef Label,
203                                   ArrayRef<uint8_t> Block) override {
204     StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
205                      Block.size());
206     if (opts::CodeViewSubsectionBytes)
207       CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
208   }
209
210   StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
211     return CD.getFileNameForFileOffset(FileOffset);
212   }
213
214   DebugStringTableSubsectionRef getStringTable() override {
215     return CD.CVStringTable;
216   }
217
218 private:
219   COFFDumper &CD;
220   const SectionRef &SR;
221   const coff_section *Sec;
222   StringRef SectionContents;
223 };
224
225 } // end namespace
226
227 namespace llvm {
228
229 std::error_code createCOFFDumper(const object::ObjectFile *Obj,
230                                  ScopedPrinter &Writer,
231                                  std::unique_ptr<ObjDumper> &Result) {
232   const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
233   if (!COFFObj)
234     return readobj_error::unsupported_obj_file_format;
235
236   Result.reset(new COFFDumper(COFFObj, Writer));
237   return readobj_error::success;
238 }
239
240 } // namespace llvm
241
242 // Given a a section and an offset into this section the function returns the
243 // symbol used for the relocation at the offset.
244 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
245                                           uint64_t Offset, SymbolRef &Sym) {
246   cacheRelocations();
247   const auto &Relocations = RelocMap[Section];
248   auto SymI = Obj->symbol_end();
249   for (const auto &Relocation : Relocations) {
250     uint64_t RelocationOffset = Relocation.getOffset();
251
252     if (RelocationOffset == Offset) {
253       SymI = Relocation.getSymbol();
254       break;
255     }
256   }
257   if (SymI == Obj->symbol_end())
258     return readobj_error::unknown_symbol;
259   Sym = *SymI;
260   return readobj_error::success;
261 }
262
263 // Given a section and an offset into this section the function returns the name
264 // of the symbol used for the relocation at the offset.
265 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
266                                               uint64_t Offset,
267                                               StringRef &Name) {
268   SymbolRef Symbol;
269   if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
270     return EC;
271   Expected<StringRef> NameOrErr = Symbol.getName();
272   if (!NameOrErr)
273     return errorToErrorCode(NameOrErr.takeError());
274   Name = *NameOrErr;
275   return std::error_code();
276 }
277
278 // Helper for when you have a pointer to real data and you want to know about
279 // relocations against it.
280 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
281                                               StringRef SectionContents,
282                                               const void *RelocPtr,
283                                               StringRef &Name) {
284   assert(SectionContents.data() < RelocPtr &&
285          RelocPtr < SectionContents.data() + SectionContents.size() &&
286          "pointer to relocated object is not in section");
287   uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
288                               SectionContents.data());
289   return resolveSymbolName(Section, Offset, Name);
290 }
291
292 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
293                                      uint32_t RelocOffset, uint32_t Offset,
294                                      StringRef *RelocSym) {
295   StringRef SymStorage;
296   StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
297   if (!resolveSymbolName(Sec, RelocOffset, Symbol))
298     W.printSymbolOffset(Label, Symbol, Offset);
299   else
300     W.printHex(Label, RelocOffset);
301 }
302
303 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
304                                             const SectionRef &Sec,
305                                             StringRef SectionContents,
306                                             StringRef Block) {
307   W.printBinaryBlock(Label, Block);
308
309   assert(SectionContents.begin() < Block.begin() &&
310          SectionContents.end() >= Block.end() &&
311          "Block is not contained in SectionContents");
312   uint64_t OffsetStart = Block.data() - SectionContents.data();
313   uint64_t OffsetEnd = OffsetStart + Block.size();
314
315   W.flush();
316   cacheRelocations();
317   ListScope D(W, "BlockRelocations");
318   const coff_section *Section = Obj->getCOFFSection(Sec);
319   const auto &Relocations = RelocMap[Section];
320   for (const auto &Relocation : Relocations) {
321     uint64_t RelocationOffset = Relocation.getOffset();
322     if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
323       printRelocation(Sec, Relocation, OffsetStart);
324   }
325 }
326
327 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
328   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
329   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
330   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
331   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
332   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64    ),
333   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT    ),
334   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC      ),
335   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386     ),
336   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64     ),
337   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R     ),
338   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16   ),
339   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU  ),
340   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
341   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC  ),
342   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
343   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000    ),
344   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3      ),
345   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP   ),
346   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4      ),
347   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5      ),
348   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB    ),
349   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
350 };
351
352 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
353   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED        ),
354   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE       ),
355   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED     ),
356   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED    ),
357   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM     ),
358   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE    ),
359   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO      ),
360   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE          ),
361   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED         ),
362   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
363   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP      ),
364   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM                 ),
365   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL                    ),
366   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY         ),
367   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI      )
368 };
369
370 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
371   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN                ),
372   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE                 ),
373   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI            ),
374   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI            ),
375   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI              ),
376   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI         ),
377   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION        ),
378   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
379   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER     ),
380   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM                ),
381   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX                   ),
382 };
383
384 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
385   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA      ),
386   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE         ),
387   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY      ),
388   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT            ),
389   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION         ),
390   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH               ),
391   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND              ),
392   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER         ),
393   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER           ),
394   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF             ),
395   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
396 };
397
398 static const EnumEntry<COFF::SectionCharacteristics>
399 ImageSectionCharacteristics[] = {
400   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD           ),
401   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD           ),
402   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE              ),
403   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA  ),
404   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
405   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER             ),
406   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO              ),
407   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE            ),
408   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT            ),
409   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL                 ),
410   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE         ),
411   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT             ),
412   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED            ),
413   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD           ),
414   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES          ),
415   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES          ),
416   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES          ),
417   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES          ),
418   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES         ),
419   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES         ),
420   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES         ),
421   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES        ),
422   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES        ),
423   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES        ),
424   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES       ),
425   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES       ),
426   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES       ),
427   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES       ),
428   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL       ),
429   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE       ),
430   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED        ),
431   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED         ),
432   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED            ),
433   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE           ),
434   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ              ),
435   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE             )
436 };
437
438 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
439   { "Null"  , COFF::IMAGE_SYM_TYPE_NULL   },
440   { "Void"  , COFF::IMAGE_SYM_TYPE_VOID   },
441   { "Char"  , COFF::IMAGE_SYM_TYPE_CHAR   },
442   { "Short" , COFF::IMAGE_SYM_TYPE_SHORT  },
443   { "Int"   , COFF::IMAGE_SYM_TYPE_INT    },
444   { "Long"  , COFF::IMAGE_SYM_TYPE_LONG   },
445   { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT  },
446   { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
447   { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
448   { "Union" , COFF::IMAGE_SYM_TYPE_UNION  },
449   { "Enum"  , COFF::IMAGE_SYM_TYPE_ENUM   },
450   { "MOE"   , COFF::IMAGE_SYM_TYPE_MOE    },
451   { "Byte"  , COFF::IMAGE_SYM_TYPE_BYTE   },
452   { "Word"  , COFF::IMAGE_SYM_TYPE_WORD   },
453   { "UInt"  , COFF::IMAGE_SYM_TYPE_UINT   },
454   { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD  }
455 };
456
457 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
458   { "Null"    , COFF::IMAGE_SYM_DTYPE_NULL     },
459   { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER  },
460   { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
461   { "Array"   , COFF::IMAGE_SYM_DTYPE_ARRAY    }
462 };
463
464 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
465   { "EndOfFunction"  , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION  },
466   { "Null"           , COFF::IMAGE_SYM_CLASS_NULL             },
467   { "Automatic"      , COFF::IMAGE_SYM_CLASS_AUTOMATIC        },
468   { "External"       , COFF::IMAGE_SYM_CLASS_EXTERNAL         },
469   { "Static"         , COFF::IMAGE_SYM_CLASS_STATIC           },
470   { "Register"       , COFF::IMAGE_SYM_CLASS_REGISTER         },
471   { "ExternalDef"    , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF     },
472   { "Label"          , COFF::IMAGE_SYM_CLASS_LABEL            },
473   { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL  },
474   { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
475   { "Argument"       , COFF::IMAGE_SYM_CLASS_ARGUMENT         },
476   { "StructTag"      , COFF::IMAGE_SYM_CLASS_STRUCT_TAG       },
477   { "MemberOfUnion"  , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION  },
478   { "UnionTag"       , COFF::IMAGE_SYM_CLASS_UNION_TAG        },
479   { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION  },
480   { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
481   { "EnumTag"        , COFF::IMAGE_SYM_CLASS_ENUM_TAG         },
482   { "MemberOfEnum"   , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM   },
483   { "RegisterParam"  , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM   },
484   { "BitField"       , COFF::IMAGE_SYM_CLASS_BIT_FIELD        },
485   { "Block"          , COFF::IMAGE_SYM_CLASS_BLOCK            },
486   { "Function"       , COFF::IMAGE_SYM_CLASS_FUNCTION         },
487   { "EndOfStruct"    , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT    },
488   { "File"           , COFF::IMAGE_SYM_CLASS_FILE             },
489   { "Section"        , COFF::IMAGE_SYM_CLASS_SECTION          },
490   { "WeakExternal"   , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL    },
491   { "CLRToken"       , COFF::IMAGE_SYM_CLASS_CLR_TOKEN        }
492 };
493
494 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
495   { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
496   { "Any"         , COFF::IMAGE_COMDAT_SELECT_ANY          },
497   { "SameSize"    , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE    },
498   { "ExactMatch"  , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH  },
499   { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE  },
500   { "Largest"     , COFF::IMAGE_COMDAT_SELECT_LARGEST      },
501   { "Newest"      , COFF::IMAGE_COMDAT_SELECT_NEWEST       }
502 };
503
504 static const EnumEntry<COFF::DebugType> ImageDebugType[] = {
505   { "Unknown"    , COFF::IMAGE_DEBUG_TYPE_UNKNOWN       },
506   { "COFF"       , COFF::IMAGE_DEBUG_TYPE_COFF          },
507   { "CodeView"   , COFF::IMAGE_DEBUG_TYPE_CODEVIEW      },
508   { "FPO"        , COFF::IMAGE_DEBUG_TYPE_FPO           },
509   { "Misc"       , COFF::IMAGE_DEBUG_TYPE_MISC          },
510   { "Exception"  , COFF::IMAGE_DEBUG_TYPE_EXCEPTION     },
511   { "Fixup"      , COFF::IMAGE_DEBUG_TYPE_FIXUP         },
512   { "OmapToSrc"  , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC   },
513   { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC },
514   { "Borland"    , COFF::IMAGE_DEBUG_TYPE_BORLAND       },
515   { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10    },
516   { "CLSID"      , COFF::IMAGE_DEBUG_TYPE_CLSID         },
517   { "VCFeature"  , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE    },
518   { "POGO"       , COFF::IMAGE_DEBUG_TYPE_POGO          },
519   { "ILTCG"      , COFF::IMAGE_DEBUG_TYPE_ILTCG         },
520   { "MPX"        , COFF::IMAGE_DEBUG_TYPE_MPX           },
521   { "Repro"      , COFF::IMAGE_DEBUG_TYPE_REPRO         },
522 };
523
524 static const EnumEntry<COFF::WeakExternalCharacteristics>
525 WeakExternalCharacteristics[] = {
526   { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
527   { "Library"  , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY   },
528   { "Alias"    , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS     }
529 };
530
531 static const EnumEntry<uint32_t> SubSectionTypes[] = {
532     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
533     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
534     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
535     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
536     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
537     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
538     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
539     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
540     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
541     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
542     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
543     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
544     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
545 };
546
547 static const EnumEntry<uint32_t> FrameDataFlags[] = {
548     LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
549     LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
550     LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
551 };
552
553 static const EnumEntry<uint8_t> FileChecksumKindNames[] = {
554   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
555   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
556   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
557   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
558 };
559
560 static const EnumEntry<COFF::ResourceTypeID> ResourceTypeNames[]{
561     {"kRT_CURSOR (ID 1)", COFF::RID_Cursor},
562     {"kRT_BITMAP (ID 2)", COFF::RID_Bitmap},
563     {"kRT_ICON (ID 3)", COFF::RID_Icon},
564     {"kRT_MENU (ID 4)", COFF::RID_Menu},
565     {"kRT_DIALOG (ID 5)", COFF::RID_Dialog},
566     {"kRT_STRING (ID 6)", COFF::RID_String},
567     {"kRT_FONTDIR (ID 7)", COFF::RID_FontDir},
568     {"kRT_FONT (ID 8)", COFF::RID_Font},
569     {"kRT_ACCELERATOR (ID 9)", COFF::RID_Accelerator},
570     {"kRT_RCDATA (ID 10)", COFF::RID_RCData},
571     {"kRT_MESSAGETABLE (ID 11)", COFF::RID_MessageTable},
572     {"kRT_GROUP_CURSOR (ID 12)", COFF::RID_Group_Cursor},
573     {"kRT_GROUP_ICON (ID 14)", COFF::RID_Group_Icon},
574     {"kRT_VERSION (ID 16)", COFF::RID_Version},
575     {"kRT_DLGINCLUDE (ID 17)", COFF::RID_DLGInclude},
576     {"kRT_PLUGPLAY (ID 19)", COFF::RID_PlugPlay},
577     {"kRT_VXD (ID 20)", COFF::RID_VXD},
578     {"kRT_ANICURSOR (ID 21)", COFF::RID_AniCursor},
579     {"kRT_ANIICON (ID 22)", COFF::RID_AniIcon},
580     {"kRT_HTML (ID 23)", COFF::RID_HTML},
581     {"kRT_MANIFEST (ID 24)", COFF::RID_Manifest}};
582
583 template <typename T>
584 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
585                                         COFFSymbolRef Symbol,
586                                         uint8_t AuxSymbolIdx, const T *&Aux) {
587   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
588   AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
589   Aux = reinterpret_cast<const T*>(AuxData.data());
590   return readobj_error::success;
591 }
592
593 void COFFDumper::cacheRelocations() {
594   if (RelocCached)
595     return;
596   RelocCached = true;
597
598   for (const SectionRef &S : Obj->sections()) {
599     const coff_section *Section = Obj->getCOFFSection(S);
600
601     for (const RelocationRef &Reloc : S.relocations())
602       RelocMap[Section].push_back(Reloc);
603
604     // Sort relocations by address.
605     std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
606               relocAddressLess);
607   }
608 }
609
610 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
611   const data_directory *Data;
612   if (Obj->getDataDirectory(Index, Data))
613     return;
614   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
615   W.printHex(FieldName + "Size", Data->Size);
616 }
617
618 void COFFDumper::printFileHeaders() {
619   time_t TDS = Obj->getTimeDateStamp();
620   char FormattedTime[20] = { };
621   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
622
623   {
624     DictScope D(W, "ImageFileHeader");
625     W.printEnum  ("Machine", Obj->getMachine(),
626                     makeArrayRef(ImageFileMachineType));
627     W.printNumber("SectionCount", Obj->getNumberOfSections());
628     W.printHex   ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
629     W.printHex   ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
630     W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
631     W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
632     W.printFlags ("Characteristics", Obj->getCharacteristics(),
633                     makeArrayRef(ImageFileCharacteristics));
634   }
635
636   // Print PE header. This header does not exist if this is an object file and
637   // not an executable.
638   const pe32_header *PEHeader = nullptr;
639   error(Obj->getPE32Header(PEHeader));
640   if (PEHeader)
641     printPEHeader<pe32_header>(PEHeader);
642
643   const pe32plus_header *PEPlusHeader = nullptr;
644   error(Obj->getPE32PlusHeader(PEPlusHeader));
645   if (PEPlusHeader)
646     printPEHeader<pe32plus_header>(PEPlusHeader);
647
648   if (const dos_header *DH = Obj->getDOSHeader())
649     printDOSHeader(DH);
650 }
651
652 void COFFDumper::printDOSHeader(const dos_header *DH) {
653   DictScope D(W, "DOSHeader");
654   W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
655   W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
656   W.printNumber("FileSizeInPages", DH->FileSizeInPages);
657   W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
658   W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
659   W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
660   W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
661   W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
662   W.printNumber("InitialSP", DH->InitialSP);
663   W.printNumber("Checksum", DH->Checksum);
664   W.printNumber("InitialIP", DH->InitialIP);
665   W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
666   W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
667   W.printNumber("OverlayNumber", DH->OverlayNumber);
668   W.printNumber("OEMid", DH->OEMid);
669   W.printNumber("OEMinfo", DH->OEMinfo);
670   W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
671 }
672
673 template <class PEHeader>
674 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
675   DictScope D(W, "ImageOptionalHeader");
676   W.printHex   ("Magic", Hdr->Magic);
677   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
678   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
679   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
680   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
681   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
682   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
683   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
684   printBaseOfDataField(Hdr);
685   W.printHex   ("ImageBase", Hdr->ImageBase);
686   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
687   W.printNumber("FileAlignment", Hdr->FileAlignment);
688   W.printNumber("MajorOperatingSystemVersion",
689                 Hdr->MajorOperatingSystemVersion);
690   W.printNumber("MinorOperatingSystemVersion",
691                 Hdr->MinorOperatingSystemVersion);
692   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
693   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
694   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
695   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
696   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
697   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
698   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
699   W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
700                 makeArrayRef(PEDLLCharacteristics));
701   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
702   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
703   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
704   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
705   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
706
707   if (Hdr->NumberOfRvaAndSize > 0) {
708     DictScope D(W, "DataDirectory");
709     static const char * const directory[] = {
710       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
711       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
712       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
713       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
714     };
715
716     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
717       printDataDirectory(i, directory[i]);
718   }
719 }
720
721 void COFFDumper::printCOFFDebugDirectory() {
722   ListScope LS(W, "DebugDirectory");
723   for (const debug_directory &D : Obj->debug_directories()) {
724     char FormattedTime[20] = {};
725     time_t TDS = D.TimeDateStamp;
726     strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
727     DictScope S(W, "DebugEntry");
728     W.printHex("Characteristics", D.Characteristics);
729     W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
730     W.printHex("MajorVersion", D.MajorVersion);
731     W.printHex("MinorVersion", D.MinorVersion);
732     W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
733     W.printHex("SizeOfData", D.SizeOfData);
734     W.printHex("AddressOfRawData", D.AddressOfRawData);
735     W.printHex("PointerToRawData", D.PointerToRawData);
736     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
737       const codeview::DebugInfo *DebugInfo;
738       StringRef PDBFileName;
739       error(Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName));
740       DictScope PDBScope(W, "PDBInfo");
741       W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
742       if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
743         W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
744         W.printNumber("PDBAge", DebugInfo->PDB70.Age);
745         W.printString("PDBFileName", PDBFileName);
746       }
747     } else {
748       // FIXME: Type values of 12 and 13 are commonly observed but are not in
749       // the documented type enum.  Figure out what they mean.
750       ArrayRef<uint8_t> RawData;
751       error(
752           Obj->getRvaAndSizeAsBytes(D.AddressOfRawData, D.SizeOfData, RawData));
753       W.printBinaryBlock("RawData", RawData);
754     }
755   }
756 }
757
758 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
759                                uint64_t EntrySize, PrintExtraCB PrintExtra) {
760   uintptr_t TableStart, TableEnd;
761   error(Obj->getVaPtr(TableVA, TableStart));
762   error(Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd));
763   TableEnd++;
764   for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
765     uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
766     raw_ostream &OS = W.startLine();
767     OS << "0x" << utohexstr(Obj->getImageBase() + RVA);
768     if (PrintExtra)
769       PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
770     OS << '\n';
771   }
772 }
773
774 void COFFDumper::printCOFFLoadConfig() {
775   LoadConfigTables Tables;
776   if (Obj->is64())
777     printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
778   else
779     printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
780
781   if (Tables.SEHTableVA) {
782     ListScope LS(W, "SEHTable");
783     printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
784   }
785
786   if (Tables.GuardFidTableVA) {
787     ListScope LS(W, "GuardFidTable");
788     if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
789       auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
790         uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
791         if (Flags)
792           OS << " flags " << utohexstr(Flags);
793       };
794       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
795                     PrintGuardFlags);
796     } else {
797       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
798     }
799   }
800 }
801
802 template <typename T>
803 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
804   if (!Conf)
805     return;
806
807   ListScope LS(W, "LoadConfig");
808   char FormattedTime[20] = {};
809   time_t TDS = Conf->TimeDateStamp;
810   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
811   W.printHex("Size", Conf->Size);
812
813   // Print everything before SecurityCookie. The vast majority of images today
814   // have all these fields.
815   if (Conf->Size < offsetof(T, SEHandlerTable))
816     return;
817   W.printHex("TimeDateStamp", FormattedTime, TDS);
818   W.printHex("MajorVersion", Conf->MajorVersion);
819   W.printHex("MinorVersion", Conf->MinorVersion);
820   W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
821   W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
822   W.printHex("CriticalSectionDefaultTimeout",
823              Conf->CriticalSectionDefaultTimeout);
824   W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
825   W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
826   W.printHex("LockPrefixTable", Conf->LockPrefixTable);
827   W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
828   W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
829   W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
830   W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
831   W.printHex("CSDVersion", Conf->CSDVersion);
832   W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
833   W.printHex("EditList", Conf->EditList);
834   W.printHex("SecurityCookie", Conf->SecurityCookie);
835
836   // Print the safe SEH table if present.
837   if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
838     return;
839   W.printHex("SEHandlerTable", Conf->SEHandlerTable);
840   W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
841
842   Tables.SEHTableVA = Conf->SEHandlerTable;
843   Tables.SEHTableCount = Conf->SEHandlerCount;
844
845   // Print everything before CodeIntegrity. (2015)
846   if (Conf->Size < offsetof(T, CodeIntegrity))
847     return;
848   W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
849   W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
850   W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
851   W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
852   W.printHex("GuardFlags", Conf->GuardFlags);
853
854   Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
855   Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
856   Tables.GuardFlags = Conf->GuardFlags;
857
858   // Print the rest. (2017)
859   if (Conf->Size < sizeof(T))
860     return;
861   W.printHex("GuardAddressTakenIatEntryTable",
862              Conf->GuardAddressTakenIatEntryTable);
863   W.printNumber("GuardAddressTakenIatEntryCount",
864                 Conf->GuardAddressTakenIatEntryCount);
865   W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
866   W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
867   W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
868   W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
869   W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
870   W.printHex("GuardRFFailureRoutineFunctionPointer",
871              Conf->GuardRFFailureRoutineFunctionPointer);
872   W.printHex("DynamicValueRelocTableOffset",
873              Conf->DynamicValueRelocTableOffset);
874   W.printNumber("DynamicValueRelocTableSection",
875                 Conf->DynamicValueRelocTableSection);
876   W.printHex("GuardRFVerifyStackPointerFunctionPointer",
877              Conf->GuardRFVerifyStackPointerFunctionPointer);
878   W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
879 }
880
881 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
882   W.printHex("BaseOfData", Hdr->BaseOfData);
883 }
884
885 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
886
887 void COFFDumper::printCodeViewDebugInfo() {
888   // Print types first to build CVUDTNames, then print symbols.
889   for (const SectionRef &S : Obj->sections()) {
890     StringRef SectionName;
891     error(S.getName(SectionName));
892     if (SectionName == ".debug$T")
893       printCodeViewTypeSection(SectionName, S);
894   }
895   for (const SectionRef &S : Obj->sections()) {
896     StringRef SectionName;
897     error(S.getName(SectionName));
898     if (SectionName == ".debug$S")
899       printCodeViewSymbolSection(SectionName, S);
900   }
901 }
902
903 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
904   while (Reader.bytesRemaining() > 0 &&
905          (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
906     // The section consists of a number of subsection in the following format:
907     // |SubSectionType|SubSectionSize|Contents...|
908     uint32_t SubType, SubSectionSize;
909     error(Reader.readInteger(SubType));
910     error(Reader.readInteger(SubSectionSize));
911
912     StringRef Contents;
913     error(Reader.readFixedString(Contents, SubSectionSize));
914
915     BinaryStreamRef ST(Contents, support::little);
916     switch (DebugSubsectionKind(SubType)) {
917     case DebugSubsectionKind::FileChecksums:
918       error(CVFileChecksumTable.initialize(ST));
919       break;
920     case DebugSubsectionKind::StringTable:
921       error(CVStringTable.initialize(ST));
922       break;
923     default:
924       break;
925     }
926
927     uint32_t PaddedSize = alignTo(SubSectionSize, 4);
928     error(Reader.skip(PaddedSize - SubSectionSize));
929   }
930 }
931
932 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
933                                             const SectionRef &Section) {
934   StringRef SectionContents;
935   error(Section.getContents(SectionContents));
936   StringRef Data = SectionContents;
937
938   SmallVector<StringRef, 10> FunctionNames;
939   StringMap<StringRef> FunctionLineTables;
940
941   ListScope D(W, "CodeViewDebugInfo");
942   // Print the section to allow correlation with printSections.
943   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
944
945   uint32_t Magic;
946   error(consume(Data, Magic));
947   W.printHex("Magic", Magic);
948   if (Magic != COFF::DEBUG_SECTION_MAGIC)
949     return error(object_error::parse_failed);
950
951   BinaryStreamReader FSReader(Data, support::little);
952   initializeFileAndStringTables(FSReader);
953
954   // TODO: Convert this over to using ModuleSubstreamVisitor.
955   while (!Data.empty()) {
956     // The section consists of a number of subsection in the following format:
957     // |SubSectionType|SubSectionSize|Contents...|
958     uint32_t SubType, SubSectionSize;
959     error(consume(Data, SubType));
960     error(consume(Data, SubSectionSize));
961
962     ListScope S(W, "Subsection");
963     W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
964     W.printHex("SubSectionSize", SubSectionSize);
965
966     // Get the contents of the subsection.
967     if (SubSectionSize > Data.size())
968       return error(object_error::parse_failed);
969     StringRef Contents = Data.substr(0, SubSectionSize);
970
971     // Add SubSectionSize to the current offset and align that offset to find
972     // the next subsection.
973     size_t SectionOffset = Data.data() - SectionContents.data();
974     size_t NextOffset = SectionOffset + SubSectionSize;
975     NextOffset = alignTo(NextOffset, 4);
976     if (NextOffset > SectionContents.size())
977       return error(object_error::parse_failed);
978     Data = SectionContents.drop_front(NextOffset);
979
980     // Optionally print the subsection bytes in case our parsing gets confused
981     // later.
982     if (opts::CodeViewSubsectionBytes)
983       printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
984                                  Contents);
985
986     switch (DebugSubsectionKind(SubType)) {
987     case DebugSubsectionKind::Symbols:
988       printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
989       break;
990
991     case DebugSubsectionKind::InlineeLines:
992       printCodeViewInlineeLines(Contents);
993       break;
994
995     case DebugSubsectionKind::FileChecksums:
996       printCodeViewFileChecksums(Contents);
997       break;
998
999     case DebugSubsectionKind::Lines: {
1000       // Holds a PC to file:line table.  Some data to parse this subsection is
1001       // stored in the other subsections, so just check sanity and store the
1002       // pointers for deferred processing.
1003
1004       if (SubSectionSize < 12) {
1005         // There should be at least three words to store two function
1006         // relocations and size of the code.
1007         error(object_error::parse_failed);
1008         return;
1009       }
1010
1011       StringRef LinkageName;
1012       error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
1013                               LinkageName));
1014       W.printString("LinkageName", LinkageName);
1015       if (FunctionLineTables.count(LinkageName) != 0) {
1016         // Saw debug info for this function already?
1017         error(object_error::parse_failed);
1018         return;
1019       }
1020
1021       FunctionLineTables[LinkageName] = Contents;
1022       FunctionNames.push_back(LinkageName);
1023       break;
1024     }
1025     case DebugSubsectionKind::FrameData: {
1026       // First four bytes is a relocation against the function.
1027       BinaryStreamReader SR(Contents, llvm::support::little);
1028
1029       DebugFrameDataSubsectionRef FrameData;
1030       error(FrameData.initialize(SR));
1031
1032       StringRef LinkageName;
1033       error(resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1034                               FrameData.getRelocPtr(), LinkageName));
1035       W.printString("LinkageName", LinkageName);
1036
1037       // To find the active frame description, search this array for the
1038       // smallest PC range that includes the current PC.
1039       for (const auto &FD : FrameData) {
1040         StringRef FrameFunc = error(CVStringTable.getString(FD.FrameFunc));
1041
1042         DictScope S(W, "FrameData");
1043         W.printHex("RvaStart", FD.RvaStart);
1044         W.printHex("CodeSize", FD.CodeSize);
1045         W.printHex("LocalSize", FD.LocalSize);
1046         W.printHex("ParamsSize", FD.ParamsSize);
1047         W.printHex("MaxStackSize", FD.MaxStackSize);
1048         W.printString("FrameFunc", FrameFunc);
1049         W.printHex("PrologSize", FD.PrologSize);
1050         W.printHex("SavedRegsSize", FD.SavedRegsSize);
1051         W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1052       }
1053       break;
1054     }
1055
1056     // Do nothing for unrecognized subsections.
1057     default:
1058       break;
1059     }
1060     W.flush();
1061   }
1062
1063   // Dump the line tables now that we've read all the subsections and know all
1064   // the required information.
1065   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1066     StringRef Name = FunctionNames[I];
1067     ListScope S(W, "FunctionLineTable");
1068     W.printString("LinkageName", Name);
1069
1070     BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1071
1072     DebugLinesSubsectionRef LineInfo;
1073     error(LineInfo.initialize(Reader));
1074
1075     W.printHex("Flags", LineInfo.header()->Flags);
1076     W.printHex("CodeSize", LineInfo.header()->CodeSize);
1077     for (const auto &Entry : LineInfo) {
1078
1079       ListScope S(W, "FilenameSegment");
1080       printFileNameForOffset("Filename", Entry.NameIndex);
1081       uint32_t ColumnIndex = 0;
1082       for (const auto &Line : Entry.LineNumbers) {
1083         if (Line.Offset >= LineInfo.header()->CodeSize) {
1084           error(object_error::parse_failed);
1085           return;
1086         }
1087
1088         std::string PC = formatv("+{0:X}", uint32_t(Line.Offset));
1089         ListScope PCScope(W, PC);
1090         codeview::LineInfo LI(Line.Flags);
1091
1092         if (LI.isAlwaysStepInto())
1093           W.printString("StepInto", StringRef("Always"));
1094         else if (LI.isNeverStepInto())
1095           W.printString("StepInto", StringRef("Never"));
1096         else
1097           W.printNumber("LineNumberStart", LI.getStartLine());
1098         W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1099         W.printBoolean("IsStatement", LI.isStatement());
1100         if (LineInfo.hasColumnInfo()) {
1101           W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1102           W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1103           ++ColumnIndex;
1104         }
1105       }
1106     }
1107   }
1108 }
1109
1110 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1111                                                 const SectionRef &Section,
1112                                                 StringRef SectionContents) {
1113   ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1114                                Subsection.bytes_end());
1115   auto CODD = llvm::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1116                                                         SectionContents);
1117   CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1118                       opts::CodeViewSubsectionBytes);
1119   CVSymbolArray Symbols;
1120   BinaryStreamReader Reader(BinaryData, llvm::support::little);
1121   if (auto EC = Reader.readArray(Symbols, Reader.getLength())) {
1122     consumeError(std::move(EC));
1123     W.flush();
1124     error(object_error::parse_failed);
1125   }
1126
1127   if (auto EC = CVSD.dump(Symbols)) {
1128     W.flush();
1129     error(std::move(EC));
1130   }
1131   W.flush();
1132 }
1133
1134 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1135   BinaryStreamRef Stream(Subsection, llvm::support::little);
1136   DebugChecksumsSubsectionRef Checksums;
1137   error(Checksums.initialize(Stream));
1138
1139   for (auto &FC : Checksums) {
1140     DictScope S(W, "FileChecksum");
1141
1142     StringRef Filename = error(CVStringTable.getString(FC.FileNameOffset));
1143     W.printHex("Filename", Filename, FC.FileNameOffset);
1144     W.printHex("ChecksumSize", FC.Checksum.size());
1145     W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1146                 makeArrayRef(FileChecksumKindNames));
1147
1148     W.printBinary("ChecksumBytes", FC.Checksum);
1149   }
1150 }
1151
1152 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1153   BinaryStreamReader SR(Subsection, llvm::support::little);
1154   DebugInlineeLinesSubsectionRef Lines;
1155   error(Lines.initialize(SR));
1156
1157   for (auto &Line : Lines) {
1158     DictScope S(W, "InlineeSourceLine");
1159     printTypeIndex("Inlinee", Line.Header->Inlinee);
1160     printFileNameForOffset("FileID", Line.Header->FileID);
1161     W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1162
1163     if (Lines.hasExtraFiles()) {
1164       W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1165       ListScope ExtraFiles(W, "ExtraFiles");
1166       for (const auto &FID : Line.ExtraFiles) {
1167         printFileNameForOffset("FileID", FID);
1168       }
1169     }
1170   }
1171 }
1172
1173 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1174   // The file checksum subsection should precede all references to it.
1175   if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1176     error(object_error::parse_failed);
1177
1178   auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1179
1180   // Check if the file checksum table offset is valid.
1181   if (Iter == CVFileChecksumTable.end())
1182     error(object_error::parse_failed);
1183
1184   return error(CVStringTable.getString(Iter->FileNameOffset));
1185 }
1186
1187 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1188   W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1189 }
1190
1191 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1192                                     MergingTypeTableBuilder &CVTypes) {
1193   for (const SectionRef &S : Obj->sections()) {
1194     StringRef SectionName;
1195     error(S.getName(SectionName));
1196     if (SectionName == ".debug$T") {
1197       StringRef Data;
1198       error(S.getContents(Data));
1199       uint32_t Magic;
1200       error(consume(Data, Magic));
1201       if (Magic != 4)
1202         error(object_error::parse_failed);
1203
1204       CVTypeArray Types;
1205       BinaryStreamReader Reader(Data, llvm::support::little);
1206       if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1207         consumeError(std::move(EC));
1208         W.flush();
1209         error(object_error::parse_failed);
1210       }
1211       SmallVector<TypeIndex, 128> SourceToDest;
1212       if (auto EC = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types))
1213         return error(std::move(EC));
1214     }
1215   }
1216 }
1217
1218 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1219                                           const SectionRef &Section) {
1220   ListScope D(W, "CodeViewTypes");
1221   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1222
1223   StringRef Data;
1224   error(Section.getContents(Data));
1225   if (opts::CodeViewSubsectionBytes)
1226     W.printBinaryBlock("Data", Data);
1227
1228   uint32_t Magic;
1229   error(consume(Data, Magic));
1230   W.printHex("Magic", Magic);
1231   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1232     return error(object_error::parse_failed);
1233
1234   Types.reset(Data, 100);
1235
1236   TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1237   error(codeview::visitTypeStream(Types, TDV));
1238   W.flush();
1239 }
1240
1241 void COFFDumper::printSections() {
1242   ListScope SectionsD(W, "Sections");
1243   int SectionNumber = 0;
1244   for (const SectionRef &Sec : Obj->sections()) {
1245     ++SectionNumber;
1246     const coff_section *Section = Obj->getCOFFSection(Sec);
1247
1248     StringRef Name;
1249     error(Sec.getName(Name));
1250
1251     DictScope D(W, "Section");
1252     W.printNumber("Number", SectionNumber);
1253     W.printBinary("Name", Name, Section->Name);
1254     W.printHex   ("VirtualSize", Section->VirtualSize);
1255     W.printHex   ("VirtualAddress", Section->VirtualAddress);
1256     W.printNumber("RawDataSize", Section->SizeOfRawData);
1257     W.printHex   ("PointerToRawData", Section->PointerToRawData);
1258     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
1259     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
1260     W.printNumber("RelocationCount", Section->NumberOfRelocations);
1261     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1262     W.printFlags ("Characteristics", Section->Characteristics,
1263                     makeArrayRef(ImageSectionCharacteristics),
1264                     COFF::SectionCharacteristics(0x00F00000));
1265
1266     if (opts::SectionRelocations) {
1267       ListScope D(W, "Relocations");
1268       for (const RelocationRef &Reloc : Sec.relocations())
1269         printRelocation(Sec, Reloc);
1270     }
1271
1272     if (opts::SectionSymbols) {
1273       ListScope D(W, "Symbols");
1274       for (const SymbolRef &Symbol : Obj->symbols()) {
1275         if (!Sec.containsSymbol(Symbol))
1276           continue;
1277
1278         printSymbol(Symbol);
1279       }
1280     }
1281
1282     if (opts::SectionData &&
1283         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1284       StringRef Data;
1285       error(Sec.getContents(Data));
1286
1287       W.printBinaryBlock("SectionData", Data);
1288     }
1289   }
1290 }
1291
1292 void COFFDumper::printRelocations() {
1293   ListScope D(W, "Relocations");
1294
1295   int SectionNumber = 0;
1296   for (const SectionRef &Section : Obj->sections()) {
1297     ++SectionNumber;
1298     StringRef Name;
1299     error(Section.getName(Name));
1300
1301     bool PrintedGroup = false;
1302     for (const RelocationRef &Reloc : Section.relocations()) {
1303       if (!PrintedGroup) {
1304         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1305         W.indent();
1306         PrintedGroup = true;
1307       }
1308
1309       printRelocation(Section, Reloc);
1310     }
1311
1312     if (PrintedGroup) {
1313       W.unindent();
1314       W.startLine() << "}\n";
1315     }
1316   }
1317 }
1318
1319 void COFFDumper::printRelocation(const SectionRef &Section,
1320                                  const RelocationRef &Reloc, uint64_t Bias) {
1321   uint64_t Offset = Reloc.getOffset() - Bias;
1322   uint64_t RelocType = Reloc.getType();
1323   SmallString<32> RelocName;
1324   StringRef SymbolName;
1325   Reloc.getTypeName(RelocName);
1326   symbol_iterator Symbol = Reloc.getSymbol();
1327   if (Symbol != Obj->symbol_end()) {
1328     Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1329     error(errorToErrorCode(SymbolNameOrErr.takeError()));
1330     SymbolName = *SymbolNameOrErr;
1331   }
1332
1333   if (opts::ExpandRelocs) {
1334     DictScope Group(W, "Relocation");
1335     W.printHex("Offset", Offset);
1336     W.printNumber("Type", RelocName, RelocType);
1337     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1338   } else {
1339     raw_ostream& OS = W.startLine();
1340     OS << W.hex(Offset)
1341        << " " << RelocName
1342        << " " << (SymbolName.empty() ? "-" : SymbolName)
1343        << "\n";
1344   }
1345 }
1346
1347 void COFFDumper::printSymbols() {
1348   ListScope Group(W, "Symbols");
1349
1350   for (const SymbolRef &Symbol : Obj->symbols())
1351     printSymbol(Symbol);
1352 }
1353
1354 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1355
1356 static ErrorOr<StringRef>
1357 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1358                const coff_section *Section) {
1359   if (Section) {
1360     StringRef SectionName;
1361     if (std::error_code EC = Obj->getSectionName(Section, SectionName))
1362       return EC;
1363     return SectionName;
1364   }
1365   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1366     return StringRef("IMAGE_SYM_DEBUG");
1367   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1368     return StringRef("IMAGE_SYM_ABSOLUTE");
1369   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1370     return StringRef("IMAGE_SYM_UNDEFINED");
1371   return StringRef("");
1372 }
1373
1374 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1375   DictScope D(W, "Symbol");
1376
1377   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1378   const coff_section *Section;
1379   if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1380     W.startLine() << "Invalid section number: " << EC.message() << "\n";
1381     W.flush();
1382     return;
1383   }
1384
1385   StringRef SymbolName;
1386   if (Obj->getSymbolName(Symbol, SymbolName))
1387     SymbolName = "";
1388
1389   StringRef SectionName = "";
1390   ErrorOr<StringRef> Res =
1391       getSectionName(Obj, Symbol.getSectionNumber(), Section);
1392   if (Res)
1393     SectionName = *Res;
1394
1395   W.printString("Name", SymbolName);
1396   W.printNumber("Value", Symbol.getValue());
1397   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1398   W.printEnum  ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1399   W.printEnum  ("ComplexType", Symbol.getComplexType(),
1400                                                    makeArrayRef(ImageSymDType));
1401   W.printEnum  ("StorageClass", Symbol.getStorageClass(),
1402                                                    makeArrayRef(ImageSymClass));
1403   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1404
1405   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1406     if (Symbol.isFunctionDefinition()) {
1407       const coff_aux_function_definition *Aux;
1408       error(getSymbolAuxData(Obj, Symbol, I, Aux));
1409
1410       DictScope AS(W, "AuxFunctionDef");
1411       W.printNumber("TagIndex", Aux->TagIndex);
1412       W.printNumber("TotalSize", Aux->TotalSize);
1413       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1414       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1415
1416     } else if (Symbol.isAnyUndefined()) {
1417       const coff_aux_weak_external *Aux;
1418       error(getSymbolAuxData(Obj, Symbol, I, Aux));
1419
1420       Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1421       StringRef LinkedName;
1422       std::error_code EC = errorToErrorCode(Linked.takeError());
1423       if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) {
1424         LinkedName = "";
1425         error(EC);
1426       }
1427
1428       DictScope AS(W, "AuxWeakExternal");
1429       W.printNumber("Linked", LinkedName, Aux->TagIndex);
1430       W.printEnum  ("Search", Aux->Characteristics,
1431                     makeArrayRef(WeakExternalCharacteristics));
1432
1433     } else if (Symbol.isFileRecord()) {
1434       const char *FileName;
1435       error(getSymbolAuxData(Obj, Symbol, I, FileName));
1436
1437       DictScope AS(W, "AuxFileRecord");
1438
1439       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1440                                    Obj->getSymbolTableEntrySize());
1441       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1442       break;
1443     } else if (Symbol.isSectionDefinition()) {
1444       const coff_aux_section_definition *Aux;
1445       error(getSymbolAuxData(Obj, Symbol, I, Aux));
1446
1447       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1448
1449       DictScope AS(W, "AuxSectionDef");
1450       W.printNumber("Length", Aux->Length);
1451       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1452       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1453       W.printHex("Checksum", Aux->CheckSum);
1454       W.printNumber("Number", AuxNumber);
1455       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1456
1457       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1458           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1459         const coff_section *Assoc;
1460         StringRef AssocName = "";
1461         std::error_code EC = Obj->getSection(AuxNumber, Assoc);
1462         ErrorOr<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1463         if (Res)
1464           AssocName = *Res;
1465         if (!EC)
1466           EC = Res.getError();
1467         if (EC) {
1468           AssocName = "";
1469           error(EC);
1470         }
1471
1472         W.printNumber("AssocSection", AssocName, AuxNumber);
1473       }
1474     } else if (Symbol.isCLRToken()) {
1475       const coff_aux_clr_token *Aux;
1476       error(getSymbolAuxData(Obj, Symbol, I, Aux));
1477
1478       Expected<COFFSymbolRef> ReferredSym =
1479           Obj->getSymbol(Aux->SymbolTableIndex);
1480       StringRef ReferredName;
1481       std::error_code EC = errorToErrorCode(ReferredSym.takeError());
1482       if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
1483         ReferredName = "";
1484         error(EC);
1485       }
1486
1487       DictScope AS(W, "AuxCLRToken");
1488       W.printNumber("AuxType", Aux->AuxType);
1489       W.printNumber("Reserved", Aux->Reserved);
1490       W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1491
1492     } else {
1493       W.startLine() << "<unhandled auxiliary record>\n";
1494     }
1495   }
1496 }
1497
1498 void COFFDumper::printUnwindInfo() {
1499   ListScope D(W, "UnwindInformation");
1500   switch (Obj->getMachine()) {
1501   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1502     Win64EH::Dumper Dumper(W);
1503     Win64EH::Dumper::SymbolResolver
1504     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1505                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1506       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1507       return Dumper->resolveSymbol(Section, Offset, Symbol);
1508     };
1509     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1510     Dumper.printData(Ctx);
1511     break;
1512   }
1513   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1514     ARM::WinEH::Decoder Decoder(W);
1515     Decoder.dumpProcedureData(*Obj);
1516     break;
1517   }
1518   default:
1519     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1520                 makeArrayRef(ImageFileMachineType));
1521     break;
1522   }
1523 }
1524
1525 void COFFDumper::printImportedSymbols(
1526     iterator_range<imported_symbol_iterator> Range) {
1527   for (const ImportedSymbolRef &I : Range) {
1528     StringRef Sym;
1529     error(I.getSymbolName(Sym));
1530     uint16_t Ordinal;
1531     error(I.getOrdinal(Ordinal));
1532     W.printNumber("Symbol", Sym, Ordinal);
1533   }
1534 }
1535
1536 void COFFDumper::printDelayImportedSymbols(
1537     const DelayImportDirectoryEntryRef &I,
1538     iterator_range<imported_symbol_iterator> Range) {
1539   int Index = 0;
1540   for (const ImportedSymbolRef &S : Range) {
1541     DictScope Import(W, "Import");
1542     StringRef Sym;
1543     error(S.getSymbolName(Sym));
1544     uint16_t Ordinal;
1545     error(S.getOrdinal(Ordinal));
1546     W.printNumber("Symbol", Sym, Ordinal);
1547     uint64_t Addr;
1548     error(I.getImportAddress(Index++, Addr));
1549     W.printHex("Address", Addr);
1550   }
1551 }
1552
1553 void COFFDumper::printCOFFImports() {
1554   // Regular imports
1555   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1556     DictScope Import(W, "Import");
1557     StringRef Name;
1558     error(I.getName(Name));
1559     W.printString("Name", Name);
1560     uint32_t ILTAddr;
1561     error(I.getImportLookupTableRVA(ILTAddr));
1562     W.printHex("ImportLookupTableRVA", ILTAddr);
1563     uint32_t IATAddr;
1564     error(I.getImportAddressTableRVA(IATAddr));
1565     W.printHex("ImportAddressTableRVA", IATAddr);
1566     // The import lookup table can be missing with certain older linkers, so
1567     // fall back to the import address table in that case.
1568     if (ILTAddr)
1569       printImportedSymbols(I.lookup_table_symbols());
1570     else
1571       printImportedSymbols(I.imported_symbols());
1572   }
1573
1574   // Delay imports
1575   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1576     DictScope Import(W, "DelayImport");
1577     StringRef Name;
1578     error(I.getName(Name));
1579     W.printString("Name", Name);
1580     const delay_import_directory_table_entry *Table;
1581     error(I.getDelayImportTable(Table));
1582     W.printHex("Attributes", Table->Attributes);
1583     W.printHex("ModuleHandle", Table->ModuleHandle);
1584     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1585     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1586     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1587     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1588     printDelayImportedSymbols(I, I.imported_symbols());
1589   }
1590 }
1591
1592 void COFFDumper::printCOFFExports() {
1593   for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1594     DictScope Export(W, "Export");
1595
1596     StringRef Name;
1597     uint32_t Ordinal, RVA;
1598
1599     error(E.getSymbolName(Name));
1600     error(E.getOrdinal(Ordinal));
1601     error(E.getExportRVA(RVA));
1602
1603     W.printNumber("Ordinal", Ordinal);
1604     W.printString("Name", Name);
1605     W.printHex("RVA", RVA);
1606   }
1607 }
1608
1609 void COFFDumper::printCOFFDirectives() {
1610   for (const SectionRef &Section : Obj->sections()) {
1611     StringRef Contents;
1612     StringRef Name;
1613
1614     error(Section.getName(Name));
1615     if (Name != ".drectve")
1616       continue;
1617
1618     error(Section.getContents(Contents));
1619
1620     W.printString("Directive(s)", Contents);
1621   }
1622 }
1623
1624 static std::string getBaseRelocTypeName(uint8_t Type) {
1625   switch (Type) {
1626   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1627   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1628   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1629   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1630   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1631   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1632   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1633   default: return "unknown (" + llvm::utostr(Type) + ")";
1634   }
1635 }
1636
1637 void COFFDumper::printCOFFBaseReloc() {
1638   ListScope D(W, "BaseReloc");
1639   for (const BaseRelocRef &I : Obj->base_relocs()) {
1640     uint8_t Type;
1641     uint32_t RVA;
1642     error(I.getRVA(RVA));
1643     error(I.getType(Type));
1644     DictScope Import(W, "Entry");
1645     W.printString("Type", getBaseRelocTypeName(Type));
1646     W.printHex("Address", RVA);
1647   }
1648 }
1649
1650 void COFFDumper::printCOFFResources() {
1651   ListScope ResourcesD(W, "Resources");
1652   for (const SectionRef &S : Obj->sections()) {
1653     StringRef Name;
1654     error(S.getName(Name));
1655     if (!Name.startswith(".rsrc"))
1656       continue;
1657
1658     StringRef Ref;
1659     error(S.getContents(Ref));
1660
1661     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1662       ResourceSectionRef RSF(Ref);
1663       auto &BaseTable = unwrapOrError(RSF.getBaseTable());
1664       W.printNumber("Total Number of Resources",
1665                     countTotalTableEntries(RSF, BaseTable, "Type"));
1666       W.printHex("Base Table Address",
1667                  Obj->getCOFFSection(S)->PointerToRawData);
1668       W.startLine() << "\n";
1669       printResourceDirectoryTable(RSF, BaseTable, "Type");
1670     }
1671     if (opts::SectionData)
1672       W.printBinaryBlock(Name.str() + " Data", Ref);
1673   }
1674 }
1675
1676 uint32_t
1677 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1678                                    const coff_resource_dir_table &Table,
1679                                    StringRef Level) {
1680   uint32_t TotalEntries = 0;
1681   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1682        i++) {
1683     auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1684     if (Entry.Offset.isSubDir()) {
1685       StringRef NextLevel;
1686       if (Level == "Name")
1687         NextLevel = "Language";
1688       else
1689         NextLevel = "Name";
1690       auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1691       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1692     } else {
1693       TotalEntries += 1;
1694     }
1695   }
1696   return TotalEntries;
1697 }
1698
1699 void COFFDumper::printResourceDirectoryTable(
1700     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1701     StringRef Level) {
1702
1703   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1704   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1705
1706   // Iterate through level in resource directory tree.
1707   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1708        i++) {
1709     auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1710     StringRef Name;
1711     SmallString<20> IDStr;
1712     raw_svector_ostream OS(IDStr);
1713     if (i < Table.NumberOfNameEntries) {
1714       ArrayRef<UTF16> RawEntryNameString = unwrapOrError(RSF.getEntryNameString(Entry));
1715       std::vector<UTF16> EndianCorrectedNameString;
1716       if (llvm::sys::IsBigEndianHost) {
1717         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1718         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1719                   EndianCorrectedNameString.begin() + 1);
1720         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1721         RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1722       }
1723       std::string EntryNameString;
1724       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1725         error(object_error::parse_failed);
1726       OS << ": ";
1727       OS << EntryNameString;
1728     } else {
1729       if (Level == "Type") {
1730         ScopedPrinter Printer(OS);
1731         Printer.printEnum("", Entry.Identifier.ID,
1732                           makeArrayRef(ResourceTypeNames));
1733         IDStr = IDStr.slice(0, IDStr.find_first_of(")", 0) + 1);
1734       } else {
1735         OS << ": (ID " << Entry.Identifier.ID << ")";
1736       }
1737     }
1738     Name = StringRef(IDStr);
1739     ListScope ResourceType(W, Level.str() + Name.str());
1740     if (Entry.Offset.isSubDir()) {
1741       W.printHex("Table Offset", Entry.Offset.value());
1742       StringRef NextLevel;
1743       if (Level == "Name")
1744         NextLevel = "Language";
1745       else
1746         NextLevel = "Name";
1747       auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1748       printResourceDirectoryTable(RSF, NextTable, NextLevel);
1749     } else {
1750       W.printHex("Entry Offset", Entry.Offset.value());
1751       char FormattedTime[20] = {};
1752       time_t TDS = time_t(Table.TimeDateStamp);
1753       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1754       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1755       W.printNumber("Major Version", Table.MajorVersion);
1756       W.printNumber("Minor Version", Table.MinorVersion);
1757       W.printNumber("Characteristics", Table.Characteristics);
1758     }
1759   }
1760 }
1761
1762 ErrorOr<const coff_resource_dir_entry &>
1763 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
1764                                            uint32_t Index) {
1765   if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1766     return object_error::parse_failed;
1767   auto TablePtr = reinterpret_cast<const coff_resource_dir_entry *>(&Table + 1);
1768   return TablePtr[Index];
1769 }
1770
1771 void COFFDumper::printStackMap() const {
1772   object::SectionRef StackMapSection;
1773   for (auto Sec : Obj->sections()) {
1774     StringRef Name;
1775     Sec.getName(Name);
1776     if (Name == ".llvm_stackmaps") {
1777       StackMapSection = Sec;
1778       break;
1779     }
1780   }
1781
1782   if (StackMapSection == object::SectionRef())
1783     return;
1784
1785   StringRef StackMapContents;
1786   StackMapSection.getContents(StackMapContents);
1787   ArrayRef<uint8_t> StackMapContentsArray(
1788       reinterpret_cast<const uint8_t*>(StackMapContents.data()),
1789       StackMapContents.size());
1790
1791   if (Obj->isLittleEndian())
1792     prettyPrintStackMap(
1793                       llvm::outs(),
1794                       StackMapV2Parser<support::little>(StackMapContentsArray));
1795   else
1796     prettyPrintStackMap(llvm::outs(),
1797                         StackMapV2Parser<support::big>(StackMapContentsArray));
1798 }
1799
1800 void llvm::dumpCodeViewMergedTypes(
1801     ScopedPrinter &Writer, llvm::codeview::MergingTypeTableBuilder &IDTable,
1802     llvm::codeview::MergingTypeTableBuilder &CVTypes) {
1803   // Flatten it first, then run our dumper on it.
1804   SmallString<0> TypeBuf;
1805   CVTypes.ForEachRecord([&](TypeIndex TI, const CVType &Record) {
1806     TypeBuf.append(Record.RecordData.begin(), Record.RecordData.end());
1807   });
1808
1809   TypeTableCollection TpiTypes(CVTypes.records());
1810   {
1811     ListScope S(Writer, "MergedTypeStream");
1812     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1813     error(codeview::visitTypeStream(TpiTypes, TDV));
1814     Writer.flush();
1815   }
1816
1817   // Flatten the id stream and print it next. The ID stream refers to names from
1818   // the type stream.
1819   TypeTableCollection IpiTypes(IDTable.records());
1820   {
1821     ListScope S(Writer, "MergedIDStream");
1822     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1823     TDV.setIpiTypes(IpiTypes);
1824     error(codeview::visitTypeStream(IpiTypes, TDV));
1825     Writer.flush();
1826   }
1827 }