gn build: Extract git() and git_out() functions in sync script
[llvm-complete.git] / tools / llvm-readobj / COFFDumper.cpp
blob2ee4d52df3231df501945879edf546f93c9680a3
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 =
941 unwrapOrError(Obj->getFileName(), Section.getContents());
942 StringRef Data = SectionContents;
944 SmallVector<StringRef, 10> FunctionNames;
945 StringMap<StringRef> FunctionLineTables;
947 ListScope D(W, "CodeViewDebugInfo");
948 // Print the section to allow correlation with printSectionHeaders.
949 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
951 uint32_t Magic;
952 error(consume(Data, Magic));
953 W.printHex("Magic", Magic);
954 if (Magic != COFF::DEBUG_SECTION_MAGIC)
955 return error(object_error::parse_failed);
957 BinaryStreamReader FSReader(Data, support::little);
958 initializeFileAndStringTables(FSReader);
960 // TODO: Convert this over to using ModuleSubstreamVisitor.
961 while (!Data.empty()) {
962 // The section consists of a number of subsection in the following format:
963 // |SubSectionType|SubSectionSize|Contents...|
964 uint32_t SubType, SubSectionSize;
965 error(consume(Data, SubType));
966 error(consume(Data, SubSectionSize));
968 ListScope S(W, "Subsection");
969 // Dump the subsection as normal even if the ignore bit is set.
970 if (SubType & SubsectionIgnoreFlag) {
971 W.printHex("IgnoredSubsectionKind", SubType);
972 SubType &= ~SubsectionIgnoreFlag;
974 W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
975 W.printHex("SubSectionSize", SubSectionSize);
977 // Get the contents of the subsection.
978 if (SubSectionSize > Data.size())
979 return error(object_error::parse_failed);
980 StringRef Contents = Data.substr(0, SubSectionSize);
982 // Add SubSectionSize to the current offset and align that offset to find
983 // the next subsection.
984 size_t SectionOffset = Data.data() - SectionContents.data();
985 size_t NextOffset = SectionOffset + SubSectionSize;
986 NextOffset = alignTo(NextOffset, 4);
987 if (NextOffset > SectionContents.size())
988 return error(object_error::parse_failed);
989 Data = SectionContents.drop_front(NextOffset);
991 // Optionally print the subsection bytes in case our parsing gets confused
992 // later.
993 if (opts::CodeViewSubsectionBytes)
994 printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
995 Contents);
997 switch (DebugSubsectionKind(SubType)) {
998 case DebugSubsectionKind::Symbols:
999 printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1000 break;
1002 case DebugSubsectionKind::InlineeLines:
1003 printCodeViewInlineeLines(Contents);
1004 break;
1006 case DebugSubsectionKind::FileChecksums:
1007 printCodeViewFileChecksums(Contents);
1008 break;
1010 case DebugSubsectionKind::Lines: {
1011 // Holds a PC to file:line table. Some data to parse this subsection is
1012 // stored in the other subsections, so just check sanity and store the
1013 // pointers for deferred processing.
1015 if (SubSectionSize < 12) {
1016 // There should be at least three words to store two function
1017 // relocations and size of the code.
1018 error(object_error::parse_failed);
1019 return;
1022 StringRef LinkageName;
1023 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionOffset,
1024 LinkageName));
1025 W.printString("LinkageName", LinkageName);
1026 if (FunctionLineTables.count(LinkageName) != 0) {
1027 // Saw debug info for this function already?
1028 error(object_error::parse_failed);
1029 return;
1032 FunctionLineTables[LinkageName] = Contents;
1033 FunctionNames.push_back(LinkageName);
1034 break;
1036 case DebugSubsectionKind::FrameData: {
1037 // First four bytes is a relocation against the function.
1038 BinaryStreamReader SR(Contents, llvm::support::little);
1040 DebugFrameDataSubsectionRef FrameData;
1041 error(FrameData.initialize(SR));
1043 StringRef LinkageName;
1044 error(resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1045 FrameData.getRelocPtr(), LinkageName));
1046 W.printString("LinkageName", LinkageName);
1048 // To find the active frame description, search this array for the
1049 // smallest PC range that includes the current PC.
1050 for (const auto &FD : FrameData) {
1051 StringRef FrameFunc = unwrapOrError(
1052 Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
1054 DictScope S(W, "FrameData");
1055 W.printHex("RvaStart", FD.RvaStart);
1056 W.printHex("CodeSize", FD.CodeSize);
1057 W.printHex("LocalSize", FD.LocalSize);
1058 W.printHex("ParamsSize", FD.ParamsSize);
1059 W.printHex("MaxStackSize", FD.MaxStackSize);
1060 W.printHex("PrologSize", FD.PrologSize);
1061 W.printHex("SavedRegsSize", FD.SavedRegsSize);
1062 W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1064 // The FrameFunc string is a small RPN program. It can be broken up into
1065 // statements that end in the '=' operator, which assigns the value on
1066 // the top of the stack to the previously pushed variable. Variables can
1067 // be temporary values ($T0) or physical registers ($esp). Print each
1068 // assignment on its own line to make these programs easier to read.
1070 ListScope FFS(W, "FrameFunc");
1071 while (!FrameFunc.empty()) {
1072 size_t EqOrEnd = FrameFunc.find('=');
1073 if (EqOrEnd == StringRef::npos)
1074 EqOrEnd = FrameFunc.size();
1075 else
1076 ++EqOrEnd;
1077 StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1078 W.printString(Stmt);
1079 FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1083 break;
1086 // Do nothing for unrecognized subsections.
1087 default:
1088 break;
1090 W.flush();
1093 // Dump the line tables now that we've read all the subsections and know all
1094 // the required information.
1095 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1096 StringRef Name = FunctionNames[I];
1097 ListScope S(W, "FunctionLineTable");
1098 W.printString("LinkageName", Name);
1100 BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1102 DebugLinesSubsectionRef LineInfo;
1103 error(LineInfo.initialize(Reader));
1105 W.printHex("Flags", LineInfo.header()->Flags);
1106 W.printHex("CodeSize", LineInfo.header()->CodeSize);
1107 for (const auto &Entry : LineInfo) {
1109 ListScope S(W, "FilenameSegment");
1110 printFileNameForOffset("Filename", Entry.NameIndex);
1111 uint32_t ColumnIndex = 0;
1112 for (const auto &Line : Entry.LineNumbers) {
1113 if (Line.Offset >= LineInfo.header()->CodeSize) {
1114 error(object_error::parse_failed);
1115 return;
1118 std::string PC = formatv("+{0:X}", uint32_t(Line.Offset));
1119 ListScope PCScope(W, PC);
1120 codeview::LineInfo LI(Line.Flags);
1122 if (LI.isAlwaysStepInto())
1123 W.printString("StepInto", StringRef("Always"));
1124 else if (LI.isNeverStepInto())
1125 W.printString("StepInto", StringRef("Never"));
1126 else
1127 W.printNumber("LineNumberStart", LI.getStartLine());
1128 W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1129 W.printBoolean("IsStatement", LI.isStatement());
1130 if (LineInfo.hasColumnInfo()) {
1131 W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1132 W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1133 ++ColumnIndex;
1140 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1141 const SectionRef &Section,
1142 StringRef SectionContents) {
1143 ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1144 Subsection.bytes_end());
1145 auto CODD = llvm::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1146 SectionContents);
1147 CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1148 CompilationCPUType, opts::CodeViewSubsectionBytes);
1149 CVSymbolArray Symbols;
1150 BinaryStreamReader Reader(BinaryData, llvm::support::little);
1151 if (auto EC = Reader.readArray(Symbols, Reader.getLength())) {
1152 consumeError(std::move(EC));
1153 W.flush();
1154 error(object_error::parse_failed);
1157 if (auto EC = CVSD.dump(Symbols)) {
1158 W.flush();
1159 error(std::move(EC));
1161 CompilationCPUType = CVSD.getCompilationCPUType();
1162 W.flush();
1165 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1166 BinaryStreamRef Stream(Subsection, llvm::support::little);
1167 DebugChecksumsSubsectionRef Checksums;
1168 error(Checksums.initialize(Stream));
1170 for (auto &FC : Checksums) {
1171 DictScope S(W, "FileChecksum");
1173 StringRef Filename = unwrapOrError(
1174 Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
1175 W.printHex("Filename", Filename, FC.FileNameOffset);
1176 W.printHex("ChecksumSize", FC.Checksum.size());
1177 W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1178 makeArrayRef(FileChecksumKindNames));
1180 W.printBinary("ChecksumBytes", FC.Checksum);
1184 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1185 BinaryStreamReader SR(Subsection, llvm::support::little);
1186 DebugInlineeLinesSubsectionRef Lines;
1187 error(Lines.initialize(SR));
1189 for (auto &Line : Lines) {
1190 DictScope S(W, "InlineeSourceLine");
1191 printTypeIndex("Inlinee", Line.Header->Inlinee);
1192 printFileNameForOffset("FileID", Line.Header->FileID);
1193 W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1195 if (Lines.hasExtraFiles()) {
1196 W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1197 ListScope ExtraFiles(W, "ExtraFiles");
1198 for (const auto &FID : Line.ExtraFiles) {
1199 printFileNameForOffset("FileID", FID);
1205 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1206 // The file checksum subsection should precede all references to it.
1207 if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1208 error(object_error::parse_failed);
1210 auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1212 // Check if the file checksum table offset is valid.
1213 if (Iter == CVFileChecksumTable.end())
1214 error(object_error::parse_failed);
1216 return unwrapOrError(Obj->getFileName(),
1217 CVStringTable.getString(Iter->FileNameOffset));
1220 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1221 W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1224 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1225 MergingTypeTableBuilder &CVTypes,
1226 GlobalTypeTableBuilder &GlobalCVIDs,
1227 GlobalTypeTableBuilder &GlobalCVTypes,
1228 bool GHash) {
1229 for (const SectionRef &S : Obj->sections()) {
1230 StringRef SectionName;
1231 error(S.getName(SectionName));
1232 if (SectionName == ".debug$T") {
1233 StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
1234 uint32_t Magic;
1235 error(consume(Data, Magic));
1236 if (Magic != 4)
1237 error(object_error::parse_failed);
1239 CVTypeArray Types;
1240 BinaryStreamReader Reader(Data, llvm::support::little);
1241 if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1242 consumeError(std::move(EC));
1243 W.flush();
1244 error(object_error::parse_failed);
1246 SmallVector<TypeIndex, 128> SourceToDest;
1247 Optional<uint32_t> PCHSignature;
1248 if (GHash) {
1249 std::vector<GloballyHashedType> Hashes =
1250 GloballyHashedType::hashTypes(Types);
1251 if (auto EC =
1252 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1253 Types, Hashes, PCHSignature))
1254 return error(std::move(EC));
1255 } else {
1256 if (auto EC = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1257 PCHSignature))
1258 return error(std::move(EC));
1264 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1265 const SectionRef &Section) {
1266 ListScope D(W, "CodeViewTypes");
1267 W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1269 StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
1270 if (opts::CodeViewSubsectionBytes)
1271 W.printBinaryBlock("Data", Data);
1273 uint32_t Magic;
1274 error(consume(Data, Magic));
1275 W.printHex("Magic", Magic);
1276 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1277 return error(object_error::parse_failed);
1279 Types.reset(Data, 100);
1281 TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1282 error(codeview::visitTypeStream(Types, TDV));
1283 W.flush();
1286 void COFFDumper::printSectionHeaders() {
1287 ListScope SectionsD(W, "Sections");
1288 int SectionNumber = 0;
1289 for (const SectionRef &Sec : Obj->sections()) {
1290 ++SectionNumber;
1291 const coff_section *Section = Obj->getCOFFSection(Sec);
1293 StringRef Name;
1294 error(Sec.getName(Name));
1296 DictScope D(W, "Section");
1297 W.printNumber("Number", SectionNumber);
1298 W.printBinary("Name", Name, Section->Name);
1299 W.printHex ("VirtualSize", Section->VirtualSize);
1300 W.printHex ("VirtualAddress", Section->VirtualAddress);
1301 W.printNumber("RawDataSize", Section->SizeOfRawData);
1302 W.printHex ("PointerToRawData", Section->PointerToRawData);
1303 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
1304 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
1305 W.printNumber("RelocationCount", Section->NumberOfRelocations);
1306 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1307 W.printFlags ("Characteristics", Section->Characteristics,
1308 makeArrayRef(ImageSectionCharacteristics),
1309 COFF::SectionCharacteristics(0x00F00000));
1311 if (opts::SectionRelocations) {
1312 ListScope D(W, "Relocations");
1313 for (const RelocationRef &Reloc : Sec.relocations())
1314 printRelocation(Sec, Reloc);
1317 if (opts::SectionSymbols) {
1318 ListScope D(W, "Symbols");
1319 for (const SymbolRef &Symbol : Obj->symbols()) {
1320 if (!Sec.containsSymbol(Symbol))
1321 continue;
1323 printSymbol(Symbol);
1327 if (opts::SectionData &&
1328 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1329 StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
1330 W.printBinaryBlock("SectionData", Data);
1335 void COFFDumper::printRelocations() {
1336 ListScope D(W, "Relocations");
1338 int SectionNumber = 0;
1339 for (const SectionRef &Section : Obj->sections()) {
1340 ++SectionNumber;
1341 StringRef Name;
1342 error(Section.getName(Name));
1344 bool PrintedGroup = false;
1345 for (const RelocationRef &Reloc : Section.relocations()) {
1346 if (!PrintedGroup) {
1347 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1348 W.indent();
1349 PrintedGroup = true;
1352 printRelocation(Section, Reloc);
1355 if (PrintedGroup) {
1356 W.unindent();
1357 W.startLine() << "}\n";
1362 void COFFDumper::printRelocation(const SectionRef &Section,
1363 const RelocationRef &Reloc, uint64_t Bias) {
1364 uint64_t Offset = Reloc.getOffset() - Bias;
1365 uint64_t RelocType = Reloc.getType();
1366 SmallString<32> RelocName;
1367 StringRef SymbolName;
1368 Reloc.getTypeName(RelocName);
1369 symbol_iterator Symbol = Reloc.getSymbol();
1370 int64_t SymbolIndex = -1;
1371 if (Symbol != Obj->symbol_end()) {
1372 Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1373 error(errorToErrorCode(SymbolNameOrErr.takeError()));
1374 SymbolName = *SymbolNameOrErr;
1375 SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1378 if (opts::ExpandRelocs) {
1379 DictScope Group(W, "Relocation");
1380 W.printHex("Offset", Offset);
1381 W.printNumber("Type", RelocName, RelocType);
1382 W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1383 W.printNumber("SymbolIndex", SymbolIndex);
1384 } else {
1385 raw_ostream& OS = W.startLine();
1386 OS << W.hex(Offset)
1387 << " " << RelocName
1388 << " " << (SymbolName.empty() ? "-" : SymbolName)
1389 << " (" << SymbolIndex << ")"
1390 << "\n";
1394 void COFFDumper::printSymbols() {
1395 ListScope Group(W, "Symbols");
1397 for (const SymbolRef &Symbol : Obj->symbols())
1398 printSymbol(Symbol);
1401 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1403 static Expected<StringRef>
1404 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1405 const coff_section *Section) {
1406 if (Section)
1407 return Obj->getSectionName(Section);
1408 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1409 return StringRef("IMAGE_SYM_DEBUG");
1410 if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1411 return StringRef("IMAGE_SYM_ABSOLUTE");
1412 if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1413 return StringRef("IMAGE_SYM_UNDEFINED");
1414 return StringRef("");
1417 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1418 DictScope D(W, "Symbol");
1420 COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1421 const coff_section *Section;
1422 if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
1423 W.startLine() << "Invalid section number: " << EC.message() << "\n";
1424 W.flush();
1425 return;
1428 StringRef SymbolName;
1429 if (Obj->getSymbolName(Symbol, SymbolName))
1430 SymbolName = "";
1432 StringRef SectionName;
1433 if (Expected<StringRef> NameOrErr =
1434 getSectionName(Obj, Symbol.getSectionNumber(), Section))
1435 SectionName = *NameOrErr;
1437 W.printString("Name", SymbolName);
1438 W.printNumber("Value", Symbol.getValue());
1439 W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1440 W.printEnum ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1441 W.printEnum ("ComplexType", Symbol.getComplexType(),
1442 makeArrayRef(ImageSymDType));
1443 W.printEnum ("StorageClass", Symbol.getStorageClass(),
1444 makeArrayRef(ImageSymClass));
1445 W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1447 for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1448 if (Symbol.isFunctionDefinition()) {
1449 const coff_aux_function_definition *Aux;
1450 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1452 DictScope AS(W, "AuxFunctionDef");
1453 W.printNumber("TagIndex", Aux->TagIndex);
1454 W.printNumber("TotalSize", Aux->TotalSize);
1455 W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1456 W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1458 } else if (Symbol.isAnyUndefined()) {
1459 const coff_aux_weak_external *Aux;
1460 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1462 Expected<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
1463 StringRef LinkedName;
1464 std::error_code EC = errorToErrorCode(Linked.takeError());
1465 if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) {
1466 LinkedName = "";
1467 error(EC);
1470 DictScope AS(W, "AuxWeakExternal");
1471 W.printNumber("Linked", LinkedName, Aux->TagIndex);
1472 W.printEnum ("Search", Aux->Characteristics,
1473 makeArrayRef(WeakExternalCharacteristics));
1475 } else if (Symbol.isFileRecord()) {
1476 const char *FileName;
1477 error(getSymbolAuxData(Obj, Symbol, I, FileName));
1479 DictScope AS(W, "AuxFileRecord");
1481 StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1482 Obj->getSymbolTableEntrySize());
1483 W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1484 break;
1485 } else if (Symbol.isSectionDefinition()) {
1486 const coff_aux_section_definition *Aux;
1487 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1489 int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1491 DictScope AS(W, "AuxSectionDef");
1492 W.printNumber("Length", Aux->Length);
1493 W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1494 W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1495 W.printHex("Checksum", Aux->CheckSum);
1496 W.printNumber("Number", AuxNumber);
1497 W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1499 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1500 && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1501 const coff_section *Assoc;
1502 StringRef AssocName = "";
1503 if (std::error_code EC = Obj->getSection(AuxNumber, Assoc))
1504 error(EC);
1505 Expected<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
1506 if (!Res)
1507 error(Res.takeError());
1508 AssocName = *Res;
1510 W.printNumber("AssocSection", AssocName, AuxNumber);
1512 } else if (Symbol.isCLRToken()) {
1513 const coff_aux_clr_token *Aux;
1514 error(getSymbolAuxData(Obj, Symbol, I, Aux));
1516 Expected<COFFSymbolRef> ReferredSym =
1517 Obj->getSymbol(Aux->SymbolTableIndex);
1518 StringRef ReferredName;
1519 std::error_code EC = errorToErrorCode(ReferredSym.takeError());
1520 if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
1521 ReferredName = "";
1522 error(EC);
1525 DictScope AS(W, "AuxCLRToken");
1526 W.printNumber("AuxType", Aux->AuxType);
1527 W.printNumber("Reserved", Aux->Reserved);
1528 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
1530 } else {
1531 W.startLine() << "<unhandled auxiliary record>\n";
1536 void COFFDumper::printUnwindInfo() {
1537 ListScope D(W, "UnwindInformation");
1538 switch (Obj->getMachine()) {
1539 case COFF::IMAGE_FILE_MACHINE_AMD64: {
1540 Win64EH::Dumper Dumper(W);
1541 Win64EH::Dumper::SymbolResolver
1542 Resolver = [](const object::coff_section *Section, uint64_t Offset,
1543 SymbolRef &Symbol, void *user_data) -> std::error_code {
1544 COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1545 return Dumper->resolveSymbol(Section, Offset, Symbol);
1547 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1548 Dumper.printData(Ctx);
1549 break;
1551 case COFF::IMAGE_FILE_MACHINE_ARM64:
1552 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1553 ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
1554 COFF::IMAGE_FILE_MACHINE_ARM64);
1555 // TODO Propagate the error.
1556 consumeError(Decoder.dumpProcedureData(*Obj));
1557 break;
1559 default:
1560 W.printEnum("unsupported Image Machine", Obj->getMachine(),
1561 makeArrayRef(ImageFileMachineType));
1562 break;
1566 void COFFDumper::printNeededLibraries() {
1567 ListScope D(W, "NeededLibraries");
1569 using LibsTy = std::vector<StringRef>;
1570 LibsTy Libs;
1572 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1573 StringRef Name;
1574 if (!DirRef.getName(Name))
1575 Libs.push_back(Name);
1578 llvm::stable_sort(Libs);
1580 for (const auto &L : Libs) {
1581 W.startLine() << L << "\n";
1585 void COFFDumper::printImportedSymbols(
1586 iterator_range<imported_symbol_iterator> Range) {
1587 for (const ImportedSymbolRef &I : Range) {
1588 StringRef Sym;
1589 error(I.getSymbolName(Sym));
1590 uint16_t Ordinal;
1591 error(I.getOrdinal(Ordinal));
1592 W.printNumber("Symbol", Sym, Ordinal);
1596 void COFFDumper::printDelayImportedSymbols(
1597 const DelayImportDirectoryEntryRef &I,
1598 iterator_range<imported_symbol_iterator> Range) {
1599 int Index = 0;
1600 for (const ImportedSymbolRef &S : Range) {
1601 DictScope Import(W, "Import");
1602 StringRef Sym;
1603 error(S.getSymbolName(Sym));
1604 uint16_t Ordinal;
1605 error(S.getOrdinal(Ordinal));
1606 W.printNumber("Symbol", Sym, Ordinal);
1607 uint64_t Addr;
1608 error(I.getImportAddress(Index++, Addr));
1609 W.printHex("Address", Addr);
1613 void COFFDumper::printCOFFImports() {
1614 // Regular imports
1615 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1616 DictScope Import(W, "Import");
1617 StringRef Name;
1618 error(I.getName(Name));
1619 W.printString("Name", Name);
1620 uint32_t ILTAddr;
1621 error(I.getImportLookupTableRVA(ILTAddr));
1622 W.printHex("ImportLookupTableRVA", ILTAddr);
1623 uint32_t IATAddr;
1624 error(I.getImportAddressTableRVA(IATAddr));
1625 W.printHex("ImportAddressTableRVA", IATAddr);
1626 // The import lookup table can be missing with certain older linkers, so
1627 // fall back to the import address table in that case.
1628 if (ILTAddr)
1629 printImportedSymbols(I.lookup_table_symbols());
1630 else
1631 printImportedSymbols(I.imported_symbols());
1634 // Delay imports
1635 for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1636 DictScope Import(W, "DelayImport");
1637 StringRef Name;
1638 error(I.getName(Name));
1639 W.printString("Name", Name);
1640 const delay_import_directory_table_entry *Table;
1641 error(I.getDelayImportTable(Table));
1642 W.printHex("Attributes", Table->Attributes);
1643 W.printHex("ModuleHandle", Table->ModuleHandle);
1644 W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1645 W.printHex("ImportNameTable", Table->DelayImportNameTable);
1646 W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1647 W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1648 printDelayImportedSymbols(I, I.imported_symbols());
1652 void COFFDumper::printCOFFExports() {
1653 for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1654 DictScope Export(W, "Export");
1656 StringRef Name;
1657 uint32_t Ordinal, RVA;
1659 error(E.getSymbolName(Name));
1660 error(E.getOrdinal(Ordinal));
1661 error(E.getExportRVA(RVA));
1663 W.printNumber("Ordinal", Ordinal);
1664 W.printString("Name", Name);
1665 W.printHex("RVA", RVA);
1669 void COFFDumper::printCOFFDirectives() {
1670 for (const SectionRef &Section : Obj->sections()) {
1671 StringRef Name;
1673 error(Section.getName(Name));
1674 if (Name != ".drectve")
1675 continue;
1677 StringRef Contents =
1678 unwrapOrError(Obj->getFileName(), Section.getContents());
1679 W.printString("Directive(s)", Contents);
1683 static std::string getBaseRelocTypeName(uint8_t Type) {
1684 switch (Type) {
1685 case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1686 case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1687 case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1688 case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1689 case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1690 case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1691 case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1692 default: return "unknown (" + llvm::utostr(Type) + ")";
1696 void COFFDumper::printCOFFBaseReloc() {
1697 ListScope D(W, "BaseReloc");
1698 for (const BaseRelocRef &I : Obj->base_relocs()) {
1699 uint8_t Type;
1700 uint32_t RVA;
1701 error(I.getRVA(RVA));
1702 error(I.getType(Type));
1703 DictScope Import(W, "Entry");
1704 W.printString("Type", getBaseRelocTypeName(Type));
1705 W.printHex("Address", RVA);
1709 void COFFDumper::printCOFFResources() {
1710 ListScope ResourcesD(W, "Resources");
1711 for (const SectionRef &S : Obj->sections()) {
1712 StringRef Name;
1713 error(S.getName(Name));
1714 if (!Name.startswith(".rsrc"))
1715 continue;
1717 StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1719 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1720 ResourceSectionRef RSF(Ref);
1721 auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1722 W.printNumber("Total Number of Resources",
1723 countTotalTableEntries(RSF, BaseTable, "Type"));
1724 W.printHex("Base Table Address",
1725 Obj->getCOFFSection(S)->PointerToRawData);
1726 W.startLine() << "\n";
1727 printResourceDirectoryTable(RSF, BaseTable, "Type");
1729 if (opts::SectionData)
1730 W.printBinaryBlock(Name.str() + " Data", Ref);
1734 uint32_t
1735 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1736 const coff_resource_dir_table &Table,
1737 StringRef Level) {
1738 uint32_t TotalEntries = 0;
1739 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1740 i++) {
1741 auto Entry = unwrapOrError(Obj->getFileName(),
1742 getResourceDirectoryTableEntry(Table, i));
1743 if (Entry.Offset.isSubDir()) {
1744 StringRef NextLevel;
1745 if (Level == "Name")
1746 NextLevel = "Language";
1747 else
1748 NextLevel = "Name";
1749 auto &NextTable =
1750 unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1751 TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1752 } else {
1753 TotalEntries += 1;
1756 return TotalEntries;
1759 void COFFDumper::printResourceDirectoryTable(
1760 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1761 StringRef Level) {
1763 W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1764 W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1766 // Iterate through level in resource directory tree.
1767 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1768 i++) {
1769 auto Entry = unwrapOrError(Obj->getFileName(),
1770 getResourceDirectoryTableEntry(Table, i));
1771 StringRef Name;
1772 SmallString<20> IDStr;
1773 raw_svector_ostream OS(IDStr);
1774 if (i < Table.NumberOfNameEntries) {
1775 ArrayRef<UTF16> RawEntryNameString =
1776 unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
1777 std::vector<UTF16> EndianCorrectedNameString;
1778 if (llvm::sys::IsBigEndianHost) {
1779 EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1780 std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1781 EndianCorrectedNameString.begin() + 1);
1782 EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1783 RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1785 std::string EntryNameString;
1786 if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1787 error(object_error::parse_failed);
1788 OS << ": ";
1789 OS << EntryNameString;
1790 } else {
1791 if (Level == "Type") {
1792 OS << ": ";
1793 printResourceTypeName(Entry.Identifier.ID, OS);
1794 IDStr = IDStr.slice(0, IDStr.find_first_of(")", 0) + 1);
1795 } else {
1796 OS << ": (ID " << Entry.Identifier.ID << ")";
1799 Name = StringRef(IDStr);
1800 ListScope ResourceType(W, Level.str() + Name.str());
1801 if (Entry.Offset.isSubDir()) {
1802 W.printHex("Table Offset", Entry.Offset.value());
1803 StringRef NextLevel;
1804 if (Level == "Name")
1805 NextLevel = "Language";
1806 else
1807 NextLevel = "Name";
1808 auto &NextTable =
1809 unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1810 printResourceDirectoryTable(RSF, NextTable, NextLevel);
1811 } else {
1812 W.printHex("Entry Offset", Entry.Offset.value());
1813 char FormattedTime[20] = {};
1814 time_t TDS = time_t(Table.TimeDateStamp);
1815 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1816 W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1817 W.printNumber("Major Version", Table.MajorVersion);
1818 W.printNumber("Minor Version", Table.MinorVersion);
1819 W.printNumber("Characteristics", Table.Characteristics);
1824 Expected<const coff_resource_dir_entry &>
1825 COFFDumper::getResourceDirectoryTableEntry(const coff_resource_dir_table &Table,
1826 uint32_t Index) {
1827 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1828 return createError("can't get resource directory table entry");
1829 auto TablePtr = reinterpret_cast<const coff_resource_dir_entry *>(&Table + 1);
1830 return TablePtr[Index];
1833 void COFFDumper::printStackMap() const {
1834 object::SectionRef StackMapSection;
1835 for (auto Sec : Obj->sections()) {
1836 StringRef Name;
1837 Sec.getName(Name);
1838 if (Name == ".llvm_stackmaps") {
1839 StackMapSection = Sec;
1840 break;
1844 if (StackMapSection == object::SectionRef())
1845 return;
1847 StringRef StackMapContents =
1848 unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
1849 ArrayRef<uint8_t> StackMapContentsArray =
1850 arrayRefFromStringRef(StackMapContents);
1852 if (Obj->isLittleEndian())
1853 prettyPrintStackMap(
1854 W, StackMapParser<support::little>(StackMapContentsArray));
1855 else
1856 prettyPrintStackMap(
1857 W, StackMapParser<support::big>(StackMapContentsArray));
1860 void COFFDumper::printAddrsig() {
1861 object::SectionRef AddrsigSection;
1862 for (auto Sec : Obj->sections()) {
1863 StringRef Name;
1864 Sec.getName(Name);
1865 if (Name == ".llvm_addrsig") {
1866 AddrsigSection = Sec;
1867 break;
1871 if (AddrsigSection == object::SectionRef())
1872 return;
1874 StringRef AddrsigContents =
1875 unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
1876 ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
1877 AddrsigContents.size());
1879 ListScope L(W, "Addrsig");
1880 const uint8_t *Cur = AddrsigContents.bytes_begin();
1881 const uint8_t *End = AddrsigContents.bytes_end();
1882 while (Cur != End) {
1883 unsigned Size;
1884 const char *Err;
1885 uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
1886 if (Err)
1887 reportError(Err);
1889 Expected<COFFSymbolRef> Sym = Obj->getSymbol(SymIndex);
1890 StringRef SymName;
1891 std::error_code EC = errorToErrorCode(Sym.takeError());
1892 if (EC || (EC = Obj->getSymbolName(*Sym, SymName))) {
1893 SymName = "";
1894 error(EC);
1897 W.printNumber("Sym", SymName, SymIndex);
1898 Cur += Size;
1902 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
1903 ArrayRef<ArrayRef<uint8_t>> IpiRecords,
1904 ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
1905 TypeTableCollection TpiTypes(TpiRecords);
1907 ListScope S(Writer, "MergedTypeStream");
1908 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1909 error(codeview::visitTypeStream(TpiTypes, TDV));
1910 Writer.flush();
1913 // Flatten the id stream and print it next. The ID stream refers to names from
1914 // the type stream.
1915 TypeTableCollection IpiTypes(IpiRecords);
1917 ListScope S(Writer, "MergedIDStream");
1918 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
1919 TDV.setIpiTypes(IpiTypes);
1920 error(codeview::visitTypeStream(IpiTypes, TDV));
1921 Writer.flush();