08031ae8f49c86631a94875474311b4c94309933
[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("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
633     W.printFlags ("Characteristics", Obj->getCharacteristics(),
634                     makeArrayRef(ImageFileCharacteristics));
635   }
636
637   // Print PE header. This header does not exist if this is an object file and
638   // not an executable.
639   if (const pe32_header *PEHeader = Obj->getPE32Header())
640     printPEHeader<pe32_header>(PEHeader);
641
642   if (const pe32plus_header *PEPlusHeader = Obj->getPE32PlusHeader())
643     printPEHeader<pe32plus_header>(PEPlusHeader);
644
645   if (const dos_header *DH = Obj->getDOSHeader())
646     printDOSHeader(DH);
647 }
648
649 void COFFDumper::printDOSHeader(const dos_header *DH) {
650   DictScope D(W, "DOSHeader");
651   W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
652   W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
653   W.printNumber("FileSizeInPages", DH->FileSizeInPages);
654   W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
655   W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
656   W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
657   W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
658   W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
659   W.printNumber("InitialSP", DH->InitialSP);
660   W.printNumber("Checksum", DH->Checksum);
661   W.printNumber("InitialIP", DH->InitialIP);
662   W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
663   W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
664   W.printNumber("OverlayNumber", DH->OverlayNumber);
665   W.printNumber("OEMid", DH->OEMid);
666   W.printNumber("OEMinfo", DH->OEMinfo);
667   W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
668 }
669
670 template <class PEHeader>
671 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
672   DictScope D(W, "ImageOptionalHeader");
673   W.printHex   ("Magic", Hdr->Magic);
674   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
675   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
676   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
677   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
678   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
679   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
680   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
681   printBaseOfDataField(Hdr);
682   W.printHex   ("ImageBase", Hdr->ImageBase);
683   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
684   W.printNumber("FileAlignment", Hdr->FileAlignment);
685   W.printNumber("MajorOperatingSystemVersion",
686                 Hdr->MajorOperatingSystemVersion);
687   W.printNumber("MinorOperatingSystemVersion",
688                 Hdr->MinorOperatingSystemVersion);
689   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
690   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
691   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
692   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
693   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
694   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
695   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
696   W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
697                 makeArrayRef(PEDLLCharacteristics));
698   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
699   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
700   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
701   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
702   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
703
704   if (Hdr->NumberOfRvaAndSize > 0) {
705     DictScope D(W, "DataDirectory");
706     static const char * const directory[] = {
707       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
708       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
709       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
710       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
711     };
712
713     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
714       printDataDirectory(i, directory[i]);
715   }
716 }
717
718 void COFFDumper::printCOFFDebugDirectory() {
719   ListScope LS(W, "DebugDirectory");
720   for (const debug_directory &D : Obj->debug_directories()) {
721     char FormattedTime[20] = {};
722     time_t TDS = D.TimeDateStamp;
723     strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
724     DictScope S(W, "DebugEntry");
725     W.printHex("Characteristics", D.Characteristics);
726     W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
727     W.printHex("MajorVersion", D.MajorVersion);
728     W.printHex("MinorVersion", D.MinorVersion);
729     W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
730     W.printHex("SizeOfData", D.SizeOfData);
731     W.printHex("AddressOfRawData", D.AddressOfRawData);
732     W.printHex("PointerToRawData", D.PointerToRawData);
733     // Ideally, if D.AddressOfRawData == 0, we should try to load the payload
734     // using D.PointerToRawData instead.
735     if (D.AddressOfRawData == 0)
736       continue;
737     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
738       const codeview::DebugInfo *DebugInfo;
739       StringRef PDBFileName;
740       if (std::error_code EC = Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName))
741         reportError(errorCodeToError(EC), Obj->getFileName());
742
743       DictScope PDBScope(W, "PDBInfo");
744       W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
745       if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
746         W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
747         W.printNumber("PDBAge", DebugInfo->PDB70.Age);
748         W.printString("PDBFileName", PDBFileName);
749       }
750     } else if (D.SizeOfData != 0) {
751       // FIXME: Data visualization for IMAGE_DEBUG_TYPE_VC_FEATURE and
752       // IMAGE_DEBUG_TYPE_POGO?
753       ArrayRef<uint8_t> RawData;
754       if (std::error_code EC = Obj->getRvaAndSizeAsBytes(D.AddressOfRawData,
755                                                          D.SizeOfData, RawData))
756         reportError(errorCodeToError(EC), Obj->getFileName());
757       if (D.Type == COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) {
758         // FIXME right now the only possible value would fit in 8 bits,
759         // but that might change in the future
760         uint16_t Characteristics = RawData[0];
761         W.printFlags("ExtendedCharacteristics", Characteristics,
762                      makeArrayRef(PEExtendedDLLCharacteristics));
763       }
764       W.printBinaryBlock("RawData", RawData);
765     }
766   }
767 }
768
769 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
770                                uint64_t EntrySize, PrintExtraCB PrintExtra) {
771   uintptr_t TableStart, TableEnd;
772   if (std::error_code EC = Obj->getVaPtr(TableVA, TableStart))
773     reportError(errorCodeToError(EC), Obj->getFileName());
774   if (std::error_code EC =
775           Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd))
776     reportError(errorCodeToError(EC), Obj->getFileName());
777   TableEnd++;
778   for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
779     uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
780     raw_ostream &OS = W.startLine();
781     OS << W.hex(Obj->getImageBase() + RVA);
782     if (PrintExtra)
783       PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
784     OS << '\n';
785   }
786 }
787
788 void COFFDumper::printCOFFLoadConfig() {
789   LoadConfigTables Tables;
790   if (Obj->is64())
791     printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
792   else
793     printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
794
795   if (Tables.SEHTableVA) {
796     ListScope LS(W, "SEHTable");
797     printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
798   }
799
800   if (Tables.GuardFidTableVA) {
801     ListScope LS(W, "GuardFidTable");
802     if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
803       auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
804         uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
805         if (Flags)
806           OS << " flags " << utohexstr(Flags);
807       };
808       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
809                     PrintGuardFlags);
810     } else {
811       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
812     }
813   }
814
815   if (Tables.GuardLJmpTableVA) {
816     ListScope LS(W, "GuardLJmpTable");
817     printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
818   }
819 }
820
821 template <typename T>
822 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
823   if (!Conf)
824     return;
825
826   ListScope LS(W, "LoadConfig");
827   char FormattedTime[20] = {};
828   time_t TDS = Conf->TimeDateStamp;
829   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
830   W.printHex("Size", Conf->Size);
831
832   // Print everything before SecurityCookie. The vast majority of images today
833   // have all these fields.
834   if (Conf->Size < offsetof(T, SEHandlerTable))
835     return;
836   W.printHex("TimeDateStamp", FormattedTime, TDS);
837   W.printHex("MajorVersion", Conf->MajorVersion);
838   W.printHex("MinorVersion", Conf->MinorVersion);
839   W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
840   W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
841   W.printHex("CriticalSectionDefaultTimeout",
842              Conf->CriticalSectionDefaultTimeout);
843   W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
844   W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
845   W.printHex("LockPrefixTable", Conf->LockPrefixTable);
846   W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
847   W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
848   W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
849   W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
850   W.printHex("CSDVersion", Conf->CSDVersion);
851   W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
852   W.printHex("EditList", Conf->EditList);
853   W.printHex("SecurityCookie", Conf->SecurityCookie);
854
855   // Print the safe SEH table if present.
856   if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
857     return;
858   W.printHex("SEHandlerTable", Conf->SEHandlerTable);
859   W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
860
861   Tables.SEHTableVA = Conf->SEHandlerTable;
862   Tables.SEHTableCount = Conf->SEHandlerCount;
863
864   // Print everything before CodeIntegrity. (2015)
865   if (Conf->Size < offsetof(T, CodeIntegrity))
866     return;
867   W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
868   W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
869   W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
870   W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
871   W.printHex("GuardFlags", Conf->GuardFlags);
872
873   Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
874   Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
875   Tables.GuardFlags = Conf->GuardFlags;
876
877   // Print the rest. (2017)
878   if (Conf->Size < sizeof(T))
879     return;
880   W.printHex("GuardAddressTakenIatEntryTable",
881              Conf->GuardAddressTakenIatEntryTable);
882   W.printNumber("GuardAddressTakenIatEntryCount",
883                 Conf->GuardAddressTakenIatEntryCount);
884   W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
885   W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
886   W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
887   W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
888   W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
889   W.printHex("GuardRFFailureRoutineFunctionPointer",
890              Conf->GuardRFFailureRoutineFunctionPointer);
891   W.printHex("DynamicValueRelocTableOffset",
892              Conf->DynamicValueRelocTableOffset);
893   W.printNumber("DynamicValueRelocTableSection",
894                 Conf->DynamicValueRelocTableSection);
895   W.printHex("GuardRFVerifyStackPointerFunctionPointer",
896              Conf->GuardRFVerifyStackPointerFunctionPointer);
897   W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
898
899   Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
900   Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
901 }
902
903 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
904   W.printHex("BaseOfData", Hdr->BaseOfData);
905 }
906
907 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
908
909 void COFFDumper::printCodeViewDebugInfo() {
910   // Print types first to build CVUDTNames, then print symbols.
911   for (const SectionRef &S : Obj->sections()) {
912     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
913     // .debug$T is a standard CodeView type section, while .debug$P is the same
914     // format but used for MSVC precompiled header object files.
915     if (SectionName == ".debug$T" || SectionName == ".debug$P")
916       printCodeViewTypeSection(SectionName, S);
917   }
918   for (const SectionRef &S : Obj->sections()) {
919     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
920     if (SectionName == ".debug$S")
921       printCodeViewSymbolSection(SectionName, S);
922   }
923 }
924
925 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
926   while (Reader.bytesRemaining() > 0 &&
927          (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
928     // The section consists of a number of subsection in the following format:
929     // |SubSectionType|SubSectionSize|Contents...|
930     uint32_t SubType, SubSectionSize;
931
932     if (Error E = Reader.readInteger(SubType))
933       reportError(std::move(E), Obj->getFileName());
934     if (Error E = Reader.readInteger(SubSectionSize))
935       reportError(std::move(E), Obj->getFileName());
936
937     StringRef Contents;
938     if (Error E = Reader.readFixedString(Contents, SubSectionSize))
939       reportError(std::move(E), Obj->getFileName());
940
941     BinaryStreamRef ST(Contents, support::little);
942     switch (DebugSubsectionKind(SubType)) {
943     case DebugSubsectionKind::FileChecksums:
944       if (Error E = CVFileChecksumTable.initialize(ST))
945         reportError(std::move(E), Obj->getFileName());
946       break;
947     case DebugSubsectionKind::StringTable:
948       if (Error E = CVStringTable.initialize(ST))
949         reportError(std::move(E), Obj->getFileName());
950       break;
951     default:
952       break;
953     }
954
955     uint32_t PaddedSize = alignTo(SubSectionSize, 4);
956     if (Error E = Reader.skip(PaddedSize - SubSectionSize))
957       reportError(std::move(E), Obj->getFileName());
958   }
959 }
960
961 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
962                                             const SectionRef &Section) {
963   StringRef SectionContents =
964       unwrapOrError(Obj->getFileName(), Section.getContents());
965   StringRef Data = SectionContents;
966
967   SmallVector<StringRef, 10> FunctionNames;
968   StringMap<StringRef> FunctionLineTables;
969
970   ListScope D(W, "CodeViewDebugInfo");
971   // Print the section to allow correlation with printSectionHeaders.
972   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
973
974   uint32_t Magic;
975   if (Error E = consume(Data, Magic))
976     reportError(std::move(E), Obj->getFileName());
977
978   W.printHex("Magic", Magic);
979   if (Magic != COFF::DEBUG_SECTION_MAGIC)
980     reportError(errorCodeToError(object_error::parse_failed),
981                 Obj->getFileName());
982
983   BinaryStreamReader FSReader(Data, support::little);
984   initializeFileAndStringTables(FSReader);
985
986   // TODO: Convert this over to using ModuleSubstreamVisitor.
987   while (!Data.empty()) {
988     // The section consists of a number of subsection in the following format:
989     // |SubSectionType|SubSectionSize|Contents...|
990     uint32_t SubType, SubSectionSize;
991     if (Error E = consume(Data, SubType))
992       reportError(std::move(E), Obj->getFileName());
993     if (Error E = consume(Data, SubSectionSize))
994       reportError(std::move(E), Obj->getFileName());
995
996     ListScope S(W, "Subsection");
997     // Dump the subsection as normal even if the ignore bit is set.
998     if (SubType & SubsectionIgnoreFlag) {
999       W.printHex("IgnoredSubsectionKind", SubType);
1000       SubType &= ~SubsectionIgnoreFlag;
1001     }
1002     W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
1003     W.printHex("SubSectionSize", SubSectionSize);
1004
1005     // Get the contents of the subsection.
1006     if (SubSectionSize > Data.size())
1007       return reportError(errorCodeToError(object_error::parse_failed),
1008                          Obj->getFileName());
1009     StringRef Contents = Data.substr(0, SubSectionSize);
1010
1011     // Add SubSectionSize to the current offset and align that offset to find
1012     // the next subsection.
1013     size_t SectionOffset = Data.data() - SectionContents.data();
1014     size_t NextOffset = SectionOffset + SubSectionSize;
1015     NextOffset = alignTo(NextOffset, 4);
1016     if (NextOffset > SectionContents.size())
1017       return reportError(errorCodeToError(object_error::parse_failed),
1018                          Obj->getFileName());
1019     Data = SectionContents.drop_front(NextOffset);
1020
1021     // Optionally print the subsection bytes in case our parsing gets confused
1022     // later.
1023     if (opts::CodeViewSubsectionBytes)
1024       printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
1025                                  Contents);
1026
1027     switch (DebugSubsectionKind(SubType)) {
1028     case DebugSubsectionKind::Symbols:
1029       printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1030       break;
1031
1032     case DebugSubsectionKind::InlineeLines:
1033       printCodeViewInlineeLines(Contents);
1034       break;
1035
1036     case DebugSubsectionKind::FileChecksums:
1037       printCodeViewFileChecksums(Contents);
1038       break;
1039
1040     case DebugSubsectionKind::Lines: {
1041       // Holds a PC to file:line table.  Some data to parse this subsection is
1042       // stored in the other subsections, so just check sanity and store the
1043       // pointers for deferred processing.
1044
1045       if (SubSectionSize < 12) {
1046         // There should be at least three words to store two function
1047         // relocations and size of the code.
1048         reportError(errorCodeToError(object_error::parse_failed),
1049                     Obj->getFileName());
1050         return;
1051       }
1052
1053       StringRef LinkageName;
1054       if (std::error_code EC = resolveSymbolName(Obj->getCOFFSection(Section),
1055                                                  SectionOffset, LinkageName))
1056         reportError(errorCodeToError(EC), Obj->getFileName());
1057
1058       W.printString("LinkageName", LinkageName);
1059       if (FunctionLineTables.count(LinkageName) != 0) {
1060         // Saw debug info for this function already?
1061         reportError(errorCodeToError(object_error::parse_failed),
1062                     Obj->getFileName());
1063         return;
1064       }
1065
1066       FunctionLineTables[LinkageName] = Contents;
1067       FunctionNames.push_back(LinkageName);
1068       break;
1069     }
1070     case DebugSubsectionKind::FrameData: {
1071       // First four bytes is a relocation against the function.
1072       BinaryStreamReader SR(Contents, llvm::support::little);
1073
1074       DebugFrameDataSubsectionRef FrameData;
1075       if (Error E = FrameData.initialize(SR))
1076         reportError(std::move(E), Obj->getFileName());
1077
1078       StringRef LinkageName;
1079       if (std::error_code EC =
1080               resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1081                                 FrameData.getRelocPtr(), LinkageName))
1082         reportError(errorCodeToError(EC), Obj->getFileName());
1083       W.printString("LinkageName", LinkageName);
1084
1085       // To find the active frame description, search this array for the
1086       // smallest PC range that includes the current PC.
1087       for (const auto &FD : FrameData) {
1088         StringRef FrameFunc = unwrapOrError(
1089             Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
1090
1091         DictScope S(W, "FrameData");
1092         W.printHex("RvaStart", FD.RvaStart);
1093         W.printHex("CodeSize", FD.CodeSize);
1094         W.printHex("LocalSize", FD.LocalSize);
1095         W.printHex("ParamsSize", FD.ParamsSize);
1096         W.printHex("MaxStackSize", FD.MaxStackSize);
1097         W.printHex("PrologSize", FD.PrologSize);
1098         W.printHex("SavedRegsSize", FD.SavedRegsSize);
1099         W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1100
1101         // The FrameFunc string is a small RPN program. It can be broken up into
1102         // statements that end in the '=' operator, which assigns the value on
1103         // the top of the stack to the previously pushed variable. Variables can
1104         // be temporary values ($T0) or physical registers ($esp). Print each
1105         // assignment on its own line to make these programs easier to read.
1106         {
1107           ListScope FFS(W, "FrameFunc");
1108           while (!FrameFunc.empty()) {
1109             size_t EqOrEnd = FrameFunc.find('=');
1110             if (EqOrEnd == StringRef::npos)
1111               EqOrEnd = FrameFunc.size();
1112             else
1113               ++EqOrEnd;
1114             StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1115             W.printString(Stmt);
1116             FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1117           }
1118         }
1119       }
1120       break;
1121     }
1122
1123     // Do nothing for unrecognized subsections.
1124     default:
1125       break;
1126     }
1127     W.flush();
1128   }
1129
1130   // Dump the line tables now that we've read all the subsections and know all
1131   // the required information.
1132   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1133     StringRef Name = FunctionNames[I];
1134     ListScope S(W, "FunctionLineTable");
1135     W.printString("LinkageName", Name);
1136
1137     BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1138
1139     DebugLinesSubsectionRef LineInfo;
1140     if (Error E = LineInfo.initialize(Reader))
1141       reportError(std::move(E), Obj->getFileName());
1142
1143     W.printHex("Flags", LineInfo.header()->Flags);
1144     W.printHex("CodeSize", LineInfo.header()->CodeSize);
1145     for (const auto &Entry : LineInfo) {
1146
1147       ListScope S(W, "FilenameSegment");
1148       printFileNameForOffset("Filename", Entry.NameIndex);
1149       uint32_t ColumnIndex = 0;
1150       for (const auto &Line : Entry.LineNumbers) {
1151         if (Line.Offset >= LineInfo.header()->CodeSize) {
1152           reportError(errorCodeToError(object_error::parse_failed),
1153                       Obj->getFileName());
1154           return;
1155         }
1156
1157         std::string PC = std::string(formatv("+{0:X}", uint32_t(Line.Offset)));
1158         ListScope PCScope(W, PC);
1159         codeview::LineInfo LI(Line.Flags);
1160
1161         if (LI.isAlwaysStepInto())
1162           W.printString("StepInto", StringRef("Always"));
1163         else if (LI.isNeverStepInto())
1164           W.printString("StepInto", StringRef("Never"));
1165         else
1166           W.printNumber("LineNumberStart", LI.getStartLine());
1167         W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1168         W.printBoolean("IsStatement", LI.isStatement());
1169         if (LineInfo.hasColumnInfo()) {
1170           W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1171           W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1172           ++ColumnIndex;
1173         }
1174       }
1175     }
1176   }
1177 }
1178
1179 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1180                                                 const SectionRef &Section,
1181                                                 StringRef SectionContents) {
1182   ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1183                                Subsection.bytes_end());
1184   auto CODD = std::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1185                                                         SectionContents);
1186   CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1187                       CompilationCPUType, opts::CodeViewSubsectionBytes);
1188   CVSymbolArray Symbols;
1189   BinaryStreamReader Reader(BinaryData, llvm::support::little);
1190   if (Error E = Reader.readArray(Symbols, Reader.getLength())) {
1191     W.flush();
1192     reportError(std::move(E), Obj->getFileName());
1193   }
1194
1195   if (Error E = CVSD.dump(Symbols)) {
1196     W.flush();
1197     reportError(std::move(E), Obj->getFileName());
1198   }
1199   CompilationCPUType = CVSD.getCompilationCPUType();
1200   W.flush();
1201 }
1202
1203 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1204   BinaryStreamRef Stream(Subsection, llvm::support::little);
1205   DebugChecksumsSubsectionRef Checksums;
1206   if (Error E = Checksums.initialize(Stream))
1207     reportError(std::move(E), Obj->getFileName());
1208
1209   for (auto &FC : Checksums) {
1210     DictScope S(W, "FileChecksum");
1211
1212     StringRef Filename = unwrapOrError(
1213         Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
1214     W.printHex("Filename", Filename, FC.FileNameOffset);
1215     W.printHex("ChecksumSize", FC.Checksum.size());
1216     W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1217                 makeArrayRef(FileChecksumKindNames));
1218
1219     W.printBinary("ChecksumBytes", FC.Checksum);
1220   }
1221 }
1222
1223 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1224   BinaryStreamReader SR(Subsection, llvm::support::little);
1225   DebugInlineeLinesSubsectionRef Lines;
1226   if (Error E = Lines.initialize(SR))
1227     reportError(std::move(E), Obj->getFileName());
1228
1229   for (auto &Line : Lines) {
1230     DictScope S(W, "InlineeSourceLine");
1231     printTypeIndex("Inlinee", Line.Header->Inlinee);
1232     printFileNameForOffset("FileID", Line.Header->FileID);
1233     W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1234
1235     if (Lines.hasExtraFiles()) {
1236       W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1237       ListScope ExtraFiles(W, "ExtraFiles");
1238       for (const auto &FID : Line.ExtraFiles) {
1239         printFileNameForOffset("FileID", FID);
1240       }
1241     }
1242   }
1243 }
1244
1245 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1246   // The file checksum subsection should precede all references to it.
1247   if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1248     reportError(errorCodeToError(object_error::parse_failed),
1249                 Obj->getFileName());
1250
1251   auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1252
1253   // Check if the file checksum table offset is valid.
1254   if (Iter == CVFileChecksumTable.end())
1255     reportError(errorCodeToError(object_error::parse_failed),
1256                 Obj->getFileName());
1257
1258   return unwrapOrError(Obj->getFileName(),
1259                        CVStringTable.getString(Iter->FileNameOffset));
1260 }
1261
1262 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1263   W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1264 }
1265
1266 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1267                                     MergingTypeTableBuilder &CVTypes,
1268                                     GlobalTypeTableBuilder &GlobalCVIDs,
1269                                     GlobalTypeTableBuilder &GlobalCVTypes,
1270                                     bool GHash) {
1271   for (const SectionRef &S : Obj->sections()) {
1272     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1273     if (SectionName == ".debug$T") {
1274       StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
1275       uint32_t Magic;
1276       if (Error E = consume(Data, Magic))
1277         reportError(std::move(E), Obj->getFileName());
1278
1279       if (Magic != 4)
1280         reportError(errorCodeToError(object_error::parse_failed),
1281                     Obj->getFileName());
1282
1283       CVTypeArray Types;
1284       BinaryStreamReader Reader(Data, llvm::support::little);
1285       if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1286         consumeError(std::move(EC));
1287         W.flush();
1288         reportError(errorCodeToError(object_error::parse_failed),
1289                     Obj->getFileName());
1290       }
1291       SmallVector<TypeIndex, 128> SourceToDest;
1292       Optional<uint32_t> PCHSignature;
1293       if (GHash) {
1294         std::vector<GloballyHashedType> Hashes =
1295             GloballyHashedType::hashTypes(Types);
1296         if (Error E =
1297                 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1298                                       Types, Hashes, PCHSignature))
1299           return reportError(std::move(E), Obj->getFileName());
1300       } else {
1301         if (Error E = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1302                                             PCHSignature))
1303           return reportError(std::move(E), Obj->getFileName());
1304       }
1305     }
1306   }
1307 }
1308
1309 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1310                                           const SectionRef &Section) {
1311   ListScope D(W, "CodeViewTypes");
1312   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1313
1314   StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
1315   if (opts::CodeViewSubsectionBytes)
1316     W.printBinaryBlock("Data", Data);
1317
1318   uint32_t Magic;
1319   if (Error E = consume(Data, Magic))
1320     reportError(std::move(E), Obj->getFileName());
1321
1322   W.printHex("Magic", Magic);
1323   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1324     reportError(errorCodeToError(object_error::parse_failed),
1325                 Obj->getFileName());
1326
1327   Types.reset(Data, 100);
1328
1329   TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1330   if (Error E = codeview::visitTypeStream(Types, TDV))
1331     reportError(std::move(E), Obj->getFileName());
1332
1333   W.flush();
1334 }
1335
1336 void COFFDumper::printSectionHeaders() {
1337   ListScope SectionsD(W, "Sections");
1338   int SectionNumber = 0;
1339   for (const SectionRef &Sec : Obj->sections()) {
1340     ++SectionNumber;
1341     const coff_section *Section = Obj->getCOFFSection(Sec);
1342
1343     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
1344
1345     DictScope D(W, "Section");
1346     W.printNumber("Number", SectionNumber);
1347     W.printBinary("Name", Name, Section->Name);
1348     W.printHex   ("VirtualSize", Section->VirtualSize);
1349     W.printHex   ("VirtualAddress", Section->VirtualAddress);
1350     W.printNumber("RawDataSize", Section->SizeOfRawData);
1351     W.printHex   ("PointerToRawData", Section->PointerToRawData);
1352     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
1353     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
1354     W.printNumber("RelocationCount", Section->NumberOfRelocations);
1355     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1356     W.printFlags ("Characteristics", Section->Characteristics,
1357                     makeArrayRef(ImageSectionCharacteristics),
1358                     COFF::SectionCharacteristics(0x00F00000));
1359
1360     if (opts::SectionRelocations) {
1361       ListScope D(W, "Relocations");
1362       for (const RelocationRef &Reloc : Sec.relocations())
1363         printRelocation(Sec, Reloc);
1364     }
1365
1366     if (opts::SectionSymbols) {
1367       ListScope D(W, "Symbols");
1368       for (const SymbolRef &Symbol : Obj->symbols()) {
1369         if (!Sec.containsSymbol(Symbol))
1370           continue;
1371
1372         printSymbol(Symbol);
1373       }
1374     }
1375
1376     if (opts::SectionData &&
1377         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1378       StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
1379       W.printBinaryBlock("SectionData", Data);
1380     }
1381   }
1382 }
1383
1384 void COFFDumper::printRelocations() {
1385   ListScope D(W, "Relocations");
1386
1387   int SectionNumber = 0;
1388   for (const SectionRef &Section : Obj->sections()) {
1389     ++SectionNumber;
1390     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1391
1392     bool PrintedGroup = false;
1393     for (const RelocationRef &Reloc : Section.relocations()) {
1394       if (!PrintedGroup) {
1395         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1396         W.indent();
1397         PrintedGroup = true;
1398       }
1399
1400       printRelocation(Section, Reloc);
1401     }
1402
1403     if (PrintedGroup) {
1404       W.unindent();
1405       W.startLine() << "}\n";
1406     }
1407   }
1408 }
1409
1410 void COFFDumper::printRelocation(const SectionRef &Section,
1411                                  const RelocationRef &Reloc, uint64_t Bias) {
1412   uint64_t Offset = Reloc.getOffset() - Bias;
1413   uint64_t RelocType = Reloc.getType();
1414   SmallString<32> RelocName;
1415   StringRef SymbolName;
1416   Reloc.getTypeName(RelocName);
1417   symbol_iterator Symbol = Reloc.getSymbol();
1418   int64_t SymbolIndex = -1;
1419   if (Symbol != Obj->symbol_end()) {
1420     Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1421     if (!SymbolNameOrErr)
1422       reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
1423
1424     SymbolName = *SymbolNameOrErr;
1425     SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1426   }
1427
1428   if (opts::ExpandRelocs) {
1429     DictScope Group(W, "Relocation");
1430     W.printHex("Offset", Offset);
1431     W.printNumber("Type", RelocName, RelocType);
1432     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1433     W.printNumber("SymbolIndex", SymbolIndex);
1434   } else {
1435     raw_ostream& OS = W.startLine();
1436     OS << W.hex(Offset)
1437        << " " << RelocName
1438        << " " << (SymbolName.empty() ? "-" : SymbolName)
1439        << " (" << SymbolIndex << ")"
1440        << "\n";
1441   }
1442 }
1443
1444 void COFFDumper::printSymbols() {
1445   ListScope Group(W, "Symbols");
1446
1447   for (const SymbolRef &Symbol : Obj->symbols())
1448     printSymbol(Symbol);
1449 }
1450
1451 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1452
1453 static Expected<StringRef>
1454 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1455                const coff_section *Section) {
1456   if (Section)
1457     return Obj->getSectionName(Section);
1458   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1459     return StringRef("IMAGE_SYM_DEBUG");
1460   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1461     return StringRef("IMAGE_SYM_ABSOLUTE");
1462   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1463     return StringRef("IMAGE_SYM_UNDEFINED");
1464   return StringRef("");
1465 }
1466
1467 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1468   DictScope D(W, "Symbol");
1469
1470   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1471   const coff_section *Section;
1472   if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1473     W.startLine() << "Invalid section number: " << EC.message() << "\n";
1474     W.flush();
1475     return;
1476   }
1477
1478   StringRef SymbolName;
1479   if (Obj->getSymbolName(Symbol, SymbolName))
1480     SymbolName = "";
1481
1482   StringRef SectionName;
1483   if (Expected<StringRef> NameOrErr =
1484           getSectionName(Obj, Symbol.getSectionNumber(), Section))
1485     SectionName = *NameOrErr;
1486
1487   W.printString("Name", SymbolName);
1488   W.printNumber("Value", Symbol.getValue());
1489   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1490   W.printEnum  ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1491   W.printEnum  ("ComplexType", Symbol.getComplexType(),
1492                                                    makeArrayRef(ImageSymDType));
1493   W.printEnum  ("StorageClass", Symbol.getStorageClass(),
1494                                                    makeArrayRef(ImageSymClass));
1495   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1496
1497   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1498     if (Symbol.isFunctionDefinition()) {
1499       const coff_aux_function_definition *Aux;
1500       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1501         reportError(errorCodeToError(EC), Obj->getFileName());
1502
1503       DictScope AS(W, "AuxFunctionDef");
1504       W.printNumber("TagIndex", Aux->TagIndex);
1505       W.printNumber("TotalSize", Aux->TotalSize);
1506       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1507       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1508
1509     } else if (Symbol.isAnyUndefined()) {
1510       const coff_aux_weak_external *Aux;
1511       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1512         reportError(errorCodeToError(EC), Obj->getFileName());
1513
1514       Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1515       if (!Linked)
1516         reportError(Linked.takeError(), Obj->getFileName());
1517
1518       StringRef LinkedName;
1519       if (std::error_code EC = Obj->getSymbolName(*Linked, LinkedName))
1520         reportError(errorCodeToError(EC), Obj->getFileName());
1521
1522       DictScope AS(W, "AuxWeakExternal");
1523       W.printNumber("Linked", LinkedName, Aux->TagIndex);
1524       W.printEnum  ("Search", Aux->Characteristics,
1525                     makeArrayRef(WeakExternalCharacteristics));
1526
1527     } else if (Symbol.isFileRecord()) {
1528       const char *FileName;
1529       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
1530         reportError(errorCodeToError(EC), Obj->getFileName());
1531       DictScope AS(W, "AuxFileRecord");
1532
1533       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1534                                    Obj->getSymbolTableEntrySize());
1535       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1536       break;
1537     } else if (Symbol.isSectionDefinition()) {
1538       const coff_aux_section_definition *Aux;
1539       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1540         reportError(errorCodeToError(EC), Obj->getFileName());
1541
1542       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1543
1544       DictScope AS(W, "AuxSectionDef");
1545       W.printNumber("Length", Aux->Length);
1546       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1547       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1548       W.printHex("Checksum", Aux->CheckSum);
1549       W.printNumber("Number", AuxNumber);
1550       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1551
1552       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1553           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1554         const coff_section *Assoc;
1555         StringRef AssocName = "";
1556         if (std::error_code EC = Obj->getSection(AuxNumber, Assoc))
1557           reportError(errorCodeToError(EC), Obj->getFileName());
1558         Expected<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1559         if (!Res)
1560           reportError(Res.takeError(), Obj->getFileName());
1561         AssocName = *Res;
1562
1563         W.printNumber("AssocSection", AssocName, AuxNumber);
1564       }
1565     } else if (Symbol.isCLRToken()) {
1566       const coff_aux_clr_token *Aux;
1567       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1568         reportError(errorCodeToError(EC), Obj->getFileName());
1569
1570       Expected<COFFSymbolRef> ReferredSym =
1571           Obj->getSymbol(Aux->SymbolTableIndex);
1572       if (!ReferredSym)
1573         reportError(ReferredSym.takeError(), Obj->getFileName());
1574
1575       StringRef ReferredName;
1576       if (std::error_code EC = Obj->getSymbolName(*ReferredSym, ReferredName))
1577         reportError(errorCodeToError(EC), Obj->getFileName());
1578
1579       DictScope AS(W, "AuxCLRToken");
1580       W.printNumber("AuxType", Aux->AuxType);
1581       W.printNumber("Reserved", Aux->Reserved);
1582       W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1583
1584     } else {
1585       W.startLine() << "<unhandled auxiliary record>\n";
1586     }
1587   }
1588 }
1589
1590 void COFFDumper::printUnwindInfo() {
1591   ListScope D(W, "UnwindInformation");
1592   switch (Obj->getMachine()) {
1593   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1594     Win64EH::Dumper Dumper(W);
1595     Win64EH::Dumper::SymbolResolver
1596     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1597                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1598       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1599       return Dumper->resolveSymbol(Section, Offset, Symbol);
1600     };
1601     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1602     Dumper.printData(Ctx);
1603     break;
1604   }
1605   case COFF::IMAGE_FILE_MACHINE_ARM64:
1606   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1607     ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
1608                                        COFF::IMAGE_FILE_MACHINE_ARM64);
1609     // TODO Propagate the error.
1610     consumeError(Decoder.dumpProcedureData(*Obj));
1611     break;
1612   }
1613   default:
1614     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1615                 makeArrayRef(ImageFileMachineType));
1616     break;
1617   }
1618 }
1619
1620 void COFFDumper::printNeededLibraries() {
1621   ListScope D(W, "NeededLibraries");
1622
1623   using LibsTy = std::vector<StringRef>;
1624   LibsTy Libs;
1625
1626   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1627     StringRef Name;
1628     if (!DirRef.getName(Name))
1629       Libs.push_back(Name);
1630   }
1631
1632   llvm::stable_sort(Libs);
1633
1634   for (const auto &L : Libs) {
1635     W.startLine() << L << "\n";
1636   }
1637 }
1638
1639 void COFFDumper::printImportedSymbols(
1640     iterator_range<imported_symbol_iterator> Range) {
1641   for (const ImportedSymbolRef &I : Range) {
1642     StringRef Sym;
1643     if (std::error_code EC = I.getSymbolName(Sym))
1644       reportError(errorCodeToError(EC), Obj->getFileName());
1645     uint16_t Ordinal;
1646     if (std::error_code EC = I.getOrdinal(Ordinal))
1647       reportError(errorCodeToError(EC), Obj->getFileName());
1648     W.printNumber("Symbol", Sym, Ordinal);
1649   }
1650 }
1651
1652 void COFFDumper::printDelayImportedSymbols(
1653     const DelayImportDirectoryEntryRef &I,
1654     iterator_range<imported_symbol_iterator> Range) {
1655   int Index = 0;
1656   for (const ImportedSymbolRef &S : Range) {
1657     DictScope Import(W, "Import");
1658     StringRef Sym;
1659     if (std::error_code EC = S.getSymbolName(Sym))
1660       reportError(errorCodeToError(EC), Obj->getFileName());
1661
1662     uint16_t Ordinal;
1663     if (std::error_code EC = S.getOrdinal(Ordinal))
1664       reportError(errorCodeToError(EC), Obj->getFileName());
1665     W.printNumber("Symbol", Sym, Ordinal);
1666
1667     uint64_t Addr;
1668     if (std::error_code EC = I.getImportAddress(Index++, Addr))
1669       reportError(errorCodeToError(EC), Obj->getFileName());
1670     W.printHex("Address", Addr);
1671   }
1672 }
1673
1674 void COFFDumper::printCOFFImports() {
1675   // Regular imports
1676   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1677     DictScope Import(W, "Import");
1678     StringRef Name;
1679     if (std::error_code EC = I.getName(Name))
1680       reportError(errorCodeToError(EC), Obj->getFileName());
1681     W.printString("Name", Name);
1682     uint32_t ILTAddr;
1683     if (std::error_code EC = I.getImportLookupTableRVA(ILTAddr))
1684       reportError(errorCodeToError(EC), Obj->getFileName());
1685     W.printHex("ImportLookupTableRVA", ILTAddr);
1686     uint32_t IATAddr;
1687     if (std::error_code EC = I.getImportAddressTableRVA(IATAddr))
1688       reportError(errorCodeToError(EC), Obj->getFileName());
1689     W.printHex("ImportAddressTableRVA", IATAddr);
1690     // The import lookup table can be missing with certain older linkers, so
1691     // fall back to the import address table in that case.
1692     if (ILTAddr)
1693       printImportedSymbols(I.lookup_table_symbols());
1694     else
1695       printImportedSymbols(I.imported_symbols());
1696   }
1697
1698   // Delay imports
1699   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1700     DictScope Import(W, "DelayImport");
1701     StringRef Name;
1702     if (std::error_code EC = I.getName(Name))
1703       reportError(errorCodeToError(EC), Obj->getFileName());
1704     W.printString("Name", Name);
1705     const delay_import_directory_table_entry *Table;
1706     if (std::error_code EC = I.getDelayImportTable(Table))
1707       reportError(errorCodeToError(EC), Obj->getFileName());
1708     W.printHex("Attributes", Table->Attributes);
1709     W.printHex("ModuleHandle", Table->ModuleHandle);
1710     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1711     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1712     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1713     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1714     printDelayImportedSymbols(I, I.imported_symbols());
1715   }
1716 }
1717
1718 void COFFDumper::printCOFFExports() {
1719   for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1720     DictScope Export(W, "Export");
1721
1722     StringRef Name;
1723     uint32_t Ordinal, RVA;
1724
1725     if (std::error_code EC = E.getSymbolName(Name))
1726       reportError(errorCodeToError(EC), Obj->getFileName());
1727     if (std::error_code EC = E.getOrdinal(Ordinal))
1728       reportError(errorCodeToError(EC), Obj->getFileName());
1729     if (std::error_code EC = E.getExportRVA(RVA))
1730       reportError(errorCodeToError(EC), Obj->getFileName());
1731
1732     W.printNumber("Ordinal", Ordinal);
1733     W.printString("Name", Name);
1734     W.printHex("RVA", RVA);
1735   }
1736 }
1737
1738 void COFFDumper::printCOFFDirectives() {
1739   for (const SectionRef &Section : Obj->sections()) {
1740     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1741     if (Name != ".drectve")
1742       continue;
1743
1744     StringRef Contents =
1745         unwrapOrError(Obj->getFileName(), Section.getContents());
1746     W.printString("Directive(s)", Contents);
1747   }
1748 }
1749
1750 static std::string getBaseRelocTypeName(uint8_t Type) {
1751   switch (Type) {
1752   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1753   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1754   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1755   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1756   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1757   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1758   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1759   default: return "unknown (" + llvm::utostr(Type) + ")";
1760   }
1761 }
1762
1763 void COFFDumper::printCOFFBaseReloc() {
1764   ListScope D(W, "BaseReloc");
1765   for (const BaseRelocRef &I : Obj->base_relocs()) {
1766     uint8_t Type;
1767     uint32_t RVA;
1768     if (std::error_code EC = I.getRVA(RVA))
1769       reportError(errorCodeToError(EC), Obj->getFileName());
1770     if (std::error_code EC = I.getType(Type))
1771       reportError(errorCodeToError(EC), Obj->getFileName());
1772     DictScope Import(W, "Entry");
1773     W.printString("Type", getBaseRelocTypeName(Type));
1774     W.printHex("Address", RVA);
1775   }
1776 }
1777
1778 void COFFDumper::printCOFFResources() {
1779   ListScope ResourcesD(W, "Resources");
1780   for (const SectionRef &S : Obj->sections()) {
1781     StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
1782     if (!Name.startswith(".rsrc"))
1783       continue;
1784
1785     StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1786
1787     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1788       ResourceSectionRef RSF;
1789       Error E = RSF.load(Obj, S);
1790       if (E)
1791         reportError(std::move(E), Obj->getFileName());
1792       auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1793       W.printNumber("Total Number of Resources",
1794                     countTotalTableEntries(RSF, BaseTable, "Type"));
1795       W.printHex("Base Table Address",
1796                  Obj->getCOFFSection(S)->PointerToRawData);
1797       W.startLine() << "\n";
1798       printResourceDirectoryTable(RSF, BaseTable, "Type");
1799     }
1800     if (opts::SectionData)
1801       W.printBinaryBlock(Name.str() + " Data", Ref);
1802   }
1803 }
1804
1805 uint32_t
1806 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1807                                    const coff_resource_dir_table &Table,
1808                                    StringRef Level) {
1809   uint32_t TotalEntries = 0;
1810   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1811        i++) {
1812     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1813     if (Entry.Offset.isSubDir()) {
1814       StringRef NextLevel;
1815       if (Level == "Name")
1816         NextLevel = "Language";
1817       else
1818         NextLevel = "Name";
1819       auto &NextTable =
1820           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1821       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1822     } else {
1823       TotalEntries += 1;
1824     }
1825   }
1826   return TotalEntries;
1827 }
1828
1829 void COFFDumper::printResourceDirectoryTable(
1830     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1831     StringRef Level) {
1832
1833   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1834   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1835
1836   // Iterate through level in resource directory tree.
1837   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1838        i++) {
1839     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1840     StringRef Name;
1841     SmallString<20> IDStr;
1842     raw_svector_ostream OS(IDStr);
1843     if (i < Table.NumberOfNameEntries) {
1844       ArrayRef<UTF16> RawEntryNameString =
1845           unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
1846       std::vector<UTF16> EndianCorrectedNameString;
1847       if (llvm::sys::IsBigEndianHost) {
1848         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1849         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1850                   EndianCorrectedNameString.begin() + 1);
1851         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1852         RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1853       }
1854       std::string EntryNameString;
1855       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1856         reportError(errorCodeToError(object_error::parse_failed),
1857                     Obj->getFileName());
1858       OS << ": ";
1859       OS << EntryNameString;
1860     } else {
1861       if (Level == "Type") {
1862         OS << ": ";
1863         printResourceTypeName(Entry.Identifier.ID, OS);
1864       } else {
1865         OS << ": (ID " << Entry.Identifier.ID << ")";
1866       }
1867     }
1868     Name = StringRef(IDStr);
1869     ListScope ResourceType(W, Level.str() + Name.str());
1870     if (Entry.Offset.isSubDir()) {
1871       W.printHex("Table Offset", Entry.Offset.value());
1872       StringRef NextLevel;
1873       if (Level == "Name")
1874         NextLevel = "Language";
1875       else
1876         NextLevel = "Name";
1877       auto &NextTable =
1878           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1879       printResourceDirectoryTable(RSF, NextTable, NextLevel);
1880     } else {
1881       W.printHex("Entry Offset", Entry.Offset.value());
1882       char FormattedTime[20] = {};
1883       time_t TDS = time_t(Table.TimeDateStamp);
1884       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1885       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1886       W.printNumber("Major Version", Table.MajorVersion);
1887       W.printNumber("Minor Version", Table.MinorVersion);
1888       W.printNumber("Characteristics", Table.Characteristics);
1889       ListScope DataScope(W, "Data");
1890       auto &DataEntry =
1891           unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
1892       W.printHex("DataRVA", DataEntry.DataRVA);
1893       W.printNumber("DataSize", DataEntry.DataSize);
1894       W.printNumber("Codepage", DataEntry.Codepage);
1895       W.printNumber("Reserved", DataEntry.Reserved);
1896       StringRef Contents =
1897           unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
1898       W.printBinaryBlock("Data", Contents);
1899     }
1900   }
1901 }
1902
1903 void COFFDumper::printStackMap() const {
1904   object::SectionRef StackMapSection;
1905   for (auto Sec : Obj->sections()) {
1906     StringRef Name;
1907     if (Expected<StringRef> NameOrErr = Sec.getName())
1908       Name = *NameOrErr;
1909     else
1910       consumeError(NameOrErr.takeError());
1911
1912     if (Name == ".llvm_stackmaps") {
1913       StackMapSection = Sec;
1914       break;
1915     }
1916   }
1917
1918   if (StackMapSection == object::SectionRef())
1919     return;
1920
1921   StringRef StackMapContents =
1922       unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
1923   ArrayRef<uint8_t> StackMapContentsArray =
1924       arrayRefFromStringRef(StackMapContents);
1925
1926   if (Obj->isLittleEndian())
1927     prettyPrintStackMap(
1928         W, StackMapParser<support::little>(StackMapContentsArray));
1929   else
1930     prettyPrintStackMap(
1931         W, StackMapParser<support::big>(StackMapContentsArray));
1932 }
1933
1934 void COFFDumper::printAddrsig() {
1935   object::SectionRef AddrsigSection;
1936   for (auto Sec : Obj->sections()) {
1937     StringRef Name;
1938     if (Expected<StringRef> NameOrErr = Sec.getName())
1939       Name = *NameOrErr;
1940     else
1941       consumeError(NameOrErr.takeError());
1942
1943     if (Name == ".llvm_addrsig") {
1944       AddrsigSection = Sec;
1945       break;
1946     }
1947   }
1948
1949   if (AddrsigSection == object::SectionRef())
1950     return;
1951
1952   StringRef AddrsigContents =
1953       unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
1954   ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
1955                                          AddrsigContents.size());
1956
1957   ListScope L(W, "Addrsig");
1958   const uint8_t *Cur = AddrsigContents.bytes_begin();
1959   const uint8_t *End = AddrsigContents.bytes_end();
1960   while (Cur != End) {
1961     unsigned Size;
1962     const char *Err;
1963     uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
1964     if (Err)
1965       reportError(createError(Err), Obj->getFileName());
1966
1967     Expected<COFFSymbolRef> Sym = Obj->getSymbol(SymIndex);
1968     if (!Sym)
1969       reportError(Sym.takeError(), Obj->getFileName());
1970
1971     StringRef SymName;
1972     if (std::error_code EC = Obj->getSymbolName(*Sym, SymName))
1973       reportError(errorCodeToError(EC), Obj->getFileName());
1974
1975     W.printNumber("Sym", SymName, SymIndex);
1976     Cur += Size;
1977   }
1978 }
1979
1980 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
1981                                    ArrayRef<ArrayRef<uint8_t>> IpiRecords,
1982                                    ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
1983   TypeTableCollection TpiTypes(TpiRecords);
1984   {
1985     ListScope S(Writer, "MergedTypeStream");
1986     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1987     if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
1988       reportError(std::move(Err), "<?>");
1989     Writer.flush();
1990   }
1991
1992   // Flatten the id stream and print it next. The ID stream refers to names from
1993   // the type stream.
1994   TypeTableCollection IpiTypes(IpiRecords);
1995   {
1996     ListScope S(Writer, "MergedIDStream");
1997     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1998     TDV.setIpiTypes(IpiTypes);
1999     if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
2000       reportError(std::move(Err), "<?>");
2001     Writer.flush();
2002   }
2003 }