1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements the COFF-specific dumper for llvm-readobj.
13 //===----------------------------------------------------------------------===//
15 #include "ARMWinEHPrinter.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"
59 #include <system_error>
63 using namespace llvm::object;
64 using namespace llvm::codeview;
65 using namespace llvm::support;
66 using namespace llvm::Win64EH;
70 class COFFDumper : public ObjDumper {
72 friend class COFFObjectDumpDelegate;
73 COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
74 : ObjDumper(Writer), Obj(Obj), Writer(Writer), TypeDB(100) {}
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;
93 void printSymbol(const SymbolRef &Sym);
94 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
96 void printDataDirectory(uint32_t Index, const std::string &FieldName);
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);
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);
113 void printCodeViewSymbolsSubsection(StringRef Subsection,
114 const SectionRef &Section,
115 StringRef SectionContents);
117 void printCodeViewFileChecksums(StringRef Subsection);
119 void printCodeViewInlineeLines(StringRef Subsection);
121 void printRelocatedField(StringRef Label, const coff_section *Sec,
122 uint32_t RelocOffset, uint32_t Offset,
123 StringRef *RelocSym = nullptr);
125 void printResourceDirectoryTable(ResourceSectionRef RSF,
126 const coff_resource_dir_table &Table,
129 void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
130 StringRef SectionContents, StringRef Block);
132 /// Given a .debug$S section, find the string table and file checksum table.
133 void initializeFileAndStringTables(BinaryStreamReader &Reader);
135 void cacheRelocations();
137 std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
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,
152 typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
154 const llvm::object::COFFObjectFile *Obj;
155 bool RelocCached = false;
158 BinaryByteStream ChecksumContents;
159 VarStreamArray<FileChecksumEntry> CVFileChecksumTable;
161 BinaryByteStream StringTableContents;
162 StringTableRef CVStringTable;
164 ScopedPrinter &Writer;
168 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
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);
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));
182 return Data.data() - SectionContents.bytes_begin();
185 void printRelocatedField(StringRef Label, uint32_t RelocOffset,
186 uint32_t Offset, StringRef *RelocSym) override {
187 CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
190 void printBinaryBlockWithRelocs(StringRef Label,
191 ArrayRef<uint8_t> Block) override {
192 StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
194 if (opts::CodeViewSubsectionBytes)
195 CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
198 StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
199 return CD.getFileNameForFileOffset(FileOffset);
202 StringTableRef getStringTable() override { return CD.CVStringTable; }
206 const SectionRef &SR;
207 const coff_section *Sec;
208 StringRef SectionContents;
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);
220 return readobj_error::unsupported_obj_file_format;
222 Result.reset(new COFFDumper(COFFObj, Writer));
223 return readobj_error::success;
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) {
233 const auto &Relocations = RelocMap[Section];
234 auto SymI = Obj->symbol_end();
235 for (const auto &Relocation : Relocations) {
236 uint64_t RelocationOffset = Relocation.getOffset();
238 if (RelocationOffset == Offset) {
239 SymI = Relocation.getSymbol();
243 if (SymI == Obj->symbol_end())
244 return readobj_error::unknown_symbol;
246 return readobj_error::success;
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,
255 if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
257 Expected<StringRef> NameOrErr = Symbol.getName();
259 return errorToErrorCode(NameOrErr.takeError());
261 return std::error_code();
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,
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);
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);
286 W.printHex(Label, RelocOffset);
289 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
290 const SectionRef &Sec,
291 StringRef SectionContents,
293 W.printBinaryBlock(Label, Block);
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();
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);
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)
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 )
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 ),
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),
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 )
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 }
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 }
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 }
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 }
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 },
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 }
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),
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),
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),
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}};
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;
578 void COFFDumper::cacheRelocations() {
583 for (const SectionRef &S : Obj->sections()) {
584 const coff_section *Section = Obj->getCOFFSection(S);
586 for (const RelocationRef &Reloc : S.relocations())
587 RelocMap[Section].push_back(Reloc);
589 // Sort relocations by address.
590 std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
595 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
596 const data_directory *Data;
597 if (Obj->getDataDirectory(Index, Data))
599 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
600 W.printHex(FieldName + "Size", Data->Size);
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));
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));
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));
626 printPEHeader<pe32_header>(PEHeader);
628 const pe32plus_header *PEPlusHeader = nullptr;
629 error(Obj->getPE32PlusHeader(PEPlusHeader));
631 printPEHeader<pe32plus_header>(PEPlusHeader);
633 if (const dos_header *DH = Obj->getDOSHeader())
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);
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);
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"
700 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
701 printDataDirectory(i, directory[i]);
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);
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;
736 Obj->getRvaAndSizeAsBytes(D.AddressOfRawData, D.SizeOfData, RawData));
737 W.printBinaryBlock("RawData", RawData);
742 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
743 W.printHex("BaseOfData", Hdr->BaseOfData);
746 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
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);
756 for (const SectionRef &S : Obj->sections()) {
757 StringRef SectionName;
758 error(S.getName(SectionName));
759 if (SectionName == ".debug$S")
760 printCodeViewSymbolSection(SectionName, S);
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));
774 error(Reader.readFixedString(Contents, SubSectionSize));
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()));
783 case ModuleDebugFragmentKind::StringTable: {
784 StringTableContents = BinaryByteStream(Contents, support::little);
785 error(CVStringTable.initialize(StringTableContents));
791 uint32_t PaddedSize = alignTo(SubSectionSize, 4);
792 error(Reader.skip(PaddedSize - SubSectionSize));
796 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
797 const SectionRef &Section) {
798 StringRef SectionContents;
799 error(Section.getContents(SectionContents));
800 StringRef Data = SectionContents;
802 SmallVector<StringRef, 10> FunctionNames;
803 StringMap<StringRef> FunctionLineTables;
805 ListScope D(W, "CodeViewDebugInfo");
806 // Print the section to allow correlation with printSections.
807 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
810 error(consume(Data, Magic));
811 W.printHex("Magic", Magic);
812 if (Magic != COFF::DEBUG_SECTION_MAGIC)
813 return error(object_error::parse_failed);
815 BinaryByteStream FileAndStrings(Data, support::little);
816 BinaryStreamReader FSReader(FileAndStrings);
817 initializeFileAndStringTables(FSReader);
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));
827 ListScope S(W, "Subsection");
828 W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
829 W.printHex("SubSectionSize", SubSectionSize);
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);
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);
845 // Optionally print the subsection bytes in case our parsing gets confused
847 if (opts::CodeViewSubsectionBytes)
848 printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
851 switch (ModuleDebugFragmentKind(SubType)) {
852 case ModuleDebugFragmentKind::Symbols:
853 printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
856 case ModuleDebugFragmentKind::InlineeLines:
857 printCodeViewInlineeLines(Contents);
860 case ModuleDebugFragmentKind::FileChecksums:
861 printCodeViewFileChecksums(Contents);
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.
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);
876 StringRef LinkageName;
877 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
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);
886 FunctionLineTables[LinkageName] = Contents;
887 FunctionNames.push_back(LinkageName);
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);
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()) {
905 error(SR.readObject(FD));
907 StringRef FrameFunc = error(CVStringTable.getString(FD->FrameFunc));
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));
923 // Do nothing for unrecognized subsections.
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);
937 BinaryByteStream LineTableInfo(FunctionLineTables[Name], support::little);
938 BinaryStreamReader Reader(LineTableInfo);
940 ModuleDebugLineFragmentRef LineInfo;
941 error(LineInfo.initialize(Reader));
943 W.printHex("Flags", LineInfo.header()->Flags);
944 W.printHex("CodeSize", LineInfo.header()->CodeSize);
945 for (const auto &Entry : LineInfo) {
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);
956 std::string PC = formatv("+{0:X}", uint32_t(Line.Offset));
957 ListScope PCScope(W, PC);
958 codeview::LineInfo LI(Line.Flags);
960 if (LI.isAlwaysStepInto())
961 W.printString("StepInto", StringRef("Always"));
962 else if (LI.isNeverStepInto())
963 W.printString("StepInto", StringRef("Never"));
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);
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,
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));
994 error(object_error::parse_failed);
997 if (auto EC = CVSD.dump(Symbols)) {
999 error(std::move(EC));
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));
1010 for (auto &FC : Checksums) {
1011 DictScope S(W, "FileChecksum");
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));
1019 W.printBinary("ChecksumBytes", FC.Checksum);
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));
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);
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);
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);
1050 auto Iter = CVFileChecksumTable.at(FileOffset);
1052 // Check if the file checksum table offset is valid.
1053 if (Iter == CVFileChecksumTable.end())
1054 error(object_error::parse_failed);
1056 return error(CVStringTable.getString(Iter->FileNameOffset));
1059 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1060 W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
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") {
1070 error(S.getContents(Data));
1072 error(consume(Data, Magic));
1074 error(object_error::parse_failed);
1075 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(Data.data()),
1077 BinaryByteStream Stream(Bytes, llvm::support::little);
1079 BinaryStreamReader Reader(Stream);
1080 if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1081 consumeError(std::move(EC));
1083 error(object_error::parse_failed);
1086 if (auto EC = mergeTypeStreams(CVIDs, CVTypes, nullptr, Types))
1087 return error(std::move(EC));
1092 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1093 const SectionRef &Section) {
1094 ListScope D(W, "CodeViewTypes");
1095 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1098 error(Section.getContents(Data));
1099 if (opts::CodeViewSubsectionBytes)
1100 W.printBinaryBlock("Data", Data);
1103 error(consume(Data, Magic));
1104 W.printHex("Magic", Magic);
1105 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1106 return error(object_error::parse_failed);
1108 CVTypeDumper CVTD(TypeDB);
1109 TypeDumpVisitor TDV(TypeDB, &W, opts::CodeViewSubsectionBytes);
1110 if (auto EC = CVTD.dump({Data.bytes_begin(), Data.bytes_end()}, TDV)) {
1112 error(llvm::errorToErrorCode(std::move(EC)));
1116 void COFFDumper::printSections() {
1117 ListScope SectionsD(W, "Sections");
1118 int SectionNumber = 0;
1119 for (const SectionRef &Sec : Obj->sections()) {
1121 const coff_section *Section = Obj->getCOFFSection(Sec);
1124 error(Sec.getName(Name));
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));
1141 if (opts::SectionRelocations) {
1142 ListScope D(W, "Relocations");
1143 for (const RelocationRef &Reloc : Sec.relocations())
1144 printRelocation(Sec, Reloc);
1147 if (opts::SectionSymbols) {
1148 ListScope D(W, "Symbols");
1149 for (const SymbolRef &Symbol : Obj->symbols()) {
1150 if (!Sec.containsSymbol(Symbol))
1153 printSymbol(Symbol);
1157 if (opts::SectionData &&
1158 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1160 error(Sec.getContents(Data));
1162 W.printBinaryBlock("SectionData", Data);
1167 void COFFDumper::printRelocations() {
1168 ListScope D(W, "Relocations");
1170 int SectionNumber = 0;
1171 for (const SectionRef &Section : Obj->sections()) {
1174 error(Section.getName(Name));
1176 bool PrintedGroup = false;
1177 for (const RelocationRef &Reloc : Section.relocations()) {
1178 if (!PrintedGroup) {
1179 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1181 PrintedGroup = true;
1184 printRelocation(Section, Reloc);
1189 W.startLine() << "}\n";
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;
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);
1214 raw_ostream& OS = W.startLine();
1217 << " " << (SymbolName.empty() ? "-" : SymbolName)
1222 void COFFDumper::printSymbols() {
1223 ListScope Group(W, "Symbols");
1225 for (const SymbolRef &Symbol : Obj->symbols())
1226 printSymbol(Symbol);
1229 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1231 static ErrorOr<StringRef>
1232 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1233 const coff_section *Section) {
1235 StringRef SectionName;
1236 if (std::error_code EC = Obj->getSectionName(Section, SectionName))
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("");
1249 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1250 DictScope D(W, "Symbol");
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";
1260 StringRef SymbolName;
1261 if (Obj->getSymbolName(Symbol, SymbolName))
1264 StringRef SectionName = "";
1265 ErrorOr<StringRef> Res =
1266 getSectionName(Obj, Symbol.getSectionNumber(), Section);
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());
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));
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);
1291 } else if (Symbol.isAnyUndefined()) {
1292 const coff_aux_weak_external *Aux;
1293 error(getSymbolAuxData(Obj, Symbol, I, Aux));
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))) {
1303 DictScope AS(W, "AuxWeakExternal");
1304 W.printNumber("Linked", LinkedName, Aux->TagIndex);
1305 W.printEnum ("Search", Aux->Characteristics,
1306 makeArrayRef(WeakExternalCharacteristics));
1308 } else if (Symbol.isFileRecord()) {
1309 const char *FileName;
1310 error(getSymbolAuxData(Obj, Symbol, I, FileName));
1312 DictScope AS(W, "AuxFileRecord");
1314 StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1315 Obj->getSymbolTableEntrySize());
1316 W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1318 } else if (Symbol.isSectionDefinition()) {
1319 const coff_aux_section_definition *Aux;
1320 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1322 int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
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));
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);
1341 EC = Res.getError();
1347 W.printNumber("AssocSection", AssocName, AuxNumber);
1349 } else if (Symbol.isCLRToken()) {
1350 const coff_aux_clr_token *Aux;
1351 error(getSymbolAuxData(Obj, Symbol, I, Aux));
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))) {
1362 DictScope AS(W, "AuxCLRToken");
1363 W.printNumber("AuxType", Aux->AuxType);
1364 W.printNumber("Reserved", Aux->Reserved);
1365 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1368 W.startLine() << "<unhandled auxiliary record>\n";
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);
1384 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1385 Dumper.printData(Ctx);
1388 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1389 ARM::WinEH::Decoder Decoder(W);
1390 Decoder.dumpProcedureData(*Obj);
1394 W.printEnum("unsupported Image Machine", Obj->getMachine(),
1395 makeArrayRef(ImageFileMachineType));
1400 void COFFDumper::printImportedSymbols(
1401 iterator_range<imported_symbol_iterator> Range) {
1402 for (const ImportedSymbolRef &I : Range) {
1404 error(I.getSymbolName(Sym));
1406 error(I.getOrdinal(Ordinal));
1407 W.printNumber("Symbol", Sym, Ordinal);
1411 void COFFDumper::printDelayImportedSymbols(
1412 const DelayImportDirectoryEntryRef &I,
1413 iterator_range<imported_symbol_iterator> Range) {
1415 for (const ImportedSymbolRef &S : Range) {
1416 DictScope Import(W, "Import");
1418 error(S.getSymbolName(Sym));
1420 error(S.getOrdinal(Ordinal));
1421 W.printNumber("Symbol", Sym, Ordinal);
1423 error(I.getImportAddress(Index++, Addr));
1424 W.printHex("Address", Addr);
1428 void COFFDumper::printCOFFImports() {
1430 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1431 DictScope Import(W, "Import");
1433 error(I.getName(Name));
1434 W.printString("Name", Name);
1436 error(I.getImportLookupTableRVA(ILTAddr));
1437 W.printHex("ImportLookupTableRVA", ILTAddr);
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.
1444 printImportedSymbols(I.lookup_table_symbols());
1446 printImportedSymbols(I.imported_symbols());
1450 for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1451 DictScope Import(W, "DelayImport");
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());
1467 void COFFDumper::printCOFFExports() {
1468 for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1469 DictScope Export(W, "Export");
1472 uint32_t Ordinal, RVA;
1474 error(E.getSymbolName(Name));
1475 error(E.getOrdinal(Ordinal));
1476 error(E.getExportRVA(RVA));
1478 W.printNumber("Ordinal", Ordinal);
1479 W.printString("Name", Name);
1480 W.printHex("RVA", RVA);
1484 void COFFDumper::printCOFFDirectives() {
1485 for (const SectionRef &Section : Obj->sections()) {
1489 error(Section.getName(Name));
1490 if (Name != ".drectve")
1493 error(Section.getContents(Contents));
1495 W.printString("Directive(s)", Contents);
1499 static StringRef getBaseRelocTypeName(uint8_t 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) + ")";
1512 void COFFDumper::printCOFFBaseReloc() {
1513 ListScope D(W, "BaseReloc");
1514 for (const BaseRelocRef &I : Obj->base_relocs()) {
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);
1525 void COFFDumper::printCOFFResources() {
1526 ListScope ResourcesD(W, "Resources");
1527 for (const SectionRef &S : Obj->sections()) {
1529 error(S.getName(Name));
1530 if (!Name.startswith(".rsrc"))
1534 error(S.getContents(Ref));
1536 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1537 ResourceSectionRef RSF(Ref);
1538 auto &BaseTable = unwrapOrError(RSF.getBaseTable());
1539 printResourceDirectoryTable(RSF, BaseTable, "Type");
1541 if (opts::SectionData)
1542 W.printBinaryBlock(Name.str() + " Data", Ref);
1546 void COFFDumper::printResourceDirectoryTable(
1547 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1549 W.printNumber("String Name Entries", Table.NumberOfNameEntries);
1550 W.printNumber("ID Entries", Table.NumberOfIDEntries);
1552 char FormattedTime[20] = {};
1553 time_t TDS = time_t(Table.TimeDateStamp);
1554 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1556 // Iterate through level in resource directory tree.
1557 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1559 auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
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);
1569 OS << EntryNameString;
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);
1577 OS << ": (ID " << Entry.Identifier.ID << ")";
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";
1588 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1589 printResourceDirectoryTable(RSF, NextTable, NextLevel);
1591 W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1592 W.printNumber("Major Version", Table.MajorVersion);
1593 W.printNumber("Minor Version", Table.MinorVersion);
1598 ErrorOr<const coff_resource_dir_entry &>
1599 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
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];
1607 void COFFDumper::printStackMap() const {
1608 object::SectionRef StackMapSection;
1609 for (auto Sec : Obj->sections()) {
1612 if (Name == ".llvm_stackmaps") {
1613 StackMapSection = Sec;
1618 if (StackMapSection == object::SectionRef())
1621 StringRef StackMapContents;
1622 StackMapSection.getContents(StackMapContents);
1623 ArrayRef<uint8_t> StackMapContentsArray(
1624 reinterpret_cast<const uint8_t*>(StackMapContents.data()),
1625 StackMapContents.size());
1627 if (Obj->isLittleEndian())
1628 prettyPrintStackMap(
1630 StackMapV2Parser<support::little>(StackMapContentsArray));
1632 prettyPrintStackMap(llvm::outs(),
1633 StackMapV2Parser<support::big>(StackMapContentsArray));
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());
1645 TypeDatabase TypeDB(CVTypes.records().size());
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)) {
1653 error(std::move(EC));
1657 // Flatten the id stream and print it next. The ID stream refers to names from
1659 SmallString<0> IDBuf;
1660 IDTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Record) {
1661 IDBuf.append(Record.begin(), Record.end());
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)) {
1673 error(std::move(EC));