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//===----------------------------------------------------------------------===//
13
14#include "ARMWinEHPrinter.h"
15#include "ObjDumper.h"
16#include "StackMapPrinter.h"
17#include "Win64EHDumper.h"
18#include "llvm-readobj.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/Enum.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/Formatters.h"
32#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
33#include "llvm/DebugInfo/CodeView/Line.h"
34#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
35#include "llvm/DebugInfo/CodeView/RecordSerialization.h"
36#include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
37#include "llvm/DebugInfo/CodeView/SymbolDumper.h"
38#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
39#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
40#include "llvm/DebugInfo/CodeView/TypeHashing.h"
41#include "llvm/DebugInfo/CodeView/TypeIndex.h"
42#include "llvm/DebugInfo/CodeView/TypeRecord.h"
43#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
44#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
45#include "llvm/Object/COFF.h"
46#include "llvm/Object/ObjectFile.h"
47#include "llvm/Object/WindowsResource.h"
48#include "llvm/Support/BinaryStreamReader.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/ConvertUTF.h"
52#include "llvm/Support/FormatVariadic.h"
53#include "llvm/Support/LEB128.h"
54#include "llvm/Support/ScopedPrinter.h"
55#include "llvm/Support/Win64EH.h"
56#include "llvm/Support/raw_ostream.h"
57#include <ctime>
58
59using namespace llvm;
60using namespace llvm::object;
61using namespace llvm::codeview;
62using namespace llvm::support;
63using namespace llvm::Win64EH;
64
65namespace {
66
67struct LoadConfigTables {
68 uint64_t SEHTableVA = 0;
69 uint64_t SEHTableCount = 0;
70 uint32_t GuardFlags = 0;
71 uint64_t GuardFidTableVA = 0;
72 uint64_t GuardFidTableCount = 0;
73 uint64_t GuardIatTableVA = 0;
74 uint64_t GuardIatTableCount = 0;
75 uint64_t GuardLJmpTableVA = 0;
76 uint64_t GuardLJmpTableCount = 0;
77 uint64_t GuardEHContTableVA = 0;
78 uint64_t GuardEHContTableCount = 0;
79};
80
81class COFFDumper : public ObjDumper {
82public:
83 friend class COFFObjectDumpDelegate;
84 COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
85 : ObjDumper(Writer, Obj->getFileName()), Obj(Obj), Writer(Writer),
86 Types(100) {}
87
88 void printFileHeaders() override;
89 void printSectionHeaders() override;
90 void printRelocations() override;
91 void printUnwindInfo() override;
92
93 void printNeededLibraries() override;
94
95 void printCOFFImports() override;
96 void printCOFFExports() override;
97 void printCOFFDirectives() override;
98 void printCOFFBaseReloc() override;
99 void printCOFFPseudoReloc() override;
100 void printCOFFDebugDirectory() override;
101 void printCOFFTLSDirectory() override;
102 void printCOFFResources() override;
103 void printCOFFLoadConfig() override;
104 void printCodeViewDebugInfo() override;
105 void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
106 llvm::codeview::MergingTypeTableBuilder &CVTypes,
107 llvm::codeview::GlobalTypeTableBuilder &GlobalCVIDs,
108 llvm::codeview::GlobalTypeTableBuilder &GlobalCVTypes,
109 bool GHash) override;
110 void printStackMap() const override;
111 void printAddrsig() override;
112 void printCGProfile() override;
113 void printStringTable() override;
114
115private:
116 StringRef getSymbolName(uint32_t Index);
117 void printSymbols(bool ExtraSymInfo) override;
118 void printDynamicSymbols() override;
119 void printSymbol(const SymbolRef &Sym);
120 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
121 uint64_t Bias = 0);
122 void printDataDirectory(uint32_t Index, const std::string &FieldName);
123
124 void printDOSHeader(const dos_header *DH);
125 template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
126 void printBaseOfDataField(const pe32_header *Hdr);
127 void printBaseOfDataField(const pe32plus_header *Hdr);
128 template <typename T>
129 void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
130 template <typename IntTy>
131 void printCOFFTLSDirectory(const coff_tls_directory<IntTy> *TlsTable);
132 typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
133 void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
134 PrintExtraCB PrintExtra = nullptr);
135
136 void printCodeViewSymbolSection(StringRef SectionName,
137 const SectionRef &Section);
138 void printCodeViewTypeSection(StringRef SectionName,
139 const SectionRef &Section);
140 StringRef getFileNameForFileOffset(uint32_t FileOffset);
141 void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
142 void printTypeIndex(StringRef FieldName, TypeIndex TI) {
143 // Forward to CVTypeDumper for simplicity.
144 codeview::printTypeIndex(Printer&: Writer, FieldName, TI, Types);
145 }
146
147 void printCodeViewSymbolsSubsection(StringRef Subsection,
148 const SectionRef &Section,
149 StringRef SectionContents);
150
151 void printCodeViewFileChecksums(StringRef Subsection);
152
153 void printCodeViewInlineeLines(StringRef Subsection);
154
155 void printRelocatedField(StringRef Label, const coff_section *Sec,
156 uint32_t RelocOffset, uint32_t Offset,
157 StringRef *RelocSym = nullptr);
158
159 uint32_t countTotalTableEntries(ResourceSectionRef RSF,
160 const coff_resource_dir_table &Table,
161 StringRef Level);
162
163 void printResourceDirectoryTable(ResourceSectionRef RSF,
164 const coff_resource_dir_table &Table,
165 StringRef Level);
166
167 void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
168 StringRef SectionContents, StringRef Block);
169
170 /// Given a .debug$S section, find the string table and file checksum table.
171 void initializeFileAndStringTables(BinaryStreamReader &Reader);
172
173 void cacheRelocations();
174
175 std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
176 SymbolRef &Sym);
177 std::error_code resolveSymbolName(const coff_section *Section,
178 uint64_t Offset, StringRef &Name);
179 std::error_code resolveSymbolName(const coff_section *Section,
180 StringRef SectionContents,
181 const void *RelocPtr, StringRef &Name);
182 void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
183 void
184 printDelayImportedSymbols(const DelayImportDirectoryEntryRef &I,
185 iterator_range<imported_symbol_iterator> Range);
186
187 typedef DenseMap<const coff_section *, std::vector<RelocationRef>> RelocMapTy;
188
189 const llvm::object::COFFObjectFile *Obj;
190 bool RelocCached = false;
191 RelocMapTy RelocMap;
192
193 DebugChecksumsSubsectionRef CVFileChecksumTable;
194
195 DebugStringTableSubsectionRef CVStringTable;
196
197 /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
198 /// first, but if we don't see one, just assume an X64 CPU type. It is common.
199 CPUType CompilationCPUType = CPUType::X64;
200
201 ScopedPrinter &Writer;
202 LazyRandomTypeCollection Types;
203};
204
205class COFFObjectDumpDelegate : public SymbolDumpDelegate {
206public:
207 COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
208 const COFFObjectFile *Obj, StringRef SectionContents)
209 : CD(CD), SR(SR), SectionContents(SectionContents) {
210 Sec = Obj->getCOFFSection(Section: SR);
211 }
212
213 uint32_t getRecordOffset(BinaryStreamReader Reader) override {
214 ArrayRef<uint8_t> Data;
215 if (auto EC = Reader.readLongestContiguousChunk(Buffer&: Data)) {
216 llvm::consumeError(Err: std::move(EC));
217 return 0;
218 }
219 return Data.data() - SectionContents.bytes_begin();
220 }
221
222 void printRelocatedField(StringRef Label, uint32_t RelocOffset,
223 uint32_t Offset, StringRef *RelocSym) override {
224 CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
225 }
226
227 void printBinaryBlockWithRelocs(StringRef Label,
228 ArrayRef<uint8_t> Block) override {
229 StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
230 Block.size());
231 if (opts::CodeViewSubsectionBytes)
232 CD.printBinaryBlockWithRelocs(Label, Sec: SR, SectionContents, Block: SBlock);
233 }
234
235 StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
236 return CD.getFileNameForFileOffset(FileOffset);
237 }
238
239 DebugStringTableSubsectionRef getStringTable() override {
240 return CD.CVStringTable;
241 }
242
243private:
244 COFFDumper &CD;
245 const SectionRef &SR;
246 const coff_section *Sec;
247 StringRef SectionContents;
248};
249
250} // end namespace
251
252namespace llvm {
253
254std::unique_ptr<ObjDumper> createCOFFDumper(const object::COFFObjectFile &Obj,
255 ScopedPrinter &Writer) {
256 return std::make_unique<COFFDumper>(args: &Obj, args&: Writer);
257}
258
259} // namespace llvm
260
261// Given a section and an offset into this section the function returns the
262// symbol used for the relocation at the offset.
263std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
264 uint64_t Offset, SymbolRef &Sym) {
265 cacheRelocations();
266 const auto &Relocations = RelocMap[Section];
267 auto SymI = Obj->symbol_end();
268 for (const auto &Relocation : Relocations) {
269 uint64_t RelocationOffset = Relocation.getOffset();
270
271 if (RelocationOffset == Offset) {
272 SymI = Relocation.getSymbol();
273 break;
274 }
275 }
276 if (SymI == Obj->symbol_end())
277 return inconvertibleErrorCode();
278 Sym = *SymI;
279 return std::error_code();
280}
281
282// Given a section and an offset into this section the function returns the name
283// of the symbol used for the relocation at the offset.
284std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
285 uint64_t Offset,
286 StringRef &Name) {
287 SymbolRef Symbol;
288 if (std::error_code EC = resolveSymbol(Section, Offset, Sym&: Symbol))
289 return EC;
290 Expected<StringRef> NameOrErr = Symbol.getName();
291 if (!NameOrErr)
292 return errorToErrorCode(Err: NameOrErr.takeError());
293 Name = *NameOrErr;
294 return std::error_code();
295}
296
297// Helper for when you have a pointer to real data and you want to know about
298// relocations against it.
299std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
300 StringRef SectionContents,
301 const void *RelocPtr,
302 StringRef &Name) {
303 assert(SectionContents.data() < RelocPtr &&
304 RelocPtr < SectionContents.data() + SectionContents.size() &&
305 "pointer to relocated object is not in section");
306 uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
307 SectionContents.data());
308 return resolveSymbolName(Section, Offset, Name);
309}
310
311void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
312 uint32_t RelocOffset, uint32_t Offset,
313 StringRef *RelocSym) {
314 StringRef SymStorage;
315 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
316 if (!resolveSymbolName(Section: Sec, Offset: RelocOffset, Name&: Symbol))
317 W.printSymbolOffset(Label, Symbol, Value: Offset);
318 else
319 W.printHex(Label, Value: RelocOffset);
320}
321
322void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
323 const SectionRef &Sec,
324 StringRef SectionContents,
325 StringRef Block) {
326 W.printBinaryBlock(Label, Value: Block);
327
328 assert(SectionContents.begin() < Block.begin() &&
329 SectionContents.end() >= Block.end() &&
330 "Block is not contained in SectionContents");
331 uint64_t OffsetStart = Block.data() - SectionContents.data();
332 uint64_t OffsetEnd = OffsetStart + Block.size();
333
334 W.flush();
335 cacheRelocations();
336 ListScope D(W, "BlockRelocations");
337 const coff_section *Section = Obj->getCOFFSection(Section: Sec);
338 const auto &Relocations = RelocMap[Section];
339 for (const auto &Relocation : Relocations) {
340 uint64_t RelocationOffset = Relocation.getOffset();
341 if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
342 printRelocation(Section: Sec, Reloc: Relocation, Bias: OffsetStart);
343 }
344}
345
346constexpr EnumStringDef<COFF::MachineTypes> ImageFileMachineTypeDefs[] = {
347 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN),
348 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33),
349 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64),
350 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM),
351 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64),
352 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64EC),
353 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64X),
354 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT),
355 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC),
356 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386),
357 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64),
358 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R),
359 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16),
360 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU),
361 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
362 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC),
363 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
364 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000),
365 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3),
366 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP),
367 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4),
368 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5),
369 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB),
370 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)};
371constexpr auto ImageFileMachineType =
372 BUILD_ENUM_STRINGS(ImageFileMachineTypeDefs);
373
374constexpr EnumStringDef<COFF::Characteristics> ImageFileCharacteristicsDefs[] =
375 {LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED),
376 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE),
377 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED),
378 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED),
379 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM),
380 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE),
381 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO),
382 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE),
383 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED),
384 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
385 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP),
386 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM),
387 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL),
388 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY),
389 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI)};
390constexpr auto ImageFileCharacteristics =
391 BUILD_ENUM_STRINGS(ImageFileCharacteristicsDefs);
392
393constexpr EnumStringDef<COFF::WindowsSubsystem> PEWindowsSubsystemDefs[] = {
394 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN),
395 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE),
396 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI),
397 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI),
398 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI),
399 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI),
400 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION),
401 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
402 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER),
403 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM),
404 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX),
405};
406constexpr auto PEWindowsSubsystem = BUILD_ENUM_STRINGS(PEWindowsSubsystemDefs);
407
408constexpr EnumStringDef<COFF::DLLCharacteristics> PEDLLCharacteristicsDefs[] = {
409 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA),
410 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE),
411 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY),
412 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT),
413 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION),
414 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH),
415 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND),
416 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER),
417 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER),
418 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF),
419 LLVM_READOBJ_ENUM_ENT(COFF,
420 IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
421};
422constexpr auto PEDLLCharacteristics =
423 BUILD_ENUM_STRINGS(PEDLLCharacteristicsDefs);
424
425// clang-format off
426constexpr EnumStringDef<COFF::ExtendedDLLCharacteristics> PEExtendedDLLCharacteristicsDefs[] = {
427 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT ),
428 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT_STRICT_MODE ),
429 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_SET_CONTEXT_IP_VALIDATION_RELAXED_MODE),
430 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_DYNAMIC_APIS_ALLOW_IN_PROC_ONLY ),
431 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_RESERVED_1 ),
432 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_RESERVED_2 ),
433 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_FORWARD_CFI_COMPAT ),
434 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_HOTPATCH_COMPATIBLE ),
435};
436constexpr auto PEExtendedDLLCharacteristics = BUILD_ENUM_STRINGS(PEExtendedDLLCharacteristicsDefs);
437// clang-format on
438
439constexpr EnumStringDef<COFF::SectionCharacteristics>
440 ImageSectionCharacteristicsDefs[] = {
441 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD),
442 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD),
443 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE),
444 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA),
445 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
446 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER),
447 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO),
448 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE),
449 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT),
450 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL),
451 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE),
452 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT),
453 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED),
454 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD),
455 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES),
456 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES),
457 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES),
458 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES),
459 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES),
460 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES),
461 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES),
462 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES),
463 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES),
464 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES),
465 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES),
466 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES),
467 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES),
468 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES),
469 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL),
470 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE),
471 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED),
472 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED),
473 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED),
474 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE),
475 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ),
476 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE)};
477constexpr auto ImageSectionCharacteristics =
478 BUILD_ENUM_STRINGS(ImageSectionCharacteristicsDefs);
479
480constexpr EnumStringDef<COFF::SymbolBaseType> ImageSymTypeDefs[] = {
481 {.Names: {"Null"}, .Value: COFF::IMAGE_SYM_TYPE_NULL},
482 {.Names: {"Void"}, .Value: COFF::IMAGE_SYM_TYPE_VOID},
483 {.Names: {"Char"}, .Value: COFF::IMAGE_SYM_TYPE_CHAR},
484 {.Names: {"Short"}, .Value: COFF::IMAGE_SYM_TYPE_SHORT},
485 {.Names: {"Int"}, .Value: COFF::IMAGE_SYM_TYPE_INT},
486 {.Names: {"Long"}, .Value: COFF::IMAGE_SYM_TYPE_LONG},
487 {.Names: {"Float"}, .Value: COFF::IMAGE_SYM_TYPE_FLOAT},
488 {.Names: {"Double"}, .Value: COFF::IMAGE_SYM_TYPE_DOUBLE},
489 {.Names: {"Struct"}, .Value: COFF::IMAGE_SYM_TYPE_STRUCT},
490 {.Names: {"Union"}, .Value: COFF::IMAGE_SYM_TYPE_UNION},
491 {.Names: {"Enum"}, .Value: COFF::IMAGE_SYM_TYPE_ENUM},
492 {.Names: {"MOE"}, .Value: COFF::IMAGE_SYM_TYPE_MOE},
493 {.Names: {"Byte"}, .Value: COFF::IMAGE_SYM_TYPE_BYTE},
494 {.Names: {"Word"}, .Value: COFF::IMAGE_SYM_TYPE_WORD},
495 {.Names: {"UInt"}, .Value: COFF::IMAGE_SYM_TYPE_UINT},
496 {.Names: {"DWord"}, .Value: COFF::IMAGE_SYM_TYPE_DWORD},
497};
498constexpr auto ImageSymType = BUILD_ENUM_STRINGS(ImageSymTypeDefs);
499
500constexpr EnumStringDef<COFF::SymbolComplexType> ImageSymDTypeDefs[] = {
501 {.Names: {"Null"}, .Value: COFF::IMAGE_SYM_DTYPE_NULL},
502 {.Names: {"Pointer"}, .Value: COFF::IMAGE_SYM_DTYPE_POINTER},
503 {.Names: {"Function"}, .Value: COFF::IMAGE_SYM_DTYPE_FUNCTION},
504 {.Names: {"Array"}, .Value: COFF::IMAGE_SYM_DTYPE_ARRAY},
505};
506constexpr auto ImageSymDType = BUILD_ENUM_STRINGS(ImageSymDTypeDefs);
507
508constexpr EnumStringDef<COFF::SymbolStorageClass> ImageSymClassDefs[] = {
509 {.Names: {"EndOfFunction"}, .Value: COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION},
510 {.Names: {"Null"}, .Value: COFF::IMAGE_SYM_CLASS_NULL},
511 {.Names: {"Automatic"}, .Value: COFF::IMAGE_SYM_CLASS_AUTOMATIC},
512 {.Names: {"External"}, .Value: COFF::IMAGE_SYM_CLASS_EXTERNAL},
513 {.Names: {"Static"}, .Value: COFF::IMAGE_SYM_CLASS_STATIC},
514 {.Names: {"Register"}, .Value: COFF::IMAGE_SYM_CLASS_REGISTER},
515 {.Names: {"ExternalDef"}, .Value: COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF},
516 {.Names: {"Label"}, .Value: COFF::IMAGE_SYM_CLASS_LABEL},
517 {.Names: {"UndefinedLabel"}, .Value: COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL},
518 {.Names: {"MemberOfStruct"}, .Value: COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT},
519 {.Names: {"Argument"}, .Value: COFF::IMAGE_SYM_CLASS_ARGUMENT},
520 {.Names: {"StructTag"}, .Value: COFF::IMAGE_SYM_CLASS_STRUCT_TAG},
521 {.Names: {"MemberOfUnion"}, .Value: COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION},
522 {.Names: {"UnionTag"}, .Value: COFF::IMAGE_SYM_CLASS_UNION_TAG},
523 {.Names: {"TypeDefinition"}, .Value: COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION},
524 {.Names: {"UndefinedStatic"}, .Value: COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC},
525 {.Names: {"EnumTag"}, .Value: COFF::IMAGE_SYM_CLASS_ENUM_TAG},
526 {.Names: {"MemberOfEnum"}, .Value: COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM},
527 {.Names: {"RegisterParam"}, .Value: COFF::IMAGE_SYM_CLASS_REGISTER_PARAM},
528 {.Names: {"BitField"}, .Value: COFF::IMAGE_SYM_CLASS_BIT_FIELD},
529 {.Names: {"Block"}, .Value: COFF::IMAGE_SYM_CLASS_BLOCK},
530 {.Names: {"Function"}, .Value: COFF::IMAGE_SYM_CLASS_FUNCTION},
531 {.Names: {"EndOfStruct"}, .Value: COFF::IMAGE_SYM_CLASS_END_OF_STRUCT},
532 {.Names: {"File"}, .Value: COFF::IMAGE_SYM_CLASS_FILE},
533 {.Names: {"Section"}, .Value: COFF::IMAGE_SYM_CLASS_SECTION},
534 {.Names: {"WeakExternal"}, .Value: COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL},
535 {.Names: {"CLRToken"}, .Value: COFF::IMAGE_SYM_CLASS_CLR_TOKEN},
536};
537constexpr auto ImageSymClass = BUILD_ENUM_STRINGS(ImageSymClassDefs);
538
539constexpr EnumStringDef<COFF::COMDATType> ImageCOMDATSelectDefs[] = {
540 {.Names: {"NoDuplicates"}, .Value: COFF::IMAGE_COMDAT_SELECT_NODUPLICATES},
541 {.Names: {"Any"}, .Value: COFF::IMAGE_COMDAT_SELECT_ANY},
542 {.Names: {"SameSize"}, .Value: COFF::IMAGE_COMDAT_SELECT_SAME_SIZE},
543 {.Names: {"ExactMatch"}, .Value: COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH},
544 {.Names: {"Associative"}, .Value: COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE},
545 {.Names: {"Largest"}, .Value: COFF::IMAGE_COMDAT_SELECT_LARGEST},
546 {.Names: {"Newest"}, .Value: COFF::IMAGE_COMDAT_SELECT_NEWEST},
547};
548constexpr auto ImageCOMDATSelect = BUILD_ENUM_STRINGS(ImageCOMDATSelectDefs);
549
550constexpr EnumStringDef<COFF::DebugType> ImageDebugTypeDefs[] = {
551 {.Names: {"Unknown"}, .Value: COFF::IMAGE_DEBUG_TYPE_UNKNOWN},
552 {.Names: {"COFF"}, .Value: COFF::IMAGE_DEBUG_TYPE_COFF},
553 {.Names: {"CodeView"}, .Value: COFF::IMAGE_DEBUG_TYPE_CODEVIEW},
554 {.Names: {"FPO"}, .Value: COFF::IMAGE_DEBUG_TYPE_FPO},
555 {.Names: {"Misc"}, .Value: COFF::IMAGE_DEBUG_TYPE_MISC},
556 {.Names: {"Exception"}, .Value: COFF::IMAGE_DEBUG_TYPE_EXCEPTION},
557 {.Names: {"Fixup"}, .Value: COFF::IMAGE_DEBUG_TYPE_FIXUP},
558 {.Names: {"OmapToSrc"}, .Value: COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC},
559 {.Names: {"OmapFromSrc"}, .Value: COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC},
560 {.Names: {"Borland"}, .Value: COFF::IMAGE_DEBUG_TYPE_BORLAND},
561 {.Names: {"Reserved10"}, .Value: COFF::IMAGE_DEBUG_TYPE_RESERVED10},
562 {.Names: {"CLSID"}, .Value: COFF::IMAGE_DEBUG_TYPE_CLSID},
563 {.Names: {"VCFeature"}, .Value: COFF::IMAGE_DEBUG_TYPE_VC_FEATURE},
564 {.Names: {"POGO"}, .Value: COFF::IMAGE_DEBUG_TYPE_POGO},
565 {.Names: {"ILTCG"}, .Value: COFF::IMAGE_DEBUG_TYPE_ILTCG},
566 {.Names: {"MPX"}, .Value: COFF::IMAGE_DEBUG_TYPE_MPX},
567 {.Names: {"Repro"}, .Value: COFF::IMAGE_DEBUG_TYPE_REPRO},
568 {.Names: {"ExtendedDLLCharacteristics"},
569 .Value: COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS},
570};
571constexpr auto ImageDebugType = BUILD_ENUM_STRINGS(ImageDebugTypeDefs);
572
573constexpr EnumStringDef<COFF::WeakExternalCharacteristics>
574 WeakExternalCharacteristicsDefs[] = {
575 {.Names: {"NoLibrary"}, .Value: COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY},
576 {.Names: {"Library"}, .Value: COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY},
577 {.Names: {"Alias"}, .Value: COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS},
578 {.Names: {"AntiDependency"}, .Value: COFF::IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY},
579};
580constexpr auto WeakExternalCharacteristics =
581 BUILD_ENUM_STRINGS(WeakExternalCharacteristicsDefs);
582
583constexpr EnumStringDef<uint32_t> SubSectionTypesDefs[] = {
584 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
585 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
586 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
587 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
588 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
589 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
590 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
591 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
592 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
593 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
594 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
595 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
596 LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
597};
598constexpr auto SubSectionTypes = BUILD_ENUM_STRINGS(SubSectionTypesDefs);
599
600constexpr EnumStringDef<uint32_t> FrameDataFlagsDefs[] = {
601 LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
602 LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
603 LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
604};
605constexpr auto FrameDataFlags = BUILD_ENUM_STRINGS(FrameDataFlagsDefs);
606
607constexpr EnumStringDef<uint8_t> FileChecksumKindNamesDefs[] = {
608 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
609 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
610 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
611 LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
612};
613constexpr auto FileChecksumKindNames =
614 BUILD_ENUM_STRINGS(FileChecksumKindNamesDefs);
615
616constexpr EnumStringDef<uint32_t> PELoadConfigGuardFlagsDefs[] = {
617 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_INSTRUMENTED),
618 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CFW_INSTRUMENTED),
619 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_FUNCTION_TABLE_PRESENT),
620 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, SECURITY_COOKIE_UNUSED),
621 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, PROTECT_DELAYLOAD_IAT),
622 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
623 DELAYLOAD_IAT_IN_ITS_OWN_SECTION),
624 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
625 CF_EXPORT_SUPPRESSION_INFO_PRESENT),
626 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_ENABLE_EXPORT_SUPPRESSION),
627 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags, CF_LONGJUMP_TABLE_PRESENT),
628 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
629 EH_CONTINUATION_TABLE_PRESENT),
630 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
631 CF_FUNCTION_TABLE_SIZE_5BYTES),
632 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
633 CF_FUNCTION_TABLE_SIZE_6BYTES),
634 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
635 CF_FUNCTION_TABLE_SIZE_7BYTES),
636 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
637 CF_FUNCTION_TABLE_SIZE_8BYTES),
638 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
639 CF_FUNCTION_TABLE_SIZE_9BYTES),
640 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
641 CF_FUNCTION_TABLE_SIZE_10BYTES),
642 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
643 CF_FUNCTION_TABLE_SIZE_11BYTES),
644 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
645 CF_FUNCTION_TABLE_SIZE_12BYTES),
646 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
647 CF_FUNCTION_TABLE_SIZE_13BYTES),
648 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
649 CF_FUNCTION_TABLE_SIZE_14BYTES),
650 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
651 CF_FUNCTION_TABLE_SIZE_15BYTES),
652 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
653 CF_FUNCTION_TABLE_SIZE_16BYTES),
654 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
655 CF_FUNCTION_TABLE_SIZE_17BYTES),
656 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
657 CF_FUNCTION_TABLE_SIZE_18BYTES),
658 LLVM_READOBJ_ENUM_CLASS_ENT(COFF::GuardFlags,
659 CF_FUNCTION_TABLE_SIZE_19BYTES),
660};
661constexpr auto PELoadConfigGuardFlags =
662 BUILD_ENUM_STRINGS(PELoadConfigGuardFlagsDefs);
663
664template <typename T>
665static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
666 COFFSymbolRef Symbol,
667 uint8_t AuxSymbolIdx, const T *&Aux) {
668 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
669 AuxData = AuxData.slice(N: AuxSymbolIdx * Obj->getSymbolTableEntrySize());
670 Aux = reinterpret_cast<const T *>(AuxData.data());
671 return std::error_code();
672}
673
674void COFFDumper::cacheRelocations() {
675 if (RelocCached)
676 return;
677 RelocCached = true;
678
679 for (const SectionRef &S : Obj->sections()) {
680 const coff_section *Section = Obj->getCOFFSection(Section: S);
681
682 auto &RM = RelocMap[Section];
683 append_range(C&: RM, R: S.relocations());
684
685 // Sort relocations by address.
686 llvm::sort(C&: RM, Comp: [](RelocationRef L, RelocationRef R) {
687 return L.getOffset() < R.getOffset();
688 });
689 }
690}
691
692void COFFDumper::printDataDirectory(uint32_t Index,
693 const std::string &FieldName) {
694 const data_directory *Data = Obj->getDataDirectory(index: Index);
695 if (!Data)
696 return;
697 W.printHex(Label: FieldName + "RVA", Value: Data->RelativeVirtualAddress);
698 W.printHex(Label: FieldName + "Size", Value: Data->Size);
699}
700
701void COFFDumper::printFileHeaders() {
702 time_t TDS = Obj->getTimeDateStamp();
703 char FormattedTime[20] = {};
704 strftime(s: FormattedTime, maxsize: 20, format: "%Y-%m-%d %H:%M:%S", tp: gmtime(timer: &TDS));
705
706 {
707 DictScope D(W, "ImageFileHeader");
708 W.printEnum(Label: "Machine", Value: Obj->getMachine(),
709 EnumValues: EnumStrings(ImageFileMachineType));
710 W.printNumber(Label: "SectionCount", Value: Obj->getNumberOfSections());
711 W.printHex(Label: "TimeDateStamp", Str: FormattedTime, Value: Obj->getTimeDateStamp());
712 W.printHex(Label: "PointerToSymbolTable", Value: Obj->getPointerToSymbolTable());
713 W.printNumber(Label: "SymbolCount", Value: Obj->getNumberOfSymbols());
714 W.printNumber(Label: "StringTableSize", Value: Obj->getStringTableSize());
715 W.printNumber(Label: "OptionalHeaderSize", Value: Obj->getSizeOfOptionalHeader());
716 W.printFlags(Label: "Characteristics", Value: Obj->getCharacteristics(),
717 Flags: EnumStrings(ImageFileCharacteristics));
718 }
719
720 // Print PE header. This header does not exist if this is an object file and
721 // not an executable.
722 if (const pe32_header *PEHeader = Obj->getPE32Header())
723 printPEHeader<pe32_header>(Hdr: PEHeader);
724
725 if (const pe32plus_header *PEPlusHeader = Obj->getPE32PlusHeader())
726 printPEHeader<pe32plus_header>(Hdr: PEPlusHeader);
727
728 if (const dos_header *DH = Obj->getDOSHeader())
729 printDOSHeader(DH);
730}
731
732void COFFDumper::printDOSHeader(const dos_header *DH) {
733 DictScope D(W, "DOSHeader");
734 W.printString(Label: "Magic", Value: StringRef(DH->Magic, sizeof(DH->Magic)));
735 W.printNumber(Label: "UsedBytesInTheLastPage", Value: DH->UsedBytesInTheLastPage);
736 W.printNumber(Label: "FileSizeInPages", Value: DH->FileSizeInPages);
737 W.printNumber(Label: "NumberOfRelocationItems", Value: DH->NumberOfRelocationItems);
738 W.printNumber(Label: "HeaderSizeInParagraphs", Value: DH->HeaderSizeInParagraphs);
739 W.printNumber(Label: "MinimumExtraParagraphs", Value: DH->MinimumExtraParagraphs);
740 W.printNumber(Label: "MaximumExtraParagraphs", Value: DH->MaximumExtraParagraphs);
741 W.printNumber(Label: "InitialRelativeSS", Value: DH->InitialRelativeSS);
742 W.printNumber(Label: "InitialSP", Value: DH->InitialSP);
743 W.printNumber(Label: "Checksum", Value: DH->Checksum);
744 W.printNumber(Label: "InitialIP", Value: DH->InitialIP);
745 W.printNumber(Label: "InitialRelativeCS", Value: DH->InitialRelativeCS);
746 W.printNumber(Label: "AddressOfRelocationTable", Value: DH->AddressOfRelocationTable);
747 W.printNumber(Label: "OverlayNumber", Value: DH->OverlayNumber);
748 W.printNumber(Label: "OEMid", Value: DH->OEMid);
749 W.printNumber(Label: "OEMinfo", Value: DH->OEMinfo);
750 W.printNumber(Label: "AddressOfNewExeHeader", Value: DH->AddressOfNewExeHeader);
751}
752
753template <class PEHeader> void COFFDumper::printPEHeader(const PEHeader *Hdr) {
754 DictScope D(W, "ImageOptionalHeader");
755 W.printHex("Magic", Hdr->Magic);
756 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
757 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
758 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
759 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
760 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
761 W.printHex("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
762 W.printHex("BaseOfCode", Hdr->BaseOfCode);
763 printBaseOfDataField(Hdr);
764 W.printHex("ImageBase", Hdr->ImageBase);
765 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
766 W.printNumber("FileAlignment", Hdr->FileAlignment);
767 W.printNumber("MajorOperatingSystemVersion",
768 Hdr->MajorOperatingSystemVersion);
769 W.printNumber("MinorOperatingSystemVersion",
770 Hdr->MinorOperatingSystemVersion);
771 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
772 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
773 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
774 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
775 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
776 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
777 W.printHex("CheckSum", Hdr->CheckSum);
778 W.printEnum("Subsystem", Hdr->Subsystem, EnumStrings(PEWindowsSubsystem));
779 W.printFlags("Characteristics", Hdr->DLLCharacteristics,
780 EnumStrings(PEDLLCharacteristics));
781 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
782 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
783 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
784 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
785 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
786
787 if (Hdr->NumberOfRvaAndSize > 0) {
788 DictScope D(W, "DataDirectory");
789 static const char *const directory[] = {"ExportTable",
790 "ImportTable",
791 "ResourceTable",
792 "ExceptionTable",
793 "CertificateTable",
794 "BaseRelocationTable",
795 "Debug",
796 "Architecture",
797 "GlobalPtr",
798 "TLSTable",
799 "LoadConfigTable",
800 "BoundImport",
801 "IAT",
802 "DelayImportDescriptor",
803 "CLRRuntimeHeader",
804 "Reserved"};
805
806 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
807 if (i < std::size(directory))
808 printDataDirectory(Index: i, FieldName: directory[i]);
809 else
810 printDataDirectory(Index: i, FieldName: "Unknown");
811 }
812}
813
814void COFFDumper::printCOFFDebugDirectory() {
815 ListScope LS(W, "DebugDirectory");
816 for (const debug_directory &D : Obj->debug_directories()) {
817 char FormattedTime[20] = {};
818 time_t TDS = D.TimeDateStamp;
819 strftime(s: FormattedTime, maxsize: 20, format: "%Y-%m-%d %H:%M:%S", tp: gmtime(timer: &TDS));
820 DictScope S(W, "DebugEntry");
821 W.printHex(Label: "Characteristics", Value: D.Characteristics);
822 W.printHex(Label: "TimeDateStamp", Str: FormattedTime, Value: D.TimeDateStamp);
823 W.printHex(Label: "MajorVersion", Value: D.MajorVersion);
824 W.printHex(Label: "MinorVersion", Value: D.MinorVersion);
825 W.printEnum(Label: "Type", Value: D.Type, EnumValues: EnumStrings(ImageDebugType));
826 W.printHex(Label: "SizeOfData", Value: D.SizeOfData);
827 W.printHex(Label: "AddressOfRawData", Value: D.AddressOfRawData);
828 W.printHex(Label: "PointerToRawData", Value: D.PointerToRawData);
829 // Ideally, if D.AddressOfRawData == 0, we should try to load the payload
830 // using D.PointerToRawData instead.
831 if (D.AddressOfRawData == 0)
832 continue;
833 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
834 const codeview::DebugInfo *DebugInfo;
835 StringRef PDBFileName;
836 if (Error E = Obj->getDebugPDBInfo(DebugDir: &D, Info&: DebugInfo, PDBFileName))
837 reportError(Err: std::move(E), Input: Obj->getFileName());
838
839 DictScope PDBScope(W, "PDBInfo");
840 W.printHex(Label: "PDBSignature", Value: DebugInfo->Signature.CVSignature);
841 if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
842 W.printString(
843 Label: "PDBGUID",
844 Value: formatv(Fmt: "{0}", Vals: fmt_guid(Item: DebugInfo->PDB70.Signature)).str());
845 W.printNumber(Label: "PDBAge", Value: DebugInfo->PDB70.Age);
846 W.printString(Label: "PDBFileName", Value: PDBFileName);
847 }
848 } else if (D.SizeOfData != 0) {
849 // FIXME: Data visualization for IMAGE_DEBUG_TYPE_VC_FEATURE and
850 // IMAGE_DEBUG_TYPE_POGO?
851 ArrayRef<uint8_t> RawData;
852 if (Error E = Obj->getRvaAndSizeAsBytes(RVA: D.AddressOfRawData, Size: D.SizeOfData,
853 Contents&: RawData))
854 reportError(Err: std::move(E), Input: Obj->getFileName());
855 if (D.Type == COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) {
856 // FIXME right now the only possible value would fit in 8 bits,
857 // but that might change in the future
858 uint16_t Characteristics = RawData[0];
859 W.printFlags(Label: "ExtendedCharacteristics", Value: Characteristics,
860 Flags: EnumStrings(PEExtendedDLLCharacteristics));
861 }
862 W.printBinaryBlock(Label: "RawData", Value: RawData);
863 }
864 }
865}
866
867void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
868 uint64_t EntrySize, PrintExtraCB PrintExtra) {
869 uintptr_t TableStart, TableEnd;
870 if (Error E = Obj->getVaPtr(VA: TableVA, Res&: TableStart))
871 reportError(Err: std::move(E), Input: Obj->getFileName());
872 if (Error E = Obj->getVaPtr(VA: TableVA + Count * EntrySize - 1, Res&: TableEnd))
873 reportError(Err: std::move(E), Input: Obj->getFileName());
874 TableEnd++;
875 for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
876 uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
877 raw_ostream &OS = W.startLine();
878 OS << W.hex(Value: Obj->getImageBase() + RVA);
879 if (PrintExtra)
880 PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
881 OS << '\n';
882 }
883}
884
885void COFFDumper::printCOFFLoadConfig() {
886 LoadConfigTables Tables;
887 if (Obj->is64())
888 printCOFFLoadConfig(Conf: Obj->getLoadConfig64(), Tables);
889 else
890 printCOFFLoadConfig(Conf: Obj->getLoadConfig32(), Tables);
891
892 if (auto CHPE = Obj->getCHPEMetadata()) {
893 ListScope LS(W, "CHPEMetadata");
894 W.printHex(Label: "Version", Value: CHPE->Version);
895
896 if (CHPE->CodeMapCount) {
897 ListScope CMLS(W, "CodeMap");
898
899 uintptr_t CodeMapInt;
900 if (Error E = Obj->getRvaPtr(Rva: CHPE->CodeMap, Res&: CodeMapInt))
901 reportError(Err: std::move(E), Input: Obj->getFileName());
902 auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
903 for (uint32_t i = 0; i < CHPE->CodeMapCount; i++) {
904 uint32_t Start = CodeMap[i].getStart();
905 W.startLine() << W.hex(Value: Start) << " - "
906 << W.hex(Value: Start + CodeMap[i].Length) << " ";
907 switch (CodeMap[i].getType()) {
908 case chpe_range_type::Arm64:
909 W.getOStream() << "ARM64\n";
910 break;
911 case chpe_range_type::Arm64EC:
912 W.getOStream() << "ARM64EC\n";
913 break;
914 case chpe_range_type::Amd64:
915 W.getOStream() << "X64\n";
916 break;
917 default:
918 W.getOStream() << W.hex(Value: CodeMap[i].StartOffset & 3) << "\n";
919 break;
920 }
921 }
922 } else {
923 W.printNumber(Label: "CodeMap", Value: CHPE->CodeMap);
924 }
925
926 if (CHPE->CodeRangesToEntryPointsCount) {
927 ListScope CRLS(W, "CodeRangesToEntryPoints");
928
929 uintptr_t CodeRangesInt;
930 if (Error E =
931 Obj->getRvaPtr(Rva: CHPE->CodeRangesToEntryPoints, Res&: CodeRangesInt))
932 reportError(Err: std::move(E), Input: Obj->getFileName());
933 auto CodeRanges =
934 reinterpret_cast<const chpe_code_range_entry *>(CodeRangesInt);
935 for (uint32_t i = 0; i < CHPE->CodeRangesToEntryPointsCount; i++) {
936 W.startLine() << W.hex(Value: CodeRanges[i].StartRva) << " - "
937 << W.hex(Value: CodeRanges[i].EndRva) << " -> "
938 << W.hex(Value: CodeRanges[i].EntryPoint) << "\n";
939 }
940 } else {
941 W.printNumber(Label: "CodeRangesToEntryPoints", Value: CHPE->CodeRangesToEntryPoints);
942 }
943
944 if (CHPE->RedirectionMetadataCount) {
945 ListScope RMLS(W, "RedirectionMetadata");
946
947 uintptr_t RedirMetadataInt;
948 if (Error E = Obj->getRvaPtr(Rva: CHPE->RedirectionMetadata, Res&: RedirMetadataInt))
949 reportError(Err: std::move(E), Input: Obj->getFileName());
950 auto RedirMetadata =
951 reinterpret_cast<const chpe_redirection_entry *>(RedirMetadataInt);
952 for (uint32_t i = 0; i < CHPE->RedirectionMetadataCount; i++) {
953 W.startLine() << W.hex(Value: RedirMetadata[i].Source) << " -> "
954 << W.hex(Value: RedirMetadata[i].Destination) << "\n";
955 }
956 } else {
957 W.printNumber(Label: "RedirectionMetadata", Value: CHPE->RedirectionMetadata);
958 }
959
960 W.printHex(Label: "__os_arm64x_dispatch_call_no_redirect",
961 Value: CHPE->__os_arm64x_dispatch_call_no_redirect);
962 W.printHex(Label: "__os_arm64x_dispatch_ret", Value: CHPE->__os_arm64x_dispatch_ret);
963 W.printHex(Label: "__os_arm64x_dispatch_call", Value: CHPE->__os_arm64x_dispatch_call);
964 W.printHex(Label: "__os_arm64x_dispatch_icall", Value: CHPE->__os_arm64x_dispatch_icall);
965 W.printHex(Label: "__os_arm64x_dispatch_icall_cfg",
966 Value: CHPE->__os_arm64x_dispatch_icall_cfg);
967 W.printHex(Label: "AlternateEntryPoint", Value: CHPE->AlternateEntryPoint);
968 W.printHex(Label: "AuxiliaryIAT", Value: CHPE->AuxiliaryIAT);
969 W.printHex(Label: "GetX64InformationFunctionPointer",
970 Value: CHPE->GetX64InformationFunctionPointer);
971 W.printHex(Label: "SetX64InformationFunctionPointer",
972 Value: CHPE->SetX64InformationFunctionPointer);
973 W.printHex(Label: "ExtraRFETable", Value: CHPE->ExtraRFETable);
974 W.printHex(Label: "ExtraRFETableSize", Value: CHPE->ExtraRFETableSize);
975 W.printHex(Label: "__os_arm64x_dispatch_fptr", Value: CHPE->__os_arm64x_dispatch_fptr);
976 W.printHex(Label: "AuxiliaryIATCopy", Value: CHPE->AuxiliaryIATCopy);
977
978 if (CHPE->Version >= 2) {
979 W.printHex(Label: "AuxiliaryDelayloadIAT", Value: CHPE->AuxiliaryDelayloadIAT);
980 W.printHex(Label: "AuxiliaryDelayloadIATCopy", Value: CHPE->AuxiliaryDelayloadIATCopy);
981 W.printHex(Label: "HybridImageInfoBitfield", Value: CHPE->HybridImageInfoBitfield);
982 }
983 }
984
985 if (Tables.SEHTableVA) {
986 ListScope LS(W, "SEHTable");
987 printRVATable(TableVA: Tables.SEHTableVA, Count: Tables.SEHTableCount, EntrySize: 4);
988 }
989
990 auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
991 uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
992 if (Flags)
993 OS << " flags " << utohexstr(X: Flags);
994 };
995
996 // The stride gives the number of extra bytes in addition to the 4-byte
997 // RVA of each entry in the table. As of writing only a 1-byte extra flag
998 // has been defined.
999 uint32_t Stride = Tables.GuardFlags >> 28;
1000 PrintExtraCB PrintExtra = Stride == 1 ? +PrintGuardFlags : nullptr;
1001
1002 if (Tables.GuardFidTableVA) {
1003 ListScope LS(W, "GuardFidTable");
1004 printRVATable(TableVA: Tables.GuardFidTableVA, Count: Tables.GuardFidTableCount, EntrySize: 4 + Stride,
1005 PrintExtra);
1006 }
1007
1008 if (Tables.GuardIatTableVA) {
1009 ListScope LS(W, "GuardIatTable");
1010 printRVATable(TableVA: Tables.GuardIatTableVA, Count: Tables.GuardIatTableCount, EntrySize: 4 + Stride,
1011 PrintExtra);
1012 }
1013
1014 if (Tables.GuardLJmpTableVA) {
1015 ListScope LS(W, "GuardLJmpTable");
1016 printRVATable(TableVA: Tables.GuardLJmpTableVA, Count: Tables.GuardLJmpTableCount,
1017 EntrySize: 4 + Stride, PrintExtra);
1018 }
1019
1020 if (Tables.GuardEHContTableVA) {
1021 ListScope LS(W, "GuardEHContTable");
1022 printRVATable(TableVA: Tables.GuardEHContTableVA, Count: Tables.GuardEHContTableCount,
1023 EntrySize: 4 + Stride, PrintExtra);
1024 }
1025
1026 if (const coff_dynamic_reloc_table *DynRelocTable =
1027 Obj->getDynamicRelocTable()) {
1028 ListScope LS(W, "DynamicRelocations");
1029 W.printHex(Label: "Version", Value: DynRelocTable->Version);
1030 for (auto reloc : Obj->dynamic_relocs()) {
1031 switch (reloc.getType()) {
1032 case COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X: {
1033 ListScope TLS(W, "Arm64X");
1034 for (auto Arm64XReloc : reloc.arm64x_relocs()) {
1035 ListScope ELS(W, "Entry");
1036 W.printHex(Label: "RVA", Value: Arm64XReloc.getRVA());
1037 switch (Arm64XReloc.getType()) {
1038 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
1039 W.printString(Label: "Type", Value: "ZEROFILL");
1040 W.printHex(Label: "Size", Value: Arm64XReloc.getSize());
1041 break;
1042 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
1043 W.printString(Label: "Type", Value: "VALUE");
1044 W.printHex(Label: "Size", Value: Arm64XReloc.getSize());
1045 W.printHex(Label: "Value", Value: Arm64XReloc.getValue());
1046 break;
1047 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
1048 W.printString(Label: "Type", Value: "DELTA");
1049 W.printNumber(Label: "Value",
1050 Value: static_cast<int32_t>(Arm64XReloc.getValue()));
1051 break;
1052 }
1053 }
1054 break;
1055 }
1056 default:
1057 W.printHex(Label: "Type", Value: reloc.getType());
1058 break;
1059 }
1060 }
1061 }
1062}
1063
1064template <typename T>
1065void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
1066 if (!Conf)
1067 return;
1068
1069 ListScope LS(W, "LoadConfig");
1070 char FormattedTime[20] = {};
1071 time_t TDS = Conf->TimeDateStamp;
1072 strftime(s: FormattedTime, maxsize: 20, format: "%Y-%m-%d %H:%M:%S", tp: gmtime(timer: &TDS));
1073 W.printHex("Size", Conf->Size);
1074
1075 // Print everything before SecurityCookie. The vast majority of images today
1076 // have all these fields.
1077 if (Conf->Size < offsetof(T, SEHandlerTable))
1078 return;
1079 W.printHex(Label: "TimeDateStamp", Str: FormattedTime, Value: TDS);
1080 W.printHex("MajorVersion", Conf->MajorVersion);
1081 W.printHex("MinorVersion", Conf->MinorVersion);
1082 W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
1083 W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
1084 W.printHex("CriticalSectionDefaultTimeout",
1085 Conf->CriticalSectionDefaultTimeout);
1086 W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
1087 W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
1088 W.printHex("LockPrefixTable", Conf->LockPrefixTable);
1089 W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
1090 W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
1091 W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
1092 W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
1093 W.printHex("CSDVersion", Conf->CSDVersion);
1094 W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
1095 W.printHex("EditList", Conf->EditList);
1096 W.printHex("SecurityCookie", Conf->SecurityCookie);
1097
1098 // Print the safe SEH table if present.
1099 if (Conf->Size < offsetof(T, GuardCFCheckFunction))
1100 return;
1101 W.printHex("SEHandlerTable", Conf->SEHandlerTable);
1102 W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
1103
1104 Tables.SEHTableVA = Conf->SEHandlerTable;
1105 Tables.SEHTableCount = Conf->SEHandlerCount;
1106
1107 // Print everything before CodeIntegrity. (2015)
1108 if (Conf->Size < offsetof(T, CodeIntegrity))
1109 return;
1110 W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
1111 W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
1112 W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
1113 W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
1114 W.printFlags("GuardFlags", Conf->GuardFlags,
1115 EnumStrings(PELoadConfigGuardFlags),
1116 (uint32_t)COFF::GuardFlags::CF_FUNCTION_TABLE_SIZE_MASK);
1117
1118 Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
1119 Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
1120 Tables.GuardFlags = Conf->GuardFlags;
1121
1122 // Print everything before Reserved3. (2017)
1123 if (Conf->Size < offsetof(T, Reserved3))
1124 return;
1125 W.printHex("GuardAddressTakenIatEntryTable",
1126 Conf->GuardAddressTakenIatEntryTable);
1127 W.printNumber("GuardAddressTakenIatEntryCount",
1128 Conf->GuardAddressTakenIatEntryCount);
1129 W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
1130 W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
1131 W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
1132 W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
1133 W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
1134 W.printHex("GuardRFFailureRoutineFunctionPointer",
1135 Conf->GuardRFFailureRoutineFunctionPointer);
1136 W.printHex("DynamicValueRelocTableOffset",
1137 Conf->DynamicValueRelocTableOffset);
1138 W.printNumber("DynamicValueRelocTableSection",
1139 Conf->DynamicValueRelocTableSection);
1140 W.printHex("GuardRFVerifyStackPointerFunctionPointer",
1141 Conf->GuardRFVerifyStackPointerFunctionPointer);
1142 W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
1143
1144 Tables.GuardIatTableVA = Conf->GuardAddressTakenIatEntryTable;
1145 Tables.GuardIatTableCount = Conf->GuardAddressTakenIatEntryCount;
1146
1147 Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
1148 Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
1149
1150 // Print the rest. (2019)
1151 if (Conf->Size < sizeof(T))
1152 return;
1153 W.printHex("EnclaveConfigurationPointer", Conf->EnclaveConfigurationPointer);
1154 W.printHex("VolatileMetadataPointer", Conf->VolatileMetadataPointer);
1155 W.printHex("GuardEHContinuationTable", Conf->GuardEHContinuationTable);
1156 W.printNumber("GuardEHContinuationCount", Conf->GuardEHContinuationCount);
1157
1158 Tables.GuardEHContTableVA = Conf->GuardEHContinuationTable;
1159 Tables.GuardEHContTableCount = Conf->GuardEHContinuationCount;
1160}
1161
1162void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
1163 W.printHex(Label: "BaseOfData", Value: Hdr->BaseOfData);
1164}
1165
1166void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
1167
1168void COFFDumper::printCodeViewDebugInfo() {
1169 // Print types first to build CVUDTNames, then print symbols.
1170 for (const SectionRef &S : Obj->sections()) {
1171 StringRef SectionName = unwrapOrError(Input: Obj->getFileName(), EO: S.getName());
1172 // .debug$T is a standard CodeView type section, while .debug$P is the same
1173 // format but used for MSVC precompiled header object files.
1174 if (SectionName == ".debug$T" || SectionName == ".debug$P")
1175 printCodeViewTypeSection(SectionName, Section: S);
1176 }
1177 for (const SectionRef &S : Obj->sections()) {
1178 StringRef SectionName = unwrapOrError(Input: Obj->getFileName(), EO: S.getName());
1179 if (SectionName == ".debug$S")
1180 printCodeViewSymbolSection(SectionName, Section: S);
1181 }
1182}
1183
1184void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
1185 while (Reader.bytesRemaining() > 0 &&
1186 (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
1187 // The section consists of a number of subsection in the following format:
1188 // |SubSectionType|SubSectionSize|Contents...|
1189 uint32_t SubType, SubSectionSize;
1190
1191 if (Error E = Reader.readInteger(Dest&: SubType))
1192 reportError(Err: std::move(E), Input: Obj->getFileName());
1193 if (Error E = Reader.readInteger(Dest&: SubSectionSize))
1194 reportError(Err: std::move(E), Input: Obj->getFileName());
1195
1196 StringRef Contents;
1197 if (Error E = Reader.readFixedString(Dest&: Contents, Length: SubSectionSize))
1198 reportError(Err: std::move(E), Input: Obj->getFileName());
1199
1200 BinaryStreamRef ST(Contents, llvm::endianness::little);
1201 switch (DebugSubsectionKind(SubType)) {
1202 case DebugSubsectionKind::FileChecksums:
1203 if (Error E = CVFileChecksumTable.initialize(Stream: ST))
1204 reportError(Err: std::move(E), Input: Obj->getFileName());
1205 break;
1206 case DebugSubsectionKind::StringTable:
1207 if (Error E = CVStringTable.initialize(Contents: ST))
1208 reportError(Err: std::move(E), Input: Obj->getFileName());
1209 break;
1210 default:
1211 break;
1212 }
1213
1214 uint32_t PaddedSize = alignTo(Value: SubSectionSize, Align: 4);
1215 if (Error E = Reader.skip(Amount: PaddedSize - SubSectionSize))
1216 reportError(Err: std::move(E), Input: Obj->getFileName());
1217 }
1218}
1219
1220void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
1221 const SectionRef &Section) {
1222 StringRef SectionContents =
1223 unwrapOrError(Input: Obj->getFileName(), EO: Section.getContents());
1224 StringRef Data = SectionContents;
1225
1226 SmallVector<StringRef, 10> FunctionNames;
1227 StringMap<StringRef> FunctionLineTables;
1228
1229 ListScope D(W, "CodeViewDebugInfo");
1230 // Print the section to allow correlation with printSectionHeaders.
1231 W.printNumber(Label: "Section", Str: SectionName, Value: Obj->getSectionID(Sec: Section));
1232
1233 uint32_t Magic;
1234 if (Error E = consume(Data, Item&: Magic))
1235 reportError(Err: std::move(E), Input: Obj->getFileName());
1236
1237 W.printHex(Label: "Magic", Value: Magic);
1238 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1239 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1240 Input: Obj->getFileName());
1241
1242 BinaryStreamReader FSReader(Data, llvm::endianness::little);
1243 initializeFileAndStringTables(Reader&: FSReader);
1244
1245 // TODO: Convert this over to using ModuleSubstreamVisitor.
1246 while (!Data.empty()) {
1247 // The section consists of a number of subsection in the following format:
1248 // |SubSectionType|SubSectionSize|Contents...|
1249 uint32_t SubType, SubSectionSize;
1250 if (Error E = consume(Data, Item&: SubType))
1251 reportError(Err: std::move(E), Input: Obj->getFileName());
1252 if (Error E = consume(Data, Item&: SubSectionSize))
1253 reportError(Err: std::move(E), Input: Obj->getFileName());
1254
1255 ListScope S(W, "Subsection");
1256 // Dump the subsection as normal even if the ignore bit is set.
1257 if (SubType & SubsectionIgnoreFlag) {
1258 W.printHex(Label: "IgnoredSubsectionKind", Value: SubType);
1259 SubType &= ~SubsectionIgnoreFlag;
1260 }
1261 W.printEnum(Label: "SubSectionType", Value: SubType, EnumValues: EnumStrings(SubSectionTypes));
1262 W.printHex(Label: "SubSectionSize", Value: SubSectionSize);
1263
1264 // Get the contents of the subsection.
1265 if (SubSectionSize > Data.size())
1266 return reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1267 Input: Obj->getFileName());
1268 StringRef Contents = Data.substr(Start: 0, N: SubSectionSize);
1269
1270 // Add SubSectionSize to the current offset and align that offset to find
1271 // the next subsection.
1272 size_t SectionOffset = Data.data() - SectionContents.data();
1273 size_t NextOffset = SectionOffset + SubSectionSize;
1274 NextOffset = alignTo(Value: NextOffset, Align: 4);
1275 if (NextOffset > SectionContents.size())
1276 return reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1277 Input: Obj->getFileName());
1278 Data = SectionContents.drop_front(N: NextOffset);
1279
1280 // Optionally print the subsection bytes in case our parsing gets confused
1281 // later.
1282 if (opts::CodeViewSubsectionBytes)
1283 printBinaryBlockWithRelocs(Label: "SubSectionContents", Sec: Section, SectionContents,
1284 Block: Contents);
1285
1286 switch (DebugSubsectionKind(SubType)) {
1287 case DebugSubsectionKind::Symbols:
1288 printCodeViewSymbolsSubsection(Subsection: Contents, Section, SectionContents);
1289 break;
1290
1291 case DebugSubsectionKind::InlineeLines:
1292 printCodeViewInlineeLines(Subsection: Contents);
1293 break;
1294
1295 case DebugSubsectionKind::FileChecksums:
1296 printCodeViewFileChecksums(Subsection: Contents);
1297 break;
1298
1299 case DebugSubsectionKind::Lines: {
1300 // Holds a PC to file:line table. Some data to parse this subsection is
1301 // stored in the other subsections, so just check sanity and store the
1302 // pointers for deferred processing.
1303
1304 if (SubSectionSize < 12) {
1305 // There should be at least three words to store two function
1306 // relocations and size of the code.
1307 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1308 Input: Obj->getFileName());
1309 return;
1310 }
1311
1312 StringRef LinkageName;
1313 if (std::error_code EC = resolveSymbolName(Section: Obj->getCOFFSection(Section),
1314 Offset: SectionOffset, Name&: LinkageName))
1315 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1316
1317 W.printString(Label: "LinkageName", Value: LinkageName);
1318 auto [It, Inserted] =
1319 FunctionLineTables.try_emplace(Key: LinkageName, Args&: Contents);
1320 if (!Inserted) {
1321 // Saw debug info for this function already?
1322 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1323 Input: Obj->getFileName());
1324 return;
1325 }
1326
1327 FunctionNames.push_back(Elt: LinkageName);
1328 break;
1329 }
1330 case DebugSubsectionKind::FrameData: {
1331 // First four bytes is a relocation against the function.
1332 BinaryStreamReader SR(Contents, llvm::endianness::little);
1333
1334 DebugFrameDataSubsectionRef FrameData;
1335 if (Error E = FrameData.initialize(Reader: SR))
1336 reportError(Err: std::move(E), Input: Obj->getFileName());
1337
1338 StringRef LinkageName;
1339 if (std::error_code EC =
1340 resolveSymbolName(Section: Obj->getCOFFSection(Section), SectionContents,
1341 RelocPtr: FrameData.getRelocPtr(), Name&: LinkageName))
1342 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1343 W.printString(Label: "LinkageName", Value: LinkageName);
1344
1345 // To find the active frame description, search this array for the
1346 // smallest PC range that includes the current PC.
1347 for (const auto &FD : FrameData) {
1348 StringRef FrameFunc = unwrapOrError(
1349 Input: Obj->getFileName(), EO: CVStringTable.getString(Offset: FD.FrameFunc));
1350
1351 DictScope S(W, "FrameData");
1352 W.printHex(Label: "RvaStart", Value: FD.RvaStart);
1353 W.printHex(Label: "CodeSize", Value: FD.CodeSize);
1354 W.printHex(Label: "LocalSize", Value: FD.LocalSize);
1355 W.printHex(Label: "ParamsSize", Value: FD.ParamsSize);
1356 W.printHex(Label: "MaxStackSize", Value: FD.MaxStackSize);
1357 W.printHex(Label: "PrologSize", Value: FD.PrologSize);
1358 W.printHex(Label: "SavedRegsSize", Value: FD.SavedRegsSize);
1359 W.printFlags(Label: "Flags", Value: FD.Flags, Flags: EnumStrings(FrameDataFlags));
1360
1361 // The FrameFunc string is a small RPN program. It can be broken up into
1362 // statements that end in the '=' operator, which assigns the value on
1363 // the top of the stack to the previously pushed variable. Variables can
1364 // be temporary values ($T0) or physical registers ($esp). Print each
1365 // assignment on its own line to make these programs easier to read.
1366 {
1367 ListScope FFS(W, "FrameFunc");
1368 while (!FrameFunc.empty()) {
1369 size_t EqOrEnd = FrameFunc.find(C: '=');
1370 if (EqOrEnd == StringRef::npos)
1371 EqOrEnd = FrameFunc.size();
1372 else
1373 ++EqOrEnd;
1374 StringRef Stmt = FrameFunc.substr(Start: 0, N: EqOrEnd);
1375 W.printString(Value: Stmt);
1376 FrameFunc = FrameFunc.drop_front(N: EqOrEnd).trim();
1377 }
1378 }
1379 }
1380 break;
1381 }
1382
1383 // Do nothing for unrecognized subsections.
1384 default:
1385 break;
1386 }
1387 W.flush();
1388 }
1389
1390 // Dump the line tables now that we've read all the subsections and know all
1391 // the required information.
1392 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1393 StringRef Name = FunctionNames[I];
1394 ListScope S(W, "FunctionLineTable");
1395 W.printString(Label: "LinkageName", Value: Name);
1396
1397 BinaryStreamReader Reader(FunctionLineTables[Name],
1398 llvm::endianness::little);
1399
1400 DebugLinesSubsectionRef LineInfo;
1401 if (Error E = LineInfo.initialize(Reader))
1402 reportError(Err: std::move(E), Input: Obj->getFileName());
1403
1404 W.printHex(Label: "Flags", Value: LineInfo.header()->Flags);
1405 W.printHex(Label: "CodeSize", Value: LineInfo.header()->CodeSize);
1406 for (const auto &Entry : LineInfo) {
1407
1408 ListScope S(W, "FilenameSegment");
1409 printFileNameForOffset(Label: "Filename", FileOffset: Entry.NameIndex);
1410 uint32_t ColumnIndex = 0;
1411 for (const auto &Line : Entry.LineNumbers) {
1412 if (Line.Offset >= LineInfo.header()->CodeSize) {
1413 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1414 Input: Obj->getFileName());
1415 return;
1416 }
1417
1418 std::string PC = std::string(formatv(Fmt: "+{0:X}", Vals: uint32_t(Line.Offset)));
1419 ListScope PCScope(W, PC);
1420 codeview::LineInfo LI(Line.Flags);
1421
1422 if (LI.isAlwaysStepInto())
1423 W.printString(Label: "StepInto", Value: StringRef("Always"));
1424 else if (LI.isNeverStepInto())
1425 W.printString(Label: "StepInto", Value: StringRef("Never"));
1426 else
1427 W.printNumber(Label: "LineNumberStart", Value: LI.getStartLine());
1428 W.printNumber(Label: "LineNumberEndDelta", Value: LI.getLineDelta());
1429 W.printBoolean(Label: "IsStatement", Value: LI.isStatement());
1430 if (LineInfo.hasColumnInfo()) {
1431 W.printNumber(Label: "ColStart", Value: Entry.Columns[ColumnIndex].StartColumn);
1432 W.printNumber(Label: "ColEnd", Value: Entry.Columns[ColumnIndex].EndColumn);
1433 ++ColumnIndex;
1434 }
1435 }
1436 }
1437 }
1438}
1439
1440void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1441 const SectionRef &Section,
1442 StringRef SectionContents) {
1443 ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1444 Subsection.bytes_end());
1445 auto CODD = std::make_unique<COFFObjectDumpDelegate>(args&: *this, args: Section, args&: Obj,
1446 args&: SectionContents);
1447 CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1448 CompilationCPUType, opts::CodeViewSubsectionBytes);
1449 CVSymbolArray Symbols;
1450 BinaryStreamReader Reader(BinaryData, llvm::endianness::little);
1451 if (Error E = Reader.readArray(Array&: Symbols, Size: Reader.getLength())) {
1452 W.flush();
1453 reportError(Err: std::move(E), Input: Obj->getFileName());
1454 }
1455
1456 if (Error E = CVSD.dump(Symbols)) {
1457 W.flush();
1458 reportError(Err: std::move(E), Input: Obj->getFileName());
1459 }
1460 CompilationCPUType = CVSD.getCompilationCPUType();
1461 W.flush();
1462}
1463
1464void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1465 BinaryStreamRef Stream(Subsection, llvm::endianness::little);
1466 DebugChecksumsSubsectionRef Checksums;
1467 if (Error E = Checksums.initialize(Stream))
1468 reportError(Err: std::move(E), Input: Obj->getFileName());
1469
1470 for (auto &FC : Checksums) {
1471 DictScope S(W, "FileChecksum");
1472
1473 StringRef Filename = unwrapOrError(
1474 Input: Obj->getFileName(), EO: CVStringTable.getString(Offset: FC.FileNameOffset));
1475 W.printHex(Label: "Filename", Str: Filename, Value: FC.FileNameOffset);
1476 W.printHex(Label: "ChecksumSize", Value: FC.Checksum.size());
1477 W.printEnum(Label: "ChecksumKind", Value: uint8_t(FC.Kind),
1478 EnumValues: EnumStrings(FileChecksumKindNames));
1479
1480 W.printBinary(Label: "ChecksumBytes", Value: FC.Checksum);
1481 }
1482}
1483
1484void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1485 BinaryStreamReader SR(Subsection, llvm::endianness::little);
1486 DebugInlineeLinesSubsectionRef Lines;
1487 if (Error E = Lines.initialize(Reader: SR))
1488 reportError(Err: std::move(E), Input: Obj->getFileName());
1489
1490 for (auto &Line : Lines) {
1491 DictScope S(W, "InlineeSourceLine");
1492 printTypeIndex(FieldName: "Inlinee", TI: Line.Header->Inlinee);
1493 printFileNameForOffset(Label: "FileID", FileOffset: Line.Header->FileID);
1494 W.printNumber(Label: "SourceLineNum", Value: Line.Header->SourceLineNum);
1495
1496 if (Lines.hasExtraFiles()) {
1497 W.printNumber(Label: "ExtraFileCount", Value: Line.ExtraFiles.size());
1498 ListScope ExtraFiles(W, "ExtraFiles");
1499 for (const auto &FID : Line.ExtraFiles) {
1500 printFileNameForOffset(Label: "FileID", FileOffset: FID);
1501 }
1502 }
1503 }
1504}
1505
1506StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1507 // The file checksum subsection should precede all references to it.
1508 if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1509 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1510 Input: Obj->getFileName());
1511
1512 auto Iter = CVFileChecksumTable.getArray().at(Offset: FileOffset);
1513
1514 // Check if the file checksum table offset is valid.
1515 if (Iter == CVFileChecksumTable.end())
1516 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1517 Input: Obj->getFileName());
1518
1519 return unwrapOrError(Input: Obj->getFileName(),
1520 EO: CVStringTable.getString(Offset: Iter->FileNameOffset));
1521}
1522
1523void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1524 W.printHex(Label, Str: getFileNameForFileOffset(FileOffset), Value: FileOffset);
1525}
1526
1527void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1528 MergingTypeTableBuilder &CVTypes,
1529 GlobalTypeTableBuilder &GlobalCVIDs,
1530 GlobalTypeTableBuilder &GlobalCVTypes,
1531 bool GHash) {
1532 for (const SectionRef &S : Obj->sections()) {
1533 StringRef SectionName = unwrapOrError(Input: Obj->getFileName(), EO: S.getName());
1534 if (SectionName == ".debug$T") {
1535 StringRef Data = unwrapOrError(Input: Obj->getFileName(), EO: S.getContents());
1536 uint32_t Magic;
1537 if (Error E = consume(Data, Item&: Magic))
1538 reportError(Err: std::move(E), Input: Obj->getFileName());
1539
1540 if (Magic != 4)
1541 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1542 Input: Obj->getFileName());
1543
1544 CVTypeArray Types;
1545 BinaryStreamReader Reader(Data, llvm::endianness::little);
1546 if (auto EC = Reader.readArray(Array&: Types, Size: Reader.getLength())) {
1547 consumeError(Err: std::move(EC));
1548 W.flush();
1549 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1550 Input: Obj->getFileName());
1551 }
1552 SmallVector<TypeIndex, 128> SourceToDest;
1553 std::optional<PCHMergerInfo> PCHInfo;
1554 if (GHash) {
1555 std::vector<GloballyHashedType> Hashes =
1556 GloballyHashedType::hashTypes(Records&: Types);
1557 if (Error E =
1558 mergeTypeAndIdRecords(DestIds&: GlobalCVIDs, DestTypes&: GlobalCVTypes, SourceToDest,
1559 IdsAndTypes: Types, Hashes, PCHInfo))
1560 return reportError(Err: std::move(E), Input: Obj->getFileName());
1561 } else {
1562 if (Error E = mergeTypeAndIdRecords(DestIds&: CVIDs, DestTypes&: CVTypes, SourceToDest, IdsAndTypes: Types,
1563 PCHInfo))
1564 return reportError(Err: std::move(E), Input: Obj->getFileName());
1565 }
1566 }
1567 }
1568}
1569
1570void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1571 const SectionRef &Section) {
1572 ListScope D(W, "CodeViewTypes");
1573 W.printNumber(Label: "Section", Str: SectionName, Value: Obj->getSectionID(Sec: Section));
1574
1575 StringRef Data = unwrapOrError(Input: Obj->getFileName(), EO: Section.getContents());
1576 if (opts::CodeViewSubsectionBytes)
1577 W.printBinaryBlock(Label: "Data", Value: Data);
1578
1579 uint32_t Magic;
1580 if (Error E = consume(Data, Item&: Magic))
1581 reportError(Err: std::move(E), Input: Obj->getFileName());
1582
1583 W.printHex(Label: "Magic", Value: Magic);
1584 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1585 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
1586 Input: Obj->getFileName());
1587
1588 Types.reset(Data, RecordCountHint: 100);
1589
1590 TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1591 if (Error E = codeview::visitTypeStream(Types, Callbacks&: TDV))
1592 reportError(Err: std::move(E), Input: Obj->getFileName());
1593
1594 W.flush();
1595}
1596
1597void COFFDumper::printSectionHeaders() {
1598 ListScope SectionsD(W, "Sections");
1599 int SectionNumber = 0;
1600 for (const SectionRef &Sec : Obj->sections()) {
1601 ++SectionNumber;
1602 const coff_section *Section = Obj->getCOFFSection(Section: Sec);
1603
1604 StringRef Name = unwrapOrError(Input: Obj->getFileName(), EO: Sec.getName());
1605
1606 DictScope D(W, "Section");
1607 W.printNumber(Label: "Number", Value: SectionNumber);
1608 W.printBinary(Label: "Name", Str: Name, Value: Section->Name);
1609 W.printHex(Label: "VirtualSize", Value: Section->VirtualSize);
1610 W.printHex(Label: "VirtualAddress", Value: Section->VirtualAddress);
1611 W.printHex(Label: "RawDataSize", Value: Section->SizeOfRawData);
1612 W.printHex(Label: "PointerToRawData", Value: Section->PointerToRawData);
1613 W.printHex(Label: "PointerToRelocations", Value: Section->PointerToRelocations);
1614 W.printHex(Label: "PointerToLineNumbers", Value: Section->PointerToLinenumbers);
1615 W.printNumber(Label: "RelocationCount", Value: Section->NumberOfRelocations);
1616 W.printNumber(Label: "LineNumberCount", Value: Section->NumberOfLinenumbers);
1617 W.printFlags(Label: "Characteristics", Value: Section->Characteristics,
1618 Flags: EnumStrings(ImageSectionCharacteristics),
1619 EnumMask1: COFF::SectionCharacteristics(0x00F00000));
1620
1621 if (opts::SectionRelocations) {
1622 ListScope D(W, "Relocations");
1623 for (const RelocationRef &Reloc : Sec.relocations())
1624 printRelocation(Section: Sec, Reloc);
1625 }
1626
1627 if (opts::SectionSymbols) {
1628 ListScope D(W, "Symbols");
1629 for (const SymbolRef &Symbol : Obj->symbols()) {
1630 if (!Sec.containsSymbol(S: Symbol))
1631 continue;
1632
1633 printSymbol(Sym: Symbol);
1634 }
1635 }
1636
1637 if (opts::SectionData &&
1638 !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1639 StringRef Data = unwrapOrError(Input: Obj->getFileName(), EO: Sec.getContents());
1640 W.printBinaryBlock(Label: "SectionData", Value: Data);
1641 }
1642 }
1643}
1644
1645void COFFDumper::printRelocations() {
1646 ListScope D(W, "Relocations");
1647
1648 int SectionNumber = 0;
1649 for (const SectionRef &Section : Obj->sections()) {
1650 ++SectionNumber;
1651 StringRef Name = unwrapOrError(Input: Obj->getFileName(), EO: Section.getName());
1652
1653 bool PrintedGroup = false;
1654 for (const RelocationRef &Reloc : Section.relocations()) {
1655 if (!PrintedGroup) {
1656 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1657 W.indent();
1658 PrintedGroup = true;
1659 }
1660
1661 printRelocation(Section, Reloc);
1662 }
1663
1664 if (PrintedGroup) {
1665 W.unindent();
1666 W.startLine() << "}\n";
1667 }
1668 }
1669}
1670
1671void COFFDumper::printRelocation(const SectionRef &Section,
1672 const RelocationRef &Reloc, uint64_t Bias) {
1673 uint64_t Offset = Reloc.getOffset() - Bias;
1674 uint64_t RelocType = Reloc.getType();
1675 SmallString<32> RelocName;
1676 StringRef SymbolName;
1677 Reloc.getTypeName(Result&: RelocName);
1678 symbol_iterator Symbol = Reloc.getSymbol();
1679 int64_t SymbolIndex = -1;
1680 if (Symbol != Obj->symbol_end()) {
1681 Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1682 if (!SymbolNameOrErr)
1683 reportError(Err: SymbolNameOrErr.takeError(), Input: Obj->getFileName());
1684
1685 SymbolName = *SymbolNameOrErr;
1686 SymbolIndex = Obj->getSymbolIndex(Symbol: Obj->getCOFFSymbol(Symbol: *Symbol));
1687 }
1688
1689 if (opts::ExpandRelocs) {
1690 DictScope Group(W, "Relocation");
1691 W.printHex(Label: "Offset", Value: Offset);
1692 W.printNumber(Label: "Type", Str: RelocName, Value: RelocType);
1693 W.printString(Label: "Symbol", Value: SymbolName.empty() ? "-" : SymbolName);
1694 W.printNumber(Label: "SymbolIndex", Value: SymbolIndex);
1695 } else {
1696 raw_ostream &OS = W.startLine();
1697 OS << W.hex(Value: Offset) << " " << RelocName << " "
1698 << (SymbolName.empty() ? "-" : SymbolName) << " (" << SymbolIndex << ")"
1699 << "\n";
1700 }
1701}
1702
1703void COFFDumper::printSymbols(bool /*ExtraSymInfo*/) {
1704 ListScope Group(W, "Symbols");
1705
1706 for (const SymbolRef &Symbol : Obj->symbols())
1707 printSymbol(Sym: Symbol);
1708}
1709
1710void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1711
1712static Expected<StringRef>
1713getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1714 const coff_section *Section) {
1715 if (Section)
1716 return Obj->getSectionName(Sec: Section);
1717 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1718 return StringRef("IMAGE_SYM_DEBUG");
1719 if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1720 return StringRef("IMAGE_SYM_ABSOLUTE");
1721 if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1722 return StringRef("IMAGE_SYM_UNDEFINED");
1723 return StringRef("");
1724}
1725
1726void COFFDumper::printSymbol(const SymbolRef &Sym) {
1727 DictScope D(W, "Symbol");
1728
1729 COFFSymbolRef Symbol = Obj->getCOFFSymbol(Symbol: Sym);
1730 Expected<const coff_section *> SecOrErr =
1731 Obj->getSection(index: Symbol.getSectionNumber());
1732 if (!SecOrErr) {
1733 W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
1734 << "\n";
1735 W.flush();
1736 consumeError(Err: SecOrErr.takeError());
1737 return;
1738 }
1739 const coff_section *Section = *SecOrErr;
1740
1741 StringRef SymbolName;
1742 if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
1743 SymbolName = *SymNameOrErr;
1744
1745 StringRef SectionName;
1746 if (Expected<StringRef> SecNameOrErr =
1747 getSectionName(Obj, SectionNumber: Symbol.getSectionNumber(), Section))
1748 SectionName = *SecNameOrErr;
1749
1750 W.printString(Label: "Name", Value: SymbolName);
1751 W.printNumber(Label: "Value", Value: Symbol.getValue());
1752 W.printNumber(Label: "Section", Str: SectionName, Value: Symbol.getSectionNumber());
1753 W.printEnum(Label: "BaseType", Value: Symbol.getBaseType(), EnumValues: EnumStrings(ImageSymType));
1754 W.printEnum(Label: "ComplexType", Value: Symbol.getComplexType(),
1755 EnumValues: EnumStrings(ImageSymDType));
1756 W.printEnum(Label: "StorageClass", Value: Symbol.getStorageClass(),
1757 EnumValues: EnumStrings(ImageSymClass));
1758 W.printNumber(Label: "AuxSymbolCount", Value: Symbol.getNumberOfAuxSymbols());
1759
1760 for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1761 if (Symbol.isFunctionDefinition()) {
1762 const coff_aux_function_definition *Aux;
1763 if (std::error_code EC = getSymbolAuxData(Obj, Symbol, AuxSymbolIdx: I, Aux))
1764 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1765
1766 DictScope AS(W, "AuxFunctionDef");
1767 W.printNumber(Label: "TagIndex", Value: Aux->TagIndex);
1768 W.printNumber(Label: "TotalSize", Value: Aux->TotalSize);
1769 W.printHex(Label: "PointerToLineNumber", Value: Aux->PointerToLinenumber);
1770 W.printHex(Label: "PointerToNextFunction", Value: Aux->PointerToNextFunction);
1771
1772 } else if (Symbol.isAnyUndefined()) {
1773 const coff_aux_weak_external *Aux;
1774 if (std::error_code EC = getSymbolAuxData(Obj, Symbol, AuxSymbolIdx: I, Aux))
1775 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1776
1777 DictScope AS(W, "AuxWeakExternal");
1778 W.printNumber(Label: "Linked", Str: getSymbolName(Index: Aux->TagIndex), Value: Aux->TagIndex);
1779 W.printEnum(Label: "Search", Value: Aux->Characteristics,
1780 EnumValues: EnumStrings(WeakExternalCharacteristics));
1781
1782 } else if (Symbol.isFileRecord()) {
1783 const char *FileName;
1784 if (std::error_code EC = getSymbolAuxData(Obj, Symbol, AuxSymbolIdx: I, Aux&: FileName))
1785 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1786 DictScope AS(W, "AuxFileRecord");
1787
1788 StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1789 Obj->getSymbolTableEntrySize());
1790 W.printString(Label: "FileName", Value: Name.rtrim(Chars: StringRef("\0", 1)));
1791 break;
1792 } else if (Symbol.isSectionDefinition()) {
1793 const coff_aux_section_definition *Aux;
1794 if (std::error_code EC = getSymbolAuxData(Obj, Symbol, AuxSymbolIdx: I, Aux))
1795 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1796
1797 int32_t AuxNumber = Aux->getNumber(IsBigObj: Symbol.isBigObj());
1798
1799 DictScope AS(W, "AuxSectionDef");
1800 W.printNumber(Label: "Length", Value: Aux->Length);
1801 W.printNumber(Label: "RelocationCount", Value: Aux->NumberOfRelocations);
1802 W.printNumber(Label: "LineNumberCount", Value: Aux->NumberOfLinenumbers);
1803 W.printHex(Label: "Checksum", Value: Aux->CheckSum);
1804 W.printNumber(Label: "Number", Value: AuxNumber);
1805 W.printEnum(Label: "Selection", Value: Aux->Selection, EnumValues: EnumStrings(ImageCOMDATSelect));
1806
1807 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT &&
1808 Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1809 Expected<const coff_section *> Assoc = Obj->getSection(index: AuxNumber);
1810 if (!Assoc)
1811 reportError(Err: Assoc.takeError(), Input: Obj->getFileName());
1812 Expected<StringRef> AssocName = getSectionName(Obj, SectionNumber: AuxNumber, Section: *Assoc);
1813 if (!AssocName)
1814 reportError(Err: AssocName.takeError(), Input: Obj->getFileName());
1815
1816 W.printNumber(Label: "AssocSection", Str: *AssocName, Value: AuxNumber);
1817 }
1818 } else if (Symbol.isCLRToken()) {
1819 const coff_aux_clr_token *Aux;
1820 if (std::error_code EC = getSymbolAuxData(Obj, Symbol, AuxSymbolIdx: I, Aux))
1821 reportError(Err: errorCodeToError(EC), Input: Obj->getFileName());
1822
1823 DictScope AS(W, "AuxCLRToken");
1824 W.printNumber(Label: "AuxType", Value: Aux->AuxType);
1825 W.printNumber(Label: "Reserved", Value: Aux->Reserved);
1826 W.printNumber(Label: "SymbolTableIndex", Str: getSymbolName(Index: Aux->SymbolTableIndex),
1827 Value: Aux->SymbolTableIndex);
1828
1829 } else {
1830 W.startLine() << "<unhandled auxiliary record>\n";
1831 }
1832 }
1833}
1834
1835void COFFDumper::printUnwindInfo() {
1836 ListScope D(W, "UnwindInformation");
1837 switch (Obj->getMachine()) {
1838 case COFF::IMAGE_FILE_MACHINE_AMD64: {
1839 Win64EH::Dumper Dumper(W);
1840 Win64EH::Dumper::SymbolResolver Resolver =
1841 [](const object::coff_section *Section, uint64_t Offset,
1842 SymbolRef &Symbol, void *user_data) -> std::error_code {
1843 COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1844 return Dumper->resolveSymbol(Section, Offset, Sym&: Symbol);
1845 };
1846 Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1847 Dumper.printData(Ctx);
1848 break;
1849 }
1850 case COFF::IMAGE_FILE_MACHINE_ARM64:
1851 case COFF::IMAGE_FILE_MACHINE_ARM64EC:
1852 case COFF::IMAGE_FILE_MACHINE_ARM64X:
1853 case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1854 ARM::WinEH::Decoder Decoder(W, Obj->getMachine() !=
1855 COFF::IMAGE_FILE_MACHINE_ARMNT);
1856 // TODO Propagate the error.
1857 consumeError(Err: Decoder.dumpProcedureData(COFF: *Obj));
1858 break;
1859 }
1860 default:
1861 W.printEnum(Label: "unsupported Image Machine", Value: Obj->getMachine(),
1862 EnumValues: EnumStrings(ImageFileMachineType));
1863 break;
1864 }
1865}
1866
1867void COFFDumper::printNeededLibraries() {
1868 ListScope D(W, "NeededLibraries");
1869
1870 using LibsTy = std::vector<StringRef>;
1871 LibsTy Libs;
1872
1873 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1874 StringRef Name;
1875 if (!DirRef.getName(Result&: Name))
1876 Libs.push_back(x: Name);
1877 }
1878
1879 llvm::stable_sort(Range&: Libs);
1880
1881 for (const auto &L : Libs) {
1882 W.startLine() << L << "\n";
1883 }
1884}
1885
1886void COFFDumper::printImportedSymbols(
1887 iterator_range<imported_symbol_iterator> Range) {
1888 for (const ImportedSymbolRef &I : Range) {
1889 StringRef Sym;
1890 if (Error E = I.getSymbolName(Result&: Sym))
1891 reportError(Err: std::move(E), Input: Obj->getFileName());
1892 uint16_t Ordinal;
1893 if (Error E = I.getOrdinal(Result&: Ordinal))
1894 reportError(Err: std::move(E), Input: Obj->getFileName());
1895 W.printNumber(Label: "Symbol", Str: Sym, Value: Ordinal);
1896 }
1897}
1898
1899void COFFDumper::printDelayImportedSymbols(
1900 const DelayImportDirectoryEntryRef &I,
1901 iterator_range<imported_symbol_iterator> Range) {
1902 int Index = 0;
1903 for (const ImportedSymbolRef &S : Range) {
1904 DictScope Import(W, "Import");
1905 StringRef Sym;
1906 if (Error E = S.getSymbolName(Result&: Sym))
1907 reportError(Err: std::move(E), Input: Obj->getFileName());
1908
1909 uint16_t Ordinal;
1910 if (Error E = S.getOrdinal(Result&: Ordinal))
1911 reportError(Err: std::move(E), Input: Obj->getFileName());
1912 W.printNumber(Label: "Symbol", Str: Sym, Value: Ordinal);
1913
1914 uint64_t Addr;
1915 if (Error E = I.getImportAddress(AddrIndex: Index++, Result&: Addr))
1916 reportError(Err: std::move(E), Input: Obj->getFileName());
1917 W.printHex(Label: "Address", Value: Addr);
1918 }
1919}
1920
1921void COFFDumper::printCOFFImports() {
1922 // Regular imports
1923 for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1924 DictScope Import(W, "Import");
1925 StringRef Name;
1926 if (Error E = I.getName(Result&: Name))
1927 reportError(Err: std::move(E), Input: Obj->getFileName());
1928 W.printString(Label: "Name", Value: Name);
1929 uint32_t ILTAddr;
1930 if (Error E = I.getImportLookupTableRVA(Result&: ILTAddr))
1931 reportError(Err: std::move(E), Input: Obj->getFileName());
1932 W.printHex(Label: "ImportLookupTableRVA", Value: ILTAddr);
1933 uint32_t IATAddr;
1934 if (Error E = I.getImportAddressTableRVA(Result&: IATAddr))
1935 reportError(Err: std::move(E), Input: Obj->getFileName());
1936 W.printHex(Label: "ImportAddressTableRVA", Value: IATAddr);
1937 // The import lookup table can be missing with certain older linkers, so
1938 // fall back to the import address table in that case.
1939 if (ILTAddr)
1940 printImportedSymbols(Range: I.lookup_table_symbols());
1941 else
1942 printImportedSymbols(Range: I.imported_symbols());
1943 }
1944
1945 // Delay imports
1946 for (const DelayImportDirectoryEntryRef &I :
1947 Obj->delay_import_directories()) {
1948 DictScope Import(W, "DelayImport");
1949 StringRef Name;
1950 if (Error E = I.getName(Result&: Name))
1951 reportError(Err: std::move(E), Input: Obj->getFileName());
1952 W.printString(Label: "Name", Value: Name);
1953 const delay_import_directory_table_entry *Table;
1954 if (Error E = I.getDelayImportTable(Result&: Table))
1955 reportError(Err: std::move(E), Input: Obj->getFileName());
1956 W.printHex(Label: "Attributes", Value: Table->Attributes);
1957 W.printHex(Label: "ModuleHandle", Value: Table->ModuleHandle);
1958 W.printHex(Label: "ImportAddressTable", Value: Table->DelayImportAddressTable);
1959 W.printHex(Label: "ImportNameTable", Value: Table->DelayImportNameTable);
1960 W.printHex(Label: "BoundDelayImportTable", Value: Table->BoundDelayImportTable);
1961 W.printHex(Label: "UnloadDelayImportTable", Value: Table->UnloadDelayImportTable);
1962 printDelayImportedSymbols(I, Range: I.imported_symbols());
1963 }
1964}
1965
1966void COFFDumper::printCOFFExports() {
1967 for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
1968 DictScope Export(W, "Export");
1969
1970 StringRef Name;
1971 uint32_t Ordinal;
1972 bool IsForwarder;
1973
1974 if (Error E = Exp.getSymbolName(Result&: Name))
1975 reportError(Err: std::move(E), Input: Obj->getFileName());
1976 if (Error E = Exp.getOrdinal(Result&: Ordinal))
1977 reportError(Err: std::move(E), Input: Obj->getFileName());
1978 if (Error E = Exp.isForwarder(Result&: IsForwarder))
1979 reportError(Err: std::move(E), Input: Obj->getFileName());
1980
1981 W.printNumber(Label: "Ordinal", Value: Ordinal);
1982 W.printString(Label: "Name", Value: Name);
1983 StringRef ForwardTo;
1984 if (IsForwarder) {
1985 if (Error E = Exp.getForwardTo(Result&: ForwardTo))
1986 reportError(Err: std::move(E), Input: Obj->getFileName());
1987 W.printString(Label: "ForwardedTo", Value: ForwardTo);
1988 } else {
1989 uint32_t RVA;
1990 if (Error E = Exp.getExportRVA(Result&: RVA))
1991 reportError(Err: std::move(E), Input: Obj->getFileName());
1992 W.printHex(Label: "RVA", Value: RVA);
1993 }
1994 }
1995}
1996
1997void COFFDumper::printCOFFDirectives() {
1998 for (const SectionRef &Section : Obj->sections()) {
1999 StringRef Name = unwrapOrError(Input: Obj->getFileName(), EO: Section.getName());
2000 if (Name != ".drectve")
2001 continue;
2002
2003 StringRef Contents =
2004 unwrapOrError(Input: Obj->getFileName(), EO: Section.getContents());
2005 W.printString(Label: "Directive(s)", Value: Contents);
2006 }
2007}
2008
2009static std::string getBaseRelocTypeName(uint8_t Type) {
2010 switch (Type) {
2011 case COFF::IMAGE_REL_BASED_ABSOLUTE:
2012 return "ABSOLUTE";
2013 case COFF::IMAGE_REL_BASED_HIGH:
2014 return "HIGH";
2015 case COFF::IMAGE_REL_BASED_LOW:
2016 return "LOW";
2017 case COFF::IMAGE_REL_BASED_HIGHLOW:
2018 return "HIGHLOW";
2019 case COFF::IMAGE_REL_BASED_HIGHADJ:
2020 return "HIGHADJ";
2021 case COFF::IMAGE_REL_BASED_ARM_MOV32T:
2022 return "ARM_MOV32(T)";
2023 case COFF::IMAGE_REL_BASED_DIR64:
2024 return "DIR64";
2025 default:
2026 return "unknown (" + llvm::utostr(X: Type) + ")";
2027 }
2028}
2029
2030void COFFDumper::printCOFFBaseReloc() {
2031 ListScope D(W, "BaseReloc");
2032 for (const BaseRelocRef &I : Obj->base_relocs()) {
2033 uint8_t Type;
2034 uint32_t RVA;
2035 if (Error E = I.getRVA(Result&: RVA))
2036 reportError(Err: std::move(E), Input: Obj->getFileName());
2037 if (Error E = I.getType(Type))
2038 reportError(Err: std::move(E), Input: Obj->getFileName());
2039 DictScope Import(W, "Entry");
2040 W.printString(Label: "Type", Value: getBaseRelocTypeName(Type));
2041 W.printHex(Label: "Address", Value: RVA);
2042 }
2043}
2044
2045void COFFDumper::printCOFFPseudoReloc() {
2046 ListScope D(W, "PseudoReloc");
2047
2048 // Pseudo-relocations are only meaningful with PE image files.
2049 if (!Obj->getDOSHeader())
2050 return;
2051
2052 const StringRef RelocBeginName = Obj->getArch() == Triple::x86
2053 ? "___RUNTIME_PSEUDO_RELOC_LIST__"
2054 : "__RUNTIME_PSEUDO_RELOC_LIST__";
2055 const StringRef RelocEndName = Obj->getArch() == Triple::x86
2056 ? "___RUNTIME_PSEUDO_RELOC_LIST_END__"
2057 : "__RUNTIME_PSEUDO_RELOC_LIST_END__";
2058
2059 const uint32_t Count = Obj->getNumberOfSymbols();
2060 // Skip if no symbol was found (maybe stripped).
2061 if (Count == 0)
2062 return;
2063
2064 struct SymbolEntry {
2065 uint32_t RVA;
2066 COFFSymbolRef Symbol;
2067 const coff_section *Section;
2068 StringRef SymbolName;
2069 };
2070 SmallVector<SymbolEntry> RVASymbolMap;
2071 COFFSymbolRef RelocBegin, RelocEnd;
2072 for (uint32_t i = 0; i < Count; ++i) {
2073 COFFSymbolRef Sym;
2074 if (Expected<COFFSymbolRef> SymOrErr = Obj->getSymbol(index: i)) {
2075 Sym = *SymOrErr;
2076 } else {
2077 reportUniqueWarning(Err: SymOrErr.takeError());
2078 continue;
2079 }
2080
2081 i += Sym.getNumberOfAuxSymbols();
2082
2083 if (Sym.getSectionNumber() <= 0)
2084 continue;
2085
2086 StringRef Name;
2087 if (Expected<StringRef> NameOrErr = Obj->getSymbolName(Symbol: Sym)) {
2088 Name = *NameOrErr;
2089 } else {
2090 reportUniqueWarning(Err: NameOrErr.takeError());
2091 continue;
2092 }
2093
2094 if (Name == RelocBeginName)
2095 RelocBegin = Sym;
2096 else if (Name == RelocEndName)
2097 RelocEnd = Sym;
2098
2099 const coff_section *Sec = nullptr;
2100 if (Expected<const coff_section *> SecOrErr =
2101 Obj->getSection(index: Sym.getSectionNumber())) {
2102 Sec = *SecOrErr;
2103 } else {
2104 reportUniqueWarning(Err: SecOrErr.takeError());
2105 continue;
2106 }
2107
2108 RVASymbolMap.push_back(
2109 Elt: {.RVA: Sec->VirtualAddress + Sym.getValue(), .Symbol: Sym, .Section: Sec, .SymbolName: Name});
2110 }
2111
2112 if (!RelocBegin.getRawPtr() || !RelocEnd.getRawPtr()) {
2113 reportUniqueWarning(Err: createStringError(
2114 Fmt: "the marker symbols for runtime pseudo-relocation were not found"));
2115 return;
2116 }
2117
2118 const coff_section *Section = nullptr;
2119 if (Expected<const coff_section *> SecOrErr =
2120 Obj->getSection(index: RelocBegin.getSectionNumber())) {
2121 Section = *SecOrErr;
2122 } else {
2123 reportUniqueWarning(Err: SecOrErr.takeError());
2124 return;
2125 }
2126
2127 if (RelocBegin.getSectionNumber() != RelocEnd.getSectionNumber()) {
2128 reportUniqueWarning(Err: createStringError(
2129 Fmt: "the end marker symbol for runtime pseudo-relocation must "
2130 "point to the same section where the begin marker points to: "
2131 "expected %d, but got %d",
2132 Vals: RelocBegin.getSectionNumber(), Vals: RelocEnd.getSectionNumber()));
2133 return;
2134 }
2135
2136 // Skip if the relocation list is empty.
2137 if (RelocBegin.getValue() == RelocEnd.getValue())
2138 return;
2139
2140 if (RelocEnd.getValue() < RelocBegin.getValue()) {
2141 reportUniqueWarning(Err: createStringError(
2142 Fmt: "the end marker symbol for runtime pseudo-relocation must point "
2143 "to a higher address than where the begin marker points to: "
2144 "expected >=0x%x, but got 0x%x",
2145 Vals: RelocBegin.getValue(), Vals: RelocEnd.getValue()));
2146 return;
2147 }
2148
2149 ArrayRef<uint8_t> Data;
2150 if (auto E = Obj->getSectionContents(Sec: Section, Res&: Data)) {
2151 reportUniqueWarning(Err: std::move(E));
2152 return;
2153 }
2154
2155 if (const uint32_t Begin = RelocBegin.getValue(), End = RelocEnd.getValue();
2156 Begin >= Data.size() || End > Data.size()) {
2157 reportUniqueWarning(
2158 Err: createStringError(Fmt: "the marker symbol of runtime pseudo-relocation "
2159 "points past the end of the section 0x%x: got 0x%x",
2160 Vals: Data.size(), Vals: Begin >= Data.size() ? Begin : End));
2161 return;
2162 }
2163
2164 const ArrayRef<uint8_t> RawRelocs =
2165 Data.take_front(N: RelocEnd.getValue()).drop_front(N: RelocBegin.getValue());
2166 struct alignas(4) PseudoRelocationHeader {
2167 PseudoRelocationHeader(uint32_t Signature)
2168 : Zero1(0), Zero2(0), Signature(Signature) {}
2169 support::ulittle32_t Zero1;
2170 support::ulittle32_t Zero2;
2171 support::ulittle32_t Signature;
2172 };
2173 const PseudoRelocationHeader HeaderV2(1);
2174 if (RawRelocs.size() < sizeof(HeaderV2) ||
2175 (memcmp(s1: RawRelocs.data(), s2: &HeaderV2, n: sizeof(HeaderV2)) != 0)) {
2176 reportUniqueWarning(
2177 Err: createStringError(Fmt: "invalid runtime pseudo-relocation records"));
2178 return;
2179 }
2180
2181 struct alignas(4) PseudoRelocationRecord {
2182 support::ulittle32_t Symbol;
2183 support::ulittle32_t Target;
2184 support::ulittle32_t BitSize;
2185 };
2186 ArrayRef<PseudoRelocationRecord> RelocRecords(
2187 reinterpret_cast<const PseudoRelocationRecord *>(
2188 RawRelocs.data() + sizeof(PseudoRelocationHeader)),
2189 (RawRelocs.size() - sizeof(PseudoRelocationHeader)) /
2190 sizeof(PseudoRelocationRecord));
2191
2192 struct CachingImportedSymbolLookup {
2193 struct SizedImportDirectoryEntry {
2194 uint32_t StartRVA;
2195 uint32_t EndRVA;
2196 ImportDirectoryEntryRef EntryRef;
2197 };
2198
2199 CachingImportedSymbolLookup(const COFFObjectFile *Obj) : Obj(Obj) {
2200 for (auto D : Obj->import_directories()) {
2201 auto &Entry = ImportDirectories.emplace_back();
2202 Entry.EntryRef = D;
2203 Entry.EndRVA = 0;
2204 if (auto E = D.getImportAddressTableRVA(Result&: Entry.StartRVA))
2205 reportError(Err: std::move(E), Input: Obj->getFileName());
2206 }
2207 if (ImportDirectories.empty())
2208 return;
2209 llvm::sort(C&: ImportDirectories, Comp: [](const auto &x, const auto &y) {
2210 return x.StartRVA < y.StartRVA;
2211 });
2212 }
2213
2214 Expected<StringRef> find(COFFDumper *Self, uint32_t EntryRVA) {
2215 static constexpr char Msg[] =
2216 "the address referenced by pseudo-relocation is not a valid import "
2217 "entry: 0x%x";
2218 if (auto Ite = ImportedSymbols.find(Val: EntryRVA);
2219 Ite != ImportedSymbols.end())
2220 return Ite->second;
2221
2222 auto Ite = llvm::upper_bound(
2223 Range&: ImportDirectories, Value&: EntryRVA,
2224 C: [](uint32_t RVA, const auto &D) { return RVA < D.StartRVA; });
2225 if (Ite == ImportDirectories.begin())
2226 return createStringError(Fmt: Msg, Vals: EntryRVA);
2227
2228 --Ite;
2229 uint32_t RVA = Ite->StartRVA;
2230 if (Ite->EndRVA != 0 && Ite->EndRVA <= RVA)
2231 return createStringError(Fmt: Msg, Vals: EntryRVA);
2232 // Search with linear iteration to care if padding or garbage exist
2233 // between ImportDirectoryEntry.
2234 for (auto S : Ite->EntryRef.imported_symbols()) {
2235 if (RVA == EntryRVA) {
2236 StringRef &NameDst = ImportedSymbols[RVA];
2237 if (auto E = S.getSymbolName(Result&: NameDst)) {
2238 Self->reportUniqueWarning(Err: std::move(E));
2239 NameDst = "(no symbol)";
2240 }
2241 return NameDst;
2242 }
2243 RVA += Obj->is64() ? 8 : 4;
2244 if (EntryRVA < RVA)
2245 return createStringError(Fmt: Msg, Vals: EntryRVA);
2246 }
2247 Ite->EndRVA = RVA;
2248
2249 return createStringError(Fmt: Msg, Vals: EntryRVA);
2250 }
2251
2252 private:
2253 const COFFObjectFile *Obj;
2254 SmallVector<SizedImportDirectoryEntry> ImportDirectories;
2255 DenseMap<uint32_t, StringRef> ImportedSymbols;
2256 };
2257 CachingImportedSymbolLookup ImportedSymbols(Obj);
2258 llvm::stable_sort(Range&: RVASymbolMap,
2259 C: [](const auto &x, const auto &y) { return x.RVA < y.RVA; });
2260 RVASymbolMap.erase(
2261 CS: llvm::unique(R&: RVASymbolMap,
2262 P: [](const auto &x, const auto &y) { return x.RVA == y.RVA; }),
2263 CE: RVASymbolMap.end());
2264
2265 for (const auto &Reloc : RelocRecords) {
2266 DictScope Entry(W, "Entry");
2267
2268 W.printHex(Label: "Symbol", Value: Reloc.Symbol);
2269 if (Expected<StringRef> SymOrErr =
2270 ImportedSymbols.find(Self: this, EntryRVA: Reloc.Symbol)) {
2271 W.printString(Label: "SymbolName", Value: *SymOrErr);
2272 } else {
2273 reportUniqueWarning(Err: SymOrErr.takeError());
2274 W.printString(Label: "SymbolName", Value: "(missing)");
2275 }
2276
2277 W.printHex(Label: "Target", Value: Reloc.Target);
2278 if (auto Ite = llvm::upper_bound(
2279 Range&: RVASymbolMap, Value: Reloc.Target.value(),
2280 C: [](uint32_t RVA, const auto &Sym) { return RVA < Sym.RVA; });
2281 Ite == RVASymbolMap.begin()) {
2282 W.printSymbolOffset(Label: "TargetSymbol", Symbol: "(base)", Value: Reloc.Target);
2283 } else if (const uint32_t Offset = Reloc.Target.value() - (--Ite)->RVA;
2284 Offset == 0) {
2285 W.printString(Label: "TargetSymbol", Value: Ite->SymbolName);
2286 } else if (Offset < Ite->Section->VirtualSize) {
2287 W.printSymbolOffset(Label: "TargetSymbol", Symbol: Ite->SymbolName, Value: Offset);
2288 } else if (++Ite == RVASymbolMap.end()) {
2289 W.printSymbolOffset(Label: "TargetSymbol", Symbol: "(base)", Value: Reloc.Target);
2290 } else if (Expected<StringRef> NameOrErr =
2291 Obj->getSectionName(Sec: Ite->Section)) {
2292 W.printSymbolOffset(Label: "TargetSymbol", Symbol: *NameOrErr,
2293 Value: Reloc.Target - Ite->Section->VirtualAddress);
2294 } else {
2295 reportUniqueWarning(Err: NameOrErr.takeError());
2296 W.printSymbolOffset(Label: "TargetSymbol", Symbol: "(base)", Value: Reloc.Target);
2297 }
2298
2299 W.printNumber(Label: "BitWidth", Value: Reloc.BitSize);
2300 }
2301}
2302
2303void COFFDumper::printCOFFResources() {
2304 ListScope ResourcesD(W, "Resources");
2305 for (const SectionRef &S : Obj->sections()) {
2306 StringRef Name = unwrapOrError(Input: Obj->getFileName(), EO: S.getName());
2307 if (!Name.starts_with(Prefix: ".rsrc"))
2308 continue;
2309
2310 StringRef Ref = unwrapOrError(Input: Obj->getFileName(), EO: S.getContents());
2311
2312 if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
2313 ResourceSectionRef RSF;
2314 Error E = RSF.load(O: Obj, S);
2315 if (E)
2316 reportError(Err: std::move(E), Input: Obj->getFileName());
2317 auto &BaseTable = unwrapOrError(Input: Obj->getFileName(), EO: RSF.getBaseTable());
2318 W.printNumber(Label: "Total Number of Resources",
2319 Value: countTotalTableEntries(RSF, Table: BaseTable, Level: "Type"));
2320 W.printHex(Label: "Base Table Address",
2321 Value: Obj->getCOFFSection(Section: S)->PointerToRawData);
2322 W.startLine() << "\n";
2323 printResourceDirectoryTable(RSF, Table: BaseTable, Level: "Type");
2324 }
2325 if (opts::SectionData)
2326 W.printBinaryBlock(Label: Name.str() + " Data", Value: Ref);
2327 }
2328}
2329
2330uint32_t
2331COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
2332 const coff_resource_dir_table &Table,
2333 StringRef Level) {
2334 uint32_t TotalEntries = 0;
2335 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
2336 i++) {
2337 auto Entry = unwrapOrError(Input: Obj->getFileName(), EO: RSF.getTableEntry(Table, Index: i));
2338 if (Entry.Offset.isSubDir()) {
2339 StringRef NextLevel;
2340 if (Level == "Name")
2341 NextLevel = "Language";
2342 else
2343 NextLevel = "Name";
2344 auto &NextTable =
2345 unwrapOrError(Input: Obj->getFileName(), EO: RSF.getEntrySubDir(Entry));
2346 TotalEntries += countTotalTableEntries(RSF, Table: NextTable, Level: NextLevel);
2347 } else {
2348 TotalEntries += 1;
2349 }
2350 }
2351 return TotalEntries;
2352}
2353
2354void COFFDumper::printResourceDirectoryTable(
2355 ResourceSectionRef RSF, const coff_resource_dir_table &Table,
2356 StringRef Level) {
2357
2358 W.printNumber(Label: "Number of String Entries", Value: Table.NumberOfNameEntries);
2359 W.printNumber(Label: "Number of ID Entries", Value: Table.NumberOfIDEntries);
2360
2361 // Iterate through level in resource directory tree.
2362 for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
2363 i++) {
2364 auto Entry = unwrapOrError(Input: Obj->getFileName(), EO: RSF.getTableEntry(Table, Index: i));
2365 StringRef Name;
2366 SmallString<20> IDStr;
2367 raw_svector_ostream OS(IDStr);
2368 if (i < Table.NumberOfNameEntries) {
2369 ArrayRef<UTF16> RawEntryNameString =
2370 unwrapOrError(Input: Obj->getFileName(), EO: RSF.getEntryNameString(Entry));
2371 std::vector<UTF16> EndianCorrectedNameString;
2372 if (llvm::sys::IsBigEndianHost) {
2373 EndianCorrectedNameString.resize(new_size: RawEntryNameString.size() + 1);
2374 llvm::copy(Range&: RawEntryNameString, Out: EndianCorrectedNameString.begin() + 1);
2375 EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
2376 RawEntryNameString = ArrayRef(EndianCorrectedNameString);
2377 }
2378 std::string EntryNameString;
2379 if (!llvm::convertUTF16ToUTF8String(Src: RawEntryNameString, Out&: EntryNameString))
2380 reportError(Err: errorCodeToError(EC: object_error::parse_failed),
2381 Input: Obj->getFileName());
2382 OS << ": ";
2383 OS << EntryNameString;
2384 } else {
2385 if (Level == "Type") {
2386 OS << ": ";
2387 printResourceTypeName(TypeID: Entry.Identifier.ID, OS);
2388 } else {
2389 OS << ": (ID " << Entry.Identifier.ID << ")";
2390 }
2391 }
2392 Name = IDStr;
2393 ListScope ResourceType(W, Level.str() + Name.str());
2394 if (Entry.Offset.isSubDir()) {
2395 W.printHex(Label: "Table Offset", Value: Entry.Offset.value());
2396 StringRef NextLevel;
2397 if (Level == "Name")
2398 NextLevel = "Language";
2399 else
2400 NextLevel = "Name";
2401 auto &NextTable =
2402 unwrapOrError(Input: Obj->getFileName(), EO: RSF.getEntrySubDir(Entry));
2403 printResourceDirectoryTable(RSF, Table: NextTable, Level: NextLevel);
2404 } else {
2405 W.printHex(Label: "Entry Offset", Value: Entry.Offset.value());
2406 char FormattedTime[20] = {};
2407 time_t TDS = time_t(Table.TimeDateStamp);
2408 strftime(s: FormattedTime, maxsize: 20, format: "%Y-%m-%d %H:%M:%S", tp: gmtime(timer: &TDS));
2409 W.printHex(Label: "Time/Date Stamp", Str: FormattedTime, Value: Table.TimeDateStamp);
2410 W.printNumber(Label: "Major Version", Value: Table.MajorVersion);
2411 W.printNumber(Label: "Minor Version", Value: Table.MinorVersion);
2412 W.printNumber(Label: "Characteristics", Value: Table.Characteristics);
2413 ListScope DataScope(W, "Data");
2414 auto &DataEntry =
2415 unwrapOrError(Input: Obj->getFileName(), EO: RSF.getEntryData(Entry));
2416 W.printHex(Label: "DataRVA", Value: DataEntry.DataRVA);
2417 W.printNumber(Label: "DataSize", Value: DataEntry.DataSize);
2418 W.printNumber(Label: "Codepage", Value: DataEntry.Codepage);
2419 W.printNumber(Label: "Reserved", Value: DataEntry.Reserved);
2420 StringRef Contents =
2421 unwrapOrError(Input: Obj->getFileName(), EO: RSF.getContents(Entry: DataEntry));
2422 W.printBinaryBlock(Label: "Data", Value: Contents);
2423 }
2424 }
2425}
2426
2427void COFFDumper::printStackMap() const {
2428 SectionRef StackMapSection;
2429 for (auto Sec : Obj->sections()) {
2430 StringRef Name;
2431 if (Expected<StringRef> NameOrErr = Sec.getName())
2432 Name = *NameOrErr;
2433 else
2434 consumeError(Err: NameOrErr.takeError());
2435
2436 if (Name == ".llvm_stackmaps") {
2437 StackMapSection = Sec;
2438 break;
2439 }
2440 }
2441
2442 if (StackMapSection == SectionRef())
2443 return;
2444
2445 StringRef StackMapContents =
2446 unwrapOrError(Input: Obj->getFileName(), EO: StackMapSection.getContents());
2447 ArrayRef<uint8_t> StackMapContentsArray =
2448 arrayRefFromStringRef(Input: StackMapContents);
2449
2450 if (Obj->isLittleEndian())
2451 prettyPrintStackMap(
2452 W, SMP: StackMapParser<llvm::endianness::little>(StackMapContentsArray));
2453 else
2454 prettyPrintStackMap(
2455 W, SMP: StackMapParser<llvm::endianness::big>(StackMapContentsArray));
2456}
2457
2458void COFFDumper::printAddrsig() {
2459 SectionRef AddrsigSection;
2460 for (auto Sec : Obj->sections()) {
2461 StringRef Name;
2462 if (Expected<StringRef> NameOrErr = Sec.getName())
2463 Name = *NameOrErr;
2464 else
2465 consumeError(Err: NameOrErr.takeError());
2466
2467 if (Name == ".llvm_addrsig") {
2468 AddrsigSection = Sec;
2469 break;
2470 }
2471 }
2472
2473 if (AddrsigSection == SectionRef())
2474 return;
2475
2476 StringRef AddrsigContents =
2477 unwrapOrError(Input: Obj->getFileName(), EO: AddrsigSection.getContents());
2478 ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
2479 AddrsigContents.size());
2480
2481 ListScope L(W, "Addrsig");
2482 const uint8_t *Cur = AddrsigContents.bytes_begin();
2483 const uint8_t *End = AddrsigContents.bytes_end();
2484 while (Cur != End) {
2485 unsigned Size;
2486 const char *Err = nullptr;
2487 uint64_t SymIndex = decodeULEB128(p: Cur, n: &Size, end: End, error: &Err);
2488 if (Err)
2489 reportError(Err: createError(Err), Input: Obj->getFileName());
2490
2491 W.printNumber(Label: "Sym", Str: getSymbolName(Index: SymIndex), Value: SymIndex);
2492 Cur += Size;
2493 }
2494}
2495
2496void COFFDumper::printCGProfile() {
2497 SectionRef CGProfileSection;
2498 for (SectionRef Sec : Obj->sections()) {
2499 StringRef Name = unwrapOrError(Input: Obj->getFileName(), EO: Sec.getName());
2500 if (Name == ".llvm.call-graph-profile") {
2501 CGProfileSection = Sec;
2502 break;
2503 }
2504 }
2505
2506 if (CGProfileSection == SectionRef())
2507 return;
2508
2509 StringRef CGProfileContents =
2510 unwrapOrError(Input: Obj->getFileName(), EO: CGProfileSection.getContents());
2511 BinaryStreamReader Reader(CGProfileContents, llvm::endianness::little);
2512
2513 ListScope L(W, "CGProfile");
2514 while (!Reader.empty()) {
2515 uint32_t FromIndex, ToIndex;
2516 uint64_t Count;
2517 if (Error Err = Reader.readInteger(Dest&: FromIndex))
2518 reportError(Err: std::move(Err), Input: Obj->getFileName());
2519 if (Error Err = Reader.readInteger(Dest&: ToIndex))
2520 reportError(Err: std::move(Err), Input: Obj->getFileName());
2521 if (Error Err = Reader.readInteger(Dest&: Count))
2522 reportError(Err: std::move(Err), Input: Obj->getFileName());
2523
2524 DictScope D(W, "CGProfileEntry");
2525 W.printNumber(Label: "From", Str: getSymbolName(Index: FromIndex), Value: FromIndex);
2526 W.printNumber(Label: "To", Str: getSymbolName(Index: ToIndex), Value: ToIndex);
2527 W.printNumber(Label: "Weight", Value: Count);
2528 }
2529}
2530
2531void COFFDumper::printStringTable() {
2532 DictScope DS(W, "StringTable");
2533 StringRef StrTable = Obj->getStringTable();
2534 uint32_t StrTabSize = StrTable.size();
2535 W.printNumber(Label: "Length", Value: StrTabSize);
2536 // Print strings from the fifth byte, since the first four bytes contain the
2537 // length (in bytes) of the string table (including the length field).
2538 if (StrTabSize > 4)
2539 printAsStringList(StringContent: StrTable, StringDataOffset: 4);
2540}
2541
2542StringRef COFFDumper::getSymbolName(uint32_t Index) {
2543 Expected<COFFSymbolRef> Sym = Obj->getSymbol(index: Index);
2544 if (!Sym)
2545 reportError(Err: Sym.takeError(), Input: Obj->getFileName());
2546
2547 Expected<StringRef> SymName = Obj->getSymbolName(Symbol: *Sym);
2548 if (!SymName)
2549 reportError(Err: SymName.takeError(), Input: Obj->getFileName());
2550
2551 return *SymName;
2552}
2553
2554void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
2555 ArrayRef<ArrayRef<uint8_t>> IpiRecords,
2556 ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
2557 TypeTableCollection TpiTypes(TpiRecords);
2558 {
2559 ListScope S(Writer, "MergedTypeStream");
2560 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2561 if (Error Err = codeview::visitTypeStream(Types&: TpiTypes, Callbacks&: TDV))
2562 reportError(Err: std::move(Err), Input: "<?>");
2563 Writer.flush();
2564 }
2565
2566 // Flatten the id stream and print it next. The ID stream refers to names from
2567 // the type stream.
2568 TypeTableCollection IpiTypes(IpiRecords);
2569 {
2570 ListScope S(Writer, "MergedIDStream");
2571 TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2572 TDV.setIpiTypes(IpiTypes);
2573 if (Error Err = codeview::visitTypeStream(Types&: IpiTypes, Callbacks&: TDV))
2574 reportError(Err: std::move(Err), Input: "<?>");
2575 Writer.flush();
2576 }
2577}
2578
2579void COFFDumper::printCOFFTLSDirectory() {
2580 if (Obj->is64())
2581 printCOFFTLSDirectory(TlsTable: Obj->getTLSDirectory64());
2582 else
2583 printCOFFTLSDirectory(TlsTable: Obj->getTLSDirectory32());
2584}
2585
2586template <typename IntTy>
2587void COFFDumper::printCOFFTLSDirectory(
2588 const coff_tls_directory<IntTy> *TlsTable) {
2589 DictScope D(W, "TLSDirectory");
2590 if (!TlsTable)
2591 return;
2592
2593 W.printHex("StartAddressOfRawData", TlsTable->StartAddressOfRawData);
2594 W.printHex("EndAddressOfRawData", TlsTable->EndAddressOfRawData);
2595 W.printHex("AddressOfIndex", TlsTable->AddressOfIndex);
2596 W.printHex("AddressOfCallBacks", TlsTable->AddressOfCallBacks);
2597 W.printHex("SizeOfZeroFill", TlsTable->SizeOfZeroFill);
2598 W.printFlags("Characteristics", TlsTable->Characteristics,
2599 EnumStrings(ImageSectionCharacteristics),
2600 COFF::SectionCharacteristics(COFF::IMAGE_SCN_ALIGN_MASK));
2601}
2602