1//===- DumpOutputStyle.cpp ------------------------------------ *- C++ --*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DumpOutputStyle.h"
10
11#include "MinimalSymbolDumper.h"
12#include "MinimalTypeDumper.h"
13#include "StreamUtil.h"
14#include "TypeReferenceTracker.h"
15#include "llvm-pdbutil.h"
16
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringExtras.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/DebugSymbolsSubsection.h"
29#include "llvm/DebugInfo/CodeView/Formatters.h"
30#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
31#include "llvm/DebugInfo/CodeView/Line.h"
32#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
33#include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h"
34#include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
35#include "llvm/DebugInfo/CodeView/TypeHashing.h"
36#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
37#include "llvm/DebugInfo/MSF/MappedBlockStream.h"
38#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h"
39#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
40#include "llvm/DebugInfo/PDB/Native/FormatUtil.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/InputFile.h"
45#include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
46#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
47#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
48#include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
49#include "llvm/DebugInfo/PDB/Native/RawError.h"
50#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
51#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
52#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
53#include "llvm/Object/COFF.h"
54#include "llvm/Support/BinaryStreamReader.h"
55#include "llvm/Support/FormatAdapters.h"
56#include "llvm/Support/FormatVariadic.h"
57
58#include <cctype>
59
60using namespace llvm;
61using namespace llvm::codeview;
62using namespace llvm::msf;
63using namespace llvm::pdb;
64
65DumpOutputStyle::DumpOutputStyle(InputFile &File)
66 : File(File), P(2, false, outs(), opts::Filters) {
67 if (opts::dump::DumpTypeRefStats)
68 RefTracker.reset(p: new TypeReferenceTracker(File));
69}
70
71DumpOutputStyle::~DumpOutputStyle() = default;
72
73PDBFile &DumpOutputStyle::getPdb() { return File.pdb(); }
74object::COFFObjectFile &DumpOutputStyle::getObj() { return File.obj(); }
75
76void DumpOutputStyle::printStreamNotValidForObj() {
77 AutoIndent Indent(P, 4);
78 P.formatLine(Fmt: "Dumping this stream is not valid for object files");
79}
80
81void DumpOutputStyle::printStreamNotPresent(StringRef StreamName) {
82 AutoIndent Indent(P, 4);
83 P.formatLine(Fmt: "{0} stream not present", Items&: StreamName);
84}
85
86Error DumpOutputStyle::dump() {
87 // Walk symbols & globals if we are supposed to mark types referenced.
88 if (opts::dump::DumpTypeRefStats)
89 RefTracker->mark();
90
91 if (opts::dump::DumpSummary) {
92 if (auto EC = dumpFileSummary())
93 return EC;
94 P.NewLine();
95 }
96
97 if (opts::dump::DumpStreams) {
98 if (auto EC = dumpStreamSummary())
99 return EC;
100 P.NewLine();
101 }
102
103 if (opts::dump::DumpDXContainer) {
104 if (auto EC = dumpDXContainer())
105 return EC;
106 P.NewLine();
107 }
108
109 if (opts::dump::DumpSymbolStats) {
110 ExitOnError Err("Unexpected error processing module stats: ");
111 Err(dumpSymbolStats());
112 P.NewLine();
113 }
114
115 if (opts::dump::DumpUdtStats) {
116 if (auto EC = dumpUdtStats())
117 return EC;
118 P.NewLine();
119 }
120
121 if (opts::dump::DumpTypeStats || opts::dump::DumpIDStats) {
122 if (auto EC = dumpTypeStats())
123 return EC;
124 P.NewLine();
125 }
126
127 if (opts::dump::DumpNamedStreams) {
128 if (auto EC = dumpNamedStreams())
129 return EC;
130 P.NewLine();
131 }
132
133 if (opts::dump::DumpStringTable || opts::dump::DumpStringTableDetails) {
134 if (auto EC = dumpStringTable())
135 return EC;
136 P.NewLine();
137 }
138
139 if (opts::dump::DumpModules) {
140 ExitOnError Err("Unexpected error processing modules: ");
141 Err(dumpModules());
142 }
143
144 if (opts::dump::DumpModuleFiles) {
145 ExitOnError Err("Unexpected error processing files: ");
146 Err(dumpModuleFiles());
147 }
148
149 if (opts::dump::DumpLines) {
150 ExitOnError Err("Unexpected error processing lines: ");
151 Err(dumpLines());
152 }
153
154 if (opts::dump::DumpInlineeLines) {
155 ExitOnError Err("Unexpected error processing inlinee lines: ");
156 Err(dumpInlineeLines());
157 }
158
159 if (opts::dump::DumpXmi) {
160 ExitOnError Err("Unexpected error processing cross module imports: ");
161 Err(dumpXmi());
162 }
163
164 if (opts::dump::DumpXme) {
165 ExitOnError Err("Unexpected error processing cross module exports: ");
166 Err(dumpXme());
167 }
168
169 if (opts::dump::DumpFpo) {
170 if (auto EC = dumpFpo())
171 return EC;
172 }
173
174 if (File.isObj()) {
175 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
176 opts::dump::DumpTypeExtras)
177 if (auto EC = dumpTypesFromObjectFile())
178 return EC;
179 } else {
180 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
181 opts::dump::DumpTypeExtras) {
182 if (auto EC = dumpTpiStream(StreamIdx: StreamTPI))
183 return EC;
184 }
185
186 if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
187 opts::dump::DumpIdExtras) {
188 if (auto EC = dumpTpiStream(StreamIdx: StreamIPI))
189 return EC;
190 }
191 }
192
193 if (opts::dump::DumpGSIRecords) {
194 if (auto EC = dumpGSIRecords())
195 return EC;
196 }
197
198 if (opts::dump::DumpGlobals) {
199 if (auto EC = dumpGlobals())
200 return EC;
201 }
202
203 if (opts::dump::DumpPublics) {
204 if (auto EC = dumpPublics())
205 return EC;
206 }
207
208 if (opts::dump::DumpSymbols) {
209 ExitOnError Err("Unexpected error processing symbols: ");
210 Err(File.isPdb() ? dumpModuleSymsForPdb() : dumpModuleSymsForObj());
211 }
212
213 if (opts::dump::DumpTypeRefStats) {
214 if (auto EC = dumpTypeRefStats())
215 return EC;
216 }
217
218 if (opts::dump::DumpSectionHeaders) {
219 if (auto EC = dumpSectionHeaders())
220 return EC;
221 }
222
223 if (opts::dump::DumpSectionContribs) {
224 if (auto EC = dumpSectionContribs())
225 return EC;
226 }
227
228 if (opts::dump::DumpSectionMap) {
229 if (auto EC = dumpSectionMap())
230 return EC;
231 }
232
233 P.NewLine();
234
235 return Error::success();
236}
237
238static void printHeader(LinePrinter &P, const Twine &S) {
239 P.NewLine();
240 P.formatLine(Fmt: "{0,=60}", Items: S);
241 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '=', Count: 60));
242}
243
244Error DumpOutputStyle::dumpFileSummary() {
245 printHeader(P, S: "Summary");
246
247 if (File.isObj()) {
248 printStreamNotValidForObj();
249 return Error::success();
250 }
251
252 AutoIndent Indent(P);
253 ExitOnError Err("Invalid PDB Format: ");
254
255 P.formatLine(Fmt: "Block Size: {0}", Items: getPdb().getBlockSize());
256 P.formatLine(Fmt: "Number of blocks: {0}", Items: getPdb().getBlockCount());
257 P.formatLine(Fmt: "Number of streams: {0}", Items: getPdb().getNumStreams());
258
259 auto &PS = Err(getPdb().getPDBInfoStream());
260 P.formatLine(Fmt: "Signature: {0}", Items: PS.getSignature());
261 P.formatLine(Fmt: "Age: {0}", Items: PS.getAge());
262 P.formatLine(Fmt: "GUID: {0}", Items: fmt_guid(Item: PS.getGuid().Guid));
263 P.formatLine(Fmt: "Features: {0:x+}", Items: static_cast<uint32_t>(PS.getFeatures()));
264 P.formatLine(Fmt: "Has Debug Info: {0}", Items: getPdb().hasPDBDbiStream());
265 P.formatLine(Fmt: "Has Types: {0}", Items: getPdb().hasPDBTpiStream());
266 P.formatLine(Fmt: "Has IDs: {0}", Items: getPdb().hasPDBIpiStream());
267 P.formatLine(Fmt: "Has Globals: {0}", Items: getPdb().hasPDBGlobalsStream());
268 P.formatLine(Fmt: "Has Publics: {0}", Items: getPdb().hasPDBPublicsStream());
269 if (getPdb().hasPDBDbiStream()) {
270 DbiStream &DBI = Err(getPdb().getPDBDbiStream());
271 P.formatLine(Fmt: "Is incrementally linked: {0}", Items: DBI.isIncrementallyLinked());
272 P.formatLine(Fmt: "Has conflicting types: {0}", Items: DBI.hasCTypes());
273 P.formatLine(Fmt: "Is stripped: {0}", Items: DBI.isStripped());
274 }
275
276 return Error::success();
277}
278
279static StatCollection getSymbolStats(const SymbolGroup &SG,
280 StatCollection &CumulativeStats) {
281 StatCollection Stats;
282 if (SG.getFile().isPdb() && SG.hasDebugStream()) {
283 // For PDB files, all symbols are packed into one stream.
284 for (const auto &S : SG.getPdbModuleStream().symbols(HadError: nullptr)) {
285 Stats.update(Kind: S.kind(), RecordSize: S.length());
286 CumulativeStats.update(Kind: S.kind(), RecordSize: S.length());
287 }
288 return Stats;
289 }
290
291 for (const auto &SS : SG.getDebugSubsections()) {
292 // For object files, all symbols are spread across multiple Symbol
293 // subsections of a given .debug$S section.
294 if (SS.kind() != DebugSubsectionKind::Symbols)
295 continue;
296 DebugSymbolsSubsectionRef Symbols;
297 BinaryStreamReader Reader(SS.getRecordData());
298 cantFail(Err: Symbols.initialize(Reader));
299 for (const auto &S : Symbols) {
300 Stats.update(Kind: S.kind(), RecordSize: S.length());
301 CumulativeStats.update(Kind: S.kind(), RecordSize: S.length());
302 }
303 }
304 return Stats;
305}
306
307static StatCollection getChunkStats(const SymbolGroup &SG,
308 StatCollection &CumulativeStats) {
309 StatCollection Stats;
310 for (const auto &Chunk : SG.getDebugSubsections()) {
311 Stats.update(Kind: uint32_t(Chunk.kind()), RecordSize: Chunk.getRecordLength());
312 CumulativeStats.update(Kind: uint32_t(Chunk.kind()), RecordSize: Chunk.getRecordLength());
313 }
314 return Stats;
315}
316
317static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
318 return formatChunkKind(Kind: K, Friendly: false);
319}
320
321static inline std::string formatModuleDetailKind(SymbolKind K) {
322 return formatSymbolKind(K);
323}
324
325// Get the stats sorted by size, descending.
326std::vector<StatCollection::KindAndStat>
327StatCollection::getStatsSortedBySize() const {
328 std::vector<KindAndStat> SortedStats(Individual.begin(), Individual.end());
329 llvm::stable_sort(Range&: SortedStats,
330 C: [](const KindAndStat &LHS, const KindAndStat &RHS) {
331 return LHS.second.Size > RHS.second.Size;
332 });
333 return SortedStats;
334}
335
336template <typename Kind>
337static void printModuleDetailStats(LinePrinter &P, StringRef Label,
338 const StatCollection &Stats) {
339 P.NewLine();
340 P.formatLine(Fmt: " {0}", Items&: Label);
341 AutoIndent Indent(P);
342 P.formatLine(Fmt: "{0,40}: {1,7} entries ({2,12:N} bytes)", Items: "Total",
343 Items: Stats.Totals.Count, Items: Stats.Totals.Size);
344 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '-', Count: 74));
345
346 for (const auto &K : Stats.getStatsSortedBySize()) {
347 std::string KindName = formatModuleDetailKind(Kind(K.first));
348 P.formatLine(Fmt: "{0,40}: {1,7} entries ({2,12:N} bytes)", Items&: KindName,
349 Items: K.second.Count, Items: K.second.Size);
350 }
351}
352
353Error DumpOutputStyle::dumpStreamSummary() {
354 printHeader(P, S: "Streams");
355
356 if (File.isObj()) {
357 printStreamNotValidForObj();
358 return Error::success();
359 }
360
361 AutoIndent Indent(P);
362
363 if (StreamPurposes.empty())
364 discoverStreamPurposes(File&: getPdb(), Streams&: StreamPurposes);
365
366 uint32_t StreamCount = getPdb().getNumStreams();
367 uint32_t MaxStreamSize = getPdb().getMaxStreamSize();
368
369 for (uint32_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
370 P.formatLine(
371 Fmt: "Stream {0} ({1} bytes): [{2}]",
372 Items: fmt_align(Item&: StreamIdx, Where: AlignStyle::Right, Amount: NumDigitsBase10(X: StreamCount)),
373 Items: fmt_align(Item: getPdb().getStreamByteSize(StreamIndex: StreamIdx), Where: AlignStyle::Right,
374 Amount: NumDigitsBase10(X: MaxStreamSize)),
375 Items: StreamPurposes[StreamIdx].getLongName());
376
377 if (opts::dump::DumpStreamBlocks) {
378 auto Blocks = getPdb().getStreamBlockList(StreamIndex: StreamIdx);
379 std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
380 P.formatLine(Fmt: " {0} Blocks: [{1}]",
381 Items: fmt_repeat(Item: ' ', Count: NumDigitsBase10(X: StreamCount)),
382 Items: make_range(x: BV.begin(), y: BV.end()));
383 }
384 }
385
386 return Error::success();
387}
388
389static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
390 ArrayRef<llvm::object::coff_section>>>
391loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
392 if (!File.hasPDBDbiStream())
393 return make_error<StringError>(
394 Args: "Section headers require a DBI Stream, which could not be loaded",
395 Args: inconvertibleErrorCode());
396
397 DbiStream &Dbi = cantFail(ValOrErr: File.getPDBDbiStream());
398 uint32_t SI = Dbi.getDebugStreamIndex(Type);
399
400 if (SI == kInvalidStreamIndex)
401 return make_error<StringError>(
402 Args: "PDB does not contain the requested image section header type",
403 Args: inconvertibleErrorCode());
404
405 auto Stream = File.createIndexedStream(SN: SI);
406 if (!Stream)
407 return make_error<StringError>(Args: "Could not load the required stream data",
408 Args: inconvertibleErrorCode());
409
410 ArrayRef<object::coff_section> Headers;
411 if (Stream->getLength() % sizeof(object::coff_section) != 0)
412 return make_error<StringError>(
413 Args: "Section header array size is not a multiple of section header size",
414 Args: inconvertibleErrorCode());
415
416 uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
417 BinaryStreamReader Reader(*Stream);
418 cantFail(Err: Reader.readArray(Array&: Headers, NumElements: NumHeaders));
419 return std::make_pair(x: std::move(Stream), y&: Headers);
420}
421
422static Expected<std::vector<std::string>> getSectionNames(PDBFile &File) {
423 auto ExpectedHeaders = loadSectionHeaders(File, Type: DbgHeaderType::SectionHdr);
424 if (!ExpectedHeaders)
425 return ExpectedHeaders.takeError();
426
427 std::unique_ptr<MappedBlockStream> Stream;
428 ArrayRef<object::coff_section> Headers;
429 std::tie(args&: Stream, args&: Headers) = std::move(*ExpectedHeaders);
430 std::vector<std::string> Names;
431 for (const auto &H : Headers)
432 Names.push_back(x: H.Name);
433 return Names;
434}
435
436static void dumpSectionContrib(LinePrinter &P, const SectionContrib &SC,
437 ArrayRef<std::string> SectionNames,
438 uint32_t FieldWidth) {
439 std::string NameInsert;
440 if (SC.ISect > 0 && SC.ISect <= SectionNames.size()) {
441 StringRef SectionName = SectionNames[SC.ISect - 1];
442 NameInsert = formatv(Fmt: "[{0}]", Vals&: SectionName).str();
443 } else
444 NameInsert = "[???]";
445 P.formatLine(Fmt: "SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
446 "crc = {4}",
447 Items: formatSegmentOffset(Segment: SC.ISect, Offset: SC.Off), Items: fmtle(Value: SC.Size),
448 Items: fmtle(Value: SC.Imod), Items: fmtle(Value: SC.DataCrc), Items: fmtle(Value: SC.RelocCrc),
449 Items: fmt_align(Item&: NameInsert, Where: AlignStyle::Left, Amount: FieldWidth + 2));
450 AutoIndent Indent(P, FieldWidth + 2);
451 P.formatLine(Fmt: " {0}",
452 Items: formatSectionCharacteristics(IndentLevel: P.getIndentLevel() + 6,
453 C: SC.Characteristics, FlagsPerLine: 3, Separator: " | "));
454}
455
456static void dumpSectionContrib(LinePrinter &P, const SectionContrib2 &SC,
457 ArrayRef<std::string> SectionNames,
458 uint32_t FieldWidth) {
459 P.formatLine(Fmt: "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
460 "crc = {4}, coff section = {5}",
461 Items: formatSegmentOffset(Segment: SC.Base.ISect, Offset: SC.Base.Off),
462 Items: fmtle(Value: SC.Base.Size), Items: fmtle(Value: SC.Base.Imod), Items: fmtle(Value: SC.Base.DataCrc),
463 Items: fmtle(Value: SC.Base.RelocCrc), Items: fmtle(Value: SC.ISectCoff));
464 P.formatLine(Fmt: " {0}",
465 Items: formatSectionCharacteristics(IndentLevel: P.getIndentLevel() + 6,
466 C: SC.Base.Characteristics, FlagsPerLine: 3, Separator: " | "));
467}
468
469Error DumpOutputStyle::dumpModules() {
470 printHeader(P, S: "Modules");
471
472 if (File.isObj()) {
473 printStreamNotValidForObj();
474 return Error::success();
475 }
476
477 if (!getPdb().hasPDBDbiStream()) {
478 printStreamNotPresent(StreamName: "DBI");
479 return Error::success();
480 }
481
482 AutoIndent Indent(P);
483
484 Expected<DbiStream &> StreamOrErr = getPdb().getPDBDbiStream();
485 if (!StreamOrErr)
486 return StreamOrErr.takeError();
487 DbiStream &Stream = *StreamOrErr;
488
489 const DbiModuleList &Modules = Stream.modules();
490 return iterateSymbolGroups(
491 Input&: File, HeaderScope: PrintScope{P, 11},
492 Callback: [&](uint32_t Modi, const SymbolGroup &Strings) -> Error {
493 auto Desc = Modules.getModuleDescriptor(Modi);
494 if (opts::dump::DumpSectionContribs) {
495 auto SectionsOrErr = getSectionNames(File&: getPdb());
496 if (!SectionsOrErr)
497 return SectionsOrErr.takeError();
498 ArrayRef<std::string> Sections = *SectionsOrErr;
499 dumpSectionContrib(P, SC: Desc.getSectionContrib(), SectionNames: Sections, FieldWidth: 0);
500 }
501 P.formatLine(Fmt: "Obj: `{0}`: ", Items: Desc.getObjFileName());
502 P.formatLine(Fmt: "debug stream: {0}, # files: {1}, has ec info: {2}",
503 Items: Desc.getModuleStreamIndex(), Items: Desc.getNumberOfFiles(),
504 Items: Desc.hasECInfo());
505
506 auto PdbPathOrErr = Stream.getECName(NI: Desc.getPdbFilePathNameIndex());
507 if (!PdbPathOrErr)
508 return PdbPathOrErr.takeError();
509 StringRef PdbFilePath = *PdbPathOrErr;
510
511 auto SrcPathOrErr = Stream.getECName(NI: Desc.getSourceFileNameIndex());
512 if (!SrcPathOrErr)
513 return SrcPathOrErr.takeError();
514 StringRef SrcFilePath = *SrcPathOrErr;
515
516 P.formatLine(Fmt: "pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
517 Items: Desc.getPdbFilePathNameIndex(), Items&: PdbFilePath,
518 Items: Desc.getSourceFileNameIndex(), Items&: SrcFilePath);
519 return Error::success();
520 });
521}
522
523Error DumpOutputStyle::dumpModuleFiles() {
524 printHeader(P, S: "Files");
525
526 if (File.isObj()) {
527 printStreamNotValidForObj();
528 return Error::success();
529 }
530
531 if (!getPdb().hasPDBDbiStream()) {
532 printStreamNotPresent(StreamName: "DBI");
533 return Error::success();
534 }
535
536 return iterateSymbolGroups(
537 Input&: File, HeaderScope: PrintScope{P, 11},
538 Callback: [this](uint32_t Modi, const SymbolGroup &Strings) -> Error {
539 Expected<DbiStream &> StreamOrErr = getPdb().getPDBDbiStream();
540 if (!StreamOrErr)
541 return StreamOrErr.takeError();
542 DbiStream &Stream = *StreamOrErr;
543
544 const DbiModuleList &Modules = Stream.modules();
545 for (const auto &F : Modules.source_files(Modi)) {
546 Strings.formatFromFileName(Printer&: P, File: F);
547 }
548 return Error::success();
549 });
550}
551
552Error DumpOutputStyle::dumpSymbolStats() {
553 printHeader(P, S: "Module Stats");
554
555 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
556 printStreamNotPresent(StreamName: "DBI");
557 return Error::success();
558 }
559
560 StatCollection SymStats;
561 StatCollection ChunkStats;
562 PrintScope Scope(P, 2);
563
564 if (Error Err = iterateSymbolGroups(
565 Input&: File, HeaderScope: Scope, Callback: [&](uint32_t Modi, const SymbolGroup &SG) -> Error {
566 StatCollection SS = getSymbolStats(SG, CumulativeStats&: SymStats);
567 StatCollection CS = getChunkStats(SG, CumulativeStats&: ChunkStats);
568
569 if (!SG.getFile().isPdb())
570 return Error::success();
571
572 AutoIndent Indent(P);
573 auto Modules = cantFail(ValOrErr: File.pdb().getPDBDbiStream()).modules();
574 uint32_t ModCount = Modules.getModuleCount();
575 DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
576 uint32_t StreamIdx = Desc.getModuleStreamIndex();
577
578 if (StreamIdx == kInvalidStreamIndex) {
579 P.formatLine(
580 Fmt: "Mod {0} (debug info not present): [{1}]",
581 Items: fmt_align(Item&: Modi, Where: AlignStyle::Right, Amount: NumDigitsBase10(X: ModCount)),
582 Items: Desc.getModuleName());
583 return Error::success();
584 }
585 P.formatLine(Fmt: "Stream {0}, {1} bytes", Items&: StreamIdx,
586 Items: getPdb().getStreamByteSize(StreamIndex: StreamIdx));
587
588 printModuleDetailStats<SymbolKind>(P, Label: "Symbols", Stats: SS);
589 printModuleDetailStats<DebugSubsectionKind>(P, Label: "Chunks", Stats: CS);
590
591 return Error::success();
592 }))
593 return Err;
594
595 if (SymStats.Totals.Count > 0) {
596 P.printLine(T: " Summary |");
597 AutoIndent Indent(P, 4);
598 printModuleDetailStats<SymbolKind>(P, Label: "Symbols", Stats: SymStats);
599 printModuleDetailStats<DebugSubsectionKind>(P, Label: "Chunks", Stats: ChunkStats);
600 }
601
602 return Error::success();
603}
604
605Error DumpOutputStyle::dumpTypeStats() {
606 printHeader(P, S: "Type Record Stats");
607
608 // Iterate the types, categorize by kind, accumulate size stats.
609 StatCollection TypeStats;
610 LazyRandomTypeCollection &Types =
611 opts::dump::DumpTypeStats ? File.types() : File.ids();
612 for (std::optional<TypeIndex> TI = Types.getFirst(); TI;
613 TI = Types.getNext(Prev: *TI)) {
614 CVType Type = Types.getType(Index: *TI);
615 TypeStats.update(Kind: uint32_t(Type.kind()), RecordSize: Type.length());
616 }
617
618 P.NewLine();
619 P.formatLine(Fmt: " Types");
620 AutoIndent Indent(P);
621 P.formatLine(Fmt: "{0,16}: {1,7} entries ({2,12:N} bytes, {3,7} avg)", Items: "Total",
622 Items&: TypeStats.Totals.Count, Items&: TypeStats.Totals.Size,
623 Items: (double)TypeStats.Totals.Size / TypeStats.Totals.Count);
624 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '-', Count: 74));
625
626 for (const auto &K : TypeStats.getStatsSortedBySize()) {
627 P.formatLine(Fmt: "{0,16}: {1,7} entries ({2,12:N} bytes, {3,7} avg)",
628 Items: formatTypeLeafKind(K: TypeLeafKind(K.first)), Items: K.second.Count,
629 Items: K.second.Size, Items: (double)K.second.Size / K.second.Count);
630 }
631 return Error::success();
632}
633
634static bool isValidNamespaceIdentifier(StringRef S) {
635 if (S.empty())
636 return false;
637
638 if (std::isdigit(S[0]))
639 return false;
640
641 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C); });
642}
643
644namespace {
645constexpr uint32_t kNoneUdtKind = 0;
646constexpr uint32_t kSimpleUdtKind = 1;
647constexpr uint32_t kUnknownUdtKind = 2;
648} // namespace
649
650static std::string getUdtStatLabel(uint32_t Kind) {
651 if (Kind == kNoneUdtKind)
652 return "<none type>";
653
654 if (Kind == kSimpleUdtKind)
655 return "<simple type>";
656
657 if (Kind == kUnknownUdtKind)
658 return "<unknown type>";
659
660 return formatTypeLeafKind(K: static_cast<TypeLeafKind>(Kind));
661}
662
663static uint32_t getLongestTypeLeafName(const StatCollection &Stats) {
664 size_t L = 0;
665 for (const auto &Stat : Stats.Individual) {
666 std::string Label = getUdtStatLabel(Kind: Stat.first);
667 L = std::max(a: L, b: Label.size());
668 }
669 return static_cast<uint32_t>(L);
670}
671
672Error DumpOutputStyle::dumpUdtStats() {
673 printHeader(P, S: "S_UDT Record Stats");
674
675 if (File.isPdb() && !getPdb().hasPDBGlobalsStream()) {
676 printStreamNotPresent(StreamName: "Globals");
677 return Error::success();
678 }
679
680 StatCollection UdtStats;
681 StatCollection UdtTargetStats;
682 AutoIndent Indent(P, 4);
683
684 auto &TpiTypes = File.types();
685
686 StringMap<StatCollection::Stat> NamespacedStats;
687
688 size_t LongestNamespace = 0;
689 auto HandleOneSymbol = [&](const CVSymbol &Sym) {
690 if (Sym.kind() != SymbolKind::S_UDT)
691 return;
692 UdtStats.update(Kind: SymbolKind::S_UDT, RecordSize: Sym.length());
693
694 UDTSym UDT = cantFail(ValOrErr: SymbolDeserializer::deserializeAs<UDTSym>(Symbol: Sym));
695
696 uint32_t Kind = 0;
697 uint32_t RecordSize = 0;
698
699 if (UDT.Type.isNoneType())
700 Kind = kNoneUdtKind;
701 else if (UDT.Type.isSimple())
702 Kind = kSimpleUdtKind;
703 else if (std::optional<CVType> T = TpiTypes.tryGetType(Index: UDT.Type)) {
704 Kind = T->kind();
705 RecordSize = T->length();
706 } else
707 Kind = kUnknownUdtKind;
708
709 UdtTargetStats.update(Kind, RecordSize);
710
711 size_t Pos = UDT.Name.find(Str: "::");
712 if (Pos == StringRef::npos)
713 return;
714
715 StringRef Scope = UDT.Name.take_front(N: Pos);
716 if (Scope.empty() || !isValidNamespaceIdentifier(S: Scope))
717 return;
718
719 LongestNamespace = std::max(a: LongestNamespace, b: Scope.size());
720 NamespacedStats[Scope].update(RecordSize);
721 };
722
723 P.NewLine();
724
725 if (File.isPdb()) {
726 auto &SymbolRecords = cantFail(ValOrErr: getPdb().getPDBSymbolStream());
727 auto ExpGlobals = getPdb().getPDBGlobalsStream();
728 if (!ExpGlobals)
729 return ExpGlobals.takeError();
730
731 for (uint32_t PubSymOff : ExpGlobals->getGlobalsTable()) {
732 CVSymbol Sym = SymbolRecords.readRecord(Offset: PubSymOff);
733 HandleOneSymbol(Sym);
734 }
735 } else {
736 for (const auto &Sec : File.symbol_groups()) {
737 for (const auto &SS : Sec.getDebugSubsections()) {
738 if (SS.kind() != DebugSubsectionKind::Symbols)
739 continue;
740
741 DebugSymbolsSubsectionRef Symbols;
742 BinaryStreamReader Reader(SS.getRecordData());
743 cantFail(Err: Symbols.initialize(Reader));
744 for (const auto &S : Symbols)
745 HandleOneSymbol(S);
746 }
747 }
748 }
749
750 LongestNamespace += StringRef(" namespace ''").size();
751 size_t LongestTypeLeafKind = getLongestTypeLeafName(Stats: UdtTargetStats);
752 size_t FieldWidth = std::max(a: LongestNamespace, b: LongestTypeLeafKind);
753
754 // Compute the max number of digits for count and size fields, including comma
755 // separators.
756 StringRef CountHeader("Count");
757 StringRef SizeHeader("Size");
758 size_t CD = NumDigitsBase10(X: UdtStats.Totals.Count);
759 CD += (CD - 1) / 3;
760 CD = std::max(a: CD, b: CountHeader.size());
761
762 size_t SD = NumDigitsBase10(X: UdtStats.Totals.Size);
763 SD += (SD - 1) / 3;
764 SD = std::max(a: SD, b: SizeHeader.size());
765
766 uint32_t TableWidth = FieldWidth + 3 + CD + 2 + SD + 1;
767
768 P.formatLine(Fmt: "{0} | {1} {2}",
769 Items: fmt_align(Item: "Record Kind", Where: AlignStyle::Right, Amount: FieldWidth),
770 Items: fmt_align(Item&: CountHeader, Where: AlignStyle::Right, Amount: CD),
771 Items: fmt_align(Item&: SizeHeader, Where: AlignStyle::Right, Amount: SD));
772
773 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '-', Count: TableWidth));
774 for (const auto &Stat : UdtTargetStats.getStatsSortedBySize()) {
775 std::string Label = getUdtStatLabel(Kind: Stat.first);
776 P.formatLine(Fmt: "{0} | {1:N} {2:N}",
777 Items: fmt_align(Item&: Label, Where: AlignStyle::Right, Amount: FieldWidth),
778 Items: fmt_align(Item: Stat.second.Count, Where: AlignStyle::Right, Amount: CD),
779 Items: fmt_align(Item: Stat.second.Size, Where: AlignStyle::Right, Amount: SD));
780 }
781 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '-', Count: TableWidth));
782 P.formatLine(Fmt: "{0} | {1:N} {2:N}",
783 Items: fmt_align(Item: "Total (S_UDT)", Where: AlignStyle::Right, Amount: FieldWidth),
784 Items: fmt_align(Item&: UdtStats.Totals.Count, Where: AlignStyle::Right, Amount: CD),
785 Items: fmt_align(Item&: UdtStats.Totals.Size, Where: AlignStyle::Right, Amount: SD));
786 P.formatLine(Fmt: "{0}", Items: fmt_repeat(Item: '-', Count: TableWidth));
787 struct StrAndStat {
788 StringRef Key;
789 StatCollection::Stat Stat;
790 };
791
792 // Print namespace stats in descending order of size.
793 std::vector<StrAndStat> NamespacedStatsSorted;
794 for (const auto &Stat : NamespacedStats)
795 NamespacedStatsSorted.push_back(x: {.Key: Stat.getKey(), .Stat: Stat.second});
796 llvm::stable_sort(Range&: NamespacedStatsSorted,
797 C: [](const StrAndStat &L, const StrAndStat &R) {
798 return L.Stat.Size > R.Stat.Size;
799 });
800 for (const auto &Stat : NamespacedStatsSorted) {
801 std::string Label = std::string(formatv(Fmt: "namespace '{0}'", Vals: Stat.Key));
802 P.formatLine(Fmt: "{0} | {1:N} {2:N}",
803 Items: fmt_align(Item&: Label, Where: AlignStyle::Right, Amount: FieldWidth),
804 Items: fmt_align(Item: Stat.Stat.Count, Where: AlignStyle::Right, Amount: CD),
805 Items: fmt_align(Item: Stat.Stat.Size, Where: AlignStyle::Right, Amount: SD));
806 }
807 return Error::success();
808}
809
810static void typesetLinesAndColumns(LinePrinter &P, uint32_t Start,
811 const LineColumnEntry &E) {
812 const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
813 uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
814
815 // Let's try to keep it under 100 characters
816 constexpr uint32_t kMaxRowLength = 100;
817 // At least 3 spaces between columns.
818 uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
819 uint32_t ItemsLeft = E.LineNumbers.size();
820 auto LineIter = E.LineNumbers.begin();
821 while (ItemsLeft != 0) {
822 uint32_t RowColumns = std::min(a: ItemsLeft, b: ColumnsPerRow);
823 for (uint32_t I = 0; I < RowColumns; ++I) {
824 LineInfo Line(LineIter->Flags);
825 std::string LineStr;
826 if (Line.isAlwaysStepInto())
827 LineStr = "ASI";
828 else if (Line.isNeverStepInto())
829 LineStr = "NSI";
830 else
831 LineStr = utostr(X: Line.getStartLine());
832 char Statement = Line.isStatement() ? ' ' : '!';
833 P.format(Fmt: "{0} {1:X-} {2} ",
834 Items: fmt_align(Item&: LineStr, Where: AlignStyle::Right, Amount: kMaxCharsPerLineNumber),
835 Items: fmt_align(Item: Start + LineIter->Offset, Where: AlignStyle::Right, Amount: 8, Fill: '0'),
836 Items&: Statement);
837 ++LineIter;
838 --ItemsLeft;
839 }
840 P.NewLine();
841 }
842}
843
844Error DumpOutputStyle::dumpLines() {
845 printHeader(P, S: "Lines");
846
847 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
848 printStreamNotPresent(StreamName: "DBI");
849 return Error::success();
850 }
851
852 uint32_t LastModi = UINT32_MAX;
853 uint32_t LastNameIndex = UINT32_MAX;
854 return iterateModuleSubsections<DebugLinesSubsectionRef>(
855 File, HeaderScope: PrintScope{P, 4},
856 Callback: [this, &LastModi,
857 &LastNameIndex](uint32_t Modi, const SymbolGroup &Strings,
858 DebugLinesSubsectionRef &Lines) -> Error {
859 uint16_t Segment = Lines.header()->RelocSegment;
860 uint32_t Begin = Lines.header()->RelocOffset;
861 uint32_t End = Begin + Lines.header()->CodeSize;
862 for (const auto &Block : Lines) {
863 if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
864 LastModi = Modi;
865 LastNameIndex = Block.NameIndex;
866 Strings.formatFromChecksumsOffset(Printer&: P, Offset: Block.NameIndex);
867 }
868
869 AutoIndent Indent(P, 2);
870 P.formatLine(Fmt: "{0:X-4}:{1:X-8}-{2:X-8}, ", Items&: Segment, Items&: Begin, Items&: End);
871 uint32_t Count = Block.LineNumbers.size();
872 if (Lines.hasColumnInfo())
873 P.format(Fmt: "line/column/addr entries = {0}", Items&: Count);
874 else
875 P.format(Fmt: "line/addr entries = {0}", Items&: Count);
876
877 P.NewLine();
878 typesetLinesAndColumns(P, Start: Begin, E: Block);
879 }
880 return Error::success();
881 });
882}
883
884Error DumpOutputStyle::dumpInlineeLines() {
885 printHeader(P, S: "Inlinee Lines");
886
887 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
888 printStreamNotPresent(StreamName: "DBI");
889 return Error::success();
890 }
891
892 return iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
893 File, HeaderScope: PrintScope{P, 2},
894 Callback: [this](uint32_t Modi, const SymbolGroup &Strings,
895 DebugInlineeLinesSubsectionRef &Lines) -> Error {
896 P.formatLine(Fmt: "{0,+8} | {1,+5} | {2}", Items: "Inlinee", Items: "Line", Items: "Source File");
897 for (const auto &Entry : Lines) {
898 P.formatLine(Fmt: "{0,+8} | {1,+5} | ", Items: Entry.Header->Inlinee,
899 Items: fmtle(Value: Entry.Header->SourceLineNum));
900 Strings.formatFromChecksumsOffset(Printer&: P, Offset: Entry.Header->FileID, Append: true);
901 for (const auto &ExtraFileID : Entry.ExtraFiles) {
902 P.formatLine(Fmt: " ");
903 Strings.formatFromChecksumsOffset(Printer&: P, Offset: ExtraFileID, Append: true);
904 }
905 }
906 P.NewLine();
907 return Error::success();
908 });
909}
910
911Error DumpOutputStyle::dumpXmi() {
912 printHeader(P, S: "Cross Module Imports");
913
914 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
915 printStreamNotPresent(StreamName: "DBI");
916 return Error::success();
917 }
918
919 return iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
920 File, HeaderScope: PrintScope{P, 2},
921 Callback: [this](uint32_t Modi, const SymbolGroup &Strings,
922 DebugCrossModuleImportsSubsectionRef &Imports) -> Error {
923 P.formatLine(Fmt: "{0,=32} | {1}", Items: "Imported Module", Items: "Type IDs");
924
925 for (const auto &Xmi : Imports) {
926 auto ExpectedModule =
927 Strings.getNameFromStringTable(Offset: Xmi.Header->ModuleNameOffset);
928 StringRef Module;
929 SmallString<32> ModuleStorage;
930 if (!ExpectedModule) {
931 Module = "(unknown module)";
932 consumeError(Err: ExpectedModule.takeError());
933 } else
934 Module = *ExpectedModule;
935 if (Module.size() > 32) {
936 ModuleStorage = "...";
937 ModuleStorage += Module.take_back(N: 32 - 3);
938 Module = ModuleStorage;
939 }
940 std::vector<std::string> TIs;
941 for (const auto I : Xmi.Imports)
942 TIs.push_back(x: std::string(formatv(Fmt: "{0,+10:X+}", Vals: fmtle(Value: I))));
943 std::string Result =
944 typesetItemList(Opts: TIs, IndentLevel: P.getIndentLevel() + 35, GroupSize: 12, Sep: " ");
945 P.formatLine(Fmt: "{0,+32} | {1}", Items&: Module, Items&: Result);
946 }
947 return Error::success();
948 });
949}
950
951Error DumpOutputStyle::dumpXme() {
952 printHeader(P, S: "Cross Module Exports");
953
954 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
955 printStreamNotPresent(StreamName: "DBI");
956 return Error::success();
957 }
958
959 return iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
960 File, HeaderScope: PrintScope{P, 2},
961 Callback: [this](uint32_t Modi, const SymbolGroup &Strings,
962 DebugCrossModuleExportsSubsectionRef &Exports) -> Error {
963 P.formatLine(Fmt: "{0,-10} | {1}", Items: "Local ID", Items: "Global ID");
964 for (const auto &Export : Exports) {
965 P.formatLine(Fmt: "{0,+10:X+} | {1}", Items: TypeIndex(Export.Local),
966 Items: TypeIndex(Export.Global));
967 }
968 return Error::success();
969 });
970}
971
972std::string formatFrameType(object::frame_type FT) {
973 switch (FT) {
974 case object::frame_type::Fpo:
975 return "FPO";
976 case object::frame_type::NonFpo:
977 return "Non-FPO";
978 case object::frame_type::Trap:
979 return "Trap";
980 case object::frame_type::Tss:
981 return "TSS";
982 }
983 return "<unknown>";
984}
985
986Error DumpOutputStyle::dumpOldFpo(PDBFile &File) {
987 printHeader(P, S: "Old FPO Data");
988
989 ExitOnError Err("Error dumping old fpo data:");
990 DbiStream &Dbi = Err(File.getPDBDbiStream());
991
992 if (!Dbi.hasOldFpoRecords()) {
993 printStreamNotPresent(StreamName: "FPO");
994 return Error::success();
995 }
996
997 const FixedStreamArray<object::FpoData>& Records = Dbi.getOldFpoRecords();
998
999 P.printLine(T: " RVA | Code | Locals | Params | Prolog | Saved Regs | Use "
1000 "BP | Has SEH | Frame Type");
1001
1002 for (const object::FpoData &FD : Records) {
1003 P.formatLine(Fmt: "{0:X-8} | {1,4} | {2,6} | {3,6} | {4,6} | {5,10} | {6,6} | "
1004 "{7,7} | {8,9}",
1005 Items: uint32_t(FD.Offset), Items: uint32_t(FD.Size), Items: uint32_t(FD.NumLocals),
1006 Items: uint32_t(FD.NumParams), Items: FD.getPrologSize(),
1007 Items: FD.getNumSavedRegs(), Items: FD.useBP(), Items: FD.hasSEH(),
1008 Items: formatFrameType(FT: FD.getFP()));
1009 }
1010 return Error::success();
1011}
1012
1013Error DumpOutputStyle::dumpNewFpo(PDBFile &File) {
1014 printHeader(P, S: "New FPO Data");
1015
1016 ExitOnError Err("Error dumping new fpo data:");
1017 DbiStream &Dbi = Err(File.getPDBDbiStream());
1018
1019 if (!Dbi.hasNewFpoRecords()) {
1020 printStreamNotPresent(StreamName: "New FPO");
1021 return Error::success();
1022 }
1023
1024 const DebugFrameDataSubsectionRef& FDS = Dbi.getNewFpoRecords();
1025
1026 P.printLine(T: " RVA | Code | Locals | Params | Stack | Prolog | Saved Regs "
1027 "| Has SEH | Has C++EH | Start | Program");
1028 for (const FrameData &FD : FDS) {
1029 bool IsFuncStart = FD.Flags & FrameData::IsFunctionStart;
1030 bool HasEH = FD.Flags & FrameData::HasEH;
1031 bool HasSEH = FD.Flags & FrameData::HasSEH;
1032
1033 auto &StringTable = Err(File.getStringTable());
1034
1035 auto Program = Err(StringTable.getStringForID(ID: FD.FrameFunc));
1036 P.formatLine(Fmt: "{0:X-8} | {1,4} | {2,6} | {3,6} | {4,5} | {5,6} | {6,10} | "
1037 "{7,7} | {8,9} | {9,5} | {10}",
1038 Items: uint32_t(FD.RvaStart), Items: uint32_t(FD.CodeSize),
1039 Items: uint32_t(FD.LocalSize), Items: uint32_t(FD.ParamsSize),
1040 Items: uint32_t(FD.MaxStackSize), Items: uint16_t(FD.PrologSize),
1041 Items: uint16_t(FD.SavedRegsSize), Items&: HasSEH, Items&: HasEH, Items&: IsFuncStart,
1042 Items&: Program);
1043 }
1044 return Error::success();
1045}
1046
1047Error DumpOutputStyle::dumpFpo() {
1048 if (!File.isPdb()) {
1049 printStreamNotValidForObj();
1050 return Error::success();
1051 }
1052
1053 PDBFile &File = getPdb();
1054 if (!File.hasPDBDbiStream()) {
1055 printStreamNotPresent(StreamName: "DBI");
1056 return Error::success();
1057 }
1058
1059 if (auto EC = dumpOldFpo(File))
1060 return EC;
1061 if (auto EC = dumpNewFpo(File))
1062 return EC;
1063 return Error::success();
1064}
1065
1066Error DumpOutputStyle::dumpStringTableFromPdb() {
1067 AutoIndent Indent(P);
1068 auto IS = getPdb().getStringTable();
1069 if (!IS) {
1070 P.formatLine(Fmt: "Not present in file");
1071 consumeError(Err: IS.takeError());
1072 return Error::success();
1073 }
1074
1075 if (opts::dump::DumpStringTable) {
1076 if (IS->name_ids().empty())
1077 P.formatLine(Fmt: "Empty");
1078 else {
1079 auto MaxID = llvm::max_element(Range: IS->name_ids());
1080 uint32_t Digits = NumDigitsBase10(X: *MaxID);
1081
1082 P.formatLine(Fmt: "{0} | {1}", Items: fmt_align(Item: "ID", Where: AlignStyle::Right, Amount: Digits),
1083 Items: "String");
1084
1085 std::vector<uint32_t> SortedIDs(IS->name_ids().begin(),
1086 IS->name_ids().end());
1087 llvm::sort(C&: SortedIDs);
1088 for (uint32_t I : SortedIDs) {
1089 auto ES = IS->getStringForID(ID: I);
1090 llvm::SmallString<32> Str;
1091 if (!ES) {
1092 consumeError(Err: ES.takeError());
1093 Str = "Error reading string";
1094 } else if (!ES->empty()) {
1095 Str.append(RHS: "'");
1096 Str.append(RHS: *ES);
1097 Str.append(RHS: "'");
1098 }
1099
1100 if (!Str.empty())
1101 P.formatLine(Fmt: "{0} | {1}", Items: fmt_align(Item&: I, Where: AlignStyle::Right, Amount: Digits),
1102 Items&: Str);
1103 }
1104 }
1105 }
1106
1107 if (opts::dump::DumpStringTableDetails) {
1108 P.NewLine();
1109 {
1110 P.printLine(T: "String Table Header:");
1111 AutoIndent Indent(P);
1112 P.formatLine(Fmt: "Signature: {0}", Items: IS->getSignature());
1113 P.formatLine(Fmt: "Hash Version: {0}", Items: IS->getHashVersion());
1114 P.formatLine(Fmt: "Name Buffer Size: {0}", Items: IS->getByteSize());
1115 P.NewLine();
1116 }
1117
1118 BinaryStreamRef NameBuffer = IS->getStringTable().getBuffer();
1119 ArrayRef<uint8_t> Contents;
1120 cantFail(Err: NameBuffer.readBytes(Offset: 0, Size: NameBuffer.getLength(), Buffer&: Contents));
1121 P.formatBinary(Label: "Name Buffer", Data: Contents, StartOffset: 0);
1122 P.NewLine();
1123 {
1124 P.printLine(T: "Hash Table:");
1125 AutoIndent Indent(P);
1126 P.formatLine(Fmt: "Bucket Count: {0}", Items: IS->name_ids().size());
1127 for (const auto &Entry : enumerate(First: IS->name_ids()))
1128 P.formatLine(Fmt: "Bucket[{0}] : {1}", Items: Entry.index(),
1129 Items: uint32_t(Entry.value()));
1130 P.formatLine(Fmt: "Name Count: {0}", Items: IS->getNameCount());
1131 }
1132 }
1133 return Error::success();
1134}
1135
1136Error DumpOutputStyle::dumpStringTableFromObj() {
1137 return iterateModuleSubsections<DebugStringTableSubsectionRef>(
1138 File, HeaderScope: PrintScope{P, 4},
1139 Callback: [&](uint32_t Modi, const SymbolGroup &Strings,
1140 DebugStringTableSubsectionRef &Strings2) -> Error {
1141 BinaryStreamRef StringTableBuffer = Strings2.getBuffer();
1142 BinaryStreamReader Reader(StringTableBuffer);
1143 while (Reader.bytesRemaining() > 0) {
1144 StringRef Str;
1145 uint32_t Offset = Reader.getOffset();
1146 cantFail(Err: Reader.readCString(Dest&: Str));
1147 if (Str.empty())
1148 continue;
1149
1150 P.formatLine(Fmt: "{0} | {1}", Items: fmt_align(Item&: Offset, Where: AlignStyle::Right, Amount: 4),
1151 Items&: Str);
1152 }
1153 return Error::success();
1154 });
1155}
1156
1157Error DumpOutputStyle::dumpNamedStreams() {
1158 printHeader(P, S: "Named Streams");
1159
1160 if (File.isObj()) {
1161 printStreamNotValidForObj();
1162 return Error::success();
1163 }
1164
1165 AutoIndent Indent(P);
1166 ExitOnError Err("Invalid PDB File: ");
1167
1168 auto &IS = Err(File.pdb().getPDBInfoStream());
1169 const NamedStreamMap &NS = IS.getNamedStreams();
1170 for (const auto &Entry : NS.entries()) {
1171 P.printLine(T: Entry.getKey());
1172 AutoIndent Indent2(P, 2);
1173 P.formatLine(Fmt: "Index: {0}", Items: Entry.getValue());
1174 P.formatLine(Fmt: "Size in bytes: {0}",
1175 Items: File.pdb().getStreamByteSize(StreamIndex: Entry.getValue()));
1176 }
1177
1178 return Error::success();
1179}
1180
1181Error DumpOutputStyle::dumpStringTable() {
1182 printHeader(P, S: "String Table");
1183
1184 if (File.isPdb())
1185 return dumpStringTableFromPdb();
1186
1187 return dumpStringTableFromObj();
1188}
1189
1190static void buildDepSet(LazyRandomTypeCollection &Types,
1191 ArrayRef<TypeIndex> Indices,
1192 std::map<TypeIndex, CVType> &DepSet) {
1193 SmallVector<TypeIndex, 4> DepList;
1194 for (const auto &I : Indices) {
1195 TypeIndex TI(I);
1196 if (DepSet.find(x: TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
1197 continue;
1198
1199 CVType Type = Types.getType(Index: TI);
1200 DepSet[TI] = Type;
1201 codeview::discoverTypeIndices(Type, Indices&: DepList);
1202 buildDepSet(Types, Indices: DepList, DepSet);
1203 }
1204}
1205
1206static void
1207dumpFullTypeStream(LinePrinter &Printer, LazyRandomTypeCollection &Types,
1208 TypeReferenceTracker *RefTracker, uint32_t NumTypeRecords,
1209 uint32_t NumHashBuckets,
1210 FixedStreamArray<support::ulittle32_t> HashValues,
1211 TpiStream *Stream, bool Bytes, bool Extras) {
1212
1213 Printer.formatLine(Fmt: "Showing {0:N} records", Items&: NumTypeRecords);
1214 uint32_t Width =
1215 NumDigitsBase10(X: TypeIndex::FirstNonSimpleIndex + NumTypeRecords);
1216
1217 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types, RefTracker,
1218 NumHashBuckets, HashValues, Stream);
1219
1220 if (auto EC = codeview::visitTypeStream(Types, Callbacks&: V)) {
1221 Printer.formatLine(Fmt: "An error occurred dumping type records: {0}",
1222 Items: toString(E: std::move(EC)));
1223 }
1224}
1225
1226static void dumpPartialTypeStream(LinePrinter &Printer,
1227 LazyRandomTypeCollection &Types,
1228 TypeReferenceTracker *RefTracker,
1229 TpiStream &Stream, ArrayRef<TypeIndex> TiList,
1230 bool Bytes, bool Extras, bool Deps) {
1231 uint32_t Width = NumDigitsBase10(X: TypeIndex::FirstNonSimpleIndex +
1232 Stream.getNumTypeRecords());
1233
1234 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types, RefTracker,
1235 Stream.getNumHashBuckets(), Stream.getHashValues(),
1236 &Stream);
1237
1238 if (opts::dump::DumpTypeDependents) {
1239 // If we need to dump all dependents, then iterate each index and find
1240 // all dependents, adding them to a map ordered by TypeIndex.
1241 std::map<TypeIndex, CVType> DepSet;
1242 buildDepSet(Types, Indices: TiList, DepSet);
1243
1244 Printer.formatLine(
1245 Fmt: "Showing {0:N} records and their dependents ({1:N} records total)",
1246 Items: TiList.size(), Items: DepSet.size());
1247
1248 for (auto &Dep : DepSet) {
1249 if (auto EC = codeview::visitTypeRecord(Record&: Dep.second, Index: Dep.first, Callbacks&: V))
1250 Printer.formatLine(Fmt: "An error occurred dumping type record {0}: {1}",
1251 Items: Dep.first, Items: toString(E: std::move(EC)));
1252 }
1253 } else {
1254 Printer.formatLine(Fmt: "Showing {0:N} records.", Items: TiList.size());
1255
1256 for (const auto &I : TiList) {
1257 TypeIndex TI(I);
1258 if (TI.isSimple()) {
1259 Printer.formatLine(Fmt: "{0} | {1}", Items: fmt_align(Item: I, Where: AlignStyle::Right, Amount: Width),
1260 Items: Types.getTypeName(Index: TI));
1261 } else if (std::optional<CVType> Type = Types.tryGetType(Index: TI)) {
1262 if (auto EC = codeview::visitTypeRecord(Record&: *Type, Index: TI, Callbacks&: V))
1263 Printer.formatLine(Fmt: "An error occurred dumping type record {0}: {1}",
1264 Items&: TI, Items: toString(E: std::move(EC)));
1265 } else {
1266 Printer.formatLine(Fmt: "Type {0} doesn't exist in TPI stream", Items&: TI);
1267 }
1268 }
1269 }
1270}
1271
1272Error DumpOutputStyle::dumpTypesFromObjectFile() {
1273 LazyRandomTypeCollection Types(100);
1274
1275 for (const auto &S : getObj().sections()) {
1276 Expected<StringRef> NameOrErr = S.getName();
1277 if (!NameOrErr)
1278 return NameOrErr.takeError();
1279 StringRef SectionName = *NameOrErr;
1280
1281 // .debug$T is a standard CodeView type section, while .debug$P is the same
1282 // format but used for MSVC precompiled header object files.
1283 if (SectionName == ".debug$T")
1284 printHeader(P, S: "Types (.debug$T)");
1285 else if (SectionName == ".debug$P")
1286 printHeader(P, S: "Precompiled Types (.debug$P)");
1287 else
1288 continue;
1289
1290 Expected<StringRef> ContentsOrErr = S.getContents();
1291 if (!ContentsOrErr)
1292 return ContentsOrErr.takeError();
1293
1294 uint32_t Magic;
1295 BinaryStreamReader Reader(*ContentsOrErr, llvm::endianness::little);
1296 if (auto EC = Reader.readInteger(Dest&: Magic))
1297 return EC;
1298 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1299 return make_error<StringError>(Args: "Invalid CodeView debug section.",
1300 Args: inconvertibleErrorCode());
1301
1302 Types.reset(Reader, RecordCountHint: 100);
1303
1304 if (opts::dump::DumpTypes) {
1305 dumpFullTypeStream(Printer&: P, Types, RefTracker: RefTracker.get(), NumTypeRecords: 0, NumHashBuckets: 0, HashValues: {}, Stream: nullptr,
1306 Bytes: opts::dump::DumpTypeData, Extras: false);
1307 } else if (opts::dump::DumpTypeExtras) {
1308 auto LocalHashes = LocallyHashedType::hashTypeCollection(Types);
1309 auto GlobalHashes = GloballyHashedType::hashTypeCollection(Types);
1310 assert(LocalHashes.size() == GlobalHashes.size());
1311
1312 P.formatLine(Fmt: "Local / Global hashes:");
1313 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
1314 for (auto H : zip(t&: LocalHashes, u&: GlobalHashes)) {
1315 AutoIndent Indent2(P);
1316 LocallyHashedType &L = std::get<0>(t&: H);
1317 GloballyHashedType &G = std::get<1>(t&: H);
1318
1319 P.formatLine(Fmt: "TI: {0}, LocalHash: {1:X}, GlobalHash: {2}", Items&: TI, Items&: L, Items&: G);
1320
1321 ++TI;
1322 }
1323 P.NewLine();
1324 }
1325 }
1326
1327 return Error::success();
1328}
1329
1330Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
1331 assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
1332
1333 if (StreamIdx == StreamTPI) {
1334 printHeader(P, S: "Types (TPI Stream)");
1335 } else if (StreamIdx == StreamIPI) {
1336 printHeader(P, S: "Types (IPI Stream)");
1337 }
1338
1339 assert(!File.isObj());
1340
1341 bool Present = false;
1342 bool DumpTypes = false;
1343 bool DumpBytes = false;
1344 bool DumpExtras = false;
1345 std::vector<uint32_t> Indices;
1346 if (StreamIdx == StreamTPI) {
1347 Present = getPdb().hasPDBTpiStream();
1348 DumpTypes = opts::dump::DumpTypes;
1349 DumpBytes = opts::dump::DumpTypeData;
1350 DumpExtras = opts::dump::DumpTypeExtras;
1351 Indices.assign(first: opts::dump::DumpTypeIndex.begin(),
1352 last: opts::dump::DumpTypeIndex.end());
1353 } else if (StreamIdx == StreamIPI) {
1354 Present = getPdb().hasPDBIpiStream();
1355 DumpTypes = opts::dump::DumpIds;
1356 DumpBytes = opts::dump::DumpIdData;
1357 DumpExtras = opts::dump::DumpIdExtras;
1358 Indices.assign(first: opts::dump::DumpIdIndex.begin(),
1359 last: opts::dump::DumpIdIndex.end());
1360 }
1361
1362 if (!Present) {
1363 printStreamNotPresent(StreamName: StreamIdx == StreamTPI ? "TPI" : "IPI");
1364 return Error::success();
1365 }
1366
1367 AutoIndent Indent(P);
1368 ExitOnError Err("Unexpected error processing types: ");
1369
1370 auto &Stream = Err((StreamIdx == StreamTPI) ? getPdb().getPDBTpiStream()
1371 : getPdb().getPDBIpiStream());
1372
1373 auto &Types = (StreamIdx == StreamTPI) ? File.types() : File.ids();
1374
1375 // Only emit notes about referenced/unreferenced for types.
1376 TypeReferenceTracker *MaybeTracker =
1377 (StreamIdx == StreamTPI) ? RefTracker.get() : nullptr;
1378
1379 // Enable resolving forward decls.
1380 Stream.buildHashMap();
1381
1382 if (DumpTypes || !Indices.empty()) {
1383 if (Indices.empty())
1384 dumpFullTypeStream(Printer&: P, Types, RefTracker: MaybeTracker, NumTypeRecords: Stream.getNumTypeRecords(),
1385 NumHashBuckets: Stream.getNumHashBuckets(), HashValues: Stream.getHashValues(),
1386 Stream: &Stream, Bytes: DumpBytes, Extras: DumpExtras);
1387 else {
1388 std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
1389 dumpPartialTypeStream(Printer&: P, Types, RefTracker: MaybeTracker, Stream, TiList, Bytes: DumpBytes,
1390 Extras: DumpExtras, Deps: opts::dump::DumpTypeDependents);
1391 }
1392 }
1393
1394 if (DumpExtras) {
1395 P.NewLine();
1396
1397 P.formatLine(Fmt: "Header Version: {0}",
1398 Items: static_cast<uint32_t>(Stream.getTpiVersion()));
1399 P.formatLine(Fmt: "Hash Stream Index: {0}", Items: Stream.getTypeHashStreamIndex());
1400 P.formatLine(Fmt: "Aux Hash Stream Index: {0}",
1401 Items: Stream.getTypeHashStreamAuxIndex());
1402 P.formatLine(Fmt: "Hash Key Size: {0}", Items: Stream.getHashKeySize());
1403 P.formatLine(Fmt: "Num Hash Buckets: {0}", Items: Stream.getNumHashBuckets());
1404
1405 auto IndexOffsets = Stream.getTypeIndexOffsets();
1406 P.formatLine(Fmt: "Type Index Offsets:");
1407 for (const auto &IO : IndexOffsets) {
1408 AutoIndent Indent2(P);
1409 P.formatLine(Fmt: "TI: {0}, Offset: {1}", Items: IO.Type, Items: fmtle(Value: IO.Offset));
1410 }
1411
1412 if (getPdb().hasPDBStringTable()) {
1413 P.NewLine();
1414 P.formatLine(Fmt: "Hash Adjusters:");
1415 auto &Adjusters = Stream.getHashAdjusters();
1416 auto &Strings = Err(getPdb().getStringTable());
1417 for (const auto &A : Adjusters) {
1418 AutoIndent Indent2(P);
1419 auto ExpectedStr = Strings.getStringForID(ID: A.first);
1420 TypeIndex TI(A.second);
1421 if (ExpectedStr)
1422 P.formatLine(Fmt: "`{0}` -> {1}", Items&: *ExpectedStr, Items&: TI);
1423 else {
1424 P.formatLine(Fmt: "unknown str id ({0}) -> {1}", Items: A.first, Items&: TI);
1425 consumeError(Err: ExpectedStr.takeError());
1426 }
1427 }
1428 }
1429 }
1430 return Error::success();
1431}
1432
1433Error DumpOutputStyle::dumpModuleSymsForObj() {
1434 printHeader(P, S: "Symbols");
1435
1436 AutoIndent Indent(P);
1437
1438 auto &Types = File.types();
1439
1440 SymbolVisitorCallbackPipeline Pipeline;
1441 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::ObjectFile);
1442 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Types, Types);
1443
1444 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
1445 Pipeline.addCallbackToPipeline(Callbacks&: Dumper);
1446 CVSymbolVisitor Visitor(Pipeline);
1447
1448 return iterateModuleSubsections<DebugSymbolsSubsectionRef>(
1449 File, HeaderScope: PrintScope{P, 2},
1450 Callback: [&](uint32_t Modi, const SymbolGroup &Strings,
1451 DebugSymbolsSubsectionRef &Symbols) -> Error {
1452 Dumper.setSymbolGroup(&Strings);
1453 for (auto Symbol : Symbols) {
1454 if (auto EC = Visitor.visitSymbolRecord(Record&: Symbol)) {
1455 return EC;
1456 }
1457 }
1458 return Error::success();
1459 });
1460}
1461
1462Error DumpOutputStyle::dumpModuleSymsForPdb() {
1463 printHeader(P, S: "Symbols");
1464
1465 if (File.isPdb() && !getPdb().hasPDBDbiStream()) {
1466 printStreamNotPresent(StreamName: "DBI");
1467 return Error::success();
1468 }
1469
1470 AutoIndent Indent(P);
1471
1472 auto &Ids = File.ids();
1473 auto &Types = File.types();
1474
1475 return iterateSymbolGroups(
1476 Input&: File, HeaderScope: PrintScope{P, 2},
1477 Callback: [&](uint32_t I, const SymbolGroup &Strings) -> Error {
1478 auto ExpectedModS = getModuleDebugStream(File&: File.pdb(), Index: I);
1479 if (!ExpectedModS) {
1480 P.formatLine(Fmt: "Error loading module stream {0}. {1}", Items&: I,
1481 Items: toString(E: ExpectedModS.takeError()));
1482 return Error::success();
1483 }
1484
1485 ModuleDebugStreamRef &ModS = *ExpectedModS;
1486
1487 SymbolVisitorCallbackPipeline Pipeline;
1488 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1489 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Strings,
1490 Ids, Types);
1491
1492 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
1493 Pipeline.addCallbackToPipeline(Callbacks&: Dumper);
1494 CVSymbolVisitor Visitor(Pipeline);
1495 auto SS = ModS.getSymbolsSubstream();
1496 if (opts::Filters.SymbolOffset) {
1497 CVSymbolVisitor::FilterOptions Filter;
1498 Filter.SymbolOffset = opts::Filters.SymbolOffset;
1499 Filter.ParentRecursiveDepth = opts::Filters.ParentRecurseDepth;
1500 Filter.ChildRecursiveDepth = opts::Filters.ChildrenRecurseDepth;
1501 if (auto EC = Visitor.visitSymbolStreamFiltered(Symbols: ModS.getSymbolArray(),
1502 Filter)) {
1503 P.formatLine(Fmt: "Error while processing symbol records. {0}",
1504 Items: toStringWithoutConsuming(E: EC));
1505 return EC;
1506 }
1507 } else if (auto EC = Visitor.visitSymbolStream(Symbols: ModS.getSymbolArray(),
1508 InitialOffset: SS.Offset)) {
1509 P.formatLine(Fmt: "Error while processing symbol records. {0}",
1510 Items: toStringWithoutConsuming(E: EC));
1511 return EC;
1512 }
1513 return Error::success();
1514 });
1515}
1516
1517Error DumpOutputStyle::dumpTypeRefStats() {
1518 printHeader(P, S: "Type Reference Statistics");
1519 AutoIndent Indent(P);
1520
1521 // Sum the byte size of all type records, and the size and count of all
1522 // referenced records.
1523 size_t TotalRecs = File.types().size();
1524 size_t RefRecs = 0;
1525 size_t TotalBytes = 0;
1526 size_t RefBytes = 0;
1527 auto &Types = File.types();
1528 for (std::optional<TypeIndex> TI = Types.getFirst(); TI;
1529 TI = Types.getNext(Prev: *TI)) {
1530 CVType Type = File.types().getType(Index: *TI);
1531 TotalBytes += Type.length();
1532 if (RefTracker->isTypeReferenced(TI: *TI)) {
1533 ++RefRecs;
1534 RefBytes += Type.length();
1535 }
1536 }
1537
1538 P.formatLine(Fmt: "Records referenced: {0:N} / {1:N} {2:P}", Items&: RefRecs, Items&: TotalRecs,
1539 Items: (double)RefRecs / TotalRecs);
1540 P.formatLine(Fmt: "Bytes referenced: {0:N} / {1:N} {2:P}", Items&: RefBytes, Items&: TotalBytes,
1541 Items: (double)RefBytes / TotalBytes);
1542
1543 return Error::success();
1544}
1545
1546Error DumpOutputStyle::dumpGSIRecords() {
1547 printHeader(P, S: "GSI Records");
1548
1549 if (File.isObj()) {
1550 printStreamNotValidForObj();
1551 return Error::success();
1552 }
1553
1554 if (!getPdb().hasPDBSymbolStream()) {
1555 printStreamNotPresent(StreamName: "GSI Common Symbol");
1556 return Error::success();
1557 }
1558
1559 AutoIndent Indent(P);
1560
1561 auto &Records = cantFail(ValOrErr: getPdb().getPDBSymbolStream());
1562 auto &Types = File.types();
1563 auto &Ids = File.ids();
1564
1565 P.printLine(T: "Records");
1566 SymbolVisitorCallbackPipeline Pipeline;
1567 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1568 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids, Types);
1569
1570 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
1571 Pipeline.addCallbackToPipeline(Callbacks&: Dumper);
1572 CVSymbolVisitor Visitor(Pipeline);
1573
1574 BinaryStreamRef SymStream = Records.getSymbolArray().getUnderlyingStream();
1575 if (auto E = Visitor.visitSymbolStream(Symbols: Records.getSymbolArray(), InitialOffset: 0))
1576 return E;
1577 return Error::success();
1578}
1579
1580Error DumpOutputStyle::dumpGlobals() {
1581 printHeader(P, S: "Global Symbols");
1582
1583 if (File.isObj()) {
1584 printStreamNotValidForObj();
1585 return Error::success();
1586 }
1587
1588 if (!getPdb().hasPDBGlobalsStream()) {
1589 printStreamNotPresent(StreamName: "Globals");
1590 return Error::success();
1591 }
1592
1593 AutoIndent Indent(P);
1594 ExitOnError Err("Error dumping globals stream: ");
1595 auto &Globals = Err(getPdb().getPDBGlobalsStream());
1596
1597 if (opts::dump::DumpGlobalNames.empty()) {
1598 const GSIHashTable &Table = Globals.getGlobalsTable();
1599 Err(dumpSymbolsFromGSI(Table, HashExtras: opts::dump::DumpGlobalExtras));
1600 } else {
1601 SymbolStream &SymRecords = cantFail(ValOrErr: getPdb().getPDBSymbolStream());
1602 auto &Types = File.types();
1603 auto &Ids = File.ids();
1604
1605 SymbolVisitorCallbackPipeline Pipeline;
1606 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1607 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids, Types);
1608
1609 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
1610 Pipeline.addCallbackToPipeline(Callbacks&: Dumper);
1611 CVSymbolVisitor Visitor(Pipeline);
1612
1613 using ResultEntryType = std::pair<uint32_t, CVSymbol>;
1614 for (StringRef Name : opts::dump::DumpGlobalNames) {
1615 AutoIndent Indent(P);
1616 P.formatLine(Fmt: "Global Name `{0}`", Items&: Name);
1617 std::vector<ResultEntryType> Results =
1618 Globals.findRecordsByName(Name, Symbols: SymRecords);
1619 if (Results.empty()) {
1620 AutoIndent Indent(P);
1621 P.printLine(T: "(no matching records found)");
1622 continue;
1623 }
1624
1625 for (ResultEntryType Result : Results) {
1626 if (auto E = Visitor.visitSymbolRecord(Record&: Result.second, Offset: Result.first))
1627 return E;
1628 }
1629 }
1630 }
1631 return Error::success();
1632}
1633
1634Error DumpOutputStyle::dumpPublics() {
1635 printHeader(P, S: "Public Symbols");
1636
1637 if (File.isObj()) {
1638 printStreamNotValidForObj();
1639 return Error::success();
1640 }
1641
1642 if (!getPdb().hasPDBPublicsStream()) {
1643 printStreamNotPresent(StreamName: "Publics");
1644 return Error::success();
1645 }
1646
1647 AutoIndent Indent(P);
1648 ExitOnError Err("Error dumping publics stream: ");
1649 auto &Publics = Err(getPdb().getPDBPublicsStream());
1650
1651 const GSIHashTable &PublicsTable = Publics.getPublicsTable();
1652 if (opts::dump::DumpPublicExtras) {
1653 P.printLine(T: "Publics Header");
1654 AutoIndent Indent(P);
1655 P.formatLine(Fmt: "sym hash = {0}, thunk table addr = {1}", Items: Publics.getSymHash(),
1656 Items: formatSegmentOffset(Segment: Publics.getThunkTableSection(),
1657 Offset: Publics.getThunkTableOffset()));
1658 }
1659 Err(dumpSymbolsFromGSI(Table: PublicsTable, HashExtras: opts::dump::DumpPublicExtras));
1660
1661 // Skip the rest if we aren't dumping extras.
1662 if (!opts::dump::DumpPublicExtras)
1663 return Error::success();
1664
1665 P.formatLine(Fmt: "Address Map");
1666 {
1667 // These are offsets into the publics stream sorted by secidx:secrel.
1668 AutoIndent Indent2(P);
1669 for (uint32_t Addr : Publics.getAddressMap())
1670 P.formatLine(Fmt: "off = {0}", Items&: Addr);
1671 }
1672
1673 // The thunk map is optional debug info used for ILT thunks.
1674 if (!Publics.getThunkMap().empty()) {
1675 P.formatLine(Fmt: "Thunk Map");
1676 AutoIndent Indent2(P);
1677 for (uint32_t Addr : Publics.getThunkMap())
1678 P.formatLine(Fmt: "{0:x8}", Items&: Addr);
1679 }
1680
1681 // The section offsets table appears to be empty when incremental linking
1682 // isn't in use.
1683 if (!Publics.getSectionOffsets().empty()) {
1684 P.formatLine(Fmt: "Section Offsets");
1685 AutoIndent Indent2(P);
1686 for (const SectionOffset &SO : Publics.getSectionOffsets())
1687 P.formatLine(Fmt: "{0:x4}:{1:x8}", Items: uint16_t(SO.Isect), Items: uint32_t(SO.Off));
1688 }
1689
1690 return Error::success();
1691}
1692
1693Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1694 bool HashExtras) {
1695 auto ExpectedSyms = getPdb().getPDBSymbolStream();
1696 if (!ExpectedSyms)
1697 return ExpectedSyms.takeError();
1698 auto &Types = File.types();
1699 auto &Ids = File.ids();
1700
1701 if (HashExtras) {
1702 P.printLine(T: "GSI Header");
1703 AutoIndent Indent(P);
1704 P.formatLine(Fmt: "sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1705 Items: Table.getVerSignature(), Items: Table.getVerHeader(),
1706 Items: Table.getHashRecordSize(), Items: Table.getNumBuckets());
1707 }
1708
1709 {
1710 P.printLine(T: "Records");
1711 SymbolVisitorCallbackPipeline Pipeline;
1712 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1713 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids, Types);
1714
1715 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
1716 Pipeline.addCallbackToPipeline(Callbacks&: Dumper);
1717 CVSymbolVisitor Visitor(Pipeline);
1718
1719
1720 BinaryStreamRef SymStream =
1721 ExpectedSyms->getSymbolArray().getUnderlyingStream();
1722 for (uint32_t PubSymOff : Table) {
1723 Expected<CVSymbol> Sym = readSymbolFromStream(Stream: SymStream, Offset: PubSymOff);
1724 if (!Sym)
1725 return Sym.takeError();
1726 if (auto E = Visitor.visitSymbolRecord(Record&: *Sym, Offset: PubSymOff))
1727 return E;
1728 }
1729 }
1730
1731 // Return early if we aren't dumping public hash table and address map info.
1732 if (HashExtras) {
1733 P.formatLine(Fmt: "Hash Entries");
1734 {
1735 AutoIndent Indent2(P);
1736 for (const PSHashRecord &HR : Table.HashRecords)
1737 P.formatLine(Fmt: "off = {0}, refcnt = {1}", Items: uint32_t(HR.Off),
1738 Items: uint32_t(HR.CRef));
1739 }
1740
1741 P.formatLine(Fmt: "Hash Buckets");
1742 {
1743 AutoIndent Indent2(P);
1744 for (uint32_t Hash : Table.HashBuckets)
1745 P.formatLine(Fmt: "{0:x8}", Items&: Hash);
1746 }
1747 }
1748
1749 return Error::success();
1750}
1751
1752static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1753 OMFSegDescFlags Flags) {
1754 std::vector<std::string> Opts;
1755 if (Flags == OMFSegDescFlags::None)
1756 return "none";
1757
1758 PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1759 PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1760 PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1761 PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1762 PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1763 PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1764 PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
1765 return typesetItemList(Opts, IndentLevel, GroupSize: 4, Sep: " | ");
1766}
1767
1768Error DumpOutputStyle::dumpSectionHeaders() {
1769 dumpSectionHeaders(Label: "Section Headers", Type: DbgHeaderType::SectionHdr);
1770 dumpSectionHeaders(Label: "Original Section Headers", Type: DbgHeaderType::SectionHdrOrig);
1771 return Error::success();
1772}
1773
1774void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1775 printHeader(P, S: Label);
1776
1777 if (File.isObj()) {
1778 printStreamNotValidForObj();
1779 return;
1780 }
1781
1782 if (!getPdb().hasPDBDbiStream()) {
1783 printStreamNotPresent(StreamName: "DBI");
1784 return;
1785 }
1786
1787 AutoIndent Indent(P);
1788 ExitOnError Err("Error dumping section headers: ");
1789 std::unique_ptr<MappedBlockStream> Stream;
1790 ArrayRef<object::coff_section> Headers;
1791 auto ExpectedHeaders = loadSectionHeaders(File&: getPdb(), Type);
1792 if (!ExpectedHeaders) {
1793 P.printLine(T: toString(E: ExpectedHeaders.takeError()));
1794 return;
1795 }
1796 std::tie(args&: Stream, args&: Headers) = std::move(*ExpectedHeaders);
1797
1798 uint32_t I = 1;
1799 for (const auto &Header : Headers) {
1800 P.NewLine();
1801 P.formatLine(Fmt: "SECTION HEADER #{0}", Items&: I);
1802 P.formatLine(Fmt: "{0,8} name", Items: Header.Name);
1803 P.formatLine(Fmt: "{0,8:X-} virtual size", Items: uint32_t(Header.VirtualSize));
1804 P.formatLine(Fmt: "{0,8:X-} virtual address", Items: uint32_t(Header.VirtualAddress));
1805 P.formatLine(Fmt: "{0,8:X-} size of raw data", Items: uint32_t(Header.SizeOfRawData));
1806 P.formatLine(Fmt: "{0,8:X-} file pointer to raw data",
1807 Items: uint32_t(Header.PointerToRawData));
1808 P.formatLine(Fmt: "{0,8:X-} file pointer to relocation table",
1809 Items: uint32_t(Header.PointerToRelocations));
1810 P.formatLine(Fmt: "{0,8:X-} file pointer to line numbers",
1811 Items: uint32_t(Header.PointerToLinenumbers));
1812 P.formatLine(Fmt: "{0,8:X-} number of relocations",
1813 Items: uint32_t(Header.NumberOfRelocations));
1814 P.formatLine(Fmt: "{0,8:X-} number of line numbers",
1815 Items: uint32_t(Header.NumberOfLinenumbers));
1816 P.formatLine(Fmt: "{0,8:X-} flags", Items: uint32_t(Header.Characteristics));
1817 AutoIndent IndentMore(P, 9);
1818 P.formatLine(Fmt: "{0}", Items: formatSectionCharacteristics(
1819 IndentLevel: P.getIndentLevel(), C: Header.Characteristics, FlagsPerLine: 1, Separator: ""));
1820 ++I;
1821 }
1822}
1823
1824Error DumpOutputStyle::dumpSectionContribs() {
1825 printHeader(P, S: "Section Contributions");
1826
1827 if (File.isObj()) {
1828 printStreamNotValidForObj();
1829 return Error::success();
1830 }
1831
1832 if (!getPdb().hasPDBDbiStream()) {
1833 printStreamNotPresent(StreamName: "DBI");
1834 return Error::success();
1835 }
1836
1837 AutoIndent Indent(P);
1838 ExitOnError Err("Error dumping section contributions: ");
1839
1840 DbiStream &Dbi = Err(getPdb().getPDBDbiStream());
1841
1842 class Visitor : public ISectionContribVisitor {
1843 public:
1844 Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1845 auto Max = llvm::max_element(Range&: Names, C: [](StringRef S1, StringRef S2) {
1846 return S1.size() < S2.size();
1847 });
1848 MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1849 }
1850 void visit(const SectionContrib &SC) override {
1851 dumpSectionContrib(P, SC, SectionNames: Names, FieldWidth: MaxNameLen);
1852 }
1853 void visit(const SectionContrib2 &SC) override {
1854 dumpSectionContrib(P, SC, SectionNames: Names, FieldWidth: MaxNameLen);
1855 }
1856
1857 private:
1858 LinePrinter &P;
1859 uint32_t MaxNameLen;
1860 ArrayRef<std::string> Names;
1861 };
1862
1863 auto NamesOrErr = getSectionNames(File&: getPdb());
1864 if (!NamesOrErr)
1865 return NamesOrErr.takeError();
1866 ArrayRef<std::string> Names = *NamesOrErr;
1867 Visitor V(P, Names);
1868 Dbi.visitSectionContributions(Visitor&: V);
1869 return Error::success();
1870}
1871
1872Error DumpOutputStyle::dumpSectionMap() {
1873 printHeader(P, S: "Section Map");
1874
1875 if (File.isObj()) {
1876 printStreamNotValidForObj();
1877 return Error::success();
1878 }
1879
1880 if (!getPdb().hasPDBDbiStream()) {
1881 printStreamNotPresent(StreamName: "DBI");
1882 return Error::success();
1883 }
1884
1885 AutoIndent Indent(P);
1886 ExitOnError Err("Error dumping section map: ");
1887
1888 DbiStream &Dbi = Err(getPdb().getPDBDbiStream());
1889
1890 uint32_t I = 0;
1891 for (auto &M : Dbi.getSectionMap()) {
1892 P.formatLine(
1893 Fmt: "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", Items&: I,
1894 Items: fmtle(Value: M.Ovl), Items: fmtle(Value: M.Group), Items: fmtle(Value: M.Frame), Items: fmtle(Value: M.SecName));
1895 P.formatLine(Fmt: " class = {0}, offset = {1}, size = {2}",
1896 Items: fmtle(Value: M.ClassName), Items: fmtle(Value: M.Offset), Items: fmtle(Value: M.SecByteLength));
1897 P.formatLine(Fmt: " flags = {0}",
1898 Items: formatSegMapDescriptorFlag(
1899 IndentLevel: P.getIndentLevel() + 13,
1900 Flags: static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1901 ++I;
1902 }
1903 return Error::success();
1904}
1905
1906Error DumpOutputStyle::dumpDXContainer() {
1907 printHeader(P, S: "DirectX Container");
1908 if (File.isObj()) {
1909 printStreamNotValidForObj();
1910 return Error::success();
1911 }
1912
1913 AutoIndent Indent(P);
1914 auto Dxc = getPdb().getDXContainerStream();
1915 if (!Dxc) {
1916 P.formatLine(Fmt: "Not present in file");
1917 consumeError(Err: Dxc.takeError());
1918 return Error::success();
1919 }
1920
1921 auto Header = Dxc->getHeader();
1922 P.formatLine(Fmt: "Hash: ");
1923 P << format_bytes(Bytes: Header.FileHash.Digest, FirstByteOffset: std::nullopt,
1924 NumPerLine: sizeof(Header.FileHash), ByteGroupSize: sizeof(Header.FileHash), IndentLevel: 0, Upper: true);
1925 P.formatLine(Fmt: "Version:");
1926 {
1927 AutoIndent Indent(P);
1928 P.formatLine(Fmt: "Major: {0}", Items&: Header.Version.Major);
1929 P.formatLine(Fmt: "Minor: {0}", Items&: Header.Version.Minor);
1930 }
1931 P.formatLine(Fmt: "FileSize: {0}", Items&: Header.FileSize);
1932 P.formatLine(Fmt: "PartCount: {0}", Items&: Header.PartCount);
1933 P.formatLine(Fmt: "Parts:");
1934 for (auto &part : *Dxc) {
1935 AutoIndent Indent(P);
1936 P.formatLine(Fmt: "{0} | offset = {1}, size = {2}", Items: part.Part.getName(),
1937 Items: part.Offset, Items: part.Part.Size);
1938 }
1939 return Error::success();
1940}
1941