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