xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-readobj/COFFDumper.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 "ObjDumper.h"
16 #include "StackMapPrinter.h"
17 #include "Win64EHDumper.h"
18 #include "llvm-readobj.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/BinaryFormat/COFF.h"
23 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
24 #include "llvm/DebugInfo/CodeView/CodeView.h"
25 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
30 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
31 #include "llvm/DebugInfo/CodeView/Line.h"
32 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
33 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
34 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
36 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
37 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
38 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
39 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
40 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
41 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
42 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
43 #include "llvm/Object/COFF.h"
44 #include "llvm/Object/ObjectFile.h"
45 #include "llvm/Object/WindowsResource.h"
46 #include "llvm/Support/BinaryStreamReader.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/FormatVariadic.h"
51 #include "llvm/Support/LEB128.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/Win64EH.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <ctime>
56 
57 using namespace llvm;
58 using namespace llvm::object;
59 using namespace llvm::codeview;
60 using namespace llvm::support;
61 using namespace llvm::Win64EH;
62 
63 namespace {
64 
65 struct LoadConfigTables {
66   uint64_t SEHTableVA = 0;
67   uint64_t SEHTableCount = 0;
68   uint32_t GuardFlags = 0;
69   uint64_t GuardFidTableVA = 0;
70   uint64_t GuardFidTableCount = 0;
71   uint64_t GuardIatTableVA = 0;
72   uint64_t GuardIatTableCount = 0;
73   uint64_t GuardLJmpTableVA = 0;
74   uint64_t GuardLJmpTableCount = 0;
75   uint64_t GuardEHContTableVA = 0;
76   uint64_t GuardEHContTableCount = 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->getFileName()), Obj(Obj), Writer(Writer),
84         Types(100) {}
85 
86   void printFileHeaders() override;
87   void printSectionHeaders() override;
88   void printRelocations() override;
89   void printUnwindInfo() override;
90 
91   void printNeededLibraries() override;
92 
93   void printCOFFImports() override;
94   void printCOFFExports() override;
95   void printCOFFDirectives() override;
96   void printCOFFBaseReloc() override;
97   void printCOFFDebugDirectory() override;
98   void printCOFFTLSDirectory() override;
99   void printCOFFResources() override;
100   void printCOFFLoadConfig() override;
101   void printCodeViewDebugInfo() override;
102   void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
103                           llvm::codeview::MergingTypeTableBuilder &CVTypes,
104                           llvm::codeview::GlobalTypeTableBuilder &GlobalCVIDs,
105                           llvm::codeview::GlobalTypeTableBuilder &GlobalCVTypes,
106                           bool GHash) override;
107   void printStackMap() const override;
108   void printAddrsig() override;
109   void printCGProfile() override;
110 
111 private:
112   StringRef getSymbolName(uint32_t Index);
113   void printSymbols() override;
114   void printDynamicSymbols() override;
115   void printSymbol(const SymbolRef &Sym);
116   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
117                        uint64_t Bias = 0);
118   void printDataDirectory(uint32_t Index, const std::string &FieldName);
119 
120   void printDOSHeader(const dos_header *DH);
121   template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
122   void printBaseOfDataField(const pe32_header *Hdr);
123   void printBaseOfDataField(const pe32plus_header *Hdr);
124   template <typename T>
125   void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
126   template <typename IntTy>
127   void printCOFFTLSDirectory(const coff_tls_directory<IntTy> *TlsTable);
128   typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
129   void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
130                      PrintExtraCB PrintExtra = nullptr);
131 
132   void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
133   void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
134   StringRef getFileNameForFileOffset(uint32_t FileOffset);
135   void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
136   void printTypeIndex(StringRef FieldName, TypeIndex TI) {
137     // Forward to CVTypeDumper for simplicity.
138     codeview::printTypeIndex(Writer, FieldName, TI, Types);
139   }
140 
141   void printCodeViewSymbolsSubsection(StringRef Subsection,
142                                       const SectionRef &Section,
143                                       StringRef SectionContents);
144 
145   void printCodeViewFileChecksums(StringRef Subsection);
146 
147   void printCodeViewInlineeLines(StringRef Subsection);
148 
149   void printRelocatedField(StringRef Label, const coff_section *Sec,
150                            uint32_t RelocOffset, uint32_t Offset,
151                            StringRef *RelocSym = nullptr);
152 
153   uint32_t countTotalTableEntries(ResourceSectionRef RSF,
154                                   const coff_resource_dir_table &Table,
155                                   StringRef Level);
156 
157   void printResourceDirectoryTable(ResourceSectionRef RSF,
158                                    const coff_resource_dir_table &Table,
159                                    StringRef Level);
160 
161   void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
162                                   StringRef SectionContents, StringRef Block);
163 
164   /// Given a .debug$S section, find the string table and file checksum table.
165   void initializeFileAndStringTables(BinaryStreamReader &Reader);
166 
167   void cacheRelocations();
168 
169   std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
170                                 SymbolRef &Sym);
171   std::error_code resolveSymbolName(const coff_section *Section,
172                                     uint64_t Offset, StringRef &Name);
173   std::error_code resolveSymbolName(const coff_section *Section,
174                                     StringRef SectionContents,
175                                     const void *RelocPtr, StringRef &Name);
176   void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
177   void printDelayImportedSymbols(
178       const DelayImportDirectoryEntryRef &I,
179       iterator_range<imported_symbol_iterator> Range);
180 
181   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
182 
183   const llvm::object::COFFObjectFile *Obj;
184   bool RelocCached = false;
185   RelocMapTy RelocMap;
186 
187   DebugChecksumsSubsectionRef CVFileChecksumTable;
188 
189   DebugStringTableSubsectionRef CVStringTable;
190 
191   /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
192   /// first, but if we don't see one, just assume an X64 CPU type. It is common.
193   CPUType CompilationCPUType = CPUType::X64;
194 
195   ScopedPrinter &Writer;
196   LazyRandomTypeCollection Types;
197 };
198 
199 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
200 public:
201   COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
202                          const COFFObjectFile *Obj, StringRef SectionContents)
203       : CD(CD), SR(SR), SectionContents(SectionContents) {
204     Sec = Obj->getCOFFSection(SR);
205   }
206 
207   uint32_t getRecordOffset(BinaryStreamReader Reader) override {
208     ArrayRef<uint8_t> Data;
209     if (auto EC = Reader.readLongestContiguousChunk(Data)) {
210       llvm::consumeError(std::move(EC));
211       return 0;
212     }
213     return Data.data() - SectionContents.bytes_begin();
214   }
215 
216   void printRelocatedField(StringRef Label, uint32_t RelocOffset,
217                            uint32_t Offset, StringRef *RelocSym) override {
218     CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
219   }
220 
221   void printBinaryBlockWithRelocs(StringRef Label,
222                                   ArrayRef<uint8_t> Block) override {
223     StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
224                      Block.size());
225     if (opts::CodeViewSubsectionBytes)
226       CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
227   }
228 
229   StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
230     return CD.getFileNameForFileOffset(FileOffset);
231   }
232 
233   DebugStringTableSubsectionRef getStringTable() override {
234     return CD.CVStringTable;
235   }
236 
237 private:
238   COFFDumper &CD;
239   const SectionRef &SR;
240   const coff_section *Sec;
241   StringRef SectionContents;
242 };
243 
244 } // end namespace
245 
246 namespace llvm {
247 
248 std::unique_ptr<ObjDumper> createCOFFDumper(const object::COFFObjectFile &Obj,
249                                             ScopedPrinter &Writer) {
250   return std::make_unique<COFFDumper>(&Obj, Writer);
251 }
252 
253 } // namespace llvm
254 
255 // Given a section and an offset into this section the function returns the
256 // symbol used for the relocation at the offset.
257 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
258                                           uint64_t Offset, SymbolRef &Sym) {
259   cacheRelocations();
260   const auto &Relocations = RelocMap[Section];
261   auto SymI = Obj->symbol_end();
262   for (const auto &Relocation : Relocations) {
263     uint64_t RelocationOffset = Relocation.getOffset();
264 
265     if (RelocationOffset == Offset) {
266       SymI = Relocation.getSymbol();
267       break;
268     }
269   }
270   if (SymI == Obj->symbol_end())
271     return inconvertibleErrorCode();
272   Sym = *SymI;
273   return std::error_code();
274 }
275 
276 // Given a section and an offset into this section the function returns the name
277 // of the symbol used for the relocation at the offset.
278 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
279                                               uint64_t Offset,
280                                               StringRef &Name) {
281   SymbolRef Symbol;
282   if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
283     return EC;
284   Expected<StringRef> NameOrErr = Symbol.getName();
285   if (!NameOrErr)
286     return errorToErrorCode(NameOrErr.takeError());
287   Name = *NameOrErr;
288   return std::error_code();
289 }
290 
291 // Helper for when you have a pointer to real data and you want to know about
292 // relocations against it.
293 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
294                                               StringRef SectionContents,
295                                               const void *RelocPtr,
296                                               StringRef &Name) {
297   assert(SectionContents.data() < RelocPtr &&
298          RelocPtr < SectionContents.data() + SectionContents.size() &&
299          "pointer to relocated object is not in section");
300   uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
301                               SectionContents.data());
302   return resolveSymbolName(Section, Offset, Name);
303 }
304 
305 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
306                                      uint32_t RelocOffset, uint32_t Offset,
307                                      StringRef *RelocSym) {
308   StringRef SymStorage;
309   StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
310   if (!resolveSymbolName(Sec, RelocOffset, Symbol))
311     W.printSymbolOffset(Label, Symbol, Offset);
312   else
313     W.printHex(Label, RelocOffset);
314 }
315 
316 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
317                                             const SectionRef &Sec,
318                                             StringRef SectionContents,
319                                             StringRef Block) {
320   W.printBinaryBlock(Label, Block);
321 
322   assert(SectionContents.begin() < Block.begin() &&
323          SectionContents.end() >= Block.end() &&
324          "Block is not contained in SectionContents");
325   uint64_t OffsetStart = Block.data() - SectionContents.data();
326   uint64_t OffsetEnd = OffsetStart + Block.size();
327 
328   W.flush();
329   cacheRelocations();
330   ListScope D(W, "BlockRelocations");
331   const coff_section *Section = Obj->getCOFFSection(Sec);
332   const auto &Relocations = RelocMap[Section];
333   for (const auto &Relocation : Relocations) {
334     uint64_t RelocationOffset = Relocation.getOffset();
335     if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
336       printRelocation(Sec, Relocation, OffsetStart);
337   }
338 }
339 
340 const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
341   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
342   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
343   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
344   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
345   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64    ),
346   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64EC  ),
347   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64X   ),
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 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 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 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 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 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 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 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 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   { "AntiDependency"  , COFF::IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY  },
552 };
553 
554 const EnumEntry<uint32_t> SubSectionTypes[] = {
555     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
556     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
557     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
558     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
559     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
560     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
561     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
562     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
563     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
564     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
565     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
566     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
567     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
568 };
569 
570 const EnumEntry<uint32_t> FrameDataFlags[] = {
571     LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
572     LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
573     LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
574 };
575 
576 const EnumEntry<uint8_t> FileChecksumKindNames[] = {
577   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
578   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
579   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
580   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
581 };
582 
583 const EnumEntry<uint32_t> PELoadConfigGuardFlags[] = {
584     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_INSTRUMENTED),
585     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CFW_INSTRUMENTED),
586     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_FUNCTION_TABLE_PRESENT),
587     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, SECURITY_COOKIE_UNUSED),
588     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, PROTECT_DELAYLOAD_IAT),
589     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
590                                 DELAYLOAD_IAT_IN_ITS_OWN_SECTION),
591     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
592                                 CF_EXPORT_SUPPRESSION_INFO_PRESENT),
593     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_ENABLE_EXPORT_SUPPRESSION),
594     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_LONGJUMP_TABLE_PRESENT),
595     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
596                                 EH_CONTINUATION_TABLE_PRESENT),
597     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
598                                 CF_FUNCTION_TABLE_SIZE_5BYTES),
599     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
600                                 CF_FUNCTION_TABLE_SIZE_6BYTES),
601     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
602                                 CF_FUNCTION_TABLE_SIZE_7BYTES),
603     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
604                                 CF_FUNCTION_TABLE_SIZE_8BYTES),
605     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
606                                 CF_FUNCTION_TABLE_SIZE_9BYTES),
607     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
608                                 CF_FUNCTION_TABLE_SIZE_10BYTES),
609     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
610                                 CF_FUNCTION_TABLE_SIZE_11BYTES),
611     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
612                                 CF_FUNCTION_TABLE_SIZE_12BYTES),
613     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
614                                 CF_FUNCTION_TABLE_SIZE_13BYTES),
615     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
616                                 CF_FUNCTION_TABLE_SIZE_14BYTES),
617     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
618                                 CF_FUNCTION_TABLE_SIZE_15BYTES),
619     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
620                                 CF_FUNCTION_TABLE_SIZE_16BYTES),
621     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
622                                 CF_FUNCTION_TABLE_SIZE_17BYTES),
623     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
624                                 CF_FUNCTION_TABLE_SIZE_18BYTES),
625     LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
626                                 CF_FUNCTION_TABLE_SIZE_19BYTES),
627 };
628 
629 template <typename T>
630 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
631                                         COFFSymbolRef Symbol,
632                                         uint8_t AuxSymbolIdx, const T *&Aux) {
633   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
634   AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
635   Aux = reinterpret_cast<const T*>(AuxData.data());
636   return std::error_code();
637 }
638 
639 void COFFDumper::cacheRelocations() {
640   if (RelocCached)
641     return;
642   RelocCached = true;
643 
644   for (const SectionRef &S : Obj->sections()) {
645     const coff_section *Section = Obj->getCOFFSection(S);
646 
647     append_range(RelocMap[Section], S.relocations());
648 
649     // Sort relocations by address.
650     llvm::sort(RelocMap[Section], [](RelocationRef L, RelocationRef R) {
651       return L.getOffset() < R.getOffset();
652     });
653   }
654 }
655 
656 void COFFDumper::printDataDirectory(uint32_t Index,
657                                     const std::string &FieldName) {
658   const data_directory *Data = Obj->getDataDirectory(Index);
659   if (!Data)
660     return;
661   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
662   W.printHex(FieldName + "Size", Data->Size);
663 }
664 
665 void COFFDumper::printFileHeaders() {
666   time_t TDS = Obj->getTimeDateStamp();
667   char FormattedTime[20] = { };
668   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
669 
670   {
671     DictScope D(W, "ImageFileHeader");
672     W.printEnum("Machine", Obj->getMachine(), ArrayRef(ImageFileMachineType));
673     W.printNumber("SectionCount", Obj->getNumberOfSections());
674     W.printHex   ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
675     W.printHex   ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
676     W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
677     W.printNumber("StringTableSize", Obj->getStringTableSize());
678     W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
679     W.printFlags("Characteristics", Obj->getCharacteristics(),
680                  ArrayRef(ImageFileCharacteristics));
681   }
682 
683   // Print PE header. This header does not exist if this is an object file and
684   // not an executable.
685   if (const pe32_header *PEHeader = Obj->getPE32Header())
686     printPEHeader<pe32_header>(PEHeader);
687 
688   if (const pe32plus_header *PEPlusHeader = Obj->getPE32PlusHeader())
689     printPEHeader<pe32plus_header>(PEPlusHeader);
690 
691   if (const dos_header *DH = Obj->getDOSHeader())
692     printDOSHeader(DH);
693 }
694 
695 void COFFDumper::printDOSHeader(const dos_header *DH) {
696   DictScope D(W, "DOSHeader");
697   W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
698   W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
699   W.printNumber("FileSizeInPages", DH->FileSizeInPages);
700   W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
701   W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
702   W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
703   W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
704   W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
705   W.printNumber("InitialSP", DH->InitialSP);
706   W.printNumber("Checksum", DH->Checksum);
707   W.printNumber("InitialIP", DH->InitialIP);
708   W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
709   W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
710   W.printNumber("OverlayNumber", DH->OverlayNumber);
711   W.printNumber("OEMid", DH->OEMid);
712   W.printNumber("OEMinfo", DH->OEMinfo);
713   W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
714 }
715 
716 template <class PEHeader>
717 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
718   DictScope D(W, "ImageOptionalHeader");
719   W.printHex   ("Magic", Hdr->Magic);
720   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
721   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
722   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
723   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
724   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
725   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
726   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
727   printBaseOfDataField(Hdr);
728   W.printHex   ("ImageBase", Hdr->ImageBase);
729   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
730   W.printNumber("FileAlignment", Hdr->FileAlignment);
731   W.printNumber("MajorOperatingSystemVersion",
732                 Hdr->MajorOperatingSystemVersion);
733   W.printNumber("MinorOperatingSystemVersion",
734                 Hdr->MinorOperatingSystemVersion);
735   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
736   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
737   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
738   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
739   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
740   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
741   W.printHex   ("CheckSum", Hdr->CheckSum);
742   W.printEnum("Subsystem", Hdr->Subsystem, ArrayRef(PEWindowsSubsystem));
743   W.printFlags("Characteristics", Hdr->DLLCharacteristics,
744                ArrayRef(PEDLLCharacteristics));
745   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
746   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
747   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
748   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
749   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
750 
751   if (Hdr->NumberOfRvaAndSize > 0) {
752     DictScope D(W, "DataDirectory");
753     static const char * const directory[] = {
754       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
755       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
756       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
757       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
758     };
759 
760     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
761       if (i < std::size(directory))
762         printDataDirectory(i, directory[i]);
763       else
764         printDataDirectory(i, "Unknown");
765   }
766 }
767 
768 void COFFDumper::printCOFFDebugDirectory() {
769   ListScope LS(W, "DebugDirectory");
770   for (const debug_directory &D : Obj->debug_directories()) {
771     char FormattedTime[20] = {};
772     time_t TDS = D.TimeDateStamp;
773     strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
774     DictScope S(W, "DebugEntry");
775     W.printHex("Characteristics", D.Characteristics);
776     W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
777     W.printHex("MajorVersion", D.MajorVersion);
778     W.printHex("MinorVersion", D.MinorVersion);
779     W.printEnum("Type", D.Type, ArrayRef(ImageDebugType));
780     W.printHex("SizeOfData", D.SizeOfData);
781     W.printHex("AddressOfRawData", D.AddressOfRawData);
782     W.printHex("PointerToRawData", D.PointerToRawData);
783     // Ideally, if D.AddressOfRawData == 0, we should try to load the payload
784     // using D.PointerToRawData instead.
785     if (D.AddressOfRawData == 0)
786       continue;
787     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
788       const codeview::DebugInfo *DebugInfo;
789       StringRef PDBFileName;
790       if (Error E = Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName))
791         reportError(std::move(E), Obj->getFileName());
792 
793       DictScope PDBScope(W, "PDBInfo");
794       W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
795       if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
796         W.printBinary("PDBGUID", ArrayRef(DebugInfo->PDB70.Signature));
797         W.printNumber("PDBAge", DebugInfo->PDB70.Age);
798         W.printString("PDBFileName", PDBFileName);
799       }
800     } else if (D.SizeOfData != 0) {
801       // FIXME: Data visualization for IMAGE_DEBUG_TYPE_VC_FEATURE and
802       // IMAGE_DEBUG_TYPE_POGO?
803       ArrayRef<uint8_t> RawData;
804       if (Error E = Obj->getRvaAndSizeAsBytes(D.AddressOfRawData,
805                                                          D.SizeOfData, RawData))
806         reportError(std::move(E), Obj->getFileName());
807       if (D.Type == COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) {
808         // FIXME right now the only possible value would fit in 8 bits,
809         // but that might change in the future
810         uint16_t Characteristics = RawData[0];
811         W.printFlags("ExtendedCharacteristics", Characteristics,
812                      ArrayRef(PEExtendedDLLCharacteristics));
813       }
814       W.printBinaryBlock("RawData", RawData);
815     }
816   }
817 }
818 
819 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
820                                uint64_t EntrySize, PrintExtraCB PrintExtra) {
821   uintptr_t TableStart, TableEnd;
822   if (Error E = Obj->getVaPtr(TableVA, TableStart))
823     reportError(std::move(E), Obj->getFileName());
824   if (Error E =
825           Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd))
826     reportError(std::move(E), Obj->getFileName());
827   TableEnd++;
828   for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
829     uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
830     raw_ostream &OS = W.startLine();
831     OS << W.hex(Obj->getImageBase() + RVA);
832     if (PrintExtra)
833       PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
834     OS << '\n';
835   }
836 }
837 
838 void COFFDumper::printCOFFLoadConfig() {
839   LoadConfigTables Tables;
840   if (Obj->is64())
841     printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
842   else
843     printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
844 
845   if (auto CHPE = Obj->getCHPEMetadata()) {
846     ListScope LS(W, "CHPEMetadata");
847     W.printHex("Version", CHPE->Version);
848 
849     if (CHPE->CodeMapCount) {
850       ListScope CMLS(W, "CodeMap");
851 
852       uintptr_t CodeMapInt;
853       if (Error E = Obj->getRvaPtr(CHPE->CodeMap, CodeMapInt))
854         reportError(std::move(E), Obj->getFileName());
855       auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
856       for (uint32_t i = 0; i < CHPE->CodeMapCount; i++) {
857         uint32_t Start = CodeMap[i].StartOffset & ~3;
858         W.startLine() << W.hex(Start) << " - "
859                       << W.hex(Start + CodeMap[i].Length) << "  ";
860         switch (CodeMap[i].StartOffset & 3) {
861         case CHPE_RANGE_ARM64:
862           W.getOStream() << "ARM64\n";
863           break;
864         case CHPE_RANGE_ARM64EC:
865           W.getOStream() << "ARM64EC\n";
866           break;
867         case CHPE_RANGE_AMD64:
868           W.getOStream() << "X64\n";
869           break;
870         default:
871           W.getOStream() << W.hex(CodeMap[i].StartOffset & 3) << "\n";
872           break;
873         }
874       }
875     } else {
876       W.printNumber("CodeMap", CHPE->CodeMap);
877     }
878 
879     if (CHPE->CodeRangesToEntryPointsCount) {
880       ListScope CRLS(W, "CodeRangesToEntryPoints");
881 
882       uintptr_t CodeRangesInt;
883       if (Error E =
884               Obj->getRvaPtr(CHPE->CodeRangesToEntryPoints, CodeRangesInt))
885         reportError(std::move(E), Obj->getFileName());
886       auto CodeRanges =
887           reinterpret_cast<const chpe_code_range_entry *>(CodeRangesInt);
888       for (uint32_t i = 0; i < CHPE->CodeRangesToEntryPointsCount; i++) {
889         W.startLine() << W.hex(CodeRanges[i].StartRva) << " - "
890                       << W.hex(CodeRanges[i].EndRva) << " -> "
891                       << W.hex(CodeRanges[i].EntryPoint) << "\n";
892       }
893     } else {
894       W.printNumber("CodeRangesToEntryPoints", CHPE->CodeRangesToEntryPoints);
895     }
896 
897     if (CHPE->RedirectionMetadataCount) {
898       ListScope RMLS(W, "RedirectionMetadata");
899 
900       uintptr_t RedirMetadataInt;
901       if (Error E = Obj->getRvaPtr(CHPE->RedirectionMetadata, RedirMetadataInt))
902         reportError(std::move(E), Obj->getFileName());
903       auto RedirMetadata =
904           reinterpret_cast<const chpe_redirection_entry *>(RedirMetadataInt);
905       for (uint32_t i = 0; i < CHPE->RedirectionMetadataCount; i++) {
906         W.startLine() << W.hex(RedirMetadata[i].Source) << " -> "
907                       << W.hex(RedirMetadata[i].Destination) << "\n";
908       }
909     } else {
910       W.printNumber("RedirectionMetadata", CHPE->RedirectionMetadata);
911     }
912 
913     W.printHex("__os_arm64x_dispatch_call_no_redirect",
914                CHPE->__os_arm64x_dispatch_call_no_redirect);
915     W.printHex("__os_arm64x_dispatch_ret", CHPE->__os_arm64x_dispatch_ret);
916     W.printHex("__os_arm64x_dispatch_call", CHPE->__os_arm64x_dispatch_call);
917     W.printHex("__os_arm64x_dispatch_icall", CHPE->__os_arm64x_dispatch_icall);
918     W.printHex("__os_arm64x_dispatch_icall_cfg",
919                CHPE->__os_arm64x_dispatch_icall_cfg);
920     W.printHex("AlternateEntryPoint", CHPE->AlternateEntryPoint);
921     W.printHex("AuxiliaryIAT", CHPE->AuxiliaryIAT);
922     W.printHex("GetX64InformationFunctionPointer",
923                CHPE->GetX64InformationFunctionPointer);
924     W.printHex("SetX64InformationFunctionPointer",
925                CHPE->SetX64InformationFunctionPointer);
926     W.printHex("ExtraRFETable", CHPE->ExtraRFETable);
927     W.printHex("ExtraRFETableSize", CHPE->ExtraRFETableSize);
928     W.printHex("__os_arm64x_dispatch_fptr", CHPE->__os_arm64x_dispatch_fptr);
929     W.printHex("AuxiliaryIATCopy", CHPE->AuxiliaryIATCopy);
930   }
931 
932   if (Tables.SEHTableVA) {
933     ListScope LS(W, "SEHTable");
934     printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
935   }
936 
937   auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
938     uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
939     if (Flags)
940       OS << " flags " << utohexstr(Flags);
941   };
942 
943   // The stride gives the number of extra bytes in addition to the 4-byte
944   // RVA of each entry in the table. As of writing only a 1-byte extra flag
945   // has been defined.
946   uint32_t Stride = Tables.GuardFlags >> 28;
947   PrintExtraCB PrintExtra = Stride == 1 ? +PrintGuardFlags : nullptr;
948 
949   if (Tables.GuardFidTableVA) {
950     ListScope LS(W, "GuardFidTable");
951     printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount,
952                   4 + Stride, PrintExtra);
953   }
954 
955   if (Tables.GuardIatTableVA) {
956     ListScope LS(W, "GuardIatTable");
957     printRVATable(Tables.GuardIatTableVA, Tables.GuardIatTableCount,
958                   4 + Stride, PrintExtra);
959   }
960 
961   if (Tables.GuardLJmpTableVA) {
962     ListScope LS(W, "GuardLJmpTable");
963     printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount,
964                   4 + Stride, PrintExtra);
965   }
966 
967   if (Tables.GuardEHContTableVA) {
968     ListScope LS(W, "GuardEHContTable");
969     printRVATable(Tables.GuardEHContTableVA, Tables.GuardEHContTableCount,
970                   4 + Stride, PrintExtra);
971   }
972 }
973 
974 template <typename T>
975 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
976   if (!Conf)
977     return;
978 
979   ListScope LS(W, "LoadConfig");
980   char FormattedTime[20] = {};
981   time_t TDS = Conf->TimeDateStamp;
982   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
983   W.printHex("Size", Conf->Size);
984 
985   // Print everything before SecurityCookie. The vast majority of images today
986   // have all these fields.
987   if (Conf->Size < offsetof(T, SEHandlerTable))
988     return;
989   W.printHex("TimeDateStamp", FormattedTime, TDS);
990   W.printHex("MajorVersion", Conf->MajorVersion);
991   W.printHex("MinorVersion", Conf->MinorVersion);
992   W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
993   W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
994   W.printHex("CriticalSectionDefaultTimeout",
995              Conf->CriticalSectionDefaultTimeout);
996   W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
997   W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
998   W.printHex("LockPrefixTable", Conf->LockPrefixTable);
999   W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
1000   W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
1001   W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
1002   W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
1003   W.printHex("CSDVersion", Conf->CSDVersion);
1004   W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
1005   W.printHex("EditList", Conf->EditList);
1006   W.printHex("SecurityCookie", Conf->SecurityCookie);
1007 
1008   // Print the safe SEH table if present.
1009   if (Conf->Size < offsetof(T, GuardCFCheckFunction))
1010     return;
1011   W.printHex("SEHandlerTable", Conf->SEHandlerTable);
1012   W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
1013 
1014   Tables.SEHTableVA = Conf->SEHandlerTable;
1015   Tables.SEHTableCount = Conf->SEHandlerCount;
1016 
1017   // Print everything before CodeIntegrity. (2015)
1018   if (Conf->Size < offsetof(T, CodeIntegrity))
1019     return;
1020   W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
1021   W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
1022   W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
1023   W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
1024   W.printFlags("GuardFlags", Conf->GuardFlags, ArrayRef(PELoadConfigGuardFlags),
1025                (uint32_t)COFF::GuardFlags::CF_FUNCTION_TABLE_SIZE_MASK);
1026 
1027   Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
1028   Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
1029   Tables.GuardFlags = Conf->GuardFlags;
1030 
1031   // Print everything before Reserved3. (2017)
1032   if (Conf->Size < offsetof(T, Reserved3))
1033     return;
1034   W.printHex("GuardAddressTakenIatEntryTable",
1035              Conf->GuardAddressTakenIatEntryTable);
1036   W.printNumber("GuardAddressTakenIatEntryCount",
1037                 Conf->GuardAddressTakenIatEntryCount);
1038   W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
1039   W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
1040   W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
1041   W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
1042   W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
1043   W.printHex("GuardRFFailureRoutineFunctionPointer",
1044              Conf->GuardRFFailureRoutineFunctionPointer);
1045   W.printHex("DynamicValueRelocTableOffset",
1046              Conf->DynamicValueRelocTableOffset);
1047   W.printNumber("DynamicValueRelocTableSection",
1048                 Conf->DynamicValueRelocTableSection);
1049   W.printHex("GuardRFVerifyStackPointerFunctionPointer",
1050              Conf->GuardRFVerifyStackPointerFunctionPointer);
1051   W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
1052 
1053   Tables.GuardIatTableVA = Conf->GuardAddressTakenIatEntryTable;
1054   Tables.GuardIatTableCount = Conf->GuardAddressTakenIatEntryCount;
1055 
1056   Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
1057   Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
1058 
1059   // Print the rest. (2019)
1060   if (Conf->Size < sizeof(T))
1061     return;
1062   W.printHex("EnclaveConfigurationPointer", Conf->EnclaveConfigurationPointer);
1063   W.printHex("VolatileMetadataPointer", Conf->VolatileMetadataPointer);
1064   W.printHex("GuardEHContinuationTable", Conf->GuardEHContinuationTable);
1065   W.printNumber("GuardEHContinuationCount", Conf->GuardEHContinuationCount);
1066 
1067   Tables.GuardEHContTableVA = Conf->GuardEHContinuationTable;
1068   Tables.GuardEHContTableCount = Conf->GuardEHContinuationCount;
1069 }
1070 
1071 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
1072   W.printHex("BaseOfData", Hdr->BaseOfData);
1073 }
1074 
1075 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
1076 
1077 void COFFDumper::printCodeViewDebugInfo() {
1078   // Print types first to build CVUDTNames, then print symbols.
1079   for (const SectionRef &S : Obj->sections()) {
1080     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1081     // .debug$T is a standard CodeView type section, while .debug$P is the same
1082     // format but used for MSVC precompiled header object files.
1083     if (SectionName == ".debug$T" || SectionName == ".debug$P")
1084       printCodeViewTypeSection(SectionName, S);
1085   }
1086   for (const SectionRef &S : Obj->sections()) {
1087     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1088     if (SectionName == ".debug$S")
1089       printCodeViewSymbolSection(SectionName, S);
1090   }
1091 }
1092 
1093 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
1094   while (Reader.bytesRemaining() > 0 &&
1095          (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
1096     // The section consists of a number of subsection in the following format:
1097     // |SubSectionType|SubSectionSize|Contents...|
1098     uint32_t SubType, SubSectionSize;
1099 
1100     if (Error E = Reader.readInteger(SubType))
1101       reportError(std::move(E), Obj->getFileName());
1102     if (Error E = Reader.readInteger(SubSectionSize))
1103       reportError(std::move(E), Obj->getFileName());
1104 
1105     StringRef Contents;
1106     if (Error E = Reader.readFixedString(Contents, SubSectionSize))
1107       reportError(std::move(E), Obj->getFileName());
1108 
1109     BinaryStreamRef ST(Contents, support::little);
1110     switch (DebugSubsectionKind(SubType)) {
1111     case DebugSubsectionKind::FileChecksums:
1112       if (Error E = CVFileChecksumTable.initialize(ST))
1113         reportError(std::move(E), Obj->getFileName());
1114       break;
1115     case DebugSubsectionKind::StringTable:
1116       if (Error E = CVStringTable.initialize(ST))
1117         reportError(std::move(E), Obj->getFileName());
1118       break;
1119     default:
1120       break;
1121     }
1122 
1123     uint32_t PaddedSize = alignTo(SubSectionSize, 4);
1124     if (Error E = Reader.skip(PaddedSize - SubSectionSize))
1125       reportError(std::move(E), Obj->getFileName());
1126   }
1127 }
1128 
1129 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
1130                                             const SectionRef &Section) {
1131   StringRef SectionContents =
1132       unwrapOrError(Obj->getFileName(), Section.getContents());
1133   StringRef Data = SectionContents;
1134 
1135   SmallVector<StringRef, 10> FunctionNames;
1136   StringMap<StringRef> FunctionLineTables;
1137 
1138   ListScope D(W, "CodeViewDebugInfo");
1139   // Print the section to allow correlation with printSectionHeaders.
1140   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1141 
1142   uint32_t Magic;
1143   if (Error E = consume(Data, Magic))
1144     reportError(std::move(E), Obj->getFileName());
1145 
1146   W.printHex("Magic", Magic);
1147   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1148     reportError(errorCodeToError(object_error::parse_failed),
1149                 Obj->getFileName());
1150 
1151   BinaryStreamReader FSReader(Data, support::little);
1152   initializeFileAndStringTables(FSReader);
1153 
1154   // TODO: Convert this over to using ModuleSubstreamVisitor.
1155   while (!Data.empty()) {
1156     // The section consists of a number of subsection in the following format:
1157     // |SubSectionType|SubSectionSize|Contents...|
1158     uint32_t SubType, SubSectionSize;
1159     if (Error E = consume(Data, SubType))
1160       reportError(std::move(E), Obj->getFileName());
1161     if (Error E = consume(Data, SubSectionSize))
1162       reportError(std::move(E), Obj->getFileName());
1163 
1164     ListScope S(W, "Subsection");
1165     // Dump the subsection as normal even if the ignore bit is set.
1166     if (SubType & SubsectionIgnoreFlag) {
1167       W.printHex("IgnoredSubsectionKind", SubType);
1168       SubType &= ~SubsectionIgnoreFlag;
1169     }
1170     W.printEnum("SubSectionType", SubType, ArrayRef(SubSectionTypes));
1171     W.printHex("SubSectionSize", SubSectionSize);
1172 
1173     // Get the contents of the subsection.
1174     if (SubSectionSize > Data.size())
1175       return reportError(errorCodeToError(object_error::parse_failed),
1176                          Obj->getFileName());
1177     StringRef Contents = Data.substr(0, SubSectionSize);
1178 
1179     // Add SubSectionSize to the current offset and align that offset to find
1180     // the next subsection.
1181     size_t SectionOffset = Data.data() - SectionContents.data();
1182     size_t NextOffset = SectionOffset + SubSectionSize;
1183     NextOffset = alignTo(NextOffset, 4);
1184     if (NextOffset > SectionContents.size())
1185       return reportError(errorCodeToError(object_error::parse_failed),
1186                          Obj->getFileName());
1187     Data = SectionContents.drop_front(NextOffset);
1188 
1189     // Optionally print the subsection bytes in case our parsing gets confused
1190     // later.
1191     if (opts::CodeViewSubsectionBytes)
1192       printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
1193                                  Contents);
1194 
1195     switch (DebugSubsectionKind(SubType)) {
1196     case DebugSubsectionKind::Symbols:
1197       printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1198       break;
1199 
1200     case DebugSubsectionKind::InlineeLines:
1201       printCodeViewInlineeLines(Contents);
1202       break;
1203 
1204     case DebugSubsectionKind::FileChecksums:
1205       printCodeViewFileChecksums(Contents);
1206       break;
1207 
1208     case DebugSubsectionKind::Lines: {
1209       // Holds a PC to file:line table.  Some data to parse this subsection is
1210       // stored in the other subsections, so just check sanity and store the
1211       // pointers for deferred processing.
1212 
1213       if (SubSectionSize < 12) {
1214         // There should be at least three words to store two function
1215         // relocations and size of the code.
1216         reportError(errorCodeToError(object_error::parse_failed),
1217                     Obj->getFileName());
1218         return;
1219       }
1220 
1221       StringRef LinkageName;
1222       if (std::error_code EC = resolveSymbolName(Obj->getCOFFSection(Section),
1223                                                  SectionOffset, LinkageName))
1224         reportError(errorCodeToError(EC), Obj->getFileName());
1225 
1226       W.printString("LinkageName", LinkageName);
1227       if (FunctionLineTables.count(LinkageName) != 0) {
1228         // Saw debug info for this function already?
1229         reportError(errorCodeToError(object_error::parse_failed),
1230                     Obj->getFileName());
1231         return;
1232       }
1233 
1234       FunctionLineTables[LinkageName] = Contents;
1235       FunctionNames.push_back(LinkageName);
1236       break;
1237     }
1238     case DebugSubsectionKind::FrameData: {
1239       // First four bytes is a relocation against the function.
1240       BinaryStreamReader SR(Contents, llvm::support::little);
1241 
1242       DebugFrameDataSubsectionRef FrameData;
1243       if (Error E = FrameData.initialize(SR))
1244         reportError(std::move(E), Obj->getFileName());
1245 
1246       StringRef LinkageName;
1247       if (std::error_code EC =
1248               resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1249                                 FrameData.getRelocPtr(), LinkageName))
1250         reportError(errorCodeToError(EC), Obj->getFileName());
1251       W.printString("LinkageName", LinkageName);
1252 
1253       // To find the active frame description, search this array for the
1254       // smallest PC range that includes the current PC.
1255       for (const auto &FD : FrameData) {
1256         StringRef FrameFunc = unwrapOrError(
1257             Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
1258 
1259         DictScope S(W, "FrameData");
1260         W.printHex("RvaStart", FD.RvaStart);
1261         W.printHex("CodeSize", FD.CodeSize);
1262         W.printHex("LocalSize", FD.LocalSize);
1263         W.printHex("ParamsSize", FD.ParamsSize);
1264         W.printHex("MaxStackSize", FD.MaxStackSize);
1265         W.printHex("PrologSize", FD.PrologSize);
1266         W.printHex("SavedRegsSize", FD.SavedRegsSize);
1267         W.printFlags("Flags", FD.Flags, ArrayRef(FrameDataFlags));
1268 
1269         // The FrameFunc string is a small RPN program. It can be broken up into
1270         // statements that end in the '=' operator, which assigns the value on
1271         // the top of the stack to the previously pushed variable. Variables can
1272         // be temporary values ($T0) or physical registers ($esp). Print each
1273         // assignment on its own line to make these programs easier to read.
1274         {
1275           ListScope FFS(W, "FrameFunc");
1276           while (!FrameFunc.empty()) {
1277             size_t EqOrEnd = FrameFunc.find('=');
1278             if (EqOrEnd == StringRef::npos)
1279               EqOrEnd = FrameFunc.size();
1280             else
1281               ++EqOrEnd;
1282             StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1283             W.printString(Stmt);
1284             FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1285           }
1286         }
1287       }
1288       break;
1289     }
1290 
1291     // Do nothing for unrecognized subsections.
1292     default:
1293       break;
1294     }
1295     W.flush();
1296   }
1297 
1298   // Dump the line tables now that we've read all the subsections and know all
1299   // the required information.
1300   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1301     StringRef Name = FunctionNames[I];
1302     ListScope S(W, "FunctionLineTable");
1303     W.printString("LinkageName", Name);
1304 
1305     BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1306 
1307     DebugLinesSubsectionRef LineInfo;
1308     if (Error E = LineInfo.initialize(Reader))
1309       reportError(std::move(E), Obj->getFileName());
1310 
1311     W.printHex("Flags", LineInfo.header()->Flags);
1312     W.printHex("CodeSize", LineInfo.header()->CodeSize);
1313     for (const auto &Entry : LineInfo) {
1314 
1315       ListScope S(W, "FilenameSegment");
1316       printFileNameForOffset("Filename", Entry.NameIndex);
1317       uint32_t ColumnIndex = 0;
1318       for (const auto &Line : Entry.LineNumbers) {
1319         if (Line.Offset >= LineInfo.header()->CodeSize) {
1320           reportError(errorCodeToError(object_error::parse_failed),
1321                       Obj->getFileName());
1322           return;
1323         }
1324 
1325         std::string PC = std::string(formatv("+{0:X}", uint32_t(Line.Offset)));
1326         ListScope PCScope(W, PC);
1327         codeview::LineInfo LI(Line.Flags);
1328 
1329         if (LI.isAlwaysStepInto())
1330           W.printString("StepInto", StringRef("Always"));
1331         else if (LI.isNeverStepInto())
1332           W.printString("StepInto", StringRef("Never"));
1333         else
1334           W.printNumber("LineNumberStart", LI.getStartLine());
1335         W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1336         W.printBoolean("IsStatement", LI.isStatement());
1337         if (LineInfo.hasColumnInfo()) {
1338           W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1339           W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1340           ++ColumnIndex;
1341         }
1342       }
1343     }
1344   }
1345 }
1346 
1347 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1348                                                 const SectionRef &Section,
1349                                                 StringRef SectionContents) {
1350   ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1351                                Subsection.bytes_end());
1352   auto CODD = std::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1353                                                         SectionContents);
1354   CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1355                       CompilationCPUType, opts::CodeViewSubsectionBytes);
1356   CVSymbolArray Symbols;
1357   BinaryStreamReader Reader(BinaryData, llvm::support::little);
1358   if (Error E = Reader.readArray(Symbols, Reader.getLength())) {
1359     W.flush();
1360     reportError(std::move(E), Obj->getFileName());
1361   }
1362 
1363   if (Error E = CVSD.dump(Symbols)) {
1364     W.flush();
1365     reportError(std::move(E), Obj->getFileName());
1366   }
1367   CompilationCPUType = CVSD.getCompilationCPUType();
1368   W.flush();
1369 }
1370 
1371 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1372   BinaryStreamRef Stream(Subsection, llvm::support::little);
1373   DebugChecksumsSubsectionRef Checksums;
1374   if (Error E = Checksums.initialize(Stream))
1375     reportError(std::move(E), Obj->getFileName());
1376 
1377   for (auto &FC : Checksums) {
1378     DictScope S(W, "FileChecksum");
1379 
1380     StringRef Filename = unwrapOrError(
1381         Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
1382     W.printHex("Filename", Filename, FC.FileNameOffset);
1383     W.printHex("ChecksumSize", FC.Checksum.size());
1384     W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1385                 ArrayRef(FileChecksumKindNames));
1386 
1387     W.printBinary("ChecksumBytes", FC.Checksum);
1388   }
1389 }
1390 
1391 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1392   BinaryStreamReader SR(Subsection, llvm::support::little);
1393   DebugInlineeLinesSubsectionRef Lines;
1394   if (Error E = Lines.initialize(SR))
1395     reportError(std::move(E), Obj->getFileName());
1396 
1397   for (auto &Line : Lines) {
1398     DictScope S(W, "InlineeSourceLine");
1399     printTypeIndex("Inlinee", Line.Header->Inlinee);
1400     printFileNameForOffset("FileID", Line.Header->FileID);
1401     W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1402 
1403     if (Lines.hasExtraFiles()) {
1404       W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1405       ListScope ExtraFiles(W, "ExtraFiles");
1406       for (const auto &FID : Line.ExtraFiles) {
1407         printFileNameForOffset("FileID", FID);
1408       }
1409     }
1410   }
1411 }
1412 
1413 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1414   // The file checksum subsection should precede all references to it.
1415   if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1416     reportError(errorCodeToError(object_error::parse_failed),
1417                 Obj->getFileName());
1418 
1419   auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1420 
1421   // Check if the file checksum table offset is valid.
1422   if (Iter == CVFileChecksumTable.end())
1423     reportError(errorCodeToError(object_error::parse_failed),
1424                 Obj->getFileName());
1425 
1426   return unwrapOrError(Obj->getFileName(),
1427                        CVStringTable.getString(Iter->FileNameOffset));
1428 }
1429 
1430 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1431   W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1432 }
1433 
1434 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1435                                     MergingTypeTableBuilder &CVTypes,
1436                                     GlobalTypeTableBuilder &GlobalCVIDs,
1437                                     GlobalTypeTableBuilder &GlobalCVTypes,
1438                                     bool GHash) {
1439   for (const SectionRef &S : Obj->sections()) {
1440     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1441     if (SectionName == ".debug$T") {
1442       StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
1443       uint32_t Magic;
1444       if (Error E = consume(Data, Magic))
1445         reportError(std::move(E), Obj->getFileName());
1446 
1447       if (Magic != 4)
1448         reportError(errorCodeToError(object_error::parse_failed),
1449                     Obj->getFileName());
1450 
1451       CVTypeArray Types;
1452       BinaryStreamReader Reader(Data, llvm::support::little);
1453       if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1454         consumeError(std::move(EC));
1455         W.flush();
1456         reportError(errorCodeToError(object_error::parse_failed),
1457                     Obj->getFileName());
1458       }
1459       SmallVector<TypeIndex, 128> SourceToDest;
1460       std::optional<PCHMergerInfo> PCHInfo;
1461       if (GHash) {
1462         std::vector<GloballyHashedType> Hashes =
1463             GloballyHashedType::hashTypes(Types);
1464         if (Error E =
1465                 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1466                                       Types, Hashes, PCHInfo))
1467           return reportError(std::move(E), Obj->getFileName());
1468       } else {
1469         if (Error E = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1470                                             PCHInfo))
1471           return reportError(std::move(E), Obj->getFileName());
1472       }
1473     }
1474   }
1475 }
1476 
1477 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1478                                           const SectionRef &Section) {
1479   ListScope D(W, "CodeViewTypes");
1480   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1481 
1482   StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
1483   if (opts::CodeViewSubsectionBytes)
1484     W.printBinaryBlock("Data", Data);
1485 
1486   uint32_t Magic;
1487   if (Error E = consume(Data, Magic))
1488     reportError(std::move(E), Obj->getFileName());
1489 
1490   W.printHex("Magic", Magic);
1491   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1492     reportError(errorCodeToError(object_error::parse_failed),
1493                 Obj->getFileName());
1494 
1495   Types.reset(Data, 100);
1496 
1497   TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1498   if (Error E = codeview::visitTypeStream(Types, TDV))
1499     reportError(std::move(E), Obj->getFileName());
1500 
1501   W.flush();
1502 }
1503 
1504 void COFFDumper::printSectionHeaders() {
1505   ListScope SectionsD(W, "Sections");
1506   int SectionNumber = 0;
1507   for (const SectionRef &Sec : Obj->sections()) {
1508     ++SectionNumber;
1509     const coff_section *Section = Obj->getCOFFSection(Sec);
1510 
1511     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
1512 
1513     DictScope D(W, "Section");
1514     W.printNumber("Number", SectionNumber);
1515     W.printBinary("Name", Name, Section->Name);
1516     W.printHex   ("VirtualSize", Section->VirtualSize);
1517     W.printHex   ("VirtualAddress", Section->VirtualAddress);
1518     W.printNumber("RawDataSize", Section->SizeOfRawData);
1519     W.printHex   ("PointerToRawData", Section->PointerToRawData);
1520     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
1521     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
1522     W.printNumber("RelocationCount", Section->NumberOfRelocations);
1523     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1524     W.printFlags("Characteristics", Section->Characteristics,
1525                  ArrayRef(ImageSectionCharacteristics),
1526                  COFF::SectionCharacteristics(0x00F00000));
1527 
1528     if (opts::SectionRelocations) {
1529       ListScope D(W, "Relocations");
1530       for (const RelocationRef &Reloc : Sec.relocations())
1531         printRelocation(Sec, Reloc);
1532     }
1533 
1534     if (opts::SectionSymbols) {
1535       ListScope D(W, "Symbols");
1536       for (const SymbolRef &Symbol : Obj->symbols()) {
1537         if (!Sec.containsSymbol(Symbol))
1538           continue;
1539 
1540         printSymbol(Symbol);
1541       }
1542     }
1543 
1544     if (opts::SectionData &&
1545         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1546       StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
1547       W.printBinaryBlock("SectionData", Data);
1548     }
1549   }
1550 }
1551 
1552 void COFFDumper::printRelocations() {
1553   ListScope D(W, "Relocations");
1554 
1555   int SectionNumber = 0;
1556   for (const SectionRef &Section : Obj->sections()) {
1557     ++SectionNumber;
1558     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1559 
1560     bool PrintedGroup = false;
1561     for (const RelocationRef &Reloc : Section.relocations()) {
1562       if (!PrintedGroup) {
1563         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1564         W.indent();
1565         PrintedGroup = true;
1566       }
1567 
1568       printRelocation(Section, Reloc);
1569     }
1570 
1571     if (PrintedGroup) {
1572       W.unindent();
1573       W.startLine() << "}\n";
1574     }
1575   }
1576 }
1577 
1578 void COFFDumper::printRelocation(const SectionRef &Section,
1579                                  const RelocationRef &Reloc, uint64_t Bias) {
1580   uint64_t Offset = Reloc.getOffset() - Bias;
1581   uint64_t RelocType = Reloc.getType();
1582   SmallString<32> RelocName;
1583   StringRef SymbolName;
1584   Reloc.getTypeName(RelocName);
1585   symbol_iterator Symbol = Reloc.getSymbol();
1586   int64_t SymbolIndex = -1;
1587   if (Symbol != Obj->symbol_end()) {
1588     Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1589     if (!SymbolNameOrErr)
1590       reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
1591 
1592     SymbolName = *SymbolNameOrErr;
1593     SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1594   }
1595 
1596   if (opts::ExpandRelocs) {
1597     DictScope Group(W, "Relocation");
1598     W.printHex("Offset", Offset);
1599     W.printNumber("Type", RelocName, RelocType);
1600     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1601     W.printNumber("SymbolIndex", SymbolIndex);
1602   } else {
1603     raw_ostream& OS = W.startLine();
1604     OS << W.hex(Offset)
1605        << " " << RelocName
1606        << " " << (SymbolName.empty() ? "-" : SymbolName)
1607        << " (" << SymbolIndex << ")"
1608        << "\n";
1609   }
1610 }
1611 
1612 void COFFDumper::printSymbols() {
1613   ListScope Group(W, "Symbols");
1614 
1615   for (const SymbolRef &Symbol : Obj->symbols())
1616     printSymbol(Symbol);
1617 }
1618 
1619 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1620 
1621 static Expected<StringRef>
1622 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1623                const coff_section *Section) {
1624   if (Section)
1625     return Obj->getSectionName(Section);
1626   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1627     return StringRef("IMAGE_SYM_DEBUG");
1628   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1629     return StringRef("IMAGE_SYM_ABSOLUTE");
1630   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1631     return StringRef("IMAGE_SYM_UNDEFINED");
1632   return StringRef("");
1633 }
1634 
1635 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1636   DictScope D(W, "Symbol");
1637 
1638   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1639   Expected<const coff_section *> SecOrErr =
1640       Obj->getSection(Symbol.getSectionNumber());
1641   if (!SecOrErr) {
1642     W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
1643                   << "\n";
1644     W.flush();
1645     consumeError(SecOrErr.takeError());
1646     return;
1647   }
1648   const coff_section *Section = *SecOrErr;
1649 
1650   StringRef SymbolName;
1651   if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
1652     SymbolName = *SymNameOrErr;
1653 
1654   StringRef SectionName;
1655   if (Expected<StringRef> SecNameOrErr =
1656           getSectionName(Obj, Symbol.getSectionNumber(), Section))
1657     SectionName = *SecNameOrErr;
1658 
1659   W.printString("Name", SymbolName);
1660   W.printNumber("Value", Symbol.getValue());
1661   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1662   W.printEnum("BaseType", Symbol.getBaseType(), ArrayRef(ImageSymType));
1663   W.printEnum("ComplexType", Symbol.getComplexType(), ArrayRef(ImageSymDType));
1664   W.printEnum("StorageClass", Symbol.getStorageClass(),
1665               ArrayRef(ImageSymClass));
1666   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1667 
1668   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1669     if (Symbol.isFunctionDefinition()) {
1670       const coff_aux_function_definition *Aux;
1671       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1672         reportError(errorCodeToError(EC), Obj->getFileName());
1673 
1674       DictScope AS(W, "AuxFunctionDef");
1675       W.printNumber("TagIndex", Aux->TagIndex);
1676       W.printNumber("TotalSize", Aux->TotalSize);
1677       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1678       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1679 
1680     } else if (Symbol.isAnyUndefined()) {
1681       const coff_aux_weak_external *Aux;
1682       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1683         reportError(errorCodeToError(EC), Obj->getFileName());
1684 
1685       DictScope AS(W, "AuxWeakExternal");
1686       W.printNumber("Linked", getSymbolName(Aux->TagIndex), Aux->TagIndex);
1687       W.printEnum("Search", Aux->Characteristics,
1688                   ArrayRef(WeakExternalCharacteristics));
1689 
1690     } else if (Symbol.isFileRecord()) {
1691       const char *FileName;
1692       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
1693         reportError(errorCodeToError(EC), Obj->getFileName());
1694       DictScope AS(W, "AuxFileRecord");
1695 
1696       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1697                                    Obj->getSymbolTableEntrySize());
1698       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1699       break;
1700     } else if (Symbol.isSectionDefinition()) {
1701       const coff_aux_section_definition *Aux;
1702       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1703         reportError(errorCodeToError(EC), Obj->getFileName());
1704 
1705       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1706 
1707       DictScope AS(W, "AuxSectionDef");
1708       W.printNumber("Length", Aux->Length);
1709       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1710       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1711       W.printHex("Checksum", Aux->CheckSum);
1712       W.printNumber("Number", AuxNumber);
1713       W.printEnum("Selection", Aux->Selection, ArrayRef(ImageCOMDATSelect));
1714 
1715       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1716           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1717         Expected<const coff_section *> Assoc = Obj->getSection(AuxNumber);
1718         if (!Assoc)
1719           reportError(Assoc.takeError(), Obj->getFileName());
1720         Expected<StringRef> AssocName = getSectionName(Obj, AuxNumber, *Assoc);
1721         if (!AssocName)
1722           reportError(AssocName.takeError(), Obj->getFileName());
1723 
1724         W.printNumber("AssocSection", *AssocName, AuxNumber);
1725       }
1726     } else if (Symbol.isCLRToken()) {
1727       const coff_aux_clr_token *Aux;
1728       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1729         reportError(errorCodeToError(EC), Obj->getFileName());
1730 
1731       DictScope AS(W, "AuxCLRToken");
1732       W.printNumber("AuxType", Aux->AuxType);
1733       W.printNumber("Reserved", Aux->Reserved);
1734       W.printNumber("SymbolTableIndex", getSymbolName(Aux->SymbolTableIndex),
1735                     Aux->SymbolTableIndex);
1736 
1737     } else {
1738       W.startLine() << "<unhandled auxiliary record>\n";
1739     }
1740   }
1741 }
1742 
1743 void COFFDumper::printUnwindInfo() {
1744   ListScope D(W, "UnwindInformation");
1745   switch (Obj->getMachine()) {
1746   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1747     Win64EH::Dumper Dumper(W);
1748     Win64EH::Dumper::SymbolResolver
1749     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1750                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1751       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1752       return Dumper->resolveSymbol(Section, Offset, Symbol);
1753     };
1754     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1755     Dumper.printData(Ctx);
1756     break;
1757   }
1758   case COFF::IMAGE_FILE_MACHINE_ARM64:
1759   case COFF::IMAGE_FILE_MACHINE_ARM64EC:
1760   case COFF::IMAGE_FILE_MACHINE_ARM64X:
1761   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1762     ARM::WinEH::Decoder Decoder(W, Obj->getMachine() !=
1763                                        COFF::IMAGE_FILE_MACHINE_ARMNT);
1764     // TODO Propagate the error.
1765     consumeError(Decoder.dumpProcedureData(*Obj));
1766     break;
1767   }
1768   default:
1769     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1770                 ArrayRef(ImageFileMachineType));
1771     break;
1772   }
1773 }
1774 
1775 void COFFDumper::printNeededLibraries() {
1776   ListScope D(W, "NeededLibraries");
1777 
1778   using LibsTy = std::vector<StringRef>;
1779   LibsTy Libs;
1780 
1781   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1782     StringRef Name;
1783     if (!DirRef.getName(Name))
1784       Libs.push_back(Name);
1785   }
1786 
1787   llvm::stable_sort(Libs);
1788 
1789   for (const auto &L : Libs) {
1790     W.startLine() << L << "\n";
1791   }
1792 }
1793 
1794 void COFFDumper::printImportedSymbols(
1795     iterator_range<imported_symbol_iterator> Range) {
1796   for (const ImportedSymbolRef &I : Range) {
1797     StringRef Sym;
1798     if (Error E = I.getSymbolName(Sym))
1799       reportError(std::move(E), Obj->getFileName());
1800     uint16_t Ordinal;
1801     if (Error E = I.getOrdinal(Ordinal))
1802       reportError(std::move(E), Obj->getFileName());
1803     W.printNumber("Symbol", Sym, Ordinal);
1804   }
1805 }
1806 
1807 void COFFDumper::printDelayImportedSymbols(
1808     const DelayImportDirectoryEntryRef &I,
1809     iterator_range<imported_symbol_iterator> Range) {
1810   int Index = 0;
1811   for (const ImportedSymbolRef &S : Range) {
1812     DictScope Import(W, "Import");
1813     StringRef Sym;
1814     if (Error E = S.getSymbolName(Sym))
1815       reportError(std::move(E), Obj->getFileName());
1816 
1817     uint16_t Ordinal;
1818     if (Error E = S.getOrdinal(Ordinal))
1819       reportError(std::move(E), Obj->getFileName());
1820     W.printNumber("Symbol", Sym, Ordinal);
1821 
1822     uint64_t Addr;
1823     if (Error E = I.getImportAddress(Index++, Addr))
1824       reportError(std::move(E), Obj->getFileName());
1825     W.printHex("Address", Addr);
1826   }
1827 }
1828 
1829 void COFFDumper::printCOFFImports() {
1830   // Regular imports
1831   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1832     DictScope Import(W, "Import");
1833     StringRef Name;
1834     if (Error E = I.getName(Name))
1835       reportError(std::move(E), Obj->getFileName());
1836     W.printString("Name", Name);
1837     uint32_t ILTAddr;
1838     if (Error E = I.getImportLookupTableRVA(ILTAddr))
1839       reportError(std::move(E), Obj->getFileName());
1840     W.printHex("ImportLookupTableRVA", ILTAddr);
1841     uint32_t IATAddr;
1842     if (Error E = I.getImportAddressTableRVA(IATAddr))
1843       reportError(std::move(E), Obj->getFileName());
1844     W.printHex("ImportAddressTableRVA", IATAddr);
1845     // The import lookup table can be missing with certain older linkers, so
1846     // fall back to the import address table in that case.
1847     if (ILTAddr)
1848       printImportedSymbols(I.lookup_table_symbols());
1849     else
1850       printImportedSymbols(I.imported_symbols());
1851   }
1852 
1853   // Delay imports
1854   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1855     DictScope Import(W, "DelayImport");
1856     StringRef Name;
1857     if (Error E = I.getName(Name))
1858       reportError(std::move(E), Obj->getFileName());
1859     W.printString("Name", Name);
1860     const delay_import_directory_table_entry *Table;
1861     if (Error E = I.getDelayImportTable(Table))
1862       reportError(std::move(E), Obj->getFileName());
1863     W.printHex("Attributes", Table->Attributes);
1864     W.printHex("ModuleHandle", Table->ModuleHandle);
1865     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1866     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1867     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1868     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1869     printDelayImportedSymbols(I, I.imported_symbols());
1870   }
1871 }
1872 
1873 void COFFDumper::printCOFFExports() {
1874   for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
1875     DictScope Export(W, "Export");
1876 
1877     StringRef Name;
1878     uint32_t Ordinal;
1879     bool IsForwarder;
1880 
1881     if (Error E = Exp.getSymbolName(Name))
1882       reportError(std::move(E), Obj->getFileName());
1883     if (Error E = Exp.getOrdinal(Ordinal))
1884       reportError(std::move(E), Obj->getFileName());
1885     if (Error E = Exp.isForwarder(IsForwarder))
1886       reportError(std::move(E), Obj->getFileName());
1887 
1888     W.printNumber("Ordinal", Ordinal);
1889     W.printString("Name", Name);
1890     StringRef ForwardTo;
1891     if (IsForwarder) {
1892       if (Error E = Exp.getForwardTo(ForwardTo))
1893         reportError(std::move(E), Obj->getFileName());
1894       W.printString("ForwardedTo", ForwardTo);
1895     } else {
1896       uint32_t RVA;
1897       if (Error E = Exp.getExportRVA(RVA))
1898         reportError(std::move(E), Obj->getFileName());
1899       W.printHex("RVA", RVA);
1900     }
1901   }
1902 }
1903 
1904 void COFFDumper::printCOFFDirectives() {
1905   for (const SectionRef &Section : Obj->sections()) {
1906     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1907     if (Name != ".drectve")
1908       continue;
1909 
1910     StringRef Contents =
1911         unwrapOrError(Obj->getFileName(), Section.getContents());
1912     W.printString("Directive(s)", Contents);
1913   }
1914 }
1915 
1916 static std::string getBaseRelocTypeName(uint8_t Type) {
1917   switch (Type) {
1918   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1919   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1920   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1921   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1922   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1923   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1924   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1925   default: return "unknown (" + llvm::utostr(Type) + ")";
1926   }
1927 }
1928 
1929 void COFFDumper::printCOFFBaseReloc() {
1930   ListScope D(W, "BaseReloc");
1931   for (const BaseRelocRef &I : Obj->base_relocs()) {
1932     uint8_t Type;
1933     uint32_t RVA;
1934     if (Error E = I.getRVA(RVA))
1935       reportError(std::move(E), Obj->getFileName());
1936     if (Error E = I.getType(Type))
1937       reportError(std::move(E), Obj->getFileName());
1938     DictScope Import(W, "Entry");
1939     W.printString("Type", getBaseRelocTypeName(Type));
1940     W.printHex("Address", RVA);
1941   }
1942 }
1943 
1944 void COFFDumper::printCOFFResources() {
1945   ListScope ResourcesD(W, "Resources");
1946   for (const SectionRef &S : Obj->sections()) {
1947     StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
1948     if (!Name.startswith(".rsrc"))
1949       continue;
1950 
1951     StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1952 
1953     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1954       ResourceSectionRef RSF;
1955       Error E = RSF.load(Obj, S);
1956       if (E)
1957         reportError(std::move(E), Obj->getFileName());
1958       auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1959       W.printNumber("Total Number of Resources",
1960                     countTotalTableEntries(RSF, BaseTable, "Type"));
1961       W.printHex("Base Table Address",
1962                  Obj->getCOFFSection(S)->PointerToRawData);
1963       W.startLine() << "\n";
1964       printResourceDirectoryTable(RSF, BaseTable, "Type");
1965     }
1966     if (opts::SectionData)
1967       W.printBinaryBlock(Name.str() + " Data", Ref);
1968   }
1969 }
1970 
1971 uint32_t
1972 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1973                                    const coff_resource_dir_table &Table,
1974                                    StringRef Level) {
1975   uint32_t TotalEntries = 0;
1976   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1977        i++) {
1978     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1979     if (Entry.Offset.isSubDir()) {
1980       StringRef NextLevel;
1981       if (Level == "Name")
1982         NextLevel = "Language";
1983       else
1984         NextLevel = "Name";
1985       auto &NextTable =
1986           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1987       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1988     } else {
1989       TotalEntries += 1;
1990     }
1991   }
1992   return TotalEntries;
1993 }
1994 
1995 void COFFDumper::printResourceDirectoryTable(
1996     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1997     StringRef Level) {
1998 
1999   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
2000   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
2001 
2002   // Iterate through level in resource directory tree.
2003   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
2004        i++) {
2005     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
2006     StringRef Name;
2007     SmallString<20> IDStr;
2008     raw_svector_ostream OS(IDStr);
2009     if (i < Table.NumberOfNameEntries) {
2010       ArrayRef<UTF16> RawEntryNameString =
2011           unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
2012       std::vector<UTF16> EndianCorrectedNameString;
2013       if (llvm::sys::IsBigEndianHost) {
2014         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
2015         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
2016                   EndianCorrectedNameString.begin() + 1);
2017         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
2018         RawEntryNameString = ArrayRef(EndianCorrectedNameString);
2019       }
2020       std::string EntryNameString;
2021       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
2022         reportError(errorCodeToError(object_error::parse_failed),
2023                     Obj->getFileName());
2024       OS << ": ";
2025       OS << EntryNameString;
2026     } else {
2027       if (Level == "Type") {
2028         OS << ": ";
2029         printResourceTypeName(Entry.Identifier.ID, OS);
2030       } else {
2031         OS << ": (ID " << Entry.Identifier.ID << ")";
2032       }
2033     }
2034     Name = IDStr;
2035     ListScope ResourceType(W, Level.str() + Name.str());
2036     if (Entry.Offset.isSubDir()) {
2037       W.printHex("Table Offset", Entry.Offset.value());
2038       StringRef NextLevel;
2039       if (Level == "Name")
2040         NextLevel = "Language";
2041       else
2042         NextLevel = "Name";
2043       auto &NextTable =
2044           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
2045       printResourceDirectoryTable(RSF, NextTable, NextLevel);
2046     } else {
2047       W.printHex("Entry Offset", Entry.Offset.value());
2048       char FormattedTime[20] = {};
2049       time_t TDS = time_t(Table.TimeDateStamp);
2050       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
2051       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
2052       W.printNumber("Major Version", Table.MajorVersion);
2053       W.printNumber("Minor Version", Table.MinorVersion);
2054       W.printNumber("Characteristics", Table.Characteristics);
2055       ListScope DataScope(W, "Data");
2056       auto &DataEntry =
2057           unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
2058       W.printHex("DataRVA", DataEntry.DataRVA);
2059       W.printNumber("DataSize", DataEntry.DataSize);
2060       W.printNumber("Codepage", DataEntry.Codepage);
2061       W.printNumber("Reserved", DataEntry.Reserved);
2062       StringRef Contents =
2063           unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
2064       W.printBinaryBlock("Data", Contents);
2065     }
2066   }
2067 }
2068 
2069 void COFFDumper::printStackMap() const {
2070   SectionRef StackMapSection;
2071   for (auto Sec : Obj->sections()) {
2072     StringRef Name;
2073     if (Expected<StringRef> NameOrErr = Sec.getName())
2074       Name = *NameOrErr;
2075     else
2076       consumeError(NameOrErr.takeError());
2077 
2078     if (Name == ".llvm_stackmaps") {
2079       StackMapSection = Sec;
2080       break;
2081     }
2082   }
2083 
2084   if (StackMapSection == SectionRef())
2085     return;
2086 
2087   StringRef StackMapContents =
2088       unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
2089   ArrayRef<uint8_t> StackMapContentsArray =
2090       arrayRefFromStringRef(StackMapContents);
2091 
2092   if (Obj->isLittleEndian())
2093     prettyPrintStackMap(
2094         W, StackMapParser<support::little>(StackMapContentsArray));
2095   else
2096     prettyPrintStackMap(
2097         W, StackMapParser<support::big>(StackMapContentsArray));
2098 }
2099 
2100 void COFFDumper::printAddrsig() {
2101   SectionRef AddrsigSection;
2102   for (auto Sec : Obj->sections()) {
2103     StringRef Name;
2104     if (Expected<StringRef> NameOrErr = Sec.getName())
2105       Name = *NameOrErr;
2106     else
2107       consumeError(NameOrErr.takeError());
2108 
2109     if (Name == ".llvm_addrsig") {
2110       AddrsigSection = Sec;
2111       break;
2112     }
2113   }
2114 
2115   if (AddrsigSection == SectionRef())
2116     return;
2117 
2118   StringRef AddrsigContents =
2119       unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
2120   ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
2121                                          AddrsigContents.size());
2122 
2123   ListScope L(W, "Addrsig");
2124   const uint8_t *Cur = AddrsigContents.bytes_begin();
2125   const uint8_t *End = AddrsigContents.bytes_end();
2126   while (Cur != End) {
2127     unsigned Size;
2128     const char *Err;
2129     uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
2130     if (Err)
2131       reportError(createError(Err), Obj->getFileName());
2132 
2133     W.printNumber("Sym", getSymbolName(SymIndex), SymIndex);
2134     Cur += Size;
2135   }
2136 }
2137 
2138 void COFFDumper::printCGProfile() {
2139   SectionRef CGProfileSection;
2140   for (SectionRef Sec : Obj->sections()) {
2141     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
2142     if (Name == ".llvm.call-graph-profile") {
2143       CGProfileSection = Sec;
2144       break;
2145     }
2146   }
2147 
2148   if (CGProfileSection == SectionRef())
2149     return;
2150 
2151   StringRef CGProfileContents =
2152       unwrapOrError(Obj->getFileName(), CGProfileSection.getContents());
2153   BinaryStreamReader Reader(CGProfileContents, llvm::support::little);
2154 
2155   ListScope L(W, "CGProfile");
2156   while (!Reader.empty()) {
2157     uint32_t FromIndex, ToIndex;
2158     uint64_t Count;
2159     if (Error Err = Reader.readInteger(FromIndex))
2160       reportError(std::move(Err), Obj->getFileName());
2161     if (Error Err = Reader.readInteger(ToIndex))
2162       reportError(std::move(Err), Obj->getFileName());
2163     if (Error Err = Reader.readInteger(Count))
2164       reportError(std::move(Err), Obj->getFileName());
2165 
2166     DictScope D(W, "CGProfileEntry");
2167     W.printNumber("From", getSymbolName(FromIndex), FromIndex);
2168     W.printNumber("To", getSymbolName(ToIndex), ToIndex);
2169     W.printNumber("Weight", Count);
2170   }
2171 }
2172 
2173 StringRef COFFDumper::getSymbolName(uint32_t Index) {
2174   Expected<COFFSymbolRef> Sym = Obj->getSymbol(Index);
2175   if (!Sym)
2176     reportError(Sym.takeError(), Obj->getFileName());
2177 
2178   Expected<StringRef> SymName = Obj->getSymbolName(*Sym);
2179   if (!SymName)
2180     reportError(SymName.takeError(), Obj->getFileName());
2181 
2182   return *SymName;
2183 }
2184 
2185 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
2186                                    ArrayRef<ArrayRef<uint8_t>> IpiRecords,
2187                                    ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
2188   TypeTableCollection TpiTypes(TpiRecords);
2189   {
2190     ListScope S(Writer, "MergedTypeStream");
2191     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2192     if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
2193       reportError(std::move(Err), "<?>");
2194     Writer.flush();
2195   }
2196 
2197   // Flatten the id stream and print it next. The ID stream refers to names from
2198   // the type stream.
2199   TypeTableCollection IpiTypes(IpiRecords);
2200   {
2201     ListScope S(Writer, "MergedIDStream");
2202     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2203     TDV.setIpiTypes(IpiTypes);
2204     if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
2205       reportError(std::move(Err), "<?>");
2206     Writer.flush();
2207   }
2208 }
2209 
2210 void COFFDumper::printCOFFTLSDirectory() {
2211   if (Obj->is64())
2212     printCOFFTLSDirectory(Obj->getTLSDirectory64());
2213   else
2214     printCOFFTLSDirectory(Obj->getTLSDirectory32());
2215 }
2216 
2217 template <typename IntTy>
2218 void COFFDumper::printCOFFTLSDirectory(
2219     const coff_tls_directory<IntTy> *TlsTable) {
2220   DictScope D(W, "TLSDirectory");
2221   if (!TlsTable)
2222     return;
2223 
2224   W.printHex("StartAddressOfRawData", TlsTable->StartAddressOfRawData);
2225   W.printHex("EndAddressOfRawData", TlsTable->EndAddressOfRawData);
2226   W.printHex("AddressOfIndex", TlsTable->AddressOfIndex);
2227   W.printHex("AddressOfCallBacks", TlsTable->AddressOfCallBacks);
2228   W.printHex("SizeOfZeroFill", TlsTable->SizeOfZeroFill);
2229   W.printFlags("Characteristics", TlsTable->Characteristics,
2230                ArrayRef(ImageSectionCharacteristics),
2231                COFF::SectionCharacteristics(COFF::IMAGE_SCN_ALIGN_MASK));
2232 }
2233