1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements the COFF-specific dumper for llvm-readobj.
13 //===----------------------------------------------------------------------===//
15 #include "ARMWinEHPrinter.h"
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;
72 class COFFDumper : public ObjDumper {
74 friend class COFFObjectDumpDelegate;
75 COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
76 : ObjDumper(Writer), Obj(Obj), Writer(Writer), Types(100) {}
78 void printFileHeaders() override;
79 void printSections() override;
80 void printRelocations() override;
81 void printSymbols() override;
82 void printDynamicSymbols() 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;
96 mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
97 llvm::codeview::MergingTypeTableBuilder &CVTypes) override;
98 void printStackMap() const override;
100 void printSymbol(const SymbolRef &Sym);
101 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
103 void printDataDirectory(uint32_t Index, const std::string &FieldName);
105 void printDOSHeader(const dos_header *DH);
106 template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
107 void printBaseOfDataField(const pe32_header *Hdr);
108 void printBaseOfDataField(const pe32plus_header *Hdr);
109 template <typename T>
110 void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
111 typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
112 void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
113 PrintExtraCB PrintExtra = 0);
115 void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
116 void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
117 StringRef getTypeName(TypeIndex Ty);
118 StringRef getFileNameForFileOffset(uint32_t FileOffset);
119 void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
120 void printTypeIndex(StringRef FieldName, TypeIndex TI) {
121 // Forward to CVTypeDumper for simplicity.
122 codeview::printTypeIndex(Writer, FieldName, TI, Types);
125 void printCodeViewSymbolsSubsection(StringRef Subsection,
126 const SectionRef &Section,
127 StringRef SectionContents);
129 void printCodeViewFileChecksums(StringRef Subsection);
131 void printCodeViewInlineeLines(StringRef Subsection);
133 void printRelocatedField(StringRef Label, const coff_section *Sec,
134 uint32_t RelocOffset, uint32_t Offset,
135 StringRef *RelocSym = nullptr);
137 uint32_t countTotalTableEntries(ResourceSectionRef RSF,
138 const coff_resource_dir_table &Table,
141 void printResourceDirectoryTable(ResourceSectionRef RSF,
142 const coff_resource_dir_table &Table,
145 void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
146 StringRef SectionContents, StringRef Block);
148 /// Given a .debug$S section, find the string table and file checksum table.
149 void initializeFileAndStringTables(BinaryStreamReader &Reader);
151 void cacheRelocations();
153 std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
155 std::error_code resolveSymbolName(const coff_section *Section,
156 uint64_t Offset, StringRef &Name);
157 std::error_code resolveSymbolName(const coff_section *Section,
158 StringRef SectionContents,
159 const void *RelocPtr, StringRef &Name);
160 void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
161 void printDelayImportedSymbols(
162 const DelayImportDirectoryEntryRef &I,
163 iterator_range<imported_symbol_iterator> Range);
164 ErrorOr<const coff_resource_dir_entry &>
165 getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
168 typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
170 const llvm::object::COFFObjectFile *Obj;
171 bool RelocCached = false;
174 DebugChecksumsSubsectionRef CVFileChecksumTable;
176 DebugStringTableSubsectionRef CVStringTable;
178 ScopedPrinter &Writer;
179 BinaryByteStream TypeContents;
180 LazyRandomTypeCollection Types;
183 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
185 COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
186 const COFFObjectFile *Obj, StringRef SectionContents)
187 : CD(CD), SR(SR), SectionContents(SectionContents) {
188 Sec = Obj->getCOFFSection(SR);
191 uint32_t getRecordOffset(BinaryStreamReader Reader) override {
192 ArrayRef<uint8_t> Data;
193 if (auto EC = Reader.readLongestContiguousChunk(Data)) {
194 llvm::consumeError(std::move(EC));
197 return Data.data() - SectionContents.bytes_begin();
200 void printRelocatedField(StringRef Label, uint32_t RelocOffset,
201 uint32_t Offset, StringRef *RelocSym) override {
202 CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
205 void printBinaryBlockWithRelocs(StringRef Label,
206 ArrayRef<uint8_t> Block) override {
207 StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
209 if (opts::CodeViewSubsectionBytes)
210 CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
213 StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
214 return CD.getFileNameForFileOffset(FileOffset);
217 DebugStringTableSubsectionRef getStringTable() override {
218 return CD.CVStringTable;
223 const SectionRef &SR;
224 const coff_section *Sec;
225 StringRef SectionContents;
232 std::error_code createCOFFDumper(const object::ObjectFile *Obj,
233 ScopedPrinter &Writer,
234 std::unique_ptr<ObjDumper> &Result) {
235 const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
237 return readobj_error::unsupported_obj_file_format;
239 Result.reset(new COFFDumper(COFFObj, Writer));
240 return readobj_error::success;
245 // Given a a section and an offset into this section the function returns the
246 // symbol used for the relocation at the offset.
247 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
248 uint64_t Offset, SymbolRef &Sym) {
250 const auto &Relocations = RelocMap[Section];
251 auto SymI = Obj->symbol_end();
252 for (const auto &Relocation : Relocations) {
253 uint64_t RelocationOffset = Relocation.getOffset();
255 if (RelocationOffset == Offset) {
256 SymI = Relocation.getSymbol();
260 if (SymI == Obj->symbol_end())
261 return readobj_error::unknown_symbol;
263 return readobj_error::success;
266 // Given a section and an offset into this section the function returns the name
267 // of the symbol used for the relocation at the offset.
268 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
272 if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
274 Expected<StringRef> NameOrErr = Symbol.getName();
276 return errorToErrorCode(NameOrErr.takeError());
278 return std::error_code();
281 // Helper for when you have a pointer to real data and you want to know about
282 // relocations against it.
283 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
284 StringRef SectionContents,
285 const void *RelocPtr,
287 assert(SectionContents.data() < RelocPtr &&
288 RelocPtr < SectionContents.data() + SectionContents.size() &&
289 "pointer to relocated object is not in section");
290 uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
291 SectionContents.data());
292 return resolveSymbolName(Section, Offset, Name);
295 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
296 uint32_t RelocOffset, uint32_t Offset,
297 StringRef *RelocSym) {
298 StringRef SymStorage;
299 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
300 if (!resolveSymbolName(Sec, RelocOffset, Symbol))
301 W.printSymbolOffset(Label, Symbol, Offset);
303 W.printHex(Label, RelocOffset);
306 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
307 const SectionRef &Sec,
308 StringRef SectionContents,
310 W.printBinaryBlock(Label, Block);
312 assert(SectionContents.begin() < Block.begin() &&
313 SectionContents.end() >= Block.end() &&
314 "Block is not contained in SectionContents");
315 uint64_t OffsetStart = Block.data() - SectionContents.data();
316 uint64_t OffsetEnd = OffsetStart + Block.size();
320 ListScope D(W, "BlockRelocations");
321 const coff_section *Section = Obj->getCOFFSection(Sec);
322 const auto &Relocations = RelocMap[Section];
323 for (const auto &Relocation : Relocations) {
324 uint64_t RelocationOffset = Relocation.getOffset();
325 if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
326 printRelocation(Sec, Relocation, OffsetStart);
330 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
331 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
332 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
333 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
334 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
335 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64 ),
336 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
337 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
338 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
339 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
340 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
341 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
342 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
343 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
344 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
345 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
346 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
347 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
348 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
349 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
350 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
351 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
352 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
355 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
356 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
357 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
358 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
359 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
360 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
361 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
362 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
363 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
364 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
365 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
366 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
367 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
368 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
369 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
370 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
373 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
374 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
375 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
376 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
377 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
378 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
379 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
380 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
381 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
382 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
383 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
384 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
387 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
388 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
389 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
390 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
391 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
392 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
393 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
394 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
395 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER ),
396 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
397 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF ),
398 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
401 static const EnumEntry<COFF::SectionCharacteristics>
402 ImageSectionCharacteristics[] = {
403 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD ),
404 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
405 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
406 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
407 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
408 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
409 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
410 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
411 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
412 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
413 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
414 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
415 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
416 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
417 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
418 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
419 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
420 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
421 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
422 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
423 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
424 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
425 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
426 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
427 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
428 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
429 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
430 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
431 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
432 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
433 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
434 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
435 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
436 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
437 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
438 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
441 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
442 { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
443 { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
444 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
445 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
446 { "Int" , COFF::IMAGE_SYM_TYPE_INT },
447 { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
448 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
449 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
450 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
451 { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
452 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
453 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
454 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
455 { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
456 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
457 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
460 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
461 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
462 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
463 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
464 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
467 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
468 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
469 { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
470 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
471 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
472 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
473 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
474 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
475 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
476 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
477 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
478 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
479 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
480 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
481 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
482 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
483 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
484 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
485 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
486 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
487 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
488 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
489 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
490 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
491 { "File" , COFF::IMAGE_SYM_CLASS_FILE },
492 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
493 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
494 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
497 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
498 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
499 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
500 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
501 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
502 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
503 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
504 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
507 static const EnumEntry<COFF::DebugType> ImageDebugType[] = {
508 { "Unknown" , COFF::IMAGE_DEBUG_TYPE_UNKNOWN },
509 { "COFF" , COFF::IMAGE_DEBUG_TYPE_COFF },
510 { "CodeView" , COFF::IMAGE_DEBUG_TYPE_CODEVIEW },
511 { "FPO" , COFF::IMAGE_DEBUG_TYPE_FPO },
512 { "Misc" , COFF::IMAGE_DEBUG_TYPE_MISC },
513 { "Exception" , COFF::IMAGE_DEBUG_TYPE_EXCEPTION },
514 { "Fixup" , COFF::IMAGE_DEBUG_TYPE_FIXUP },
515 { "OmapToSrc" , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC },
516 { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC },
517 { "Borland" , COFF::IMAGE_DEBUG_TYPE_BORLAND },
518 { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10 },
519 { "CLSID" , COFF::IMAGE_DEBUG_TYPE_CLSID },
520 { "VCFeature" , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE },
521 { "POGO" , COFF::IMAGE_DEBUG_TYPE_POGO },
522 { "ILTCG" , COFF::IMAGE_DEBUG_TYPE_ILTCG },
523 { "MPX" , COFF::IMAGE_DEBUG_TYPE_MPX },
524 { "Repro" , COFF::IMAGE_DEBUG_TYPE_REPRO },
527 static const EnumEntry<COFF::WeakExternalCharacteristics>
528 WeakExternalCharacteristics[] = {
529 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
530 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
531 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
534 static const EnumEntry<uint32_t> SubSectionTypes[] = {
535 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
536 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
537 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
538 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
539 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
540 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
541 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
542 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
543 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
544 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
545 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
546 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
547 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
550 static const EnumEntry<uint32_t> FrameDataFlags[] = {
551 LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
552 LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
553 LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
556 static const EnumEntry<uint8_t> FileChecksumKindNames[] = {
557 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
558 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
559 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
560 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
563 static const EnumEntry<COFF::ResourceTypeID> ResourceTypeNames[]{
564 {"kRT_CURSOR (ID 1)", COFF::RID_Cursor},
565 {"kRT_BITMAP (ID 2)", COFF::RID_Bitmap},
566 {"kRT_ICON (ID 3)", COFF::RID_Icon},
567 {"kRT_MENU (ID 4)", COFF::RID_Menu},
568 {"kRT_DIALOG (ID 5)", COFF::RID_Dialog},
569 {"kRT_STRING (ID 6)", COFF::RID_String},
570 {"kRT_FONTDIR (ID 7)", COFF::RID_FontDir},
571 {"kRT_FONT (ID 8)", COFF::RID_Font},
572 {"kRT_ACCELERATOR (ID 9)", COFF::RID_Accelerator},
573 {"kRT_RCDATA (ID 10)", COFF::RID_RCData},
574 {"kRT_MESSAGETABLE (ID 11)", COFF::RID_MessageTable},
575 {"kRT_GROUP_CURSOR (ID 12)", COFF::RID_Group_Cursor},
576 {"kRT_GROUP_ICON (ID 14)", COFF::RID_Group_Icon},
577 {"kRT_VERSION (ID 16)", COFF::RID_Version},
578 {"kRT_DLGINCLUDE (ID 17)", COFF::RID_DLGInclude},
579 {"kRT_PLUGPLAY (ID 19)", COFF::RID_PlugPlay},
580 {"kRT_VXD (ID 20)", COFF::RID_VXD},
581 {"kRT_ANICURSOR (ID 21)", COFF::RID_AniCursor},
582 {"kRT_ANIICON (ID 22)", COFF::RID_AniIcon},
583 {"kRT_HTML (ID 23)", COFF::RID_HTML},
584 {"kRT_MANIFEST (ID 24)", COFF::RID_Manifest}};
586 template <typename T>
587 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
588 COFFSymbolRef Symbol,
589 uint8_t AuxSymbolIdx, const T *&Aux) {
590 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
591 AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
592 Aux = reinterpret_cast<const T*>(AuxData.data());
593 return readobj_error::success;
596 void COFFDumper::cacheRelocations() {
601 for (const SectionRef &S : Obj->sections()) {
602 const coff_section *Section = Obj->getCOFFSection(S);
604 for (const RelocationRef &Reloc : S.relocations())
605 RelocMap[Section].push_back(Reloc);
607 // Sort relocations by address.
608 std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
613 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
614 const data_directory *Data;
615 if (Obj->getDataDirectory(Index, Data))
617 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
618 W.printHex(FieldName + "Size", Data->Size);
621 void COFFDumper::printFileHeaders() {
622 time_t TDS = Obj->getTimeDateStamp();
623 char FormattedTime[20] = { };
624 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
627 DictScope D(W, "ImageFileHeader");
628 W.printEnum ("Machine", Obj->getMachine(),
629 makeArrayRef(ImageFileMachineType));
630 W.printNumber("SectionCount", Obj->getNumberOfSections());
631 W.printHex ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
632 W.printHex ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
633 W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
634 W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
635 W.printFlags ("Characteristics", Obj->getCharacteristics(),
636 makeArrayRef(ImageFileCharacteristics));
639 // Print PE header. This header does not exist if this is an object file and
640 // not an executable.
641 const pe32_header *PEHeader = nullptr;
642 error(Obj->getPE32Header(PEHeader));
644 printPEHeader<pe32_header>(PEHeader);
646 const pe32plus_header *PEPlusHeader = nullptr;
647 error(Obj->getPE32PlusHeader(PEPlusHeader));
649 printPEHeader<pe32plus_header>(PEPlusHeader);
651 if (const dos_header *DH = Obj->getDOSHeader())
655 void COFFDumper::printDOSHeader(const dos_header *DH) {
656 DictScope D(W, "DOSHeader");
657 W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
658 W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
659 W.printNumber("FileSizeInPages", DH->FileSizeInPages);
660 W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
661 W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
662 W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
663 W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
664 W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
665 W.printNumber("InitialSP", DH->InitialSP);
666 W.printNumber("Checksum", DH->Checksum);
667 W.printNumber("InitialIP", DH->InitialIP);
668 W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
669 W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
670 W.printNumber("OverlayNumber", DH->OverlayNumber);
671 W.printNumber("OEMid", DH->OEMid);
672 W.printNumber("OEMinfo", DH->OEMinfo);
673 W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
676 template <class PEHeader>
677 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
678 DictScope D(W, "ImageOptionalHeader");
679 W.printHex ("Magic", Hdr->Magic);
680 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
681 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
682 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
683 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
684 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
685 W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
686 W.printHex ("BaseOfCode", Hdr->BaseOfCode);
687 printBaseOfDataField(Hdr);
688 W.printHex ("ImageBase", Hdr->ImageBase);
689 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
690 W.printNumber("FileAlignment", Hdr->FileAlignment);
691 W.printNumber("MajorOperatingSystemVersion",
692 Hdr->MajorOperatingSystemVersion);
693 W.printNumber("MinorOperatingSystemVersion",
694 Hdr->MinorOperatingSystemVersion);
695 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
696 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
697 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
698 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
699 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
700 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
701 W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
702 W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
703 makeArrayRef(PEDLLCharacteristics));
704 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
705 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
706 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
707 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
708 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
710 if (Hdr->NumberOfRvaAndSize > 0) {
711 DictScope D(W, "DataDirectory");
712 static const char * const directory[] = {
713 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
714 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
715 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
716 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
719 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
720 printDataDirectory(i, directory[i]);
724 void COFFDumper::printCOFFDebugDirectory() {
725 ListScope LS(W, "DebugDirectory");
726 for (const debug_directory &D : Obj->debug_directories()) {
727 char FormattedTime[20] = {};
728 time_t TDS = D.TimeDateStamp;
729 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
730 DictScope S(W, "DebugEntry");
731 W.printHex("Characteristics", D.Characteristics);
732 W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
733 W.printHex("MajorVersion", D.MajorVersion);
734 W.printHex("MinorVersion", D.MinorVersion);
735 W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
736 W.printHex("SizeOfData", D.SizeOfData);
737 W.printHex("AddressOfRawData", D.AddressOfRawData);
738 W.printHex("PointerToRawData", D.PointerToRawData);
739 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
740 const codeview::DebugInfo *DebugInfo;
741 StringRef PDBFileName;
742 error(Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName));
743 DictScope PDBScope(W, "PDBInfo");
744 W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
745 if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
746 W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
747 W.printNumber("PDBAge", DebugInfo->PDB70.Age);
748 W.printString("PDBFileName", PDBFileName);
751 // FIXME: Type values of 12 and 13 are commonly observed but are not in
752 // the documented type enum. Figure out what they mean.
753 ArrayRef<uint8_t> RawData;
755 Obj->getRvaAndSizeAsBytes(D.AddressOfRawData, D.SizeOfData, RawData));
756 W.printBinaryBlock("RawData", RawData);
761 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
762 uint64_t EntrySize, PrintExtraCB PrintExtra) {
763 uintptr_t TableStart, TableEnd;
764 error(Obj->getVaPtr(TableVA, TableStart));
765 error(Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd));
767 for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
768 uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
769 raw_ostream &OS = W.startLine();
770 OS << "0x" << W.hex(Obj->getImageBase() + RVA);
772 PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
777 void COFFDumper::printCOFFLoadConfig() {
778 LoadConfigTables Tables;
780 printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
782 printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
784 if (Tables.SEHTableVA) {
785 ListScope LS(W, "SEHTable");
786 printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
789 if (Tables.GuardFidTableVA) {
790 ListScope LS(W, "GuardFidTable");
791 if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
792 auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
793 uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
795 OS << " flags " << utohexstr(Flags);
797 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
800 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
805 template <typename T>
806 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
810 ListScope LS(W, "LoadConfig");
811 char FormattedTime[20] = {};
812 time_t TDS = Conf->TimeDateStamp;
813 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
814 W.printHex("Size", Conf->Size);
816 // Print everything before SecurityCookie. The vast majority of images today
817 // have all these fields.
818 if (Conf->Size < offsetof(T, SEHandlerTable))
820 W.printHex("TimeDateStamp", FormattedTime, TDS);
821 W.printHex("MajorVersion", Conf->MajorVersion);
822 W.printHex("MinorVersion", Conf->MinorVersion);
823 W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
824 W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
825 W.printHex("CriticalSectionDefaultTimeout",
826 Conf->CriticalSectionDefaultTimeout);
827 W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
828 W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
829 W.printHex("LockPrefixTable", Conf->LockPrefixTable);
830 W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
831 W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
832 W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
833 W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
834 W.printHex("CSDVersion", Conf->CSDVersion);
835 W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
836 W.printHex("EditList", Conf->EditList);
837 W.printHex("SecurityCookie", Conf->SecurityCookie);
839 // Print the safe SEH table if present.
840 if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
842 W.printHex("SEHandlerTable", Conf->SEHandlerTable);
843 W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
845 Tables.SEHTableVA = Conf->SEHandlerTable;
846 Tables.SEHTableCount = Conf->SEHandlerCount;
848 // Print everything before CodeIntegrity. (2015)
849 if (Conf->Size < offsetof(T, CodeIntegrity))
851 W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
852 W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
853 W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
854 W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
855 W.printHex("GuardFlags", Conf->GuardFlags);
857 Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
858 Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
859 Tables.GuardFlags = Conf->GuardFlags;
861 // Print the rest. (2017)
862 if (Conf->Size < sizeof(T))
864 W.printHex("GuardAddressTakenIatEntryTable",
865 Conf->GuardAddressTakenIatEntryTable);
866 W.printNumber("GuardAddressTakenIatEntryCount",
867 Conf->GuardAddressTakenIatEntryCount);
868 W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
869 W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
870 W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
871 W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
872 W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
873 W.printHex("GuardRFFailureRoutineFunctionPointer",
874 Conf->GuardRFFailureRoutineFunctionPointer);
875 W.printHex("DynamicValueRelocTableOffset",
876 Conf->DynamicValueRelocTableOffset);
877 W.printNumber("DynamicValueRelocTableSection",
878 Conf->DynamicValueRelocTableSection);
879 W.printHex("GuardRFVerifyStackPointerFunctionPointer",
880 Conf->GuardRFVerifyStackPointerFunctionPointer);
881 W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
884 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
885 W.printHex("BaseOfData", Hdr->BaseOfData);
888 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
890 void COFFDumper::printCodeViewDebugInfo() {
891 // Print types first to build CVUDTNames, then print symbols.
892 for (const SectionRef &S : Obj->sections()) {
893 StringRef SectionName;
894 error(S.getName(SectionName));
895 if (SectionName == ".debug$T")
896 printCodeViewTypeSection(SectionName, S);
898 for (const SectionRef &S : Obj->sections()) {
899 StringRef SectionName;
900 error(S.getName(SectionName));
901 if (SectionName == ".debug$S")
902 printCodeViewSymbolSection(SectionName, S);
906 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
907 while (Reader.bytesRemaining() > 0 &&
908 (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
909 // The section consists of a number of subsection in the following format:
910 // |SubSectionType|SubSectionSize|Contents...|
911 uint32_t SubType, SubSectionSize;
912 error(Reader.readInteger(SubType));
913 error(Reader.readInteger(SubSectionSize));
916 error(Reader.readFixedString(Contents, SubSectionSize));
918 BinaryStreamRef ST(Contents, support::little);
919 switch (DebugSubsectionKind(SubType)) {
920 case DebugSubsectionKind::FileChecksums:
921 error(CVFileChecksumTable.initialize(ST));
923 case DebugSubsectionKind::StringTable:
924 error(CVStringTable.initialize(ST));
930 uint32_t PaddedSize = alignTo(SubSectionSize, 4);
931 error(Reader.skip(PaddedSize - SubSectionSize));
935 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
936 const SectionRef &Section) {
937 StringRef SectionContents;
938 error(Section.getContents(SectionContents));
939 StringRef Data = SectionContents;
941 SmallVector<StringRef, 10> FunctionNames;
942 StringMap<StringRef> FunctionLineTables;
944 ListScope D(W, "CodeViewDebugInfo");
945 // Print the section to allow correlation with printSections.
946 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
949 error(consume(Data, Magic));
950 W.printHex("Magic", Magic);
951 if (Magic != COFF::DEBUG_SECTION_MAGIC)
952 return error(object_error::parse_failed);
954 BinaryStreamReader FSReader(Data, support::little);
955 initializeFileAndStringTables(FSReader);
957 // TODO: Convert this over to using ModuleSubstreamVisitor.
958 while (!Data.empty()) {
959 // The section consists of a number of subsection in the following format:
960 // |SubSectionType|SubSectionSize|Contents...|
961 uint32_t SubType, SubSectionSize;
962 error(consume(Data, SubType));
963 error(consume(Data, SubSectionSize));
965 ListScope S(W, "Subsection");
966 W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
967 W.printHex("SubSectionSize", SubSectionSize);
969 // Get the contents of the subsection.
970 if (SubSectionSize > Data.size())
971 return error(object_error::parse_failed);
972 StringRef Contents = Data.substr(0, SubSectionSize);
974 // Add SubSectionSize to the current offset and align that offset to find
975 // the next subsection.
976 size_t SectionOffset = Data.data() - SectionContents.data();
977 size_t NextOffset = SectionOffset + SubSectionSize;
978 NextOffset = alignTo(NextOffset, 4);
979 if (NextOffset > SectionContents.size())
980 return error(object_error::parse_failed);
981 Data = SectionContents.drop_front(NextOffset);
983 // Optionally print the subsection bytes in case our parsing gets confused
985 if (opts::CodeViewSubsectionBytes)
986 printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
989 switch (DebugSubsectionKind(SubType)) {
990 case DebugSubsectionKind::Symbols:
991 printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
994 case DebugSubsectionKind::InlineeLines:
995 printCodeViewInlineeLines(Contents);
998 case DebugSubsectionKind::FileChecksums:
999 printCodeViewFileChecksums(Contents);
1002 case DebugSubsectionKind::Lines: {
1003 // Holds a PC to file:line table. Some data to parse this subsection is
1004 // stored in the other subsections, so just check sanity and store the
1005 // pointers for deferred processing.
1007 if (SubSectionSize < 12) {
1008 // There should be at least three words to store two function
1009 // relocations and size of the code.
1010 error(object_error::parse_failed);
1014 StringRef LinkageName;
1015 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
1017 W.printString("LinkageName", LinkageName);
1018 if (FunctionLineTables.count(LinkageName) != 0) {
1019 // Saw debug info for this function already?
1020 error(object_error::parse_failed);
1024 FunctionLineTables[LinkageName] = Contents;
1025 FunctionNames.push_back(LinkageName);
1028 case DebugSubsectionKind::FrameData: {
1029 // First four bytes is a relocation against the function.
1030 BinaryStreamReader SR(Contents, llvm::support::little);
1032 DebugFrameDataSubsectionRef FrameData;
1033 error(FrameData.initialize(SR));
1035 StringRef LinkageName;
1036 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1037 FrameData.getRelocPtr(), LinkageName));
1038 W.printString("LinkageName", LinkageName);
1040 // To find the active frame description, search this array for the
1041 // smallest PC range that includes the current PC.
1042 for (const auto &FD : FrameData) {
1043 StringRef FrameFunc = error(CVStringTable.getString(FD.FrameFunc));
1045 DictScope S(W, "FrameData");
1046 W.printHex("RvaStart", FD.RvaStart);
1047 W.printHex("CodeSize", FD.CodeSize);
1048 W.printHex("LocalSize", FD.LocalSize);
1049 W.printHex("ParamsSize", FD.ParamsSize);
1050 W.printHex("MaxStackSize", FD.MaxStackSize);
1051 W.printString("FrameFunc", FrameFunc);
1052 W.printHex("PrologSize", FD.PrologSize);
1053 W.printHex("SavedRegsSize", FD.SavedRegsSize);
1054 W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1059 // Do nothing for unrecognized subsections.
1066 // Dump the line tables now that we've read all the subsections and know all
1067 // the required information.
1068 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1069 StringRef Name = FunctionNames[I];
1070 ListScope S(W, "FunctionLineTable");
1071 W.printString("LinkageName", Name);
1073 BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1075 DebugLinesSubsectionRef LineInfo;
1076 error(LineInfo.initialize(Reader));
1078 W.printHex("Flags", LineInfo.header()->Flags);
1079 W.printHex("CodeSize", LineInfo.header()->CodeSize);
1080 for (const auto &Entry : LineInfo) {
1082 ListScope S(W, "FilenameSegment");
1083 printFileNameForOffset("Filename", Entry.NameIndex);
1084 uint32_t ColumnIndex = 0;
1085 for (const auto &Line : Entry.LineNumbers) {
1086 if (Line.Offset >= LineInfo.header()->CodeSize) {
1087 error(object_error::parse_failed);
1091 std::string PC = formatv("+{0:X}", uint32_t(Line.Offset));
1092 ListScope PCScope(W, PC);
1093 codeview::LineInfo LI(Line.Flags);
1095 if (LI.isAlwaysStepInto())
1096 W.printString("StepInto", StringRef("Always"));
1097 else if (LI.isNeverStepInto())
1098 W.printString("StepInto", StringRef("Never"));
1100 W.printNumber("LineNumberStart", LI.getStartLine());
1101 W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1102 W.printBoolean("IsStatement", LI.isStatement());
1103 if (LineInfo.hasColumnInfo()) {
1104 W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1105 W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1113 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1114 const SectionRef &Section,
1115 StringRef SectionContents) {
1116 ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1117 Subsection.bytes_end());
1118 auto CODD = llvm::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1120 CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1121 opts::CodeViewSubsectionBytes);
1122 CVSymbolArray Symbols;
1123 BinaryStreamReader Reader(BinaryData, llvm::support::little);
1124 if (auto EC = Reader.readArray(Symbols, Reader.getLength())) {
1125 consumeError(std::move(EC));
1127 error(object_error::parse_failed);
1130 if (auto EC = CVSD.dump(Symbols)) {
1132 error(std::move(EC));
1137 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1138 BinaryStreamRef Stream(Subsection, llvm::support::little);
1139 DebugChecksumsSubsectionRef Checksums;
1140 error(Checksums.initialize(Stream));
1142 for (auto &FC : Checksums) {
1143 DictScope S(W, "FileChecksum");
1145 StringRef Filename = error(CVStringTable.getString(FC.FileNameOffset));
1146 W.printHex("Filename", Filename, FC.FileNameOffset);
1147 W.printHex("ChecksumSize", FC.Checksum.size());
1148 W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1149 makeArrayRef(FileChecksumKindNames));
1151 W.printBinary("ChecksumBytes", FC.Checksum);
1155 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1156 BinaryStreamReader SR(Subsection, llvm::support::little);
1157 DebugInlineeLinesSubsectionRef Lines;
1158 error(Lines.initialize(SR));
1160 for (auto &Line : Lines) {
1161 DictScope S(W, "InlineeSourceLine");
1162 printTypeIndex("Inlinee", Line.Header->Inlinee);
1163 printFileNameForOffset("FileID", Line.Header->FileID);
1164 W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1166 if (Lines.hasExtraFiles()) {
1167 W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1168 ListScope ExtraFiles(W, "ExtraFiles");
1169 for (const auto &FID : Line.ExtraFiles) {
1170 printFileNameForOffset("FileID", FID);
1176 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1177 // The file checksum subsection should precede all references to it.
1178 if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1179 error(object_error::parse_failed);
1181 auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1183 // Check if the file checksum table offset is valid.
1184 if (Iter == CVFileChecksumTable.end())
1185 error(object_error::parse_failed);
1187 return error(CVStringTable.getString(Iter->FileNameOffset));
1190 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1191 W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1194 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1195 MergingTypeTableBuilder &CVTypes) {
1196 for (const SectionRef &S : Obj->sections()) {
1197 StringRef SectionName;
1198 error(S.getName(SectionName));
1199 if (SectionName == ".debug$T") {
1201 error(S.getContents(Data));
1203 error(consume(Data, Magic));
1205 error(object_error::parse_failed);
1208 BinaryStreamReader Reader(Data, llvm::support::little);
1209 if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1210 consumeError(std::move(EC));
1212 error(object_error::parse_failed);
1214 SmallVector<TypeIndex, 128> SourceToDest;
1215 if (auto EC = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types))
1216 return error(std::move(EC));
1221 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1222 const SectionRef &Section) {
1223 ListScope D(W, "CodeViewTypes");
1224 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1227 error(Section.getContents(Data));
1228 if (opts::CodeViewSubsectionBytes)
1229 W.printBinaryBlock("Data", Data);
1232 error(consume(Data, Magic));
1233 W.printHex("Magic", Magic);
1234 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1235 return error(object_error::parse_failed);
1237 Types.reset(Data, 100);
1239 TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1240 error(codeview::visitTypeStream(Types, TDV));
1244 void COFFDumper::printSections() {
1245 ListScope SectionsD(W, "Sections");
1246 int SectionNumber = 0;
1247 for (const SectionRef &Sec : Obj->sections()) {
1249 const coff_section *Section = Obj->getCOFFSection(Sec);
1252 error(Sec.getName(Name));
1254 DictScope D(W, "Section");
1255 W.printNumber("Number", SectionNumber);
1256 W.printBinary("Name", Name, Section->Name);
1257 W.printHex ("VirtualSize", Section->VirtualSize);
1258 W.printHex ("VirtualAddress", Section->VirtualAddress);
1259 W.printNumber("RawDataSize", Section->SizeOfRawData);
1260 W.printHex ("PointerToRawData", Section->PointerToRawData);
1261 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
1262 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
1263 W.printNumber("RelocationCount", Section->NumberOfRelocations);
1264 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1265 W.printFlags ("Characteristics", Section->Characteristics,
1266 makeArrayRef(ImageSectionCharacteristics),
1267 COFF::SectionCharacteristics(0x00F00000));
1269 if (opts::SectionRelocations) {
1270 ListScope D(W, "Relocations");
1271 for (const RelocationRef &Reloc : Sec.relocations())
1272 printRelocation(Sec, Reloc);
1275 if (opts::SectionSymbols) {
1276 ListScope D(W, "Symbols");
1277 for (const SymbolRef &Symbol : Obj->symbols()) {
1278 if (!Sec.containsSymbol(Symbol))
1281 printSymbol(Symbol);
1285 if (opts::SectionData &&
1286 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1288 error(Sec.getContents(Data));
1290 W.printBinaryBlock("SectionData", Data);
1295 void COFFDumper::printRelocations() {
1296 ListScope D(W, "Relocations");
1298 int SectionNumber = 0;
1299 for (const SectionRef &Section : Obj->sections()) {
1302 error(Section.getName(Name));
1304 bool PrintedGroup = false;
1305 for (const RelocationRef &Reloc : Section.relocations()) {
1306 if (!PrintedGroup) {
1307 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1309 PrintedGroup = true;
1312 printRelocation(Section, Reloc);
1317 W.startLine() << "}\n";
1322 void COFFDumper::printRelocation(const SectionRef &Section,
1323 const RelocationRef &Reloc, uint64_t Bias) {
1324 uint64_t Offset = Reloc.getOffset() - Bias;
1325 uint64_t RelocType = Reloc.getType();
1326 SmallString<32> RelocName;
1327 StringRef SymbolName;
1328 Reloc.getTypeName(RelocName);
1329 symbol_iterator Symbol = Reloc.getSymbol();
1330 if (Symbol != Obj->symbol_end()) {
1331 Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1332 error(errorToErrorCode(SymbolNameOrErr.takeError()));
1333 SymbolName = *SymbolNameOrErr;
1336 if (opts::ExpandRelocs) {
1337 DictScope Group(W, "Relocation");
1338 W.printHex("Offset", Offset);
1339 W.printNumber("Type", RelocName, RelocType);
1340 W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1342 raw_ostream& OS = W.startLine();
1345 << " " << (SymbolName.empty() ? "-" : SymbolName)
1350 void COFFDumper::printSymbols() {
1351 ListScope Group(W, "Symbols");
1353 for (const SymbolRef &Symbol : Obj->symbols())
1354 printSymbol(Symbol);
1357 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1359 static ErrorOr<StringRef>
1360 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1361 const coff_section *Section) {
1363 StringRef SectionName;
1364 if (std::error_code EC = Obj->getSectionName(Section, SectionName))
1368 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1369 return StringRef("IMAGE_SYM_DEBUG");
1370 if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1371 return StringRef("IMAGE_SYM_ABSOLUTE");
1372 if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1373 return StringRef("IMAGE_SYM_UNDEFINED");
1374 return StringRef("");
1377 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1378 DictScope D(W, "Symbol");
1380 COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1381 const coff_section *Section;
1382 if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1383 W.startLine() << "Invalid section number: " << EC.message() << "\n";
1388 StringRef SymbolName;
1389 if (Obj->getSymbolName(Symbol, SymbolName))
1392 StringRef SectionName = "";
1393 ErrorOr<StringRef> Res =
1394 getSectionName(Obj, Symbol.getSectionNumber(), Section);
1398 W.printString("Name", SymbolName);
1399 W.printNumber("Value", Symbol.getValue());
1400 W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1401 W.printEnum ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1402 W.printEnum ("ComplexType", Symbol.getComplexType(),
1403 makeArrayRef(ImageSymDType));
1404 W.printEnum ("StorageClass", Symbol.getStorageClass(),
1405 makeArrayRef(ImageSymClass));
1406 W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1408 for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1409 if (Symbol.isFunctionDefinition()) {
1410 const coff_aux_function_definition *Aux;
1411 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1413 DictScope AS(W, "AuxFunctionDef");
1414 W.printNumber("TagIndex", Aux->TagIndex);
1415 W.printNumber("TotalSize", Aux->TotalSize);
1416 W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1417 W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1419 } else if (Symbol.isAnyUndefined()) {
1420 const coff_aux_weak_external *Aux;
1421 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1423 Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1424 StringRef LinkedName;
1425 std::error_code EC = errorToErrorCode(Linked.takeError());
1426 if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) {
1431 DictScope AS(W, "AuxWeakExternal");
1432 W.printNumber("Linked", LinkedName, Aux->TagIndex);
1433 W.printEnum ("Search", Aux->Characteristics,
1434 makeArrayRef(WeakExternalCharacteristics));
1436 } else if (Symbol.isFileRecord()) {
1437 const char *FileName;
1438 error(getSymbolAuxData(Obj, Symbol, I, FileName));
1440 DictScope AS(W, "AuxFileRecord");
1442 StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1443 Obj->getSymbolTableEntrySize());
1444 W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1446 } else if (Symbol.isSectionDefinition()) {
1447 const coff_aux_section_definition *Aux;
1448 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1450 int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1452 DictScope AS(W, "AuxSectionDef");
1453 W.printNumber("Length", Aux->Length);
1454 W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1455 W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1456 W.printHex("Checksum", Aux->CheckSum);
1457 W.printNumber("Number", AuxNumber);
1458 W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1460 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1461 && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1462 const coff_section *Assoc;
1463 StringRef AssocName = "";
1464 std::error_code EC = Obj->getSection(AuxNumber, Assoc);
1465 ErrorOr<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1469 EC = Res.getError();
1475 W.printNumber("AssocSection", AssocName, AuxNumber);
1477 } else if (Symbol.isCLRToken()) {
1478 const coff_aux_clr_token *Aux;
1479 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1481 Expected<COFFSymbolRef> ReferredSym =
1482 Obj->getSymbol(Aux->SymbolTableIndex);
1483 StringRef ReferredName;
1484 std::error_code EC = errorToErrorCode(ReferredSym.takeError());
1485 if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
1490 DictScope AS(W, "AuxCLRToken");
1491 W.printNumber("AuxType", Aux->AuxType);
1492 W.printNumber("Reserved", Aux->Reserved);
1493 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1496 W.startLine() << "<unhandled auxiliary record>\n";
1501 void COFFDumper::printUnwindInfo() {
1502 ListScope D(W, "UnwindInformation");
1503 switch (Obj->getMachine()) {
1504 case COFF::IMAGE_FILE_MACHINE_AMD64: {
1505 Win64EH::Dumper Dumper(W);
1506 Win64EH::Dumper::SymbolResolver
1507 Resolver = [](const object::coff_section *Section, uint64_t Offset,
1508 SymbolRef &Symbol, void *user_data) -> std::error_code {
1509 COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1510 return Dumper->resolveSymbol(Section, Offset, Symbol);
1512 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1513 Dumper.printData(Ctx);
1516 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1517 ARM::WinEH::Decoder Decoder(W);
1518 Decoder.dumpProcedureData(*Obj);
1522 W.printEnum("unsupported Image Machine", Obj->getMachine(),
1523 makeArrayRef(ImageFileMachineType));
1528 void COFFDumper::printNeededLibraries() {
1529 ListScope D(W, "NeededLibraries");
1531 using LibsTy = std::vector<StringRef>;
1534 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1536 if (!DirRef.getName(Name))
1537 Libs.push_back(Name);
1540 std::stable_sort(Libs.begin(), Libs.end());
1542 for (const auto &L : Libs) {
1543 outs() << " " << L << "\n";
1547 void COFFDumper::printImportedSymbols(
1548 iterator_range<imported_symbol_iterator> Range) {
1549 for (const ImportedSymbolRef &I : Range) {
1551 error(I.getSymbolName(Sym));
1553 error(I.getOrdinal(Ordinal));
1554 W.printNumber("Symbol", Sym, Ordinal);
1558 void COFFDumper::printDelayImportedSymbols(
1559 const DelayImportDirectoryEntryRef &I,
1560 iterator_range<imported_symbol_iterator> Range) {
1562 for (const ImportedSymbolRef &S : Range) {
1563 DictScope Import(W, "Import");
1565 error(S.getSymbolName(Sym));
1567 error(S.getOrdinal(Ordinal));
1568 W.printNumber("Symbol", Sym, Ordinal);
1570 error(I.getImportAddress(Index++, Addr));
1571 W.printHex("Address", Addr);
1575 void COFFDumper::printCOFFImports() {
1577 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1578 DictScope Import(W, "Import");
1580 error(I.getName(Name));
1581 W.printString("Name", Name);
1583 error(I.getImportLookupTableRVA(ILTAddr));
1584 W.printHex("ImportLookupTableRVA", ILTAddr);
1586 error(I.getImportAddressTableRVA(IATAddr));
1587 W.printHex("ImportAddressTableRVA", IATAddr);
1588 // The import lookup table can be missing with certain older linkers, so
1589 // fall back to the import address table in that case.
1591 printImportedSymbols(I.lookup_table_symbols());
1593 printImportedSymbols(I.imported_symbols());
1597 for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1598 DictScope Import(W, "DelayImport");
1600 error(I.getName(Name));
1601 W.printString("Name", Name);
1602 const delay_import_directory_table_entry *Table;
1603 error(I.getDelayImportTable(Table));
1604 W.printHex("Attributes", Table->Attributes);
1605 W.printHex("ModuleHandle", Table->ModuleHandle);
1606 W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1607 W.printHex("ImportNameTable", Table->DelayImportNameTable);
1608 W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1609 W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1610 printDelayImportedSymbols(I, I.imported_symbols());
1614 void COFFDumper::printCOFFExports() {
1615 for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1616 DictScope Export(W, "Export");
1619 uint32_t Ordinal, RVA;
1621 error(E.getSymbolName(Name));
1622 error(E.getOrdinal(Ordinal));
1623 error(E.getExportRVA(RVA));
1625 W.printNumber("Ordinal", Ordinal);
1626 W.printString("Name", Name);
1627 W.printHex("RVA", RVA);
1631 void COFFDumper::printCOFFDirectives() {
1632 for (const SectionRef &Section : Obj->sections()) {
1636 error(Section.getName(Name));
1637 if (Name != ".drectve")
1640 error(Section.getContents(Contents));
1642 W.printString("Directive(s)", Contents);
1646 static std::string getBaseRelocTypeName(uint8_t Type) {
1648 case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1649 case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1650 case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1651 case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1652 case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1653 case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1654 case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1655 default: return "unknown (" + llvm::utostr(Type) + ")";
1659 void COFFDumper::printCOFFBaseReloc() {
1660 ListScope D(W, "BaseReloc");
1661 for (const BaseRelocRef &I : Obj->base_relocs()) {
1664 error(I.getRVA(RVA));
1665 error(I.getType(Type));
1666 DictScope Import(W, "Entry");
1667 W.printString("Type", getBaseRelocTypeName(Type));
1668 W.printHex("Address", RVA);
1672 void COFFDumper::printCOFFResources() {
1673 ListScope ResourcesD(W, "Resources");
1674 for (const SectionRef &S : Obj->sections()) {
1676 error(S.getName(Name));
1677 if (!Name.startswith(".rsrc"))
1681 error(S.getContents(Ref));
1683 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1684 ResourceSectionRef RSF(Ref);
1685 auto &BaseTable = unwrapOrError(RSF.getBaseTable());
1686 W.printNumber("Total Number of Resources",
1687 countTotalTableEntries(RSF, BaseTable, "Type"));
1688 W.printHex("Base Table Address",
1689 Obj->getCOFFSection(S)->PointerToRawData);
1690 W.startLine() << "\n";
1691 printResourceDirectoryTable(RSF, BaseTable, "Type");
1693 if (opts::SectionData)
1694 W.printBinaryBlock(Name.str() + " Data", Ref);
1699 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1700 const coff_resource_dir_table &Table,
1702 uint32_t TotalEntries = 0;
1703 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1705 auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1706 if (Entry.Offset.isSubDir()) {
1707 StringRef NextLevel;
1708 if (Level == "Name")
1709 NextLevel = "Language";
1712 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1713 TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1718 return TotalEntries;
1721 void COFFDumper::printResourceDirectoryTable(
1722 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1725 W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1726 W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1728 // Iterate through level in resource directory tree.
1729 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1731 auto Entry = unwrapOrError(getResourceDirectoryTableEntry(Table, i));
1733 SmallString<20> IDStr;
1734 raw_svector_ostream OS(IDStr);
1735 if (i < Table.NumberOfNameEntries) {
1736 ArrayRef<UTF16> RawEntryNameString = unwrapOrError(RSF.getEntryNameString(Entry));
1737 std::vector<UTF16> EndianCorrectedNameString;
1738 if (llvm::sys::IsBigEndianHost) {
1739 EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1740 std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1741 EndianCorrectedNameString.begin() + 1);
1742 EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1743 RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1745 std::string EntryNameString;
1746 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1747 error(object_error::parse_failed);
1749 OS << EntryNameString;
1751 if (Level == "Type") {
1752 ScopedPrinter Printer(OS);
1753 Printer.printEnum("", Entry.Identifier.ID,
1754 makeArrayRef(ResourceTypeNames));
1755 IDStr = IDStr.slice(0, IDStr.find_first_of(")", 0) + 1);
1757 OS << ": (ID " << Entry.Identifier.ID << ")";
1760 Name = StringRef(IDStr);
1761 ListScope ResourceType(W, Level.str() + Name.str());
1762 if (Entry.Offset.isSubDir()) {
1763 W.printHex("Table Offset", Entry.Offset.value());
1764 StringRef NextLevel;
1765 if (Level == "Name")
1766 NextLevel = "Language";
1769 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1770 printResourceDirectoryTable(RSF, NextTable, NextLevel);
1772 W.printHex("Entry Offset", Entry.Offset.value());
1773 char FormattedTime[20] = {};
1774 time_t TDS = time_t(Table.TimeDateStamp);
1775 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1776 W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1777 W.printNumber("Major Version", Table.MajorVersion);
1778 W.printNumber("Minor Version", Table.MinorVersion);
1779 W.printNumber("Characteristics", Table.Characteristics);
1784 ErrorOr<const coff_resource_dir_entry &>
1785 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
1787 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1788 return object_error::parse_failed;
1789 auto TablePtr = reinterpret_cast<const coff_resource_dir_entry *>(&Table + 1);
1790 return TablePtr[Index];
1793 void COFFDumper::printStackMap() const {
1794 object::SectionRef StackMapSection;
1795 for (auto Sec : Obj->sections()) {
1798 if (Name == ".llvm_stackmaps") {
1799 StackMapSection = Sec;
1804 if (StackMapSection == object::SectionRef())
1807 StringRef StackMapContents;
1808 StackMapSection.getContents(StackMapContents);
1809 ArrayRef<uint8_t> StackMapContentsArray(
1810 reinterpret_cast<const uint8_t*>(StackMapContents.data()),
1811 StackMapContents.size());
1813 if (Obj->isLittleEndian())
1814 prettyPrintStackMap(
1816 StackMapV2Parser<support::little>(StackMapContentsArray));
1818 prettyPrintStackMap(llvm::outs(),
1819 StackMapV2Parser<support::big>(StackMapContentsArray));
1822 void llvm::dumpCodeViewMergedTypes(
1823 ScopedPrinter &Writer, llvm::codeview::MergingTypeTableBuilder &IDTable,
1824 llvm::codeview::MergingTypeTableBuilder &CVTypes) {
1825 // Flatten it first, then run our dumper on it.
1826 SmallString<0> TypeBuf;
1827 CVTypes.ForEachRecord([&](TypeIndex TI, const CVType &Record) {
1828 TypeBuf.append(Record.RecordData.begin(), Record.RecordData.end());
1831 TypeTableCollection TpiTypes(CVTypes.records());
1833 ListScope S(Writer, "MergedTypeStream");
1834 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1835 error(codeview::visitTypeStream(TpiTypes, TDV));
1839 // Flatten the id stream and print it next. The ID stream refers to names from
1841 TypeTableCollection IpiTypes(IDTable.records());
1843 ListScope S(Writer, "MergedIDStream");
1844 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1845 TDV.setIpiTypes(IpiTypes);
1846 error(codeview::visitTypeStream(IpiTypes, TDV));