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 /// This file implements the COFF-specific dumper for llvm-readobj.
13 //===----------------------------------------------------------------------===//
15 #include "ARMWinEHPrinter.h"
17 #include "ObjDumper.h"
18 #include "StackMapPrinter.h"
19 #include "Win64EHDumper.h"
20 #include "llvm-readobj.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/BinaryFormat/COFF.h"
25 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
26 #include "llvm/DebugInfo/CodeView/CodeView.h"
27 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
31 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
32 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
33 #include "llvm/DebugInfo/CodeView/Line.h"
34 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
35 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
37 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
38 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
39 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
40 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
41 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
42 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
43 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
44 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
45 #include "llvm/Object/COFF.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Support/BinaryStreamReader.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/LEB128.h"
54 #include "llvm/Support/Win64EH.h"
55 #include "llvm/Support/raw_ostream.h"
58 using namespace llvm::object
;
59 using namespace llvm::codeview
;
60 using namespace llvm::support
;
61 using namespace llvm::Win64EH
;
65 struct LoadConfigTables
{
66 uint64_t SEHTableVA
= 0;
67 uint64_t SEHTableCount
= 0;
68 uint32_t GuardFlags
= 0;
69 uint64_t GuardFidTableVA
= 0;
70 uint64_t GuardFidTableCount
= 0;
71 uint64_t GuardLJmpTableVA
= 0;
72 uint64_t GuardLJmpTableCount
= 0;
75 class COFFDumper
: public ObjDumper
{
77 friend class COFFObjectDumpDelegate
;
78 COFFDumper(const llvm::object::COFFObjectFile
*Obj
, ScopedPrinter
&Writer
)
79 : ObjDumper(Writer
), Obj(Obj
), Writer(Writer
), Types(100) {}
81 void printFileHeaders() override
;
82 void printSections() override
;
83 void printRelocations() override
;
84 void printSymbols() override
;
85 void printDynamicSymbols() override
;
86 void printUnwindInfo() override
;
88 void printNeededLibraries() override
;
90 void printCOFFImports() override
;
91 void printCOFFExports() override
;
92 void printCOFFDirectives() override
;
93 void printCOFFBaseReloc() override
;
94 void printCOFFDebugDirectory() override
;
95 void printCOFFResources() override
;
96 void printCOFFLoadConfig() override
;
97 void printCodeViewDebugInfo() override
;
99 mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder
&CVIDs
,
100 llvm::codeview::MergingTypeTableBuilder
&CVTypes
) override
;
101 void printStackMap() const override
;
102 void printAddrsig() override
;
104 void printSymbol(const SymbolRef
&Sym
);
105 void printRelocation(const SectionRef
&Section
, const RelocationRef
&Reloc
,
107 void printDataDirectory(uint32_t Index
, const std::string
&FieldName
);
109 void printDOSHeader(const dos_header
*DH
);
110 template <class PEHeader
> void printPEHeader(const PEHeader
*Hdr
);
111 void printBaseOfDataField(const pe32_header
*Hdr
);
112 void printBaseOfDataField(const pe32plus_header
*Hdr
);
113 template <typename T
>
114 void printCOFFLoadConfig(const T
*Conf
, LoadConfigTables
&Tables
);
115 typedef void (*PrintExtraCB
)(raw_ostream
&, const uint8_t *);
116 void printRVATable(uint64_t TableVA
, uint64_t Count
, uint64_t EntrySize
,
117 PrintExtraCB PrintExtra
= 0);
119 void printCodeViewSymbolSection(StringRef SectionName
, const SectionRef
&Section
);
120 void printCodeViewTypeSection(StringRef SectionName
, const SectionRef
&Section
);
121 StringRef
getTypeName(TypeIndex Ty
);
122 StringRef
getFileNameForFileOffset(uint32_t FileOffset
);
123 void printFileNameForOffset(StringRef Label
, uint32_t FileOffset
);
124 void printTypeIndex(StringRef FieldName
, TypeIndex TI
) {
125 // Forward to CVTypeDumper for simplicity.
126 codeview::printTypeIndex(Writer
, FieldName
, TI
, Types
);
129 void printCodeViewSymbolsSubsection(StringRef Subsection
,
130 const SectionRef
&Section
,
131 StringRef SectionContents
);
133 void printCodeViewFileChecksums(StringRef Subsection
);
135 void printCodeViewInlineeLines(StringRef Subsection
);
137 void printRelocatedField(StringRef Label
, const coff_section
*Sec
,
138 uint32_t RelocOffset
, uint32_t Offset
,
139 StringRef
*RelocSym
= nullptr);
141 uint32_t countTotalTableEntries(ResourceSectionRef RSF
,
142 const coff_resource_dir_table
&Table
,
145 void printResourceDirectoryTable(ResourceSectionRef RSF
,
146 const coff_resource_dir_table
&Table
,
149 void printBinaryBlockWithRelocs(StringRef Label
, const SectionRef
&Sec
,
150 StringRef SectionContents
, StringRef Block
);
152 /// Given a .debug$S section, find the string table and file checksum table.
153 void initializeFileAndStringTables(BinaryStreamReader
&Reader
);
155 void cacheRelocations();
157 std::error_code
resolveSymbol(const coff_section
*Section
, uint64_t Offset
,
159 std::error_code
resolveSymbolName(const coff_section
*Section
,
160 uint64_t Offset
, StringRef
&Name
);
161 std::error_code
resolveSymbolName(const coff_section
*Section
,
162 StringRef SectionContents
,
163 const void *RelocPtr
, StringRef
&Name
);
164 void printImportedSymbols(iterator_range
<imported_symbol_iterator
> Range
);
165 void printDelayImportedSymbols(
166 const DelayImportDirectoryEntryRef
&I
,
167 iterator_range
<imported_symbol_iterator
> Range
);
168 ErrorOr
<const coff_resource_dir_entry
&>
169 getResourceDirectoryTableEntry(const coff_resource_dir_table
&Table
,
172 typedef DenseMap
<const coff_section
*, std::vector
<RelocationRef
> > RelocMapTy
;
174 const llvm::object::COFFObjectFile
*Obj
;
175 bool RelocCached
= false;
178 DebugChecksumsSubsectionRef CVFileChecksumTable
;
180 DebugStringTableSubsectionRef CVStringTable
;
182 /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
183 /// first, but if we don't see one, just assume an X64 CPU type. It is common.
184 CPUType CompilationCPUType
= CPUType::X64
;
186 ScopedPrinter
&Writer
;
187 BinaryByteStream TypeContents
;
188 LazyRandomTypeCollection Types
;
191 class COFFObjectDumpDelegate
: public SymbolDumpDelegate
{
193 COFFObjectDumpDelegate(COFFDumper
&CD
, const SectionRef
&SR
,
194 const COFFObjectFile
*Obj
, StringRef SectionContents
)
195 : CD(CD
), SR(SR
), SectionContents(SectionContents
) {
196 Sec
= Obj
->getCOFFSection(SR
);
199 uint32_t getRecordOffset(BinaryStreamReader Reader
) override
{
200 ArrayRef
<uint8_t> Data
;
201 if (auto EC
= Reader
.readLongestContiguousChunk(Data
)) {
202 llvm::consumeError(std::move(EC
));
205 return Data
.data() - SectionContents
.bytes_begin();
208 void printRelocatedField(StringRef Label
, uint32_t RelocOffset
,
209 uint32_t Offset
, StringRef
*RelocSym
) override
{
210 CD
.printRelocatedField(Label
, Sec
, RelocOffset
, Offset
, RelocSym
);
213 void printBinaryBlockWithRelocs(StringRef Label
,
214 ArrayRef
<uint8_t> Block
) override
{
215 StringRef
SBlock(reinterpret_cast<const char *>(Block
.data()),
217 if (opts::CodeViewSubsectionBytes
)
218 CD
.printBinaryBlockWithRelocs(Label
, SR
, SectionContents
, SBlock
);
221 StringRef
getFileNameForFileOffset(uint32_t FileOffset
) override
{
222 return CD
.getFileNameForFileOffset(FileOffset
);
225 DebugStringTableSubsectionRef
getStringTable() override
{
226 return CD
.CVStringTable
;
231 const SectionRef
&SR
;
232 const coff_section
*Sec
;
233 StringRef SectionContents
;
240 std::error_code
createCOFFDumper(const object::ObjectFile
*Obj
,
241 ScopedPrinter
&Writer
,
242 std::unique_ptr
<ObjDumper
> &Result
) {
243 const COFFObjectFile
*COFFObj
= dyn_cast
<COFFObjectFile
>(Obj
);
245 return readobj_error::unsupported_obj_file_format
;
247 Result
.reset(new COFFDumper(COFFObj
, Writer
));
248 return readobj_error::success
;
253 // Given a section and an offset into this section the function returns the
254 // symbol used for the relocation at the offset.
255 std::error_code
COFFDumper::resolveSymbol(const coff_section
*Section
,
256 uint64_t Offset
, SymbolRef
&Sym
) {
258 const auto &Relocations
= RelocMap
[Section
];
259 auto SymI
= Obj
->symbol_end();
260 for (const auto &Relocation
: Relocations
) {
261 uint64_t RelocationOffset
= Relocation
.getOffset();
263 if (RelocationOffset
== Offset
) {
264 SymI
= Relocation
.getSymbol();
268 if (SymI
== Obj
->symbol_end())
269 return readobj_error::unknown_symbol
;
271 return readobj_error::success
;
274 // Given a section and an offset into this section the function returns the name
275 // of the symbol used for the relocation at the offset.
276 std::error_code
COFFDumper::resolveSymbolName(const coff_section
*Section
,
280 if (std::error_code EC
= resolveSymbol(Section
, Offset
, Symbol
))
282 Expected
<StringRef
> NameOrErr
= Symbol
.getName();
284 return errorToErrorCode(NameOrErr
.takeError());
286 return std::error_code();
289 // Helper for when you have a pointer to real data and you want to know about
290 // relocations against it.
291 std::error_code
COFFDumper::resolveSymbolName(const coff_section
*Section
,
292 StringRef SectionContents
,
293 const void *RelocPtr
,
295 assert(SectionContents
.data() < RelocPtr
&&
296 RelocPtr
< SectionContents
.data() + SectionContents
.size() &&
297 "pointer to relocated object is not in section");
298 uint64_t Offset
= ptrdiff_t(reinterpret_cast<const char *>(RelocPtr
) -
299 SectionContents
.data());
300 return resolveSymbolName(Section
, Offset
, Name
);
303 void COFFDumper::printRelocatedField(StringRef Label
, const coff_section
*Sec
,
304 uint32_t RelocOffset
, uint32_t Offset
,
305 StringRef
*RelocSym
) {
306 StringRef SymStorage
;
307 StringRef
&Symbol
= RelocSym
? *RelocSym
: SymStorage
;
308 if (!resolveSymbolName(Sec
, RelocOffset
, Symbol
))
309 W
.printSymbolOffset(Label
, Symbol
, Offset
);
311 W
.printHex(Label
, RelocOffset
);
314 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label
,
315 const SectionRef
&Sec
,
316 StringRef SectionContents
,
318 W
.printBinaryBlock(Label
, Block
);
320 assert(SectionContents
.begin() < Block
.begin() &&
321 SectionContents
.end() >= Block
.end() &&
322 "Block is not contained in SectionContents");
323 uint64_t OffsetStart
= Block
.data() - SectionContents
.data();
324 uint64_t OffsetEnd
= OffsetStart
+ Block
.size();
328 ListScope
D(W
, "BlockRelocations");
329 const coff_section
*Section
= Obj
->getCOFFSection(Sec
);
330 const auto &Relocations
= RelocMap
[Section
];
331 for (const auto &Relocation
: Relocations
) {
332 uint64_t RelocationOffset
= Relocation
.getOffset();
333 if (OffsetStart
<= RelocationOffset
&& RelocationOffset
< OffsetEnd
)
334 printRelocation(Sec
, Relocation
, OffsetStart
);
338 static const EnumEntry
<COFF::MachineTypes
> ImageFileMachineType
[] = {
339 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_UNKNOWN
),
340 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_AM33
),
341 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_AMD64
),
342 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARM
),
343 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARM64
),
344 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARMNT
),
345 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_EBC
),
346 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_I386
),
347 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_IA64
),
348 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_M32R
),
349 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPS16
),
350 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPSFPU
),
351 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPSFPU16
),
352 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_POWERPC
),
353 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_POWERPCFP
),
354 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_R4000
),
355 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH3
),
356 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH3DSP
),
357 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH4
),
358 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH5
),
359 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_THUMB
),
360 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_WCEMIPSV2
)
363 static const EnumEntry
<COFF::Characteristics
> ImageFileCharacteristics
[] = {
364 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_RELOCS_STRIPPED
),
365 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_EXECUTABLE_IMAGE
),
366 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LINE_NUMS_STRIPPED
),
367 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LOCAL_SYMS_STRIPPED
),
368 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_AGGRESSIVE_WS_TRIM
),
369 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LARGE_ADDRESS_AWARE
),
370 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_BYTES_REVERSED_LO
),
371 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_32BIT_MACHINE
),
372 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_DEBUG_STRIPPED
),
373 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP
),
374 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_NET_RUN_FROM_SWAP
),
375 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_SYSTEM
),
376 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_DLL
),
377 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_UP_SYSTEM_ONLY
),
378 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_BYTES_REVERSED_HI
)
381 static const EnumEntry
<COFF::WindowsSubsystem
> PEWindowsSubsystem
[] = {
382 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_UNKNOWN
),
383 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_NATIVE
),
384 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_GUI
),
385 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_CUI
),
386 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_POSIX_CUI
),
387 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI
),
388 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_APPLICATION
),
389 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER
),
390 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER
),
391 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_ROM
),
392 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_XBOX
),
395 static const EnumEntry
<COFF::DLLCharacteristics
> PEDLLCharacteristics
[] = {
396 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA
),
397 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
),
398 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY
),
399 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
),
400 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION
),
401 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_SEH
),
402 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_BIND
),
403 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER
),
404 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER
),
405 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_GUARD_CF
),
406 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE
),
409 static const EnumEntry
<COFF::SectionCharacteristics
>
410 ImageSectionCharacteristics
[] = {
411 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_TYPE_NOLOAD
),
412 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_TYPE_NO_PAD
),
413 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_CODE
),
414 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_INITIALIZED_DATA
),
415 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_UNINITIALIZED_DATA
),
416 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_OTHER
),
417 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_INFO
),
418 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_REMOVE
),
419 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_COMDAT
),
420 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_GPREL
),
421 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_PURGEABLE
),
422 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_16BIT
),
423 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_LOCKED
),
424 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_PRELOAD
),
425 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_1BYTES
),
426 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_2BYTES
),
427 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_4BYTES
),
428 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_8BYTES
),
429 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_16BYTES
),
430 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_32BYTES
),
431 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_64BYTES
),
432 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_128BYTES
),
433 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_256BYTES
),
434 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_512BYTES
),
435 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_1024BYTES
),
436 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_2048BYTES
),
437 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_4096BYTES
),
438 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_8192BYTES
),
439 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_NRELOC_OVFL
),
440 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_DISCARDABLE
),
441 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_NOT_CACHED
),
442 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_NOT_PAGED
),
443 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_SHARED
),
444 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_EXECUTE
),
445 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_READ
),
446 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_WRITE
)
449 static const EnumEntry
<COFF::SymbolBaseType
> ImageSymType
[] = {
450 { "Null" , COFF::IMAGE_SYM_TYPE_NULL
},
451 { "Void" , COFF::IMAGE_SYM_TYPE_VOID
},
452 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR
},
453 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT
},
454 { "Int" , COFF::IMAGE_SYM_TYPE_INT
},
455 { "Long" , COFF::IMAGE_SYM_TYPE_LONG
},
456 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT
},
457 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE
},
458 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT
},
459 { "Union" , COFF::IMAGE_SYM_TYPE_UNION
},
460 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM
},
461 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE
},
462 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE
},
463 { "Word" , COFF::IMAGE_SYM_TYPE_WORD
},
464 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT
},
465 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD
}
468 static const EnumEntry
<COFF::SymbolComplexType
> ImageSymDType
[] = {
469 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL
},
470 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER
},
471 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION
},
472 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY
}
475 static const EnumEntry
<COFF::SymbolStorageClass
> ImageSymClass
[] = {
476 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION
},
477 { "Null" , COFF::IMAGE_SYM_CLASS_NULL
},
478 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC
},
479 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL
},
480 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC
},
481 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER
},
482 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF
},
483 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL
},
484 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL
},
485 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT
},
486 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT
},
487 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG
},
488 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION
},
489 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG
},
490 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION
},
491 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC
},
492 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG
},
493 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM
},
494 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM
},
495 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD
},
496 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK
},
497 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION
},
498 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT
},
499 { "File" , COFF::IMAGE_SYM_CLASS_FILE
},
500 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION
},
501 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL
},
502 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN
}
505 static const EnumEntry
<COFF::COMDATType
> ImageCOMDATSelect
[] = {
506 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES
},
507 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY
},
508 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE
},
509 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH
},
510 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
},
511 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST
},
512 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST
}
515 static const EnumEntry
<COFF::DebugType
> ImageDebugType
[] = {
516 { "Unknown" , COFF::IMAGE_DEBUG_TYPE_UNKNOWN
},
517 { "COFF" , COFF::IMAGE_DEBUG_TYPE_COFF
},
518 { "CodeView" , COFF::IMAGE_DEBUG_TYPE_CODEVIEW
},
519 { "FPO" , COFF::IMAGE_DEBUG_TYPE_FPO
},
520 { "Misc" , COFF::IMAGE_DEBUG_TYPE_MISC
},
521 { "Exception" , COFF::IMAGE_DEBUG_TYPE_EXCEPTION
},
522 { "Fixup" , COFF::IMAGE_DEBUG_TYPE_FIXUP
},
523 { "OmapToSrc" , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC
},
524 { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC
},
525 { "Borland" , COFF::IMAGE_DEBUG_TYPE_BORLAND
},
526 { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10
},
527 { "CLSID" , COFF::IMAGE_DEBUG_TYPE_CLSID
},
528 { "VCFeature" , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE
},
529 { "POGO" , COFF::IMAGE_DEBUG_TYPE_POGO
},
530 { "ILTCG" , COFF::IMAGE_DEBUG_TYPE_ILTCG
},
531 { "MPX" , COFF::IMAGE_DEBUG_TYPE_MPX
},
532 { "Repro" , COFF::IMAGE_DEBUG_TYPE_REPRO
},
535 static const EnumEntry
<COFF::WeakExternalCharacteristics
>
536 WeakExternalCharacteristics
[] = {
537 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY
},
538 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY
},
539 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS
}
542 static const EnumEntry
<uint32_t> SubSectionTypes
[] = {
543 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, Symbols
),
544 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, Lines
),
545 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, StringTable
),
546 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FileChecksums
),
547 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FrameData
),
548 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, InlineeLines
),
549 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CrossScopeImports
),
550 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CrossScopeExports
),
551 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, ILLines
),
552 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FuncMDTokenMap
),
553 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, TypeMDTokenMap
),
554 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, MergedAssemblyInput
),
555 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CoffSymbolRVA
),
558 static const EnumEntry
<uint32_t> FrameDataFlags
[] = {
559 LLVM_READOBJ_ENUM_ENT(FrameData
, HasSEH
),
560 LLVM_READOBJ_ENUM_ENT(FrameData
, HasEH
),
561 LLVM_READOBJ_ENUM_ENT(FrameData
, IsFunctionStart
),
564 static const EnumEntry
<uint8_t> FileChecksumKindNames
[] = {
565 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, None
),
566 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, MD5
),
567 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, SHA1
),
568 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, SHA256
),
571 static const EnumEntry
<COFF::ResourceTypeID
> ResourceTypeNames
[]{
572 {"kRT_CURSOR (ID 1)", COFF::RID_Cursor
},
573 {"kRT_BITMAP (ID 2)", COFF::RID_Bitmap
},
574 {"kRT_ICON (ID 3)", COFF::RID_Icon
},
575 {"kRT_MENU (ID 4)", COFF::RID_Menu
},
576 {"kRT_DIALOG (ID 5)", COFF::RID_Dialog
},
577 {"kRT_STRING (ID 6)", COFF::RID_String
},
578 {"kRT_FONTDIR (ID 7)", COFF::RID_FontDir
},
579 {"kRT_FONT (ID 8)", COFF::RID_Font
},
580 {"kRT_ACCELERATOR (ID 9)", COFF::RID_Accelerator
},
581 {"kRT_RCDATA (ID 10)", COFF::RID_RCData
},
582 {"kRT_MESSAGETABLE (ID 11)", COFF::RID_MessageTable
},
583 {"kRT_GROUP_CURSOR (ID 12)", COFF::RID_Group_Cursor
},
584 {"kRT_GROUP_ICON (ID 14)", COFF::RID_Group_Icon
},
585 {"kRT_VERSION (ID 16)", COFF::RID_Version
},
586 {"kRT_DLGINCLUDE (ID 17)", COFF::RID_DLGInclude
},
587 {"kRT_PLUGPLAY (ID 19)", COFF::RID_PlugPlay
},
588 {"kRT_VXD (ID 20)", COFF::RID_VXD
},
589 {"kRT_ANICURSOR (ID 21)", COFF::RID_AniCursor
},
590 {"kRT_ANIICON (ID 22)", COFF::RID_AniIcon
},
591 {"kRT_HTML (ID 23)", COFF::RID_HTML
},
592 {"kRT_MANIFEST (ID 24)", COFF::RID_Manifest
}};
594 template <typename T
>
595 static std::error_code
getSymbolAuxData(const COFFObjectFile
*Obj
,
596 COFFSymbolRef Symbol
,
597 uint8_t AuxSymbolIdx
, const T
*&Aux
) {
598 ArrayRef
<uint8_t> AuxData
= Obj
->getSymbolAuxData(Symbol
);
599 AuxData
= AuxData
.slice(AuxSymbolIdx
* Obj
->getSymbolTableEntrySize());
600 Aux
= reinterpret_cast<const T
*>(AuxData
.data());
601 return readobj_error::success
;
604 void COFFDumper::cacheRelocations() {
609 for (const SectionRef
&S
: Obj
->sections()) {
610 const coff_section
*Section
= Obj
->getCOFFSection(S
);
612 for (const RelocationRef
&Reloc
: S
.relocations())
613 RelocMap
[Section
].push_back(Reloc
);
615 // Sort relocations by address.
616 llvm::sort(RelocMap
[Section
], relocAddressLess
);
620 void COFFDumper::printDataDirectory(uint32_t Index
, const std::string
&FieldName
) {
621 const data_directory
*Data
;
622 if (Obj
->getDataDirectory(Index
, Data
))
624 W
.printHex(FieldName
+ "RVA", Data
->RelativeVirtualAddress
);
625 W
.printHex(FieldName
+ "Size", Data
->Size
);
628 void COFFDumper::printFileHeaders() {
629 time_t TDS
= Obj
->getTimeDateStamp();
630 char FormattedTime
[20] = { };
631 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
634 DictScope
D(W
, "ImageFileHeader");
635 W
.printEnum ("Machine", Obj
->getMachine(),
636 makeArrayRef(ImageFileMachineType
));
637 W
.printNumber("SectionCount", Obj
->getNumberOfSections());
638 W
.printHex ("TimeDateStamp", FormattedTime
, Obj
->getTimeDateStamp());
639 W
.printHex ("PointerToSymbolTable", Obj
->getPointerToSymbolTable());
640 W
.printNumber("SymbolCount", Obj
->getNumberOfSymbols());
641 W
.printNumber("OptionalHeaderSize", Obj
->getSizeOfOptionalHeader());
642 W
.printFlags ("Characteristics", Obj
->getCharacteristics(),
643 makeArrayRef(ImageFileCharacteristics
));
646 // Print PE header. This header does not exist if this is an object file and
647 // not an executable.
648 const pe32_header
*PEHeader
= nullptr;
649 error(Obj
->getPE32Header(PEHeader
));
651 printPEHeader
<pe32_header
>(PEHeader
);
653 const pe32plus_header
*PEPlusHeader
= nullptr;
654 error(Obj
->getPE32PlusHeader(PEPlusHeader
));
656 printPEHeader
<pe32plus_header
>(PEPlusHeader
);
658 if (const dos_header
*DH
= Obj
->getDOSHeader())
662 void COFFDumper::printDOSHeader(const dos_header
*DH
) {
663 DictScope
D(W
, "DOSHeader");
664 W
.printString("Magic", StringRef(DH
->Magic
, sizeof(DH
->Magic
)));
665 W
.printNumber("UsedBytesInTheLastPage", DH
->UsedBytesInTheLastPage
);
666 W
.printNumber("FileSizeInPages", DH
->FileSizeInPages
);
667 W
.printNumber("NumberOfRelocationItems", DH
->NumberOfRelocationItems
);
668 W
.printNumber("HeaderSizeInParagraphs", DH
->HeaderSizeInParagraphs
);
669 W
.printNumber("MinimumExtraParagraphs", DH
->MinimumExtraParagraphs
);
670 W
.printNumber("MaximumExtraParagraphs", DH
->MaximumExtraParagraphs
);
671 W
.printNumber("InitialRelativeSS", DH
->InitialRelativeSS
);
672 W
.printNumber("InitialSP", DH
->InitialSP
);
673 W
.printNumber("Checksum", DH
->Checksum
);
674 W
.printNumber("InitialIP", DH
->InitialIP
);
675 W
.printNumber("InitialRelativeCS", DH
->InitialRelativeCS
);
676 W
.printNumber("AddressOfRelocationTable", DH
->AddressOfRelocationTable
);
677 W
.printNumber("OverlayNumber", DH
->OverlayNumber
);
678 W
.printNumber("OEMid", DH
->OEMid
);
679 W
.printNumber("OEMinfo", DH
->OEMinfo
);
680 W
.printNumber("AddressOfNewExeHeader", DH
->AddressOfNewExeHeader
);
683 template <class PEHeader
>
684 void COFFDumper::printPEHeader(const PEHeader
*Hdr
) {
685 DictScope
D(W
, "ImageOptionalHeader");
686 W
.printHex ("Magic", Hdr
->Magic
);
687 W
.printNumber("MajorLinkerVersion", Hdr
->MajorLinkerVersion
);
688 W
.printNumber("MinorLinkerVersion", Hdr
->MinorLinkerVersion
);
689 W
.printNumber("SizeOfCode", Hdr
->SizeOfCode
);
690 W
.printNumber("SizeOfInitializedData", Hdr
->SizeOfInitializedData
);
691 W
.printNumber("SizeOfUninitializedData", Hdr
->SizeOfUninitializedData
);
692 W
.printHex ("AddressOfEntryPoint", Hdr
->AddressOfEntryPoint
);
693 W
.printHex ("BaseOfCode", Hdr
->BaseOfCode
);
694 printBaseOfDataField(Hdr
);
695 W
.printHex ("ImageBase", Hdr
->ImageBase
);
696 W
.printNumber("SectionAlignment", Hdr
->SectionAlignment
);
697 W
.printNumber("FileAlignment", Hdr
->FileAlignment
);
698 W
.printNumber("MajorOperatingSystemVersion",
699 Hdr
->MajorOperatingSystemVersion
);
700 W
.printNumber("MinorOperatingSystemVersion",
701 Hdr
->MinorOperatingSystemVersion
);
702 W
.printNumber("MajorImageVersion", Hdr
->MajorImageVersion
);
703 W
.printNumber("MinorImageVersion", Hdr
->MinorImageVersion
);
704 W
.printNumber("MajorSubsystemVersion", Hdr
->MajorSubsystemVersion
);
705 W
.printNumber("MinorSubsystemVersion", Hdr
->MinorSubsystemVersion
);
706 W
.printNumber("SizeOfImage", Hdr
->SizeOfImage
);
707 W
.printNumber("SizeOfHeaders", Hdr
->SizeOfHeaders
);
708 W
.printEnum ("Subsystem", Hdr
->Subsystem
, makeArrayRef(PEWindowsSubsystem
));
709 W
.printFlags ("Characteristics", Hdr
->DLLCharacteristics
,
710 makeArrayRef(PEDLLCharacteristics
));
711 W
.printNumber("SizeOfStackReserve", Hdr
->SizeOfStackReserve
);
712 W
.printNumber("SizeOfStackCommit", Hdr
->SizeOfStackCommit
);
713 W
.printNumber("SizeOfHeapReserve", Hdr
->SizeOfHeapReserve
);
714 W
.printNumber("SizeOfHeapCommit", Hdr
->SizeOfHeapCommit
);
715 W
.printNumber("NumberOfRvaAndSize", Hdr
->NumberOfRvaAndSize
);
717 if (Hdr
->NumberOfRvaAndSize
> 0) {
718 DictScope
D(W
, "DataDirectory");
719 static const char * const directory
[] = {
720 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
721 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
722 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
723 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
726 for (uint32_t i
= 0; i
< Hdr
->NumberOfRvaAndSize
; ++i
)
727 printDataDirectory(i
, directory
[i
]);
731 void COFFDumper::printCOFFDebugDirectory() {
732 ListScope
LS(W
, "DebugDirectory");
733 for (const debug_directory
&D
: Obj
->debug_directories()) {
734 char FormattedTime
[20] = {};
735 time_t TDS
= D
.TimeDateStamp
;
736 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
737 DictScope
S(W
, "DebugEntry");
738 W
.printHex("Characteristics", D
.Characteristics
);
739 W
.printHex("TimeDateStamp", FormattedTime
, D
.TimeDateStamp
);
740 W
.printHex("MajorVersion", D
.MajorVersion
);
741 W
.printHex("MinorVersion", D
.MinorVersion
);
742 W
.printEnum("Type", D
.Type
, makeArrayRef(ImageDebugType
));
743 W
.printHex("SizeOfData", D
.SizeOfData
);
744 W
.printHex("AddressOfRawData", D
.AddressOfRawData
);
745 W
.printHex("PointerToRawData", D
.PointerToRawData
);
746 if (D
.Type
== COFF::IMAGE_DEBUG_TYPE_CODEVIEW
) {
747 const codeview::DebugInfo
*DebugInfo
;
748 StringRef PDBFileName
;
749 error(Obj
->getDebugPDBInfo(&D
, DebugInfo
, PDBFileName
));
750 DictScope
PDBScope(W
, "PDBInfo");
751 W
.printHex("PDBSignature", DebugInfo
->Signature
.CVSignature
);
752 if (DebugInfo
->Signature
.CVSignature
== OMF::Signature::PDB70
) {
753 W
.printBinary("PDBGUID", makeArrayRef(DebugInfo
->PDB70
.Signature
));
754 W
.printNumber("PDBAge", DebugInfo
->PDB70
.Age
);
755 W
.printString("PDBFileName", PDBFileName
);
757 } else if (D
.SizeOfData
!= 0) {
758 // FIXME: Type values of 12 and 13 are commonly observed but are not in
759 // the documented type enum. Figure out what they mean.
760 ArrayRef
<uint8_t> RawData
;
762 Obj
->getRvaAndSizeAsBytes(D
.AddressOfRawData
, D
.SizeOfData
, RawData
));
763 W
.printBinaryBlock("RawData", RawData
);
768 void COFFDumper::printRVATable(uint64_t TableVA
, uint64_t Count
,
769 uint64_t EntrySize
, PrintExtraCB PrintExtra
) {
770 uintptr_t TableStart
, TableEnd
;
771 error(Obj
->getVaPtr(TableVA
, TableStart
));
772 error(Obj
->getVaPtr(TableVA
+ Count
* EntrySize
- 1, TableEnd
));
774 for (uintptr_t I
= TableStart
; I
< TableEnd
; I
+= EntrySize
) {
775 uint32_t RVA
= *reinterpret_cast<const ulittle32_t
*>(I
);
776 raw_ostream
&OS
= W
.startLine();
777 OS
<< W
.hex(Obj
->getImageBase() + RVA
);
779 PrintExtra(OS
, reinterpret_cast<const uint8_t *>(I
));
784 void COFFDumper::printCOFFLoadConfig() {
785 LoadConfigTables Tables
;
787 printCOFFLoadConfig(Obj
->getLoadConfig64(), Tables
);
789 printCOFFLoadConfig(Obj
->getLoadConfig32(), Tables
);
791 if (Tables
.SEHTableVA
) {
792 ListScope
LS(W
, "SEHTable");
793 printRVATable(Tables
.SEHTableVA
, Tables
.SEHTableCount
, 4);
796 if (Tables
.GuardFidTableVA
) {
797 ListScope
LS(W
, "GuardFidTable");
798 if (Tables
.GuardFlags
& uint32_t(coff_guard_flags::FidTableHasFlags
)) {
799 auto PrintGuardFlags
= [](raw_ostream
&OS
, const uint8_t *Entry
) {
800 uint8_t Flags
= *reinterpret_cast<const uint8_t *>(Entry
+ 4);
802 OS
<< " flags " << utohexstr(Flags
);
804 printRVATable(Tables
.GuardFidTableVA
, Tables
.GuardFidTableCount
, 5,
807 printRVATable(Tables
.GuardFidTableVA
, Tables
.GuardFidTableCount
, 4);
811 if (Tables
.GuardLJmpTableVA
) {
812 ListScope
LS(W
, "GuardLJmpTable");
813 printRVATable(Tables
.GuardLJmpTableVA
, Tables
.GuardLJmpTableCount
, 4);
817 template <typename T
>
818 void COFFDumper::printCOFFLoadConfig(const T
*Conf
, LoadConfigTables
&Tables
) {
822 ListScope
LS(W
, "LoadConfig");
823 char FormattedTime
[20] = {};
824 time_t TDS
= Conf
->TimeDateStamp
;
825 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
826 W
.printHex("Size", Conf
->Size
);
828 // Print everything before SecurityCookie. The vast majority of images today
829 // have all these fields.
830 if (Conf
->Size
< offsetof(T
, SEHandlerTable
))
832 W
.printHex("TimeDateStamp", FormattedTime
, TDS
);
833 W
.printHex("MajorVersion", Conf
->MajorVersion
);
834 W
.printHex("MinorVersion", Conf
->MinorVersion
);
835 W
.printHex("GlobalFlagsClear", Conf
->GlobalFlagsClear
);
836 W
.printHex("GlobalFlagsSet", Conf
->GlobalFlagsSet
);
837 W
.printHex("CriticalSectionDefaultTimeout",
838 Conf
->CriticalSectionDefaultTimeout
);
839 W
.printHex("DeCommitFreeBlockThreshold", Conf
->DeCommitFreeBlockThreshold
);
840 W
.printHex("DeCommitTotalFreeThreshold", Conf
->DeCommitTotalFreeThreshold
);
841 W
.printHex("LockPrefixTable", Conf
->LockPrefixTable
);
842 W
.printHex("MaximumAllocationSize", Conf
->MaximumAllocationSize
);
843 W
.printHex("VirtualMemoryThreshold", Conf
->VirtualMemoryThreshold
);
844 W
.printHex("ProcessHeapFlags", Conf
->ProcessHeapFlags
);
845 W
.printHex("ProcessAffinityMask", Conf
->ProcessAffinityMask
);
846 W
.printHex("CSDVersion", Conf
->CSDVersion
);
847 W
.printHex("DependentLoadFlags", Conf
->DependentLoadFlags
);
848 W
.printHex("EditList", Conf
->EditList
);
849 W
.printHex("SecurityCookie", Conf
->SecurityCookie
);
851 // Print the safe SEH table if present.
852 if (Conf
->Size
< offsetof(coff_load_configuration32
, GuardCFCheckFunction
))
854 W
.printHex("SEHandlerTable", Conf
->SEHandlerTable
);
855 W
.printNumber("SEHandlerCount", Conf
->SEHandlerCount
);
857 Tables
.SEHTableVA
= Conf
->SEHandlerTable
;
858 Tables
.SEHTableCount
= Conf
->SEHandlerCount
;
860 // Print everything before CodeIntegrity. (2015)
861 if (Conf
->Size
< offsetof(T
, CodeIntegrity
))
863 W
.printHex("GuardCFCheckFunction", Conf
->GuardCFCheckFunction
);
864 W
.printHex("GuardCFCheckDispatch", Conf
->GuardCFCheckDispatch
);
865 W
.printHex("GuardCFFunctionTable", Conf
->GuardCFFunctionTable
);
866 W
.printNumber("GuardCFFunctionCount", Conf
->GuardCFFunctionCount
);
867 W
.printHex("GuardFlags", Conf
->GuardFlags
);
869 Tables
.GuardFidTableVA
= Conf
->GuardCFFunctionTable
;
870 Tables
.GuardFidTableCount
= Conf
->GuardCFFunctionCount
;
871 Tables
.GuardFlags
= Conf
->GuardFlags
;
873 // Print the rest. (2017)
874 if (Conf
->Size
< sizeof(T
))
876 W
.printHex("GuardAddressTakenIatEntryTable",
877 Conf
->GuardAddressTakenIatEntryTable
);
878 W
.printNumber("GuardAddressTakenIatEntryCount",
879 Conf
->GuardAddressTakenIatEntryCount
);
880 W
.printHex("GuardLongJumpTargetTable", Conf
->GuardLongJumpTargetTable
);
881 W
.printNumber("GuardLongJumpTargetCount", Conf
->GuardLongJumpTargetCount
);
882 W
.printHex("DynamicValueRelocTable", Conf
->DynamicValueRelocTable
);
883 W
.printHex("CHPEMetadataPointer", Conf
->CHPEMetadataPointer
);
884 W
.printHex("GuardRFFailureRoutine", Conf
->GuardRFFailureRoutine
);
885 W
.printHex("GuardRFFailureRoutineFunctionPointer",
886 Conf
->GuardRFFailureRoutineFunctionPointer
);
887 W
.printHex("DynamicValueRelocTableOffset",
888 Conf
->DynamicValueRelocTableOffset
);
889 W
.printNumber("DynamicValueRelocTableSection",
890 Conf
->DynamicValueRelocTableSection
);
891 W
.printHex("GuardRFVerifyStackPointerFunctionPointer",
892 Conf
->GuardRFVerifyStackPointerFunctionPointer
);
893 W
.printHex("HotPatchTableOffset", Conf
->HotPatchTableOffset
);
895 Tables
.GuardLJmpTableVA
= Conf
->GuardLongJumpTargetTable
;
896 Tables
.GuardLJmpTableCount
= Conf
->GuardLongJumpTargetCount
;
899 void COFFDumper::printBaseOfDataField(const pe32_header
*Hdr
) {
900 W
.printHex("BaseOfData", Hdr
->BaseOfData
);
903 void COFFDumper::printBaseOfDataField(const pe32plus_header
*) {}
905 void COFFDumper::printCodeViewDebugInfo() {
906 // Print types first to build CVUDTNames, then print symbols.
907 for (const SectionRef
&S
: Obj
->sections()) {
908 StringRef SectionName
;
909 error(S
.getName(SectionName
));
910 // .debug$T is a standard CodeView type section, while .debug$P is the same
911 // format but used for MSVC precompiled header object files.
912 if (SectionName
== ".debug$T" || SectionName
== ".debug$P")
913 printCodeViewTypeSection(SectionName
, S
);
915 for (const SectionRef
&S
: Obj
->sections()) {
916 StringRef SectionName
;
917 error(S
.getName(SectionName
));
918 if (SectionName
== ".debug$S")
919 printCodeViewSymbolSection(SectionName
, S
);
923 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader
&Reader
) {
924 while (Reader
.bytesRemaining() > 0 &&
925 (!CVFileChecksumTable
.valid() || !CVStringTable
.valid())) {
926 // The section consists of a number of subsection in the following format:
927 // |SubSectionType|SubSectionSize|Contents...|
928 uint32_t SubType
, SubSectionSize
;
929 error(Reader
.readInteger(SubType
));
930 error(Reader
.readInteger(SubSectionSize
));
933 error(Reader
.readFixedString(Contents
, SubSectionSize
));
935 BinaryStreamRef
ST(Contents
, support::little
);
936 switch (DebugSubsectionKind(SubType
)) {
937 case DebugSubsectionKind::FileChecksums
:
938 error(CVFileChecksumTable
.initialize(ST
));
940 case DebugSubsectionKind::StringTable
:
941 error(CVStringTable
.initialize(ST
));
947 uint32_t PaddedSize
= alignTo(SubSectionSize
, 4);
948 error(Reader
.skip(PaddedSize
- SubSectionSize
));
952 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName
,
953 const SectionRef
&Section
) {
954 StringRef SectionContents
;
955 error(Section
.getContents(SectionContents
));
956 StringRef Data
= SectionContents
;
958 SmallVector
<StringRef
, 10> FunctionNames
;
959 StringMap
<StringRef
> FunctionLineTables
;
961 ListScope
D(W
, "CodeViewDebugInfo");
962 // Print the section to allow correlation with printSections.
963 W
.printNumber("Section", SectionName
, Obj
->getSectionID(Section
));
966 error(consume(Data
, Magic
));
967 W
.printHex("Magic", Magic
);
968 if (Magic
!= COFF::DEBUG_SECTION_MAGIC
)
969 return error(object_error::parse_failed
);
971 BinaryStreamReader
FSReader(Data
, support::little
);
972 initializeFileAndStringTables(FSReader
);
974 // TODO: Convert this over to using ModuleSubstreamVisitor.
975 while (!Data
.empty()) {
976 // The section consists of a number of subsection in the following format:
977 // |SubSectionType|SubSectionSize|Contents...|
978 uint32_t SubType
, SubSectionSize
;
979 error(consume(Data
, SubType
));
980 error(consume(Data
, SubSectionSize
));
982 ListScope
S(W
, "Subsection");
983 W
.printEnum("SubSectionType", SubType
, makeArrayRef(SubSectionTypes
));
984 W
.printHex("SubSectionSize", SubSectionSize
);
986 // Get the contents of the subsection.
987 if (SubSectionSize
> Data
.size())
988 return error(object_error::parse_failed
);
989 StringRef Contents
= Data
.substr(0, SubSectionSize
);
991 // Add SubSectionSize to the current offset and align that offset to find
992 // the next subsection.
993 size_t SectionOffset
= Data
.data() - SectionContents
.data();
994 size_t NextOffset
= SectionOffset
+ SubSectionSize
;
995 NextOffset
= alignTo(NextOffset
, 4);
996 if (NextOffset
> SectionContents
.size())
997 return error(object_error::parse_failed
);
998 Data
= SectionContents
.drop_front(NextOffset
);
1000 // Optionally print the subsection bytes in case our parsing gets confused
1002 if (opts::CodeViewSubsectionBytes
)
1003 printBinaryBlockWithRelocs("SubSectionContents", Section
, SectionContents
,
1006 switch (DebugSubsectionKind(SubType
)) {
1007 case DebugSubsectionKind::Symbols
:
1008 printCodeViewSymbolsSubsection(Contents
, Section
, SectionContents
);
1011 case DebugSubsectionKind::InlineeLines
:
1012 printCodeViewInlineeLines(Contents
);
1015 case DebugSubsectionKind::FileChecksums
:
1016 printCodeViewFileChecksums(Contents
);
1019 case DebugSubsectionKind::Lines
: {
1020 // Holds a PC to file:line table. Some data to parse this subsection is
1021 // stored in the other subsections, so just check sanity and store the
1022 // pointers for deferred processing.
1024 if (SubSectionSize
< 12) {
1025 // There should be at least three words to store two function
1026 // relocations and size of the code.
1027 error(object_error::parse_failed
);
1031 StringRef LinkageName
;
1032 error(resolveSymbolName(Obj
->getCOFFSection(Section
), SectionOffset
,
1034 W
.printString("LinkageName", LinkageName
);
1035 if (FunctionLineTables
.count(LinkageName
) != 0) {
1036 // Saw debug info for this function already?
1037 error(object_error::parse_failed
);
1041 FunctionLineTables
[LinkageName
] = Contents
;
1042 FunctionNames
.push_back(LinkageName
);
1045 case DebugSubsectionKind::FrameData
: {
1046 // First four bytes is a relocation against the function.
1047 BinaryStreamReader
SR(Contents
, llvm::support::little
);
1049 DebugFrameDataSubsectionRef FrameData
;
1050 error(FrameData
.initialize(SR
));
1052 StringRef LinkageName
;
1053 error(resolveSymbolName(Obj
->getCOFFSection(Section
), SectionContents
,
1054 FrameData
.getRelocPtr(), LinkageName
));
1055 W
.printString("LinkageName", LinkageName
);
1057 // To find the active frame description, search this array for the
1058 // smallest PC range that includes the current PC.
1059 for (const auto &FD
: FrameData
) {
1060 StringRef FrameFunc
= error(CVStringTable
.getString(FD
.FrameFunc
));
1062 DictScope
S(W
, "FrameData");
1063 W
.printHex("RvaStart", FD
.RvaStart
);
1064 W
.printHex("CodeSize", FD
.CodeSize
);
1065 W
.printHex("LocalSize", FD
.LocalSize
);
1066 W
.printHex("ParamsSize", FD
.ParamsSize
);
1067 W
.printHex("MaxStackSize", FD
.MaxStackSize
);
1068 W
.printHex("PrologSize", FD
.PrologSize
);
1069 W
.printHex("SavedRegsSize", FD
.SavedRegsSize
);
1070 W
.printFlags("Flags", FD
.Flags
, makeArrayRef(FrameDataFlags
));
1072 // The FrameFunc string is a small RPN program. It can be broken up into
1073 // statements that end in the '=' operator, which assigns the value on
1074 // the top of the stack to the previously pushed variable. Variables can
1075 // be temporary values ($T0) or physical registers ($esp). Print each
1076 // assignment on its own line to make these programs easier to read.
1078 ListScope
FFS(W
, "FrameFunc");
1079 while (!FrameFunc
.empty()) {
1080 size_t EqOrEnd
= FrameFunc
.find('=');
1081 if (EqOrEnd
== StringRef::npos
)
1082 EqOrEnd
= FrameFunc
.size();
1085 StringRef Stmt
= FrameFunc
.substr(0, EqOrEnd
);
1086 W
.printString(Stmt
);
1087 FrameFunc
= FrameFunc
.drop_front(EqOrEnd
).trim();
1094 // Do nothing for unrecognized subsections.
1101 // Dump the line tables now that we've read all the subsections and know all
1102 // the required information.
1103 for (unsigned I
= 0, E
= FunctionNames
.size(); I
!= E
; ++I
) {
1104 StringRef Name
= FunctionNames
[I
];
1105 ListScope
S(W
, "FunctionLineTable");
1106 W
.printString("LinkageName", Name
);
1108 BinaryStreamReader
Reader(FunctionLineTables
[Name
], support::little
);
1110 DebugLinesSubsectionRef LineInfo
;
1111 error(LineInfo
.initialize(Reader
));
1113 W
.printHex("Flags", LineInfo
.header()->Flags
);
1114 W
.printHex("CodeSize", LineInfo
.header()->CodeSize
);
1115 for (const auto &Entry
: LineInfo
) {
1117 ListScope
S(W
, "FilenameSegment");
1118 printFileNameForOffset("Filename", Entry
.NameIndex
);
1119 uint32_t ColumnIndex
= 0;
1120 for (const auto &Line
: Entry
.LineNumbers
) {
1121 if (Line
.Offset
>= LineInfo
.header()->CodeSize
) {
1122 error(object_error::parse_failed
);
1126 std::string PC
= formatv("+{0:X}", uint32_t(Line
.Offset
));
1127 ListScope
PCScope(W
, PC
);
1128 codeview::LineInfo
LI(Line
.Flags
);
1130 if (LI
.isAlwaysStepInto())
1131 W
.printString("StepInto", StringRef("Always"));
1132 else if (LI
.isNeverStepInto())
1133 W
.printString("StepInto", StringRef("Never"));
1135 W
.printNumber("LineNumberStart", LI
.getStartLine());
1136 W
.printNumber("LineNumberEndDelta", LI
.getLineDelta());
1137 W
.printBoolean("IsStatement", LI
.isStatement());
1138 if (LineInfo
.hasColumnInfo()) {
1139 W
.printNumber("ColStart", Entry
.Columns
[ColumnIndex
].StartColumn
);
1140 W
.printNumber("ColEnd", Entry
.Columns
[ColumnIndex
].EndColumn
);
1148 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection
,
1149 const SectionRef
&Section
,
1150 StringRef SectionContents
) {
1151 ArrayRef
<uint8_t> BinaryData(Subsection
.bytes_begin(),
1152 Subsection
.bytes_end());
1153 auto CODD
= llvm::make_unique
<COFFObjectDumpDelegate
>(*this, Section
, Obj
,
1155 CVSymbolDumper
CVSD(W
, Types
, CodeViewContainer::ObjectFile
, std::move(CODD
),
1156 CompilationCPUType
, opts::CodeViewSubsectionBytes
);
1157 CVSymbolArray Symbols
;
1158 BinaryStreamReader
Reader(BinaryData
, llvm::support::little
);
1159 if (auto EC
= Reader
.readArray(Symbols
, Reader
.getLength())) {
1160 consumeError(std::move(EC
));
1162 error(object_error::parse_failed
);
1165 if (auto EC
= CVSD
.dump(Symbols
)) {
1167 error(std::move(EC
));
1169 CompilationCPUType
= CVSD
.getCompilationCPUType();
1173 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection
) {
1174 BinaryStreamRef
Stream(Subsection
, llvm::support::little
);
1175 DebugChecksumsSubsectionRef Checksums
;
1176 error(Checksums
.initialize(Stream
));
1178 for (auto &FC
: Checksums
) {
1179 DictScope
S(W
, "FileChecksum");
1181 StringRef Filename
= error(CVStringTable
.getString(FC
.FileNameOffset
));
1182 W
.printHex("Filename", Filename
, FC
.FileNameOffset
);
1183 W
.printHex("ChecksumSize", FC
.Checksum
.size());
1184 W
.printEnum("ChecksumKind", uint8_t(FC
.Kind
),
1185 makeArrayRef(FileChecksumKindNames
));
1187 W
.printBinary("ChecksumBytes", FC
.Checksum
);
1191 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection
) {
1192 BinaryStreamReader
SR(Subsection
, llvm::support::little
);
1193 DebugInlineeLinesSubsectionRef Lines
;
1194 error(Lines
.initialize(SR
));
1196 for (auto &Line
: Lines
) {
1197 DictScope
S(W
, "InlineeSourceLine");
1198 printTypeIndex("Inlinee", Line
.Header
->Inlinee
);
1199 printFileNameForOffset("FileID", Line
.Header
->FileID
);
1200 W
.printNumber("SourceLineNum", Line
.Header
->SourceLineNum
);
1202 if (Lines
.hasExtraFiles()) {
1203 W
.printNumber("ExtraFileCount", Line
.ExtraFiles
.size());
1204 ListScope
ExtraFiles(W
, "ExtraFiles");
1205 for (const auto &FID
: Line
.ExtraFiles
) {
1206 printFileNameForOffset("FileID", FID
);
1212 StringRef
COFFDumper::getFileNameForFileOffset(uint32_t FileOffset
) {
1213 // The file checksum subsection should precede all references to it.
1214 if (!CVFileChecksumTable
.valid() || !CVStringTable
.valid())
1215 error(object_error::parse_failed
);
1217 auto Iter
= CVFileChecksumTable
.getArray().at(FileOffset
);
1219 // Check if the file checksum table offset is valid.
1220 if (Iter
== CVFileChecksumTable
.end())
1221 error(object_error::parse_failed
);
1223 return error(CVStringTable
.getString(Iter
->FileNameOffset
));
1226 void COFFDumper::printFileNameForOffset(StringRef Label
, uint32_t FileOffset
) {
1227 W
.printHex(Label
, getFileNameForFileOffset(FileOffset
), FileOffset
);
1230 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder
&CVIDs
,
1231 MergingTypeTableBuilder
&CVTypes
) {
1232 for (const SectionRef
&S
: Obj
->sections()) {
1233 StringRef SectionName
;
1234 error(S
.getName(SectionName
));
1235 if (SectionName
== ".debug$T") {
1237 error(S
.getContents(Data
));
1239 error(consume(Data
, Magic
));
1241 error(object_error::parse_failed
);
1244 BinaryStreamReader
Reader(Data
, llvm::support::little
);
1245 if (auto EC
= Reader
.readArray(Types
, Reader
.getLength())) {
1246 consumeError(std::move(EC
));
1248 error(object_error::parse_failed
);
1250 SmallVector
<TypeIndex
, 128> SourceToDest
;
1251 if (auto EC
= mergeTypeAndIdRecords(CVIDs
, CVTypes
, SourceToDest
, Types
))
1252 return error(std::move(EC
));
1257 void COFFDumper::printCodeViewTypeSection(StringRef SectionName
,
1258 const SectionRef
&Section
) {
1259 ListScope
D(W
, "CodeViewTypes");
1260 W
.printNumber("Section", SectionName
, Obj
->getSectionID(Section
));
1263 error(Section
.getContents(Data
));
1264 if (opts::CodeViewSubsectionBytes
)
1265 W
.printBinaryBlock("Data", Data
);
1268 error(consume(Data
, Magic
));
1269 W
.printHex("Magic", Magic
);
1270 if (Magic
!= COFF::DEBUG_SECTION_MAGIC
)
1271 return error(object_error::parse_failed
);
1273 Types
.reset(Data
, 100);
1275 TypeDumpVisitor
TDV(Types
, &W
, opts::CodeViewSubsectionBytes
);
1276 error(codeview::visitTypeStream(Types
, TDV
));
1280 void COFFDumper::printSections() {
1281 ListScope
SectionsD(W
, "Sections");
1282 int SectionNumber
= 0;
1283 for (const SectionRef
&Sec
: Obj
->sections()) {
1285 const coff_section
*Section
= Obj
->getCOFFSection(Sec
);
1288 error(Sec
.getName(Name
));
1290 DictScope
D(W
, "Section");
1291 W
.printNumber("Number", SectionNumber
);
1292 W
.printBinary("Name", Name
, Section
->Name
);
1293 W
.printHex ("VirtualSize", Section
->VirtualSize
);
1294 W
.printHex ("VirtualAddress", Section
->VirtualAddress
);
1295 W
.printNumber("RawDataSize", Section
->SizeOfRawData
);
1296 W
.printHex ("PointerToRawData", Section
->PointerToRawData
);
1297 W
.printHex ("PointerToRelocations", Section
->PointerToRelocations
);
1298 W
.printHex ("PointerToLineNumbers", Section
->PointerToLinenumbers
);
1299 W
.printNumber("RelocationCount", Section
->NumberOfRelocations
);
1300 W
.printNumber("LineNumberCount", Section
->NumberOfLinenumbers
);
1301 W
.printFlags ("Characteristics", Section
->Characteristics
,
1302 makeArrayRef(ImageSectionCharacteristics
),
1303 COFF::SectionCharacteristics(0x00F00000));
1305 if (opts::SectionRelocations
) {
1306 ListScope
D(W
, "Relocations");
1307 for (const RelocationRef
&Reloc
: Sec
.relocations())
1308 printRelocation(Sec
, Reloc
);
1311 if (opts::SectionSymbols
) {
1312 ListScope
D(W
, "Symbols");
1313 for (const SymbolRef
&Symbol
: Obj
->symbols()) {
1314 if (!Sec
.containsSymbol(Symbol
))
1317 printSymbol(Symbol
);
1321 if (opts::SectionData
&&
1322 !(Section
->Characteristics
& COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
)) {
1324 error(Sec
.getContents(Data
));
1326 W
.printBinaryBlock("SectionData", Data
);
1331 void COFFDumper::printRelocations() {
1332 ListScope
D(W
, "Relocations");
1334 int SectionNumber
= 0;
1335 for (const SectionRef
&Section
: Obj
->sections()) {
1338 error(Section
.getName(Name
));
1340 bool PrintedGroup
= false;
1341 for (const RelocationRef
&Reloc
: Section
.relocations()) {
1342 if (!PrintedGroup
) {
1343 W
.startLine() << "Section (" << SectionNumber
<< ") " << Name
<< " {\n";
1345 PrintedGroup
= true;
1348 printRelocation(Section
, Reloc
);
1353 W
.startLine() << "}\n";
1358 void COFFDumper::printRelocation(const SectionRef
&Section
,
1359 const RelocationRef
&Reloc
, uint64_t Bias
) {
1360 uint64_t Offset
= Reloc
.getOffset() - Bias
;
1361 uint64_t RelocType
= Reloc
.getType();
1362 SmallString
<32> RelocName
;
1363 StringRef SymbolName
;
1364 Reloc
.getTypeName(RelocName
);
1365 symbol_iterator Symbol
= Reloc
.getSymbol();
1366 if (Symbol
!= Obj
->symbol_end()) {
1367 Expected
<StringRef
> SymbolNameOrErr
= Symbol
->getName();
1368 error(errorToErrorCode(SymbolNameOrErr
.takeError()));
1369 SymbolName
= *SymbolNameOrErr
;
1372 if (opts::ExpandRelocs
) {
1373 DictScope
Group(W
, "Relocation");
1374 W
.printHex("Offset", Offset
);
1375 W
.printNumber("Type", RelocName
, RelocType
);
1376 W
.printString("Symbol", SymbolName
.empty() ? "-" : SymbolName
);
1378 raw_ostream
& OS
= W
.startLine();
1381 << " " << (SymbolName
.empty() ? "-" : SymbolName
)
1386 void COFFDumper::printSymbols() {
1387 ListScope
Group(W
, "Symbols");
1389 for (const SymbolRef
&Symbol
: Obj
->symbols())
1390 printSymbol(Symbol
);
1393 void COFFDumper::printDynamicSymbols() { ListScope
Group(W
, "DynamicSymbols"); }
1395 static ErrorOr
<StringRef
>
1396 getSectionName(const llvm::object::COFFObjectFile
*Obj
, int32_t SectionNumber
,
1397 const coff_section
*Section
) {
1399 StringRef SectionName
;
1400 if (std::error_code EC
= Obj
->getSectionName(Section
, SectionName
))
1404 if (SectionNumber
== llvm::COFF::IMAGE_SYM_DEBUG
)
1405 return StringRef("IMAGE_SYM_DEBUG");
1406 if (SectionNumber
== llvm::COFF::IMAGE_SYM_ABSOLUTE
)
1407 return StringRef("IMAGE_SYM_ABSOLUTE");
1408 if (SectionNumber
== llvm::COFF::IMAGE_SYM_UNDEFINED
)
1409 return StringRef("IMAGE_SYM_UNDEFINED");
1410 return StringRef("");
1413 void COFFDumper::printSymbol(const SymbolRef
&Sym
) {
1414 DictScope
D(W
, "Symbol");
1416 COFFSymbolRef Symbol
= Obj
->getCOFFSymbol(Sym
);
1417 const coff_section
*Section
;
1418 if (std::error_code EC
= Obj
->getSection(Symbol
.getSectionNumber(), Section
)) {
1419 W
.startLine() << "Invalid section number: " << EC
.message() << "\n";
1424 StringRef SymbolName
;
1425 if (Obj
->getSymbolName(Symbol
, SymbolName
))
1428 StringRef SectionName
= "";
1429 ErrorOr
<StringRef
> Res
=
1430 getSectionName(Obj
, Symbol
.getSectionNumber(), Section
);
1434 W
.printString("Name", SymbolName
);
1435 W
.printNumber("Value", Symbol
.getValue());
1436 W
.printNumber("Section", SectionName
, Symbol
.getSectionNumber());
1437 W
.printEnum ("BaseType", Symbol
.getBaseType(), makeArrayRef(ImageSymType
));
1438 W
.printEnum ("ComplexType", Symbol
.getComplexType(),
1439 makeArrayRef(ImageSymDType
));
1440 W
.printEnum ("StorageClass", Symbol
.getStorageClass(),
1441 makeArrayRef(ImageSymClass
));
1442 W
.printNumber("AuxSymbolCount", Symbol
.getNumberOfAuxSymbols());
1444 for (uint8_t I
= 0; I
< Symbol
.getNumberOfAuxSymbols(); ++I
) {
1445 if (Symbol
.isFunctionDefinition()) {
1446 const coff_aux_function_definition
*Aux
;
1447 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1449 DictScope
AS(W
, "AuxFunctionDef");
1450 W
.printNumber("TagIndex", Aux
->TagIndex
);
1451 W
.printNumber("TotalSize", Aux
->TotalSize
);
1452 W
.printHex("PointerToLineNumber", Aux
->PointerToLinenumber
);
1453 W
.printHex("PointerToNextFunction", Aux
->PointerToNextFunction
);
1455 } else if (Symbol
.isAnyUndefined()) {
1456 const coff_aux_weak_external
*Aux
;
1457 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1459 Expected
<COFFSymbolRef
> Linked
= Obj
->getSymbol(Aux
->TagIndex
);
1460 StringRef LinkedName
;
1461 std::error_code EC
= errorToErrorCode(Linked
.takeError());
1462 if (EC
|| (EC
= Obj
->getSymbolName(*Linked
, LinkedName
))) {
1467 DictScope
AS(W
, "AuxWeakExternal");
1468 W
.printNumber("Linked", LinkedName
, Aux
->TagIndex
);
1469 W
.printEnum ("Search", Aux
->Characteristics
,
1470 makeArrayRef(WeakExternalCharacteristics
));
1472 } else if (Symbol
.isFileRecord()) {
1473 const char *FileName
;
1474 error(getSymbolAuxData(Obj
, Symbol
, I
, FileName
));
1476 DictScope
AS(W
, "AuxFileRecord");
1478 StringRef
Name(FileName
, Symbol
.getNumberOfAuxSymbols() *
1479 Obj
->getSymbolTableEntrySize());
1480 W
.printString("FileName", Name
.rtrim(StringRef("\0", 1)));
1482 } else if (Symbol
.isSectionDefinition()) {
1483 const coff_aux_section_definition
*Aux
;
1484 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1486 int32_t AuxNumber
= Aux
->getNumber(Symbol
.isBigObj());
1488 DictScope
AS(W
, "AuxSectionDef");
1489 W
.printNumber("Length", Aux
->Length
);
1490 W
.printNumber("RelocationCount", Aux
->NumberOfRelocations
);
1491 W
.printNumber("LineNumberCount", Aux
->NumberOfLinenumbers
);
1492 W
.printHex("Checksum", Aux
->CheckSum
);
1493 W
.printNumber("Number", AuxNumber
);
1494 W
.printEnum("Selection", Aux
->Selection
, makeArrayRef(ImageCOMDATSelect
));
1496 if (Section
&& Section
->Characteristics
& COFF::IMAGE_SCN_LNK_COMDAT
1497 && Aux
->Selection
== COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
) {
1498 const coff_section
*Assoc
;
1499 StringRef AssocName
= "";
1500 std::error_code EC
= Obj
->getSection(AuxNumber
, Assoc
);
1501 ErrorOr
<StringRef
> Res
= getSectionName(Obj
, AuxNumber
, Assoc
);
1505 EC
= Res
.getError();
1511 W
.printNumber("AssocSection", AssocName
, AuxNumber
);
1513 } else if (Symbol
.isCLRToken()) {
1514 const coff_aux_clr_token
*Aux
;
1515 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1517 Expected
<COFFSymbolRef
> ReferredSym
=
1518 Obj
->getSymbol(Aux
->SymbolTableIndex
);
1519 StringRef ReferredName
;
1520 std::error_code EC
= errorToErrorCode(ReferredSym
.takeError());
1521 if (EC
|| (EC
= Obj
->getSymbolName(*ReferredSym
, ReferredName
))) {
1526 DictScope
AS(W
, "AuxCLRToken");
1527 W
.printNumber("AuxType", Aux
->AuxType
);
1528 W
.printNumber("Reserved", Aux
->Reserved
);
1529 W
.printNumber("SymbolTableIndex", ReferredName
, Aux
->SymbolTableIndex
);
1532 W
.startLine() << "<unhandled auxiliary record>\n";
1537 void COFFDumper::printUnwindInfo() {
1538 ListScope
D(W
, "UnwindInformation");
1539 switch (Obj
->getMachine()) {
1540 case COFF::IMAGE_FILE_MACHINE_AMD64
: {
1541 Win64EH::Dumper
Dumper(W
);
1542 Win64EH::Dumper::SymbolResolver
1543 Resolver
= [](const object::coff_section
*Section
, uint64_t Offset
,
1544 SymbolRef
&Symbol
, void *user_data
) -> std::error_code
{
1545 COFFDumper
*Dumper
= reinterpret_cast<COFFDumper
*>(user_data
);
1546 return Dumper
->resolveSymbol(Section
, Offset
, Symbol
);
1548 Win64EH::Dumper::Context
Ctx(*Obj
, Resolver
, this);
1549 Dumper
.printData(Ctx
);
1552 case COFF::IMAGE_FILE_MACHINE_ARMNT
: {
1553 ARM::WinEH::Decoder
Decoder(W
);
1554 Decoder
.dumpProcedureData(*Obj
);
1558 W
.printEnum("unsupported Image Machine", Obj
->getMachine(),
1559 makeArrayRef(ImageFileMachineType
));
1564 void COFFDumper::printNeededLibraries() {
1565 ListScope
D(W
, "NeededLibraries");
1567 using LibsTy
= std::vector
<StringRef
>;
1570 for (const ImportDirectoryEntryRef
&DirRef
: Obj
->import_directories()) {
1572 if (!DirRef
.getName(Name
))
1573 Libs
.push_back(Name
);
1576 std::stable_sort(Libs
.begin(), Libs
.end());
1578 for (const auto &L
: Libs
) {
1579 outs() << " " << L
<< "\n";
1583 void COFFDumper::printImportedSymbols(
1584 iterator_range
<imported_symbol_iterator
> Range
) {
1585 for (const ImportedSymbolRef
&I
: Range
) {
1587 error(I
.getSymbolName(Sym
));
1589 error(I
.getOrdinal(Ordinal
));
1590 W
.printNumber("Symbol", Sym
, Ordinal
);
1594 void COFFDumper::printDelayImportedSymbols(
1595 const DelayImportDirectoryEntryRef
&I
,
1596 iterator_range
<imported_symbol_iterator
> Range
) {
1598 for (const ImportedSymbolRef
&S
: Range
) {
1599 DictScope
Import(W
, "Import");
1601 error(S
.getSymbolName(Sym
));
1603 error(S
.getOrdinal(Ordinal
));
1604 W
.printNumber("Symbol", Sym
, Ordinal
);
1606 error(I
.getImportAddress(Index
++, Addr
));
1607 W
.printHex("Address", Addr
);
1611 void COFFDumper::printCOFFImports() {
1613 for (const ImportDirectoryEntryRef
&I
: Obj
->import_directories()) {
1614 DictScope
Import(W
, "Import");
1616 error(I
.getName(Name
));
1617 W
.printString("Name", Name
);
1619 error(I
.getImportLookupTableRVA(ILTAddr
));
1620 W
.printHex("ImportLookupTableRVA", ILTAddr
);
1622 error(I
.getImportAddressTableRVA(IATAddr
));
1623 W
.printHex("ImportAddressTableRVA", IATAddr
);
1624 // The import lookup table can be missing with certain older linkers, so
1625 // fall back to the import address table in that case.
1627 printImportedSymbols(I
.lookup_table_symbols());
1629 printImportedSymbols(I
.imported_symbols());
1633 for (const DelayImportDirectoryEntryRef
&I
: Obj
->delay_import_directories()) {
1634 DictScope
Import(W
, "DelayImport");
1636 error(I
.getName(Name
));
1637 W
.printString("Name", Name
);
1638 const delay_import_directory_table_entry
*Table
;
1639 error(I
.getDelayImportTable(Table
));
1640 W
.printHex("Attributes", Table
->Attributes
);
1641 W
.printHex("ModuleHandle", Table
->ModuleHandle
);
1642 W
.printHex("ImportAddressTable", Table
->DelayImportAddressTable
);
1643 W
.printHex("ImportNameTable", Table
->DelayImportNameTable
);
1644 W
.printHex("BoundDelayImportTable", Table
->BoundDelayImportTable
);
1645 W
.printHex("UnloadDelayImportTable", Table
->UnloadDelayImportTable
);
1646 printDelayImportedSymbols(I
, I
.imported_symbols());
1650 void COFFDumper::printCOFFExports() {
1651 for (const ExportDirectoryEntryRef
&E
: Obj
->export_directories()) {
1652 DictScope
Export(W
, "Export");
1655 uint32_t Ordinal
, RVA
;
1657 error(E
.getSymbolName(Name
));
1658 error(E
.getOrdinal(Ordinal
));
1659 error(E
.getExportRVA(RVA
));
1661 W
.printNumber("Ordinal", Ordinal
);
1662 W
.printString("Name", Name
);
1663 W
.printHex("RVA", RVA
);
1667 void COFFDumper::printCOFFDirectives() {
1668 for (const SectionRef
&Section
: Obj
->sections()) {
1672 error(Section
.getName(Name
));
1673 if (Name
!= ".drectve")
1676 error(Section
.getContents(Contents
));
1678 W
.printString("Directive(s)", Contents
);
1682 static std::string
getBaseRelocTypeName(uint8_t Type
) {
1684 case COFF::IMAGE_REL_BASED_ABSOLUTE
: return "ABSOLUTE";
1685 case COFF::IMAGE_REL_BASED_HIGH
: return "HIGH";
1686 case COFF::IMAGE_REL_BASED_LOW
: return "LOW";
1687 case COFF::IMAGE_REL_BASED_HIGHLOW
: return "HIGHLOW";
1688 case COFF::IMAGE_REL_BASED_HIGHADJ
: return "HIGHADJ";
1689 case COFF::IMAGE_REL_BASED_ARM_MOV32T
: return "ARM_MOV32(T)";
1690 case COFF::IMAGE_REL_BASED_DIR64
: return "DIR64";
1691 default: return "unknown (" + llvm::utostr(Type
) + ")";
1695 void COFFDumper::printCOFFBaseReloc() {
1696 ListScope
D(W
, "BaseReloc");
1697 for (const BaseRelocRef
&I
: Obj
->base_relocs()) {
1700 error(I
.getRVA(RVA
));
1701 error(I
.getType(Type
));
1702 DictScope
Import(W
, "Entry");
1703 W
.printString("Type", getBaseRelocTypeName(Type
));
1704 W
.printHex("Address", RVA
);
1708 void COFFDumper::printCOFFResources() {
1709 ListScope
ResourcesD(W
, "Resources");
1710 for (const SectionRef
&S
: Obj
->sections()) {
1712 error(S
.getName(Name
));
1713 if (!Name
.startswith(".rsrc"))
1717 error(S
.getContents(Ref
));
1719 if ((Name
== ".rsrc") || (Name
== ".rsrc$01")) {
1720 ResourceSectionRef
RSF(Ref
);
1721 auto &BaseTable
= unwrapOrError(RSF
.getBaseTable());
1722 W
.printNumber("Total Number of Resources",
1723 countTotalTableEntries(RSF
, BaseTable
, "Type"));
1724 W
.printHex("Base Table Address",
1725 Obj
->getCOFFSection(S
)->PointerToRawData
);
1726 W
.startLine() << "\n";
1727 printResourceDirectoryTable(RSF
, BaseTable
, "Type");
1729 if (opts::SectionData
)
1730 W
.printBinaryBlock(Name
.str() + " Data", Ref
);
1735 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF
,
1736 const coff_resource_dir_table
&Table
,
1738 uint32_t TotalEntries
= 0;
1739 for (int i
= 0; i
< Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
;
1741 auto Entry
= unwrapOrError(getResourceDirectoryTableEntry(Table
, i
));
1742 if (Entry
.Offset
.isSubDir()) {
1743 StringRef NextLevel
;
1744 if (Level
== "Name")
1745 NextLevel
= "Language";
1748 auto &NextTable
= unwrapOrError(RSF
.getEntrySubDir(Entry
));
1749 TotalEntries
+= countTotalTableEntries(RSF
, NextTable
, NextLevel
);
1754 return TotalEntries
;
1757 void COFFDumper::printResourceDirectoryTable(
1758 ResourceSectionRef RSF
, const coff_resource_dir_table
&Table
,
1761 W
.printNumber("Number of String Entries", Table
.NumberOfNameEntries
);
1762 W
.printNumber("Number of ID Entries", Table
.NumberOfIDEntries
);
1764 // Iterate through level in resource directory tree.
1765 for (int i
= 0; i
< Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
;
1767 auto Entry
= unwrapOrError(getResourceDirectoryTableEntry(Table
, i
));
1769 SmallString
<20> IDStr
;
1770 raw_svector_ostream
OS(IDStr
);
1771 if (i
< Table
.NumberOfNameEntries
) {
1772 ArrayRef
<UTF16
> RawEntryNameString
= unwrapOrError(RSF
.getEntryNameString(Entry
));
1773 std::vector
<UTF16
> EndianCorrectedNameString
;
1774 if (llvm::sys::IsBigEndianHost
) {
1775 EndianCorrectedNameString
.resize(RawEntryNameString
.size() + 1);
1776 std::copy(RawEntryNameString
.begin(), RawEntryNameString
.end(),
1777 EndianCorrectedNameString
.begin() + 1);
1778 EndianCorrectedNameString
[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED
;
1779 RawEntryNameString
= makeArrayRef(EndianCorrectedNameString
);
1781 std::string EntryNameString
;
1782 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString
, EntryNameString
))
1783 error(object_error::parse_failed
);
1785 OS
<< EntryNameString
;
1787 if (Level
== "Type") {
1788 ScopedPrinter
Printer(OS
);
1789 Printer
.printEnum("", Entry
.Identifier
.ID
,
1790 makeArrayRef(ResourceTypeNames
));
1791 IDStr
= IDStr
.slice(0, IDStr
.find_first_of(")", 0) + 1);
1793 OS
<< ": (ID " << Entry
.Identifier
.ID
<< ")";
1796 Name
= StringRef(IDStr
);
1797 ListScope
ResourceType(W
, Level
.str() + Name
.str());
1798 if (Entry
.Offset
.isSubDir()) {
1799 W
.printHex("Table Offset", Entry
.Offset
.value());
1800 StringRef NextLevel
;
1801 if (Level
== "Name")
1802 NextLevel
= "Language";
1805 auto &NextTable
= unwrapOrError(RSF
.getEntrySubDir(Entry
));
1806 printResourceDirectoryTable(RSF
, NextTable
, NextLevel
);
1808 W
.printHex("Entry Offset", Entry
.Offset
.value());
1809 char FormattedTime
[20] = {};
1810 time_t TDS
= time_t(Table
.TimeDateStamp
);
1811 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
1812 W
.printHex("Time/Date Stamp", FormattedTime
, Table
.TimeDateStamp
);
1813 W
.printNumber("Major Version", Table
.MajorVersion
);
1814 W
.printNumber("Minor Version", Table
.MinorVersion
);
1815 W
.printNumber("Characteristics", Table
.Characteristics
);
1820 ErrorOr
<const coff_resource_dir_entry
&>
1821 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table
&Table
,
1823 if (Index
>= (uint32_t)(Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
))
1824 return object_error::parse_failed
;
1825 auto TablePtr
= reinterpret_cast<const coff_resource_dir_entry
*>(&Table
+ 1);
1826 return TablePtr
[Index
];
1829 void COFFDumper::printStackMap() const {
1830 object::SectionRef StackMapSection
;
1831 for (auto Sec
: Obj
->sections()) {
1834 if (Name
== ".llvm_stackmaps") {
1835 StackMapSection
= Sec
;
1840 if (StackMapSection
== object::SectionRef())
1843 StringRef StackMapContents
;
1844 StackMapSection
.getContents(StackMapContents
);
1845 ArrayRef
<uint8_t> StackMapContentsArray(
1846 reinterpret_cast<const uint8_t*>(StackMapContents
.data()),
1847 StackMapContents
.size());
1849 if (Obj
->isLittleEndian())
1850 prettyPrintStackMap(
1851 W
, StackMapV2Parser
<support::little
>(StackMapContentsArray
));
1853 prettyPrintStackMap(W
,
1854 StackMapV2Parser
<support::big
>(StackMapContentsArray
));
1857 void COFFDumper::printAddrsig() {
1858 object::SectionRef AddrsigSection
;
1859 for (auto Sec
: Obj
->sections()) {
1862 if (Name
== ".llvm_addrsig") {
1863 AddrsigSection
= Sec
;
1868 if (AddrsigSection
== object::SectionRef())
1871 StringRef AddrsigContents
;
1872 AddrsigSection
.getContents(AddrsigContents
);
1873 ArrayRef
<uint8_t> AddrsigContentsArray(
1874 reinterpret_cast<const uint8_t*>(AddrsigContents
.data()),
1875 AddrsigContents
.size());
1877 ListScope
L(W
, "Addrsig");
1878 auto *Cur
= reinterpret_cast<const uint8_t *>(AddrsigContents
.begin());
1879 auto *End
= reinterpret_cast<const uint8_t *>(AddrsigContents
.end());
1880 while (Cur
!= End
) {
1883 uint64_t SymIndex
= decodeULEB128(Cur
, &Size
, End
, &Err
);
1887 Expected
<COFFSymbolRef
> Sym
= Obj
->getSymbol(SymIndex
);
1889 std::error_code EC
= errorToErrorCode(Sym
.takeError());
1890 if (EC
|| (EC
= Obj
->getSymbolName(*Sym
, SymName
))) {
1895 W
.printNumber("Sym", SymName
, SymIndex
);
1900 void llvm::dumpCodeViewMergedTypes(
1901 ScopedPrinter
&Writer
, llvm::codeview::MergingTypeTableBuilder
&IDTable
,
1902 llvm::codeview::MergingTypeTableBuilder
&CVTypes
) {
1903 // Flatten it first, then run our dumper on it.
1904 SmallString
<0> TypeBuf
;
1905 CVTypes
.ForEachRecord([&](TypeIndex TI
, const CVType
&Record
) {
1906 TypeBuf
.append(Record
.RecordData
.begin(), Record
.RecordData
.end());
1909 TypeTableCollection
TpiTypes(CVTypes
.records());
1911 ListScope
S(Writer
, "MergedTypeStream");
1912 TypeDumpVisitor
TDV(TpiTypes
, &Writer
, opts::CodeViewSubsectionBytes
);
1913 error(codeview::visitTypeStream(TpiTypes
, TDV
));
1917 // Flatten the id stream and print it next. The ID stream refers to names from
1919 TypeTableCollection
IpiTypes(IDTable
.records());
1921 ListScope
S(Writer
, "MergedIDStream");
1922 TypeDumpVisitor
TDV(TpiTypes
, &Writer
, opts::CodeViewSubsectionBytes
);
1923 TDV
.setIpiTypes(IpiTypes
);
1924 error(codeview::visitTypeStream(IpiTypes
, TDV
));