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