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

source code of llvm/tools/llvm-readobj/COFFDumper.cpp