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