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