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