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 = Obj->getDataDirectory(Index);
613   if (!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 (Error E = Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName))
742         reportError(std::move(E), 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 (Error E = Obj->getRvaAndSizeAsBytes(D.AddressOfRawData,
756                                                          D.SizeOfData, RawData))
757         reportError(std::move(E), 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 (Error E = Obj->getVaPtr(TableVA, TableStart))
774     reportError(std::move(E), Obj->getFileName());
775   if (Error E =
776           Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd))
777     reportError(std::move(E), 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   Expected<const coff_section *> SecOrErr =
1473       Obj->getSection(Symbol.getSectionNumber());
1474   if (!SecOrErr) {
1475     W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
1476                   << "\n";
1477     W.flush();
1478     consumeError(SecOrErr.takeError());
1479     return;
1480   }
1481   const coff_section *Section = *SecOrErr;
1482 
1483   StringRef SymbolName;
1484   if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
1485     SymbolName = *SymNameOrErr;
1486 
1487   StringRef SectionName;
1488   if (Expected<StringRef> SecNameOrErr =
1489           getSectionName(Obj, Symbol.getSectionNumber(), Section))
1490     SectionName = *SecNameOrErr;
1491 
1492   W.printString("Name", SymbolName);
1493   W.printNumber("Value", Symbol.getValue());
1494   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1495   W.printEnum  ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1496   W.printEnum  ("ComplexType", Symbol.getComplexType(),
1497                                                    makeArrayRef(ImageSymDType));
1498   W.printEnum  ("StorageClass", Symbol.getStorageClass(),
1499                                                    makeArrayRef(ImageSymClass));
1500   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1501 
1502   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1503     if (Symbol.isFunctionDefinition()) {
1504       const coff_aux_function_definition *Aux;
1505       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1506         reportError(errorCodeToError(EC), Obj->getFileName());
1507 
1508       DictScope AS(W, "AuxFunctionDef");
1509       W.printNumber("TagIndex", Aux->TagIndex);
1510       W.printNumber("TotalSize", Aux->TotalSize);
1511       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1512       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1513 
1514     } else if (Symbol.isAnyUndefined()) {
1515       const coff_aux_weak_external *Aux;
1516       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1517         reportError(errorCodeToError(EC), Obj->getFileName());
1518 
1519       Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1520       if (!Linked)
1521         reportError(Linked.takeError(), Obj->getFileName());
1522 
1523       Expected<StringRef> LinkedName = Obj->getSymbolName(*Linked);
1524       if (!LinkedName)
1525         reportError(LinkedName.takeError(), Obj->getFileName());
1526 
1527       DictScope AS(W, "AuxWeakExternal");
1528       W.printNumber("Linked", *LinkedName, Aux->TagIndex);
1529       W.printEnum  ("Search", Aux->Characteristics,
1530                     makeArrayRef(WeakExternalCharacteristics));
1531 
1532     } else if (Symbol.isFileRecord()) {
1533       const char *FileName;
1534       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
1535         reportError(errorCodeToError(EC), Obj->getFileName());
1536       DictScope AS(W, "AuxFileRecord");
1537 
1538       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1539                                    Obj->getSymbolTableEntrySize());
1540       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1541       break;
1542     } else if (Symbol.isSectionDefinition()) {
1543       const coff_aux_section_definition *Aux;
1544       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1545         reportError(errorCodeToError(EC), Obj->getFileName());
1546 
1547       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1548 
1549       DictScope AS(W, "AuxSectionDef");
1550       W.printNumber("Length", Aux->Length);
1551       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1552       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1553       W.printHex("Checksum", Aux->CheckSum);
1554       W.printNumber("Number", AuxNumber);
1555       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1556 
1557       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1558           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1559         Expected<const coff_section *> Assoc = Obj->getSection(AuxNumber);
1560         if (!Assoc)
1561           reportError(Assoc.takeError(), Obj->getFileName());
1562         Expected<StringRef> AssocName = getSectionName(Obj, AuxNumber, *Assoc);
1563         if (!AssocName)
1564           reportError(AssocName.takeError(), Obj->getFileName());
1565 
1566         W.printNumber("AssocSection", *AssocName, AuxNumber);
1567       }
1568     } else if (Symbol.isCLRToken()) {
1569       const coff_aux_clr_token *Aux;
1570       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1571         reportError(errorCodeToError(EC), Obj->getFileName());
1572 
1573       Expected<COFFSymbolRef> ReferredSym =
1574           Obj->getSymbol(Aux->SymbolTableIndex);
1575       if (!ReferredSym)
1576         reportError(ReferredSym.takeError(), Obj->getFileName());
1577 
1578       Expected<StringRef> ReferredName = Obj->getSymbolName(*ReferredSym);
1579       if (!ReferredName)
1580         reportError(ReferredName.takeError(), Obj->getFileName());
1581 
1582       DictScope AS(W, "AuxCLRToken");
1583       W.printNumber("AuxType", Aux->AuxType);
1584       W.printNumber("Reserved", Aux->Reserved);
1585       W.printNumber("SymbolTableIndex", *ReferredName, Aux->SymbolTableIndex);
1586 
1587     } else {
1588       W.startLine() << "<unhandled auxiliary record>\n";
1589     }
1590   }
1591 }
1592 
1593 void COFFDumper::printUnwindInfo() {
1594   ListScope D(W, "UnwindInformation");
1595   switch (Obj->getMachine()) {
1596   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1597     Win64EH::Dumper Dumper(W);
1598     Win64EH::Dumper::SymbolResolver
1599     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1600                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1601       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1602       return Dumper->resolveSymbol(Section, Offset, Symbol);
1603     };
1604     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1605     Dumper.printData(Ctx);
1606     break;
1607   }
1608   case COFF::IMAGE_FILE_MACHINE_ARM64:
1609   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1610     ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
1611                                        COFF::IMAGE_FILE_MACHINE_ARM64);
1612     // TODO Propagate the error.
1613     consumeError(Decoder.dumpProcedureData(*Obj));
1614     break;
1615   }
1616   default:
1617     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1618                 makeArrayRef(ImageFileMachineType));
1619     break;
1620   }
1621 }
1622 
1623 void COFFDumper::printNeededLibraries() {
1624   ListScope D(W, "NeededLibraries");
1625 
1626   using LibsTy = std::vector<StringRef>;
1627   LibsTy Libs;
1628 
1629   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1630     StringRef Name;
1631     if (!DirRef.getName(Name))
1632       Libs.push_back(Name);
1633   }
1634 
1635   llvm::stable_sort(Libs);
1636 
1637   for (const auto &L : Libs) {
1638     W.startLine() << L << "\n";
1639   }
1640 }
1641 
1642 void COFFDumper::printImportedSymbols(
1643     iterator_range<imported_symbol_iterator> Range) {
1644   for (const ImportedSymbolRef &I : Range) {
1645     StringRef Sym;
1646     if (Error E = I.getSymbolName(Sym))
1647       reportError(std::move(E), Obj->getFileName());
1648     uint16_t Ordinal;
1649     if (Error E = I.getOrdinal(Ordinal))
1650       reportError(std::move(E), Obj->getFileName());
1651     W.printNumber("Symbol", Sym, Ordinal);
1652   }
1653 }
1654 
1655 void COFFDumper::printDelayImportedSymbols(
1656     const DelayImportDirectoryEntryRef &I,
1657     iterator_range<imported_symbol_iterator> Range) {
1658   int Index = 0;
1659   for (const ImportedSymbolRef &S : Range) {
1660     DictScope Import(W, "Import");
1661     StringRef Sym;
1662     if (Error E = S.getSymbolName(Sym))
1663       reportError(std::move(E), Obj->getFileName());
1664 
1665     uint16_t Ordinal;
1666     if (Error E = S.getOrdinal(Ordinal))
1667       reportError(std::move(E), Obj->getFileName());
1668     W.printNumber("Symbol", Sym, Ordinal);
1669 
1670     uint64_t Addr;
1671     if (Error E = I.getImportAddress(Index++, Addr))
1672       reportError(std::move(E), Obj->getFileName());
1673     W.printHex("Address", Addr);
1674   }
1675 }
1676 
1677 void COFFDumper::printCOFFImports() {
1678   // Regular imports
1679   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1680     DictScope Import(W, "Import");
1681     StringRef Name;
1682     if (Error E = I.getName(Name))
1683       reportError(std::move(E), Obj->getFileName());
1684     W.printString("Name", Name);
1685     uint32_t ILTAddr;
1686     if (Error E = I.getImportLookupTableRVA(ILTAddr))
1687       reportError(std::move(E), Obj->getFileName());
1688     W.printHex("ImportLookupTableRVA", ILTAddr);
1689     uint32_t IATAddr;
1690     if (Error E = I.getImportAddressTableRVA(IATAddr))
1691       reportError(std::move(E), Obj->getFileName());
1692     W.printHex("ImportAddressTableRVA", IATAddr);
1693     // The import lookup table can be missing with certain older linkers, so
1694     // fall back to the import address table in that case.
1695     if (ILTAddr)
1696       printImportedSymbols(I.lookup_table_symbols());
1697     else
1698       printImportedSymbols(I.imported_symbols());
1699   }
1700 
1701   // Delay imports
1702   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1703     DictScope Import(W, "DelayImport");
1704     StringRef Name;
1705     if (Error E = I.getName(Name))
1706       reportError(std::move(E), Obj->getFileName());
1707     W.printString("Name", Name);
1708     const delay_import_directory_table_entry *Table;
1709     if (Error E = I.getDelayImportTable(Table))
1710       reportError(std::move(E), Obj->getFileName());
1711     W.printHex("Attributes", Table->Attributes);
1712     W.printHex("ModuleHandle", Table->ModuleHandle);
1713     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1714     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1715     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1716     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1717     printDelayImportedSymbols(I, I.imported_symbols());
1718   }
1719 }
1720 
1721 void COFFDumper::printCOFFExports() {
1722   for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
1723     DictScope Export(W, "Export");
1724 
1725     StringRef Name;
1726     uint32_t Ordinal, RVA;
1727 
1728     if (Error E = Exp.getSymbolName(Name))
1729       reportError(std::move(E), Obj->getFileName());
1730     if (Error E = Exp.getOrdinal(Ordinal))
1731       reportError(std::move(E), Obj->getFileName());
1732     if (Error E = Exp.getExportRVA(RVA))
1733       reportError(std::move(E), Obj->getFileName());
1734 
1735     W.printNumber("Ordinal", Ordinal);
1736     W.printString("Name", Name);
1737     W.printHex("RVA", RVA);
1738   }
1739 }
1740 
1741 void COFFDumper::printCOFFDirectives() {
1742   for (const SectionRef &Section : Obj->sections()) {
1743     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1744     if (Name != ".drectve")
1745       continue;
1746 
1747     StringRef Contents =
1748         unwrapOrError(Obj->getFileName(), Section.getContents());
1749     W.printString("Directive(s)", Contents);
1750   }
1751 }
1752 
1753 static std::string getBaseRelocTypeName(uint8_t Type) {
1754   switch (Type) {
1755   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1756   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1757   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1758   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1759   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1760   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1761   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1762   default: return "unknown (" + llvm::utostr(Type) + ")";
1763   }
1764 }
1765 
1766 void COFFDumper::printCOFFBaseReloc() {
1767   ListScope D(W, "BaseReloc");
1768   for (const BaseRelocRef &I : Obj->base_relocs()) {
1769     uint8_t Type;
1770     uint32_t RVA;
1771     if (Error E = I.getRVA(RVA))
1772       reportError(std::move(E), Obj->getFileName());
1773     if (Error E = I.getType(Type))
1774       reportError(std::move(E), Obj->getFileName());
1775     DictScope Import(W, "Entry");
1776     W.printString("Type", getBaseRelocTypeName(Type));
1777     W.printHex("Address", RVA);
1778   }
1779 }
1780 
1781 void COFFDumper::printCOFFResources() {
1782   ListScope ResourcesD(W, "Resources");
1783   for (const SectionRef &S : Obj->sections()) {
1784     StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
1785     if (!Name.startswith(".rsrc"))
1786       continue;
1787 
1788     StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1789 
1790     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1791       ResourceSectionRef RSF;
1792       Error E = RSF.load(Obj, S);
1793       if (E)
1794         reportError(std::move(E), Obj->getFileName());
1795       auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1796       W.printNumber("Total Number of Resources",
1797                     countTotalTableEntries(RSF, BaseTable, "Type"));
1798       W.printHex("Base Table Address",
1799                  Obj->getCOFFSection(S)->PointerToRawData);
1800       W.startLine() << "\n";
1801       printResourceDirectoryTable(RSF, BaseTable, "Type");
1802     }
1803     if (opts::SectionData)
1804       W.printBinaryBlock(Name.str() + " Data", Ref);
1805   }
1806 }
1807 
1808 uint32_t
1809 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1810                                    const coff_resource_dir_table &Table,
1811                                    StringRef Level) {
1812   uint32_t TotalEntries = 0;
1813   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1814        i++) {
1815     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1816     if (Entry.Offset.isSubDir()) {
1817       StringRef NextLevel;
1818       if (Level == "Name")
1819         NextLevel = "Language";
1820       else
1821         NextLevel = "Name";
1822       auto &NextTable =
1823           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1824       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1825     } else {
1826       TotalEntries += 1;
1827     }
1828   }
1829   return TotalEntries;
1830 }
1831 
1832 void COFFDumper::printResourceDirectoryTable(
1833     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1834     StringRef Level) {
1835 
1836   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1837   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1838 
1839   // Iterate through level in resource directory tree.
1840   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1841        i++) {
1842     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1843     StringRef Name;
1844     SmallString<20> IDStr;
1845     raw_svector_ostream OS(IDStr);
1846     if (i < Table.NumberOfNameEntries) {
1847       ArrayRef<UTF16> RawEntryNameString =
1848           unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
1849       std::vector<UTF16> EndianCorrectedNameString;
1850       if (llvm::sys::IsBigEndianHost) {
1851         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1852         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1853                   EndianCorrectedNameString.begin() + 1);
1854         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1855         RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1856       }
1857       std::string EntryNameString;
1858       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1859         reportError(errorCodeToError(object_error::parse_failed),
1860                     Obj->getFileName());
1861       OS << ": ";
1862       OS << EntryNameString;
1863     } else {
1864       if (Level == "Type") {
1865         OS << ": ";
1866         printResourceTypeName(Entry.Identifier.ID, OS);
1867       } else {
1868         OS << ": (ID " << Entry.Identifier.ID << ")";
1869       }
1870     }
1871     Name = StringRef(IDStr);
1872     ListScope ResourceType(W, Level.str() + Name.str());
1873     if (Entry.Offset.isSubDir()) {
1874       W.printHex("Table Offset", Entry.Offset.value());
1875       StringRef NextLevel;
1876       if (Level == "Name")
1877         NextLevel = "Language";
1878       else
1879         NextLevel = "Name";
1880       auto &NextTable =
1881           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1882       printResourceDirectoryTable(RSF, NextTable, NextLevel);
1883     } else {
1884       W.printHex("Entry Offset", Entry.Offset.value());
1885       char FormattedTime[20] = {};
1886       time_t TDS = time_t(Table.TimeDateStamp);
1887       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1888       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1889       W.printNumber("Major Version", Table.MajorVersion);
1890       W.printNumber("Minor Version", Table.MinorVersion);
1891       W.printNumber("Characteristics", Table.Characteristics);
1892       ListScope DataScope(W, "Data");
1893       auto &DataEntry =
1894           unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
1895       W.printHex("DataRVA", DataEntry.DataRVA);
1896       W.printNumber("DataSize", DataEntry.DataSize);
1897       W.printNumber("Codepage", DataEntry.Codepage);
1898       W.printNumber("Reserved", DataEntry.Reserved);
1899       StringRef Contents =
1900           unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
1901       W.printBinaryBlock("Data", Contents);
1902     }
1903   }
1904 }
1905 
1906 void COFFDumper::printStackMap() const {
1907   object::SectionRef StackMapSection;
1908   for (auto Sec : Obj->sections()) {
1909     StringRef Name;
1910     if (Expected<StringRef> NameOrErr = Sec.getName())
1911       Name = *NameOrErr;
1912     else
1913       consumeError(NameOrErr.takeError());
1914 
1915     if (Name == ".llvm_stackmaps") {
1916       StackMapSection = Sec;
1917       break;
1918     }
1919   }
1920 
1921   if (StackMapSection == object::SectionRef())
1922     return;
1923 
1924   StringRef StackMapContents =
1925       unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
1926   ArrayRef<uint8_t> StackMapContentsArray =
1927       arrayRefFromStringRef(StackMapContents);
1928 
1929   if (Obj->isLittleEndian())
1930     prettyPrintStackMap(
1931         W, StackMapParser<support::little>(StackMapContentsArray));
1932   else
1933     prettyPrintStackMap(
1934         W, StackMapParser<support::big>(StackMapContentsArray));
1935 }
1936 
1937 void COFFDumper::printAddrsig() {
1938   object::SectionRef AddrsigSection;
1939   for (auto Sec : Obj->sections()) {
1940     StringRef Name;
1941     if (Expected<StringRef> NameOrErr = Sec.getName())
1942       Name = *NameOrErr;
1943     else
1944       consumeError(NameOrErr.takeError());
1945 
1946     if (Name == ".llvm_addrsig") {
1947       AddrsigSection = Sec;
1948       break;
1949     }
1950   }
1951 
1952   if (AddrsigSection == object::SectionRef())
1953     return;
1954 
1955   StringRef AddrsigContents =
1956       unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
1957   ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
1958                                          AddrsigContents.size());
1959 
1960   ListScope L(W, "Addrsig");
1961   const uint8_t *Cur = AddrsigContents.bytes_begin();
1962   const uint8_t *End = AddrsigContents.bytes_end();
1963   while (Cur != End) {
1964     unsigned Size;
1965     const char *Err;
1966     uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
1967     if (Err)
1968       reportError(createError(Err), Obj->getFileName());
1969 
1970     Expected<COFFSymbolRef> Sym = Obj->getSymbol(SymIndex);
1971     if (!Sym)
1972       reportError(Sym.takeError(), Obj->getFileName());
1973 
1974     Expected<StringRef> SymName = Obj->getSymbolName(*Sym);
1975     if (!SymName)
1976       reportError(SymName.takeError(), Obj->getFileName());
1977 
1978     W.printNumber("Sym", *SymName, SymIndex);
1979     Cur += Size;
1980   }
1981 }
1982 
1983 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
1984                                    ArrayRef<ArrayRef<uint8_t>> IpiRecords,
1985                                    ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
1986   TypeTableCollection TpiTypes(TpiRecords);
1987   {
1988     ListScope S(Writer, "MergedTypeStream");
1989     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1990     if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
1991       reportError(std::move(Err), "<?>");
1992     Writer.flush();
1993   }
1994 
1995   // Flatten the id stream and print it next. The ID stream refers to names from
1996   // the type stream.
1997   TypeTableCollection IpiTypes(IpiRecords);
1998   {
1999     ListScope S(Writer, "MergedIDStream");
2000     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2001     TDV.setIpiTypes(IpiTypes);
2002     if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
2003       reportError(std::move(Err), "<?>");
2004     Writer.flush();
2005   }
2006 }
2007