xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-readobj/COFFDumper.cpp (revision 8a4dda33d67586ca2624f2a38417baa03a533a7f)
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   if (Tables.GuardFidTableVA) {
944     ListScope LS(W, "GuardFidTable");
945     if (uint32_t Size =
946             Tables.GuardFlags &
947             uint32_t(COFF::GuardFlags::CF_FUNCTION_TABLE_SIZE_MASK)) {
948       // The size mask gives the number of extra bytes in addition to the 4-byte
949       // RVA of each entry in the table. As of writing only a 1-byte extra flag
950       // has been defined.
951       Size = (Size >> 28) + 4;
952       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, Size,
953                     PrintGuardFlags);
954     } else {
955       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
956     }
957   }
958 
959   if (Tables.GuardIatTableVA) {
960     ListScope LS(W, "GuardIatTable");
961     printRVATable(Tables.GuardIatTableVA, Tables.GuardIatTableCount, 4);
962   }
963 
964   if (Tables.GuardLJmpTableVA) {
965     ListScope LS(W, "GuardLJmpTable");
966     printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
967   }
968 
969   if (Tables.GuardEHContTableVA) {
970     ListScope LS(W, "GuardEHContTable");
971     printRVATable(Tables.GuardEHContTableVA, Tables.GuardEHContTableCount, 5,
972                   PrintGuardFlags);
973   }
974 }
975 
976 template <typename T>
977 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
978   if (!Conf)
979     return;
980 
981   ListScope LS(W, "LoadConfig");
982   char FormattedTime[20] = {};
983   time_t TDS = Conf->TimeDateStamp;
984   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
985   W.printHex("Size", Conf->Size);
986 
987   // Print everything before SecurityCookie. The vast majority of images today
988   // have all these fields.
989   if (Conf->Size < offsetof(T, SEHandlerTable))
990     return;
991   W.printHex("TimeDateStamp", FormattedTime, TDS);
992   W.printHex("MajorVersion", Conf->MajorVersion);
993   W.printHex("MinorVersion", Conf->MinorVersion);
994   W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
995   W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
996   W.printHex("CriticalSectionDefaultTimeout",
997              Conf->CriticalSectionDefaultTimeout);
998   W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
999   W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
1000   W.printHex("LockPrefixTable", Conf->LockPrefixTable);
1001   W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
1002   W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
1003   W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
1004   W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
1005   W.printHex("CSDVersion", Conf->CSDVersion);
1006   W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
1007   W.printHex("EditList", Conf->EditList);
1008   W.printHex("SecurityCookie", Conf->SecurityCookie);
1009 
1010   // Print the safe SEH table if present.
1011   if (Conf->Size < offsetof(T, GuardCFCheckFunction))
1012     return;
1013   W.printHex("SEHandlerTable", Conf->SEHandlerTable);
1014   W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
1015 
1016   Tables.SEHTableVA = Conf->SEHandlerTable;
1017   Tables.SEHTableCount = Conf->SEHandlerCount;
1018 
1019   // Print everything before CodeIntegrity. (2015)
1020   if (Conf->Size < offsetof(T, CodeIntegrity))
1021     return;
1022   W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
1023   W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
1024   W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
1025   W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
1026   W.printFlags("GuardFlags", Conf->GuardFlags, ArrayRef(PELoadConfigGuardFlags),
1027                (uint32_t)COFF::GuardFlags::CF_FUNCTION_TABLE_SIZE_MASK);
1028 
1029   Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
1030   Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
1031   Tables.GuardFlags = Conf->GuardFlags;
1032 
1033   // Print everything before Reserved3. (2017)
1034   if (Conf->Size < offsetof(T, Reserved3))
1035     return;
1036   W.printHex("GuardAddressTakenIatEntryTable",
1037              Conf->GuardAddressTakenIatEntryTable);
1038   W.printNumber("GuardAddressTakenIatEntryCount",
1039                 Conf->GuardAddressTakenIatEntryCount);
1040   W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
1041   W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
1042   W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
1043   W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
1044   W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
1045   W.printHex("GuardRFFailureRoutineFunctionPointer",
1046              Conf->GuardRFFailureRoutineFunctionPointer);
1047   W.printHex("DynamicValueRelocTableOffset",
1048              Conf->DynamicValueRelocTableOffset);
1049   W.printNumber("DynamicValueRelocTableSection",
1050                 Conf->DynamicValueRelocTableSection);
1051   W.printHex("GuardRFVerifyStackPointerFunctionPointer",
1052              Conf->GuardRFVerifyStackPointerFunctionPointer);
1053   W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
1054 
1055   Tables.GuardIatTableVA = Conf->GuardAddressTakenIatEntryTable;
1056   Tables.GuardIatTableCount = Conf->GuardAddressTakenIatEntryCount;
1057 
1058   Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
1059   Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
1060 
1061   // Print the rest. (2019)
1062   if (Conf->Size < sizeof(T))
1063     return;
1064   W.printHex("EnclaveConfigurationPointer", Conf->EnclaveConfigurationPointer);
1065   W.printHex("VolatileMetadataPointer", Conf->VolatileMetadataPointer);
1066   W.printHex("GuardEHContinuationTable", Conf->GuardEHContinuationTable);
1067   W.printNumber("GuardEHContinuationCount", Conf->GuardEHContinuationCount);
1068 
1069   Tables.GuardEHContTableVA = Conf->GuardEHContinuationTable;
1070   Tables.GuardEHContTableCount = Conf->GuardEHContinuationCount;
1071 }
1072 
1073 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
1074   W.printHex("BaseOfData", Hdr->BaseOfData);
1075 }
1076 
1077 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
1078 
1079 void COFFDumper::printCodeViewDebugInfo() {
1080   // Print types first to build CVUDTNames, then print symbols.
1081   for (const SectionRef &S : Obj->sections()) {
1082     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1083     // .debug$T is a standard CodeView type section, while .debug$P is the same
1084     // format but used for MSVC precompiled header object files.
1085     if (SectionName == ".debug$T" || SectionName == ".debug$P")
1086       printCodeViewTypeSection(SectionName, S);
1087   }
1088   for (const SectionRef &S : Obj->sections()) {
1089     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1090     if (SectionName == ".debug$S")
1091       printCodeViewSymbolSection(SectionName, S);
1092   }
1093 }
1094 
1095 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
1096   while (Reader.bytesRemaining() > 0 &&
1097          (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
1098     // The section consists of a number of subsection in the following format:
1099     // |SubSectionType|SubSectionSize|Contents...|
1100     uint32_t SubType, SubSectionSize;
1101 
1102     if (Error E = Reader.readInteger(SubType))
1103       reportError(std::move(E), Obj->getFileName());
1104     if (Error E = Reader.readInteger(SubSectionSize))
1105       reportError(std::move(E), Obj->getFileName());
1106 
1107     StringRef Contents;
1108     if (Error E = Reader.readFixedString(Contents, SubSectionSize))
1109       reportError(std::move(E), Obj->getFileName());
1110 
1111     BinaryStreamRef ST(Contents, support::little);
1112     switch (DebugSubsectionKind(SubType)) {
1113     case DebugSubsectionKind::FileChecksums:
1114       if (Error E = CVFileChecksumTable.initialize(ST))
1115         reportError(std::move(E), Obj->getFileName());
1116       break;
1117     case DebugSubsectionKind::StringTable:
1118       if (Error E = CVStringTable.initialize(ST))
1119         reportError(std::move(E), Obj->getFileName());
1120       break;
1121     default:
1122       break;
1123     }
1124 
1125     uint32_t PaddedSize = alignTo(SubSectionSize, 4);
1126     if (Error E = Reader.skip(PaddedSize - SubSectionSize))
1127       reportError(std::move(E), Obj->getFileName());
1128   }
1129 }
1130 
1131 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
1132                                             const SectionRef &Section) {
1133   StringRef SectionContents =
1134       unwrapOrError(Obj->getFileName(), Section.getContents());
1135   StringRef Data = SectionContents;
1136 
1137   SmallVector<StringRef, 10> FunctionNames;
1138   StringMap<StringRef> FunctionLineTables;
1139 
1140   ListScope D(W, "CodeViewDebugInfo");
1141   // Print the section to allow correlation with printSectionHeaders.
1142   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1143 
1144   uint32_t Magic;
1145   if (Error E = consume(Data, Magic))
1146     reportError(std::move(E), Obj->getFileName());
1147 
1148   W.printHex("Magic", Magic);
1149   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1150     reportError(errorCodeToError(object_error::parse_failed),
1151                 Obj->getFileName());
1152 
1153   BinaryStreamReader FSReader(Data, support::little);
1154   initializeFileAndStringTables(FSReader);
1155 
1156   // TODO: Convert this over to using ModuleSubstreamVisitor.
1157   while (!Data.empty()) {
1158     // The section consists of a number of subsection in the following format:
1159     // |SubSectionType|SubSectionSize|Contents...|
1160     uint32_t SubType, SubSectionSize;
1161     if (Error E = consume(Data, SubType))
1162       reportError(std::move(E), Obj->getFileName());
1163     if (Error E = consume(Data, SubSectionSize))
1164       reportError(std::move(E), Obj->getFileName());
1165 
1166     ListScope S(W, "Subsection");
1167     // Dump the subsection as normal even if the ignore bit is set.
1168     if (SubType & SubsectionIgnoreFlag) {
1169       W.printHex("IgnoredSubsectionKind", SubType);
1170       SubType &= ~SubsectionIgnoreFlag;
1171     }
1172     W.printEnum("SubSectionType", SubType, ArrayRef(SubSectionTypes));
1173     W.printHex("SubSectionSize", SubSectionSize);
1174 
1175     // Get the contents of the subsection.
1176     if (SubSectionSize > Data.size())
1177       return reportError(errorCodeToError(object_error::parse_failed),
1178                          Obj->getFileName());
1179     StringRef Contents = Data.substr(0, SubSectionSize);
1180 
1181     // Add SubSectionSize to the current offset and align that offset to find
1182     // the next subsection.
1183     size_t SectionOffset = Data.data() - SectionContents.data();
1184     size_t NextOffset = SectionOffset + SubSectionSize;
1185     NextOffset = alignTo(NextOffset, 4);
1186     if (NextOffset > SectionContents.size())
1187       return reportError(errorCodeToError(object_error::parse_failed),
1188                          Obj->getFileName());
1189     Data = SectionContents.drop_front(NextOffset);
1190 
1191     // Optionally print the subsection bytes in case our parsing gets confused
1192     // later.
1193     if (opts::CodeViewSubsectionBytes)
1194       printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
1195                                  Contents);
1196 
1197     switch (DebugSubsectionKind(SubType)) {
1198     case DebugSubsectionKind::Symbols:
1199       printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1200       break;
1201 
1202     case DebugSubsectionKind::InlineeLines:
1203       printCodeViewInlineeLines(Contents);
1204       break;
1205 
1206     case DebugSubsectionKind::FileChecksums:
1207       printCodeViewFileChecksums(Contents);
1208       break;
1209 
1210     case DebugSubsectionKind::Lines: {
1211       // Holds a PC to file:line table.  Some data to parse this subsection is
1212       // stored in the other subsections, so just check sanity and store the
1213       // pointers for deferred processing.
1214 
1215       if (SubSectionSize < 12) {
1216         // There should be at least three words to store two function
1217         // relocations and size of the code.
1218         reportError(errorCodeToError(object_error::parse_failed),
1219                     Obj->getFileName());
1220         return;
1221       }
1222 
1223       StringRef LinkageName;
1224       if (std::error_code EC = resolveSymbolName(Obj->getCOFFSection(Section),
1225                                                  SectionOffset, LinkageName))
1226         reportError(errorCodeToError(EC), Obj->getFileName());
1227 
1228       W.printString("LinkageName", LinkageName);
1229       if (FunctionLineTables.count(LinkageName) != 0) {
1230         // Saw debug info for this function already?
1231         reportError(errorCodeToError(object_error::parse_failed),
1232                     Obj->getFileName());
1233         return;
1234       }
1235 
1236       FunctionLineTables[LinkageName] = Contents;
1237       FunctionNames.push_back(LinkageName);
1238       break;
1239     }
1240     case DebugSubsectionKind::FrameData: {
1241       // First four bytes is a relocation against the function.
1242       BinaryStreamReader SR(Contents, llvm::support::little);
1243 
1244       DebugFrameDataSubsectionRef FrameData;
1245       if (Error E = FrameData.initialize(SR))
1246         reportError(std::move(E), Obj->getFileName());
1247 
1248       StringRef LinkageName;
1249       if (std::error_code EC =
1250               resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1251                                 FrameData.getRelocPtr(), LinkageName))
1252         reportError(errorCodeToError(EC), Obj->getFileName());
1253       W.printString("LinkageName", LinkageName);
1254 
1255       // To find the active frame description, search this array for the
1256       // smallest PC range that includes the current PC.
1257       for (const auto &FD : FrameData) {
1258         StringRef FrameFunc = unwrapOrError(
1259             Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
1260 
1261         DictScope S(W, "FrameData");
1262         W.printHex("RvaStart", FD.RvaStart);
1263         W.printHex("CodeSize", FD.CodeSize);
1264         W.printHex("LocalSize", FD.LocalSize);
1265         W.printHex("ParamsSize", FD.ParamsSize);
1266         W.printHex("MaxStackSize", FD.MaxStackSize);
1267         W.printHex("PrologSize", FD.PrologSize);
1268         W.printHex("SavedRegsSize", FD.SavedRegsSize);
1269         W.printFlags("Flags", FD.Flags, ArrayRef(FrameDataFlags));
1270 
1271         // The FrameFunc string is a small RPN program. It can be broken up into
1272         // statements that end in the '=' operator, which assigns the value on
1273         // the top of the stack to the previously pushed variable. Variables can
1274         // be temporary values ($T0) or physical registers ($esp). Print each
1275         // assignment on its own line to make these programs easier to read.
1276         {
1277           ListScope FFS(W, "FrameFunc");
1278           while (!FrameFunc.empty()) {
1279             size_t EqOrEnd = FrameFunc.find('=');
1280             if (EqOrEnd == StringRef::npos)
1281               EqOrEnd = FrameFunc.size();
1282             else
1283               ++EqOrEnd;
1284             StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1285             W.printString(Stmt);
1286             FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1287           }
1288         }
1289       }
1290       break;
1291     }
1292 
1293     // Do nothing for unrecognized subsections.
1294     default:
1295       break;
1296     }
1297     W.flush();
1298   }
1299 
1300   // Dump the line tables now that we've read all the subsections and know all
1301   // the required information.
1302   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1303     StringRef Name = FunctionNames[I];
1304     ListScope S(W, "FunctionLineTable");
1305     W.printString("LinkageName", Name);
1306 
1307     BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1308 
1309     DebugLinesSubsectionRef LineInfo;
1310     if (Error E = LineInfo.initialize(Reader))
1311       reportError(std::move(E), Obj->getFileName());
1312 
1313     W.printHex("Flags", LineInfo.header()->Flags);
1314     W.printHex("CodeSize", LineInfo.header()->CodeSize);
1315     for (const auto &Entry : LineInfo) {
1316 
1317       ListScope S(W, "FilenameSegment");
1318       printFileNameForOffset("Filename", Entry.NameIndex);
1319       uint32_t ColumnIndex = 0;
1320       for (const auto &Line : Entry.LineNumbers) {
1321         if (Line.Offset >= LineInfo.header()->CodeSize) {
1322           reportError(errorCodeToError(object_error::parse_failed),
1323                       Obj->getFileName());
1324           return;
1325         }
1326 
1327         std::string PC = std::string(formatv("+{0:X}", uint32_t(Line.Offset)));
1328         ListScope PCScope(W, PC);
1329         codeview::LineInfo LI(Line.Flags);
1330 
1331         if (LI.isAlwaysStepInto())
1332           W.printString("StepInto", StringRef("Always"));
1333         else if (LI.isNeverStepInto())
1334           W.printString("StepInto", StringRef("Never"));
1335         else
1336           W.printNumber("LineNumberStart", LI.getStartLine());
1337         W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1338         W.printBoolean("IsStatement", LI.isStatement());
1339         if (LineInfo.hasColumnInfo()) {
1340           W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1341           W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1342           ++ColumnIndex;
1343         }
1344       }
1345     }
1346   }
1347 }
1348 
1349 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1350                                                 const SectionRef &Section,
1351                                                 StringRef SectionContents) {
1352   ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1353                                Subsection.bytes_end());
1354   auto CODD = std::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1355                                                         SectionContents);
1356   CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1357                       CompilationCPUType, opts::CodeViewSubsectionBytes);
1358   CVSymbolArray Symbols;
1359   BinaryStreamReader Reader(BinaryData, llvm::support::little);
1360   if (Error E = Reader.readArray(Symbols, Reader.getLength())) {
1361     W.flush();
1362     reportError(std::move(E), Obj->getFileName());
1363   }
1364 
1365   if (Error E = CVSD.dump(Symbols)) {
1366     W.flush();
1367     reportError(std::move(E), Obj->getFileName());
1368   }
1369   CompilationCPUType = CVSD.getCompilationCPUType();
1370   W.flush();
1371 }
1372 
1373 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1374   BinaryStreamRef Stream(Subsection, llvm::support::little);
1375   DebugChecksumsSubsectionRef Checksums;
1376   if (Error E = Checksums.initialize(Stream))
1377     reportError(std::move(E), Obj->getFileName());
1378 
1379   for (auto &FC : Checksums) {
1380     DictScope S(W, "FileChecksum");
1381 
1382     StringRef Filename = unwrapOrError(
1383         Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
1384     W.printHex("Filename", Filename, FC.FileNameOffset);
1385     W.printHex("ChecksumSize", FC.Checksum.size());
1386     W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1387                 ArrayRef(FileChecksumKindNames));
1388 
1389     W.printBinary("ChecksumBytes", FC.Checksum);
1390   }
1391 }
1392 
1393 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1394   BinaryStreamReader SR(Subsection, llvm::support::little);
1395   DebugInlineeLinesSubsectionRef Lines;
1396   if (Error E = Lines.initialize(SR))
1397     reportError(std::move(E), Obj->getFileName());
1398 
1399   for (auto &Line : Lines) {
1400     DictScope S(W, "InlineeSourceLine");
1401     printTypeIndex("Inlinee", Line.Header->Inlinee);
1402     printFileNameForOffset("FileID", Line.Header->FileID);
1403     W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1404 
1405     if (Lines.hasExtraFiles()) {
1406       W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1407       ListScope ExtraFiles(W, "ExtraFiles");
1408       for (const auto &FID : Line.ExtraFiles) {
1409         printFileNameForOffset("FileID", FID);
1410       }
1411     }
1412   }
1413 }
1414 
1415 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1416   // The file checksum subsection should precede all references to it.
1417   if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1418     reportError(errorCodeToError(object_error::parse_failed),
1419                 Obj->getFileName());
1420 
1421   auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1422 
1423   // Check if the file checksum table offset is valid.
1424   if (Iter == CVFileChecksumTable.end())
1425     reportError(errorCodeToError(object_error::parse_failed),
1426                 Obj->getFileName());
1427 
1428   return unwrapOrError(Obj->getFileName(),
1429                        CVStringTable.getString(Iter->FileNameOffset));
1430 }
1431 
1432 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1433   W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1434 }
1435 
1436 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1437                                     MergingTypeTableBuilder &CVTypes,
1438                                     GlobalTypeTableBuilder &GlobalCVIDs,
1439                                     GlobalTypeTableBuilder &GlobalCVTypes,
1440                                     bool GHash) {
1441   for (const SectionRef &S : Obj->sections()) {
1442     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1443     if (SectionName == ".debug$T") {
1444       StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
1445       uint32_t Magic;
1446       if (Error E = consume(Data, Magic))
1447         reportError(std::move(E), Obj->getFileName());
1448 
1449       if (Magic != 4)
1450         reportError(errorCodeToError(object_error::parse_failed),
1451                     Obj->getFileName());
1452 
1453       CVTypeArray Types;
1454       BinaryStreamReader Reader(Data, llvm::support::little);
1455       if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1456         consumeError(std::move(EC));
1457         W.flush();
1458         reportError(errorCodeToError(object_error::parse_failed),
1459                     Obj->getFileName());
1460       }
1461       SmallVector<TypeIndex, 128> SourceToDest;
1462       std::optional<PCHMergerInfo> PCHInfo;
1463       if (GHash) {
1464         std::vector<GloballyHashedType> Hashes =
1465             GloballyHashedType::hashTypes(Types);
1466         if (Error E =
1467                 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1468                                       Types, Hashes, PCHInfo))
1469           return reportError(std::move(E), Obj->getFileName());
1470       } else {
1471         if (Error E = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1472                                             PCHInfo))
1473           return reportError(std::move(E), Obj->getFileName());
1474       }
1475     }
1476   }
1477 }
1478 
1479 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1480                                           const SectionRef &Section) {
1481   ListScope D(W, "CodeViewTypes");
1482   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1483 
1484   StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
1485   if (opts::CodeViewSubsectionBytes)
1486     W.printBinaryBlock("Data", Data);
1487 
1488   uint32_t Magic;
1489   if (Error E = consume(Data, Magic))
1490     reportError(std::move(E), Obj->getFileName());
1491 
1492   W.printHex("Magic", Magic);
1493   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1494     reportError(errorCodeToError(object_error::parse_failed),
1495                 Obj->getFileName());
1496 
1497   Types.reset(Data, 100);
1498 
1499   TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1500   if (Error E = codeview::visitTypeStream(Types, TDV))
1501     reportError(std::move(E), Obj->getFileName());
1502 
1503   W.flush();
1504 }
1505 
1506 void COFFDumper::printSectionHeaders() {
1507   ListScope SectionsD(W, "Sections");
1508   int SectionNumber = 0;
1509   for (const SectionRef &Sec : Obj->sections()) {
1510     ++SectionNumber;
1511     const coff_section *Section = Obj->getCOFFSection(Sec);
1512 
1513     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
1514 
1515     DictScope D(W, "Section");
1516     W.printNumber("Number", SectionNumber);
1517     W.printBinary("Name", Name, Section->Name);
1518     W.printHex   ("VirtualSize", Section->VirtualSize);
1519     W.printHex   ("VirtualAddress", Section->VirtualAddress);
1520     W.printNumber("RawDataSize", Section->SizeOfRawData);
1521     W.printHex   ("PointerToRawData", Section->PointerToRawData);
1522     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
1523     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
1524     W.printNumber("RelocationCount", Section->NumberOfRelocations);
1525     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1526     W.printFlags("Characteristics", Section->Characteristics,
1527                  ArrayRef(ImageSectionCharacteristics),
1528                  COFF::SectionCharacteristics(0x00F00000));
1529 
1530     if (opts::SectionRelocations) {
1531       ListScope D(W, "Relocations");
1532       for (const RelocationRef &Reloc : Sec.relocations())
1533         printRelocation(Sec, Reloc);
1534     }
1535 
1536     if (opts::SectionSymbols) {
1537       ListScope D(W, "Symbols");
1538       for (const SymbolRef &Symbol : Obj->symbols()) {
1539         if (!Sec.containsSymbol(Symbol))
1540           continue;
1541 
1542         printSymbol(Symbol);
1543       }
1544     }
1545 
1546     if (opts::SectionData &&
1547         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1548       StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
1549       W.printBinaryBlock("SectionData", Data);
1550     }
1551   }
1552 }
1553 
1554 void COFFDumper::printRelocations() {
1555   ListScope D(W, "Relocations");
1556 
1557   int SectionNumber = 0;
1558   for (const SectionRef &Section : Obj->sections()) {
1559     ++SectionNumber;
1560     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1561 
1562     bool PrintedGroup = false;
1563     for (const RelocationRef &Reloc : Section.relocations()) {
1564       if (!PrintedGroup) {
1565         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1566         W.indent();
1567         PrintedGroup = true;
1568       }
1569 
1570       printRelocation(Section, Reloc);
1571     }
1572 
1573     if (PrintedGroup) {
1574       W.unindent();
1575       W.startLine() << "}\n";
1576     }
1577   }
1578 }
1579 
1580 void COFFDumper::printRelocation(const SectionRef &Section,
1581                                  const RelocationRef &Reloc, uint64_t Bias) {
1582   uint64_t Offset = Reloc.getOffset() - Bias;
1583   uint64_t RelocType = Reloc.getType();
1584   SmallString<32> RelocName;
1585   StringRef SymbolName;
1586   Reloc.getTypeName(RelocName);
1587   symbol_iterator Symbol = Reloc.getSymbol();
1588   int64_t SymbolIndex = -1;
1589   if (Symbol != Obj->symbol_end()) {
1590     Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1591     if (!SymbolNameOrErr)
1592       reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
1593 
1594     SymbolName = *SymbolNameOrErr;
1595     SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1596   }
1597 
1598   if (opts::ExpandRelocs) {
1599     DictScope Group(W, "Relocation");
1600     W.printHex("Offset", Offset);
1601     W.printNumber("Type", RelocName, RelocType);
1602     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1603     W.printNumber("SymbolIndex", SymbolIndex);
1604   } else {
1605     raw_ostream& OS = W.startLine();
1606     OS << W.hex(Offset)
1607        << " " << RelocName
1608        << " " << (SymbolName.empty() ? "-" : SymbolName)
1609        << " (" << SymbolIndex << ")"
1610        << "\n";
1611   }
1612 }
1613 
1614 void COFFDumper::printSymbols() {
1615   ListScope Group(W, "Symbols");
1616 
1617   for (const SymbolRef &Symbol : Obj->symbols())
1618     printSymbol(Symbol);
1619 }
1620 
1621 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1622 
1623 static Expected<StringRef>
1624 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1625                const coff_section *Section) {
1626   if (Section)
1627     return Obj->getSectionName(Section);
1628   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1629     return StringRef("IMAGE_SYM_DEBUG");
1630   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1631     return StringRef("IMAGE_SYM_ABSOLUTE");
1632   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1633     return StringRef("IMAGE_SYM_UNDEFINED");
1634   return StringRef("");
1635 }
1636 
1637 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1638   DictScope D(W, "Symbol");
1639 
1640   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1641   Expected<const coff_section *> SecOrErr =
1642       Obj->getSection(Symbol.getSectionNumber());
1643   if (!SecOrErr) {
1644     W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
1645                   << "\n";
1646     W.flush();
1647     consumeError(SecOrErr.takeError());
1648     return;
1649   }
1650   const coff_section *Section = *SecOrErr;
1651 
1652   StringRef SymbolName;
1653   if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
1654     SymbolName = *SymNameOrErr;
1655 
1656   StringRef SectionName;
1657   if (Expected<StringRef> SecNameOrErr =
1658           getSectionName(Obj, Symbol.getSectionNumber(), Section))
1659     SectionName = *SecNameOrErr;
1660 
1661   W.printString("Name", SymbolName);
1662   W.printNumber("Value", Symbol.getValue());
1663   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1664   W.printEnum("BaseType", Symbol.getBaseType(), ArrayRef(ImageSymType));
1665   W.printEnum("ComplexType", Symbol.getComplexType(), ArrayRef(ImageSymDType));
1666   W.printEnum("StorageClass", Symbol.getStorageClass(),
1667               ArrayRef(ImageSymClass));
1668   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1669 
1670   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1671     if (Symbol.isFunctionDefinition()) {
1672       const coff_aux_function_definition *Aux;
1673       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1674         reportError(errorCodeToError(EC), Obj->getFileName());
1675 
1676       DictScope AS(W, "AuxFunctionDef");
1677       W.printNumber("TagIndex", Aux->TagIndex);
1678       W.printNumber("TotalSize", Aux->TotalSize);
1679       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1680       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1681 
1682     } else if (Symbol.isAnyUndefined()) {
1683       const coff_aux_weak_external *Aux;
1684       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1685         reportError(errorCodeToError(EC), Obj->getFileName());
1686 
1687       DictScope AS(W, "AuxWeakExternal");
1688       W.printNumber("Linked", getSymbolName(Aux->TagIndex), Aux->TagIndex);
1689       W.printEnum("Search", Aux->Characteristics,
1690                   ArrayRef(WeakExternalCharacteristics));
1691 
1692     } else if (Symbol.isFileRecord()) {
1693       const char *FileName;
1694       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
1695         reportError(errorCodeToError(EC), Obj->getFileName());
1696       DictScope AS(W, "AuxFileRecord");
1697 
1698       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1699                                    Obj->getSymbolTableEntrySize());
1700       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1701       break;
1702     } else if (Symbol.isSectionDefinition()) {
1703       const coff_aux_section_definition *Aux;
1704       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1705         reportError(errorCodeToError(EC), Obj->getFileName());
1706 
1707       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1708 
1709       DictScope AS(W, "AuxSectionDef");
1710       W.printNumber("Length", Aux->Length);
1711       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1712       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1713       W.printHex("Checksum", Aux->CheckSum);
1714       W.printNumber("Number", AuxNumber);
1715       W.printEnum("Selection", Aux->Selection, ArrayRef(ImageCOMDATSelect));
1716 
1717       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1718           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1719         Expected<const coff_section *> Assoc = Obj->getSection(AuxNumber);
1720         if (!Assoc)
1721           reportError(Assoc.takeError(), Obj->getFileName());
1722         Expected<StringRef> AssocName = getSectionName(Obj, AuxNumber, *Assoc);
1723         if (!AssocName)
1724           reportError(AssocName.takeError(), Obj->getFileName());
1725 
1726         W.printNumber("AssocSection", *AssocName, AuxNumber);
1727       }
1728     } else if (Symbol.isCLRToken()) {
1729       const coff_aux_clr_token *Aux;
1730       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1731         reportError(errorCodeToError(EC), Obj->getFileName());
1732 
1733       DictScope AS(W, "AuxCLRToken");
1734       W.printNumber("AuxType", Aux->AuxType);
1735       W.printNumber("Reserved", Aux->Reserved);
1736       W.printNumber("SymbolTableIndex", getSymbolName(Aux->SymbolTableIndex),
1737                     Aux->SymbolTableIndex);
1738 
1739     } else {
1740       W.startLine() << "<unhandled auxiliary record>\n";
1741     }
1742   }
1743 }
1744 
1745 void COFFDumper::printUnwindInfo() {
1746   ListScope D(W, "UnwindInformation");
1747   switch (Obj->getMachine()) {
1748   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1749     Win64EH::Dumper Dumper(W);
1750     Win64EH::Dumper::SymbolResolver
1751     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1752                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1753       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1754       return Dumper->resolveSymbol(Section, Offset, Symbol);
1755     };
1756     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1757     Dumper.printData(Ctx);
1758     break;
1759   }
1760   case COFF::IMAGE_FILE_MACHINE_ARM64:
1761   case COFF::IMAGE_FILE_MACHINE_ARM64EC:
1762   case COFF::IMAGE_FILE_MACHINE_ARM64X:
1763   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1764     ARM::WinEH::Decoder Decoder(W, Obj->getMachine() !=
1765                                        COFF::IMAGE_FILE_MACHINE_ARMNT);
1766     // TODO Propagate the error.
1767     consumeError(Decoder.dumpProcedureData(*Obj));
1768     break;
1769   }
1770   default:
1771     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1772                 ArrayRef(ImageFileMachineType));
1773     break;
1774   }
1775 }
1776 
1777 void COFFDumper::printNeededLibraries() {
1778   ListScope D(W, "NeededLibraries");
1779 
1780   using LibsTy = std::vector<StringRef>;
1781   LibsTy Libs;
1782 
1783   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1784     StringRef Name;
1785     if (!DirRef.getName(Name))
1786       Libs.push_back(Name);
1787   }
1788 
1789   llvm::stable_sort(Libs);
1790 
1791   for (const auto &L : Libs) {
1792     W.startLine() << L << "\n";
1793   }
1794 }
1795 
1796 void COFFDumper::printImportedSymbols(
1797     iterator_range<imported_symbol_iterator> Range) {
1798   for (const ImportedSymbolRef &I : Range) {
1799     StringRef Sym;
1800     if (Error E = I.getSymbolName(Sym))
1801       reportError(std::move(E), Obj->getFileName());
1802     uint16_t Ordinal;
1803     if (Error E = I.getOrdinal(Ordinal))
1804       reportError(std::move(E), Obj->getFileName());
1805     W.printNumber("Symbol", Sym, Ordinal);
1806   }
1807 }
1808 
1809 void COFFDumper::printDelayImportedSymbols(
1810     const DelayImportDirectoryEntryRef &I,
1811     iterator_range<imported_symbol_iterator> Range) {
1812   int Index = 0;
1813   for (const ImportedSymbolRef &S : Range) {
1814     DictScope Import(W, "Import");
1815     StringRef Sym;
1816     if (Error E = S.getSymbolName(Sym))
1817       reportError(std::move(E), Obj->getFileName());
1818 
1819     uint16_t Ordinal;
1820     if (Error E = S.getOrdinal(Ordinal))
1821       reportError(std::move(E), Obj->getFileName());
1822     W.printNumber("Symbol", Sym, Ordinal);
1823 
1824     uint64_t Addr;
1825     if (Error E = I.getImportAddress(Index++, Addr))
1826       reportError(std::move(E), Obj->getFileName());
1827     W.printHex("Address", Addr);
1828   }
1829 }
1830 
1831 void COFFDumper::printCOFFImports() {
1832   // Regular imports
1833   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1834     DictScope Import(W, "Import");
1835     StringRef Name;
1836     if (Error E = I.getName(Name))
1837       reportError(std::move(E), Obj->getFileName());
1838     W.printString("Name", Name);
1839     uint32_t ILTAddr;
1840     if (Error E = I.getImportLookupTableRVA(ILTAddr))
1841       reportError(std::move(E), Obj->getFileName());
1842     W.printHex("ImportLookupTableRVA", ILTAddr);
1843     uint32_t IATAddr;
1844     if (Error E = I.getImportAddressTableRVA(IATAddr))
1845       reportError(std::move(E), Obj->getFileName());
1846     W.printHex("ImportAddressTableRVA", IATAddr);
1847     // The import lookup table can be missing with certain older linkers, so
1848     // fall back to the import address table in that case.
1849     if (ILTAddr)
1850       printImportedSymbols(I.lookup_table_symbols());
1851     else
1852       printImportedSymbols(I.imported_symbols());
1853   }
1854 
1855   // Delay imports
1856   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1857     DictScope Import(W, "DelayImport");
1858     StringRef Name;
1859     if (Error E = I.getName(Name))
1860       reportError(std::move(E), Obj->getFileName());
1861     W.printString("Name", Name);
1862     const delay_import_directory_table_entry *Table;
1863     if (Error E = I.getDelayImportTable(Table))
1864       reportError(std::move(E), Obj->getFileName());
1865     W.printHex("Attributes", Table->Attributes);
1866     W.printHex("ModuleHandle", Table->ModuleHandle);
1867     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1868     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1869     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1870     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1871     printDelayImportedSymbols(I, I.imported_symbols());
1872   }
1873 }
1874 
1875 void COFFDumper::printCOFFExports() {
1876   for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
1877     DictScope Export(W, "Export");
1878 
1879     StringRef Name;
1880     uint32_t Ordinal;
1881     bool IsForwarder;
1882 
1883     if (Error E = Exp.getSymbolName(Name))
1884       reportError(std::move(E), Obj->getFileName());
1885     if (Error E = Exp.getOrdinal(Ordinal))
1886       reportError(std::move(E), Obj->getFileName());
1887     if (Error E = Exp.isForwarder(IsForwarder))
1888       reportError(std::move(E), Obj->getFileName());
1889 
1890     W.printNumber("Ordinal", Ordinal);
1891     W.printString("Name", Name);
1892     StringRef ForwardTo;
1893     if (IsForwarder) {
1894       if (Error E = Exp.getForwardTo(ForwardTo))
1895         reportError(std::move(E), Obj->getFileName());
1896       W.printString("ForwardedTo", ForwardTo);
1897     } else {
1898       uint32_t RVA;
1899       if (Error E = Exp.getExportRVA(RVA))
1900         reportError(std::move(E), Obj->getFileName());
1901       W.printHex("RVA", RVA);
1902     }
1903   }
1904 }
1905 
1906 void COFFDumper::printCOFFDirectives() {
1907   for (const SectionRef &Section : Obj->sections()) {
1908     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1909     if (Name != ".drectve")
1910       continue;
1911 
1912     StringRef Contents =
1913         unwrapOrError(Obj->getFileName(), Section.getContents());
1914     W.printString("Directive(s)", Contents);
1915   }
1916 }
1917 
1918 static std::string getBaseRelocTypeName(uint8_t Type) {
1919   switch (Type) {
1920   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1921   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1922   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1923   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1924   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1925   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1926   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1927   default: return "unknown (" + llvm::utostr(Type) + ")";
1928   }
1929 }
1930 
1931 void COFFDumper::printCOFFBaseReloc() {
1932   ListScope D(W, "BaseReloc");
1933   for (const BaseRelocRef &I : Obj->base_relocs()) {
1934     uint8_t Type;
1935     uint32_t RVA;
1936     if (Error E = I.getRVA(RVA))
1937       reportError(std::move(E), Obj->getFileName());
1938     if (Error E = I.getType(Type))
1939       reportError(std::move(E), Obj->getFileName());
1940     DictScope Import(W, "Entry");
1941     W.printString("Type", getBaseRelocTypeName(Type));
1942     W.printHex("Address", RVA);
1943   }
1944 }
1945 
1946 void COFFDumper::printCOFFResources() {
1947   ListScope ResourcesD(W, "Resources");
1948   for (const SectionRef &S : Obj->sections()) {
1949     StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
1950     if (!Name.startswith(".rsrc"))
1951       continue;
1952 
1953     StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1954 
1955     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1956       ResourceSectionRef RSF;
1957       Error E = RSF.load(Obj, S);
1958       if (E)
1959         reportError(std::move(E), Obj->getFileName());
1960       auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1961       W.printNumber("Total Number of Resources",
1962                     countTotalTableEntries(RSF, BaseTable, "Type"));
1963       W.printHex("Base Table Address",
1964                  Obj->getCOFFSection(S)->PointerToRawData);
1965       W.startLine() << "\n";
1966       printResourceDirectoryTable(RSF, BaseTable, "Type");
1967     }
1968     if (opts::SectionData)
1969       W.printBinaryBlock(Name.str() + " Data", Ref);
1970   }
1971 }
1972 
1973 uint32_t
1974 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1975                                    const coff_resource_dir_table &Table,
1976                                    StringRef Level) {
1977   uint32_t TotalEntries = 0;
1978   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1979        i++) {
1980     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1981     if (Entry.Offset.isSubDir()) {
1982       StringRef NextLevel;
1983       if (Level == "Name")
1984         NextLevel = "Language";
1985       else
1986         NextLevel = "Name";
1987       auto &NextTable =
1988           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1989       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1990     } else {
1991       TotalEntries += 1;
1992     }
1993   }
1994   return TotalEntries;
1995 }
1996 
1997 void COFFDumper::printResourceDirectoryTable(
1998     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1999     StringRef Level) {
2000 
2001   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
2002   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
2003 
2004   // Iterate through level in resource directory tree.
2005   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
2006        i++) {
2007     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
2008     StringRef Name;
2009     SmallString<20> IDStr;
2010     raw_svector_ostream OS(IDStr);
2011     if (i < Table.NumberOfNameEntries) {
2012       ArrayRef<UTF16> RawEntryNameString =
2013           unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
2014       std::vector<UTF16> EndianCorrectedNameString;
2015       if (llvm::sys::IsBigEndianHost) {
2016         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
2017         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
2018                   EndianCorrectedNameString.begin() + 1);
2019         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
2020         RawEntryNameString = ArrayRef(EndianCorrectedNameString);
2021       }
2022       std::string EntryNameString;
2023       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
2024         reportError(errorCodeToError(object_error::parse_failed),
2025                     Obj->getFileName());
2026       OS << ": ";
2027       OS << EntryNameString;
2028     } else {
2029       if (Level == "Type") {
2030         OS << ": ";
2031         printResourceTypeName(Entry.Identifier.ID, OS);
2032       } else {
2033         OS << ": (ID " << Entry.Identifier.ID << ")";
2034       }
2035     }
2036     Name = IDStr;
2037     ListScope ResourceType(W, Level.str() + Name.str());
2038     if (Entry.Offset.isSubDir()) {
2039       W.printHex("Table Offset", Entry.Offset.value());
2040       StringRef NextLevel;
2041       if (Level == "Name")
2042         NextLevel = "Language";
2043       else
2044         NextLevel = "Name";
2045       auto &NextTable =
2046           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
2047       printResourceDirectoryTable(RSF, NextTable, NextLevel);
2048     } else {
2049       W.printHex("Entry Offset", Entry.Offset.value());
2050       char FormattedTime[20] = {};
2051       time_t TDS = time_t(Table.TimeDateStamp);
2052       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
2053       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
2054       W.printNumber("Major Version", Table.MajorVersion);
2055       W.printNumber("Minor Version", Table.MinorVersion);
2056       W.printNumber("Characteristics", Table.Characteristics);
2057       ListScope DataScope(W, "Data");
2058       auto &DataEntry =
2059           unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
2060       W.printHex("DataRVA", DataEntry.DataRVA);
2061       W.printNumber("DataSize", DataEntry.DataSize);
2062       W.printNumber("Codepage", DataEntry.Codepage);
2063       W.printNumber("Reserved", DataEntry.Reserved);
2064       StringRef Contents =
2065           unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
2066       W.printBinaryBlock("Data", Contents);
2067     }
2068   }
2069 }
2070 
2071 void COFFDumper::printStackMap() const {
2072   SectionRef StackMapSection;
2073   for (auto Sec : Obj->sections()) {
2074     StringRef Name;
2075     if (Expected<StringRef> NameOrErr = Sec.getName())
2076       Name = *NameOrErr;
2077     else
2078       consumeError(NameOrErr.takeError());
2079 
2080     if (Name == ".llvm_stackmaps") {
2081       StackMapSection = Sec;
2082       break;
2083     }
2084   }
2085 
2086   if (StackMapSection == SectionRef())
2087     return;
2088 
2089   StringRef StackMapContents =
2090       unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
2091   ArrayRef<uint8_t> StackMapContentsArray =
2092       arrayRefFromStringRef(StackMapContents);
2093 
2094   if (Obj->isLittleEndian())
2095     prettyPrintStackMap(
2096         W, StackMapParser<support::little>(StackMapContentsArray));
2097   else
2098     prettyPrintStackMap(
2099         W, StackMapParser<support::big>(StackMapContentsArray));
2100 }
2101 
2102 void COFFDumper::printAddrsig() {
2103   SectionRef AddrsigSection;
2104   for (auto Sec : Obj->sections()) {
2105     StringRef Name;
2106     if (Expected<StringRef> NameOrErr = Sec.getName())
2107       Name = *NameOrErr;
2108     else
2109       consumeError(NameOrErr.takeError());
2110 
2111     if (Name == ".llvm_addrsig") {
2112       AddrsigSection = Sec;
2113       break;
2114     }
2115   }
2116 
2117   if (AddrsigSection == SectionRef())
2118     return;
2119 
2120   StringRef AddrsigContents =
2121       unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
2122   ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
2123                                          AddrsigContents.size());
2124 
2125   ListScope L(W, "Addrsig");
2126   const uint8_t *Cur = AddrsigContents.bytes_begin();
2127   const uint8_t *End = AddrsigContents.bytes_end();
2128   while (Cur != End) {
2129     unsigned Size;
2130     const char *Err;
2131     uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
2132     if (Err)
2133       reportError(createError(Err), Obj->getFileName());
2134 
2135     W.printNumber("Sym", getSymbolName(SymIndex), SymIndex);
2136     Cur += Size;
2137   }
2138 }
2139 
2140 void COFFDumper::printCGProfile() {
2141   SectionRef CGProfileSection;
2142   for (SectionRef Sec : Obj->sections()) {
2143     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
2144     if (Name == ".llvm.call-graph-profile") {
2145       CGProfileSection = Sec;
2146       break;
2147     }
2148   }
2149 
2150   if (CGProfileSection == SectionRef())
2151     return;
2152 
2153   StringRef CGProfileContents =
2154       unwrapOrError(Obj->getFileName(), CGProfileSection.getContents());
2155   BinaryStreamReader Reader(CGProfileContents, llvm::support::little);
2156 
2157   ListScope L(W, "CGProfile");
2158   while (!Reader.empty()) {
2159     uint32_t FromIndex, ToIndex;
2160     uint64_t Count;
2161     if (Error Err = Reader.readInteger(FromIndex))
2162       reportError(std::move(Err), Obj->getFileName());
2163     if (Error Err = Reader.readInteger(ToIndex))
2164       reportError(std::move(Err), Obj->getFileName());
2165     if (Error Err = Reader.readInteger(Count))
2166       reportError(std::move(Err), Obj->getFileName());
2167 
2168     DictScope D(W, "CGProfileEntry");
2169     W.printNumber("From", getSymbolName(FromIndex), FromIndex);
2170     W.printNumber("To", getSymbolName(ToIndex), ToIndex);
2171     W.printNumber("Weight", Count);
2172   }
2173 }
2174 
2175 StringRef COFFDumper::getSymbolName(uint32_t Index) {
2176   Expected<COFFSymbolRef> Sym = Obj->getSymbol(Index);
2177   if (!Sym)
2178     reportError(Sym.takeError(), Obj->getFileName());
2179 
2180   Expected<StringRef> SymName = Obj->getSymbolName(*Sym);
2181   if (!SymName)
2182     reportError(SymName.takeError(), Obj->getFileName());
2183 
2184   return *SymName;
2185 }
2186 
2187 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
2188                                    ArrayRef<ArrayRef<uint8_t>> IpiRecords,
2189                                    ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
2190   TypeTableCollection TpiTypes(TpiRecords);
2191   {
2192     ListScope S(Writer, "MergedTypeStream");
2193     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2194     if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
2195       reportError(std::move(Err), "<?>");
2196     Writer.flush();
2197   }
2198 
2199   // Flatten the id stream and print it next. The ID stream refers to names from
2200   // the type stream.
2201   TypeTableCollection IpiTypes(IpiRecords);
2202   {
2203     ListScope S(Writer, "MergedIDStream");
2204     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2205     TDV.setIpiTypes(IpiTypes);
2206     if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
2207       reportError(std::move(Err), "<?>");
2208     Writer.flush();
2209   }
2210 }
2211 
2212 void COFFDumper::printCOFFTLSDirectory() {
2213   if (Obj->is64())
2214     printCOFFTLSDirectory(Obj->getTLSDirectory64());
2215   else
2216     printCOFFTLSDirectory(Obj->getTLSDirectory32());
2217 }
2218 
2219 template <typename IntTy>
2220 void COFFDumper::printCOFFTLSDirectory(
2221     const coff_tls_directory<IntTy> *TlsTable) {
2222   DictScope D(W, "TLSDirectory");
2223   if (!TlsTable)
2224     return;
2225 
2226   W.printHex("StartAddressOfRawData", TlsTable->StartAddressOfRawData);
2227   W.printHex("EndAddressOfRawData", TlsTable->EndAddressOfRawData);
2228   W.printHex("AddressOfIndex", TlsTable->AddressOfIndex);
2229   W.printHex("AddressOfCallBacks", TlsTable->AddressOfCallBacks);
2230   W.printHex("SizeOfZeroFill", TlsTable->SizeOfZeroFill);
2231   W.printFlags("Characteristics", TlsTable->Characteristics,
2232                ArrayRef(ImageSectionCharacteristics),
2233                COFF::SectionCharacteristics(COFF::IMAGE_SCN_ALIGN_MASK));
2234 }
2235