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/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 printSections() override;
82 void printRelocations() override;
83 void printSymbols() override;
84 void printDynamicSymbols() override;
85 void printUnwindInfo() override;
86 void printSectionAsHex(StringRef StringName) 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;
103 void printSymbol(const SymbolRef &Sym);
104 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
106 void printDataDirectory(uint32_t Index, const std::string &FieldName);
108 void printDOSHeader(const dos_header *DH);
109 template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
110 void printBaseOfDataField(const pe32_header *Hdr);
111 void printBaseOfDataField(const pe32plus_header *Hdr);
112 template <typename T>
113 void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
114 typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
115 void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
116 PrintExtraCB PrintExtra = 0);
118 void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
119 void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
120 StringRef getTypeName(TypeIndex Ty);
121 StringRef getFileNameForFileOffset(uint32_t FileOffset);
122 void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
123 void printTypeIndex(StringRef FieldName, TypeIndex TI) {
124 // Forward to CVTypeDumper for simplicity.
125 codeview::printTypeIndex(Writer, FieldName, TI, Types);
128 void printCodeViewSymbolsSubsection(StringRef Subsection,
129 const SectionRef &Section,
130 StringRef SectionContents);
132 void printCodeViewFileChecksums(StringRef Subsection);
134 void printCodeViewInlineeLines(StringRef Subsection);
136 void printRelocatedField(StringRef Label, const coff_section *Sec,
137 uint32_t RelocOffset, uint32_t Offset,
138 StringRef *RelocSym = nullptr);
140 uint32_t countTotalTableEntries(ResourceSectionRef RSF,
141 const coff_resource_dir_table &Table,
144 void printResourceDirectoryTable(ResourceSectionRef RSF,
145 const coff_resource_dir_table &Table,
148 void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
149 StringRef SectionContents, StringRef Block);
151 /// Given a .debug$S section, find the string table and file checksum table.
152 void initializeFileAndStringTables(BinaryStreamReader &Reader);
154 void cacheRelocations();
156 std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
158 std::error_code resolveSymbolName(const coff_section *Section,
159 uint64_t Offset, StringRef &Name);
160 std::error_code resolveSymbolName(const coff_section *Section,
161 StringRef SectionContents,
162 const void *RelocPtr, StringRef &Name);
163 void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
164 void printDelayImportedSymbols(
165 const DelayImportDirectoryEntryRef &I,
166 iterator_range<imported_symbol_iterator> Range);
167 ErrorOr<const coff_resource_dir_entry &>
168 getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
171 typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
173 const llvm::object::COFFObjectFile *Obj;
174 bool RelocCached = false;
177 DebugChecksumsSubsectionRef CVFileChecksumTable;
179 DebugStringTableSubsectionRef CVStringTable;
181 ScopedPrinter &Writer;
182 BinaryByteStream TypeContents;
183 LazyRandomTypeCollection Types;
186 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
188 COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
189 const COFFObjectFile *Obj, StringRef SectionContents)
190 : CD(CD), SR(SR), SectionContents(SectionContents) {
191 Sec = Obj->getCOFFSection(SR);
194 uint32_t getRecordOffset(BinaryStreamReader Reader) override {
195 ArrayRef<uint8_t> Data;
196 if (auto EC = Reader.readLongestContiguousChunk(Data)) {
197 llvm::consumeError(std::move(EC));
200 return Data.data() - SectionContents.bytes_begin();
203 void printRelocatedField(StringRef Label, uint32_t RelocOffset,
204 uint32_t Offset, StringRef *RelocSym) override {
205 CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
208 void printBinaryBlockWithRelocs(StringRef Label,
209 ArrayRef<uint8_t> Block) override {
210 StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
212 if (opts::CodeViewSubsectionBytes)
213 CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
216 StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
217 return CD.getFileNameForFileOffset(FileOffset);
220 DebugStringTableSubsectionRef getStringTable() override {
221 return CD.CVStringTable;
226 const SectionRef &SR;
227 const coff_section *Sec;
228 StringRef SectionContents;
235 std::error_code createCOFFDumper(const object::ObjectFile *Obj,
236 ScopedPrinter &Writer,
237 std::unique_ptr<ObjDumper> &Result) {
238 const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
240 return readobj_error::unsupported_obj_file_format;
242 Result.reset(new COFFDumper(COFFObj, Writer));
243 return readobj_error::success;
248 // Given a section and an offset into this section the function returns the
249 // symbol used for the relocation at the offset.
250 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
251 uint64_t Offset, SymbolRef &Sym) {
253 const auto &Relocations = RelocMap[Section];
254 auto SymI = Obj->symbol_end();
255 for (const auto &Relocation : Relocations) {
256 uint64_t RelocationOffset = Relocation.getOffset();
258 if (RelocationOffset == Offset) {
259 SymI = Relocation.getSymbol();
263 if (SymI == Obj->symbol_end())
264 return readobj_error::unknown_symbol;
266 return readobj_error::success;
269 // Given a section and an offset into this section the function returns the name
270 // of the symbol used for the relocation at the offset.
271 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
275 if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
277 Expected<StringRef> NameOrErr = Symbol.getName();
279 return errorToErrorCode(NameOrErr.takeError());
281 return std::error_code();
284 // Helper for when you have a pointer to real data and you want to know about
285 // relocations against it.
286 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
287 StringRef SectionContents,
288 const void *RelocPtr,
290 assert(SectionContents.data() < RelocPtr &&
291 RelocPtr < SectionContents.data() + SectionContents.size() &&
292 "pointer to relocated object is not in section");
293 uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
294 SectionContents.data());
295 return resolveSymbolName(Section, Offset, Name);
298 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
299 uint32_t RelocOffset, uint32_t Offset,
300 StringRef *RelocSym) {
301 StringRef SymStorage;
302 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
303 if (!resolveSymbolName(Sec, RelocOffset, Symbol))
304 W.printSymbolOffset(Label, Symbol, Offset);
306 W.printHex(Label, RelocOffset);
309 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
310 const SectionRef &Sec,
311 StringRef SectionContents,
313 W.printBinaryBlock(Label, Block);
315 assert(SectionContents.begin() < Block.begin() &&
316 SectionContents.end() >= Block.end() &&
317 "Block is not contained in SectionContents");
318 uint64_t OffsetStart = Block.data() - SectionContents.data();
319 uint64_t OffsetEnd = OffsetStart + Block.size();
323 ListScope D(W, "BlockRelocations");
324 const coff_section *Section = Obj->getCOFFSection(Sec);
325 const auto &Relocations = RelocMap[Section];
326 for (const auto &Relocation : Relocations) {
327 uint64_t RelocationOffset = Relocation.getOffset();
328 if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
329 printRelocation(Sec, Relocation, OffsetStart);
333 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
334 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
335 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
336 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
337 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
338 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64 ),
339 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
340 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
341 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
342 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
343 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
344 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
345 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
346 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
347 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
348 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
349 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
350 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
351 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
352 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
353 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
354 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
355 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
358 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
359 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
360 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
361 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
362 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
363 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
364 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
365 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
366 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
367 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
368 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
369 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
370 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
371 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
372 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
373 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
376 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
377 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
378 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
379 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
380 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
381 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
382 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
383 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
384 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
385 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
386 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
387 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
390 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
391 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
392 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
393 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
394 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
395 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
396 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
397 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
398 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER ),
399 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
400 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF ),
401 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
404 static const EnumEntry<COFF::SectionCharacteristics>
405 ImageSectionCharacteristics[] = {
406 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD ),
407 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
408 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
409 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
410 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
411 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
412 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
413 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
414 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
415 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
416 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
417 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
418 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
419 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
420 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
421 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
422 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
423 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
424 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
425 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
426 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
427 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
428 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
429 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
430 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
431 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
432 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
433 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
434 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
435 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
436 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
437 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
438 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
439 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
440 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
441 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
444 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
445 { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
446 { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
447 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
448 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
449 { "Int" , COFF::IMAGE_SYM_TYPE_INT },
450 { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
451 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
452 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
453 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
454 { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
455 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
456 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
457 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
458 { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
459 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
460 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
463 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
464 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
465 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
466 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
467 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
470 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
471 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
472 { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
473 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
474 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
475 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
476 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
477 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
478 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
479 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
480 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
481 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
482 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
483 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
484 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
485 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
486 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
487 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
488 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
489 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
490 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
491 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
492 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
493 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
494 { "File" , COFF::IMAGE_SYM_CLASS_FILE },
495 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
496 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
497 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
500 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
501 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
502 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
503 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
504 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
505 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
506 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
507 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
510 static const EnumEntry<COFF::DebugType> ImageDebugType[] = {
511 { "Unknown" , COFF::IMAGE_DEBUG_TYPE_UNKNOWN },
512 { "COFF" , COFF::IMAGE_DEBUG_TYPE_COFF },
513 { "CodeView" , COFF::IMAGE_DEBUG_TYPE_CODEVIEW },
514 { "FPO" , COFF::IMAGE_DEBUG_TYPE_FPO },
515 { "Misc" , COFF::IMAGE_DEBUG_TYPE_MISC },
516 { "Exception" , COFF::IMAGE_DEBUG_TYPE_EXCEPTION },
517 { "Fixup" , COFF::IMAGE_DEBUG_TYPE_FIXUP },
518 { "OmapToSrc" , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC },
519 { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC },
520 { "Borland" , COFF::IMAGE_DEBUG_TYPE_BORLAND },
521 { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10 },
522 { "CLSID" , COFF::IMAGE_DEBUG_TYPE_CLSID },
523 { "VCFeature" , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE },
524 { "POGO" , COFF::IMAGE_DEBUG_TYPE_POGO },
525 { "ILTCG" , COFF::IMAGE_DEBUG_TYPE_ILTCG },
526 { "MPX" , COFF::IMAGE_DEBUG_TYPE_MPX },
527 { "Repro" , COFF::IMAGE_DEBUG_TYPE_REPRO },
530 static const EnumEntry<COFF::WeakExternalCharacteristics>
531 WeakExternalCharacteristics[] = {
532 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
533 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
534 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
537 static const EnumEntry<uint32_t> SubSectionTypes[] = {
538 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
539 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
540 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
541 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
542 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
543 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
544 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
545 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
546 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
547 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
548 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
549 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
550 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
553 static const EnumEntry<uint32_t> FrameDataFlags[] = {
554 LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
555 LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
556 LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
559 static const EnumEntry<uint8_t> FileChecksumKindNames[] = {
560 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
561 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
562 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
563 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
566 static const EnumEntry<COFF::ResourceTypeID> ResourceTypeNames[]{
567 {"kRT_CURSOR (ID 1)", COFF::RID_Cursor},
568 {"kRT_BITMAP (ID 2)", COFF::RID_Bitmap},
569 {"kRT_ICON (ID 3)", COFF::RID_Icon},
570 {"kRT_MENU (ID 4)", COFF::RID_Menu},
571 {"kRT_DIALOG (ID 5)", COFF::RID_Dialog},
572 {"kRT_STRING (ID 6)", COFF::RID_String},
573 {"kRT_FONTDIR (ID 7)", COFF::RID_FontDir},
574 {"kRT_FONT (ID 8)", COFF::RID_Font},
575 {"kRT_ACCELERATOR (ID 9)", COFF::RID_Accelerator},
576 {"kRT_RCDATA (ID 10)", COFF::RID_RCData},
577 {"kRT_MESSAGETABLE (ID 11)", COFF::RID_MessageTable},
578 {"kRT_GROUP_CURSOR (ID 12)", COFF::RID_Group_Cursor},
579 {"kRT_GROUP_ICON (ID 14)", COFF::RID_Group_Icon},
580 {"kRT_VERSION (ID 16)", COFF::RID_Version},
581 {"kRT_DLGINCLUDE (ID 17)", COFF::RID_DLGInclude},
582 {"kRT_PLUGPLAY (ID 19)", COFF::RID_PlugPlay},
583 {"kRT_VXD (ID 20)", COFF::RID_VXD},
584 {"kRT_ANICURSOR (ID 21)", COFF::RID_AniCursor},
585 {"kRT_ANIICON (ID 22)", COFF::RID_AniIcon},
586 {"kRT_HTML (ID 23)", COFF::RID_HTML},
587 {"kRT_MANIFEST (ID 24)", COFF::RID_Manifest}};
589 template <typename T>
590 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
591 COFFSymbolRef Symbol,
592 uint8_t AuxSymbolIdx, const T *&Aux) {
593 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
594 AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
595 Aux = reinterpret_cast<const T*>(AuxData.data());
596 return readobj_error::success;
599 void COFFDumper::cacheRelocations() {
604 for (const SectionRef &S : Obj->sections()) {
605 const coff_section *Section = Obj->getCOFFSection(S);
607 for (const RelocationRef &Reloc : S.relocations())
608 RelocMap[Section].push_back(Reloc);
610 // Sort relocations by address.
611 llvm::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
616 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
617 const data_directory *Data;
618 if (Obj->getDataDirectory(Index, Data))
620 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
621 W.printHex(FieldName + "Size", Data->Size);
624 void COFFDumper::printFileHeaders() {
625 time_t TDS = Obj->getTimeDateStamp();
626 char FormattedTime[20] = { };
627 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
630 DictScope D(W, "ImageFileHeader");
631 W.printEnum ("Machine", Obj->getMachine(),
632 makeArrayRef(ImageFileMachineType));
633 W.printNumber("SectionCount", Obj->getNumberOfSections());
634 W.printHex ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
635 W.printHex ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
636 W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
637 W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
638 W.printFlags ("Characteristics", Obj->getCharacteristics(),
639 makeArrayRef(ImageFileCharacteristics));
642 // Print PE header. This header does not exist if this is an object file and
643 // not an executable.
644 const pe32_header *PEHeader = nullptr;
645 error(Obj->getPE32Header(PEHeader));
647 printPEHeader<pe32_header>(PEHeader);
649 const pe32plus_header *PEPlusHeader = nullptr;
650 error(Obj->getPE32PlusHeader(PEPlusHeader));
652 printPEHeader<pe32plus_header>(PEPlusHeader);
654 if (const dos_header *DH = Obj->getDOSHeader())
658 void COFFDumper::printSectionAsHex(StringRef SectionName) {
660 long SectionIndex = strtol(SectionName.data(), &StrPtr, 10);
661 const coff_section *Sec;
663 error(Obj->getSection(SectionName, Sec));
665 error(Obj->getSection((int)SectionIndex, Sec));
667 return error(object_error::parse_failed);
671 error(Obj->getSectionName(Sec, SecName));
673 ArrayRef<uint8_t> Content;
674 error(Obj->getSectionContents(Sec, Content));
675 const uint8_t *SecContent = Content.data();
677 SectionHexDump(SecName, SecContent, Content.size());
680 void COFFDumper::printDOSHeader(const dos_header *DH) {
681 DictScope D(W, "DOSHeader");
682 W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
683 W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
684 W.printNumber("FileSizeInPages", DH->FileSizeInPages);
685 W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
686 W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
687 W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
688 W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
689 W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
690 W.printNumber("InitialSP", DH->InitialSP);
691 W.printNumber("Checksum", DH->Checksum);
692 W.printNumber("InitialIP", DH->InitialIP);
693 W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
694 W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
695 W.printNumber("OverlayNumber", DH->OverlayNumber);
696 W.printNumber("OEMid", DH->OEMid);
697 W.printNumber("OEMinfo", DH->OEMinfo);
698 W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
701 template <class PEHeader>
702 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
703 DictScope D(W, "ImageOptionalHeader");
704 W.printHex ("Magic", Hdr->Magic);
705 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
706 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
707 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
708 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
709 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
710 W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
711 W.printHex ("BaseOfCode", Hdr->BaseOfCode);
712 printBaseOfDataField(Hdr);
713 W.printHex ("ImageBase", Hdr->ImageBase);
714 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
715 W.printNumber("FileAlignment", Hdr->FileAlignment);
716 W.printNumber("MajorOperatingSystemVersion",
717 Hdr->MajorOperatingSystemVersion);
718 W.printNumber("MinorOperatingSystemVersion",
719 Hdr->MinorOperatingSystemVersion);
720 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
721 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
722 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
723 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
724 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
725 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
726 W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
727 W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
728 makeArrayRef(PEDLLCharacteristics));
729 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
730 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
731 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
732 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
733 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
735 if (Hdr->NumberOfRvaAndSize > 0) {
736 DictScope D(W, "DataDirectory");
737 static const char * const directory[] = {
738 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
739 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
740 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
741 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
744 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
745 printDataDirectory(i, directory[i]);
749 void COFFDumper::printCOFFDebugDirectory() {
750 ListScope LS(W, "DebugDirectory");
751 for (const debug_directory &D : Obj->debug_directories()) {
752 char FormattedTime[20] = {};
753 time_t TDS = D.TimeDateStamp;
754 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
755 DictScope S(W, "DebugEntry");
756 W.printHex("Characteristics", D.Characteristics);
757 W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
758 W.printHex("MajorVersion", D.MajorVersion);
759 W.printHex("MinorVersion", D.MinorVersion);
760 W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
761 W.printHex("SizeOfData", D.SizeOfData);
762 W.printHex("AddressOfRawData", D.AddressOfRawData);
763 W.printHex("PointerToRawData", D.PointerToRawData);
764 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
765 const codeview::DebugInfo *DebugInfo;
766 StringRef PDBFileName;
767 error(Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName));
768 DictScope PDBScope(W, "PDBInfo");
769 W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
770 if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
771 W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
772 W.printNumber("PDBAge", DebugInfo->PDB70.Age);
773 W.printString("PDBFileName", PDBFileName);
776 // FIXME: Type values of 12 and 13 are commonly observed but are not in
777 // the documented type enum. Figure out what they mean.
778 ArrayRef<uint8_t> RawData;
780 Obj->getRvaAndSizeAsBytes(D.AddressOfRawData, D.SizeOfData, RawData));
781 W.printBinaryBlock("RawData", RawData);
786 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
787 uint64_t EntrySize, PrintExtraCB PrintExtra) {
788 uintptr_t TableStart, TableEnd;
789 error(Obj->getVaPtr(TableVA, TableStart));
790 error(Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd));
792 for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
793 uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
794 raw_ostream &OS = W.startLine();
795 OS << W.hex(Obj->getImageBase() + RVA);
797 PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
802 void COFFDumper::printCOFFLoadConfig() {
803 LoadConfigTables Tables;
805 printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
807 printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
809 if (Tables.SEHTableVA) {
810 ListScope LS(W, "SEHTable");
811 printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
814 if (Tables.GuardFidTableVA) {
815 ListScope LS(W, "GuardFidTable");
816 if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
817 auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
818 uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
820 OS << " flags " << utohexstr(Flags);
822 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
825 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
829 if (Tables.GuardLJmpTableVA) {
830 ListScope LS(W, "GuardLJmpTable");
831 printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
835 template <typename T>
836 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
840 ListScope LS(W, "LoadConfig");
841 char FormattedTime[20] = {};
842 time_t TDS = Conf->TimeDateStamp;
843 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
844 W.printHex("Size", Conf->Size);
846 // Print everything before SecurityCookie. The vast majority of images today
847 // have all these fields.
848 if (Conf->Size < offsetof(T, SEHandlerTable))
850 W.printHex("TimeDateStamp", FormattedTime, TDS);
851 W.printHex("MajorVersion", Conf->MajorVersion);
852 W.printHex("MinorVersion", Conf->MinorVersion);
853 W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
854 W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
855 W.printHex("CriticalSectionDefaultTimeout",
856 Conf->CriticalSectionDefaultTimeout);
857 W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
858 W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
859 W.printHex("LockPrefixTable", Conf->LockPrefixTable);
860 W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
861 W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
862 W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
863 W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
864 W.printHex("CSDVersion", Conf->CSDVersion);
865 W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
866 W.printHex("EditList", Conf->EditList);
867 W.printHex("SecurityCookie", Conf->SecurityCookie);
869 // Print the safe SEH table if present.
870 if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
872 W.printHex("SEHandlerTable", Conf->SEHandlerTable);
873 W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
875 Tables.SEHTableVA = Conf->SEHandlerTable;
876 Tables.SEHTableCount = Conf->SEHandlerCount;
878 // Print everything before CodeIntegrity. (2015)
879 if (Conf->Size < offsetof(T, CodeIntegrity))
881 W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
882 W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
883 W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
884 W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
885 W.printHex("GuardFlags", Conf->GuardFlags);
887 Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
888 Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
889 Tables.GuardFlags = Conf->GuardFlags;
891 // Print the rest. (2017)
892 if (Conf->Size < sizeof(T))
894 W.printHex("GuardAddressTakenIatEntryTable",
895 Conf->GuardAddressTakenIatEntryTable);
896 W.printNumber("GuardAddressTakenIatEntryCount",
897 Conf->GuardAddressTakenIatEntryCount);
898 W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
899 W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
900 W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
901 W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
902 W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
903 W.printHex("GuardRFFailureRoutineFunctionPointer",
904 Conf->GuardRFFailureRoutineFunctionPointer);
905 W.printHex("DynamicValueRelocTableOffset",
906 Conf->DynamicValueRelocTableOffset);
907 W.printNumber("DynamicValueRelocTableSection",
908 Conf->DynamicValueRelocTableSection);
909 W.printHex("GuardRFVerifyStackPointerFunctionPointer",
910 Conf->GuardRFVerifyStackPointerFunctionPointer);
911 W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
913 Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
914 Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
917 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
918 W.printHex("BaseOfData", Hdr->BaseOfData);
921 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
923 void COFFDumper::printCodeViewDebugInfo() {
924 // Print types first to build CVUDTNames, then print symbols.
925 for (const SectionRef &S : Obj->sections()) {
926 StringRef SectionName;
927 error(S.getName(SectionName));
928 // .debug$T is a standard CodeView type section, while .debug$P is the same
929 // format but used for MSVC precompiled header object files.
930 if (SectionName == ".debug$T" || SectionName == ".debug$P")
931 printCodeViewTypeSection(SectionName, S);
933 for (const SectionRef &S : Obj->sections()) {
934 StringRef SectionName;
935 error(S.getName(SectionName));
936 if (SectionName == ".debug$S")
937 printCodeViewSymbolSection(SectionName, S);
941 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
942 while (Reader.bytesRemaining() > 0 &&
943 (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
944 // The section consists of a number of subsection in the following format:
945 // |SubSectionType|SubSectionSize|Contents...|
946 uint32_t SubType, SubSectionSize;
947 error(Reader.readInteger(SubType));
948 error(Reader.readInteger(SubSectionSize));
951 error(Reader.readFixedString(Contents, SubSectionSize));
953 BinaryStreamRef ST(Contents, support::little);
954 switch (DebugSubsectionKind(SubType)) {
955 case DebugSubsectionKind::FileChecksums:
956 error(CVFileChecksumTable.initialize(ST));
958 case DebugSubsectionKind::StringTable:
959 error(CVStringTable.initialize(ST));
965 uint32_t PaddedSize = alignTo(SubSectionSize, 4);
966 error(Reader.skip(PaddedSize - SubSectionSize));
970 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
971 const SectionRef &Section) {
972 StringRef SectionContents;
973 error(Section.getContents(SectionContents));
974 StringRef Data = SectionContents;
976 SmallVector<StringRef, 10> FunctionNames;
977 StringMap<StringRef> FunctionLineTables;
979 ListScope D(W, "CodeViewDebugInfo");
980 // Print the section to allow correlation with printSections.
981 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
984 error(consume(Data, Magic));
985 W.printHex("Magic", Magic);
986 if (Magic != COFF::DEBUG_SECTION_MAGIC)
987 return error(object_error::parse_failed);
989 BinaryStreamReader FSReader(Data, support::little);
990 initializeFileAndStringTables(FSReader);
992 // TODO: Convert this over to using ModuleSubstreamVisitor.
993 while (!Data.empty()) {
994 // The section consists of a number of subsection in the following format:
995 // |SubSectionType|SubSectionSize|Contents...|
996 uint32_t SubType, SubSectionSize;
997 error(consume(Data, SubType));
998 error(consume(Data, SubSectionSize));
1000 ListScope S(W, "Subsection");
1001 W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
1002 W.printHex("SubSectionSize", SubSectionSize);
1004 // Get the contents of the subsection.
1005 if (SubSectionSize > Data.size())
1006 return error(object_error::parse_failed);
1007 StringRef Contents = Data.substr(0, SubSectionSize);
1009 // Add SubSectionSize to the current offset and align that offset to find
1010 // the next subsection.
1011 size_t SectionOffset = Data.data() - SectionContents.data();
1012 size_t NextOffset = SectionOffset + SubSectionSize;
1013 NextOffset = alignTo(NextOffset, 4);
1014 if (NextOffset > SectionContents.size())
1015 return error(object_error::parse_failed);
1016 Data = SectionContents.drop_front(NextOffset);
1018 // Optionally print the subsection bytes in case our parsing gets confused
1020 if (opts::CodeViewSubsectionBytes)
1021 printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
1024 switch (DebugSubsectionKind(SubType)) {
1025 case DebugSubsectionKind::Symbols:
1026 printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1029 case DebugSubsectionKind::InlineeLines:
1030 printCodeViewInlineeLines(Contents);
1033 case DebugSubsectionKind::FileChecksums:
1034 printCodeViewFileChecksums(Contents);
1037 case DebugSubsectionKind::Lines: {
1038 // Holds a PC to file:line table. Some data to parse this subsection is
1039 // stored in the other subsections, so just check sanity and store the
1040 // pointers for deferred processing.
1042 if (SubSectionSize < 12) {
1043 // There should be at least three words to store two function
1044 // relocations and size of the code.
1045 error(object_error::parse_failed);
1049 StringRef LinkageName;
1050 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
1052 W.printString("LinkageName", LinkageName);
1053 if (FunctionLineTables.count(LinkageName) != 0) {
1054 // Saw debug info for this function already?
1055 error(object_error::parse_failed);
1059 FunctionLineTables[LinkageName] = Contents;
1060 FunctionNames.push_back(LinkageName);
1063 case DebugSubsectionKind::FrameData: {
1064 // First four bytes is a relocation against the function.
1065 BinaryStreamReader SR(Contents, llvm::support::little);
1067 DebugFrameDataSubsectionRef FrameData;
1068 error(FrameData.initialize(SR));
1070 StringRef LinkageName;
1071 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1072 FrameData.getRelocPtr(), LinkageName));
1073 W.printString("LinkageName", LinkageName);
1075 // To find the active frame description, search this array for the
1076 // smallest PC range that includes the current PC.
1077 for (const auto &FD : FrameData) {
1078 StringRef FrameFunc = error(CVStringTable.getString(FD.FrameFunc));
1080 DictScope S(W, "FrameData");
1081 W.printHex("RvaStart", FD.RvaStart);
1082 W.printHex("CodeSize", FD.CodeSize);
1083 W.printHex("LocalSize", FD.LocalSize);
1084 W.printHex("ParamsSize", FD.ParamsSize);
1085 W.printHex("MaxStackSize", FD.MaxStackSize);
1086 W.printString("FrameFunc", FrameFunc);
1087 W.printHex("PrologSize", FD.PrologSize);
1088 W.printHex("SavedRegsSize", FD.SavedRegsSize);
1089 W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
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 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));
1172 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1173 BinaryStreamRef Stream(Subsection, llvm::support::little);
1174 DebugChecksumsSubsectionRef Checksums;
1175 error(Checksums.initialize(Stream));
1177 for (auto &FC : Checksums) {
1178 DictScope S(W, "FileChecksum");
1180 StringRef Filename = error(CVStringTable.getString(FC.FileNameOffset));
1181 W.printHex("Filename", Filename, FC.FileNameOffset);
1182 W.printHex("ChecksumSize", FC.Checksum.size());
1183 W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1184 makeArrayRef(FileChecksumKindNames));
1186 W.printBinary("ChecksumBytes", FC.Checksum);
1190 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1191 BinaryStreamReader SR(Subsection, llvm::support::little);
1192 DebugInlineeLinesSubsectionRef Lines;
1193 error(Lines.initialize(SR));
1195 for (auto &Line : Lines) {
1196 DictScope S(W, "InlineeSourceLine");
1197 printTypeIndex("Inlinee", Line.Header->Inlinee);
1198 printFileNameForOffset("FileID", Line.Header->FileID);
1199 W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1201 if (Lines.hasExtraFiles()) {
1202 W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1203 ListScope ExtraFiles(W, "ExtraFiles");
1204 for (const auto &FID : Line.ExtraFiles) {
1205 printFileNameForOffset("FileID", FID);
1211 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1212 // The file checksum subsection should precede all references to it.
1213 if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1214 error(object_error::parse_failed);
1216 auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1218 // Check if the file checksum table offset is valid.
1219 if (Iter == CVFileChecksumTable.end())
1220 error(object_error::parse_failed);
1222 return error(CVStringTable.getString(Iter->FileNameOffset));
1225 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1226 W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1229 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1230 MergingTypeTableBuilder &CVTypes) {
1231 for (const SectionRef &S : Obj->sections()) {
1232 StringRef SectionName;
1233 error(S.getName(SectionName));
1234 if (SectionName == ".debug$T") {
1236 error(S.getContents(Data));
1238 error(consume(Data, Magic));
1240 error(object_error::parse_failed);
1243 BinaryStreamReader Reader(Data, llvm::support::little);
1244 if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1245 consumeError(std::move(EC));
1247 error(object_error::parse_failed);
1249 SmallVector<TypeIndex, 128> SourceToDest;
1250 if (auto EC = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types))
1251 return error(std::move(EC));
1256 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1257 const SectionRef &Section) {
1258 ListScope D(W, "CodeViewTypes");
1259 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1262 error(Section.getContents(Data));
1263 if (opts::CodeViewSubsectionBytes)
1264 W.printBinaryBlock("Data", Data);
1267 error(consume(Data, Magic));
1268 W.printHex("Magic", Magic);
1269 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1270 return error(object_error::parse_failed);
1272 Types.reset(Data, 100);
1274 TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1275 error(codeview::visitTypeStream(Types, TDV));
1279 void COFFDumper::printSections() {
1280 ListScope SectionsD(W, "Sections");
1281 int SectionNumber = 0;
1282 for (const SectionRef &Sec : Obj->sections()) {
1284 const coff_section *Section = Obj->getCOFFSection(Sec);
1287 error(Sec.getName(Name));
1289 DictScope D(W, "Section");
1290 W.printNumber("Number", SectionNumber);
1291 W.printBinary("Name", Name, Section->Name);
1292 W.printHex ("VirtualSize", Section->VirtualSize);
1293 W.printHex ("VirtualAddress", Section->VirtualAddress);
1294 W.printNumber("RawDataSize", Section->SizeOfRawData);
1295 W.printHex ("PointerToRawData", Section->PointerToRawData);
1296 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
1297 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
1298 W.printNumber("RelocationCount", Section->NumberOfRelocations);
1299 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1300 W.printFlags ("Characteristics", Section->Characteristics,
1301 makeArrayRef(ImageSectionCharacteristics),
1302 COFF::SectionCharacteristics(0x00F00000));
1304 if (opts::SectionRelocations) {
1305 ListScope D(W, "Relocations");
1306 for (const RelocationRef &Reloc : Sec.relocations())
1307 printRelocation(Sec, Reloc);
1310 if (opts::SectionSymbols) {
1311 ListScope D(W, "Symbols");
1312 for (const SymbolRef &Symbol : Obj->symbols()) {
1313 if (!Sec.containsSymbol(Symbol))
1316 printSymbol(Symbol);
1320 if (opts::SectionData &&
1321 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1323 error(Sec.getContents(Data));
1325 W.printBinaryBlock("SectionData", Data);
1330 void COFFDumper::printRelocations() {
1331 ListScope D(W, "Relocations");
1333 int SectionNumber = 0;
1334 for (const SectionRef &Section : Obj->sections()) {
1337 error(Section.getName(Name));
1339 bool PrintedGroup = false;
1340 for (const RelocationRef &Reloc : Section.relocations()) {
1341 if (!PrintedGroup) {
1342 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1344 PrintedGroup = true;
1347 printRelocation(Section, Reloc);
1352 W.startLine() << "}\n";
1357 void COFFDumper::printRelocation(const SectionRef &Section,
1358 const RelocationRef &Reloc, uint64_t Bias) {
1359 uint64_t Offset = Reloc.getOffset() - Bias;
1360 uint64_t RelocType = Reloc.getType();
1361 SmallString<32> RelocName;
1362 StringRef SymbolName;
1363 Reloc.getTypeName(RelocName);
1364 symbol_iterator Symbol = Reloc.getSymbol();
1365 if (Symbol != Obj->symbol_end()) {
1366 Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1367 error(errorToErrorCode(SymbolNameOrErr.takeError()));
1368 SymbolName = *SymbolNameOrErr;
1371 if (opts::ExpandRelocs) {
1372 DictScope Group(W, "Relocation");
1373 W.printHex("Offset", Offset);
1374 W.printNumber("Type", RelocName, RelocType);
1375 W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1377 raw_ostream& OS = W.startLine();
1380 << " " << (SymbolName.empty() ? "-" : SymbolName)
1385 void COFFDumper::printSymbols() {
1386 ListScope Group(W, "Symbols");
1388 for (const SymbolRef &Symbol : Obj->symbols())
1389 printSymbol(Symbol);
1392 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1394 static ErrorOr<StringRef>
1395 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1396 const coff_section *Section) {
1398 StringRef SectionName;
1399 if (std::error_code EC = Obj->getSectionName(Section, SectionName))
1403 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1404 return StringRef("IMAGE_SYM_DEBUG");
1405 if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1406 return StringRef("IMAGE_SYM_ABSOLUTE");
1407 if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1408 return StringRef("IMAGE_SYM_UNDEFINED");
1409 return StringRef("");
1412 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1413 DictScope D(W, "Symbol");
1415 COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1416 const coff_section *Section;
1417 if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1418 W.startLine() << "Invalid section number: " << EC.message() << "\n";
1423 StringRef SymbolName;
1424 if (Obj->getSymbolName(Symbol, SymbolName))
1427 StringRef SectionName = "";
1428 ErrorOr<StringRef> Res =
1429 getSectionName(Obj, Symbol.getSectionNumber(), Section);
1433 W.printString("Name", SymbolName);
1434 W.printNumber("Value", Symbol.getValue());
1435 W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1436 W.printEnum ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1437 W.printEnum ("ComplexType", Symbol.getComplexType(),
1438 makeArrayRef(ImageSymDType));
1439 W.printEnum ("StorageClass", Symbol.getStorageClass(),
1440 makeArrayRef(ImageSymClass));
1441 W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1443 for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1444 if (Symbol.isFunctionDefinition()) {
1445 const coff_aux_function_definition *Aux;
1446 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1448 DictScope AS(W, "AuxFunctionDef");
1449 W.printNumber("TagIndex", Aux->TagIndex);
1450 W.printNumber("TotalSize", Aux->TotalSize);
1451 W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1452 W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1454 } else if (Symbol.isAnyUndefined()) {
1455 const coff_aux_weak_external *Aux;
1456 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1458 Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1459 StringRef LinkedName;
1460 std::error_code EC = errorToErrorCode(Linked.takeError());
1461 if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) {
1466 DictScope AS(W, "AuxWeakExternal");
1467 W.printNumber("Linked", LinkedName, Aux->TagIndex);
1468 W.printEnum ("Search", Aux->Characteristics,
1469 makeArrayRef(WeakExternalCharacteristics));
1471 } else if (Symbol.isFileRecord()) {
1472 const char *FileName;
1473 error(getSymbolAuxData(Obj, Symbol, I, FileName));
1475 DictScope AS(W, "AuxFileRecord");
1477 StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1478 Obj->getSymbolTableEntrySize());
1479 W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1481 } else if (Symbol.isSectionDefinition()) {
1482 const coff_aux_section_definition *Aux;
1483 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1485 int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1487 DictScope AS(W, "AuxSectionDef");
1488 W.printNumber("Length", Aux->Length);
1489 W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1490 W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1491 W.printHex("Checksum", Aux->CheckSum);
1492 W.printNumber("Number", AuxNumber);
1493 W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1495 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1496 && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1497 const coff_section *Assoc;
1498 StringRef AssocName = "";
1499 std::error_code EC = Obj->getSection(AuxNumber, Assoc);
1500 ErrorOr<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1504 EC = Res.getError();
1510 W.printNumber("AssocSection", AssocName, AuxNumber);
1512 } else if (Symbol.isCLRToken()) {
1513 const coff_aux_clr_token *Aux;
1514 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1516 Expected<COFFSymbolRef> ReferredSym =
1517 Obj->getSymbol(Aux->SymbolTableIndex);
1518 StringRef ReferredName;
1519 std::error_code EC = errorToErrorCode(ReferredSym.takeError());
1520 if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
1525 DictScope AS(W, "AuxCLRToken");
1526 W.printNumber("AuxType", Aux->AuxType);
1527 W.printNumber("Reserved", Aux->Reserved);
1528 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1531 W.startLine() << "<unhandled auxiliary record>\n";
1536 void COFFDumper::printUnwindInfo() {
1537 ListScope D(W, "UnwindInformation");
1538 switch (Obj->getMachine()) {
1539 case COFF::IMAGE_FILE_MACHINE_AMD64: {
1540 Win64EH::Dumper Dumper(W);
1541 Win64EH::Dumper::SymbolResolver
1542 Resolver = [](const object::coff_section *Section, uint64_t Offset,
1543 SymbolRef &Symbol, void *user_data) -> std::error_code {
1544 COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1545 return Dumper->resolveSymbol(Section, Offset, Symbol);
1547 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1548 Dumper.printData(Ctx);
1551 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1552 ARM::WinEH::Decoder Decoder(W);
1553 Decoder.dumpProcedureData(*Obj);
1557 W.printEnum("unsupported Image Machine", Obj->getMachine(),
1558 makeArrayRef(ImageFileMachineType));
1563 void COFFDumper::printNeededLibraries() {
1564 ListScope D(W, "NeededLibraries");
1566 using LibsTy = std::vector<StringRef>;
1569 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1571 if (!DirRef.getName(Name))
1572 Libs.push_back(Name);
1575 std::stable_sort(Libs.begin(), Libs.end());
1577 for (const auto &L : Libs) {
1578 outs() << " " << L << "\n";
1582 void COFFDumper::printImportedSymbols(
1583 iterator_range<imported_symbol_iterator> Range) {
1584 for (const ImportedSymbolRef &I : Range) {
1586 error(I.getSymbolName(Sym));
1588 error(I.getOrdinal(Ordinal));
1589 W.printNumber("Symbol", Sym, Ordinal);
1593 void COFFDumper::printDelayImportedSymbols(
1594 const DelayImportDirectoryEntryRef &I,
1595 iterator_range<imported_symbol_iterator> Range) {
1597 for (const ImportedSymbolRef &S : Range) {
1598 DictScope Import(W, "Import");
1600 error(S.getSymbolName(Sym));
1602 error(S.getOrdinal(Ordinal));
1603 W.printNumber("Symbol", Sym, Ordinal);
1605 error(I.getImportAddress(Index++, Addr));
1606 W.printHex("Address", Addr);
1610 void COFFDumper::printCOFFImports() {
1612 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1613 DictScope Import(W, "Import");
1615 error(I.getName(Name));
1616 W.printString("Name", Name);
1618 error(I.getImportLookupTableRVA(ILTAddr));
1619 W.printHex("ImportLookupTableRVA", ILTAddr);
1621 error(I.getImportAddressTableRVA(IATAddr));
1622 W.printHex("ImportAddressTableRVA", IATAddr);
1623 // The import lookup table can be missing with certain older linkers, so
1624 // fall back to the import address table in that case.
1626 printImportedSymbols(I.lookup_table_symbols());
1628 printImportedSymbols(I.imported_symbols());
1632 for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1633 DictScope Import(W, "DelayImport");
1635 error(I.getName(Name));
1636 W.printString("Name", Name);
1637 const delay_import_directory_table_entry *Table;
1638 error(I.getDelayImportTable(Table));
1639 W.printHex("Attributes", Table->Attributes);
1640 W.printHex("ModuleHandle", Table->ModuleHandle);
1641 W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1642 W.printHex("ImportNameTable", Table->DelayImportNameTable);
1643 W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1644 W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1645 printDelayImportedSymbols(I, I.imported_symbols());
1649 void COFFDumper::printCOFFExports() {
1650 for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1651 DictScope Export(W, "Export");
1654 uint32_t Ordinal, RVA;
1656 error(E.getSymbolName(Name));
1657 error(E.getOrdinal(Ordinal));
1658 error(E.getExportRVA(RVA));
1660 W.printNumber("Ordinal", Ordinal);
1661 W.printString("Name", Name);
1662 W.printHex("RVA", RVA);
1666 void COFFDumper::printCOFFDirectives() {
1667 for (const SectionRef &Section : Obj->sections()) {
1671 error(Section.getName(Name));
1672 if (Name != ".drectve")
1675 error(Section.getContents(Contents));
1677 W.printString("Directive(s)", Contents);
1681 static std::string getBaseRelocTypeName(uint8_t Type) {
1683 case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1684 case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1685 case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1686 case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1687 case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1688 case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1689 case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1690 default: return "unknown (" + llvm::utostr(Type) + ")";
1694 void COFFDumper::printCOFFBaseReloc() {
1695 ListScope D(W, "BaseReloc");
1696 for (const BaseRelocRef &I : Obj->base_relocs()) {
1699 error(I.getRVA(RVA));
1700 error(I.getType(Type));
1701 DictScope Import(W, "Entry");
1702 W.printString("Type", getBaseRelocTypeName(Type));
1703 W.printHex("Address", RVA);
1707 void COFFDumper::printCOFFResources() {
1708 ListScope ResourcesD(W, "Resources");
1709 for (const SectionRef &S : Obj->sections()) {
1711 error(S.getName(Name));
1712 if (!Name.startswith(".rsrc"))
1716 error(S.getContents(Ref));
1718 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1719 ResourceSectionRef RSF(Ref);
1720 auto &BaseTable = unwrapOrError(RSF.getBaseTable());
1721 W.printNumber("Total Number of Resources",
1722 countTotalTableEntries(RSF, BaseTable, "Type"));
1723 W.printHex("Base Table Address",
1724 Obj->getCOFFSection(S)->PointerToRawData);
1725 W.startLine() << "\n";
1726 printResourceDirectoryTable(RSF, BaseTable, "Type");
1728 if (opts::SectionData)
1729 W.printBinaryBlock(Name.str() + " Data", Ref);
1734 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1735 const coff_resource_dir_table &Table,
1737 uint32_t TotalEntries = 0;
1738 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1740 auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1741 if (Entry.Offset.isSubDir()) {
1742 StringRef NextLevel;
1743 if (Level == "Name")
1744 NextLevel = "Language";
1747 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1748 TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1753 return TotalEntries;
1756 void COFFDumper::printResourceDirectoryTable(
1757 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1760 W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1761 W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1763 // Iterate through level in resource directory tree.
1764 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1766 auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1768 SmallString<20> IDStr;
1769 raw_svector_ostream OS(IDStr);
1770 if (i < Table.NumberOfNameEntries) {
1771 ArrayRef<UTF16> RawEntryNameString = unwrapOrError(RSF.getEntryNameString(Entry));
1772 std::vector<UTF16> EndianCorrectedNameString;
1773 if (llvm::sys::IsBigEndianHost) {
1774 EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1775 std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1776 EndianCorrectedNameString.begin() + 1);
1777 EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1778 RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1780 std::string EntryNameString;
1781 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1782 error(object_error::parse_failed);
1784 OS << EntryNameString;
1786 if (Level == "Type") {
1787 ScopedPrinter Printer(OS);
1788 Printer.printEnum("", Entry.Identifier.ID,
1789 makeArrayRef(ResourceTypeNames));
1790 IDStr = IDStr.slice(0, IDStr.find_first_of(")", 0) + 1);
1792 OS << ": (ID " << Entry.Identifier.ID << ")";
1795 Name = StringRef(IDStr);
1796 ListScope ResourceType(W, Level.str() + Name.str());
1797 if (Entry.Offset.isSubDir()) {
1798 W.printHex("Table Offset", Entry.Offset.value());
1799 StringRef NextLevel;
1800 if (Level == "Name")
1801 NextLevel = "Language";
1804 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1805 printResourceDirectoryTable(RSF, NextTable, NextLevel);
1807 W.printHex("Entry Offset", Entry.Offset.value());
1808 char FormattedTime[20] = {};
1809 time_t TDS = time_t(Table.TimeDateStamp);
1810 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1811 W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1812 W.printNumber("Major Version", Table.MajorVersion);
1813 W.printNumber("Minor Version", Table.MinorVersion);
1814 W.printNumber("Characteristics", Table.Characteristics);
1819 ErrorOr<const coff_resource_dir_entry &>
1820 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
1822 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1823 return object_error::parse_failed;
1824 auto TablePtr = reinterpret_cast<const coff_resource_dir_entry *>(&Table + 1);
1825 return TablePtr[Index];
1828 void COFFDumper::printStackMap() const {
1829 object::SectionRef StackMapSection;
1830 for (auto Sec : Obj->sections()) {
1833 if (Name == ".llvm_stackmaps") {
1834 StackMapSection = Sec;
1839 if (StackMapSection == object::SectionRef())
1842 StringRef StackMapContents;
1843 StackMapSection.getContents(StackMapContents);
1844 ArrayRef<uint8_t> StackMapContentsArray(
1845 reinterpret_cast<const uint8_t*>(StackMapContents.data()),
1846 StackMapContents.size());
1848 if (Obj->isLittleEndian())
1849 prettyPrintStackMap(
1850 W, StackMapV2Parser<support::little>(StackMapContentsArray));
1852 prettyPrintStackMap(W,
1853 StackMapV2Parser<support::big>(StackMapContentsArray));
1856 void llvm::dumpCodeViewMergedTypes(
1857 ScopedPrinter &Writer, llvm::codeview::MergingTypeTableBuilder &IDTable,
1858 llvm::codeview::MergingTypeTableBuilder &CVTypes) {
1859 // Flatten it first, then run our dumper on it.
1860 SmallString<0> TypeBuf;
1861 CVTypes.ForEachRecord([&](TypeIndex TI, const CVType &Record) {
1862 TypeBuf.append(Record.RecordData.begin(), Record.RecordData.end());
1865 TypeTableCollection TpiTypes(CVTypes.records());
1867 ListScope S(Writer, "MergedTypeStream");
1868 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1869 error(codeview::visitTypeStream(TpiTypes, TDV));
1873 // Flatten the id stream and print it next. The ID stream refers to names from
1875 TypeTableCollection IpiTypes(IDTable.records());
1877 ListScope S(Writer, "MergedIDStream");
1878 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1879 TDV.setIpiTypes(IpiTypes);
1880 error(codeview::visitTypeStream(IpiTypes, TDV));