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