1 //===- DumpOutputStyle.cpp ------------------------------------ *- C++ --*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "DumpOutputStyle.h"
12 #include "FormatUtil.h"
13 #include "InputFile.h"
14 #include "MinimalSymbolDumper.h"
15 #include "MinimalTypeDumper.h"
16 #include "StreamUtil.h"
17 #include "llvm-pdbutil.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h"
21 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
22 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
23 #include "llvm/DebugInfo/CodeView/DebugCrossExSubsection.h"
24 #include "llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h"
25 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h"
30 #include "llvm/DebugInfo/CodeView/Formatters.h"
31 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
32 #include "llvm/DebugInfo/CodeView/Line.h"
33 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
34 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h"
35 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
36 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
37 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
38 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
39 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h"
40 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
41 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
42 #include "llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h"
43 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
44 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
45 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
46 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
47 #include "llvm/DebugInfo/PDB/Native/RawError.h"
48 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
49 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
50 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
51 #include "llvm/Object/COFF.h"
52 #include "llvm/Support/BinaryStreamReader.h"
53 #include "llvm/Support/FormatAdapters.h"
54 #include "llvm/Support/FormatVariadic.h"
59 using namespace llvm::codeview
;
60 using namespace llvm::msf
;
61 using namespace llvm::pdb
;
63 DumpOutputStyle::DumpOutputStyle(InputFile
&File
)
64 : File(File
), P(2, false, outs()) {}
66 PDBFile
&DumpOutputStyle::getPdb() { return File
.pdb(); }
67 object::COFFObjectFile
&DumpOutputStyle::getObj() { return File
.obj(); }
69 void DumpOutputStyle::printStreamNotValidForObj() {
70 AutoIndent
Indent(P
, 4);
71 P
.formatLine("Dumping this stream is not valid for object files");
74 void DumpOutputStyle::printStreamNotPresent(StringRef StreamName
) {
75 AutoIndent
Indent(P
, 4);
76 P
.formatLine("{0} stream not present", StreamName
);
79 Error
DumpOutputStyle::dump() {
80 if (opts::dump::DumpSummary
) {
81 if (auto EC
= dumpFileSummary())
86 if (opts::dump::DumpStreams
) {
87 if (auto EC
= dumpStreamSummary())
92 if (opts::dump::DumpSymbolStats
) {
93 if (auto EC
= dumpSymbolStats())
98 if (opts::dump::DumpUdtStats
) {
99 if (auto EC
= dumpUdtStats())
104 if (opts::dump::DumpNamedStreams
) {
105 if (auto EC
= dumpNamedStreams())
110 if (opts::dump::DumpStringTable
|| opts::dump::DumpStringTableDetails
) {
111 if (auto EC
= dumpStringTable())
116 if (opts::dump::DumpModules
) {
117 if (auto EC
= dumpModules())
121 if (opts::dump::DumpModuleFiles
) {
122 if (auto EC
= dumpModuleFiles())
126 if (opts::dump::DumpLines
) {
127 if (auto EC
= dumpLines())
131 if (opts::dump::DumpInlineeLines
) {
132 if (auto EC
= dumpInlineeLines())
136 if (opts::dump::DumpXmi
) {
137 if (auto EC
= dumpXmi())
141 if (opts::dump::DumpXme
) {
142 if (auto EC
= dumpXme())
146 if (opts::dump::DumpFpo
) {
147 if (auto EC
= dumpFpo())
152 if (opts::dump::DumpTypes
|| !opts::dump::DumpTypeIndex
.empty() ||
153 opts::dump::DumpTypeExtras
)
154 if (auto EC
= dumpTypesFromObjectFile())
157 if (opts::dump::DumpTypes
|| !opts::dump::DumpTypeIndex
.empty() ||
158 opts::dump::DumpTypeExtras
) {
159 if (auto EC
= dumpTpiStream(StreamTPI
))
163 if (opts::dump::DumpIds
|| !opts::dump::DumpIdIndex
.empty() ||
164 opts::dump::DumpIdExtras
) {
165 if (auto EC
= dumpTpiStream(StreamIPI
))
170 if (opts::dump::DumpGSIRecords
) {
171 if (auto EC
= dumpGSIRecords())
175 if (opts::dump::DumpGlobals
) {
176 if (auto EC
= dumpGlobals())
180 if (opts::dump::DumpPublics
) {
181 if (auto EC
= dumpPublics())
185 if (opts::dump::DumpSymbols
) {
186 auto EC
= File
.isPdb() ? dumpModuleSymsForPdb() : dumpModuleSymsForObj();
191 if (opts::dump::DumpSectionHeaders
) {
192 if (auto EC
= dumpSectionHeaders())
196 if (opts::dump::DumpSectionContribs
) {
197 if (auto EC
= dumpSectionContribs())
201 if (opts::dump::DumpSectionMap
) {
202 if (auto EC
= dumpSectionMap())
206 return Error::success();
209 static void printHeader(LinePrinter
&P
, const Twine
&S
) {
211 P
.formatLine("{0,=60}", S
);
212 P
.formatLine("{0}", fmt_repeat('=', 60));
215 Error
DumpOutputStyle::dumpFileSummary() {
216 printHeader(P
, "Summary");
219 printStreamNotValidForObj();
220 return Error::success();
223 AutoIndent
Indent(P
);
224 ExitOnError
Err("Invalid PDB Format: ");
226 P
.formatLine("Block Size: {0}", getPdb().getBlockSize());
227 P
.formatLine("Number of blocks: {0}", getPdb().getBlockCount());
228 P
.formatLine("Number of streams: {0}", getPdb().getNumStreams());
230 auto &PS
= Err(getPdb().getPDBInfoStream());
231 P
.formatLine("Signature: {0}", PS
.getSignature());
232 P
.formatLine("Age: {0}", PS
.getAge());
233 P
.formatLine("GUID: {0}", fmt_guid(PS
.getGuid().Guid
));
234 P
.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS
.getFeatures()));
235 P
.formatLine("Has Debug Info: {0}", getPdb().hasPDBDbiStream());
236 P
.formatLine("Has Types: {0}", getPdb().hasPDBTpiStream());
237 P
.formatLine("Has IDs: {0}", getPdb().hasPDBIpiStream());
238 P
.formatLine("Has Globals: {0}", getPdb().hasPDBGlobalsStream());
239 P
.formatLine("Has Publics: {0}", getPdb().hasPDBPublicsStream());
240 if (getPdb().hasPDBDbiStream()) {
241 auto &DBI
= Err(getPdb().getPDBDbiStream());
242 P
.formatLine("Is incrementally linked: {0}", DBI
.isIncrementallyLinked());
243 P
.formatLine("Has conflicting types: {0}", DBI
.hasCTypes());
244 P
.formatLine("Is stripped: {0}", DBI
.isStripped());
247 return Error::success();
250 static StatCollection
getSymbolStats(const SymbolGroup
&SG
,
251 StatCollection
&CumulativeStats
) {
252 StatCollection Stats
;
253 if (SG
.getFile().isPdb()) {
254 // For PDB files, all symbols are packed into one stream.
255 for (const auto &S
: SG
.getPdbModuleStream().symbols(nullptr)) {
256 Stats
.update(S
.kind(), S
.length());
257 CumulativeStats
.update(S
.kind(), S
.length());
262 for (const auto &SS
: SG
.getDebugSubsections()) {
263 // For object files, all symbols are spread across multiple Symbol
264 // subsections of a given .debug$S section.
265 if (SS
.kind() != DebugSubsectionKind::Symbols
)
267 DebugSymbolsSubsectionRef Symbols
;
268 BinaryStreamReader
Reader(SS
.getRecordData());
269 cantFail(Symbols
.initialize(Reader
));
270 for (const auto &S
: Symbols
) {
271 Stats
.update(S
.kind(), S
.length());
272 CumulativeStats
.update(S
.kind(), S
.length());
278 static StatCollection
getChunkStats(const SymbolGroup
&SG
,
279 StatCollection
&CumulativeStats
) {
280 StatCollection Stats
;
281 for (const auto &Chunk
: SG
.getDebugSubsections()) {
282 Stats
.update(uint32_t(Chunk
.kind()), Chunk
.getRecordLength());
283 CumulativeStats
.update(uint32_t(Chunk
.kind()), Chunk
.getRecordLength());
288 static inline std::string
formatModuleDetailKind(DebugSubsectionKind K
) {
289 return formatChunkKind(K
, false);
292 static inline std::string
formatModuleDetailKind(SymbolKind K
) {
293 return formatSymbolKind(K
);
296 template <typename Kind
>
297 static void printModuleDetailStats(LinePrinter
&P
, StringRef Label
,
298 const StatCollection
&Stats
) {
300 P
.formatLine(" {0}", Label
);
301 AutoIndent
Indent(P
);
302 P
.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
303 Stats
.Totals
.Count
, Stats
.Totals
.Size
);
304 P
.formatLine("{0}", fmt_repeat('-', 74));
305 for (const auto &K
: Stats
.Individual
) {
306 std::string KindName
= formatModuleDetailKind(Kind(K
.first
));
307 P
.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName
,
308 K
.second
.Count
, K
.second
.Size
);
312 static bool isMyCode(const SymbolGroup
&Group
) {
313 if (Group
.getFile().isObj())
316 StringRef Name
= Group
.name();
317 if (Name
.startswith("Import:"))
319 if (Name
.endswith_lower(".dll"))
321 if (Name
.equals_lower("* linker *"))
323 if (Name
.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
325 if (Name
.startswith_lower("f:\\dd\\vctools\\crt"))
330 static bool shouldDumpSymbolGroup(uint32_t Idx
, const SymbolGroup
&Group
) {
331 if (opts::dump::JustMyCode
&& !isMyCode(Group
))
334 // If the arg was not specified on the command line, always dump all modules.
335 if (opts::dump::DumpModi
.getNumOccurrences() == 0)
338 // Otherwise, only dump if this is the same module specified.
339 return (opts::dump::DumpModi
== Idx
);
342 Error
DumpOutputStyle::dumpStreamSummary() {
343 printHeader(P
, "Streams");
346 printStreamNotValidForObj();
347 return Error::success();
350 AutoIndent
Indent(P
);
352 if (StreamPurposes
.empty())
353 discoverStreamPurposes(getPdb(), StreamPurposes
);
355 uint32_t StreamCount
= getPdb().getNumStreams();
356 uint32_t MaxStreamSize
= getPdb().getMaxStreamSize();
358 for (uint16_t StreamIdx
= 0; StreamIdx
< StreamCount
; ++StreamIdx
) {
360 "Stream {0} ({1} bytes): [{2}]",
361 fmt_align(StreamIdx
, AlignStyle::Right
, NumDigits(StreamCount
)),
362 fmt_align(getPdb().getStreamByteSize(StreamIdx
), AlignStyle::Right
,
363 NumDigits(MaxStreamSize
)),
364 StreamPurposes
[StreamIdx
].getLongName());
366 if (opts::dump::DumpStreamBlocks
) {
367 auto Blocks
= getPdb().getStreamBlockList(StreamIdx
);
368 std::vector
<uint32_t> BV(Blocks
.begin(), Blocks
.end());
369 P
.formatLine(" {0} Blocks: [{1}]",
370 fmt_repeat(' ', NumDigits(StreamCount
)),
371 make_range(BV
.begin(), BV
.end()));
375 return Error::success();
378 static Expected
<ModuleDebugStreamRef
> getModuleDebugStream(PDBFile
&File
,
380 ExitOnError
Err("Unexpected error: ");
382 auto &Dbi
= Err(File
.getPDBDbiStream());
383 const auto &Modules
= Dbi
.modules();
384 auto Modi
= Modules
.getModuleDescriptor(Index
);
386 uint16_t ModiStream
= Modi
.getModuleStreamIndex();
387 if (ModiStream
== kInvalidStreamIndex
)
388 return make_error
<RawError
>(raw_error_code::no_stream
,
389 "Module stream not present");
391 auto ModStreamData
= File
.createIndexedStream(ModiStream
);
393 ModuleDebugStreamRef
ModS(Modi
, std::move(ModStreamData
));
394 if (auto EC
= ModS
.reload())
395 return make_error
<RawError
>(raw_error_code::corrupt_file
,
396 "Invalid module stream");
398 return std::move(ModS
);
401 template <typename CallbackT
>
403 iterateOneModule(InputFile
&File
, const Optional
<PrintScope
> &HeaderScope
,
404 const SymbolGroup
&SG
, uint32_t Modi
, CallbackT Callback
) {
406 HeaderScope
->P
.formatLine(
407 "Mod {0:4} | `{1}`: ",
408 fmt_align(Modi
, AlignStyle::Right
, HeaderScope
->LabelWidth
), SG
.name());
411 AutoIndent
Indent(HeaderScope
);
415 template <typename CallbackT
>
416 static void iterateSymbolGroups(InputFile
&Input
,
417 const Optional
<PrintScope
> &HeaderScope
,
418 CallbackT Callback
) {
419 AutoIndent
Indent(HeaderScope
);
421 ExitOnError
Err("Unexpected error processing modules: ");
423 if (opts::dump::DumpModi
.getNumOccurrences() > 0) {
424 assert(opts::dump::DumpModi
.getNumOccurrences() == 1);
425 uint32_t Modi
= opts::dump::DumpModi
;
426 SymbolGroup
SG(&Input
, Modi
);
427 iterateOneModule(Input
, withLabelWidth(HeaderScope
, NumDigits(Modi
)), SG
,
434 for (const auto &SG
: Input
.symbol_groups()) {
435 if (shouldDumpSymbolGroup(I
, SG
))
436 iterateOneModule(Input
, withLabelWidth(HeaderScope
, NumDigits(I
)), SG
, I
,
443 template <typename SubsectionT
>
444 static void iterateModuleSubsections(
445 InputFile
&File
, const Optional
<PrintScope
> &HeaderScope
,
446 llvm::function_ref
<void(uint32_t, const SymbolGroup
&, SubsectionT
&)>
449 iterateSymbolGroups(File
, HeaderScope
,
450 [&](uint32_t Modi
, const SymbolGroup
&SG
) {
451 for (const auto &SS
: SG
.getDebugSubsections()) {
452 SubsectionT Subsection
;
454 if (SS
.kind() != Subsection
.kind())
457 BinaryStreamReader
Reader(SS
.getRecordData());
458 if (auto EC
= Subsection
.initialize(Reader
))
460 Callback(Modi
, SG
, Subsection
);
465 static Expected
<std::pair
<std::unique_ptr
<MappedBlockStream
>,
466 ArrayRef
<llvm::object::coff_section
>>>
467 loadSectionHeaders(PDBFile
&File
, DbgHeaderType Type
) {
468 if (!File
.hasPDBDbiStream())
469 return make_error
<StringError
>(
470 "Section headers require a DBI Stream, which could not be loaded",
471 inconvertibleErrorCode());
473 auto &Dbi
= cantFail(File
.getPDBDbiStream());
474 uint32_t SI
= Dbi
.getDebugStreamIndex(Type
);
476 if (SI
== kInvalidStreamIndex
)
477 return make_error
<StringError
>(
478 "PDB does not contain the requested image section header type",
479 inconvertibleErrorCode());
481 auto Stream
= File
.createIndexedStream(SI
);
483 return make_error
<StringError
>("Could not load the required stream data",
484 inconvertibleErrorCode());
486 ArrayRef
<object::coff_section
> Headers
;
487 if (Stream
->getLength() % sizeof(object::coff_section
) != 0)
488 return make_error
<StringError
>(
489 "Section header array size is not a multiple of section header size",
490 inconvertibleErrorCode());
492 uint32_t NumHeaders
= Stream
->getLength() / sizeof(object::coff_section
);
493 BinaryStreamReader
Reader(*Stream
);
494 cantFail(Reader
.readArray(Headers
, NumHeaders
));
495 return std::make_pair(std::move(Stream
), Headers
);
498 static std::vector
<std::string
> getSectionNames(PDBFile
&File
) {
499 auto ExpectedHeaders
= loadSectionHeaders(File
, DbgHeaderType::SectionHdr
);
500 if (!ExpectedHeaders
)
503 std::unique_ptr
<MappedBlockStream
> Stream
;
504 ArrayRef
<object::coff_section
> Headers
;
505 std::tie(Stream
, Headers
) = std::move(*ExpectedHeaders
);
506 std::vector
<std::string
> Names
;
507 for (const auto &H
: Headers
)
508 Names
.push_back(H
.Name
);
512 static void dumpSectionContrib(LinePrinter
&P
, const SectionContrib
&SC
,
513 ArrayRef
<std::string
> SectionNames
,
514 uint32_t FieldWidth
) {
515 std::string NameInsert
;
516 if (SC
.ISect
> 0 && SC
.ISect
<= SectionNames
.size()) {
517 StringRef SectionName
= SectionNames
[SC
.ISect
- 1];
518 NameInsert
= formatv("[{0}]", SectionName
).str();
520 NameInsert
= "[???]";
521 P
.formatLine("SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
523 formatSegmentOffset(SC
.ISect
, SC
.Off
), fmtle(SC
.Size
),
524 fmtle(SC
.Imod
), fmtle(SC
.DataCrc
), fmtle(SC
.RelocCrc
),
525 fmt_align(NameInsert
, AlignStyle::Left
, FieldWidth
+ 2));
526 AutoIndent
Indent(P
, FieldWidth
+ 2);
528 formatSectionCharacteristics(P
.getIndentLevel() + 6,
529 SC
.Characteristics
, 3, " | "));
532 static void dumpSectionContrib(LinePrinter
&P
, const SectionContrib2
&SC
,
533 ArrayRef
<std::string
> SectionNames
,
534 uint32_t FieldWidth
) {
535 P
.formatLine("SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
536 "crc = {4}, coff section = {5}",
537 formatSegmentOffset(SC
.Base
.ISect
, SC
.Base
.Off
),
538 fmtle(SC
.Base
.Size
), fmtle(SC
.Base
.Imod
), fmtle(SC
.Base
.DataCrc
),
539 fmtle(SC
.Base
.RelocCrc
), fmtle(SC
.ISectCoff
));
541 formatSectionCharacteristics(P
.getIndentLevel() + 6,
542 SC
.Base
.Characteristics
, 3, " | "));
545 Error
DumpOutputStyle::dumpModules() {
546 printHeader(P
, "Modules");
549 printStreamNotValidForObj();
550 return Error::success();
553 if (!getPdb().hasPDBDbiStream()) {
554 printStreamNotPresent("DBI");
555 return Error::success();
558 AutoIndent
Indent(P
);
559 ExitOnError
Err("Unexpected error processing modules: ");
561 auto &Stream
= Err(getPdb().getPDBDbiStream());
563 const DbiModuleList
&Modules
= Stream
.modules();
565 File
, PrintScope
{P
, 11}, [&](uint32_t Modi
, const SymbolGroup
&Strings
) {
566 auto Desc
= Modules
.getModuleDescriptor(Modi
);
567 if (opts::dump::DumpSectionContribs
) {
568 std::vector
<std::string
> Sections
= getSectionNames(getPdb());
569 dumpSectionContrib(P
, Desc
.getSectionContrib(), Sections
, 0);
571 P
.formatLine("Obj: `{0}`: ", Desc
.getObjFileName());
572 P
.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
573 Desc
.getModuleStreamIndex(), Desc
.getNumberOfFiles(),
575 StringRef PdbFilePath
=
576 Err(Stream
.getECName(Desc
.getPdbFilePathNameIndex()));
577 StringRef SrcFilePath
=
578 Err(Stream
.getECName(Desc
.getSourceFileNameIndex()));
579 P
.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
580 Desc
.getPdbFilePathNameIndex(), PdbFilePath
,
581 Desc
.getSourceFileNameIndex(), SrcFilePath
);
583 return Error::success();
586 Error
DumpOutputStyle::dumpModuleFiles() {
587 printHeader(P
, "Files");
590 printStreamNotValidForObj();
591 return Error::success();
594 if (!getPdb().hasPDBDbiStream()) {
595 printStreamNotPresent("DBI");
596 return Error::success();
599 ExitOnError
Err("Unexpected error processing modules: ");
601 iterateSymbolGroups(File
, PrintScope
{P
, 11},
602 [this, &Err
](uint32_t Modi
, const SymbolGroup
&Strings
) {
603 auto &Stream
= Err(getPdb().getPDBDbiStream());
605 const DbiModuleList
&Modules
= Stream
.modules();
606 for (const auto &F
: Modules
.source_files(Modi
)) {
607 Strings
.formatFromFileName(P
, F
);
610 return Error::success();
613 Error
DumpOutputStyle::dumpSymbolStats() {
614 printHeader(P
, "Module Stats");
616 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
617 printStreamNotPresent("DBI");
618 return Error::success();
621 ExitOnError
Err("Unexpected error processing modules: ");
623 StatCollection SymStats
;
624 StatCollection ChunkStats
;
626 Optional
<PrintScope
> Scope
;
630 iterateSymbolGroups(File
, Scope
, [&](uint32_t Modi
, const SymbolGroup
&SG
) {
631 StatCollection SS
= getSymbolStats(SG
, SymStats
);
632 StatCollection CS
= getChunkStats(SG
, ChunkStats
);
634 if (SG
.getFile().isPdb()) {
635 AutoIndent
Indent(P
);
636 auto Modules
= cantFail(File
.pdb().getPDBDbiStream()).modules();
637 uint32_t ModCount
= Modules
.getModuleCount();
638 DbiModuleDescriptor Desc
= Modules
.getModuleDescriptor(Modi
);
639 uint32_t StreamIdx
= Desc
.getModuleStreamIndex();
641 if (StreamIdx
== kInvalidStreamIndex
) {
642 P
.formatLine("Mod {0} (debug info not present): [{1}]",
643 fmt_align(Modi
, AlignStyle::Right
, NumDigits(ModCount
)),
644 Desc
.getModuleName());
647 P
.formatLine("Stream {0}, {1} bytes", StreamIdx
,
648 getPdb().getStreamByteSize(StreamIdx
));
650 printModuleDetailStats
<SymbolKind
>(P
, "Symbols", SS
);
651 printModuleDetailStats
<DebugSubsectionKind
>(P
, "Chunks", CS
);
655 if (SymStats
.Totals
.Count
> 0) {
656 P
.printLine(" Summary |");
657 AutoIndent
Indent(P
, 4);
658 printModuleDetailStats
<SymbolKind
>(P
, "Symbols", SymStats
);
659 printModuleDetailStats
<DebugSubsectionKind
>(P
, "Chunks", ChunkStats
);
662 return Error::success();
665 static bool isValidNamespaceIdentifier(StringRef S
) {
669 if (std::isdigit(S
[0]))
672 return llvm::all_of(S
, [](char C
) { return std::isalnum(C
); });
676 constexpr uint32_t kNoneUdtKind
= 0;
677 constexpr uint32_t kSimpleUdtKind
= 1;
678 constexpr uint32_t kUnknownUdtKind
= 2;
679 const StringRef
NoneLabel("<none type>");
680 const StringRef
SimpleLabel("<simple type>");
681 const StringRef
UnknownLabel("<unknown type>");
685 static StringRef
getUdtStatLabel(uint32_t Kind
) {
686 if (Kind
== kNoneUdtKind
)
689 if (Kind
== kSimpleUdtKind
)
692 if (Kind
== kUnknownUdtKind
)
695 return formatTypeLeafKind(static_cast<TypeLeafKind
>(Kind
));
698 static uint32_t getLongestTypeLeafName(const StatCollection
&Stats
) {
700 for (const auto &Stat
: Stats
.Individual
) {
701 StringRef Label
= getUdtStatLabel(Stat
.first
);
702 L
= std::max(L
, Label
.size());
704 return static_cast<uint32_t>(L
);
707 Error
DumpOutputStyle::dumpUdtStats() {
708 printHeader(P
, "S_UDT Record Stats");
710 if (File
.isPdb() && !getPdb().hasPDBGlobalsStream()) {
711 printStreamNotPresent("Globals");
712 return Error::success();
715 StatCollection UdtStats
;
716 StatCollection UdtTargetStats
;
717 AutoIndent
Indent(P
, 4);
719 auto &TpiTypes
= File
.types();
721 StringMap
<StatCollection::Stat
> NamespacedStats
;
723 size_t LongestNamespace
= 0;
724 auto HandleOneSymbol
= [&](const CVSymbol
&Sym
) {
725 if (Sym
.kind() != SymbolKind::S_UDT
)
727 UdtStats
.update(SymbolKind::S_UDT
, Sym
.length());
729 UDTSym UDT
= cantFail(SymbolDeserializer::deserializeAs
<UDTSym
>(Sym
));
732 uint32_t RecordSize
= 0;
734 if (UDT
.Type
.isNoneType())
736 else if (UDT
.Type
.isSimple())
737 Kind
= kSimpleUdtKind
;
738 else if (Optional
<CVType
> T
= TpiTypes
.tryGetType(UDT
.Type
)) {
740 RecordSize
= T
->length();
742 Kind
= kUnknownUdtKind
;
744 UdtTargetStats
.update(Kind
, RecordSize
);
746 size_t Pos
= UDT
.Name
.find("::");
747 if (Pos
== StringRef::npos
)
750 StringRef Scope
= UDT
.Name
.take_front(Pos
);
751 if (Scope
.empty() || !isValidNamespaceIdentifier(Scope
))
754 LongestNamespace
= std::max(LongestNamespace
, Scope
.size());
755 NamespacedStats
[Scope
].update(RecordSize
);
761 auto &SymbolRecords
= cantFail(getPdb().getPDBSymbolStream());
762 auto ExpGlobals
= getPdb().getPDBGlobalsStream();
764 return ExpGlobals
.takeError();
766 for (uint32_t PubSymOff
: ExpGlobals
->getGlobalsTable()) {
767 CVSymbol Sym
= SymbolRecords
.readRecord(PubSymOff
);
768 HandleOneSymbol(Sym
);
771 for (const auto &Sec
: File
.symbol_groups()) {
772 for (const auto &SS
: Sec
.getDebugSubsections()) {
773 if (SS
.kind() != DebugSubsectionKind::Symbols
)
776 DebugSymbolsSubsectionRef Symbols
;
777 BinaryStreamReader
Reader(SS
.getRecordData());
778 cantFail(Symbols
.initialize(Reader
));
779 for (const auto &S
: Symbols
)
785 LongestNamespace
+= StringRef(" namespace ''").size();
786 size_t LongestTypeLeafKind
= getLongestTypeLeafName(UdtTargetStats
);
787 size_t FieldWidth
= std::max(LongestNamespace
, LongestTypeLeafKind
);
789 // Compute the max number of digits for count and size fields, including comma
791 StringRef
CountHeader("Count");
792 StringRef
SizeHeader("Size");
793 size_t CD
= NumDigits(UdtStats
.Totals
.Count
);
795 CD
= std::max(CD
, CountHeader
.size());
797 size_t SD
= NumDigits(UdtStats
.Totals
.Size
);
799 SD
= std::max(SD
, SizeHeader
.size());
801 uint32_t TableWidth
= FieldWidth
+ 3 + CD
+ 2 + SD
+ 1;
803 P
.formatLine("{0} | {1} {2}",
804 fmt_align("Record Kind", AlignStyle::Right
, FieldWidth
),
805 fmt_align(CountHeader
, AlignStyle::Right
, CD
),
806 fmt_align(SizeHeader
, AlignStyle::Right
, SD
));
808 P
.formatLine("{0}", fmt_repeat('-', TableWidth
));
809 for (const auto &Stat
: UdtTargetStats
.Individual
) {
810 StringRef Label
= getUdtStatLabel(Stat
.first
);
811 P
.formatLine("{0} | {1:N} {2:N}",
812 fmt_align(Label
, AlignStyle::Right
, FieldWidth
),
813 fmt_align(Stat
.second
.Count
, AlignStyle::Right
, CD
),
814 fmt_align(Stat
.second
.Size
, AlignStyle::Right
, SD
));
816 P
.formatLine("{0}", fmt_repeat('-', TableWidth
));
817 P
.formatLine("{0} | {1:N} {2:N}",
818 fmt_align("Total (S_UDT)", AlignStyle::Right
, FieldWidth
),
819 fmt_align(UdtStats
.Totals
.Count
, AlignStyle::Right
, CD
),
820 fmt_align(UdtStats
.Totals
.Size
, AlignStyle::Right
, SD
));
821 P
.formatLine("{0}", fmt_repeat('-', TableWidth
));
822 for (const auto &Stat
: NamespacedStats
) {
823 std::string Label
= formatv("namespace '{0}'", Stat
.getKey());
824 P
.formatLine("{0} | {1:N} {2:N}",
825 fmt_align(Label
, AlignStyle::Right
, FieldWidth
),
826 fmt_align(Stat
.second
.Count
, AlignStyle::Right
, CD
),
827 fmt_align(Stat
.second
.Size
, AlignStyle::Right
, SD
));
829 return Error::success();
832 static void typesetLinesAndColumns(LinePrinter
&P
, uint32_t Start
,
833 const LineColumnEntry
&E
) {
834 const uint32_t kMaxCharsPerLineNumber
= 4; // 4 digit line number
835 uint32_t MinColumnWidth
= kMaxCharsPerLineNumber
+ 5;
837 // Let's try to keep it under 100 characters
838 constexpr uint32_t kMaxRowLength
= 100;
839 // At least 3 spaces between columns.
840 uint32_t ColumnsPerRow
= kMaxRowLength
/ (MinColumnWidth
+ 3);
841 uint32_t ItemsLeft
= E
.LineNumbers
.size();
842 auto LineIter
= E
.LineNumbers
.begin();
843 while (ItemsLeft
!= 0) {
844 uint32_t RowColumns
= std::min(ItemsLeft
, ColumnsPerRow
);
845 for (uint32_t I
= 0; I
< RowColumns
; ++I
) {
846 LineInfo
Line(LineIter
->Flags
);
848 if (Line
.isAlwaysStepInto())
850 else if (Line
.isNeverStepInto())
853 LineStr
= utostr(Line
.getStartLine());
854 char Statement
= Line
.isStatement() ? ' ' : '!';
855 P
.format("{0} {1:X-} {2} ",
856 fmt_align(LineStr
, AlignStyle::Right
, kMaxCharsPerLineNumber
),
857 fmt_align(Start
+ LineIter
->Offset
, AlignStyle::Right
, 8, '0'),
866 Error
DumpOutputStyle::dumpLines() {
867 printHeader(P
, "Lines");
869 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
870 printStreamNotPresent("DBI");
871 return Error::success();
874 uint32_t LastModi
= UINT32_MAX
;
875 uint32_t LastNameIndex
= UINT32_MAX
;
876 iterateModuleSubsections
<DebugLinesSubsectionRef
>(
877 File
, PrintScope
{P
, 4},
878 [this, &LastModi
, &LastNameIndex
](uint32_t Modi
,
879 const SymbolGroup
&Strings
,
880 DebugLinesSubsectionRef
&Lines
) {
881 uint16_t Segment
= Lines
.header()->RelocSegment
;
882 uint32_t Begin
= Lines
.header()->RelocOffset
;
883 uint32_t End
= Begin
+ Lines
.header()->CodeSize
;
884 for (const auto &Block
: Lines
) {
885 if (LastModi
!= Modi
|| LastNameIndex
!= Block
.NameIndex
) {
887 LastNameIndex
= Block
.NameIndex
;
888 Strings
.formatFromChecksumsOffset(P
, Block
.NameIndex
);
891 AutoIndent
Indent(P
, 2);
892 P
.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment
, Begin
, End
);
893 uint32_t Count
= Block
.LineNumbers
.size();
894 if (Lines
.hasColumnInfo())
895 P
.format("line/column/addr entries = {0}", Count
);
897 P
.format("line/addr entries = {0}", Count
);
900 typesetLinesAndColumns(P
, Begin
, Block
);
904 return Error::success();
907 Error
DumpOutputStyle::dumpInlineeLines() {
908 printHeader(P
, "Inlinee Lines");
910 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
911 printStreamNotPresent("DBI");
912 return Error::success();
915 iterateModuleSubsections
<DebugInlineeLinesSubsectionRef
>(
916 File
, PrintScope
{P
, 2},
917 [this](uint32_t Modi
, const SymbolGroup
&Strings
,
918 DebugInlineeLinesSubsectionRef
&Lines
) {
919 P
.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
920 for (const auto &Entry
: Lines
) {
921 P
.formatLine("{0,+8} | {1,+5} | ", Entry
.Header
->Inlinee
,
922 fmtle(Entry
.Header
->SourceLineNum
));
923 Strings
.formatFromChecksumsOffset(P
, Entry
.Header
->FileID
, true);
928 return Error::success();
931 Error
DumpOutputStyle::dumpXmi() {
932 printHeader(P
, "Cross Module Imports");
934 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
935 printStreamNotPresent("DBI");
936 return Error::success();
939 iterateModuleSubsections
<DebugCrossModuleImportsSubsectionRef
>(
940 File
, PrintScope
{P
, 2},
941 [this](uint32_t Modi
, const SymbolGroup
&Strings
,
942 DebugCrossModuleImportsSubsectionRef
&Imports
) {
943 P
.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
945 for (const auto &Xmi
: Imports
) {
946 auto ExpectedModule
=
947 Strings
.getNameFromStringTable(Xmi
.Header
->ModuleNameOffset
);
949 SmallString
<32> ModuleStorage
;
950 if (!ExpectedModule
) {
951 Module
= "(unknown module)";
952 consumeError(ExpectedModule
.takeError());
954 Module
= *ExpectedModule
;
955 if (Module
.size() > 32) {
956 ModuleStorage
= "...";
957 ModuleStorage
+= Module
.take_back(32 - 3);
958 Module
= ModuleStorage
;
960 std::vector
<std::string
> TIs
;
961 for (const auto I
: Xmi
.Imports
)
962 TIs
.push_back(formatv("{0,+10:X+}", fmtle(I
)));
964 typesetItemList(TIs
, P
.getIndentLevel() + 35, 12, " ");
965 P
.formatLine("{0,+32} | {1}", Module
, Result
);
969 return Error::success();
972 Error
DumpOutputStyle::dumpXme() {
973 printHeader(P
, "Cross Module Exports");
975 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
976 printStreamNotPresent("DBI");
977 return Error::success();
980 iterateModuleSubsections
<DebugCrossModuleExportsSubsectionRef
>(
981 File
, PrintScope
{P
, 2},
982 [this](uint32_t Modi
, const SymbolGroup
&Strings
,
983 DebugCrossModuleExportsSubsectionRef
&Exports
) {
984 P
.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
985 for (const auto &Export
: Exports
) {
986 P
.formatLine("{0,+10:X+} | {1}", TypeIndex(Export
.Local
),
987 TypeIndex(Export
.Global
));
991 return Error::success();
994 std::string
formatFrameType(object::frame_type FT
) {
996 case object::frame_type::Fpo
:
998 case object::frame_type::NonFpo
:
1000 case object::frame_type::Trap
:
1002 case object::frame_type::Tss
:
1008 Error
DumpOutputStyle::dumpOldFpo(PDBFile
&File
) {
1009 printHeader(P
, "Old FPO Data");
1011 ExitOnError
Err("Error dumping old fpo data:");
1012 auto &Dbi
= Err(File
.getPDBDbiStream());
1014 uint32_t Index
= Dbi
.getDebugStreamIndex(DbgHeaderType::FPO
);
1015 if (Index
== kInvalidStreamIndex
) {
1016 printStreamNotPresent("FPO");
1017 return Error::success();
1020 std::unique_ptr
<MappedBlockStream
> OldFpo
= File
.createIndexedStream(Index
);
1021 BinaryStreamReader
Reader(*OldFpo
);
1022 FixedStreamArray
<object::FpoData
> Records
;
1023 Err(Reader
.readArray(Records
,
1024 Reader
.bytesRemaining() / sizeof(object::FpoData
)));
1026 P
.printLine(" RVA | Code | Locals | Params | Prolog | Saved Regs | Use "
1027 "BP | Has SEH | Frame Type");
1029 for (const object::FpoData
&FD
: Records
) {
1030 P
.formatLine("{0:X-8} | {1,4} | {2,6} | {3,6} | {4,6} | {5,10} | {6,6} | "
1032 uint32_t(FD
.Offset
), uint32_t(FD
.Size
), uint32_t(FD
.NumLocals
),
1033 uint32_t(FD
.NumParams
), FD
.getPrologSize(),
1034 FD
.getNumSavedRegs(), FD
.useBP(), FD
.hasSEH(),
1035 formatFrameType(FD
.getFP()));
1037 return Error::success();
1040 Error
DumpOutputStyle::dumpNewFpo(PDBFile
&File
) {
1041 printHeader(P
, "New FPO Data");
1043 ExitOnError
Err("Error dumping new fpo data:");
1044 auto &Dbi
= Err(File
.getPDBDbiStream());
1046 uint32_t Index
= Dbi
.getDebugStreamIndex(DbgHeaderType::NewFPO
);
1047 if (Index
== kInvalidStreamIndex
) {
1048 printStreamNotPresent("New FPO");
1049 return Error::success();
1052 std::unique_ptr
<MappedBlockStream
> NewFpo
= File
.createIndexedStream(Index
);
1054 DebugFrameDataSubsectionRef FDS
;
1055 if (auto EC
= FDS
.initialize(*NewFpo
))
1056 return make_error
<RawError
>(raw_error_code::corrupt_file
,
1057 "Invalid new fpo stream");
1059 P
.printLine(" RVA | Code | Locals | Params | Stack | Prolog | Saved Regs "
1060 "| Has SEH | Has C++EH | Start | Program");
1061 for (const FrameData
&FD
: FDS
) {
1062 bool IsFuncStart
= FD
.Flags
& FrameData::IsFunctionStart
;
1063 bool HasEH
= FD
.Flags
& FrameData::HasEH
;
1064 bool HasSEH
= FD
.Flags
& FrameData::HasSEH
;
1066 auto &StringTable
= Err(File
.getStringTable());
1068 auto Program
= Err(StringTable
.getStringForID(FD
.FrameFunc
));
1069 P
.formatLine("{0:X-8} | {1,4} | {2,6} | {3,6} | {4,5} | {5,6} | {6,10} | "
1070 "{7,7} | {8,9} | {9,5} | {10}",
1071 uint32_t(FD
.RvaStart
), uint32_t(FD
.CodeSize
),
1072 uint32_t(FD
.LocalSize
), uint32_t(FD
.ParamsSize
),
1073 uint32_t(FD
.MaxStackSize
), uint16_t(FD
.PrologSize
),
1074 uint16_t(FD
.SavedRegsSize
), HasSEH
, HasEH
, IsFuncStart
,
1077 return Error::success();
1080 Error
DumpOutputStyle::dumpFpo() {
1081 if (!File
.isPdb()) {
1082 printStreamNotValidForObj();
1083 return Error::success();
1086 PDBFile
&File
= getPdb();
1087 if (!File
.hasPDBDbiStream()) {
1088 printStreamNotPresent("DBI");
1089 return Error::success();
1092 if (auto EC
= dumpOldFpo(File
))
1094 if (auto EC
= dumpNewFpo(File
))
1096 return Error::success();
1099 Error
DumpOutputStyle::dumpStringTableFromPdb() {
1100 AutoIndent
Indent(P
);
1101 auto IS
= getPdb().getStringTable();
1103 P
.formatLine("Not present in file");
1104 consumeError(IS
.takeError());
1105 return Error::success();
1108 if (opts::dump::DumpStringTable
) {
1109 if (IS
->name_ids().empty())
1110 P
.formatLine("Empty");
1113 std::max_element(IS
->name_ids().begin(), IS
->name_ids().end());
1114 uint32_t Digits
= NumDigits(*MaxID
);
1116 P
.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right
, Digits
),
1119 std::vector
<uint32_t> SortedIDs(IS
->name_ids().begin(),
1120 IS
->name_ids().end());
1121 llvm::sort(SortedIDs
.begin(), SortedIDs
.end());
1122 for (uint32_t I
: SortedIDs
) {
1123 auto ES
= IS
->getStringForID(I
);
1124 llvm::SmallString
<32> Str
;
1126 consumeError(ES
.takeError());
1127 Str
= "Error reading string";
1128 } else if (!ES
->empty()) {
1135 P
.formatLine("{0} | {1}", fmt_align(I
, AlignStyle::Right
, Digits
),
1141 if (opts::dump::DumpStringTableDetails
) {
1144 P
.printLine("String Table Header:");
1145 AutoIndent
Indent(P
);
1146 P
.formatLine("Signature: {0}", IS
->getSignature());
1147 P
.formatLine("Hash Version: {0}", IS
->getHashVersion());
1148 P
.formatLine("Name Buffer Size: {0}", IS
->getByteSize());
1152 BinaryStreamRef NameBuffer
= IS
->getStringTable().getBuffer();
1153 ArrayRef
<uint8_t> Contents
;
1154 cantFail(NameBuffer
.readBytes(0, NameBuffer
.getLength(), Contents
));
1155 P
.formatBinary("Name Buffer", Contents
, 0);
1158 P
.printLine("Hash Table:");
1159 AutoIndent
Indent(P
);
1160 P
.formatLine("Bucket Count: {0}", IS
->name_ids().size());
1161 for (const auto &Entry
: enumerate(IS
->name_ids()))
1162 P
.formatLine("Bucket[{0}] : {1}", Entry
.index(),
1163 uint32_t(Entry
.value()));
1164 P
.formatLine("Name Count: {0}", IS
->getNameCount());
1167 return Error::success();
1170 Error
DumpOutputStyle::dumpStringTableFromObj() {
1171 iterateModuleSubsections
<DebugStringTableSubsectionRef
>(
1172 File
, PrintScope
{P
, 4},
1173 [&](uint32_t Modi
, const SymbolGroup
&Strings
,
1174 DebugStringTableSubsectionRef
&Strings2
) {
1175 BinaryStreamRef StringTableBuffer
= Strings2
.getBuffer();
1176 BinaryStreamReader
Reader(StringTableBuffer
);
1177 while (Reader
.bytesRemaining() > 0) {
1179 uint32_t Offset
= Reader
.getOffset();
1180 cantFail(Reader
.readCString(Str
));
1184 P
.formatLine("{0} | {1}", fmt_align(Offset
, AlignStyle::Right
, 4),
1188 return Error::success();
1191 Error
DumpOutputStyle::dumpNamedStreams() {
1192 printHeader(P
, "Named Streams");
1195 printStreamNotValidForObj();
1196 return Error::success();
1199 AutoIndent
Indent(P
);
1200 ExitOnError
Err("Invalid PDB File: ");
1202 auto &IS
= Err(File
.pdb().getPDBInfoStream());
1203 const NamedStreamMap
&NS
= IS
.getNamedStreams();
1204 for (const auto &Entry
: NS
.entries()) {
1205 P
.printLine(Entry
.getKey());
1206 AutoIndent
Indent2(P
, 2);
1207 P
.formatLine("Index: {0}", Entry
.getValue());
1208 P
.formatLine("Size in bytes: {0}",
1209 File
.pdb().getStreamByteSize(Entry
.getValue()));
1212 return Error::success();
1215 Error
DumpOutputStyle::dumpStringTable() {
1216 printHeader(P
, "String Table");
1219 return dumpStringTableFromPdb();
1221 return dumpStringTableFromObj();
1224 static void buildDepSet(LazyRandomTypeCollection
&Types
,
1225 ArrayRef
<TypeIndex
> Indices
,
1226 std::map
<TypeIndex
, CVType
> &DepSet
) {
1227 SmallVector
<TypeIndex
, 4> DepList
;
1228 for (const auto &I
: Indices
) {
1230 if (DepSet
.find(TI
) != DepSet
.end() || TI
.isSimple() || TI
.isNoneType())
1233 CVType Type
= Types
.getType(TI
);
1235 codeview::discoverTypeIndices(Type
, DepList
);
1236 buildDepSet(Types
, DepList
, DepSet
);
1241 dumpFullTypeStream(LinePrinter
&Printer
, LazyRandomTypeCollection
&Types
,
1242 uint32_t NumTypeRecords
, uint32_t NumHashBuckets
,
1243 FixedStreamArray
<support::ulittle32_t
> HashValues
,
1244 bool Bytes
, bool Extras
) {
1246 Printer
.formatLine("Showing {0:N} records", NumTypeRecords
);
1247 uint32_t Width
= NumDigits(TypeIndex::FirstNonSimpleIndex
+ NumTypeRecords
);
1249 MinimalTypeDumpVisitor
V(Printer
, Width
+ 2, Bytes
, Extras
, Types
,
1250 NumHashBuckets
, HashValues
);
1252 if (auto EC
= codeview::visitTypeStream(Types
, V
)) {
1253 Printer
.formatLine("An error occurred dumping type records: {0}",
1254 toString(std::move(EC
)));
1258 static void dumpPartialTypeStream(LinePrinter
&Printer
,
1259 LazyRandomTypeCollection
&Types
,
1260 TpiStream
&Stream
, ArrayRef
<TypeIndex
> TiList
,
1261 bool Bytes
, bool Extras
, bool Deps
) {
1263 NumDigits(TypeIndex::FirstNonSimpleIndex
+ Stream
.getNumTypeRecords());
1265 MinimalTypeDumpVisitor
V(Printer
, Width
+ 2, Bytes
, Extras
, Types
,
1266 Stream
.getNumHashBuckets(), Stream
.getHashValues());
1268 if (opts::dump::DumpTypeDependents
) {
1269 // If we need to dump all dependents, then iterate each index and find
1270 // all dependents, adding them to a map ordered by TypeIndex.
1271 std::map
<TypeIndex
, CVType
> DepSet
;
1272 buildDepSet(Types
, TiList
, DepSet
);
1275 "Showing {0:N} records and their dependents ({1:N} records total)",
1276 TiList
.size(), DepSet
.size());
1278 for (auto &Dep
: DepSet
) {
1279 if (auto EC
= codeview::visitTypeRecord(Dep
.second
, Dep
.first
, V
))
1280 Printer
.formatLine("An error occurred dumping type record {0}: {1}",
1281 Dep
.first
, toString(std::move(EC
)));
1284 Printer
.formatLine("Showing {0:N} records.", TiList
.size());
1286 for (const auto &I
: TiList
) {
1288 CVType Type
= Types
.getType(TI
);
1289 if (auto EC
= codeview::visitTypeRecord(Type
, TI
, V
))
1290 Printer
.formatLine("An error occurred dumping type record {0}: {1}", TI
,
1291 toString(std::move(EC
)));
1296 Error
DumpOutputStyle::dumpTypesFromObjectFile() {
1297 LazyRandomTypeCollection
Types(100);
1299 for (const auto &S
: getObj().sections()) {
1300 StringRef SectionName
;
1301 if (auto EC
= S
.getName(SectionName
))
1302 return errorCodeToError(EC
);
1304 // .debug$T is a standard CodeView type section, while .debug$P is the same
1305 // format but used for MSVC precompiled header object files.
1306 if (SectionName
== ".debug$T")
1307 printHeader(P
, "Types (.debug$T)");
1308 else if (SectionName
== ".debug$P")
1309 printHeader(P
, "Precompiled Types (.debug$P)");
1314 if (auto EC
= S
.getContents(Contents
))
1315 return errorCodeToError(EC
);
1318 BinaryStreamReader
Reader(Contents
, llvm::support::little
);
1319 if (auto EC
= Reader
.readInteger(Magic
))
1321 if (Magic
!= COFF::DEBUG_SECTION_MAGIC
)
1322 return make_error
<StringError
>("Invalid CodeView debug section.",
1323 inconvertibleErrorCode());
1325 Types
.reset(Reader
, 100);
1327 if (opts::dump::DumpTypes
) {
1328 dumpFullTypeStream(P
, Types
, 0, 0, {}, opts::dump::DumpTypeData
, false);
1329 } else if (opts::dump::DumpTypeExtras
) {
1330 auto LocalHashes
= LocallyHashedType::hashTypeCollection(Types
);
1331 auto GlobalHashes
= GloballyHashedType::hashTypeCollection(Types
);
1332 assert(LocalHashes
.size() == GlobalHashes
.size());
1334 P
.formatLine("Local / Global hashes:");
1335 TypeIndex
TI(TypeIndex::FirstNonSimpleIndex
);
1336 for (const auto &H
: zip(LocalHashes
, GlobalHashes
)) {
1337 AutoIndent
Indent2(P
);
1338 LocallyHashedType
&L
= std::get
<0>(H
);
1339 GloballyHashedType
&G
= std::get
<1>(H
);
1341 P
.formatLine("TI: {0}, LocalHash: {1:X}, GlobalHash: {2}", TI
, L
, G
);
1349 return Error::success();
1352 Error
DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx
) {
1353 assert(StreamIdx
== StreamTPI
|| StreamIdx
== StreamIPI
);
1355 if (StreamIdx
== StreamTPI
) {
1356 printHeader(P
, "Types (TPI Stream)");
1357 } else if (StreamIdx
== StreamIPI
) {
1358 printHeader(P
, "Types (IPI Stream)");
1361 assert(!File
.isObj());
1363 bool Present
= false;
1364 bool DumpTypes
= false;
1365 bool DumpBytes
= false;
1366 bool DumpExtras
= false;
1367 std::vector
<uint32_t> Indices
;
1368 if (StreamIdx
== StreamTPI
) {
1369 Present
= getPdb().hasPDBTpiStream();
1370 DumpTypes
= opts::dump::DumpTypes
;
1371 DumpBytes
= opts::dump::DumpTypeData
;
1372 DumpExtras
= opts::dump::DumpTypeExtras
;
1373 Indices
.assign(opts::dump::DumpTypeIndex
.begin(),
1374 opts::dump::DumpTypeIndex
.end());
1375 } else if (StreamIdx
== StreamIPI
) {
1376 Present
= getPdb().hasPDBIpiStream();
1377 DumpTypes
= opts::dump::DumpIds
;
1378 DumpBytes
= opts::dump::DumpIdData
;
1379 DumpExtras
= opts::dump::DumpIdExtras
;
1380 Indices
.assign(opts::dump::DumpIdIndex
.begin(),
1381 opts::dump::DumpIdIndex
.end());
1385 printStreamNotPresent(StreamIdx
== StreamTPI
? "TPI" : "IPI");
1386 return Error::success();
1389 AutoIndent
Indent(P
);
1390 ExitOnError
Err("Unexpected error processing types: ");
1392 auto &Stream
= Err((StreamIdx
== StreamTPI
) ? getPdb().getPDBTpiStream()
1393 : getPdb().getPDBIpiStream());
1395 auto &Types
= (StreamIdx
== StreamTPI
) ? File
.types() : File
.ids();
1397 if (DumpTypes
|| !Indices
.empty()) {
1398 if (Indices
.empty())
1399 dumpFullTypeStream(P
, Types
, Stream
.getNumTypeRecords(),
1400 Stream
.getNumHashBuckets(), Stream
.getHashValues(),
1401 DumpBytes
, DumpExtras
);
1403 std::vector
<TypeIndex
> TiList(Indices
.begin(), Indices
.end());
1404 dumpPartialTypeStream(P
, Types
, Stream
, TiList
, DumpBytes
, DumpExtras
,
1405 opts::dump::DumpTypeDependents
);
1411 auto IndexOffsets
= Stream
.getTypeIndexOffsets();
1412 P
.formatLine("Type Index Offsets:");
1413 for (const auto &IO
: IndexOffsets
) {
1414 AutoIndent
Indent2(P
);
1415 P
.formatLine("TI: {0}, Offset: {1}", IO
.Type
, fmtle(IO
.Offset
));
1419 P
.formatLine("Hash Adjusters:");
1420 auto &Adjusters
= Stream
.getHashAdjusters();
1421 auto &Strings
= Err(getPdb().getStringTable());
1422 for (const auto &A
: Adjusters
) {
1423 AutoIndent
Indent2(P
);
1424 auto ExpectedStr
= Strings
.getStringForID(A
.first
);
1425 TypeIndex
TI(A
.second
);
1427 P
.formatLine("`{0}` -> {1}", *ExpectedStr
, TI
);
1429 P
.formatLine("unknown str id ({0}) -> {1}", A
.first
, TI
);
1430 consumeError(ExpectedStr
.takeError());
1434 return Error::success();
1437 Error
DumpOutputStyle::dumpModuleSymsForObj() {
1438 printHeader(P
, "Symbols");
1440 AutoIndent
Indent(P
);
1442 ExitOnError
Err("Unexpected error processing symbols: ");
1444 auto &Types
= File
.types();
1446 SymbolVisitorCallbackPipeline Pipeline
;
1447 SymbolDeserializer
Deserializer(nullptr, CodeViewContainer::ObjectFile
);
1448 MinimalSymbolDumper
Dumper(P
, opts::dump::DumpSymRecordBytes
, Types
, Types
);
1450 Pipeline
.addCallbackToPipeline(Deserializer
);
1451 Pipeline
.addCallbackToPipeline(Dumper
);
1452 CVSymbolVisitor
Visitor(Pipeline
);
1454 std::unique_ptr
<llvm::Error
> SymbolError
;
1456 iterateModuleSubsections
<DebugSymbolsSubsectionRef
>(
1457 File
, PrintScope
{P
, 2},
1458 [&](uint32_t Modi
, const SymbolGroup
&Strings
,
1459 DebugSymbolsSubsectionRef
&Symbols
) {
1460 Dumper
.setSymbolGroup(&Strings
);
1461 for (auto Symbol
: Symbols
) {
1462 if (auto EC
= Visitor
.visitSymbolRecord(Symbol
)) {
1463 SymbolError
= llvm::make_unique
<Error
>(std::move(EC
));
1470 return std::move(*SymbolError
);
1472 return Error::success();
1475 Error
DumpOutputStyle::dumpModuleSymsForPdb() {
1476 printHeader(P
, "Symbols");
1478 if (File
.isPdb() && !getPdb().hasPDBDbiStream()) {
1479 printStreamNotPresent("DBI");
1480 return Error::success();
1483 AutoIndent
Indent(P
);
1484 ExitOnError
Err("Unexpected error processing symbols: ");
1486 auto &Ids
= File
.ids();
1487 auto &Types
= File
.types();
1489 iterateSymbolGroups(
1490 File
, PrintScope
{P
, 2}, [&](uint32_t I
, const SymbolGroup
&Strings
) {
1491 auto ExpectedModS
= getModuleDebugStream(File
.pdb(), I
);
1492 if (!ExpectedModS
) {
1493 P
.formatLine("Error loading module stream {0}. {1}", I
,
1494 toString(ExpectedModS
.takeError()));
1498 ModuleDebugStreamRef
&ModS
= *ExpectedModS
;
1500 SymbolVisitorCallbackPipeline Pipeline
;
1501 SymbolDeserializer
Deserializer(nullptr, CodeViewContainer::Pdb
);
1502 MinimalSymbolDumper
Dumper(P
, opts::dump::DumpSymRecordBytes
, Strings
,
1505 Pipeline
.addCallbackToPipeline(Deserializer
);
1506 Pipeline
.addCallbackToPipeline(Dumper
);
1507 CVSymbolVisitor
Visitor(Pipeline
);
1508 auto SS
= ModS
.getSymbolsSubstream();
1510 Visitor
.visitSymbolStream(ModS
.getSymbolArray(), SS
.Offset
)) {
1511 P
.formatLine("Error while processing symbol records. {0}",
1512 toString(std::move(EC
)));
1516 return Error::success();
1519 Error
DumpOutputStyle::dumpGSIRecords() {
1520 printHeader(P
, "GSI Records");
1523 printStreamNotValidForObj();
1524 return Error::success();
1527 if (!getPdb().hasPDBSymbolStream()) {
1528 printStreamNotPresent("GSI Common Symbol");
1529 return Error::success();
1532 AutoIndent
Indent(P
);
1534 auto &Records
= cantFail(getPdb().getPDBSymbolStream());
1535 auto &Types
= File
.types();
1536 auto &Ids
= File
.ids();
1538 P
.printLine("Records");
1539 SymbolVisitorCallbackPipeline Pipeline
;
1540 SymbolDeserializer
Deserializer(nullptr, CodeViewContainer::Pdb
);
1541 MinimalSymbolDumper
Dumper(P
, opts::dump::DumpSymRecordBytes
, Ids
, Types
);
1543 Pipeline
.addCallbackToPipeline(Deserializer
);
1544 Pipeline
.addCallbackToPipeline(Dumper
);
1545 CVSymbolVisitor
Visitor(Pipeline
);
1547 BinaryStreamRef SymStream
= Records
.getSymbolArray().getUnderlyingStream();
1548 if (auto E
= Visitor
.visitSymbolStream(Records
.getSymbolArray(), 0))
1550 return Error::success();
1553 Error
DumpOutputStyle::dumpGlobals() {
1554 printHeader(P
, "Global Symbols");
1557 printStreamNotValidForObj();
1558 return Error::success();
1561 if (!getPdb().hasPDBGlobalsStream()) {
1562 printStreamNotPresent("Globals");
1563 return Error::success();
1566 AutoIndent
Indent(P
);
1567 ExitOnError
Err("Error dumping globals stream: ");
1568 auto &Globals
= Err(getPdb().getPDBGlobalsStream());
1570 const GSIHashTable
&Table
= Globals
.getGlobalsTable();
1571 Err(dumpSymbolsFromGSI(Table
, opts::dump::DumpGlobalExtras
));
1572 return Error::success();
1575 Error
DumpOutputStyle::dumpPublics() {
1576 printHeader(P
, "Public Symbols");
1579 printStreamNotValidForObj();
1580 return Error::success();
1583 if (!getPdb().hasPDBPublicsStream()) {
1584 printStreamNotPresent("Publics");
1585 return Error::success();
1588 AutoIndent
Indent(P
);
1589 ExitOnError
Err("Error dumping publics stream: ");
1590 auto &Publics
= Err(getPdb().getPDBPublicsStream());
1592 const GSIHashTable
&PublicsTable
= Publics
.getPublicsTable();
1593 if (opts::dump::DumpPublicExtras
) {
1594 P
.printLine("Publics Header");
1595 AutoIndent
Indent(P
);
1596 P
.formatLine("sym hash = {0}, thunk table addr = {1}", Publics
.getSymHash(),
1597 formatSegmentOffset(Publics
.getThunkTableSection(),
1598 Publics
.getThunkTableOffset()));
1600 Err(dumpSymbolsFromGSI(PublicsTable
, opts::dump::DumpPublicExtras
));
1602 // Skip the rest if we aren't dumping extras.
1603 if (!opts::dump::DumpPublicExtras
)
1604 return Error::success();
1606 P
.formatLine("Address Map");
1608 // These are offsets into the publics stream sorted by secidx:secrel.
1609 AutoIndent
Indent2(P
);
1610 for (uint32_t Addr
: Publics
.getAddressMap())
1611 P
.formatLine("off = {0}", Addr
);
1614 // The thunk map is optional debug info used for ILT thunks.
1615 if (!Publics
.getThunkMap().empty()) {
1616 P
.formatLine("Thunk Map");
1617 AutoIndent
Indent2(P
);
1618 for (uint32_t Addr
: Publics
.getThunkMap())
1619 P
.formatLine("{0:x8}", Addr
);
1622 // The section offsets table appears to be empty when incremental linking
1624 if (!Publics
.getSectionOffsets().empty()) {
1625 P
.formatLine("Section Offsets");
1626 AutoIndent
Indent2(P
);
1627 for (const SectionOffset
&SO
: Publics
.getSectionOffsets())
1628 P
.formatLine("{0:x4}:{1:x8}", uint16_t(SO
.Isect
), uint32_t(SO
.Off
));
1631 return Error::success();
1634 Error
DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable
&Table
,
1636 auto ExpectedSyms
= getPdb().getPDBSymbolStream();
1638 return ExpectedSyms
.takeError();
1639 auto &Types
= File
.types();
1640 auto &Ids
= File
.ids();
1643 P
.printLine("GSI Header");
1644 AutoIndent
Indent(P
);
1645 P
.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1646 Table
.getVerSignature(), Table
.getVerHeader(),
1647 Table
.getHashRecordSize(), Table
.getNumBuckets());
1651 P
.printLine("Records");
1652 SymbolVisitorCallbackPipeline Pipeline
;
1653 SymbolDeserializer
Deserializer(nullptr, CodeViewContainer::Pdb
);
1654 MinimalSymbolDumper
Dumper(P
, opts::dump::DumpSymRecordBytes
, Ids
, Types
);
1656 Pipeline
.addCallbackToPipeline(Deserializer
);
1657 Pipeline
.addCallbackToPipeline(Dumper
);
1658 CVSymbolVisitor
Visitor(Pipeline
);
1661 BinaryStreamRef SymStream
=
1662 ExpectedSyms
->getSymbolArray().getUnderlyingStream();
1663 for (uint32_t PubSymOff
: Table
) {
1664 Expected
<CVSymbol
> Sym
= readSymbolFromStream(SymStream
, PubSymOff
);
1666 return Sym
.takeError();
1667 if (auto E
= Visitor
.visitSymbolRecord(*Sym
, PubSymOff
))
1672 // Return early if we aren't dumping public hash table and address map info.
1674 P
.formatBinary("Hash Bitmap", Table
.HashBitmap
, 0);
1676 P
.formatLine("Hash Entries");
1678 AutoIndent
Indent2(P
);
1679 for (const PSHashRecord
&HR
: Table
.HashRecords
)
1680 P
.formatLine("off = {0}, refcnt = {1}", uint32_t(HR
.Off
),
1684 P
.formatLine("Hash Buckets");
1686 AutoIndent
Indent2(P
);
1687 for (uint32_t Hash
: Table
.HashBuckets
)
1688 P
.formatLine("{0:x8}", Hash
);
1692 return Error::success();
1695 static std::string
formatSegMapDescriptorFlag(uint32_t IndentLevel
,
1696 OMFSegDescFlags Flags
) {
1697 std::vector
<std::string
> Opts
;
1698 if (Flags
== OMFSegDescFlags::None
)
1701 PUSH_FLAG(OMFSegDescFlags
, Read
, Flags
, "read");
1702 PUSH_FLAG(OMFSegDescFlags
, Write
, Flags
, "write");
1703 PUSH_FLAG(OMFSegDescFlags
, Execute
, Flags
, "execute");
1704 PUSH_FLAG(OMFSegDescFlags
, AddressIs32Bit
, Flags
, "32 bit addr");
1705 PUSH_FLAG(OMFSegDescFlags
, IsSelector
, Flags
, "selector");
1706 PUSH_FLAG(OMFSegDescFlags
, IsAbsoluteAddress
, Flags
, "absolute addr");
1707 PUSH_FLAG(OMFSegDescFlags
, IsGroup
, Flags
, "group");
1708 return typesetItemList(Opts
, IndentLevel
, 4, " | ");
1711 Error
DumpOutputStyle::dumpSectionHeaders() {
1712 dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr
);
1713 dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig
);
1714 return Error::success();
1717 void DumpOutputStyle::dumpSectionHeaders(StringRef Label
, DbgHeaderType Type
) {
1718 printHeader(P
, Label
);
1721 printStreamNotValidForObj();
1725 if (!getPdb().hasPDBDbiStream()) {
1726 printStreamNotPresent("DBI");
1730 AutoIndent
Indent(P
);
1731 ExitOnError
Err("Error dumping section headers: ");
1732 std::unique_ptr
<MappedBlockStream
> Stream
;
1733 ArrayRef
<object::coff_section
> Headers
;
1734 auto ExpectedHeaders
= loadSectionHeaders(getPdb(), Type
);
1735 if (!ExpectedHeaders
) {
1736 P
.printLine(toString(ExpectedHeaders
.takeError()));
1739 std::tie(Stream
, Headers
) = std::move(*ExpectedHeaders
);
1742 for (const auto &Header
: Headers
) {
1744 P
.formatLine("SECTION HEADER #{0}", I
);
1745 P
.formatLine("{0,8} name", Header
.Name
);
1746 P
.formatLine("{0,8:X-} virtual size", uint32_t(Header
.VirtualSize
));
1747 P
.formatLine("{0,8:X-} virtual address", uint32_t(Header
.VirtualAddress
));
1748 P
.formatLine("{0,8:X-} size of raw data", uint32_t(Header
.SizeOfRawData
));
1749 P
.formatLine("{0,8:X-} file pointer to raw data",
1750 uint32_t(Header
.PointerToRawData
));
1751 P
.formatLine("{0,8:X-} file pointer to relocation table",
1752 uint32_t(Header
.PointerToRelocations
));
1753 P
.formatLine("{0,8:X-} file pointer to line numbers",
1754 uint32_t(Header
.PointerToLinenumbers
));
1755 P
.formatLine("{0,8:X-} number of relocations",
1756 uint32_t(Header
.NumberOfRelocations
));
1757 P
.formatLine("{0,8:X-} number of line numbers",
1758 uint32_t(Header
.NumberOfLinenumbers
));
1759 P
.formatLine("{0,8:X-} flags", uint32_t(Header
.Characteristics
));
1760 AutoIndent
IndentMore(P
, 9);
1761 P
.formatLine("{0}", formatSectionCharacteristics(
1762 P
.getIndentLevel(), Header
.Characteristics
, 1, ""));
1768 Error
DumpOutputStyle::dumpSectionContribs() {
1769 printHeader(P
, "Section Contributions");
1772 printStreamNotValidForObj();
1773 return Error::success();
1776 if (!getPdb().hasPDBDbiStream()) {
1777 printStreamNotPresent("DBI");
1778 return Error::success();
1781 AutoIndent
Indent(P
);
1782 ExitOnError
Err("Error dumping section contributions: ");
1784 auto &Dbi
= Err(getPdb().getPDBDbiStream());
1786 class Visitor
: public ISectionContribVisitor
{
1788 Visitor(LinePrinter
&P
, ArrayRef
<std::string
> Names
) : P(P
), Names(Names
) {
1789 auto Max
= std::max_element(
1790 Names
.begin(), Names
.end(),
1791 [](StringRef S1
, StringRef S2
) { return S1
.size() < S2
.size(); });
1792 MaxNameLen
= (Max
== Names
.end() ? 0 : Max
->size());
1794 void visit(const SectionContrib
&SC
) override
{
1795 dumpSectionContrib(P
, SC
, Names
, MaxNameLen
);
1797 void visit(const SectionContrib2
&SC
) override
{
1798 dumpSectionContrib(P
, SC
, Names
, MaxNameLen
);
1803 uint32_t MaxNameLen
;
1804 ArrayRef
<std::string
> Names
;
1807 std::vector
<std::string
> Names
= getSectionNames(getPdb());
1808 Visitor
V(P
, makeArrayRef(Names
));
1809 Dbi
.visitSectionContributions(V
);
1810 return Error::success();
1813 Error
DumpOutputStyle::dumpSectionMap() {
1814 printHeader(P
, "Section Map");
1817 printStreamNotValidForObj();
1818 return Error::success();
1821 if (!getPdb().hasPDBDbiStream()) {
1822 printStreamNotPresent("DBI");
1823 return Error::success();
1826 AutoIndent
Indent(P
);
1827 ExitOnError
Err("Error dumping section map: ");
1829 auto &Dbi
= Err(getPdb().getPDBDbiStream());
1832 for (auto &M
: Dbi
.getSectionMap()) {
1834 "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I
,
1835 fmtle(M
.Ovl
), fmtle(M
.Group
), fmtle(M
.Frame
), fmtle(M
.SecName
));
1836 P
.formatLine(" class = {0}, offset = {1}, size = {2}",
1837 fmtle(M
.ClassName
), fmtle(M
.Offset
), fmtle(M
.SecByteLength
));
1838 P
.formatLine(" flags = {0}",
1839 formatSegMapDescriptorFlag(
1840 P
.getIndentLevel() + 13,
1841 static_cast<OMFSegDescFlags
>(uint16_t(M
.Flags
))));
1844 return Error::success();