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