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