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 "MinimalSymbolDumper.h"
14 #include "MinimalTypeDumper.h"
15 #include "StreamUtil.h"
16 #include "llvm-pdbutil.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h"
20 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
21 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
22 #include "llvm/DebugInfo/CodeView/DebugCrossExSubsection.h"
23 #include "llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h"
24 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
25 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h"
29 #include "llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugUnknownSubsection.h"
31 #include "llvm/DebugInfo/CodeView/EnumTables.h"
32 #include "llvm/DebugInfo/CodeView/Formatters.h"
33 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
34 #include "llvm/DebugInfo/CodeView/Line.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
37 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h"
38 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
39 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
40 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
41 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
42 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
43 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h"
44 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
45 #include "llvm/DebugInfo/PDB/Native/EnumTables.h"
46 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
47 #include "llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h"
48 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
49 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
50 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
51 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
52 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
53 #include "llvm/DebugInfo/PDB/Native/RawError.h"
54 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
55 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
56 #include "llvm/DebugInfo/PDB/PDBExtras.h"
57 #include "llvm/Object/COFF.h"
58 #include "llvm/Support/BinaryStreamReader.h"
59 #include "llvm/Support/FormatAdapters.h"
60 #include "llvm/Support/FormatVariadic.h"
63 #include <unordered_map>
66 using namespace llvm::codeview;
67 using namespace llvm::msf;
68 using namespace llvm::pdb;
70 DumpOutputStyle::DumpOutputStyle(PDBFile &File)
71 : File(File), P(2, false, outs()) {}
73 Error DumpOutputStyle::dump() {
74 if (opts::dump::DumpSummary) {
75 if (auto EC = dumpFileSummary())
80 if (opts::dump::DumpStreams) {
81 if (auto EC = dumpStreamSummary())
86 if (opts::dump::DumpSymbolStats.getNumOccurrences() > 0) {
87 if (auto EC = dumpSymbolStats())
92 if (opts::dump::DumpUdtStats.getNumOccurrences() > 0) {
93 if (auto EC = dumpUdtStats())
98 if (opts::dump::DumpStringTable) {
99 if (auto EC = dumpStringTable())
104 if (opts::dump::DumpModules) {
105 if (auto EC = dumpModules())
109 if (opts::dump::DumpModuleFiles) {
110 if (auto EC = dumpModuleFiles())
114 if (opts::dump::DumpLines) {
115 if (auto EC = dumpLines())
119 if (opts::dump::DumpInlineeLines) {
120 if (auto EC = dumpInlineeLines())
124 if (opts::dump::DumpXmi) {
125 if (auto EC = dumpXmi())
129 if (opts::dump::DumpXme) {
130 if (auto EC = dumpXme())
134 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
135 opts::dump::DumpTypeExtras) {
136 if (auto EC = dumpTpiStream(StreamTPI))
140 if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
141 opts::dump::DumpIdExtras) {
142 if (auto EC = dumpTpiStream(StreamIPI))
146 if (opts::dump::DumpGlobals) {
147 if (auto EC = dumpGlobals())
151 if (opts::dump::DumpPublics) {
152 if (auto EC = dumpPublics())
156 if (opts::dump::DumpSymbols) {
157 if (auto EC = dumpModuleSyms())
161 if (opts::dump::DumpSectionHeaders) {
162 if (auto EC = dumpSectionHeaders())
166 if (opts::dump::DumpSectionContribs) {
167 if (auto EC = dumpSectionContribs())
171 if (opts::dump::DumpSectionMap) {
172 if (auto EC = dumpSectionMap())
176 return Error::success();
179 static void printHeader(LinePrinter &P, const Twine &S) {
181 P.formatLine("{0,=60}", S);
182 P.formatLine("{0}", fmt_repeat('=', 60));
185 Error DumpOutputStyle::dumpFileSummary() {
186 printHeader(P, "Summary");
188 ExitOnError Err("Invalid PDB Format: ");
190 AutoIndent Indent(P);
191 P.formatLine("Block Size: {0}", File.getBlockSize());
192 P.formatLine("Number of blocks: {0}", File.getBlockCount());
193 P.formatLine("Number of streams: {0}", File.getNumStreams());
195 auto &PS = Err(File.getPDBInfoStream());
196 P.formatLine("Signature: {0}", PS.getSignature());
197 P.formatLine("Age: {0}", PS.getAge());
198 P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
199 P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
200 P.formatLine("Has Debug Info: {0}", File.hasPDBDbiStream());
201 P.formatLine("Has Types: {0}", File.hasPDBTpiStream());
202 P.formatLine("Has IDs: {0}", File.hasPDBIpiStream());
203 P.formatLine("Has Globals: {0}", File.hasPDBGlobalsStream());
204 P.formatLine("Has Publics: {0}", File.hasPDBPublicsStream());
205 if (File.hasPDBDbiStream()) {
206 auto &DBI = Err(File.getPDBDbiStream());
207 P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
208 P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
209 P.formatLine("Is stripped: {0}", DBI.isStripped());
212 return Error::success();
215 static StatCollection getSymbolStats(ModuleDebugStreamRef MDS,
216 StatCollection &CumulativeStats) {
217 StatCollection Stats;
218 for (const auto &S : MDS.symbols(nullptr)) {
219 Stats.update(S.kind(), S.length());
220 CumulativeStats.update(S.kind(), S.length());
225 static StatCollection getChunkStats(ModuleDebugStreamRef MDS,
226 StatCollection &CumulativeStats) {
227 StatCollection Stats;
228 for (const auto &Chunk : MDS.subsections()) {
229 Stats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
230 CumulativeStats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
235 static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
236 return formatChunkKind(K, false);
239 static inline std::string formatModuleDetailKind(SymbolKind K) {
240 return formatSymbolKind(K);
243 template <typename Kind>
244 static void printModuleDetailStats(LinePrinter &P, StringRef Label,
245 const StatCollection &Stats) {
247 P.formatLine(" {0}", Label);
248 AutoIndent Indent(P);
249 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
250 Stats.Totals.Count, Stats.Totals.Size);
251 P.formatLine("{0}", fmt_repeat('-', 74));
252 for (const auto &K : Stats.Individual) {
253 std::string KindName = formatModuleDetailKind(Kind(K.first));
254 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName,
255 K.second.Count, K.second.Size);
259 static bool isMyCode(const DbiModuleDescriptor &Desc) {
260 StringRef Name = Desc.getModuleName();
261 if (Name.startswith("Import:"))
263 if (Name.endswith_lower(".dll"))
265 if (Name.equals_lower("* linker *"))
267 if (Name.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
269 if (Name.startswith_lower("f:\\dd\\vctools\\crt"))
274 static bool shouldDumpModule(uint32_t Modi, const DbiModuleDescriptor &Desc) {
275 if (opts::dump::JustMyCode && !isMyCode(Desc))
278 // If the arg was not specified on the command line, always dump all modules.
279 if (opts::dump::DumpModi.getNumOccurrences() == 0)
282 // Otherwise, only dump if this is the same module specified.
283 return (opts::dump::DumpModi == Modi);
286 Error DumpOutputStyle::dumpStreamSummary() {
287 printHeader(P, "Streams");
289 if (StreamPurposes.empty())
290 discoverStreamPurposes(File, StreamPurposes);
292 AutoIndent Indent(P);
293 uint32_t StreamCount = File.getNumStreams();
294 uint32_t MaxStreamSize = File.getMaxStreamSize();
296 for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
298 "Stream {0} ({1} bytes): [{2}]",
299 fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
300 fmt_align(File.getStreamByteSize(StreamIdx), AlignStyle::Right,
301 NumDigits(MaxStreamSize)),
302 StreamPurposes[StreamIdx].getLongName());
304 if (opts::dump::DumpStreamBlocks) {
305 auto Blocks = File.getStreamBlockList(StreamIdx);
306 std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
307 P.formatLine(" {0} Blocks: [{1}]",
308 fmt_repeat(' ', NumDigits(StreamCount)),
309 make_range(BV.begin(), BV.end()));
313 return Error::success();
316 static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
318 ExitOnError Err("Unexpected error: ");
320 auto &Dbi = Err(File.getPDBDbiStream());
321 const auto &Modules = Dbi.modules();
322 auto Modi = Modules.getModuleDescriptor(Index);
324 uint16_t ModiStream = Modi.getModuleStreamIndex();
325 if (ModiStream == kInvalidStreamIndex)
326 return make_error<RawError>(raw_error_code::no_stream,
327 "Module stream not present");
329 auto ModStreamData = MappedBlockStream::createIndexedStream(
330 File.getMsfLayout(), File.getMsfBuffer(), ModiStream,
331 File.getAllocator());
333 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
334 if (auto EC = ModS.reload())
335 return make_error<RawError>(raw_error_code::corrupt_file,
336 "Invalid module stream");
338 return std::move(ModS);
341 static std::string formatChecksumKind(FileChecksumKind Kind) {
343 RETURN_CASE(FileChecksumKind, None, "None");
344 RETURN_CASE(FileChecksumKind, MD5, "MD5");
345 RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
346 RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
348 return formatUnknownEnum(Kind);
352 class StringsAndChecksumsPrinter {
353 const DebugStringTableSubsectionRef &extractStringTable(PDBFile &File) {
354 ExitOnError Err("Unexpected error processing modules: ");
355 return Err(File.getStringTable()).getStringTable();
358 template <typename... Args>
359 void formatInternal(LinePrinter &Printer, bool Append,
360 Args &&... args) const {
362 Printer.format(std::forward<Args>(args)...);
364 Printer.formatLine(std::forward<Args>(args)...);
368 StringsAndChecksumsPrinter(PDBFile &File, uint32_t Modi)
369 : Records(extractStringTable(File)) {
370 auto MDS = getModuleDebugStream(File, Modi);
372 consumeError(MDS.takeError());
376 DebugStream = llvm::make_unique<ModuleDebugStreamRef>(std::move(*MDS));
377 Records.initialize(MDS->subsections());
378 if (Records.hasChecksums()) {
379 for (const auto &Entry : Records.checksums()) {
380 auto S = Records.strings().getString(Entry.FileNameOffset);
383 ChecksumsByFile[*S] = Entry;
388 Expected<StringRef> getNameFromStringTable(uint32_t Offset) const {
389 return Records.strings().getString(Offset);
392 void formatFromFileName(LinePrinter &Printer, StringRef File,
393 bool Append = false) const {
394 auto FC = ChecksumsByFile.find(File);
395 if (FC == ChecksumsByFile.end()) {
396 formatInternal(Printer, Append, "- (no checksum) {0}", File);
400 formatInternal(Printer, Append, "- ({0}: {1}) {2}",
401 formatChecksumKind(FC->getValue().Kind),
402 toHex(FC->getValue().Checksum), File);
405 void formatFromChecksumsOffset(LinePrinter &Printer, uint32_t Offset,
406 bool Append = false) const {
407 if (!Records.hasChecksums()) {
408 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
412 auto Iter = Records.checksums().getArray().at(Offset);
413 if (Iter == Records.checksums().getArray().end()) {
414 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
418 uint32_t FO = Iter->FileNameOffset;
419 auto ExpectedFile = getNameFromStringTable(FO);
421 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
422 consumeError(ExpectedFile.takeError());
425 if (Iter->Kind == FileChecksumKind::None) {
426 formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
428 formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
429 formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
433 std::unique_ptr<ModuleDebugStreamRef> DebugStream;
434 StringsAndChecksumsRef Records;
435 StringMap<FileChecksumEntry> ChecksumsByFile;
439 template <typename CallbackT>
440 static void iterateOneModule(PDBFile &File, LinePrinter &P,
441 const DbiModuleDescriptor &Descriptor,
442 uint32_t Modi, uint32_t IndentLevel,
443 uint32_t Digits, CallbackT Callback) {
445 "Mod {0:4} | `{1}`: ", fmt_align(Modi, AlignStyle::Right, Digits),
446 Descriptor.getModuleName());
448 StringsAndChecksumsPrinter Strings(File, Modi);
449 AutoIndent Indent2(P, IndentLevel);
450 Callback(Modi, Strings);
453 template <typename CallbackT>
454 static void iterateModules(PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
455 CallbackT Callback) {
456 AutoIndent Indent(P);
457 if (!File.hasPDBDbiStream()) {
458 P.formatLine("DBI Stream not present");
462 ExitOnError Err("Unexpected error processing modules: ");
464 auto &Stream = Err(File.getPDBDbiStream());
466 const DbiModuleList &Modules = Stream.modules();
468 if (opts::dump::DumpModi.getNumOccurrences() > 0) {
469 assert(opts::dump::DumpModi.getNumOccurrences() == 1);
470 uint32_t Modi = opts::dump::DumpModi;
471 auto Descriptor = Modules.getModuleDescriptor(Modi);
472 iterateOneModule(File, P, Descriptor, Modi, IndentLevel, NumDigits(Modi),
477 uint32_t Count = Modules.getModuleCount();
478 uint32_t Digits = NumDigits(Count);
479 for (uint32_t I = 0; I < Count; ++I) {
480 auto Desc = Modules.getModuleDescriptor(I);
481 if (!shouldDumpModule(I, Desc))
483 iterateOneModule(File, P, Desc, I, IndentLevel, Digits, Callback);
487 template <typename SubsectionT>
488 static void iterateModuleSubsections(
489 PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
490 llvm::function_ref<void(uint32_t, StringsAndChecksumsPrinter &,
495 File, P, IndentLevel,
496 [&File, &Callback](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
497 auto MDS = getModuleDebugStream(File, Modi);
499 consumeError(MDS.takeError());
503 for (const auto &SS : MDS->subsections()) {
504 SubsectionT Subsection;
506 if (SS.kind() != Subsection.kind())
509 BinaryStreamReader Reader(SS.getRecordData());
510 if (auto EC = Subsection.initialize(Reader))
512 Callback(Modi, Strings, Subsection);
517 Error DumpOutputStyle::dumpModules() {
518 printHeader(P, "Modules");
520 AutoIndent Indent(P);
521 if (!File.hasPDBDbiStream()) {
522 P.formatLine("DBI Stream not present");
523 return Error::success();
526 ExitOnError Err("Unexpected error processing modules: ");
528 auto &Stream = Err(File.getPDBDbiStream());
530 const DbiModuleList &Modules = Stream.modules();
532 File, P, 11, [&](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
533 auto Desc = Modules.getModuleDescriptor(Modi);
534 P.formatLine("Obj: `{0}`: ", Desc.getObjFileName());
535 P.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
536 Desc.getModuleStreamIndex(), Desc.getNumberOfFiles(),
538 StringRef PdbFilePath =
539 Err(Stream.getECName(Desc.getPdbFilePathNameIndex()));
540 StringRef SrcFilePath =
541 Err(Stream.getECName(Desc.getSourceFileNameIndex()));
542 P.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
543 Desc.getPdbFilePathNameIndex(), PdbFilePath,
544 Desc.getSourceFileNameIndex(), SrcFilePath);
546 return Error::success();
549 Error DumpOutputStyle::dumpModuleFiles() {
550 printHeader(P, "Files");
552 ExitOnError Err("Unexpected error processing modules: ");
556 [this, &Err](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
557 auto &Stream = Err(File.getPDBDbiStream());
559 const DbiModuleList &Modules = Stream.modules();
560 for (const auto &F : Modules.source_files(Modi)) {
561 Strings.formatFromFileName(P, F);
564 return Error::success();
567 Error DumpOutputStyle::dumpSymbolStats() {
568 printHeader(P, "Module Stats");
570 ExitOnError Err("Unexpected error processing modules: ");
572 StatCollection SymStats;
573 StatCollection ChunkStats;
574 auto &Stream = Err(File.getPDBDbiStream());
576 const DbiModuleList &Modules = Stream.modules();
577 uint32_t ModCount = Modules.getModuleCount();
579 iterateModules(File, P, 0, [&](uint32_t Modi,
580 StringsAndChecksumsPrinter &Strings) {
581 DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
582 uint32_t StreamIdx = Desc.getModuleStreamIndex();
584 if (StreamIdx == kInvalidStreamIndex) {
585 P.formatLine("Mod {0} (debug info not present): [{1}]",
586 fmt_align(Modi, AlignStyle::Right, NumDigits(ModCount)),
587 Desc.getModuleName());
591 P.formatLine("Stream {0}, {1} bytes", StreamIdx,
592 File.getStreamByteSize(StreamIdx));
594 ModuleDebugStreamRef MDS(Desc, File.createIndexedStream(StreamIdx));
595 if (auto EC = MDS.reload()) {
596 P.printLine("- Error parsing debug info stream");
597 consumeError(std::move(EC));
601 printModuleDetailStats<SymbolKind>(P, "Symbols",
602 getSymbolStats(MDS, SymStats));
603 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks",
604 getChunkStats(MDS, ChunkStats));
607 P.printLine(" Summary |");
608 AutoIndent Indent(P, 4);
609 if (SymStats.Totals.Count > 0) {
610 printModuleDetailStats<SymbolKind>(P, "Symbols", SymStats);
611 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", ChunkStats);
614 return Error::success();
617 static bool isValidNamespaceIdentifier(StringRef S) {
621 if (std::isdigit(S[0]))
624 return llvm::all_of(S, [](char C) { return std::isalnum(C); });
628 constexpr uint32_t kNoneUdtKind = 0;
629 constexpr uint32_t kSimpleUdtKind = 1;
630 constexpr uint32_t kUnknownUdtKind = 2;
631 const StringRef NoneLabel("<none type>");
632 const StringRef SimpleLabel("<simple type>");
633 const StringRef UnknownLabel("<unknown type>");
637 static StringRef getUdtStatLabel(uint32_t Kind) {
638 if (Kind == kNoneUdtKind)
641 if (Kind == kSimpleUdtKind)
644 if (Kind == kUnknownUdtKind)
647 return formatTypeLeafKind(static_cast<TypeLeafKind>(Kind));
650 static uint32_t getLongestTypeLeafName(const StatCollection &Stats) {
652 for (const auto &Stat : Stats.Individual) {
653 StringRef Label = getUdtStatLabel(Stat.first);
654 L = std::max(L, Label.size());
656 return static_cast<uint32_t>(L);
659 Error DumpOutputStyle::dumpUdtStats() {
660 printHeader(P, "S_UDT Record Stats");
662 StatCollection UdtStats;
663 StatCollection UdtTargetStats;
664 if (!File.hasPDBGlobalsStream()) {
665 P.printLine("- Error: globals stream not present");
666 return Error::success();
669 AutoIndent Indent(P, 4);
671 auto &SymbolRecords = cantFail(File.getPDBSymbolStream());
672 auto &Globals = cantFail(File.getPDBGlobalsStream());
673 auto &TpiTypes = cantFail(initializeTypes(StreamTPI));
675 StringMap<StatCollection::Stat> NamespacedStats;
679 size_t LongestNamespace = 0;
680 for (uint32_t PubSymOff : Globals.getGlobalsTable()) {
681 CVSymbol Sym = SymbolRecords.readRecord(PubSymOff);
682 if (Sym.kind() != SymbolKind::S_UDT)
684 UdtStats.update(SymbolKind::S_UDT, Sym.length());
686 UDTSym UDT = cantFail(SymbolDeserializer::deserializeAs<UDTSym>(Sym));
689 uint32_t RecordSize = 0;
690 if (UDT.Type.isSimple() ||
691 (UDT.Type.toArrayIndex() >= TpiTypes.capacity())) {
692 if (UDT.Type.isNoneType())
694 else if (UDT.Type.isSimple())
695 Kind = kSimpleUdtKind;
697 Kind = kUnknownUdtKind;
699 CVType T = TpiTypes.getType(UDT.Type);
701 RecordSize = T.length();
704 UdtTargetStats.update(Kind, RecordSize);
706 size_t Pos = UDT.Name.find("::");
707 if (Pos == StringRef::npos)
710 StringRef Scope = UDT.Name.take_front(Pos);
711 if (Scope.empty() || !isValidNamespaceIdentifier(Scope))
714 LongestNamespace = std::max(LongestNamespace, Scope.size());
715 NamespacedStats[Scope].update(RecordSize);
718 LongestNamespace += StringRef(" namespace ''").size();
719 uint32_t LongestTypeLeafKind = getLongestTypeLeafName(UdtTargetStats);
720 uint32_t FieldWidth = std::max(LongestNamespace, LongestTypeLeafKind);
722 // Compute the max number of digits for count and size fields, including comma
724 StringRef CountHeader("Count");
725 StringRef SizeHeader("Size");
726 uint32_t CD = NumDigits(UdtStats.Totals.Count);
728 CD = std::max(CD, CountHeader.size());
730 uint32_t SD = NumDigits(UdtStats.Totals.Size);
732 SD = std::max(SD, SizeHeader.size());
734 uint32_t TableWidth = FieldWidth + 3 + CD + 2 + SD + 1;
736 P.formatLine("{0} | {1} {2}",
737 fmt_align("Record Kind", AlignStyle::Right, FieldWidth),
738 fmt_align(CountHeader, AlignStyle::Right, CD),
739 fmt_align(SizeHeader, AlignStyle::Right, SD));
741 P.formatLine("{0}", fmt_repeat('-', TableWidth));
742 for (const auto &Stat : UdtTargetStats.Individual) {
743 StringRef Label = getUdtStatLabel(Stat.first);
744 P.formatLine("{0} | {1:N} {2:N}",
745 fmt_align(Label, AlignStyle::Right, FieldWidth),
746 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
747 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
749 P.formatLine("{0}", fmt_repeat('-', TableWidth));
750 P.formatLine("{0} | {1:N} {2:N}",
751 fmt_align("Total (S_UDT)", AlignStyle::Right, FieldWidth),
752 fmt_align(UdtStats.Totals.Count, AlignStyle::Right, CD),
753 fmt_align(UdtStats.Totals.Size, AlignStyle::Right, SD));
754 P.formatLine("{0}", fmt_repeat('-', TableWidth));
755 for (const auto &Stat : NamespacedStats) {
756 std::string Label = formatv("namespace '{0}'", Stat.getKey());
757 P.formatLine("{0} | {1:N} {2:N}",
758 fmt_align(Label, AlignStyle::Right, FieldWidth),
759 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
760 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
762 return Error::success();
765 static void typesetLinesAndColumns(PDBFile &File, LinePrinter &P,
766 uint32_t Start, const LineColumnEntry &E) {
767 const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
768 uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
770 // Let's try to keep it under 100 characters
771 constexpr uint32_t kMaxRowLength = 100;
772 // At least 3 spaces between columns.
773 uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
774 uint32_t ItemsLeft = E.LineNumbers.size();
775 auto LineIter = E.LineNumbers.begin();
776 while (ItemsLeft != 0) {
777 uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
778 for (uint32_t I = 0; I < RowColumns; ++I) {
779 LineInfo Line(LineIter->Flags);
781 if (Line.isAlwaysStepInto())
783 else if (Line.isNeverStepInto())
786 LineStr = utostr(Line.getStartLine());
787 char Statement = Line.isStatement() ? ' ' : '!';
788 P.format("{0} {1:X-} {2} ",
789 fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
790 fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
799 Error DumpOutputStyle::dumpLines() {
800 printHeader(P, "Lines");
802 uint32_t LastModi = UINT32_MAX;
803 uint32_t LastNameIndex = UINT32_MAX;
804 iterateModuleSubsections<DebugLinesSubsectionRef>(
806 [this, &LastModi, &LastNameIndex](uint32_t Modi,
807 StringsAndChecksumsPrinter &Strings,
808 DebugLinesSubsectionRef &Lines) {
809 uint16_t Segment = Lines.header()->RelocSegment;
810 uint32_t Begin = Lines.header()->RelocOffset;
811 uint32_t End = Begin + Lines.header()->CodeSize;
812 for (const auto &Block : Lines) {
813 if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
815 LastNameIndex = Block.NameIndex;
816 Strings.formatFromChecksumsOffset(P, Block.NameIndex);
819 AutoIndent Indent(P, 2);
820 P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
821 uint32_t Count = Block.LineNumbers.size();
822 if (Lines.hasColumnInfo())
823 P.format("line/column/addr entries = {0}", Count);
825 P.format("line/addr entries = {0}", Count);
828 typesetLinesAndColumns(File, P, Begin, Block);
832 return Error::success();
835 Error DumpOutputStyle::dumpInlineeLines() {
836 printHeader(P, "Inlinee Lines");
838 iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
840 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
841 DebugInlineeLinesSubsectionRef &Lines) {
842 P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
843 for (const auto &Entry : Lines) {
844 P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
845 fmtle(Entry.Header->SourceLineNum));
846 Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
851 return Error::success();
854 Error DumpOutputStyle::dumpXmi() {
855 printHeader(P, "Cross Module Imports");
856 iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
858 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
859 DebugCrossModuleImportsSubsectionRef &Imports) {
860 P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
862 for (const auto &Xmi : Imports) {
863 auto ExpectedModule =
864 Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
866 SmallString<32> ModuleStorage;
867 if (!ExpectedModule) {
868 Module = "(unknown module)";
869 consumeError(ExpectedModule.takeError());
871 Module = *ExpectedModule;
872 if (Module.size() > 32) {
873 ModuleStorage = "...";
874 ModuleStorage += Module.take_back(32 - 3);
875 Module = ModuleStorage;
877 std::vector<std::string> TIs;
878 for (const auto I : Xmi.Imports)
879 TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
881 typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
882 P.formatLine("{0,+32} | {1}", Module, Result);
886 return Error::success();
889 Error DumpOutputStyle::dumpXme() {
890 printHeader(P, "Cross Module Exports");
892 iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
894 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
895 DebugCrossModuleExportsSubsectionRef &Exports) {
896 P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
897 for (const auto &Export : Exports) {
898 P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
899 TypeIndex(Export.Global));
903 return Error::success();
906 Error DumpOutputStyle::dumpStringTable() {
907 printHeader(P, "String Table");
909 AutoIndent Indent(P);
910 auto IS = File.getStringTable();
912 P.formatLine("Not present in file");
913 consumeError(IS.takeError());
914 return Error::success();
917 if (IS->name_ids().empty()) {
918 P.formatLine("Empty");
919 return Error::success();
922 auto MaxID = std::max_element(IS->name_ids().begin(), IS->name_ids().end());
923 uint32_t Digits = NumDigits(*MaxID);
925 P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
928 std::vector<uint32_t> SortedIDs(IS->name_ids().begin(), IS->name_ids().end());
929 std::sort(SortedIDs.begin(), SortedIDs.end());
930 for (uint32_t I : SortedIDs) {
931 auto ES = IS->getStringForID(I);
932 llvm::SmallString<32> Str;
934 consumeError(ES.takeError());
935 Str = "Error reading string";
936 } else if (!ES->empty()) {
943 P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits), Str);
945 return Error::success();
948 static void buildDepSet(LazyRandomTypeCollection &Types,
949 ArrayRef<TypeIndex> Indices,
950 std::map<TypeIndex, CVType> &DepSet) {
951 SmallVector<TypeIndex, 4> DepList;
952 for (const auto &I : Indices) {
954 if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
957 CVType Type = Types.getType(TI);
959 codeview::discoverTypeIndices(Type, DepList);
960 buildDepSet(Types, DepList, DepSet);
964 static void dumpFullTypeStream(LinePrinter &Printer,
965 LazyRandomTypeCollection &Types,
966 TpiStream &Stream, bool Bytes, bool Extras) {
967 Printer.formatLine("Showing {0:N} records", Stream.getNumTypeRecords());
969 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
971 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
972 Stream.getNumHashBuckets(), Stream.getHashValues());
974 if (auto EC = codeview::visitTypeStream(Types, V)) {
975 Printer.formatLine("An error occurred dumping type records: {0}",
976 toString(std::move(EC)));
980 static void dumpPartialTypeStream(LinePrinter &Printer,
981 LazyRandomTypeCollection &Types,
982 TpiStream &Stream, ArrayRef<TypeIndex> TiList,
983 bool Bytes, bool Extras, bool Deps) {
985 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
987 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
988 Stream.getNumHashBuckets(), Stream.getHashValues());
990 if (opts::dump::DumpTypeDependents) {
991 // If we need to dump all dependents, then iterate each index and find
992 // all dependents, adding them to a map ordered by TypeIndex.
993 std::map<TypeIndex, CVType> DepSet;
994 buildDepSet(Types, TiList, DepSet);
997 "Showing {0:N} records and their dependents ({1:N} records total)",
998 TiList.size(), DepSet.size());
1000 for (auto &Dep : DepSet) {
1001 if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
1002 Printer.formatLine("An error occurred dumping type record {0}: {1}",
1003 Dep.first, toString(std::move(EC)));
1006 Printer.formatLine("Showing {0:N} records.", TiList.size());
1008 for (const auto &I : TiList) {
1010 CVType Type = Types.getType(TI);
1011 if (auto EC = codeview::visitTypeRecord(Type, TI, V))
1012 Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
1013 toString(std::move(EC)));
1018 Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
1019 assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
1021 bool Present = false;
1022 bool DumpTypes = false;
1023 bool DumpBytes = false;
1024 bool DumpExtras = false;
1025 std::vector<uint32_t> Indices;
1026 if (StreamIdx == StreamTPI) {
1027 printHeader(P, "Types (TPI Stream)");
1028 Present = File.hasPDBTpiStream();
1029 DumpTypes = opts::dump::DumpTypes;
1030 DumpBytes = opts::dump::DumpTypeData;
1031 DumpExtras = opts::dump::DumpTypeExtras;
1032 Indices.assign(opts::dump::DumpTypeIndex.begin(),
1033 opts::dump::DumpTypeIndex.end());
1034 } else if (StreamIdx == StreamIPI) {
1035 printHeader(P, "Types (IPI Stream)");
1036 Present = File.hasPDBIpiStream();
1037 DumpTypes = opts::dump::DumpIds;
1038 DumpBytes = opts::dump::DumpIdData;
1039 DumpExtras = opts::dump::DumpIdExtras;
1040 Indices.assign(opts::dump::DumpIdIndex.begin(),
1041 opts::dump::DumpIdIndex.end());
1044 AutoIndent Indent(P);
1046 P.formatLine("Stream not present");
1047 return Error::success();
1050 ExitOnError Err("Unexpected error processing types: ");
1052 auto &Stream = Err((StreamIdx == StreamTPI) ? File.getPDBTpiStream()
1053 : File.getPDBIpiStream());
1055 auto &Types = Err(initializeTypes(StreamIdx));
1057 if (DumpTypes || !Indices.empty()) {
1058 if (Indices.empty())
1059 dumpFullTypeStream(P, Types, Stream, DumpBytes, DumpExtras);
1061 std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
1062 dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
1063 opts::dump::DumpTypeDependents);
1069 auto IndexOffsets = Stream.getTypeIndexOffsets();
1070 P.formatLine("Type Index Offsets:");
1071 for (const auto &IO : IndexOffsets) {
1072 AutoIndent Indent2(P);
1073 P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
1077 P.formatLine("Hash Adjusters:");
1078 auto &Adjusters = Stream.getHashAdjusters();
1079 auto &Strings = Err(File.getStringTable());
1080 for (const auto &A : Adjusters) {
1081 AutoIndent Indent2(P);
1082 auto ExpectedStr = Strings.getStringForID(A.first);
1083 TypeIndex TI(A.second);
1085 P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
1087 P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
1088 consumeError(ExpectedStr.takeError());
1092 return Error::success();
1095 Expected<codeview::LazyRandomTypeCollection &>
1096 DumpOutputStyle::initializeTypes(uint32_t SN) {
1097 auto &TypeCollection = (SN == StreamTPI) ? TpiTypes : IpiTypes;
1099 (SN == StreamTPI) ? File.getPDBTpiStream() : File.getPDBIpiStream();
1101 return Tpi.takeError();
1103 if (!TypeCollection) {
1104 auto &Types = Tpi->typeArray();
1105 uint32_t Count = Tpi->getNumTypeRecords();
1106 auto Offsets = Tpi->getTypeIndexOffsets();
1108 llvm::make_unique<LazyRandomTypeCollection>(Types, Count, Offsets);
1111 return *TypeCollection;
1114 Error DumpOutputStyle::dumpModuleSyms() {
1115 printHeader(P, "Symbols");
1117 AutoIndent Indent(P);
1118 if (!File.hasPDBDbiStream()) {
1119 P.formatLine("DBI Stream not present");
1120 return Error::success();
1123 ExitOnError Err("Unexpected error processing symbols: ");
1125 auto &Ids = Err(initializeTypes(StreamIPI));
1126 auto &Types = Err(initializeTypes(StreamTPI));
1129 File, P, 2, [&](uint32_t I, StringsAndChecksumsPrinter &Strings) {
1130 auto ExpectedModS = getModuleDebugStream(File, I);
1131 if (!ExpectedModS) {
1132 P.formatLine("Error loading module stream {0}. {1}", I,
1133 toString(ExpectedModS.takeError()));
1137 ModuleDebugStreamRef &ModS = *ExpectedModS;
1139 SymbolVisitorCallbackPipeline Pipeline;
1140 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1141 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids,
1144 Pipeline.addCallbackToPipeline(Deserializer);
1145 Pipeline.addCallbackToPipeline(Dumper);
1146 CVSymbolVisitor Visitor(Pipeline);
1147 auto SS = ModS.getSymbolsSubstream();
1149 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
1150 P.formatLine("Error while processing symbol records. {0}",
1151 toString(std::move(EC)));
1155 return Error::success();
1158 Error DumpOutputStyle::dumpGlobals() {
1159 printHeader(P, "Global Symbols");
1160 AutoIndent Indent(P);
1161 if (!File.hasPDBGlobalsStream()) {
1162 P.formatLine("Globals stream not present");
1163 return Error::success();
1165 ExitOnError Err("Error dumping globals stream: ");
1166 auto &Globals = Err(File.getPDBGlobalsStream());
1168 const GSIHashTable &Table = Globals.getGlobalsTable();
1169 Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
1170 return Error::success();
1173 Error DumpOutputStyle::dumpPublics() {
1174 printHeader(P, "Public Symbols");
1175 AutoIndent Indent(P);
1176 if (!File.hasPDBPublicsStream()) {
1177 P.formatLine("Publics stream not present");
1178 return Error::success();
1180 ExitOnError Err("Error dumping publics stream: ");
1181 auto &Publics = Err(File.getPDBPublicsStream());
1183 const GSIHashTable &PublicsTable = Publics.getPublicsTable();
1184 if (opts::dump::DumpPublicExtras) {
1185 P.printLine("Publics Header");
1186 AutoIndent Indent(P);
1187 P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
1188 formatSegmentOffset(Publics.getThunkTableSection(),
1189 Publics.getThunkTableOffset()));
1191 Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
1193 // Skip the rest if we aren't dumping extras.
1194 if (!opts::dump::DumpPublicExtras)
1195 return Error::success();
1197 P.formatLine("Address Map");
1199 // These are offsets into the publics stream sorted by secidx:secrel.
1200 AutoIndent Indent2(P);
1201 for (uint32_t Addr : Publics.getAddressMap())
1202 P.formatLine("off = {0}", Addr);
1205 // The thunk map is optional debug info used for ILT thunks.
1206 if (!Publics.getThunkMap().empty()) {
1207 P.formatLine("Thunk Map");
1208 AutoIndent Indent2(P);
1209 for (uint32_t Addr : Publics.getThunkMap())
1210 P.formatLine("{0:x8}", Addr);
1213 // The section offsets table appears to be empty when incremental linking
1215 if (!Publics.getSectionOffsets().empty()) {
1216 P.formatLine("Section Offsets");
1217 AutoIndent Indent2(P);
1218 for (const SectionOffset &SO : Publics.getSectionOffsets())
1219 P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
1222 return Error::success();
1225 Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1227 auto ExpectedSyms = File.getPDBSymbolStream();
1229 return ExpectedSyms.takeError();
1230 auto ExpectedTypes = initializeTypes(StreamTPI);
1232 return ExpectedTypes.takeError();
1233 auto ExpectedIds = initializeTypes(StreamIPI);
1235 return ExpectedIds.takeError();
1238 P.printLine("GSI Header");
1239 AutoIndent Indent(P);
1240 P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1241 Table.getVerSignature(), Table.getVerHeader(),
1242 Table.getHashRecordSize(), Table.getNumBuckets());
1246 P.printLine("Records");
1247 SymbolVisitorCallbackPipeline Pipeline;
1248 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1249 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, *ExpectedIds,
1252 Pipeline.addCallbackToPipeline(Deserializer);
1253 Pipeline.addCallbackToPipeline(Dumper);
1254 CVSymbolVisitor Visitor(Pipeline);
1256 BinaryStreamRef SymStream =
1257 ExpectedSyms->getSymbolArray().getUnderlyingStream();
1258 for (uint32_t PubSymOff : Table) {
1259 Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
1261 return Sym.takeError();
1262 if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
1267 // Return early if we aren't dumping public hash table and address map info.
1269 return Error::success();
1271 P.formatLine("Hash Entries");
1273 AutoIndent Indent2(P);
1274 for (const PSHashRecord &HR : Table.HashRecords)
1275 P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
1279 // FIXME: Dump the bitmap.
1281 P.formatLine("Hash Buckets");
1283 AutoIndent Indent2(P);
1284 for (uint32_t Hash : Table.HashBuckets)
1285 P.formatLine("{0:x8}", Hash);
1288 return Error::success();
1291 static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1292 OMFSegDescFlags Flags) {
1293 std::vector<std::string> Opts;
1294 if (Flags == OMFSegDescFlags::None)
1297 PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1298 PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1299 PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1300 PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1301 PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1302 PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1303 PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
1304 return typesetItemList(Opts, IndentLevel, 4, " | ");
1307 Error DumpOutputStyle::dumpSectionHeaders() {
1308 dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1309 dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1310 return Error::success();
1313 static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1314 ArrayRef<llvm::object::coff_section>>>
1315 loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1316 if (!File.hasPDBDbiStream())
1317 return make_error<StringError>(
1318 "Section headers require a DBI Stream, which could not be loaded",
1319 inconvertibleErrorCode());
1321 auto &Dbi = cantFail(File.getPDBDbiStream());
1322 uint32_t SI = Dbi.getDebugStreamIndex(Type);
1324 if (SI == kInvalidStreamIndex)
1325 return make_error<StringError>(
1326 "PDB does not contain the requested image section header type",
1327 inconvertibleErrorCode());
1329 auto Stream = MappedBlockStream::createIndexedStream(
1330 File.getMsfLayout(), File.getMsfBuffer(), SI, File.getAllocator());
1332 return make_error<StringError>("Could not load the required stream data",
1333 inconvertibleErrorCode());
1335 ArrayRef<object::coff_section> Headers;
1336 if (Stream->getLength() % sizeof(object::coff_section) != 0)
1337 return make_error<StringError>(
1338 "Section header array size is not a multiple of section header size",
1339 inconvertibleErrorCode());
1341 uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1342 BinaryStreamReader Reader(*Stream);
1343 cantFail(Reader.readArray(Headers, NumHeaders));
1344 return std::make_pair(std::move(Stream), Headers);
1347 void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1348 printHeader(P, Label);
1349 ExitOnError Err("Error dumping publics stream: ");
1351 AutoIndent Indent(P);
1352 std::unique_ptr<MappedBlockStream> Stream;
1353 ArrayRef<object::coff_section> Headers;
1354 auto ExpectedHeaders = loadSectionHeaders(File, Type);
1355 if (!ExpectedHeaders) {
1356 P.printLine(toString(ExpectedHeaders.takeError()));
1359 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1362 for (const auto &Header : Headers) {
1364 P.formatLine("SECTION HEADER #{0}", I);
1365 P.formatLine("{0,8} name", Header.Name);
1366 P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1367 P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1368 P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1369 P.formatLine("{0,8:X-} file pointer to raw data",
1370 uint32_t(Header.PointerToRawData));
1371 P.formatLine("{0,8:X-} file pointer to relocation table",
1372 uint32_t(Header.PointerToRelocations));
1373 P.formatLine("{0,8:X-} file pointer to line numbers",
1374 uint32_t(Header.PointerToLinenumbers));
1375 P.formatLine("{0,8:X-} number of relocations",
1376 uint32_t(Header.NumberOfRelocations));
1377 P.formatLine("{0,8:X-} number of line numbers",
1378 uint32_t(Header.NumberOfLinenumbers));
1379 P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1380 AutoIndent IndentMore(P, 9);
1381 P.formatLine("{0}", formatSectionCharacteristics(
1382 P.getIndentLevel(), Header.Characteristics, 1, ""));
1388 std::vector<std::string> getSectionNames(PDBFile &File) {
1389 auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1390 if (!ExpectedHeaders)
1393 std::unique_ptr<MappedBlockStream> Stream;
1394 ArrayRef<object::coff_section> Headers;
1395 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1396 std::vector<std::string> Names;
1397 for (const auto &H : Headers)
1398 Names.push_back(H.Name);
1402 Error DumpOutputStyle::dumpSectionContribs() {
1403 printHeader(P, "Section Contributions");
1404 ExitOnError Err("Error dumping publics stream: ");
1406 AutoIndent Indent(P);
1407 if (!File.hasPDBDbiStream()) {
1409 "Section contribs require a DBI Stream, which could not be loaded");
1410 return Error::success();
1413 auto &Dbi = Err(File.getPDBDbiStream());
1415 class Visitor : public ISectionContribVisitor {
1417 Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1418 auto Max = std::max_element(
1419 Names.begin(), Names.end(),
1420 [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1421 MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1423 void visit(const SectionContrib &SC) override {
1424 assert(SC.ISect > 0);
1425 std::string NameInsert;
1426 if (SC.ISect < Names.size()) {
1427 StringRef SectionName = Names[SC.ISect - 1];
1428 NameInsert = formatv("[{0}]", SectionName).str();
1430 NameInsert = "[???]";
1431 P.formatLine("SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1433 formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1434 fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1435 fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1436 AutoIndent Indent(P, MaxNameLen + 2);
1437 P.formatLine(" {0}",
1438 formatSectionCharacteristics(P.getIndentLevel() + 6,
1439 SC.Characteristics, 3, " | "));
1441 void visit(const SectionContrib2 &SC) override {
1443 "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1444 "crc = {4}, coff section = {5}",
1445 formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1446 fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1447 fmtle(SC.ISectCoff));
1448 P.formatLine(" {0}", formatSectionCharacteristics(
1449 P.getIndentLevel() + 6,
1450 SC.Base.Characteristics, 3, " | "));
1455 uint32_t MaxNameLen;
1456 ArrayRef<std::string> Names;
1459 std::vector<std::string> Names = getSectionNames(File);
1460 Visitor V(P, makeArrayRef(Names));
1461 Dbi.visitSectionContributions(V);
1462 return Error::success();
1465 Error DumpOutputStyle::dumpSectionMap() {
1466 printHeader(P, "Section Map");
1467 ExitOnError Err("Error dumping section map: ");
1469 AutoIndent Indent(P);
1470 if (!File.hasPDBDbiStream()) {
1471 P.formatLine("Dumping the section map requires a DBI Stream, which could "
1473 return Error::success();
1476 auto &Dbi = Err(File.getPDBDbiStream());
1479 for (auto &M : Dbi.getSectionMap()) {
1481 "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
1482 fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1483 P.formatLine(" class = {0}, offset = {1}, size = {2}",
1484 fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1485 P.formatLine(" flags = {0}",
1486 formatSegMapDescriptorFlag(
1487 P.getIndentLevel() + 13,
1488 static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1491 return Error::success();