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