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