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