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