[llvm-readobj] - Remove unwrapOrError(ErrorOr<T> EO) helper.
[llvm-complete.git] / tools / llvm-readobj / COFFDumper.cpp
blob3f61edcb97c89730c059f8107bea9d30e88df5af
1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the COFF-specific dumper for llvm-readobj.
11 ///
12 //===----------------------------------------------------------------------===//
14 #include "ARMWinEHPrinter.h"
15 #include "Error.h"
16 #include "ObjDumper.h"
17 #include "StackMapPrinter.h"
18 #include "Win64EHDumper.h"
19 #include "llvm-readobj.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/BinaryFormat/COFF.h"
24 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
25 #include "llvm/DebugInfo/CodeView/CodeView.h"
26 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
31 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
32 #include "llvm/DebugInfo/CodeView/Line.h"
33 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
34 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
37 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
38 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
39 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
40 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
41 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
42 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
43 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
44 #include "llvm/Object/COFF.h"
45 #include "llvm/Object/ObjectFile.h"
46 #include "llvm/Object/WindowsResource.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/LEB128.h"
53 #include "llvm/Support/ScopedPrinter.h"
54 #include "llvm/Support/Win64EH.h"
55 #include "llvm/Support/raw_ostream.h"
57 using namespace llvm;
58 using namespace llvm::object;
59 using namespace llvm::codeview;
60 using namespace llvm::support;
61 using namespace llvm::Win64EH;
63 static inline Error createError(const Twine &Err) {
64 return make_error<StringError>(Err, object_error::parse_failed);
67 namespace {
69 struct LoadConfigTables {
70 uint64_t SEHTableVA = 0;
71 uint64_t SEHTableCount = 0;
72 uint32_t GuardFlags = 0;
73 uint64_t GuardFidTableVA = 0;
74 uint64_t GuardFidTableCount = 0;
75 uint64_t GuardLJmpTableVA = 0;
76 uint64_t GuardLJmpTableCount = 0;
79 class COFFDumper : public ObjDumper {
80 public:
81 friend class COFFObjectDumpDelegate;
82 COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
83 : ObjDumper(Writer), Obj(Obj), Writer(Writer), Types(100) {}
85 void printFileHeaders() override;
86 void printSectionHeaders() override;
87 void printRelocations() override;
88 void printUnwindInfo() override;
90 void printNeededLibraries() override;
92 void printCOFFImports() override;
93 void printCOFFExports() override;
94 void printCOFFDirectives() override;
95 void printCOFFBaseReloc() override;
96 void printCOFFDebugDirectory() override;
97 void printCOFFResources() override;
98 void printCOFFLoadConfig() override;
99 void printCodeViewDebugInfo() override;
100 void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
101 llvm::codeview::MergingTypeTableBuilder &CVTypes,
102 llvm::codeview::GlobalTypeTableBuilder &GlobalCVIDs,
103 llvm::codeview::GlobalTypeTableBuilder &GlobalCVTypes,
104 bool GHash) override;
105 void printStackMap() const override;
106 void printAddrsig() override;
107 private:
108 void printSymbols() override;
109 void printDynamicSymbols() override;
110 void printSymbol(const SymbolRef &Sym);
111 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
112 uint64_t Bias = 0);
113 void printDataDirectory(uint32_t Index, const std::string &FieldName);
115 void printDOSHeader(const dos_header *DH);
116 template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
117 void printBaseOfDataField(const pe32_header *Hdr);
118 void printBaseOfDataField(const pe32plus_header *Hdr);
119 template <typename T>
120 void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
121 typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
122 void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
123 PrintExtraCB PrintExtra = 0);
125 void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
126 void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
127 StringRef getTypeName(TypeIndex Ty);
128 StringRef getFileNameForFileOffset(uint32_t FileOffset);
129 void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
130 void printTypeIndex(StringRef FieldName, TypeIndex TI) {
131 // Forward to CVTypeDumper for simplicity.
132 codeview::printTypeIndex(Writer, FieldName, TI, Types);
135 void printCodeViewSymbolsSubsection(StringRef Subsection,
136 const SectionRef &Section,
137 StringRef SectionContents);
139 void printCodeViewFileChecksums(StringRef Subsection);
141 void printCodeViewInlineeLines(StringRef Subsection);
143 void printRelocatedField(StringRef Label, const coff_section *Sec,
144 uint32_t RelocOffset, uint32_t Offset,
145 StringRef *RelocSym = nullptr);
147 uint32_t countTotalTableEntries(ResourceSectionRef RSF,
148 const coff_resource_dir_table &Table,
149 StringRef Level);
151 void printResourceDirectoryTable(ResourceSectionRef RSF,
152 const coff_resource_dir_table &Table,
153 StringRef Level);
155 void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
156 StringRef SectionContents, StringRef Block);
158 /// Given a .debug$S section, find the string table and file checksum table.
159 void initializeFileAndStringTables(BinaryStreamReader &Reader);
161 void cacheRelocations();
163 std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
164 SymbolRef &Sym);
165 std::error_code resolveSymbolName(const coff_section *Section,
166 uint64_t Offset, StringRef &Name);
167 std::error_code resolveSymbolName(const coff_section *Section,
168 StringRef SectionContents,
169 const void *RelocPtr, StringRef &Name);
170 void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
171 void printDelayImportedSymbols(
172 const DelayImportDirectoryEntryRef &I,
173 iterator_range<imported_symbol_iterator> Range);
174 Expected<const coff_resource_dir_entry &>
175 getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
176 uint32_t Index);
178 typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
180 const llvm::object::COFFObjectFile *Obj;
181 bool RelocCached = false;
182 RelocMapTy RelocMap;
184 DebugChecksumsSubsectionRef CVFileChecksumTable;
186 DebugStringTableSubsectionRef CVStringTable;
188 /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
189 /// first, but if we don't see one, just assume an X64 CPU type. It is common.
190 CPUType CompilationCPUType = CPUType::X64;
192 ScopedPrinter &Writer;
193 BinaryByteStream TypeContents;
194 LazyRandomTypeCollection Types;
197 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
198 public:
199 COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
200 const COFFObjectFile *Obj, StringRef SectionContents)
201 : CD(CD), SR(SR), SectionContents(SectionContents) {
202 Sec = Obj->getCOFFSection(SR);
205 uint32_t getRecordOffset(BinaryStreamReader Reader) override {
206 ArrayRef<uint8_t> Data;
207 if (auto EC = Reader.readLongestContiguousChunk(Data)) {
208 llvm::consumeError(std::move(EC));
209 return 0;
211 return Data.data() - SectionContents.bytes_begin();
214 void printRelocatedField(StringRef Label, uint32_t RelocOffset,
215 uint32_t Offset, StringRef *RelocSym) override {
216 CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
219 void printBinaryBlockWithRelocs(StringRef Label,
220 ArrayRef<uint8_t> Block) override {
221 StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
222 Block.size());
223 if (opts::CodeViewSubsectionBytes)
224 CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
227 StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
228 return CD.getFileNameForFileOffset(FileOffset);
231 DebugStringTableSubsectionRef getStringTable() override {
232 return CD.CVStringTable;
235 private:
236 COFFDumper &CD;
237 const SectionRef &SR;
238 const coff_section *Sec;
239 StringRef SectionContents;
242 } // end namespace
244 namespace llvm {
246 std::error_code createCOFFDumper(const object::ObjectFile *Obj,
247 ScopedPrinter &Writer,
248 std::unique_ptr<ObjDumper> &Result) {
249 const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
250 if (!COFFObj)
251 return readobj_error::unsupported_obj_file_format;
253 Result.reset(new COFFDumper(COFFObj, Writer));
254 return readobj_error::success;
257 } // namespace llvm
259 // Given a section and an offset into this section the function returns the
260 // symbol used for the relocation at the offset.
261 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
262 uint64_t Offset, SymbolRef &Sym) {
263 cacheRelocations();
264 const auto &Relocations = RelocMap[Section];
265 auto SymI = Obj->symbol_end();
266 for (const auto &Relocation : Relocations) {
267 uint64_t RelocationOffset = Relocation.getOffset();
269 if (RelocationOffset == Offset) {
270 SymI = Relocation.getSymbol();
271 break;
274 if (SymI == Obj->symbol_end())
275 return readobj_error::unknown_symbol;
276 Sym = *SymI;
277 return readobj_error::success;
280 // Given a section and an offset into this section the function returns the name
281 // of the symbol used for the relocation at the offset.
282 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
283 uint64_t Offset,
284 StringRef &Name) {
285 SymbolRef Symbol;
286 if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
287 return EC;
288 Expected<StringRef> NameOrErr = Symbol.getName();
289 if (!NameOrErr)
290 return errorToErrorCode(NameOrErr.takeError());
291 Name = *NameOrErr;
292 return std::error_code();
295 // Helper for when you have a pointer to real data and you want to know about
296 // relocations against it.
297 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
298 StringRef SectionContents,
299 const void *RelocPtr,
300 StringRef &Name) {
301 assert(SectionContents.data() < RelocPtr &&
302 RelocPtr < SectionContents.data() + SectionContents.size() &&
303 "pointer to relocated object is not in section");
304 uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
305 SectionContents.data());
306 return resolveSymbolName(Section, Offset, Name);
309 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
310 uint32_t RelocOffset, uint32_t Offset,
311 StringRef *RelocSym) {
312 StringRef SymStorage;
313 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
314 if (!resolveSymbolName(Sec, RelocOffset, Symbol))
315 W.printSymbolOffset(Label, Symbol, Offset);
316 else
317 W.printHex(Label, RelocOffset);
320 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
321 const SectionRef &Sec,
322 StringRef SectionContents,
323 StringRef Block) {
324 W.printBinaryBlock(Label, Block);
326 assert(SectionContents.begin() < Block.begin() &&
327 SectionContents.end() >= Block.end() &&
328 "Block is not contained in SectionContents");
329 uint64_t OffsetStart = Block.data() - SectionContents.data();
330 uint64_t OffsetEnd = OffsetStart + Block.size();
332 W.flush();
333 cacheRelocations();
334 ListScope D(W, "BlockRelocations");
335 const coff_section *Section = Obj->getCOFFSection(Sec);
336 const auto &Relocations = RelocMap[Section];
337 for (const auto &Relocation : Relocations) {
338 uint64_t RelocationOffset = Relocation.getOffset();
339 if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
340 printRelocation(Sec, Relocation, OffsetStart);
344 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
345 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
346 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
347 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
348 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
349 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64 ),
350 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
351 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
352 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
353 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
354 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
355 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
356 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
357 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
358 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
359 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
360 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
361 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
362 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
363 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
364 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
365 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
366 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
369 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
370 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
371 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
372 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
373 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
374 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
375 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
376 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
377 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
378 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
379 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
380 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
381 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
382 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
383 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
384 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
387 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
388 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
389 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
390 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
391 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
392 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
393 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
394 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
395 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
396 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
397 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
398 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
401 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
402 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
403 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
404 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
405 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
406 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
407 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
408 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
409 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER ),
410 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
411 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF ),
412 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
415 static const EnumEntry<COFF::SectionCharacteristics>
416 ImageSectionCharacteristics[] = {
417 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD ),
418 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
419 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
420 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
421 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
422 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
423 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
424 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
425 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
426 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
427 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
428 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
429 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
430 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
431 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
432 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
433 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
434 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
435 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
436 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
437 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
438 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
439 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
440 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
441 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
442 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
443 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
444 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
445 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
446 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
447 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
448 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
449 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
450 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
451 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
452 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
455 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
456 { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
457 { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
458 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
459 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
460 { "Int" , COFF::IMAGE_SYM_TYPE_INT },
461 { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
462 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
463 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
464 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
465 { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
466 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
467 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
468 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
469 { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
470 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
471 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
474 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
475 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
476 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
477 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
478 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
481 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
482 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
483 { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
484 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
485 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
486 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
487 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
488 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
489 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
490 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
491 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
492 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
493 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
494 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
495 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
496 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
497 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
498 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
499 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
500 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
501 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
502 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
503 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
504 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
505 { "File" , COFF::IMAGE_SYM_CLASS_FILE },
506 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
507 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
508 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
511 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
512 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
513 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
514 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
515 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
516 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
517 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
518 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
521 static const EnumEntry<COFF::DebugType> ImageDebugType[] = {
522 { "Unknown" , COFF::IMAGE_DEBUG_TYPE_UNKNOWN },
523 { "COFF" , COFF::IMAGE_DEBUG_TYPE_COFF },
524 { "CodeView" , COFF::IMAGE_DEBUG_TYPE_CODEVIEW },
525 { "FPO" , COFF::IMAGE_DEBUG_TYPE_FPO },
526 { "Misc" , COFF::IMAGE_DEBUG_TYPE_MISC },
527 { "Exception" , COFF::IMAGE_DEBUG_TYPE_EXCEPTION },
528 { "Fixup" , COFF::IMAGE_DEBUG_TYPE_FIXUP },
529 { "OmapToSrc" , COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC },
530 { "OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC },
531 { "Borland" , COFF::IMAGE_DEBUG_TYPE_BORLAND },
532 { "Reserved10" , COFF::IMAGE_DEBUG_TYPE_RESERVED10 },
533 { "CLSID" , COFF::IMAGE_DEBUG_TYPE_CLSID },
534 { "VCFeature" , COFF::IMAGE_DEBUG_TYPE_VC_FEATURE },
535 { "POGO" , COFF::IMAGE_DEBUG_TYPE_POGO },
536 { "ILTCG" , COFF::IMAGE_DEBUG_TYPE_ILTCG },
537 { "MPX" , COFF::IMAGE_DEBUG_TYPE_MPX },
538 { "Repro" , COFF::IMAGE_DEBUG_TYPE_REPRO },
541 static const EnumEntry<COFF::WeakExternalCharacteristics>
542 WeakExternalCharacteristics[] = {
543 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
544 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
545 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
548 static const EnumEntry<uint32_t> SubSectionTypes[] = {
549 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
550 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
551 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
552 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
553 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
554 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
555 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
556 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
557 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
558 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
559 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
560 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
561 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
564 static const EnumEntry<uint32_t> FrameDataFlags[] = {
565 LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
566 LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
567 LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
570 static const EnumEntry<uint8_t> FileChecksumKindNames[] = {
571 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
572 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
573 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
574 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
577 template <typename T>
578 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
579 COFFSymbolRef Symbol,
580 uint8_t AuxSymbolIdx, const T *&Aux) {
581 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
582 AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
583 Aux = reinterpret_cast<const T*>(AuxData.data());
584 return readobj_error::success;
587 void COFFDumper::cacheRelocations() {
588 if (RelocCached)
589 return;
590 RelocCached = true;
592 for (const SectionRef &S : Obj->sections()) {
593 const coff_section *Section = Obj->getCOFFSection(S);
595 for (const RelocationRef &Reloc : S.relocations())
596 RelocMap[Section].push_back(Reloc);
598 // Sort relocations by address.
599 llvm::sort(RelocMap[Section], [](RelocationRef L, RelocationRef R) {
600 return L.getOffset() < R.getOffset();
605 void COFFDumper::printDataDirectory(uint32_t Index,
606 const std::string &FieldName) {
607 const data_directory *Data;
608 if (Obj->getDataDirectory(Index, Data))
609 return;
610 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
611 W.printHex(FieldName + "Size", Data->Size);
614 void COFFDumper::printFileHeaders() {
615 time_t TDS = Obj->getTimeDateStamp();
616 char FormattedTime[20] = { };
617 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
620 DictScope D(W, "ImageFileHeader");
621 W.printEnum ("Machine", Obj->getMachine(),
622 makeArrayRef(ImageFileMachineType));
623 W.printNumber("SectionCount", Obj->getNumberOfSections());
624 W.printHex ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
625 W.printHex ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
626 W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
627 W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
628 W.printFlags ("Characteristics", Obj->getCharacteristics(),
629 makeArrayRef(ImageFileCharacteristics));
632 // Print PE header. This header does not exist if this is an object file and
633 // not an executable.
634 const pe32_header *PEHeader = nullptr;
635 error(Obj->getPE32Header(PEHeader));
636 if (PEHeader)
637 printPEHeader<pe32_header>(PEHeader);
639 const pe32plus_header *PEPlusHeader = nullptr;
640 error(Obj->getPE32PlusHeader(PEPlusHeader));
641 if (PEPlusHeader)
642 printPEHeader<pe32plus_header>(PEPlusHeader);
644 if (const dos_header *DH = Obj->getDOSHeader())
645 printDOSHeader(DH);
648 void COFFDumper::printDOSHeader(const dos_header *DH) {
649 DictScope D(W, "DOSHeader");
650 W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
651 W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
652 W.printNumber("FileSizeInPages", DH->FileSizeInPages);
653 W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
654 W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
655 W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
656 W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
657 W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
658 W.printNumber("InitialSP", DH->InitialSP);
659 W.printNumber("Checksum", DH->Checksum);
660 W.printNumber("InitialIP", DH->InitialIP);
661 W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
662 W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
663 W.printNumber("OverlayNumber", DH->OverlayNumber);
664 W.printNumber("OEMid", DH->OEMid);
665 W.printNumber("OEMinfo", DH->OEMinfo);
666 W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
669 template <class PEHeader>
670 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
671 DictScope D(W, "ImageOptionalHeader");
672 W.printHex ("Magic", Hdr->Magic);
673 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
674 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
675 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
676 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
677 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
678 W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
679 W.printHex ("BaseOfCode", Hdr->BaseOfCode);
680 printBaseOfDataField(Hdr);
681 W.printHex ("ImageBase", Hdr->ImageBase);
682 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
683 W.printNumber("FileAlignment", Hdr->FileAlignment);
684 W.printNumber("MajorOperatingSystemVersion",
685 Hdr->MajorOperatingSystemVersion);
686 W.printNumber("MinorOperatingSystemVersion",
687 Hdr->MinorOperatingSystemVersion);
688 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
689 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
690 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
691 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
692 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
693 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
694 W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
695 W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
696 makeArrayRef(PEDLLCharacteristics));
697 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
698 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
699 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
700 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
701 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
703 if (Hdr->NumberOfRvaAndSize > 0) {
704 DictScope D(W, "DataDirectory");
705 static const char * const directory[] = {
706 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
707 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
708 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
709 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
712 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
713 printDataDirectory(i, directory[i]);
717 void COFFDumper::printCOFFDebugDirectory() {
718 ListScope LS(W, "DebugDirectory");
719 for (const debug_directory &D : Obj->debug_directories()) {
720 char FormattedTime[20] = {};
721 time_t TDS = D.TimeDateStamp;
722 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
723 DictScope S(W, "DebugEntry");
724 W.printHex("Characteristics", D.Characteristics);
725 W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
726 W.printHex("MajorVersion", D.MajorVersion);
727 W.printHex("MinorVersion", D.MinorVersion);
728 W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
729 W.printHex("SizeOfData", D.SizeOfData);
730 W.printHex("AddressOfRawData", D.AddressOfRawData);
731 W.printHex("PointerToRawData", D.PointerToRawData);
732 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
733 const codeview::DebugInfo *DebugInfo;
734 StringRef PDBFileName;
735 error(Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName));
736 DictScope PDBScope(W, "PDBInfo");
737 W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
738 if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
739 W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
740 W.printNumber("PDBAge", DebugInfo->PDB70.Age);
741 W.printString("PDBFileName", PDBFileName);
743 } else if (D.SizeOfData != 0) {
744 // FIXME: Type values of 12 and 13 are commonly observed but are not in
745 // the documented type enum. Figure out what they mean.
746 ArrayRef<uint8_t> RawData;
747 error(
748 Obj->getRvaAndSizeAsBytes(D.AddressOfRawData, D.SizeOfData, RawData));
749 W.printBinaryBlock("RawData", RawData);
754 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
755 uint64_t EntrySize, PrintExtraCB PrintExtra) {
756 uintptr_t TableStart, TableEnd;
757 error(Obj->getVaPtr(TableVA, TableStart));
758 error(Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd));
759 TableEnd++;
760 for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
761 uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
762 raw_ostream &OS = W.startLine();
763 OS << W.hex(Obj->getImageBase() + RVA);
764 if (PrintExtra)
765 PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
766 OS << '\n';
770 void COFFDumper::printCOFFLoadConfig() {
771 LoadConfigTables Tables;
772 if (Obj->is64())
773 printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
774 else
775 printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
777 if (Tables.SEHTableVA) {
778 ListScope LS(W, "SEHTable");
779 printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
782 if (Tables.GuardFidTableVA) {
783 ListScope LS(W, "GuardFidTable");
784 if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
785 auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
786 uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
787 if (Flags)
788 OS << " flags " << utohexstr(Flags);
790 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
791 PrintGuardFlags);
792 } else {
793 printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
797 if (Tables.GuardLJmpTableVA) {
798 ListScope LS(W, "GuardLJmpTable");
799 printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
803 template <typename T>
804 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
805 if (!Conf)
806 return;
808 ListScope LS(W, "LoadConfig");
809 char FormattedTime[20] = {};
810 time_t TDS = Conf->TimeDateStamp;
811 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
812 W.printHex("Size", Conf->Size);
814 // Print everything before SecurityCookie. The vast majority of images today
815 // have all these fields.
816 if (Conf->Size < offsetof(T, SEHandlerTable))
817 return;
818 W.printHex("TimeDateStamp", FormattedTime, TDS);
819 W.printHex("MajorVersion", Conf->MajorVersion);
820 W.printHex("MinorVersion", Conf->MinorVersion);
821 W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
822 W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
823 W.printHex("CriticalSectionDefaultTimeout",
824 Conf->CriticalSectionDefaultTimeout);
825 W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
826 W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
827 W.printHex("LockPrefixTable", Conf->LockPrefixTable);
828 W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
829 W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
830 W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
831 W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
832 W.printHex("CSDVersion", Conf->CSDVersion);
833 W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
834 W.printHex("EditList", Conf->EditList);
835 W.printHex("SecurityCookie", Conf->SecurityCookie);
837 // Print the safe SEH table if present.
838 if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
839 return;
840 W.printHex("SEHandlerTable", Conf->SEHandlerTable);
841 W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
843 Tables.SEHTableVA = Conf->SEHandlerTable;
844 Tables.SEHTableCount = Conf->SEHandlerCount;
846 // Print everything before CodeIntegrity. (2015)
847 if (Conf->Size < offsetof(T, CodeIntegrity))
848 return;
849 W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
850 W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
851 W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
852 W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
853 W.printHex("GuardFlags", Conf->GuardFlags);
855 Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
856 Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
857 Tables.GuardFlags = Conf->GuardFlags;
859 // Print the rest. (2017)
860 if (Conf->Size < sizeof(T))
861 return;
862 W.printHex("GuardAddressTakenIatEntryTable",
863 Conf->GuardAddressTakenIatEntryTable);
864 W.printNumber("GuardAddressTakenIatEntryCount",
865 Conf->GuardAddressTakenIatEntryCount);
866 W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
867 W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
868 W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
869 W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
870 W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
871 W.printHex("GuardRFFailureRoutineFunctionPointer",
872 Conf->GuardRFFailureRoutineFunctionPointer);
873 W.printHex("DynamicValueRelocTableOffset",
874 Conf->DynamicValueRelocTableOffset);
875 W.printNumber("DynamicValueRelocTableSection",
876 Conf->DynamicValueRelocTableSection);
877 W.printHex("GuardRFVerifyStackPointerFunctionPointer",
878 Conf->GuardRFVerifyStackPointerFunctionPointer);
879 W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
881 Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
882 Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
885 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
886 W.printHex("BaseOfData", Hdr->BaseOfData);
889 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
891 void COFFDumper::printCodeViewDebugInfo() {
892 // Print types first to build CVUDTNames, then print symbols.
893 for (const SectionRef &S : Obj->sections()) {
894 StringRef SectionName;
895 error(S.getName(SectionName));
896 // .debug$T is a standard CodeView type section, while .debug$P is the same
897 // format but used for MSVC precompiled header object files.
898 if (SectionName == ".debug$T" || SectionName == ".debug$P")
899 printCodeViewTypeSection(SectionName, S);
901 for (const SectionRef &S : Obj->sections()) {
902 StringRef SectionName;
903 error(S.getName(SectionName));
904 if (SectionName == ".debug$S")
905 printCodeViewSymbolSection(SectionName, S);
909 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
910 while (Reader.bytesRemaining() > 0 &&
911 (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
912 // The section consists of a number of subsection in the following format:
913 // |SubSectionType|SubSectionSize|Contents...|
914 uint32_t SubType, SubSectionSize;
915 error(Reader.readInteger(SubType));
916 error(Reader.readInteger(SubSectionSize));
918 StringRef Contents;
919 error(Reader.readFixedString(Contents, SubSectionSize));
921 BinaryStreamRef ST(Contents, support::little);
922 switch (DebugSubsectionKind(SubType)) {
923 case DebugSubsectionKind::FileChecksums:
924 error(CVFileChecksumTable.initialize(ST));
925 break;
926 case DebugSubsectionKind::StringTable:
927 error(CVStringTable.initialize(ST));
928 break;
929 default:
930 break;
933 uint32_t PaddedSize = alignTo(SubSectionSize, 4);
934 error(Reader.skip(PaddedSize - SubSectionSize));
938 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
939 const SectionRef &Section) {
940 StringRef SectionContents = unwrapOrError(Section.getContents());
941 StringRef Data = SectionContents;
943 SmallVector<StringRef, 10> FunctionNames;
944 StringMap<StringRef> FunctionLineTables;
946 ListScope D(W, "CodeViewDebugInfo");
947 // Print the section to allow correlation with printSectionHeaders.
948 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
950 uint32_t Magic;
951 error(consume(Data, Magic));
952 W.printHex("Magic", Magic);
953 if (Magic != COFF::DEBUG_SECTION_MAGIC)
954 return error(object_error::parse_failed);
956 BinaryStreamReader FSReader(Data, support::little);
957 initializeFileAndStringTables(FSReader);
959 // TODO: Convert this over to using ModuleSubstreamVisitor.
960 while (!Data.empty()) {
961 // The section consists of a number of subsection in the following format:
962 // |SubSectionType|SubSectionSize|Contents...|
963 uint32_t SubType, SubSectionSize;
964 error(consume(Data, SubType));
965 error(consume(Data, SubSectionSize));
967 ListScope S(W, "Subsection");
968 // Dump the subsection as normal even if the ignore bit is set.
969 if (SubType & SubsectionIgnoreFlag) {
970 W.printHex("IgnoredSubsectionKind", SubType);
971 SubType &= ~SubsectionIgnoreFlag;
973 W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
974 W.printHex("SubSectionSize", SubSectionSize);
976 // Get the contents of the subsection.
977 if (SubSectionSize > Data.size())
978 return error(object_error::parse_failed);
979 StringRef Contents = Data.substr(0, SubSectionSize);
981 // Add SubSectionSize to the current offset and align that offset to find
982 // the next subsection.
983 size_t SectionOffset = Data.data() - SectionContents.data();
984 size_t NextOffset = SectionOffset + SubSectionSize;
985 NextOffset = alignTo(NextOffset, 4);
986 if (NextOffset > SectionContents.size())
987 return error(object_error::parse_failed);
988 Data = SectionContents.drop_front(NextOffset);
990 // Optionally print the subsection bytes in case our parsing gets confused
991 // later.
992 if (opts::CodeViewSubsectionBytes)
993 printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
994 Contents);
996 switch (DebugSubsectionKind(SubType)) {
997 case DebugSubsectionKind::Symbols:
998 printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
999 break;
1001 case DebugSubsectionKind::InlineeLines:
1002 printCodeViewInlineeLines(Contents);
1003 break;
1005 case DebugSubsectionKind::FileChecksums:
1006 printCodeViewFileChecksums(Contents);
1007 break;
1009 case DebugSubsectionKind::Lines: {
1010 // Holds a PC to file:line table. Some data to parse this subsection is
1011 // stored in the other subsections, so just check sanity and store the
1012 // pointers for deferred processing.
1014 if (SubSectionSize < 12) {
1015 // There should be at least three words to store two function
1016 // relocations and size of the code.
1017 error(object_error::parse_failed);
1018 return;
1021 StringRef LinkageName;
1022 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
1023 LinkageName));
1024 W.printString("LinkageName", LinkageName);
1025 if (FunctionLineTables.count(LinkageName) != 0) {
1026 // Saw debug info for this function already?
1027 error(object_error::parse_failed);
1028 return;
1031 FunctionLineTables[LinkageName] = Contents;
1032 FunctionNames.push_back(LinkageName);
1033 break;
1035 case DebugSubsectionKind::FrameData: {
1036 // First four bytes is a relocation against the function.
1037 BinaryStreamReader SR(Contents, llvm::support::little);
1039 DebugFrameDataSubsectionRef FrameData;
1040 error(FrameData.initialize(SR));
1042 StringRef LinkageName;
1043 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1044 FrameData.getRelocPtr(), LinkageName));
1045 W.printString("LinkageName", LinkageName);
1047 // To find the active frame description, search this array for the
1048 // smallest PC range that includes the current PC.
1049 for (const auto &FD : FrameData) {
1050 StringRef FrameFunc = error(CVStringTable.getString(FD.FrameFunc));
1052 DictScope S(W, "FrameData");
1053 W.printHex("RvaStart", FD.RvaStart);
1054 W.printHex("CodeSize", FD.CodeSize);
1055 W.printHex("LocalSize", FD.LocalSize);
1056 W.printHex("ParamsSize", FD.ParamsSize);
1057 W.printHex("MaxStackSize", FD.MaxStackSize);
1058 W.printHex("PrologSize", FD.PrologSize);
1059 W.printHex("SavedRegsSize", FD.SavedRegsSize);
1060 W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1062 // The FrameFunc string is a small RPN program. It can be broken up into
1063 // statements that end in the '=' operator, which assigns the value on
1064 // the top of the stack to the previously pushed variable. Variables can
1065 // be temporary values ($T0) or physical registers ($esp). Print each
1066 // assignment on its own line to make these programs easier to read.
1068 ListScope FFS(W, "FrameFunc");
1069 while (!FrameFunc.empty()) {
1070 size_t EqOrEnd = FrameFunc.find('=');
1071 if (EqOrEnd == StringRef::npos)
1072 EqOrEnd = FrameFunc.size();
1073 else
1074 ++EqOrEnd;
1075 StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1076 W.printString(Stmt);
1077 FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1081 break;
1084 // Do nothing for unrecognized subsections.
1085 default:
1086 break;
1088 W.flush();
1091 // Dump the line tables now that we've read all the subsections and know all
1092 // the required information.
1093 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1094 StringRef Name = FunctionNames[I];
1095 ListScope S(W, "FunctionLineTable");
1096 W.printString("LinkageName", Name);
1098 BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1100 DebugLinesSubsectionRef LineInfo;
1101 error(LineInfo.initialize(Reader));
1103 W.printHex("Flags", LineInfo.header()->Flags);
1104 W.printHex("CodeSize", LineInfo.header()->CodeSize);
1105 for (const auto &Entry : LineInfo) {
1107 ListScope S(W, "FilenameSegment");
1108 printFileNameForOffset("Filename", Entry.NameIndex);
1109 uint32_t ColumnIndex = 0;
1110 for (const auto &Line : Entry.LineNumbers) {
1111 if (Line.Offset >= LineInfo.header()->CodeSize) {
1112 error(object_error::parse_failed);
1113 return;
1116 std::string PC = formatv("+{0:X}", uint32_t(Line.Offset));
1117 ListScope PCScope(W, PC);
1118 codeview::LineInfo LI(Line.Flags);
1120 if (LI.isAlwaysStepInto())
1121 W.printString("StepInto", StringRef("Always"));
1122 else if (LI.isNeverStepInto())
1123 W.printString("StepInto", StringRef("Never"));
1124 else
1125 W.printNumber("LineNumberStart", LI.getStartLine());
1126 W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1127 W.printBoolean("IsStatement", LI.isStatement());
1128 if (LineInfo.hasColumnInfo()) {
1129 W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1130 W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1131 ++ColumnIndex;
1138 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1139 const SectionRef &Section,
1140 StringRef SectionContents) {
1141 ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1142 Subsection.bytes_end());
1143 auto CODD = llvm::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1144 SectionContents);
1145 CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1146 CompilationCPUType, opts::CodeViewSubsectionBytes);
1147 CVSymbolArray Symbols;
1148 BinaryStreamReader Reader(BinaryData, llvm::support::little);
1149 if (auto EC = Reader.readArray(Symbols, Reader.getLength())) {
1150 consumeError(std::move(EC));
1151 W.flush();
1152 error(object_error::parse_failed);
1155 if (auto EC = CVSD.dump(Symbols)) {
1156 W.flush();
1157 error(std::move(EC));
1159 CompilationCPUType = CVSD.getCompilationCPUType();
1160 W.flush();
1163 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1164 BinaryStreamRef Stream(Subsection, llvm::support::little);
1165 DebugChecksumsSubsectionRef Checksums;
1166 error(Checksums.initialize(Stream));
1168 for (auto &FC : Checksums) {
1169 DictScope S(W, "FileChecksum");
1171 StringRef Filename = error(CVStringTable.getString(FC.FileNameOffset));
1172 W.printHex("Filename", Filename, FC.FileNameOffset);
1173 W.printHex("ChecksumSize", FC.Checksum.size());
1174 W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1175 makeArrayRef(FileChecksumKindNames));
1177 W.printBinary("ChecksumBytes", FC.Checksum);
1181 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1182 BinaryStreamReader SR(Subsection, llvm::support::little);
1183 DebugInlineeLinesSubsectionRef Lines;
1184 error(Lines.initialize(SR));
1186 for (auto &Line : Lines) {
1187 DictScope S(W, "InlineeSourceLine");
1188 printTypeIndex("Inlinee", Line.Header->Inlinee);
1189 printFileNameForOffset("FileID", Line.Header->FileID);
1190 W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1192 if (Lines.hasExtraFiles()) {
1193 W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1194 ListScope ExtraFiles(W, "ExtraFiles");
1195 for (const auto &FID : Line.ExtraFiles) {
1196 printFileNameForOffset("FileID", FID);
1202 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1203 // The file checksum subsection should precede all references to it.
1204 if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1205 error(object_error::parse_failed);
1207 auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1209 // Check if the file checksum table offset is valid.
1210 if (Iter == CVFileChecksumTable.end())
1211 error(object_error::parse_failed);
1213 return error(CVStringTable.getString(Iter->FileNameOffset));
1216 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1217 W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1220 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1221 MergingTypeTableBuilder &CVTypes,
1222 GlobalTypeTableBuilder &GlobalCVIDs,
1223 GlobalTypeTableBuilder &GlobalCVTypes,
1224 bool GHash) {
1225 for (const SectionRef &S : Obj->sections()) {
1226 StringRef SectionName;
1227 error(S.getName(SectionName));
1228 if (SectionName == ".debug$T") {
1229 StringRef Data = unwrapOrError(S.getContents());
1230 uint32_t Magic;
1231 error(consume(Data, Magic));
1232 if (Magic != 4)
1233 error(object_error::parse_failed);
1235 CVTypeArray Types;
1236 BinaryStreamReader Reader(Data, llvm::support::little);
1237 if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1238 consumeError(std::move(EC));
1239 W.flush();
1240 error(object_error::parse_failed);
1242 SmallVector<TypeIndex, 128> SourceToDest;
1243 Optional<uint32_t> PCHSignature;
1244 if (GHash) {
1245 std::vector<GloballyHashedType> Hashes =
1246 GloballyHashedType::hashTypes(Types);
1247 if (auto EC =
1248 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1249 Types, Hashes, PCHSignature))
1250 return error(std::move(EC));
1251 } else {
1252 if (auto EC = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1253 PCHSignature))
1254 return error(std::move(EC));
1260 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1261 const SectionRef &Section) {
1262 ListScope D(W, "CodeViewTypes");
1263 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1265 StringRef Data = unwrapOrError(Section.getContents());
1266 if (opts::CodeViewSubsectionBytes)
1267 W.printBinaryBlock("Data", Data);
1269 uint32_t Magic;
1270 error(consume(Data, Magic));
1271 W.printHex("Magic", Magic);
1272 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1273 return error(object_error::parse_failed);
1275 Types.reset(Data, 100);
1277 TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1278 error(codeview::visitTypeStream(Types, TDV));
1279 W.flush();
1282 void COFFDumper::printSectionHeaders() {
1283 ListScope SectionsD(W, "Sections");
1284 int SectionNumber = 0;
1285 for (const SectionRef &Sec : Obj->sections()) {
1286 ++SectionNumber;
1287 const coff_section *Section = Obj->getCOFFSection(Sec);
1289 StringRef Name;
1290 error(Sec.getName(Name));
1292 DictScope D(W, "Section");
1293 W.printNumber("Number", SectionNumber);
1294 W.printBinary("Name", Name, Section->Name);
1295 W.printHex ("VirtualSize", Section->VirtualSize);
1296 W.printHex ("VirtualAddress", Section->VirtualAddress);
1297 W.printNumber("RawDataSize", Section->SizeOfRawData);
1298 W.printHex ("PointerToRawData", Section->PointerToRawData);
1299 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
1300 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
1301 W.printNumber("RelocationCount", Section->NumberOfRelocations);
1302 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1303 W.printFlags ("Characteristics", Section->Characteristics,
1304 makeArrayRef(ImageSectionCharacteristics),
1305 COFF::SectionCharacteristics(0x00F00000));
1307 if (opts::SectionRelocations) {
1308 ListScope D(W, "Relocations");
1309 for (const RelocationRef &Reloc : Sec.relocations())
1310 printRelocation(Sec, Reloc);
1313 if (opts::SectionSymbols) {
1314 ListScope D(W, "Symbols");
1315 for (const SymbolRef &Symbol : Obj->symbols()) {
1316 if (!Sec.containsSymbol(Symbol))
1317 continue;
1319 printSymbol(Symbol);
1323 if (opts::SectionData &&
1324 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1325 StringRef Data = unwrapOrError(Sec.getContents());
1326 W.printBinaryBlock("SectionData", Data);
1331 void COFFDumper::printRelocations() {
1332 ListScope D(W, "Relocations");
1334 int SectionNumber = 0;
1335 for (const SectionRef &Section : Obj->sections()) {
1336 ++SectionNumber;
1337 StringRef Name;
1338 error(Section.getName(Name));
1340 bool PrintedGroup = false;
1341 for (const RelocationRef &Reloc : Section.relocations()) {
1342 if (!PrintedGroup) {
1343 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1344 W.indent();
1345 PrintedGroup = true;
1348 printRelocation(Section, Reloc);
1351 if (PrintedGroup) {
1352 W.unindent();
1353 W.startLine() << "}\n";
1358 void COFFDumper::printRelocation(const SectionRef &Section,
1359 const RelocationRef &Reloc, uint64_t Bias) {
1360 uint64_t Offset = Reloc.getOffset() - Bias;
1361 uint64_t RelocType = Reloc.getType();
1362 SmallString<32> RelocName;
1363 StringRef SymbolName;
1364 Reloc.getTypeName(RelocName);
1365 symbol_iterator Symbol = Reloc.getSymbol();
1366 int64_t SymbolIndex = -1;
1367 if (Symbol != Obj->symbol_end()) {
1368 Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1369 error(errorToErrorCode(SymbolNameOrErr.takeError()));
1370 SymbolName = *SymbolNameOrErr;
1371 SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1374 if (opts::ExpandRelocs) {
1375 DictScope Group(W, "Relocation");
1376 W.printHex("Offset", Offset);
1377 W.printNumber("Type", RelocName, RelocType);
1378 W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1379 W.printNumber("SymbolIndex", SymbolIndex);
1380 } else {
1381 raw_ostream& OS = W.startLine();
1382 OS << W.hex(Offset)
1383 << " " << RelocName
1384 << " " << (SymbolName.empty() ? "-" : SymbolName)
1385 << " (" << SymbolIndex << ")"
1386 << "\n";
1390 void COFFDumper::printSymbols() {
1391 ListScope Group(W, "Symbols");
1393 for (const SymbolRef &Symbol : Obj->symbols())
1394 printSymbol(Symbol);
1397 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1399 static Expected<StringRef>
1400 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1401 const coff_section *Section) {
1402 if (Section)
1403 return Obj->getSectionName(Section);
1404 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1405 return StringRef("IMAGE_SYM_DEBUG");
1406 if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1407 return StringRef("IMAGE_SYM_ABSOLUTE");
1408 if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1409 return StringRef("IMAGE_SYM_UNDEFINED");
1410 return StringRef("");
1413 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1414 DictScope D(W, "Symbol");
1416 COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1417 const coff_section *Section;
1418 if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1419 W.startLine() << "Invalid section number: " << EC.message() << "\n";
1420 W.flush();
1421 return;
1424 StringRef SymbolName;
1425 if (Obj->getSymbolName(Symbol, SymbolName))
1426 SymbolName = "";
1428 StringRef SectionName;
1429 if (Expected<StringRef> NameOrErr =
1430 getSectionName(Obj, Symbol.getSectionNumber(), Section))
1431 SectionName = *NameOrErr;
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))) {
1462 LinkedName = "";
1463 error(EC);
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)));
1480 break;
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 if (std::error_code EC = Obj->getSection(AuxNumber, Assoc))
1500 error(EC);
1501 Expected<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1502 if (!Res)
1503 error(Res.takeError());
1504 AssocName = *Res;
1506 W.printNumber("AssocSection", AssocName, AuxNumber);
1508 } else if (Symbol.isCLRToken()) {
1509 const coff_aux_clr_token *Aux;
1510 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1512 Expected<COFFSymbolRef> ReferredSym =
1513 Obj->getSymbol(Aux->SymbolTableIndex);
1514 StringRef ReferredName;
1515 std::error_code EC = errorToErrorCode(ReferredSym.takeError());
1516 if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
1517 ReferredName = "";
1518 error(EC);
1521 DictScope AS(W, "AuxCLRToken");
1522 W.printNumber("AuxType", Aux->AuxType);
1523 W.printNumber("Reserved", Aux->Reserved);
1524 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1526 } else {
1527 W.startLine() << "<unhandled auxiliary record>\n";
1532 void COFFDumper::printUnwindInfo() {
1533 ListScope D(W, "UnwindInformation");
1534 switch (Obj->getMachine()) {
1535 case COFF::IMAGE_FILE_MACHINE_AMD64: {
1536 Win64EH::Dumper Dumper(W);
1537 Win64EH::Dumper::SymbolResolver
1538 Resolver = [](const object::coff_section *Section, uint64_t Offset,
1539 SymbolRef &Symbol, void *user_data) -> std::error_code {
1540 COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1541 return Dumper->resolveSymbol(Section, Offset, Symbol);
1543 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1544 Dumper.printData(Ctx);
1545 break;
1547 case COFF::IMAGE_FILE_MACHINE_ARM64:
1548 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1549 ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
1550 COFF::IMAGE_FILE_MACHINE_ARM64);
1551 // TODO Propagate the error.
1552 consumeError(Decoder.dumpProcedureData(*Obj));
1553 break;
1555 default:
1556 W.printEnum("unsupported Image Machine", Obj->getMachine(),
1557 makeArrayRef(ImageFileMachineType));
1558 break;
1562 void COFFDumper::printNeededLibraries() {
1563 ListScope D(W, "NeededLibraries");
1565 using LibsTy = std::vector<StringRef>;
1566 LibsTy Libs;
1568 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1569 StringRef Name;
1570 if (!DirRef.getName(Name))
1571 Libs.push_back(Name);
1574 llvm::stable_sort(Libs);
1576 for (const auto &L : Libs) {
1577 W.startLine() << L << "\n";
1581 void COFFDumper::printImportedSymbols(
1582 iterator_range<imported_symbol_iterator> Range) {
1583 for (const ImportedSymbolRef &I : Range) {
1584 StringRef Sym;
1585 error(I.getSymbolName(Sym));
1586 uint16_t Ordinal;
1587 error(I.getOrdinal(Ordinal));
1588 W.printNumber("Symbol", Sym, Ordinal);
1592 void COFFDumper::printDelayImportedSymbols(
1593 const DelayImportDirectoryEntryRef &I,
1594 iterator_range<imported_symbol_iterator> Range) {
1595 int Index = 0;
1596 for (const ImportedSymbolRef &S : Range) {
1597 DictScope Import(W, "Import");
1598 StringRef Sym;
1599 error(S.getSymbolName(Sym));
1600 uint16_t Ordinal;
1601 error(S.getOrdinal(Ordinal));
1602 W.printNumber("Symbol", Sym, Ordinal);
1603 uint64_t Addr;
1604 error(I.getImportAddress(Index++, Addr));
1605 W.printHex("Address", Addr);
1609 void COFFDumper::printCOFFImports() {
1610 // Regular imports
1611 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1612 DictScope Import(W, "Import");
1613 StringRef Name;
1614 error(I.getName(Name));
1615 W.printString("Name", Name);
1616 uint32_t ILTAddr;
1617 error(I.getImportLookupTableRVA(ILTAddr));
1618 W.printHex("ImportLookupTableRVA", ILTAddr);
1619 uint32_t IATAddr;
1620 error(I.getImportAddressTableRVA(IATAddr));
1621 W.printHex("ImportAddressTableRVA", IATAddr);
1622 // The import lookup table can be missing with certain older linkers, so
1623 // fall back to the import address table in that case.
1624 if (ILTAddr)
1625 printImportedSymbols(I.lookup_table_symbols());
1626 else
1627 printImportedSymbols(I.imported_symbols());
1630 // Delay imports
1631 for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1632 DictScope Import(W, "DelayImport");
1633 StringRef Name;
1634 error(I.getName(Name));
1635 W.printString("Name", Name);
1636 const delay_import_directory_table_entry *Table;
1637 error(I.getDelayImportTable(Table));
1638 W.printHex("Attributes", Table->Attributes);
1639 W.printHex("ModuleHandle", Table->ModuleHandle);
1640 W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1641 W.printHex("ImportNameTable", Table->DelayImportNameTable);
1642 W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1643 W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1644 printDelayImportedSymbols(I, I.imported_symbols());
1648 void COFFDumper::printCOFFExports() {
1649 for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1650 DictScope Export(W, "Export");
1652 StringRef Name;
1653 uint32_t Ordinal, RVA;
1655 error(E.getSymbolName(Name));
1656 error(E.getOrdinal(Ordinal));
1657 error(E.getExportRVA(RVA));
1659 W.printNumber("Ordinal", Ordinal);
1660 W.printString("Name", Name);
1661 W.printHex("RVA", RVA);
1665 void COFFDumper::printCOFFDirectives() {
1666 for (const SectionRef &Section : Obj->sections()) {
1667 StringRef Name;
1669 error(Section.getName(Name));
1670 if (Name != ".drectve")
1671 continue;
1673 StringRef Contents = unwrapOrError(Section.getContents());
1674 W.printString("Directive(s)", Contents);
1678 static std::string getBaseRelocTypeName(uint8_t Type) {
1679 switch (Type) {
1680 case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1681 case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1682 case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1683 case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1684 case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1685 case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1686 case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1687 default: return "unknown (" + llvm::utostr(Type) + ")";
1691 void COFFDumper::printCOFFBaseReloc() {
1692 ListScope D(W, "BaseReloc");
1693 for (const BaseRelocRef &I : Obj->base_relocs()) {
1694 uint8_t Type;
1695 uint32_t RVA;
1696 error(I.getRVA(RVA));
1697 error(I.getType(Type));
1698 DictScope Import(W, "Entry");
1699 W.printString("Type", getBaseRelocTypeName(Type));
1700 W.printHex("Address", RVA);
1704 void COFFDumper::printCOFFResources() {
1705 ListScope ResourcesD(W, "Resources");
1706 for (const SectionRef &S : Obj->sections()) {
1707 StringRef Name;
1708 error(S.getName(Name));
1709 if (!Name.startswith(".rsrc"))
1710 continue;
1712 StringRef Ref = unwrapOrError(S.getContents());
1714 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1715 ResourceSectionRef RSF(Ref);
1716 auto &BaseTable = unwrapOrError(RSF.getBaseTable());
1717 W.printNumber("Total Number of Resources",
1718 countTotalTableEntries(RSF, BaseTable, "Type"));
1719 W.printHex("Base Table Address",
1720 Obj->getCOFFSection(S)->PointerToRawData);
1721 W.startLine() << "\n";
1722 printResourceDirectoryTable(RSF, BaseTable, "Type");
1724 if (opts::SectionData)
1725 W.printBinaryBlock(Name.str() + " Data", Ref);
1729 uint32_t
1730 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1731 const coff_resource_dir_table &Table,
1732 StringRef Level) {
1733 uint32_t TotalEntries = 0;
1734 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1735 i++) {
1736 auto Entry = unwrapOrError(Obj->getFileName(),
1737 getResourceDirectoryTableEntry(Table, i));
1738 if (Entry.Offset.isSubDir()) {
1739 StringRef NextLevel;
1740 if (Level == "Name")
1741 NextLevel = "Language";
1742 else
1743 NextLevel = "Name";
1744 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1745 TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1746 } else {
1747 TotalEntries += 1;
1750 return TotalEntries;
1753 void COFFDumper::printResourceDirectoryTable(
1754 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1755 StringRef Level) {
1757 W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1758 W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1760 // Iterate through level in resource directory tree.
1761 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1762 i++) {
1763 auto Entry = unwrapOrError(Obj->getFileName(),
1764 getResourceDirectoryTableEntry(Table, i));
1765 StringRef Name;
1766 SmallString<20> IDStr;
1767 raw_svector_ostream OS(IDStr);
1768 if (i < Table.NumberOfNameEntries) {
1769 ArrayRef<UTF16> RawEntryNameString =
1770 unwrapOrError(RSF.getEntryNameString(Entry));
1771 std::vector<UTF16> EndianCorrectedNameString;
1772 if (llvm::sys::IsBigEndianHost) {
1773 EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1774 std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1775 EndianCorrectedNameString.begin() + 1);
1776 EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1777 RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1779 std::string EntryNameString;
1780 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1781 error(object_error::parse_failed);
1782 OS << ": ";
1783 OS << EntryNameString;
1784 } else {
1785 if (Level == "Type") {
1786 OS << ": ";
1787 printResourceTypeName(Entry.Identifier.ID, OS);
1788 IDStr = IDStr.slice(0, IDStr.find_first_of(")", 0) + 1);
1789 } else {
1790 OS << ": (ID " << Entry.Identifier.ID << ")";
1793 Name = StringRef(IDStr);
1794 ListScope ResourceType(W, Level.str() + Name.str());
1795 if (Entry.Offset.isSubDir()) {
1796 W.printHex("Table Offset", Entry.Offset.value());
1797 StringRef NextLevel;
1798 if (Level == "Name")
1799 NextLevel = "Language";
1800 else
1801 NextLevel = "Name";
1802 auto &NextTable = unwrapOrError(RSF.getEntrySubDir(Entry));
1803 printResourceDirectoryTable(RSF, NextTable, NextLevel);
1804 } else {
1805 W.printHex("Entry Offset", Entry.Offset.value());
1806 char FormattedTime[20] = {};
1807 time_t TDS = time_t(Table.TimeDateStamp);
1808 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1809 W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1810 W.printNumber("Major Version", Table.MajorVersion);
1811 W.printNumber("Minor Version", Table.MinorVersion);
1812 W.printNumber("Characteristics", Table.Characteristics);
1817 Expected<const coff_resource_dir_entry &>
1818 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
1819 uint32_t Index) {
1820 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1821 return createError("can't get resource directory table entry");
1822 auto TablePtr = reinterpret_cast<const coff_resource_dir_entry *>(&Table + 1);
1823 return TablePtr[Index];
1826 void COFFDumper::printStackMap() const {
1827 object::SectionRef StackMapSection;
1828 for (auto Sec : Obj->sections()) {
1829 StringRef Name;
1830 Sec.getName(Name);
1831 if (Name == ".llvm_stackmaps") {
1832 StackMapSection = Sec;
1833 break;
1837 if (StackMapSection == object::SectionRef())
1838 return;
1840 StringRef StackMapContents = unwrapOrError(StackMapSection.getContents());
1841 ArrayRef<uint8_t> StackMapContentsArray =
1842 arrayRefFromStringRef(StackMapContents);
1844 if (Obj->isLittleEndian())
1845 prettyPrintStackMap(
1846 W, StackMapParser<support::little>(StackMapContentsArray));
1847 else
1848 prettyPrintStackMap(
1849 W, StackMapParser<support::big>(StackMapContentsArray));
1852 void COFFDumper::printAddrsig() {
1853 object::SectionRef AddrsigSection;
1854 for (auto Sec : Obj->sections()) {
1855 StringRef Name;
1856 Sec.getName(Name);
1857 if (Name == ".llvm_addrsig") {
1858 AddrsigSection = Sec;
1859 break;
1863 if (AddrsigSection == object::SectionRef())
1864 return;
1866 StringRef AddrsigContents = unwrapOrError(AddrsigSection.getContents());
1867 ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
1868 AddrsigContents.size());
1870 ListScope L(W, "Addrsig");
1871 const uint8_t *Cur = AddrsigContents.bytes_begin();
1872 const uint8_t *End = AddrsigContents.bytes_end();
1873 while (Cur != End) {
1874 unsigned Size;
1875 const char *Err;
1876 uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
1877 if (Err)
1878 reportError(Err);
1880 Expected<COFFSymbolRef> Sym = Obj->getSymbol(SymIndex);
1881 StringRef SymName;
1882 std::error_code EC = errorToErrorCode(Sym.takeError());
1883 if (EC || (EC = Obj->getSymbolName(*Sym, SymName))) {
1884 SymName = "";
1885 error(EC);
1888 W.printNumber("Sym", SymName, SymIndex);
1889 Cur += Size;
1893 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
1894 ArrayRef<ArrayRef<uint8_t>> IpiRecords,
1895 ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
1896 TypeTableCollection TpiTypes(TpiRecords);
1898 ListScope S(Writer, "MergedTypeStream");
1899 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1900 error(codeview::visitTypeStream(TpiTypes, TDV));
1901 Writer.flush();
1904 // Flatten the id stream and print it next. The ID stream refers to names from
1905 // the type stream.
1906 TypeTableCollection IpiTypes(IpiRecords);
1908 ListScope S(Writer, "MergedIDStream");
1909 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1910 TDV.setIpiTypes(IpiTypes);
1911 error(codeview::visitTypeStream(IpiTypes, TDV));
1912 Writer.flush();