1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file implements the COFF-specific dumper for llvm-readobj.
12 //===----------------------------------------------------------------------===//
14 #include "ARMWinEHPrinter.h"
16 #include "ObjDumper.h"
17 #include "StackMapPrinter.h"
18 #include "Win64EHDumper.h"
19 #include "llvm-readobj.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/BinaryFormat/COFF.h"
24 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
25 #include "llvm/DebugInfo/CodeView/CodeView.h"
26 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
31 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
32 #include "llvm/DebugInfo/CodeView/Line.h"
33 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
34 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
37 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
38 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
39 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
40 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
41 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
42 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
43 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
44 #include "llvm/Object/COFF.h"
45 #include "llvm/Object/ObjectFile.h"
46 #include "llvm/Support/BinaryStreamReader.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/FormatVariadic.h"
51 #include "llvm/Support/ScopedPrinter.h"
52 #include "llvm/Support/LEB128.h"
53 #include "llvm/Support/Win64EH.h"
54 #include "llvm/Support/raw_ostream.h"
57 using namespace llvm::object
;
58 using namespace llvm::codeview
;
59 using namespace llvm::support
;
60 using namespace llvm::Win64EH
;
64 struct LoadConfigTables
{
65 uint64_t SEHTableVA
= 0;
66 uint64_t SEHTableCount
= 0;
67 uint32_t GuardFlags
= 0;
68 uint64_t GuardFidTableVA
= 0;
69 uint64_t GuardFidTableCount
= 0;
70 uint64_t GuardLJmpTableVA
= 0;
71 uint64_t GuardLJmpTableCount
= 0;
74 class COFFDumper
: public ObjDumper
{
76 friend class COFFObjectDumpDelegate
;
77 COFFDumper(const llvm::object::COFFObjectFile
*Obj
, ScopedPrinter
&Writer
)
78 : ObjDumper(Writer
), Obj(Obj
), Writer(Writer
), Types(100) {}
80 void printFileHeaders() override
;
81 void printSectionHeaders() override
;
82 void printRelocations() override
;
83 void printUnwindInfo() override
;
85 void printNeededLibraries() override
;
87 void printCOFFImports() override
;
88 void printCOFFExports() override
;
89 void printCOFFDirectives() override
;
90 void printCOFFBaseReloc() override
;
91 void printCOFFDebugDirectory() override
;
92 void printCOFFResources() override
;
93 void printCOFFLoadConfig() override
;
94 void printCodeViewDebugInfo() override
;
95 void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder
&CVIDs
,
96 llvm::codeview::MergingTypeTableBuilder
&CVTypes
,
97 llvm::codeview::GlobalTypeTableBuilder
&GlobalCVIDs
,
98 llvm::codeview::GlobalTypeTableBuilder
&GlobalCVTypes
,
100 void printStackMap() const override
;
101 void printAddrsig() override
;
103 void printSymbols() override
;
104 void printDynamicSymbols() override
;
105 void printSymbol(const SymbolRef
&Sym
);
106 void printRelocation(const SectionRef
&Section
, const RelocationRef
&Reloc
,
108 void printDataDirectory(uint32_t Index
, const std::string
&FieldName
);
110 void printDOSHeader(const dos_header
*DH
);
111 template <class PEHeader
> void printPEHeader(const PEHeader
*Hdr
);
112 void printBaseOfDataField(const pe32_header
*Hdr
);
113 void printBaseOfDataField(const pe32plus_header
*Hdr
);
114 template <typename T
>
115 void printCOFFLoadConfig(const T
*Conf
, LoadConfigTables
&Tables
);
116 typedef void (*PrintExtraCB
)(raw_ostream
&, const uint8_t *);
117 void printRVATable(uint64_t TableVA
, uint64_t Count
, uint64_t EntrySize
,
118 PrintExtraCB PrintExtra
= 0);
120 void printCodeViewSymbolSection(StringRef SectionName
, const SectionRef
&Section
);
121 void printCodeViewTypeSection(StringRef SectionName
, const SectionRef
&Section
);
122 StringRef
getTypeName(TypeIndex Ty
);
123 StringRef
getFileNameForFileOffset(uint32_t FileOffset
);
124 void printFileNameForOffset(StringRef Label
, uint32_t FileOffset
);
125 void printTypeIndex(StringRef FieldName
, TypeIndex TI
) {
126 // Forward to CVTypeDumper for simplicity.
127 codeview::printTypeIndex(Writer
, FieldName
, TI
, Types
);
130 void printCodeViewSymbolsSubsection(StringRef Subsection
,
131 const SectionRef
&Section
,
132 StringRef SectionContents
);
134 void printCodeViewFileChecksums(StringRef Subsection
);
136 void printCodeViewInlineeLines(StringRef Subsection
);
138 void printRelocatedField(StringRef Label
, const coff_section
*Sec
,
139 uint32_t RelocOffset
, uint32_t Offset
,
140 StringRef
*RelocSym
= nullptr);
142 uint32_t countTotalTableEntries(ResourceSectionRef RSF
,
143 const coff_resource_dir_table
&Table
,
146 void printResourceDirectoryTable(ResourceSectionRef RSF
,
147 const coff_resource_dir_table
&Table
,
150 void printBinaryBlockWithRelocs(StringRef Label
, const SectionRef
&Sec
,
151 StringRef SectionContents
, StringRef Block
);
153 /// Given a .debug$S section, find the string table and file checksum table.
154 void initializeFileAndStringTables(BinaryStreamReader
&Reader
);
156 void cacheRelocations();
158 std::error_code
resolveSymbol(const coff_section
*Section
, uint64_t Offset
,
160 std::error_code
resolveSymbolName(const coff_section
*Section
,
161 uint64_t Offset
, StringRef
&Name
);
162 std::error_code
resolveSymbolName(const coff_section
*Section
,
163 StringRef SectionContents
,
164 const void *RelocPtr
, StringRef
&Name
);
165 void printImportedSymbols(iterator_range
<imported_symbol_iterator
> Range
);
166 void printDelayImportedSymbols(
167 const DelayImportDirectoryEntryRef
&I
,
168 iterator_range
<imported_symbol_iterator
> Range
);
169 ErrorOr
<const coff_resource_dir_entry
&>
170 getResourceDirectoryTableEntry(const coff_resource_dir_table
&Table
,
173 typedef DenseMap
<const coff_section
*, std::vector
<RelocationRef
> > RelocMapTy
;
175 const llvm::object::COFFObjectFile
*Obj
;
176 bool RelocCached
= false;
179 DebugChecksumsSubsectionRef CVFileChecksumTable
;
181 DebugStringTableSubsectionRef CVStringTable
;
183 /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
184 /// first, but if we don't see one, just assume an X64 CPU type. It is common.
185 CPUType CompilationCPUType
= CPUType::X64
;
187 ScopedPrinter
&Writer
;
188 BinaryByteStream TypeContents
;
189 LazyRandomTypeCollection Types
;
192 class COFFObjectDumpDelegate
: public SymbolDumpDelegate
{
194 COFFObjectDumpDelegate(COFFDumper
&CD
, const SectionRef
&SR
,
195 const COFFObjectFile
*Obj
, StringRef SectionContents
)
196 : CD(CD
), SR(SR
), SectionContents(SectionContents
) {
197 Sec
= Obj
->getCOFFSection(SR
);
200 uint32_t getRecordOffset(BinaryStreamReader Reader
) override
{
201 ArrayRef
<uint8_t> Data
;
202 if (auto EC
= Reader
.readLongestContiguousChunk(Data
)) {
203 llvm::consumeError(std::move(EC
));
206 return Data
.data() - SectionContents
.bytes_begin();
209 void printRelocatedField(StringRef Label
, uint32_t RelocOffset
,
210 uint32_t Offset
, StringRef
*RelocSym
) override
{
211 CD
.printRelocatedField(Label
, Sec
, RelocOffset
, Offset
, RelocSym
);
214 void printBinaryBlockWithRelocs(StringRef Label
,
215 ArrayRef
<uint8_t> Block
) override
{
216 StringRef
SBlock(reinterpret_cast<const char *>(Block
.data()),
218 if (opts::CodeViewSubsectionBytes
)
219 CD
.printBinaryBlockWithRelocs(Label
, SR
, SectionContents
, SBlock
);
222 StringRef
getFileNameForFileOffset(uint32_t FileOffset
) override
{
223 return CD
.getFileNameForFileOffset(FileOffset
);
226 DebugStringTableSubsectionRef
getStringTable() override
{
227 return CD
.CVStringTable
;
232 const SectionRef
&SR
;
233 const coff_section
*Sec
;
234 StringRef SectionContents
;
241 std::error_code
createCOFFDumper(const object::ObjectFile
*Obj
,
242 ScopedPrinter
&Writer
,
243 std::unique_ptr
<ObjDumper
> &Result
) {
244 const COFFObjectFile
*COFFObj
= dyn_cast
<COFFObjectFile
>(Obj
);
246 return readobj_error::unsupported_obj_file_format
;
248 Result
.reset(new COFFDumper(COFFObj
, Writer
));
249 return readobj_error::success
;
254 // Given a section and an offset into this section the function returns the
255 // symbol used for the relocation at the offset.
256 std::error_code
COFFDumper::resolveSymbol(const coff_section
*Section
,
257 uint64_t Offset
, SymbolRef
&Sym
) {
259 const auto &Relocations
= RelocMap
[Section
];
260 auto SymI
= Obj
->symbol_end();
261 for (const auto &Relocation
: Relocations
) {
262 uint64_t RelocationOffset
= Relocation
.getOffset();
264 if (RelocationOffset
== Offset
) {
265 SymI
= Relocation
.getSymbol();
269 if (SymI
== Obj
->symbol_end())
270 return readobj_error::unknown_symbol
;
272 return readobj_error::success
;
275 // Given a section and an offset into this section the function returns the name
276 // of the symbol used for the relocation at the offset.
277 std::error_code
COFFDumper::resolveSymbolName(const coff_section
*Section
,
281 if (std::error_code EC
= resolveSymbol(Section
, Offset
, Symbol
))
283 Expected
<StringRef
> NameOrErr
= Symbol
.getName();
285 return errorToErrorCode(NameOrErr
.takeError());
287 return std::error_code();
290 // Helper for when you have a pointer to real data and you want to know about
291 // relocations against it.
292 std::error_code
COFFDumper::resolveSymbolName(const coff_section
*Section
,
293 StringRef SectionContents
,
294 const void *RelocPtr
,
296 assert(SectionContents
.data() < RelocPtr
&&
297 RelocPtr
< SectionContents
.data() + SectionContents
.size() &&
298 "pointer to relocated object is not in section");
299 uint64_t Offset
= ptrdiff_t(reinterpret_cast<const char *>(RelocPtr
) -
300 SectionContents
.data());
301 return resolveSymbolName(Section
, Offset
, Name
);
304 void COFFDumper::printRelocatedField(StringRef Label
, const coff_section
*Sec
,
305 uint32_t RelocOffset
, uint32_t Offset
,
306 StringRef
*RelocSym
) {
307 StringRef SymStorage
;
308 StringRef
&Symbol
= RelocSym
? *RelocSym
: SymStorage
;
309 if (!resolveSymbolName(Sec
, RelocOffset
, Symbol
))
310 W
.printSymbolOffset(Label
, Symbol
, Offset
);
312 W
.printHex(Label
, RelocOffset
);
315 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label
,
316 const SectionRef
&Sec
,
317 StringRef SectionContents
,
319 W
.printBinaryBlock(Label
, Block
);
321 assert(SectionContents
.begin() < Block
.begin() &&
322 SectionContents
.end() >= Block
.end() &&
323 "Block is not contained in SectionContents");
324 uint64_t OffsetStart
= Block
.data() - SectionContents
.data();
325 uint64_t OffsetEnd
= OffsetStart
+ Block
.size();
329 ListScope
D(W
, "BlockRelocations");
330 const coff_section
*Section
= Obj
->getCOFFSection(Sec
);
331 const auto &Relocations
= RelocMap
[Section
];
332 for (const auto &Relocation
: Relocations
) {
333 uint64_t RelocationOffset
= Relocation
.getOffset();
334 if (OffsetStart
<= RelocationOffset
&& RelocationOffset
< OffsetEnd
)
335 printRelocation(Sec
, Relocation
, OffsetStart
);
339 static const EnumEntry
<COFF::MachineTypes
> ImageFileMachineType
[] = {
340 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_UNKNOWN
),
341 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_AM33
),
342 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_AMD64
),
343 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARM
),
344 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARM64
),
345 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_ARMNT
),
346 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_EBC
),
347 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_I386
),
348 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_IA64
),
349 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_M32R
),
350 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPS16
),
351 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPSFPU
),
352 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_MIPSFPU16
),
353 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_POWERPC
),
354 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_POWERPCFP
),
355 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_R4000
),
356 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH3
),
357 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH3DSP
),
358 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH4
),
359 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_SH5
),
360 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_THUMB
),
361 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_MACHINE_WCEMIPSV2
)
364 static const EnumEntry
<COFF::Characteristics
> ImageFileCharacteristics
[] = {
365 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_RELOCS_STRIPPED
),
366 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_EXECUTABLE_IMAGE
),
367 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LINE_NUMS_STRIPPED
),
368 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LOCAL_SYMS_STRIPPED
),
369 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_AGGRESSIVE_WS_TRIM
),
370 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_LARGE_ADDRESS_AWARE
),
371 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_BYTES_REVERSED_LO
),
372 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_32BIT_MACHINE
),
373 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_DEBUG_STRIPPED
),
374 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP
),
375 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_NET_RUN_FROM_SWAP
),
376 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_SYSTEM
),
377 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_DLL
),
378 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_UP_SYSTEM_ONLY
),
379 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_FILE_BYTES_REVERSED_HI
)
382 static const EnumEntry
<COFF::WindowsSubsystem
> PEWindowsSubsystem
[] = {
383 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_UNKNOWN
),
384 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_NATIVE
),
385 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_GUI
),
386 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_CUI
),
387 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_POSIX_CUI
),
388 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI
),
389 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_APPLICATION
),
390 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER
),
391 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER
),
392 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_EFI_ROM
),
393 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SUBSYSTEM_XBOX
),
396 static const EnumEntry
<COFF::DLLCharacteristics
> PEDLLCharacteristics
[] = {
397 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA
),
398 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
),
399 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY
),
400 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
),
401 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION
),
402 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_SEH
),
403 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_NO_BIND
),
404 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER
),
405 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER
),
406 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_GUARD_CF
),
407 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE
),
410 static const EnumEntry
<COFF::SectionCharacteristics
>
411 ImageSectionCharacteristics
[] = {
412 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_TYPE_NOLOAD
),
413 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_TYPE_NO_PAD
),
414 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_CODE
),
415 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_INITIALIZED_DATA
),
416 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_CNT_UNINITIALIZED_DATA
),
417 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_OTHER
),
418 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_INFO
),
419 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_REMOVE
),
420 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_COMDAT
),
421 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_GPREL
),
422 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_PURGEABLE
),
423 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_16BIT
),
424 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_LOCKED
),
425 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_PRELOAD
),
426 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_1BYTES
),
427 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_2BYTES
),
428 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_4BYTES
),
429 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_8BYTES
),
430 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_16BYTES
),
431 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_32BYTES
),
432 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_64BYTES
),
433 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_128BYTES
),
434 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_256BYTES
),
435 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_512BYTES
),
436 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_1024BYTES
),
437 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_2048BYTES
),
438 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_4096BYTES
),
439 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_ALIGN_8192BYTES
),
440 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_LNK_NRELOC_OVFL
),
441 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_DISCARDABLE
),
442 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_NOT_CACHED
),
443 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_NOT_PAGED
),
444 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_SHARED
),
445 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_EXECUTE
),
446 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_READ
),
447 LLVM_READOBJ_ENUM_ENT(COFF
, IMAGE_SCN_MEM_WRITE
)
450 static const EnumEntry
<COFF::SymbolBaseType
> ImageSymType
[] = {
451 { "Null" , COFF::IMAGE_SYM_TYPE_NULL
},
452 { "Void" , COFF::IMAGE_SYM_TYPE_VOID
},
453 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR
},
454 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT
},
455 { "Int" , COFF::IMAGE_SYM_TYPE_INT
},
456 { "Long" , COFF::IMAGE_SYM_TYPE_LONG
},
457 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT
},
458 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE
},
459 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT
},
460 { "Union" , COFF::IMAGE_SYM_TYPE_UNION
},
461 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM
},
462 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE
},
463 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE
},
464 { "Word" , COFF::IMAGE_SYM_TYPE_WORD
},
465 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT
},
466 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD
}
469 static const EnumEntry
<COFF::SymbolComplexType
> ImageSymDType
[] = {
470 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL
},
471 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER
},
472 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION
},
473 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY
}
476 static const EnumEntry
<COFF::SymbolStorageClass
> ImageSymClass
[] = {
477 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION
},
478 { "Null" , COFF::IMAGE_SYM_CLASS_NULL
},
479 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC
},
480 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL
},
481 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC
},
482 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER
},
483 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF
},
484 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL
},
485 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL
},
486 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT
},
487 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT
},
488 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG
},
489 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION
},
490 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG
},
491 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION
},
492 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC
},
493 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG
},
494 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM
},
495 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM
},
496 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD
},
497 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK
},
498 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION
},
499 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT
},
500 { "File" , COFF::IMAGE_SYM_CLASS_FILE
},
501 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION
},
502 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL
},
503 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN
}
506 static const EnumEntry
<COFF::COMDATType
> ImageCOMDATSelect
[] = {
507 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES
},
508 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY
},
509 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE
},
510 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH
},
511 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
},
512 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST
},
513 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST
}
516 static const EnumEntry
<COFF::DebugType
> ImageDebugType
[] = {
517 { "Unknown" , COFF::IMAGE_DEBUG_TYPE_UNKNOWN
},
518 { "COFF" , COFF::IMAGE_DEBUG_TYPE_COFF
},
519 { "CodeView" , COFF::IMAGE_DEBUG_TYPE_CODEVIEW
},
520 { "FPO" , COFF::IMAGE_DEBUG_TYPE_FPO
},
521 { "Misc" , COFF::IMAGE_DEBUG_TYPE_MISC
},
522 { "Exception" , COFF::IMAGE_DEBUG_TYPE_EXCEPTION
},
523 { "Fixup" , COFF::IMAGE_DEBUG_TYPE_FIXUP
},
524 { "OmapToSrc" , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC
},
525 { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC
},
526 { "Borland" , COFF::IMAGE_DEBUG_TYPE_BORLAND
},
527 { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10
},
528 { "CLSID" , COFF::IMAGE_DEBUG_TYPE_CLSID
},
529 { "VCFeature" , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE
},
530 { "POGO" , COFF::IMAGE_DEBUG_TYPE_POGO
},
531 { "ILTCG" , COFF::IMAGE_DEBUG_TYPE_ILTCG
},
532 { "MPX" , COFF::IMAGE_DEBUG_TYPE_MPX
},
533 { "Repro" , COFF::IMAGE_DEBUG_TYPE_REPRO
},
536 static const EnumEntry
<COFF::WeakExternalCharacteristics
>
537 WeakExternalCharacteristics
[] = {
538 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY
},
539 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY
},
540 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS
}
543 static const EnumEntry
<uint32_t> SubSectionTypes
[] = {
544 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, Symbols
),
545 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, Lines
),
546 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, StringTable
),
547 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FileChecksums
),
548 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FrameData
),
549 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, InlineeLines
),
550 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CrossScopeImports
),
551 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CrossScopeExports
),
552 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, ILLines
),
553 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, FuncMDTokenMap
),
554 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, TypeMDTokenMap
),
555 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, MergedAssemblyInput
),
556 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind
, CoffSymbolRVA
),
559 static const EnumEntry
<uint32_t> FrameDataFlags
[] = {
560 LLVM_READOBJ_ENUM_ENT(FrameData
, HasSEH
),
561 LLVM_READOBJ_ENUM_ENT(FrameData
, HasEH
),
562 LLVM_READOBJ_ENUM_ENT(FrameData
, IsFunctionStart
),
565 static const EnumEntry
<uint8_t> FileChecksumKindNames
[] = {
566 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, None
),
567 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, MD5
),
568 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, SHA1
),
569 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind
, SHA256
),
572 static const EnumEntry
<COFF::ResourceTypeID
> ResourceTypeNames
[]{
573 {"kRT_CURSOR (ID 1)", COFF::RID_Cursor
},
574 {"kRT_BITMAP (ID 2)", COFF::RID_Bitmap
},
575 {"kRT_ICON (ID 3)", COFF::RID_Icon
},
576 {"kRT_MENU (ID 4)", COFF::RID_Menu
},
577 {"kRT_DIALOG (ID 5)", COFF::RID_Dialog
},
578 {"kRT_STRING (ID 6)", COFF::RID_String
},
579 {"kRT_FONTDIR (ID 7)", COFF::RID_FontDir
},
580 {"kRT_FONT (ID 8)", COFF::RID_Font
},
581 {"kRT_ACCELERATOR (ID 9)", COFF::RID_Accelerator
},
582 {"kRT_RCDATA (ID 10)", COFF::RID_RCData
},
583 {"kRT_MESSAGETABLE (ID 11)", COFF::RID_MessageTable
},
584 {"kRT_GROUP_CURSOR (ID 12)", COFF::RID_Group_Cursor
},
585 {"kRT_GROUP_ICON (ID 14)", COFF::RID_Group_Icon
},
586 {"kRT_VERSION (ID 16)", COFF::RID_Version
},
587 {"kRT_DLGINCLUDE (ID 17)", COFF::RID_DLGInclude
},
588 {"kRT_PLUGPLAY (ID 19)", COFF::RID_PlugPlay
},
589 {"kRT_VXD (ID 20)", COFF::RID_VXD
},
590 {"kRT_ANICURSOR (ID 21)", COFF::RID_AniCursor
},
591 {"kRT_ANIICON (ID 22)", COFF::RID_AniIcon
},
592 {"kRT_HTML (ID 23)", COFF::RID_HTML
},
593 {"kRT_MANIFEST (ID 24)", COFF::RID_Manifest
}};
595 template <typename T
>
596 static std::error_code
getSymbolAuxData(const COFFObjectFile
*Obj
,
597 COFFSymbolRef Symbol
,
598 uint8_t AuxSymbolIdx
, const T
*&Aux
) {
599 ArrayRef
<uint8_t> AuxData
= Obj
->getSymbolAuxData(Symbol
);
600 AuxData
= AuxData
.slice(AuxSymbolIdx
* Obj
->getSymbolTableEntrySize());
601 Aux
= reinterpret_cast<const T
*>(AuxData
.data());
602 return readobj_error::success
;
605 void COFFDumper::cacheRelocations() {
610 for (const SectionRef
&S
: Obj
->sections()) {
611 const coff_section
*Section
= Obj
->getCOFFSection(S
);
613 for (const RelocationRef
&Reloc
: S
.relocations())
614 RelocMap
[Section
].push_back(Reloc
);
616 // Sort relocations by address.
617 llvm::sort(RelocMap
[Section
], relocAddressLess
);
621 void COFFDumper::printDataDirectory(uint32_t Index
, const std::string
&FieldName
) {
622 const data_directory
*Data
;
623 if (Obj
->getDataDirectory(Index
, Data
))
625 W
.printHex(FieldName
+ "RVA", Data
->RelativeVirtualAddress
);
626 W
.printHex(FieldName
+ "Size", Data
->Size
);
629 void COFFDumper::printFileHeaders() {
630 time_t TDS
= Obj
->getTimeDateStamp();
631 char FormattedTime
[20] = { };
632 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
635 DictScope
D(W
, "ImageFileHeader");
636 W
.printEnum ("Machine", Obj
->getMachine(),
637 makeArrayRef(ImageFileMachineType
));
638 W
.printNumber("SectionCount", Obj
->getNumberOfSections());
639 W
.printHex ("TimeDateStamp", FormattedTime
, Obj
->getTimeDateStamp());
640 W
.printHex ("PointerToSymbolTable", Obj
->getPointerToSymbolTable());
641 W
.printNumber("SymbolCount", Obj
->getNumberOfSymbols());
642 W
.printNumber("OptionalHeaderSize", Obj
->getSizeOfOptionalHeader());
643 W
.printFlags ("Characteristics", Obj
->getCharacteristics(),
644 makeArrayRef(ImageFileCharacteristics
));
647 // Print PE header. This header does not exist if this is an object file and
648 // not an executable.
649 const pe32_header
*PEHeader
= nullptr;
650 error(Obj
->getPE32Header(PEHeader
));
652 printPEHeader
<pe32_header
>(PEHeader
);
654 const pe32plus_header
*PEPlusHeader
= nullptr;
655 error(Obj
->getPE32PlusHeader(PEPlusHeader
));
657 printPEHeader
<pe32plus_header
>(PEPlusHeader
);
659 if (const dos_header
*DH
= Obj
->getDOSHeader())
663 void COFFDumper::printDOSHeader(const dos_header
*DH
) {
664 DictScope
D(W
, "DOSHeader");
665 W
.printString("Magic", StringRef(DH
->Magic
, sizeof(DH
->Magic
)));
666 W
.printNumber("UsedBytesInTheLastPage", DH
->UsedBytesInTheLastPage
);
667 W
.printNumber("FileSizeInPages", DH
->FileSizeInPages
);
668 W
.printNumber("NumberOfRelocationItems", DH
->NumberOfRelocationItems
);
669 W
.printNumber("HeaderSizeInParagraphs", DH
->HeaderSizeInParagraphs
);
670 W
.printNumber("MinimumExtraParagraphs", DH
->MinimumExtraParagraphs
);
671 W
.printNumber("MaximumExtraParagraphs", DH
->MaximumExtraParagraphs
);
672 W
.printNumber("InitialRelativeSS", DH
->InitialRelativeSS
);
673 W
.printNumber("InitialSP", DH
->InitialSP
);
674 W
.printNumber("Checksum", DH
->Checksum
);
675 W
.printNumber("InitialIP", DH
->InitialIP
);
676 W
.printNumber("InitialRelativeCS", DH
->InitialRelativeCS
);
677 W
.printNumber("AddressOfRelocationTable", DH
->AddressOfRelocationTable
);
678 W
.printNumber("OverlayNumber", DH
->OverlayNumber
);
679 W
.printNumber("OEMid", DH
->OEMid
);
680 W
.printNumber("OEMinfo", DH
->OEMinfo
);
681 W
.printNumber("AddressOfNewExeHeader", DH
->AddressOfNewExeHeader
);
684 template <class PEHeader
>
685 void COFFDumper::printPEHeader(const PEHeader
*Hdr
) {
686 DictScope
D(W
, "ImageOptionalHeader");
687 W
.printHex ("Magic", Hdr
->Magic
);
688 W
.printNumber("MajorLinkerVersion", Hdr
->MajorLinkerVersion
);
689 W
.printNumber("MinorLinkerVersion", Hdr
->MinorLinkerVersion
);
690 W
.printNumber("SizeOfCode", Hdr
->SizeOfCode
);
691 W
.printNumber("SizeOfInitializedData", Hdr
->SizeOfInitializedData
);
692 W
.printNumber("SizeOfUninitializedData", Hdr
->SizeOfUninitializedData
);
693 W
.printHex ("AddressOfEntryPoint", Hdr
->AddressOfEntryPoint
);
694 W
.printHex ("BaseOfCode", Hdr
->BaseOfCode
);
695 printBaseOfDataField(Hdr
);
696 W
.printHex ("ImageBase", Hdr
->ImageBase
);
697 W
.printNumber("SectionAlignment", Hdr
->SectionAlignment
);
698 W
.printNumber("FileAlignment", Hdr
->FileAlignment
);
699 W
.printNumber("MajorOperatingSystemVersion",
700 Hdr
->MajorOperatingSystemVersion
);
701 W
.printNumber("MinorOperatingSystemVersion",
702 Hdr
->MinorOperatingSystemVersion
);
703 W
.printNumber("MajorImageVersion", Hdr
->MajorImageVersion
);
704 W
.printNumber("MinorImageVersion", Hdr
->MinorImageVersion
);
705 W
.printNumber("MajorSubsystemVersion", Hdr
->MajorSubsystemVersion
);
706 W
.printNumber("MinorSubsystemVersion", Hdr
->MinorSubsystemVersion
);
707 W
.printNumber("SizeOfImage", Hdr
->SizeOfImage
);
708 W
.printNumber("SizeOfHeaders", Hdr
->SizeOfHeaders
);
709 W
.printEnum ("Subsystem", Hdr
->Subsystem
, makeArrayRef(PEWindowsSubsystem
));
710 W
.printFlags ("Characteristics", Hdr
->DLLCharacteristics
,
711 makeArrayRef(PEDLLCharacteristics
));
712 W
.printNumber("SizeOfStackReserve", Hdr
->SizeOfStackReserve
);
713 W
.printNumber("SizeOfStackCommit", Hdr
->SizeOfStackCommit
);
714 W
.printNumber("SizeOfHeapReserve", Hdr
->SizeOfHeapReserve
);
715 W
.printNumber("SizeOfHeapCommit", Hdr
->SizeOfHeapCommit
);
716 W
.printNumber("NumberOfRvaAndSize", Hdr
->NumberOfRvaAndSize
);
718 if (Hdr
->NumberOfRvaAndSize
> 0) {
719 DictScope
D(W
, "DataDirectory");
720 static const char * const directory
[] = {
721 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
722 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
723 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
724 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
727 for (uint32_t i
= 0; i
< Hdr
->NumberOfRvaAndSize
; ++i
)
728 printDataDirectory(i
, directory
[i
]);
732 void COFFDumper::printCOFFDebugDirectory() {
733 ListScope
LS(W
, "DebugDirectory");
734 for (const debug_directory
&D
: Obj
->debug_directories()) {
735 char FormattedTime
[20] = {};
736 time_t TDS
= D
.TimeDateStamp
;
737 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
738 DictScope
S(W
, "DebugEntry");
739 W
.printHex("Characteristics", D
.Characteristics
);
740 W
.printHex("TimeDateStamp", FormattedTime
, D
.TimeDateStamp
);
741 W
.printHex("MajorVersion", D
.MajorVersion
);
742 W
.printHex("MinorVersion", D
.MinorVersion
);
743 W
.printEnum("Type", D
.Type
, makeArrayRef(ImageDebugType
));
744 W
.printHex("SizeOfData", D
.SizeOfData
);
745 W
.printHex("AddressOfRawData", D
.AddressOfRawData
);
746 W
.printHex("PointerToRawData", D
.PointerToRawData
);
747 if (D
.Type
== COFF::IMAGE_DEBUG_TYPE_CODEVIEW
) {
748 const codeview::DebugInfo
*DebugInfo
;
749 StringRef PDBFileName
;
750 error(Obj
->getDebugPDBInfo(&D
, DebugInfo
, PDBFileName
));
751 DictScope
PDBScope(W
, "PDBInfo");
752 W
.printHex("PDBSignature", DebugInfo
->Signature
.CVSignature
);
753 if (DebugInfo
->Signature
.CVSignature
== OMF::Signature::PDB70
) {
754 W
.printBinary("PDBGUID", makeArrayRef(DebugInfo
->PDB70
.Signature
));
755 W
.printNumber("PDBAge", DebugInfo
->PDB70
.Age
);
756 W
.printString("PDBFileName", PDBFileName
);
758 } else if (D
.SizeOfData
!= 0) {
759 // FIXME: Type values of 12 and 13 are commonly observed but are not in
760 // the documented type enum. Figure out what they mean.
761 ArrayRef
<uint8_t> RawData
;
763 Obj
->getRvaAndSizeAsBytes(D
.AddressOfRawData
, D
.SizeOfData
, RawData
));
764 W
.printBinaryBlock("RawData", RawData
);
769 void COFFDumper::printRVATable(uint64_t TableVA
, uint64_t Count
,
770 uint64_t EntrySize
, PrintExtraCB PrintExtra
) {
771 uintptr_t TableStart
, TableEnd
;
772 error(Obj
->getVaPtr(TableVA
, TableStart
));
773 error(Obj
->getVaPtr(TableVA
+ Count
* EntrySize
- 1, TableEnd
));
775 for (uintptr_t I
= TableStart
; I
< TableEnd
; I
+= EntrySize
) {
776 uint32_t RVA
= *reinterpret_cast<const ulittle32_t
*>(I
);
777 raw_ostream
&OS
= W
.startLine();
778 OS
<< W
.hex(Obj
->getImageBase() + RVA
);
780 PrintExtra(OS
, reinterpret_cast<const uint8_t *>(I
));
785 void COFFDumper::printCOFFLoadConfig() {
786 LoadConfigTables Tables
;
788 printCOFFLoadConfig(Obj
->getLoadConfig64(), Tables
);
790 printCOFFLoadConfig(Obj
->getLoadConfig32(), Tables
);
792 if (Tables
.SEHTableVA
) {
793 ListScope
LS(W
, "SEHTable");
794 printRVATable(Tables
.SEHTableVA
, Tables
.SEHTableCount
, 4);
797 if (Tables
.GuardFidTableVA
) {
798 ListScope
LS(W
, "GuardFidTable");
799 if (Tables
.GuardFlags
& uint32_t(coff_guard_flags::FidTableHasFlags
)) {
800 auto PrintGuardFlags
= [](raw_ostream
&OS
, const uint8_t *Entry
) {
801 uint8_t Flags
= *reinterpret_cast<const uint8_t *>(Entry
+ 4);
803 OS
<< " flags " << utohexstr(Flags
);
805 printRVATable(Tables
.GuardFidTableVA
, Tables
.GuardFidTableCount
, 5,
808 printRVATable(Tables
.GuardFidTableVA
, Tables
.GuardFidTableCount
, 4);
812 if (Tables
.GuardLJmpTableVA
) {
813 ListScope
LS(W
, "GuardLJmpTable");
814 printRVATable(Tables
.GuardLJmpTableVA
, Tables
.GuardLJmpTableCount
, 4);
818 template <typename T
>
819 void COFFDumper::printCOFFLoadConfig(const T
*Conf
, LoadConfigTables
&Tables
) {
823 ListScope
LS(W
, "LoadConfig");
824 char FormattedTime
[20] = {};
825 time_t TDS
= Conf
->TimeDateStamp
;
826 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
827 W
.printHex("Size", Conf
->Size
);
829 // Print everything before SecurityCookie. The vast majority of images today
830 // have all these fields.
831 if (Conf
->Size
< offsetof(T
, SEHandlerTable
))
833 W
.printHex("TimeDateStamp", FormattedTime
, TDS
);
834 W
.printHex("MajorVersion", Conf
->MajorVersion
);
835 W
.printHex("MinorVersion", Conf
->MinorVersion
);
836 W
.printHex("GlobalFlagsClear", Conf
->GlobalFlagsClear
);
837 W
.printHex("GlobalFlagsSet", Conf
->GlobalFlagsSet
);
838 W
.printHex("CriticalSectionDefaultTimeout",
839 Conf
->CriticalSectionDefaultTimeout
);
840 W
.printHex("DeCommitFreeBlockThreshold", Conf
->DeCommitFreeBlockThreshold
);
841 W
.printHex("DeCommitTotalFreeThreshold", Conf
->DeCommitTotalFreeThreshold
);
842 W
.printHex("LockPrefixTable", Conf
->LockPrefixTable
);
843 W
.printHex("MaximumAllocationSize", Conf
->MaximumAllocationSize
);
844 W
.printHex("VirtualMemoryThreshold", Conf
->VirtualMemoryThreshold
);
845 W
.printHex("ProcessHeapFlags", Conf
->ProcessHeapFlags
);
846 W
.printHex("ProcessAffinityMask", Conf
->ProcessAffinityMask
);
847 W
.printHex("CSDVersion", Conf
->CSDVersion
);
848 W
.printHex("DependentLoadFlags", Conf
->DependentLoadFlags
);
849 W
.printHex("EditList", Conf
->EditList
);
850 W
.printHex("SecurityCookie", Conf
->SecurityCookie
);
852 // Print the safe SEH table if present.
853 if (Conf
->Size
< offsetof(coff_load_configuration32
, GuardCFCheckFunction
))
855 W
.printHex("SEHandlerTable", Conf
->SEHandlerTable
);
856 W
.printNumber("SEHandlerCount", Conf
->SEHandlerCount
);
858 Tables
.SEHTableVA
= Conf
->SEHandlerTable
;
859 Tables
.SEHTableCount
= Conf
->SEHandlerCount
;
861 // Print everything before CodeIntegrity. (2015)
862 if (Conf
->Size
< offsetof(T
, CodeIntegrity
))
864 W
.printHex("GuardCFCheckFunction", Conf
->GuardCFCheckFunction
);
865 W
.printHex("GuardCFCheckDispatch", Conf
->GuardCFCheckDispatch
);
866 W
.printHex("GuardCFFunctionTable", Conf
->GuardCFFunctionTable
);
867 W
.printNumber("GuardCFFunctionCount", Conf
->GuardCFFunctionCount
);
868 W
.printHex("GuardFlags", Conf
->GuardFlags
);
870 Tables
.GuardFidTableVA
= Conf
->GuardCFFunctionTable
;
871 Tables
.GuardFidTableCount
= Conf
->GuardCFFunctionCount
;
872 Tables
.GuardFlags
= Conf
->GuardFlags
;
874 // Print the rest. (2017)
875 if (Conf
->Size
< sizeof(T
))
877 W
.printHex("GuardAddressTakenIatEntryTable",
878 Conf
->GuardAddressTakenIatEntryTable
);
879 W
.printNumber("GuardAddressTakenIatEntryCount",
880 Conf
->GuardAddressTakenIatEntryCount
);
881 W
.printHex("GuardLongJumpTargetTable", Conf
->GuardLongJumpTargetTable
);
882 W
.printNumber("GuardLongJumpTargetCount", Conf
->GuardLongJumpTargetCount
);
883 W
.printHex("DynamicValueRelocTable", Conf
->DynamicValueRelocTable
);
884 W
.printHex("CHPEMetadataPointer", Conf
->CHPEMetadataPointer
);
885 W
.printHex("GuardRFFailureRoutine", Conf
->GuardRFFailureRoutine
);
886 W
.printHex("GuardRFFailureRoutineFunctionPointer",
887 Conf
->GuardRFFailureRoutineFunctionPointer
);
888 W
.printHex("DynamicValueRelocTableOffset",
889 Conf
->DynamicValueRelocTableOffset
);
890 W
.printNumber("DynamicValueRelocTableSection",
891 Conf
->DynamicValueRelocTableSection
);
892 W
.printHex("GuardRFVerifyStackPointerFunctionPointer",
893 Conf
->GuardRFVerifyStackPointerFunctionPointer
);
894 W
.printHex("HotPatchTableOffset", Conf
->HotPatchTableOffset
);
896 Tables
.GuardLJmpTableVA
= Conf
->GuardLongJumpTargetTable
;
897 Tables
.GuardLJmpTableCount
= Conf
->GuardLongJumpTargetCount
;
900 void COFFDumper::printBaseOfDataField(const pe32_header
*Hdr
) {
901 W
.printHex("BaseOfData", Hdr
->BaseOfData
);
904 void COFFDumper::printBaseOfDataField(const pe32plus_header
*) {}
906 void COFFDumper::printCodeViewDebugInfo() {
907 // Print types first to build CVUDTNames, then print symbols.
908 for (const SectionRef
&S
: Obj
->sections()) {
909 StringRef SectionName
;
910 error(S
.getName(SectionName
));
911 // .debug$T is a standard CodeView type section, while .debug$P is the same
912 // format but used for MSVC precompiled header object files.
913 if (SectionName
== ".debug$T" || SectionName
== ".debug$P")
914 printCodeViewTypeSection(SectionName
, S
);
916 for (const SectionRef
&S
: Obj
->sections()) {
917 StringRef SectionName
;
918 error(S
.getName(SectionName
));
919 if (SectionName
== ".debug$S")
920 printCodeViewSymbolSection(SectionName
, S
);
924 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader
&Reader
) {
925 while (Reader
.bytesRemaining() > 0 &&
926 (!CVFileChecksumTable
.valid() || !CVStringTable
.valid())) {
927 // The section consists of a number of subsection in the following format:
928 // |SubSectionType|SubSectionSize|Contents...|
929 uint32_t SubType
, SubSectionSize
;
930 error(Reader
.readInteger(SubType
));
931 error(Reader
.readInteger(SubSectionSize
));
934 error(Reader
.readFixedString(Contents
, SubSectionSize
));
936 BinaryStreamRef
ST(Contents
, support::little
);
937 switch (DebugSubsectionKind(SubType
)) {
938 case DebugSubsectionKind::FileChecksums
:
939 error(CVFileChecksumTable
.initialize(ST
));
941 case DebugSubsectionKind::StringTable
:
942 error(CVStringTable
.initialize(ST
));
948 uint32_t PaddedSize
= alignTo(SubSectionSize
, 4);
949 error(Reader
.skip(PaddedSize
- SubSectionSize
));
953 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName
,
954 const SectionRef
&Section
) {
955 StringRef SectionContents
;
956 error(Section
.getContents(SectionContents
));
957 StringRef Data
= SectionContents
;
959 SmallVector
<StringRef
, 10> FunctionNames
;
960 StringMap
<StringRef
> FunctionLineTables
;
962 ListScope
D(W
, "CodeViewDebugInfo");
963 // Print the section to allow correlation with printSectionHeaders.
964 W
.printNumber("Section", SectionName
, Obj
->getSectionID(Section
));
967 error(consume(Data
, Magic
));
968 W
.printHex("Magic", Magic
);
969 if (Magic
!= COFF::DEBUG_SECTION_MAGIC
)
970 return error(object_error::parse_failed
);
972 BinaryStreamReader
FSReader(Data
, support::little
);
973 initializeFileAndStringTables(FSReader
);
975 // TODO: Convert this over to using ModuleSubstreamVisitor.
976 while (!Data
.empty()) {
977 // The section consists of a number of subsection in the following format:
978 // |SubSectionType|SubSectionSize|Contents...|
979 uint32_t SubType
, SubSectionSize
;
980 error(consume(Data
, SubType
));
981 error(consume(Data
, SubSectionSize
));
983 ListScope
S(W
, "Subsection");
984 W
.printEnum("SubSectionType", SubType
, makeArrayRef(SubSectionTypes
));
985 W
.printHex("SubSectionSize", SubSectionSize
);
987 // Get the contents of the subsection.
988 if (SubSectionSize
> Data
.size())
989 return error(object_error::parse_failed
);
990 StringRef Contents
= Data
.substr(0, SubSectionSize
);
992 // Add SubSectionSize to the current offset and align that offset to find
993 // the next subsection.
994 size_t SectionOffset
= Data
.data() - SectionContents
.data();
995 size_t NextOffset
= SectionOffset
+ SubSectionSize
;
996 NextOffset
= alignTo(NextOffset
, 4);
997 if (NextOffset
> SectionContents
.size())
998 return error(object_error::parse_failed
);
999 Data
= SectionContents
.drop_front(NextOffset
);
1001 // Optionally print the subsection bytes in case our parsing gets confused
1003 if (opts::CodeViewSubsectionBytes
)
1004 printBinaryBlockWithRelocs("SubSectionContents", Section
, SectionContents
,
1007 switch (DebugSubsectionKind(SubType
)) {
1008 case DebugSubsectionKind::Symbols
:
1009 printCodeViewSymbolsSubsection(Contents
, Section
, SectionContents
);
1012 case DebugSubsectionKind::InlineeLines
:
1013 printCodeViewInlineeLines(Contents
);
1016 case DebugSubsectionKind::FileChecksums
:
1017 printCodeViewFileChecksums(Contents
);
1020 case DebugSubsectionKind::Lines
: {
1021 // Holds a PC to file:line table. Some data to parse this subsection is
1022 // stored in the other subsections, so just check sanity and store the
1023 // pointers for deferred processing.
1025 if (SubSectionSize
< 12) {
1026 // There should be at least three words to store two function
1027 // relocations and size of the code.
1028 error(object_error::parse_failed
);
1032 StringRef LinkageName
;
1033 error(resolveSymbolName(Obj
->getCOFFSection(Section
), SectionOffset
,
1035 W
.printString("LinkageName", LinkageName
);
1036 if (FunctionLineTables
.count(LinkageName
) != 0) {
1037 // Saw debug info for this function already?
1038 error(object_error::parse_failed
);
1042 FunctionLineTables
[LinkageName
] = Contents
;
1043 FunctionNames
.push_back(LinkageName
);
1046 case DebugSubsectionKind::FrameData
: {
1047 // First four bytes is a relocation against the function.
1048 BinaryStreamReader
SR(Contents
, llvm::support::little
);
1050 DebugFrameDataSubsectionRef FrameData
;
1051 error(FrameData
.initialize(SR
));
1053 StringRef LinkageName
;
1054 error(resolveSymbolName(Obj
->getCOFFSection(Section
), SectionContents
,
1055 FrameData
.getRelocPtr(), LinkageName
));
1056 W
.printString("LinkageName", LinkageName
);
1058 // To find the active frame description, search this array for the
1059 // smallest PC range that includes the current PC.
1060 for (const auto &FD
: FrameData
) {
1061 StringRef FrameFunc
= error(CVStringTable
.getString(FD
.FrameFunc
));
1063 DictScope
S(W
, "FrameData");
1064 W
.printHex("RvaStart", FD
.RvaStart
);
1065 W
.printHex("CodeSize", FD
.CodeSize
);
1066 W
.printHex("LocalSize", FD
.LocalSize
);
1067 W
.printHex("ParamsSize", FD
.ParamsSize
);
1068 W
.printHex("MaxStackSize", FD
.MaxStackSize
);
1069 W
.printHex("PrologSize", FD
.PrologSize
);
1070 W
.printHex("SavedRegsSize", FD
.SavedRegsSize
);
1071 W
.printFlags("Flags", FD
.Flags
, makeArrayRef(FrameDataFlags
));
1073 // The FrameFunc string is a small RPN program. It can be broken up into
1074 // statements that end in the '=' operator, which assigns the value on
1075 // the top of the stack to the previously pushed variable. Variables can
1076 // be temporary values ($T0) or physical registers ($esp). Print each
1077 // assignment on its own line to make these programs easier to read.
1079 ListScope
FFS(W
, "FrameFunc");
1080 while (!FrameFunc
.empty()) {
1081 size_t EqOrEnd
= FrameFunc
.find('=');
1082 if (EqOrEnd
== StringRef::npos
)
1083 EqOrEnd
= FrameFunc
.size();
1086 StringRef Stmt
= FrameFunc
.substr(0, EqOrEnd
);
1087 W
.printString(Stmt
);
1088 FrameFunc
= FrameFunc
.drop_front(EqOrEnd
).trim();
1095 // Do nothing for unrecognized subsections.
1102 // Dump the line tables now that we've read all the subsections and know all
1103 // the required information.
1104 for (unsigned I
= 0, E
= FunctionNames
.size(); I
!= E
; ++I
) {
1105 StringRef Name
= FunctionNames
[I
];
1106 ListScope
S(W
, "FunctionLineTable");
1107 W
.printString("LinkageName", Name
);
1109 BinaryStreamReader
Reader(FunctionLineTables
[Name
], support::little
);
1111 DebugLinesSubsectionRef LineInfo
;
1112 error(LineInfo
.initialize(Reader
));
1114 W
.printHex("Flags", LineInfo
.header()->Flags
);
1115 W
.printHex("CodeSize", LineInfo
.header()->CodeSize
);
1116 for (const auto &Entry
: LineInfo
) {
1118 ListScope
S(W
, "FilenameSegment");
1119 printFileNameForOffset("Filename", Entry
.NameIndex
);
1120 uint32_t ColumnIndex
= 0;
1121 for (const auto &Line
: Entry
.LineNumbers
) {
1122 if (Line
.Offset
>= LineInfo
.header()->CodeSize
) {
1123 error(object_error::parse_failed
);
1127 std::string PC
= formatv("+{0:X}", uint32_t(Line
.Offset
));
1128 ListScope
PCScope(W
, PC
);
1129 codeview::LineInfo
LI(Line
.Flags
);
1131 if (LI
.isAlwaysStepInto())
1132 W
.printString("StepInto", StringRef("Always"));
1133 else if (LI
.isNeverStepInto())
1134 W
.printString("StepInto", StringRef("Never"));
1136 W
.printNumber("LineNumberStart", LI
.getStartLine());
1137 W
.printNumber("LineNumberEndDelta", LI
.getLineDelta());
1138 W
.printBoolean("IsStatement", LI
.isStatement());
1139 if (LineInfo
.hasColumnInfo()) {
1140 W
.printNumber("ColStart", Entry
.Columns
[ColumnIndex
].StartColumn
);
1141 W
.printNumber("ColEnd", Entry
.Columns
[ColumnIndex
].EndColumn
);
1149 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection
,
1150 const SectionRef
&Section
,
1151 StringRef SectionContents
) {
1152 ArrayRef
<uint8_t> BinaryData(Subsection
.bytes_begin(),
1153 Subsection
.bytes_end());
1154 auto CODD
= llvm::make_unique
<COFFObjectDumpDelegate
>(*this, Section
, Obj
,
1156 CVSymbolDumper
CVSD(W
, Types
, CodeViewContainer::ObjectFile
, std::move(CODD
),
1157 CompilationCPUType
, opts::CodeViewSubsectionBytes
);
1158 CVSymbolArray Symbols
;
1159 BinaryStreamReader
Reader(BinaryData
, llvm::support::little
);
1160 if (auto EC
= Reader
.readArray(Symbols
, Reader
.getLength())) {
1161 consumeError(std::move(EC
));
1163 error(object_error::parse_failed
);
1166 if (auto EC
= CVSD
.dump(Symbols
)) {
1168 error(std::move(EC
));
1170 CompilationCPUType
= CVSD
.getCompilationCPUType();
1174 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection
) {
1175 BinaryStreamRef
Stream(Subsection
, llvm::support::little
);
1176 DebugChecksumsSubsectionRef Checksums
;
1177 error(Checksums
.initialize(Stream
));
1179 for (auto &FC
: Checksums
) {
1180 DictScope
S(W
, "FileChecksum");
1182 StringRef Filename
= error(CVStringTable
.getString(FC
.FileNameOffset
));
1183 W
.printHex("Filename", Filename
, FC
.FileNameOffset
);
1184 W
.printHex("ChecksumSize", FC
.Checksum
.size());
1185 W
.printEnum("ChecksumKind", uint8_t(FC
.Kind
),
1186 makeArrayRef(FileChecksumKindNames
));
1188 W
.printBinary("ChecksumBytes", FC
.Checksum
);
1192 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection
) {
1193 BinaryStreamReader
SR(Subsection
, llvm::support::little
);
1194 DebugInlineeLinesSubsectionRef Lines
;
1195 error(Lines
.initialize(SR
));
1197 for (auto &Line
: Lines
) {
1198 DictScope
S(W
, "InlineeSourceLine");
1199 printTypeIndex("Inlinee", Line
.Header
->Inlinee
);
1200 printFileNameForOffset("FileID", Line
.Header
->FileID
);
1201 W
.printNumber("SourceLineNum", Line
.Header
->SourceLineNum
);
1203 if (Lines
.hasExtraFiles()) {
1204 W
.printNumber("ExtraFileCount", Line
.ExtraFiles
.size());
1205 ListScope
ExtraFiles(W
, "ExtraFiles");
1206 for (const auto &FID
: Line
.ExtraFiles
) {
1207 printFileNameForOffset("FileID", FID
);
1213 StringRef
COFFDumper::getFileNameForFileOffset(uint32_t FileOffset
) {
1214 // The file checksum subsection should precede all references to it.
1215 if (!CVFileChecksumTable
.valid() || !CVStringTable
.valid())
1216 error(object_error::parse_failed
);
1218 auto Iter
= CVFileChecksumTable
.getArray().at(FileOffset
);
1220 // Check if the file checksum table offset is valid.
1221 if (Iter
== CVFileChecksumTable
.end())
1222 error(object_error::parse_failed
);
1224 return error(CVStringTable
.getString(Iter
->FileNameOffset
));
1227 void COFFDumper::printFileNameForOffset(StringRef Label
, uint32_t FileOffset
) {
1228 W
.printHex(Label
, getFileNameForFileOffset(FileOffset
), FileOffset
);
1231 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder
&CVIDs
,
1232 MergingTypeTableBuilder
&CVTypes
,
1233 GlobalTypeTableBuilder
&GlobalCVIDs
,
1234 GlobalTypeTableBuilder
&GlobalCVTypes
,
1236 for (const SectionRef
&S
: Obj
->sections()) {
1237 StringRef SectionName
;
1238 error(S
.getName(SectionName
));
1239 if (SectionName
== ".debug$T") {
1241 error(S
.getContents(Data
));
1243 error(consume(Data
, Magic
));
1245 error(object_error::parse_failed
);
1248 BinaryStreamReader
Reader(Data
, llvm::support::little
);
1249 if (auto EC
= Reader
.readArray(Types
, Reader
.getLength())) {
1250 consumeError(std::move(EC
));
1252 error(object_error::parse_failed
);
1254 SmallVector
<TypeIndex
, 128> SourceToDest
;
1255 Optional
<uint32_t> PCHSignature
;
1257 std::vector
<GloballyHashedType
> Hashes
=
1258 GloballyHashedType::hashTypes(Types
);
1259 if (auto EC
= mergeTypeAndIdRecords(GlobalCVIDs
, GlobalCVTypes
, SourceToDest
, Types
,
1260 Hashes
, PCHSignature
))
1261 return error(std::move(EC
));
1263 if (auto EC
= mergeTypeAndIdRecords(CVIDs
, CVTypes
, SourceToDest
, Types
,
1265 return error(std::move(EC
));
1271 void COFFDumper::printCodeViewTypeSection(StringRef SectionName
,
1272 const SectionRef
&Section
) {
1273 ListScope
D(W
, "CodeViewTypes");
1274 W
.printNumber("Section", SectionName
, Obj
->getSectionID(Section
));
1277 error(Section
.getContents(Data
));
1278 if (opts::CodeViewSubsectionBytes
)
1279 W
.printBinaryBlock("Data", Data
);
1282 error(consume(Data
, Magic
));
1283 W
.printHex("Magic", Magic
);
1284 if (Magic
!= COFF::DEBUG_SECTION_MAGIC
)
1285 return error(object_error::parse_failed
);
1287 Types
.reset(Data
, 100);
1289 TypeDumpVisitor
TDV(Types
, &W
, opts::CodeViewSubsectionBytes
);
1290 error(codeview::visitTypeStream(Types
, TDV
));
1294 void COFFDumper::printSectionHeaders() {
1295 ListScope
SectionsD(W
, "Sections");
1296 int SectionNumber
= 0;
1297 for (const SectionRef
&Sec
: Obj
->sections()) {
1299 const coff_section
*Section
= Obj
->getCOFFSection(Sec
);
1302 error(Sec
.getName(Name
));
1304 DictScope
D(W
, "Section");
1305 W
.printNumber("Number", SectionNumber
);
1306 W
.printBinary("Name", Name
, Section
->Name
);
1307 W
.printHex ("VirtualSize", Section
->VirtualSize
);
1308 W
.printHex ("VirtualAddress", Section
->VirtualAddress
);
1309 W
.printNumber("RawDataSize", Section
->SizeOfRawData
);
1310 W
.printHex ("PointerToRawData", Section
->PointerToRawData
);
1311 W
.printHex ("PointerToRelocations", Section
->PointerToRelocations
);
1312 W
.printHex ("PointerToLineNumbers", Section
->PointerToLinenumbers
);
1313 W
.printNumber("RelocationCount", Section
->NumberOfRelocations
);
1314 W
.printNumber("LineNumberCount", Section
->NumberOfLinenumbers
);
1315 W
.printFlags ("Characteristics", Section
->Characteristics
,
1316 makeArrayRef(ImageSectionCharacteristics
),
1317 COFF::SectionCharacteristics(0x00F00000));
1319 if (opts::SectionRelocations
) {
1320 ListScope
D(W
, "Relocations");
1321 for (const RelocationRef
&Reloc
: Sec
.relocations())
1322 printRelocation(Sec
, Reloc
);
1325 if (opts::SectionSymbols
) {
1326 ListScope
D(W
, "Symbols");
1327 for (const SymbolRef
&Symbol
: Obj
->symbols()) {
1328 if (!Sec
.containsSymbol(Symbol
))
1331 printSymbol(Symbol
);
1335 if (opts::SectionData
&&
1336 !(Section
->Characteristics
& COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
)) {
1338 error(Sec
.getContents(Data
));
1340 W
.printBinaryBlock("SectionData", Data
);
1345 void COFFDumper::printRelocations() {
1346 ListScope
D(W
, "Relocations");
1348 int SectionNumber
= 0;
1349 for (const SectionRef
&Section
: Obj
->sections()) {
1352 error(Section
.getName(Name
));
1354 bool PrintedGroup
= false;
1355 for (const RelocationRef
&Reloc
: Section
.relocations()) {
1356 if (!PrintedGroup
) {
1357 W
.startLine() << "Section (" << SectionNumber
<< ") " << Name
<< " {\n";
1359 PrintedGroup
= true;
1362 printRelocation(Section
, Reloc
);
1367 W
.startLine() << "}\n";
1372 void COFFDumper::printRelocation(const SectionRef
&Section
,
1373 const RelocationRef
&Reloc
, uint64_t Bias
) {
1374 uint64_t Offset
= Reloc
.getOffset() - Bias
;
1375 uint64_t RelocType
= Reloc
.getType();
1376 SmallString
<32> RelocName
;
1377 StringRef SymbolName
;
1378 Reloc
.getTypeName(RelocName
);
1379 symbol_iterator Symbol
= Reloc
.getSymbol();
1380 int64_t SymbolIndex
= -1;
1381 if (Symbol
!= Obj
->symbol_end()) {
1382 Expected
<StringRef
> SymbolNameOrErr
= Symbol
->getName();
1383 error(errorToErrorCode(SymbolNameOrErr
.takeError()));
1384 SymbolName
= *SymbolNameOrErr
;
1385 SymbolIndex
= Obj
->getSymbolIndex(Obj
->getCOFFSymbol(*Symbol
));
1388 if (opts::ExpandRelocs
) {
1389 DictScope
Group(W
, "Relocation");
1390 W
.printHex("Offset", Offset
);
1391 W
.printNumber("Type", RelocName
, RelocType
);
1392 W
.printString("Symbol", SymbolName
.empty() ? "-" : SymbolName
);
1393 W
.printNumber("SymbolIndex", SymbolIndex
);
1395 raw_ostream
& OS
= W
.startLine();
1398 << " " << (SymbolName
.empty() ? "-" : SymbolName
)
1399 << " (" << SymbolIndex
<< ")"
1404 void COFFDumper::printSymbols() {
1405 ListScope
Group(W
, "Symbols");
1407 for (const SymbolRef
&Symbol
: Obj
->symbols())
1408 printSymbol(Symbol
);
1411 void COFFDumper::printDynamicSymbols() { ListScope
Group(W
, "DynamicSymbols"); }
1413 static ErrorOr
<StringRef
>
1414 getSectionName(const llvm::object::COFFObjectFile
*Obj
, int32_t SectionNumber
,
1415 const coff_section
*Section
) {
1417 StringRef SectionName
;
1418 if (std::error_code EC
= Obj
->getSectionName(Section
, SectionName
))
1422 if (SectionNumber
== llvm::COFF::IMAGE_SYM_DEBUG
)
1423 return StringRef("IMAGE_SYM_DEBUG");
1424 if (SectionNumber
== llvm::COFF::IMAGE_SYM_ABSOLUTE
)
1425 return StringRef("IMAGE_SYM_ABSOLUTE");
1426 if (SectionNumber
== llvm::COFF::IMAGE_SYM_UNDEFINED
)
1427 return StringRef("IMAGE_SYM_UNDEFINED");
1428 return StringRef("");
1431 void COFFDumper::printSymbol(const SymbolRef
&Sym
) {
1432 DictScope
D(W
, "Symbol");
1434 COFFSymbolRef Symbol
= Obj
->getCOFFSymbol(Sym
);
1435 const coff_section
*Section
;
1436 if (std::error_code EC
= Obj
->getSection(Symbol
.getSectionNumber(), Section
)) {
1437 W
.startLine() << "Invalid section number: " << EC
.message() << "\n";
1442 StringRef SymbolName
;
1443 if (Obj
->getSymbolName(Symbol
, SymbolName
))
1446 StringRef SectionName
= "";
1447 ErrorOr
<StringRef
> Res
=
1448 getSectionName(Obj
, Symbol
.getSectionNumber(), Section
);
1452 W
.printString("Name", SymbolName
);
1453 W
.printNumber("Value", Symbol
.getValue());
1454 W
.printNumber("Section", SectionName
, Symbol
.getSectionNumber());
1455 W
.printEnum ("BaseType", Symbol
.getBaseType(), makeArrayRef(ImageSymType
));
1456 W
.printEnum ("ComplexType", Symbol
.getComplexType(),
1457 makeArrayRef(ImageSymDType
));
1458 W
.printEnum ("StorageClass", Symbol
.getStorageClass(),
1459 makeArrayRef(ImageSymClass
));
1460 W
.printNumber("AuxSymbolCount", Symbol
.getNumberOfAuxSymbols());
1462 for (uint8_t I
= 0; I
< Symbol
.getNumberOfAuxSymbols(); ++I
) {
1463 if (Symbol
.isFunctionDefinition()) {
1464 const coff_aux_function_definition
*Aux
;
1465 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1467 DictScope
AS(W
, "AuxFunctionDef");
1468 W
.printNumber("TagIndex", Aux
->TagIndex
);
1469 W
.printNumber("TotalSize", Aux
->TotalSize
);
1470 W
.printHex("PointerToLineNumber", Aux
->PointerToLinenumber
);
1471 W
.printHex("PointerToNextFunction", Aux
->PointerToNextFunction
);
1473 } else if (Symbol
.isAnyUndefined()) {
1474 const coff_aux_weak_external
*Aux
;
1475 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1477 Expected
<COFFSymbolRef
> Linked
= Obj
->getSymbol(Aux
->TagIndex
);
1478 StringRef LinkedName
;
1479 std::error_code EC
= errorToErrorCode(Linked
.takeError());
1480 if (EC
|| (EC
= Obj
->getSymbolName(*Linked
, LinkedName
))) {
1485 DictScope
AS(W
, "AuxWeakExternal");
1486 W
.printNumber("Linked", LinkedName
, Aux
->TagIndex
);
1487 W
.printEnum ("Search", Aux
->Characteristics
,
1488 makeArrayRef(WeakExternalCharacteristics
));
1490 } else if (Symbol
.isFileRecord()) {
1491 const char *FileName
;
1492 error(getSymbolAuxData(Obj
, Symbol
, I
, FileName
));
1494 DictScope
AS(W
, "AuxFileRecord");
1496 StringRef
Name(FileName
, Symbol
.getNumberOfAuxSymbols() *
1497 Obj
->getSymbolTableEntrySize());
1498 W
.printString("FileName", Name
.rtrim(StringRef("\0", 1)));
1500 } else if (Symbol
.isSectionDefinition()) {
1501 const coff_aux_section_definition
*Aux
;
1502 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1504 int32_t AuxNumber
= Aux
->getNumber(Symbol
.isBigObj());
1506 DictScope
AS(W
, "AuxSectionDef");
1507 W
.printNumber("Length", Aux
->Length
);
1508 W
.printNumber("RelocationCount", Aux
->NumberOfRelocations
);
1509 W
.printNumber("LineNumberCount", Aux
->NumberOfLinenumbers
);
1510 W
.printHex("Checksum", Aux
->CheckSum
);
1511 W
.printNumber("Number", AuxNumber
);
1512 W
.printEnum("Selection", Aux
->Selection
, makeArrayRef(ImageCOMDATSelect
));
1514 if (Section
&& Section
->Characteristics
& COFF::IMAGE_SCN_LNK_COMDAT
1515 && Aux
->Selection
== COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
) {
1516 const coff_section
*Assoc
;
1517 StringRef AssocName
= "";
1518 std::error_code EC
= Obj
->getSection(AuxNumber
, Assoc
);
1519 ErrorOr
<StringRef
> Res
= getSectionName(Obj
, AuxNumber
, Assoc
);
1523 EC
= Res
.getError();
1529 W
.printNumber("AssocSection", AssocName
, AuxNumber
);
1531 } else if (Symbol
.isCLRToken()) {
1532 const coff_aux_clr_token
*Aux
;
1533 error(getSymbolAuxData(Obj
, Symbol
, I
, Aux
));
1535 Expected
<COFFSymbolRef
> ReferredSym
=
1536 Obj
->getSymbol(Aux
->SymbolTableIndex
);
1537 StringRef ReferredName
;
1538 std::error_code EC
= errorToErrorCode(ReferredSym
.takeError());
1539 if (EC
|| (EC
= Obj
->getSymbolName(*ReferredSym
, ReferredName
))) {
1544 DictScope
AS(W
, "AuxCLRToken");
1545 W
.printNumber("AuxType", Aux
->AuxType
);
1546 W
.printNumber("Reserved", Aux
->Reserved
);
1547 W
.printNumber("SymbolTableIndex", ReferredName
, Aux
->SymbolTableIndex
);
1550 W
.startLine() << "<unhandled auxiliary record>\n";
1555 void COFFDumper::printUnwindInfo() {
1556 ListScope
D(W
, "UnwindInformation");
1557 switch (Obj
->getMachine()) {
1558 case COFF::IMAGE_FILE_MACHINE_AMD64
: {
1559 Win64EH::Dumper
Dumper(W
);
1560 Win64EH::Dumper::SymbolResolver
1561 Resolver
= [](const object::coff_section
*Section
, uint64_t Offset
,
1562 SymbolRef
&Symbol
, void *user_data
) -> std::error_code
{
1563 COFFDumper
*Dumper
= reinterpret_cast<COFFDumper
*>(user_data
);
1564 return Dumper
->resolveSymbol(Section
, Offset
, Symbol
);
1566 Win64EH::Dumper::Context
Ctx(*Obj
, Resolver
, this);
1567 Dumper
.printData(Ctx
);
1570 case COFF::IMAGE_FILE_MACHINE_ARM64
:
1571 case COFF::IMAGE_FILE_MACHINE_ARMNT
: {
1572 ARM::WinEH::Decoder
Decoder(W
, Obj
->getMachine() ==
1573 COFF::IMAGE_FILE_MACHINE_ARM64
);
1574 Decoder
.dumpProcedureData(*Obj
);
1578 W
.printEnum("unsupported Image Machine", Obj
->getMachine(),
1579 makeArrayRef(ImageFileMachineType
));
1584 void COFFDumper::printNeededLibraries() {
1585 ListScope
D(W
, "NeededLibraries");
1587 using LibsTy
= std::vector
<StringRef
>;
1590 for (const ImportDirectoryEntryRef
&DirRef
: Obj
->import_directories()) {
1592 if (!DirRef
.getName(Name
))
1593 Libs
.push_back(Name
);
1596 std::stable_sort(Libs
.begin(), Libs
.end());
1598 for (const auto &L
: Libs
) {
1599 outs() << " " << L
<< "\n";
1603 void COFFDumper::printImportedSymbols(
1604 iterator_range
<imported_symbol_iterator
> Range
) {
1605 for (const ImportedSymbolRef
&I
: Range
) {
1607 error(I
.getSymbolName(Sym
));
1609 error(I
.getOrdinal(Ordinal
));
1610 W
.printNumber("Symbol", Sym
, Ordinal
);
1614 void COFFDumper::printDelayImportedSymbols(
1615 const DelayImportDirectoryEntryRef
&I
,
1616 iterator_range
<imported_symbol_iterator
> Range
) {
1618 for (const ImportedSymbolRef
&S
: Range
) {
1619 DictScope
Import(W
, "Import");
1621 error(S
.getSymbolName(Sym
));
1623 error(S
.getOrdinal(Ordinal
));
1624 W
.printNumber("Symbol", Sym
, Ordinal
);
1626 error(I
.getImportAddress(Index
++, Addr
));
1627 W
.printHex("Address", Addr
);
1631 void COFFDumper::printCOFFImports() {
1633 for (const ImportDirectoryEntryRef
&I
: Obj
->import_directories()) {
1634 DictScope
Import(W
, "Import");
1636 error(I
.getName(Name
));
1637 W
.printString("Name", Name
);
1639 error(I
.getImportLookupTableRVA(ILTAddr
));
1640 W
.printHex("ImportLookupTableRVA", ILTAddr
);
1642 error(I
.getImportAddressTableRVA(IATAddr
));
1643 W
.printHex("ImportAddressTableRVA", IATAddr
);
1644 // The import lookup table can be missing with certain older linkers, so
1645 // fall back to the import address table in that case.
1647 printImportedSymbols(I
.lookup_table_symbols());
1649 printImportedSymbols(I
.imported_symbols());
1653 for (const DelayImportDirectoryEntryRef
&I
: Obj
->delay_import_directories()) {
1654 DictScope
Import(W
, "DelayImport");
1656 error(I
.getName(Name
));
1657 W
.printString("Name", Name
);
1658 const delay_import_directory_table_entry
*Table
;
1659 error(I
.getDelayImportTable(Table
));
1660 W
.printHex("Attributes", Table
->Attributes
);
1661 W
.printHex("ModuleHandle", Table
->ModuleHandle
);
1662 W
.printHex("ImportAddressTable", Table
->DelayImportAddressTable
);
1663 W
.printHex("ImportNameTable", Table
->DelayImportNameTable
);
1664 W
.printHex("BoundDelayImportTable", Table
->BoundDelayImportTable
);
1665 W
.printHex("UnloadDelayImportTable", Table
->UnloadDelayImportTable
);
1666 printDelayImportedSymbols(I
, I
.imported_symbols());
1670 void COFFDumper::printCOFFExports() {
1671 for (const ExportDirectoryEntryRef
&E
: Obj
->export_directories()) {
1672 DictScope
Export(W
, "Export");
1675 uint32_t Ordinal
, RVA
;
1677 error(E
.getSymbolName(Name
));
1678 error(E
.getOrdinal(Ordinal
));
1679 error(E
.getExportRVA(RVA
));
1681 W
.printNumber("Ordinal", Ordinal
);
1682 W
.printString("Name", Name
);
1683 W
.printHex("RVA", RVA
);
1687 void COFFDumper::printCOFFDirectives() {
1688 for (const SectionRef
&Section
: Obj
->sections()) {
1692 error(Section
.getName(Name
));
1693 if (Name
!= ".drectve")
1696 error(Section
.getContents(Contents
));
1698 W
.printString("Directive(s)", Contents
);
1702 static std::string
getBaseRelocTypeName(uint8_t Type
) {
1704 case COFF::IMAGE_REL_BASED_ABSOLUTE
: return "ABSOLUTE";
1705 case COFF::IMAGE_REL_BASED_HIGH
: return "HIGH";
1706 case COFF::IMAGE_REL_BASED_LOW
: return "LOW";
1707 case COFF::IMAGE_REL_BASED_HIGHLOW
: return "HIGHLOW";
1708 case COFF::IMAGE_REL_BASED_HIGHADJ
: return "HIGHADJ";
1709 case COFF::IMAGE_REL_BASED_ARM_MOV32T
: return "ARM_MOV32(T)";
1710 case COFF::IMAGE_REL_BASED_DIR64
: return "DIR64";
1711 default: return "unknown (" + llvm::utostr(Type
) + ")";
1715 void COFFDumper::printCOFFBaseReloc() {
1716 ListScope
D(W
, "BaseReloc");
1717 for (const BaseRelocRef
&I
: Obj
->base_relocs()) {
1720 error(I
.getRVA(RVA
));
1721 error(I
.getType(Type
));
1722 DictScope
Import(W
, "Entry");
1723 W
.printString("Type", getBaseRelocTypeName(Type
));
1724 W
.printHex("Address", RVA
);
1728 void COFFDumper::printCOFFResources() {
1729 ListScope
ResourcesD(W
, "Resources");
1730 for (const SectionRef
&S
: Obj
->sections()) {
1732 error(S
.getName(Name
));
1733 if (!Name
.startswith(".rsrc"))
1737 error(S
.getContents(Ref
));
1739 if ((Name
== ".rsrc") || (Name
== ".rsrc$01")) {
1740 ResourceSectionRef
RSF(Ref
);
1741 auto &BaseTable
= unwrapOrError(RSF
.getBaseTable());
1742 W
.printNumber("Total Number of Resources",
1743 countTotalTableEntries(RSF
, BaseTable
, "Type"));
1744 W
.printHex("Base Table Address",
1745 Obj
->getCOFFSection(S
)->PointerToRawData
);
1746 W
.startLine() << "\n";
1747 printResourceDirectoryTable(RSF
, BaseTable
, "Type");
1749 if (opts::SectionData
)
1750 W
.printBinaryBlock(Name
.str() + " Data", Ref
);
1755 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF
,
1756 const coff_resource_dir_table
&Table
,
1758 uint32_t TotalEntries
= 0;
1759 for (int i
= 0; i
< Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
;
1761 auto Entry
= unwrapOrError(getResourceDirectoryTableEntry(Table
, i
));
1762 if (Entry
.Offset
.isSubDir()) {
1763 StringRef NextLevel
;
1764 if (Level
== "Name")
1765 NextLevel
= "Language";
1768 auto &NextTable
= unwrapOrError(RSF
.getEntrySubDir(Entry
));
1769 TotalEntries
+= countTotalTableEntries(RSF
, NextTable
, NextLevel
);
1774 return TotalEntries
;
1777 void COFFDumper::printResourceDirectoryTable(
1778 ResourceSectionRef RSF
, const coff_resource_dir_table
&Table
,
1781 W
.printNumber("Number of String Entries", Table
.NumberOfNameEntries
);
1782 W
.printNumber("Number of ID Entries", Table
.NumberOfIDEntries
);
1784 // Iterate through level in resource directory tree.
1785 for (int i
= 0; i
< Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
;
1787 auto Entry
= unwrapOrError(getResourceDirectoryTableEntry(Table
, i
));
1789 SmallString
<20> IDStr
;
1790 raw_svector_ostream
OS(IDStr
);
1791 if (i
< Table
.NumberOfNameEntries
) {
1792 ArrayRef
<UTF16
> RawEntryNameString
= unwrapOrError(RSF
.getEntryNameString(Entry
));
1793 std::vector
<UTF16
> EndianCorrectedNameString
;
1794 if (llvm::sys::IsBigEndianHost
) {
1795 EndianCorrectedNameString
.resize(RawEntryNameString
.size() + 1);
1796 std::copy(RawEntryNameString
.begin(), RawEntryNameString
.end(),
1797 EndianCorrectedNameString
.begin() + 1);
1798 EndianCorrectedNameString
[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED
;
1799 RawEntryNameString
= makeArrayRef(EndianCorrectedNameString
);
1801 std::string EntryNameString
;
1802 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString
, EntryNameString
))
1803 error(object_error::parse_failed
);
1805 OS
<< EntryNameString
;
1807 if (Level
== "Type") {
1808 ScopedPrinter
Printer(OS
);
1809 Printer
.printEnum("", Entry
.Identifier
.ID
,
1810 makeArrayRef(ResourceTypeNames
));
1811 IDStr
= IDStr
.slice(0, IDStr
.find_first_of(")", 0) + 1);
1813 OS
<< ": (ID " << Entry
.Identifier
.ID
<< ")";
1816 Name
= StringRef(IDStr
);
1817 ListScope
ResourceType(W
, Level
.str() + Name
.str());
1818 if (Entry
.Offset
.isSubDir()) {
1819 W
.printHex("Table Offset", Entry
.Offset
.value());
1820 StringRef NextLevel
;
1821 if (Level
== "Name")
1822 NextLevel
= "Language";
1825 auto &NextTable
= unwrapOrError(RSF
.getEntrySubDir(Entry
));
1826 printResourceDirectoryTable(RSF
, NextTable
, NextLevel
);
1828 W
.printHex("Entry Offset", Entry
.Offset
.value());
1829 char FormattedTime
[20] = {};
1830 time_t TDS
= time_t(Table
.TimeDateStamp
);
1831 strftime(FormattedTime
, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS
));
1832 W
.printHex("Time/Date Stamp", FormattedTime
, Table
.TimeDateStamp
);
1833 W
.printNumber("Major Version", Table
.MajorVersion
);
1834 W
.printNumber("Minor Version", Table
.MinorVersion
);
1835 W
.printNumber("Characteristics", Table
.Characteristics
);
1840 ErrorOr
<const coff_resource_dir_entry
&>
1841 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table
&Table
,
1843 if (Index
>= (uint32_t)(Table
.NumberOfNameEntries
+ Table
.NumberOfIDEntries
))
1844 return object_error::parse_failed
;
1845 auto TablePtr
= reinterpret_cast<const coff_resource_dir_entry
*>(&Table
+ 1);
1846 return TablePtr
[Index
];
1849 void COFFDumper::printStackMap() const {
1850 object::SectionRef StackMapSection
;
1851 for (auto Sec
: Obj
->sections()) {
1854 if (Name
== ".llvm_stackmaps") {
1855 StackMapSection
= Sec
;
1860 if (StackMapSection
== object::SectionRef())
1863 StringRef StackMapContents
;
1864 StackMapSection
.getContents(StackMapContents
);
1865 ArrayRef
<uint8_t> StackMapContentsArray(
1866 reinterpret_cast<const uint8_t*>(StackMapContents
.data()),
1867 StackMapContents
.size());
1869 if (Obj
->isLittleEndian())
1870 prettyPrintStackMap(
1871 W
, StackMapV2Parser
<support::little
>(StackMapContentsArray
));
1873 prettyPrintStackMap(W
,
1874 StackMapV2Parser
<support::big
>(StackMapContentsArray
));
1877 void COFFDumper::printAddrsig() {
1878 object::SectionRef AddrsigSection
;
1879 for (auto Sec
: Obj
->sections()) {
1882 if (Name
== ".llvm_addrsig") {
1883 AddrsigSection
= Sec
;
1888 if (AddrsigSection
== object::SectionRef())
1891 StringRef AddrsigContents
;
1892 AddrsigSection
.getContents(AddrsigContents
);
1893 ArrayRef
<uint8_t> AddrsigContentsArray(
1894 reinterpret_cast<const uint8_t*>(AddrsigContents
.data()),
1895 AddrsigContents
.size());
1897 ListScope
L(W
, "Addrsig");
1898 auto *Cur
= reinterpret_cast<const uint8_t *>(AddrsigContents
.begin());
1899 auto *End
= reinterpret_cast<const uint8_t *>(AddrsigContents
.end());
1900 while (Cur
!= End
) {
1903 uint64_t SymIndex
= decodeULEB128(Cur
, &Size
, End
, &Err
);
1907 Expected
<COFFSymbolRef
> Sym
= Obj
->getSymbol(SymIndex
);
1909 std::error_code EC
= errorToErrorCode(Sym
.takeError());
1910 if (EC
|| (EC
= Obj
->getSymbolName(*Sym
, SymName
))) {
1915 W
.printNumber("Sym", SymName
, SymIndex
);
1920 void llvm::dumpCodeViewMergedTypes(ScopedPrinter
&Writer
,
1921 ArrayRef
<ArrayRef
<uint8_t>> IpiRecords
,
1922 ArrayRef
<ArrayRef
<uint8_t>> TpiRecords
) {
1923 TypeTableCollection
TpiTypes(TpiRecords
);
1925 ListScope
S(Writer
, "MergedTypeStream");
1926 TypeDumpVisitor
TDV(TpiTypes
, &Writer
, opts::CodeViewSubsectionBytes
);
1927 error(codeview::visitTypeStream(TpiTypes
, TDV
));
1931 // Flatten the id stream and print it next. The ID stream refers to names from
1933 TypeTableCollection
IpiTypes(IpiRecords
);
1935 ListScope
S(Writer
, "MergedIDStream");
1936 TypeDumpVisitor
TDV(TpiTypes
, &Writer
, opts::CodeViewSubsectionBytes
);
1937 TDV
.setIpiTypes(IpiTypes
);
1938 error(codeview::visitTypeStream(IpiTypes
, TDV
));