blob: c573f606786cefb169c0d607e14969b4202c66b9 [file] [log] [blame]
Zachary Turner7df69952017-06-22 20:57:39 +00001//===- DumpOutputStyle.cpp ------------------------------------ *- C++ --*-===//
Zachary Turner63055452017-06-15 22:24:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Zachary Turner7df69952017-06-22 20:57:39 +000010#include "DumpOutputStyle.h"
Zachary Turner63055452017-06-15 22:24:24 +000011
Zachary Turner63055452017-06-15 22:24:24 +000012#include "FormatUtil.h"
13#include "MinimalSymbolDumper.h"
14#include "MinimalTypeDumper.h"
15#include "StreamUtil.h"
16#include "llvm-pdbutil.h"
17
Zachary Turnerf2872b92017-06-15 23:59:56 +000018#include "llvm/ADT/STLExtras.h"
Zachary Turner63055452017-06-15 22:24:24 +000019#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"
Zachary Turner02a26772017-06-30 18:15:47 +000040#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Zachary Turner63055452017-06-15 22:24:24 +000041#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"
Reid Kleckner14d90fd2017-07-26 00:40:36 +000052#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
Zachary Turner63055452017-06-15 22:24:24 +000053#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"
61
62#include <unordered_map>
63
64using namespace llvm;
65using namespace llvm::codeview;
66using namespace llvm::msf;
67using namespace llvm::pdb;
68
Zachary Turner7df69952017-06-22 20:57:39 +000069DumpOutputStyle::DumpOutputStyle(PDBFile &File)
Zachary Turner63055452017-06-15 22:24:24 +000070 : File(File), P(2, false, outs()) {}
71
Zachary Turner7df69952017-06-22 20:57:39 +000072Error DumpOutputStyle::dump() {
73 if (opts::dump::DumpSummary) {
Zachary Turner63055452017-06-15 22:24:24 +000074 if (auto EC = dumpFileSummary())
75 return EC;
76 P.NewLine();
77 }
78
Zachary Turner7df69952017-06-22 20:57:39 +000079 if (opts::dump::DumpStreams) {
Zachary Turner63055452017-06-15 22:24:24 +000080 if (auto EC = dumpStreamSummary())
81 return EC;
82 P.NewLine();
83 }
84
Zachary Turnerd1de2f42017-08-21 14:53:25 +000085 if (opts::dump::DumpModuleStats.getNumOccurrences() > 0) {
86 if (auto EC = dumpModuleStats())
87 return EC;
88 P.NewLine();
89 }
90
Zachary Turner7df69952017-06-22 20:57:39 +000091 if (opts::dump::DumpStringTable) {
Zachary Turner63055452017-06-15 22:24:24 +000092 if (auto EC = dumpStringTable())
93 return EC;
94 P.NewLine();
95 }
96
Zachary Turner7df69952017-06-22 20:57:39 +000097 if (opts::dump::DumpModules) {
Zachary Turner63055452017-06-15 22:24:24 +000098 if (auto EC = dumpModules())
99 return EC;
100 }
101
Zachary Turner7df69952017-06-22 20:57:39 +0000102 if (opts::dump::DumpModuleFiles) {
Zachary Turner0e327d02017-06-15 23:12:41 +0000103 if (auto EC = dumpModuleFiles())
104 return EC;
105 }
106
Zachary Turner7df69952017-06-22 20:57:39 +0000107 if (opts::dump::DumpLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000108 if (auto EC = dumpLines())
109 return EC;
110 }
111
Zachary Turner7df69952017-06-22 20:57:39 +0000112 if (opts::dump::DumpInlineeLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000113 if (auto EC = dumpInlineeLines())
114 return EC;
115 }
116
Zachary Turner7df69952017-06-22 20:57:39 +0000117 if (opts::dump::DumpXmi) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000118 if (auto EC = dumpXmi())
119 return EC;
120 }
121
Zachary Turner7df69952017-06-22 20:57:39 +0000122 if (opts::dump::DumpXme) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000123 if (auto EC = dumpXme())
124 return EC;
125 }
126
Zachary Turner02a26772017-06-30 18:15:47 +0000127 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
128 opts::dump::DumpTypeExtras) {
Zachary Turner63055452017-06-15 22:24:24 +0000129 if (auto EC = dumpTpiStream(StreamTPI))
130 return EC;
131 }
132
Zachary Turner02a26772017-06-30 18:15:47 +0000133 if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
134 opts::dump::DumpIdExtras) {
Zachary Turner63055452017-06-15 22:24:24 +0000135 if (auto EC = dumpTpiStream(StreamIPI))
136 return EC;
137 }
138
Reid Kleckner14d90fd2017-07-26 00:40:36 +0000139 if (opts::dump::DumpGlobals) {
140 if (auto EC = dumpGlobals())
141 return EC;
142 }
143
Zachary Turner7df69952017-06-22 20:57:39 +0000144 if (opts::dump::DumpPublics) {
Zachary Turner63055452017-06-15 22:24:24 +0000145 if (auto EC = dumpPublics())
146 return EC;
147 }
148
Zachary Turner7df69952017-06-22 20:57:39 +0000149 if (opts::dump::DumpSymbols) {
Zachary Turner63055452017-06-15 22:24:24 +0000150 if (auto EC = dumpModuleSyms())
151 return EC;
152 }
153
Zachary Turnerfb1cd502017-08-04 20:02:38 +0000154 if (opts::dump::DumpSectionHeaders) {
155 if (auto EC = dumpSectionHeaders())
156 return EC;
157 }
158
Zachary Turner7df69952017-06-22 20:57:39 +0000159 if (opts::dump::DumpSectionContribs) {
Zachary Turner63055452017-06-15 22:24:24 +0000160 if (auto EC = dumpSectionContribs())
161 return EC;
162 }
163
Zachary Turner7df69952017-06-22 20:57:39 +0000164 if (opts::dump::DumpSectionMap) {
Zachary Turner63055452017-06-15 22:24:24 +0000165 if (auto EC = dumpSectionMap())
166 return EC;
167 }
168
169 return Error::success();
170}
171
172static void printHeader(LinePrinter &P, const Twine &S) {
173 P.NewLine();
174 P.formatLine("{0,=60}", S);
175 P.formatLine("{0}", fmt_repeat('=', 60));
176}
177
Zachary Turner7df69952017-06-22 20:57:39 +0000178Error DumpOutputStyle::dumpFileSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000179 printHeader(P, "Summary");
180
Reid Klecknerdd853e52017-07-27 23:13:18 +0000181 ExitOnError Err("Invalid PDB Format: ");
Zachary Turner63055452017-06-15 22:24:24 +0000182
183 AutoIndent Indent(P);
184 P.formatLine("Block Size: {0}", File.getBlockSize());
185 P.formatLine("Number of blocks: {0}", File.getBlockCount());
186 P.formatLine("Number of streams: {0}", File.getNumStreams());
187
188 auto &PS = Err(File.getPDBInfoStream());
189 P.formatLine("Signature: {0}", PS.getSignature());
190 P.formatLine("Age: {0}", PS.getAge());
191 P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
192 P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
193 P.formatLine("Has Debug Info: {0}", File.hasPDBDbiStream());
194 P.formatLine("Has Types: {0}", File.hasPDBTpiStream());
195 P.formatLine("Has IDs: {0}", File.hasPDBIpiStream());
196 P.formatLine("Has Globals: {0}", File.hasPDBGlobalsStream());
197 P.formatLine("Has Publics: {0}", File.hasPDBPublicsStream());
198 if (File.hasPDBDbiStream()) {
199 auto &DBI = Err(File.getPDBDbiStream());
200 P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
201 P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
202 P.formatLine("Is stripped: {0}", DBI.isStripped());
203 }
204
205 return Error::success();
206}
207
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000208static StatCollection getSymbolStats(ModuleDebugStreamRef MDS,
209 StatCollection &CumulativeStats) {
210 StatCollection Stats;
211 for (const auto &S : MDS.symbols(nullptr)) {
212 Stats.update(S.kind(), S.length());
213 CumulativeStats.update(S.kind(), S.length());
214 }
215 return Stats;
216}
217
218static StatCollection getChunkStats(ModuleDebugStreamRef MDS,
219 StatCollection &CumulativeStats) {
220 StatCollection Stats;
221 for (const auto &Chunk : MDS.subsections()) {
222 Stats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
223 CumulativeStats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
224 }
225 return Stats;
226}
227
228static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
229 return formatChunkKind(K, false);
230}
231
232static inline std::string formatModuleDetailKind(SymbolKind K) {
233 return formatSymbolKind(K);
234}
235
236template <typename Kind>
237static void printModuleDetailStats(LinePrinter &P, StringRef Label,
238 const StatCollection &Stats) {
239 P.NewLine();
240 P.formatLine(" {0}", Label);
241 AutoIndent Indent(P);
242 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
243 Stats.Totals.Count, Stats.Totals.Size);
244 P.formatLine("{0}", fmt_repeat('-', 74));
245 for (const auto &K : Stats.Individual) {
246 std::string KindName = formatModuleDetailKind(Kind(K.first));
247 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName,
248 K.second.Count, K.second.Size);
249 }
250}
251
252static bool isMyCode(const DbiModuleDescriptor &Desc) {
253 StringRef Name = Desc.getModuleName();
254 if (Name.startswith("Import:"))
255 return false;
256 if (Name.endswith_lower(".dll"))
257 return false;
258 if (Name.equals_lower("* linker *"))
259 return false;
260 if (Name.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
261 return false;
262 if (Name.startswith_lower("f:\\dd\\vctools\\crt"))
263 return false;
264 return true;
265}
266
267static bool shouldDumpModule(uint32_t Modi, const DbiModuleDescriptor &Desc) {
268 if (opts::dump::JustMyCode && !isMyCode(Desc))
269 return false;
270
271 // If the arg was not specified on the command line, always dump all modules.
272 if (opts::dump::DumpModi.getNumOccurrences() == 0)
273 return true;
274
275 // Otherwise, only dump if this is the same module specified.
276 return (opts::dump::DumpModi == Modi);
277}
278
Zachary Turner7df69952017-06-22 20:57:39 +0000279Error DumpOutputStyle::dumpStreamSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000280 printHeader(P, "Streams");
281
282 if (StreamPurposes.empty())
283 discoverStreamPurposes(File, StreamPurposes);
284
285 AutoIndent Indent(P);
286 uint32_t StreamCount = File.getNumStreams();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000287 uint32_t MaxStreamSize = File.getMaxStreamSize();
Zachary Turner63055452017-06-15 22:24:24 +0000288
289 for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
290 P.formatLine(
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000291 "Stream {0} ({1} bytes): [{2}]",
Zachary Turner63055452017-06-15 22:24:24 +0000292 fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000293 fmt_align(File.getStreamByteSize(StreamIdx), AlignStyle::Right,
294 NumDigits(MaxStreamSize)),
295 StreamPurposes[StreamIdx].getLongName());
296
Zachary Turner5f098522017-06-23 20:28:14 +0000297 if (opts::dump::DumpStreamBlocks) {
298 auto Blocks = File.getStreamBlockList(StreamIdx);
299 std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
300 P.formatLine(" {0} Blocks: [{1}]",
301 fmt_repeat(' ', NumDigits(StreamCount)),
302 make_range(BV.begin(), BV.end()));
303 }
Zachary Turner63055452017-06-15 22:24:24 +0000304 }
305
306 return Error::success();
307}
308
Zachary Turner0e327d02017-06-15 23:12:41 +0000309static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
310 uint32_t Index) {
Reid Klecknerdd853e52017-07-27 23:13:18 +0000311 ExitOnError Err("Unexpected error: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000312
313 auto &Dbi = Err(File.getPDBDbiStream());
314 const auto &Modules = Dbi.modules();
315 auto Modi = Modules.getModuleDescriptor(Index);
316
317 uint16_t ModiStream = Modi.getModuleStreamIndex();
318 if (ModiStream == kInvalidStreamIndex)
319 return make_error<RawError>(raw_error_code::no_stream,
320 "Module stream not present");
321
322 auto ModStreamData = MappedBlockStream::createIndexedStream(
323 File.getMsfLayout(), File.getMsfBuffer(), ModiStream,
324 File.getAllocator());
325
326 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
327 if (auto EC = ModS.reload())
328 return make_error<RawError>(raw_error_code::corrupt_file,
329 "Invalid module stream");
330
331 return std::move(ModS);
332}
333
Zachary Turner0e327d02017-06-15 23:12:41 +0000334static std::string formatChecksumKind(FileChecksumKind Kind) {
335 switch (Kind) {
336 RETURN_CASE(FileChecksumKind, None, "None");
337 RETURN_CASE(FileChecksumKind, MD5, "MD5");
338 RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
339 RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
340 }
341 return formatUnknownEnum(Kind);
342}
343
Zachary Turner4e950642017-06-15 23:56:19 +0000344namespace {
345class StringsAndChecksumsPrinter {
346 const DebugStringTableSubsectionRef &extractStringTable(PDBFile &File) {
Reid Klecknerdd853e52017-07-27 23:13:18 +0000347 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner4e950642017-06-15 23:56:19 +0000348 return Err(File.getStringTable()).getStringTable();
349 }
350
351 template <typename... Args>
352 void formatInternal(LinePrinter &Printer, bool Append,
353 Args &&... args) const {
354 if (Append)
355 Printer.format(std::forward<Args>(args)...);
356 else
357 Printer.formatLine(std::forward<Args>(args)...);
358 }
359
360public:
361 StringsAndChecksumsPrinter(PDBFile &File, uint32_t Modi)
362 : Records(extractStringTable(File)) {
363 auto MDS = getModuleDebugStream(File, Modi);
364 if (!MDS) {
365 consumeError(MDS.takeError());
366 return;
367 }
368
369 DebugStream = llvm::make_unique<ModuleDebugStreamRef>(std::move(*MDS));
370 Records.initialize(MDS->subsections());
371 if (Records.hasChecksums()) {
372 for (const auto &Entry : Records.checksums()) {
373 auto S = Records.strings().getString(Entry.FileNameOffset);
374 if (!S)
375 continue;
376 ChecksumsByFile[*S] = Entry;
377 }
378 }
379 }
380
381 Expected<StringRef> getNameFromStringTable(uint32_t Offset) const {
382 return Records.strings().getString(Offset);
383 }
384
385 void formatFromFileName(LinePrinter &Printer, StringRef File,
386 bool Append = false) const {
387 auto FC = ChecksumsByFile.find(File);
388 if (FC == ChecksumsByFile.end()) {
389 formatInternal(Printer, Append, "- (no checksum) {0}", File);
390 return;
391 }
392
393 formatInternal(Printer, Append, "- ({0}: {1}) {2}",
394 formatChecksumKind(FC->getValue().Kind),
395 toHex(FC->getValue().Checksum), File);
396 }
397
398 void formatFromChecksumsOffset(LinePrinter &Printer, uint32_t Offset,
399 bool Append = false) const {
400 if (!Records.hasChecksums()) {
401 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
402 return;
403 }
404
405 auto Iter = Records.checksums().getArray().at(Offset);
406 if (Iter == Records.checksums().getArray().end()) {
407 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
408 return;
409 }
410
411 uint32_t FO = Iter->FileNameOffset;
412 auto ExpectedFile = getNameFromStringTable(FO);
413 if (!ExpectedFile) {
414 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
415 consumeError(ExpectedFile.takeError());
416 return;
417 }
418 if (Iter->Kind == FileChecksumKind::None) {
419 formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
420 } else {
421 formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
422 formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
423 }
424 }
425
426 std::unique_ptr<ModuleDebugStreamRef> DebugStream;
427 StringsAndChecksumsRef Records;
428 StringMap<FileChecksumEntry> ChecksumsByFile;
429};
430} // namespace
431
Zachary Turnerf2872b92017-06-15 23:59:56 +0000432template <typename CallbackT>
Zachary Turner58699362017-08-03 23:11:52 +0000433static void iterateOneModule(PDBFile &File, LinePrinter &P,
434 const DbiModuleDescriptor &Descriptor,
435 uint32_t Modi, uint32_t IndentLevel,
436 uint32_t Digits, CallbackT Callback) {
437 P.formatLine(
438 "Mod {0:4} | `{1}`: ", fmt_align(Modi, AlignStyle::Right, Digits),
439 Descriptor.getModuleName());
440
441 StringsAndChecksumsPrinter Strings(File, Modi);
442 AutoIndent Indent2(P, IndentLevel);
443 Callback(Modi, Strings);
444}
445
446template <typename CallbackT>
Zachary Turnerf2872b92017-06-15 23:59:56 +0000447static void iterateModules(PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
448 CallbackT Callback) {
449 AutoIndent Indent(P);
450 if (!File.hasPDBDbiStream()) {
451 P.formatLine("DBI Stream not present");
452 return;
453 }
454
Reid Klecknerdd853e52017-07-27 23:13:18 +0000455 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turnerf2872b92017-06-15 23:59:56 +0000456
457 auto &Stream = Err(File.getPDBDbiStream());
458
459 const DbiModuleList &Modules = Stream.modules();
Zachary Turner58699362017-08-03 23:11:52 +0000460
461 if (opts::dump::DumpModi.getNumOccurrences() > 0) {
462 assert(opts::dump::DumpModi.getNumOccurrences() == 1);
463 uint32_t Modi = opts::dump::DumpModi;
464 auto Descriptor = Modules.getModuleDescriptor(Modi);
465 iterateOneModule(File, P, Descriptor, Modi, IndentLevel, NumDigits(Modi),
466 Callback);
467 return;
468 }
469
Zachary Turnerf2872b92017-06-15 23:59:56 +0000470 uint32_t Count = Modules.getModuleCount();
471 uint32_t Digits = NumDigits(Count);
472 for (uint32_t I = 0; I < Count; ++I) {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000473 auto Desc = Modules.getModuleDescriptor(I);
474 if (!shouldDumpModule(I, Desc))
475 continue;
476 iterateOneModule(File, P, Desc, I, IndentLevel, Digits, Callback);
Zachary Turnerf2872b92017-06-15 23:59:56 +0000477 }
478}
479
480template <typename SubsectionT>
481static void iterateModuleSubsections(
482 PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
483 llvm::function_ref<void(uint32_t, StringsAndChecksumsPrinter &,
484 SubsectionT &)>
485 Callback) {
486
487 iterateModules(
488 File, P, IndentLevel,
489 [&File, &Callback](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
490 auto MDS = getModuleDebugStream(File, Modi);
491 if (!MDS) {
492 consumeError(MDS.takeError());
493 return;
494 }
495
496 for (const auto &SS : MDS->subsections()) {
497 SubsectionT Subsection;
498
499 if (SS.kind() != Subsection.kind())
500 continue;
501
502 BinaryStreamReader Reader(SS.getRecordData());
503 if (auto EC = Subsection.initialize(Reader))
504 continue;
505 Callback(Modi, Strings, Subsection);
506 }
507 });
508}
509
Zachary Turner7df69952017-06-22 20:57:39 +0000510Error DumpOutputStyle::dumpModules() {
Zachary Turner63055452017-06-15 22:24:24 +0000511 printHeader(P, "Modules");
512
513 AutoIndent Indent(P);
514 if (!File.hasPDBDbiStream()) {
515 P.formatLine("DBI Stream not present");
516 return Error::success();
517 }
518
Reid Klecknerdd853e52017-07-27 23:13:18 +0000519 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner63055452017-06-15 22:24:24 +0000520
521 auto &Stream = Err(File.getPDBDbiStream());
522
523 const DbiModuleList &Modules = Stream.modules();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000524 iterateModules(
525 File, P, 11, [&](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
526 auto Desc = Modules.getModuleDescriptor(Modi);
527 P.formatLine("Obj: `{0}`: ", Desc.getObjFileName());
528 P.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
529 Desc.getModuleStreamIndex(), Desc.getNumberOfFiles(),
530 Desc.hasECInfo());
531 StringRef PdbFilePath =
532 Err(Stream.getECName(Desc.getPdbFilePathNameIndex()));
533 StringRef SrcFilePath =
534 Err(Stream.getECName(Desc.getSourceFileNameIndex()));
535 P.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
536 Desc.getPdbFilePathNameIndex(), PdbFilePath,
537 Desc.getSourceFileNameIndex(), SrcFilePath);
538 });
Zachary Turner0e327d02017-06-15 23:12:41 +0000539 return Error::success();
540}
541
Zachary Turner7df69952017-06-22 20:57:39 +0000542Error DumpOutputStyle::dumpModuleFiles() {
Zachary Turner0e327d02017-06-15 23:12:41 +0000543 printHeader(P, "Files");
544
Reid Klecknerdd853e52017-07-27 23:13:18 +0000545 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000546
Zachary Turnerf2872b92017-06-15 23:59:56 +0000547 iterateModules(
548 File, P, 11,
549 [this, &Err](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
550 auto &Stream = Err(File.getPDBDbiStream());
Zachary Turner0e327d02017-06-15 23:12:41 +0000551
Zachary Turnerf2872b92017-06-15 23:59:56 +0000552 const DbiModuleList &Modules = Stream.modules();
553 for (const auto &F : Modules.source_files(Modi)) {
554 Strings.formatFromFileName(P, F);
555 }
556 });
Zachary Turner4e950642017-06-15 23:56:19 +0000557 return Error::success();
558}
559
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000560Error DumpOutputStyle::dumpModuleStats() {
561 printHeader(P, "Module Stats");
562
563 ExitOnError Err("Unexpected error processing modules: ");
564
565 StatCollection SymStats;
566 StatCollection ChunkStats;
567 auto &Stream = Err(File.getPDBDbiStream());
568
569 const DbiModuleList &Modules = Stream.modules();
570 uint32_t ModCount = Modules.getModuleCount();
571
572 iterateModules(File, P, 0, [&](uint32_t Modi,
573 StringsAndChecksumsPrinter &Strings) {
574 DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
575 uint32_t StreamIdx = Desc.getModuleStreamIndex();
576
577 if (StreamIdx == kInvalidStreamIndex) {
578 P.formatLine("Mod {0} (debug info not present): [{1}]",
579 fmt_align(Modi, AlignStyle::Right, NumDigits(ModCount)),
580 Desc.getModuleName());
581 return;
582 }
583
584 P.formatLine("Stream {0}, {1} bytes", StreamIdx,
585 File.getStreamByteSize(StreamIdx));
586
587 ModuleDebugStreamRef MDS(Desc, File.createIndexedStream(StreamIdx));
588 if (auto EC = MDS.reload()) {
589 P.printLine("- Error parsing debug info stream");
590 consumeError(std::move(EC));
591 return;
592 }
593
594 printModuleDetailStats<SymbolKind>(P, "Symbols",
595 getSymbolStats(MDS, SymStats));
596 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks",
597 getChunkStats(MDS, ChunkStats));
598 });
599
600 P.printLine(" Summary |");
601 AutoIndent Indent(P, 4);
602 if (SymStats.Totals.Count > 0) {
603 printModuleDetailStats<SymbolKind>(P, "Symbols", SymStats);
604 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", ChunkStats);
605 }
606
607 return Error::success();
608}
609
Zachary Turner4e950642017-06-15 23:56:19 +0000610static void typesetLinesAndColumns(PDBFile &File, LinePrinter &P,
611 uint32_t Start, const LineColumnEntry &E) {
612 const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
613 uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
614
615 // Let's try to keep it under 100 characters
616 constexpr uint32_t kMaxRowLength = 100;
617 // At least 3 spaces between columns.
618 uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
619 uint32_t ItemsLeft = E.LineNumbers.size();
620 auto LineIter = E.LineNumbers.begin();
621 while (ItemsLeft != 0) {
622 uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
623 for (uint32_t I = 0; I < RowColumns; ++I) {
624 LineInfo Line(LineIter->Flags);
625 std::string LineStr;
626 if (Line.isAlwaysStepInto())
627 LineStr = "ASI";
628 else if (Line.isNeverStepInto())
629 LineStr = "NSI";
Zachary Turner0e327d02017-06-15 23:12:41 +0000630 else
Zachary Turner4e950642017-06-15 23:56:19 +0000631 LineStr = utostr(Line.getStartLine());
632 char Statement = Line.isStatement() ? ' ' : '!';
633 P.format("{0} {1:X-} {2} ",
634 fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
635 fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
636 Statement);
637 ++LineIter;
638 --ItemsLeft;
Zachary Turner63055452017-06-15 22:24:24 +0000639 }
Zachary Turner4e950642017-06-15 23:56:19 +0000640 P.NewLine();
Zachary Turner63055452017-06-15 22:24:24 +0000641 }
Zachary Turner4e950642017-06-15 23:56:19 +0000642}
643
Zachary Turner7df69952017-06-22 20:57:39 +0000644Error DumpOutputStyle::dumpLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000645 printHeader(P, "Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000646
Zachary Turnerf2872b92017-06-15 23:59:56 +0000647 uint32_t LastModi = UINT32_MAX;
648 uint32_t LastNameIndex = UINT32_MAX;
649 iterateModuleSubsections<DebugLinesSubsectionRef>(
650 File, P, 4,
651 [this, &LastModi, &LastNameIndex](uint32_t Modi,
652 StringsAndChecksumsPrinter &Strings,
653 DebugLinesSubsectionRef &Lines) {
654 uint16_t Segment = Lines.header()->RelocSegment;
655 uint32_t Begin = Lines.header()->RelocOffset;
656 uint32_t End = Begin + Lines.header()->CodeSize;
657 for (const auto &Block : Lines) {
658 if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
659 LastModi = Modi;
660 LastNameIndex = Block.NameIndex;
661 Strings.formatFromChecksumsOffset(P, Block.NameIndex);
Zachary Turner4e950642017-06-15 23:56:19 +0000662 }
663
Zachary Turnerf2872b92017-06-15 23:59:56 +0000664 AutoIndent Indent(P, 2);
665 P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
666 uint32_t Count = Block.LineNumbers.size();
667 if (Lines.hasColumnInfo())
668 P.format("line/column/addr entries = {0}", Count);
669 else
670 P.format("line/addr entries = {0}", Count);
Zachary Turner4e950642017-06-15 23:56:19 +0000671
Zachary Turnerf2872b92017-06-15 23:59:56 +0000672 P.NewLine();
673 typesetLinesAndColumns(File, P, Begin, Block);
Zachary Turner4e950642017-06-15 23:56:19 +0000674 }
675 });
676
677 return Error::success();
678}
679
Zachary Turner7df69952017-06-22 20:57:39 +0000680Error DumpOutputStyle::dumpInlineeLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000681 printHeader(P, "Inlinee Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000682
Zachary Turnerf2872b92017-06-15 23:59:56 +0000683 iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
684 File, P, 2,
685 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
686 DebugInlineeLinesSubsectionRef &Lines) {
687 P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
688 for (const auto &Entry : Lines) {
689 P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
690 fmtle(Entry.Header->SourceLineNum));
691 Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
Zachary Turner4e950642017-06-15 23:56:19 +0000692 }
Zachary Turnerf2872b92017-06-15 23:59:56 +0000693 P.NewLine();
Zachary Turner4e950642017-06-15 23:56:19 +0000694 });
695
Zachary Turner63055452017-06-15 22:24:24 +0000696 return Error::success();
697}
Zachary Turner0e327d02017-06-15 23:12:41 +0000698
Zachary Turner7df69952017-06-22 20:57:39 +0000699Error DumpOutputStyle::dumpXmi() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000700 printHeader(P, "Cross Module Imports");
701 iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
702 File, P, 2,
703 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
704 DebugCrossModuleImportsSubsectionRef &Imports) {
705 P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
706
707 for (const auto &Xmi : Imports) {
708 auto ExpectedModule =
709 Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
710 StringRef Module;
711 SmallString<32> ModuleStorage;
712 if (!ExpectedModule) {
713 Module = "(unknown module)";
714 consumeError(ExpectedModule.takeError());
715 } else
716 Module = *ExpectedModule;
717 if (Module.size() > 32) {
718 ModuleStorage = "...";
719 ModuleStorage += Module.take_back(32 - 3);
720 Module = ModuleStorage;
721 }
722 std::vector<std::string> TIs;
723 for (const auto I : Xmi.Imports)
724 TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
725 std::string Result =
726 typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
727 P.formatLine("{0,+32} | {1}", Module, Result);
728 }
729 });
730
731 return Error::success();
732}
733
Zachary Turner7df69952017-06-22 20:57:39 +0000734Error DumpOutputStyle::dumpXme() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000735 printHeader(P, "Cross Module Exports");
736
737 iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
738 File, P, 2,
739 [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
740 DebugCrossModuleExportsSubsectionRef &Exports) {
741 P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
742 for (const auto &Export : Exports) {
743 P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
744 TypeIndex(Export.Global));
745 }
746 });
747
748 return Error::success();
749}
750
Zachary Turner7df69952017-06-22 20:57:39 +0000751Error DumpOutputStyle::dumpStringTable() {
Zachary Turner63055452017-06-15 22:24:24 +0000752 printHeader(P, "String Table");
753
754 AutoIndent Indent(P);
755 auto IS = File.getStringTable();
756 if (!IS) {
757 P.formatLine("Not present in file");
758 consumeError(IS.takeError());
759 return Error::success();
760 }
761
762 if (IS->name_ids().empty()) {
763 P.formatLine("Empty");
764 return Error::success();
765 }
766
767 auto MaxID = std::max_element(IS->name_ids().begin(), IS->name_ids().end());
768 uint32_t Digits = NumDigits(*MaxID);
769
770 P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
771 "String");
772
773 std::vector<uint32_t> SortedIDs(IS->name_ids().begin(), IS->name_ids().end());
774 std::sort(SortedIDs.begin(), SortedIDs.end());
775 for (uint32_t I : SortedIDs) {
776 auto ES = IS->getStringForID(I);
777 llvm::SmallString<32> Str;
778 if (!ES) {
779 consumeError(ES.takeError());
780 Str = "Error reading string";
781 } else if (!ES->empty()) {
782 Str.append("'");
783 Str.append(*ES);
784 Str.append("'");
785 }
786
787 if (!Str.empty())
788 P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits), Str);
789 }
790 return Error::success();
791}
792
Zachary Turner02a26772017-06-30 18:15:47 +0000793static void buildDepSet(LazyRandomTypeCollection &Types,
794 ArrayRef<TypeIndex> Indices,
795 std::map<TypeIndex, CVType> &DepSet) {
796 SmallVector<TypeIndex, 4> DepList;
797 for (const auto &I : Indices) {
798 TypeIndex TI(I);
799 if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
800 continue;
801
802 CVType Type = Types.getType(TI);
803 DepSet[TI] = Type;
804 codeview::discoverTypeIndices(Type, DepList);
805 buildDepSet(Types, DepList, DepSet);
806 }
807}
808
809static void dumpFullTypeStream(LinePrinter &Printer,
810 LazyRandomTypeCollection &Types,
811 TpiStream &Stream, bool Bytes, bool Extras) {
812 Printer.formatLine("Showing {0:N} records", Stream.getNumTypeRecords());
813 uint32_t Width =
814 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
815
816 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Reid Klecknerc50349d2017-07-18 00:33:45 +0000817 Stream.getNumHashBuckets(), Stream.getHashValues());
Zachary Turner02a26772017-06-30 18:15:47 +0000818
819 if (auto EC = codeview::visitTypeStream(Types, V)) {
820 Printer.formatLine("An error occurred dumping type records: {0}",
821 toString(std::move(EC)));
822 }
823}
824
825static void dumpPartialTypeStream(LinePrinter &Printer,
826 LazyRandomTypeCollection &Types,
827 TpiStream &Stream, ArrayRef<TypeIndex> TiList,
828 bool Bytes, bool Extras, bool Deps) {
829 uint32_t Width =
830 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
831
832 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Reid Klecknerc50349d2017-07-18 00:33:45 +0000833 Stream.getNumHashBuckets(), Stream.getHashValues());
Zachary Turner02a26772017-06-30 18:15:47 +0000834
835 if (opts::dump::DumpTypeDependents) {
836 // If we need to dump all dependents, then iterate each index and find
837 // all dependents, adding them to a map ordered by TypeIndex.
838 std::map<TypeIndex, CVType> DepSet;
839 buildDepSet(Types, TiList, DepSet);
840
841 Printer.formatLine(
842 "Showing {0:N} records and their dependents ({1:N} records total)",
843 TiList.size(), DepSet.size());
844
845 for (auto &Dep : DepSet) {
846 if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
847 Printer.formatLine("An error occurred dumping type record {0}: {1}",
848 Dep.first, toString(std::move(EC)));
849 }
850 } else {
851 Printer.formatLine("Showing {0:N} records.", TiList.size());
852
853 for (const auto &I : TiList) {
854 TypeIndex TI(I);
855 CVType Type = Types.getType(TI);
856 if (auto EC = codeview::visitTypeRecord(Type, TI, V))
857 Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
858 toString(std::move(EC)));
859 }
860 }
861}
862
Zachary Turner7df69952017-06-22 20:57:39 +0000863Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
Zachary Turner63055452017-06-15 22:24:24 +0000864 assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
865
866 bool Present = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +0000867 bool DumpTypes = false;
Zachary Turner63055452017-06-15 22:24:24 +0000868 bool DumpBytes = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +0000869 bool DumpExtras = false;
Zachary Turner59224cb2017-06-16 23:42:15 +0000870 std::vector<uint32_t> Indices;
Zachary Turner63055452017-06-15 22:24:24 +0000871 if (StreamIdx == StreamTPI) {
872 printHeader(P, "Types (TPI Stream)");
873 Present = File.hasPDBTpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +0000874 DumpTypes = opts::dump::DumpTypes;
875 DumpBytes = opts::dump::DumpTypeData;
876 DumpExtras = opts::dump::DumpTypeExtras;
877 Indices.assign(opts::dump::DumpTypeIndex.begin(),
878 opts::dump::DumpTypeIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +0000879 } else if (StreamIdx == StreamIPI) {
880 printHeader(P, "Types (IPI Stream)");
881 Present = File.hasPDBIpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +0000882 DumpTypes = opts::dump::DumpIds;
883 DumpBytes = opts::dump::DumpIdData;
884 DumpExtras = opts::dump::DumpIdExtras;
885 Indices.assign(opts::dump::DumpIdIndex.begin(),
886 opts::dump::DumpIdIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +0000887 }
888
889 AutoIndent Indent(P);
890 if (!Present) {
891 P.formatLine("Stream not present");
892 return Error::success();
893 }
894
Reid Klecknerdd853e52017-07-27 23:13:18 +0000895 ExitOnError Err("Unexpected error processing types: ");
Zachary Turner63055452017-06-15 22:24:24 +0000896
897 auto &Stream = Err((StreamIdx == StreamTPI) ? File.getPDBTpiStream()
898 : File.getPDBIpiStream());
899
Zachary Turner59224cb2017-06-16 23:42:15 +0000900 auto &Types = Err(initializeTypes(StreamIdx));
Zachary Turner63055452017-06-15 22:24:24 +0000901
Zachary Turner02a26772017-06-30 18:15:47 +0000902 if (DumpTypes || !Indices.empty()) {
903 if (Indices.empty())
904 dumpFullTypeStream(P, Types, Stream, DumpBytes, DumpExtras);
905 else {
906 std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
907 dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
908 opts::dump::DumpTypeDependents);
Zachary Turnerf8a2e042017-06-15 23:04:42 +0000909 }
910 }
911
912 if (DumpExtras) {
913 P.NewLine();
914 auto IndexOffsets = Stream.getTypeIndexOffsets();
915 P.formatLine("Type Index Offsets:");
916 for (const auto &IO : IndexOffsets) {
917 AutoIndent Indent2(P);
918 P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
919 }
920
921 P.NewLine();
922 P.formatLine("Hash Adjusters:");
923 auto &Adjusters = Stream.getHashAdjusters();
924 auto &Strings = Err(File.getStringTable());
925 for (const auto &A : Adjusters) {
926 AutoIndent Indent2(P);
927 auto ExpectedStr = Strings.getStringForID(A.first);
928 TypeIndex TI(A.second);
929 if (ExpectedStr)
930 P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
931 else {
932 P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
933 consumeError(ExpectedStr.takeError());
934 }
935 }
Zachary Turner63055452017-06-15 22:24:24 +0000936 }
937 return Error::success();
938}
939
940Expected<codeview::LazyRandomTypeCollection &>
Zachary Turner7df69952017-06-22 20:57:39 +0000941DumpOutputStyle::initializeTypes(uint32_t SN) {
Zachary Turner63055452017-06-15 22:24:24 +0000942 auto &TypeCollection = (SN == StreamTPI) ? TpiTypes : IpiTypes;
943 auto Tpi =
944 (SN == StreamTPI) ? File.getPDBTpiStream() : File.getPDBIpiStream();
945 if (!Tpi)
946 return Tpi.takeError();
947
948 if (!TypeCollection) {
949 auto &Types = Tpi->typeArray();
950 uint32_t Count = Tpi->getNumTypeRecords();
951 auto Offsets = Tpi->getTypeIndexOffsets();
952 TypeCollection =
953 llvm::make_unique<LazyRandomTypeCollection>(Types, Count, Offsets);
954 }
955
956 return *TypeCollection;
957}
958
Zachary Turner7df69952017-06-22 20:57:39 +0000959Error DumpOutputStyle::dumpModuleSyms() {
Zachary Turner63055452017-06-15 22:24:24 +0000960 printHeader(P, "Symbols");
961
962 AutoIndent Indent(P);
963 if (!File.hasPDBDbiStream()) {
964 P.formatLine("DBI Stream not present");
965 return Error::success();
966 }
967
Reid Klecknerdd853e52017-07-27 23:13:18 +0000968 ExitOnError Err("Unexpected error processing symbols: ");
Zachary Turner63055452017-06-15 22:24:24 +0000969
Zachary Turner59e3ae82017-08-08 18:34:44 +0000970 auto &Ids = Err(initializeTypes(StreamIPI));
Zachary Turner59224cb2017-06-16 23:42:15 +0000971 auto &Types = Err(initializeTypes(StreamTPI));
Zachary Turner63055452017-06-15 22:24:24 +0000972
Zachary Turner58699362017-08-03 23:11:52 +0000973 iterateModules(
974 File, P, 2, [&](uint32_t I, StringsAndChecksumsPrinter &Strings) {
975 auto ExpectedModS = getModuleDebugStream(File, I);
976 if (!ExpectedModS) {
977 P.formatLine("Error loading module stream {0}. {1}", I,
978 toString(ExpectedModS.takeError()));
979 return;
980 }
Zachary Turner63055452017-06-15 22:24:24 +0000981
Zachary Turner58699362017-08-03 23:11:52 +0000982 ModuleDebugStreamRef &ModS = *ExpectedModS;
Zachary Turner63055452017-06-15 22:24:24 +0000983
Zachary Turner58699362017-08-03 23:11:52 +0000984 SymbolVisitorCallbackPipeline Pipeline;
985 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000986 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids,
987 Types);
Zachary Turner63055452017-06-15 22:24:24 +0000988
Zachary Turner58699362017-08-03 23:11:52 +0000989 Pipeline.addCallbackToPipeline(Deserializer);
990 Pipeline.addCallbackToPipeline(Dumper);
991 CVSymbolVisitor Visitor(Pipeline);
992 auto SS = ModS.getSymbolsSubstream();
993 if (auto EC =
994 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
995 P.formatLine("Error while processing symbol records. {0}",
996 toString(std::move(EC)));
997 return;
998 }
999 });
Zachary Turner63055452017-06-15 22:24:24 +00001000 return Error::success();
1001}
1002
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001003Error DumpOutputStyle::dumpGlobals() {
1004 printHeader(P, "Global Symbols");
1005 AutoIndent Indent(P);
1006 if (!File.hasPDBGlobalsStream()) {
1007 P.formatLine("Globals stream not present");
1008 return Error::success();
1009 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001010 ExitOnError Err("Error dumping globals stream: ");
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001011 auto &Globals = Err(File.getPDBGlobalsStream());
1012
1013 const GSIHashTable &Table = Globals.getGlobalsTable();
1014 Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
1015 return Error::success();
1016}
1017
Zachary Turner7df69952017-06-22 20:57:39 +00001018Error DumpOutputStyle::dumpPublics() {
Zachary Turner63055452017-06-15 22:24:24 +00001019 printHeader(P, "Public Symbols");
Zachary Turner63055452017-06-15 22:24:24 +00001020 AutoIndent Indent(P);
1021 if (!File.hasPDBPublicsStream()) {
1022 P.formatLine("Publics stream not present");
1023 return Error::success();
1024 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001025 ExitOnError Err("Error dumping publics stream: ");
Zachary Turner63055452017-06-15 22:24:24 +00001026 auto &Publics = Err(File.getPDBPublicsStream());
Zachary Turner63055452017-06-15 22:24:24 +00001027
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001028 const GSIHashTable &PublicsTable = Publics.getPublicsTable();
Zachary Turner5448dab2017-08-09 04:23:59 +00001029 if (opts::dump::DumpPublicExtras) {
1030 P.printLine("Publics Header");
1031 AutoIndent Indent(P);
1032 P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
1033 formatSegmentOffset(Publics.getThunkTableSection(),
1034 Publics.getThunkTableOffset()));
1035 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001036 Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
Zachary Turneraf8c75a2017-06-30 21:35:00 +00001037
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001038 // Skip the rest if we aren't dumping extras.
Reid Kleckner686f1212017-07-21 18:28:55 +00001039 if (!opts::dump::DumpPublicExtras)
1040 return Error::success();
1041
Reid Kleckner686f1212017-07-21 18:28:55 +00001042 P.formatLine("Address Map");
1043 {
1044 // These are offsets into the publics stream sorted by secidx:secrel.
1045 AutoIndent Indent2(P);
1046 for (uint32_t Addr : Publics.getAddressMap())
1047 P.formatLine("off = {0}", Addr);
1048 }
1049
1050 // The thunk map is optional debug info used for ILT thunks.
1051 if (!Publics.getThunkMap().empty()) {
1052 P.formatLine("Thunk Map");
1053 AutoIndent Indent2(P);
1054 for (uint32_t Addr : Publics.getThunkMap())
1055 P.formatLine("{0:x8}", Addr);
1056 }
1057
1058 // The section offsets table appears to be empty when incremental linking
1059 // isn't in use.
1060 if (!Publics.getSectionOffsets().empty()) {
1061 P.formatLine("Section Offsets");
1062 AutoIndent Indent2(P);
1063 for (const SectionOffset &SO : Publics.getSectionOffsets())
1064 P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
1065 }
1066
Zachary Turner63055452017-06-15 22:24:24 +00001067 return Error::success();
1068}
1069
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001070Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1071 bool HashExtras) {
1072 auto ExpectedSyms = File.getPDBSymbolStream();
1073 if (!ExpectedSyms)
1074 return ExpectedSyms.takeError();
1075 auto ExpectedTypes = initializeTypes(StreamTPI);
1076 if (!ExpectedTypes)
1077 return ExpectedTypes.takeError();
Zachary Turner59e3ae82017-08-08 18:34:44 +00001078 auto ExpectedIds = initializeTypes(StreamIPI);
1079 if (!ExpectedIds)
1080 return ExpectedIds.takeError();
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001081
Zachary Turner5448dab2017-08-09 04:23:59 +00001082 if (HashExtras) {
1083 P.printLine("GSI Header");
1084 AutoIndent Indent(P);
1085 P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1086 Table.getVerSignature(), Table.getVerHeader(),
1087 Table.getHashRecordSize(), Table.getNumBuckets());
1088 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001089
Zachary Turner5448dab2017-08-09 04:23:59 +00001090 {
1091 P.printLine("Records");
1092 SymbolVisitorCallbackPipeline Pipeline;
1093 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1094 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, *ExpectedIds,
1095 *ExpectedTypes);
1096
1097 Pipeline.addCallbackToPipeline(Deserializer);
1098 Pipeline.addCallbackToPipeline(Dumper);
1099 CVSymbolVisitor Visitor(Pipeline);
1100
1101 BinaryStreamRef SymStream =
1102 ExpectedSyms->getSymbolArray().getUnderlyingStream();
1103 for (uint32_t PubSymOff : Table) {
1104 Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
1105 if (!Sym)
1106 return Sym.takeError();
1107 if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
1108 return E;
1109 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001110 }
1111
1112 // Return early if we aren't dumping public hash table and address map info.
1113 if (!HashExtras)
1114 return Error::success();
1115
Zachary Turner5448dab2017-08-09 04:23:59 +00001116 P.formatLine("Hash Entries");
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001117 {
1118 AutoIndent Indent2(P);
1119 for (const PSHashRecord &HR : Table.HashRecords)
1120 P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
1121 uint32_t(HR.CRef));
1122 }
1123
1124 // FIXME: Dump the bitmap.
1125
1126 P.formatLine("Hash Buckets");
1127 {
1128 AutoIndent Indent2(P);
1129 for (uint32_t Hash : Table.HashBuckets)
1130 P.formatLine("{0:x8}", Hash);
1131 }
1132
1133 return Error::success();
1134}
1135
Zachary Turner63055452017-06-15 22:24:24 +00001136static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1137 OMFSegDescFlags Flags) {
1138 std::vector<std::string> Opts;
1139 if (Flags == OMFSegDescFlags::None)
1140 return "none";
1141
1142 PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1143 PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1144 PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1145 PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1146 PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1147 PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1148 PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
Zachary Turner47d9a562017-06-16 00:04:24 +00001149 return typesetItemList(Opts, IndentLevel, 4, " | ");
Zachary Turner63055452017-06-15 22:24:24 +00001150}
1151
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001152Error DumpOutputStyle::dumpSectionHeaders() {
1153 dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1154 dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1155 return Error::success();
1156}
1157
Zachary Turner92e584c2017-08-04 21:10:04 +00001158static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1159 ArrayRef<llvm::object::coff_section>>>
1160loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1161 if (!File.hasPDBDbiStream())
1162 return make_error<StringError>(
1163 "Section headers require a DBI Stream, which could not be loaded",
1164 inconvertibleErrorCode());
1165
1166 auto &Dbi = cantFail(File.getPDBDbiStream());
1167 uint32_t SI = Dbi.getDebugStreamIndex(Type);
1168
1169 if (SI == kInvalidStreamIndex)
1170 return make_error<StringError>(
1171 "PDB does not contain the requested image section header type",
1172 inconvertibleErrorCode());
1173
1174 auto Stream = MappedBlockStream::createIndexedStream(
1175 File.getMsfLayout(), File.getMsfBuffer(), SI, File.getAllocator());
1176 if (!Stream)
1177 return make_error<StringError>("Could not load the required stream data",
1178 inconvertibleErrorCode());
1179
1180 ArrayRef<object::coff_section> Headers;
1181 if (Stream->getLength() % sizeof(object::coff_section) != 0)
1182 return make_error<StringError>(
1183 "Section header array size is not a multiple of section header size",
1184 inconvertibleErrorCode());
1185
1186 uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1187 BinaryStreamReader Reader(*Stream);
1188 cantFail(Reader.readArray(Headers, NumHeaders));
1189 return std::make_pair(std::move(Stream), Headers);
1190}
1191
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001192void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1193 printHeader(P, Label);
1194 ExitOnError Err("Error dumping publics stream: ");
1195
1196 AutoIndent Indent(P);
Zachary Turner92e584c2017-08-04 21:10:04 +00001197 std::unique_ptr<MappedBlockStream> Stream;
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001198 ArrayRef<object::coff_section> Headers;
Zachary Turner92e584c2017-08-04 21:10:04 +00001199 auto ExpectedHeaders = loadSectionHeaders(File, Type);
1200 if (!ExpectedHeaders) {
1201 P.printLine(toString(ExpectedHeaders.takeError()));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001202 return;
1203 }
Zachary Turner92e584c2017-08-04 21:10:04 +00001204 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001205
1206 uint32_t I = 1;
1207 for (const auto &Header : Headers) {
1208 P.NewLine();
1209 P.formatLine("SECTION HEADER #{0}", I);
1210 P.formatLine("{0,8} name", Header.Name);
1211 P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1212 P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1213 P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1214 P.formatLine("{0,8:X-} file pointer to raw data",
1215 uint32_t(Header.PointerToRawData));
1216 P.formatLine("{0,8:X-} file pointer to relocation table",
1217 uint32_t(Header.PointerToRelocations));
1218 P.formatLine("{0,8:X-} file pointer to line numbers",
1219 uint32_t(Header.PointerToLinenumbers));
1220 P.formatLine("{0,8:X-} number of relocations",
1221 uint32_t(Header.NumberOfRelocations));
1222 P.formatLine("{0,8:X-} number of line numbers",
1223 uint32_t(Header.NumberOfLinenumbers));
1224 P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1225 AutoIndent IndentMore(P, 9);
1226 P.formatLine("{0}", formatSectionCharacteristics(
1227 P.getIndentLevel(), Header.Characteristics, 1, ""));
1228 ++I;
1229 }
1230 return;
1231}
1232
Zachary Turner92e584c2017-08-04 21:10:04 +00001233std::vector<std::string> getSectionNames(PDBFile &File) {
1234 auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1235 if (!ExpectedHeaders)
1236 return {};
1237
1238 std::unique_ptr<MappedBlockStream> Stream;
1239 ArrayRef<object::coff_section> Headers;
1240 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1241 std::vector<std::string> Names;
1242 for (const auto &H : Headers)
1243 Names.push_back(H.Name);
1244 return Names;
1245}
1246
Zachary Turner7df69952017-06-22 20:57:39 +00001247Error DumpOutputStyle::dumpSectionContribs() {
Zachary Turner63055452017-06-15 22:24:24 +00001248 printHeader(P, "Section Contributions");
Reid Klecknerdd853e52017-07-27 23:13:18 +00001249 ExitOnError Err("Error dumping publics stream: ");
Zachary Turner63055452017-06-15 22:24:24 +00001250
1251 AutoIndent Indent(P);
1252 if (!File.hasPDBDbiStream()) {
1253 P.formatLine(
1254 "Section contribs require a DBI Stream, which could not be loaded");
1255 return Error::success();
1256 }
1257
1258 auto &Dbi = Err(File.getPDBDbiStream());
1259
1260 class Visitor : public ISectionContribVisitor {
1261 public:
Zachary Turner92e584c2017-08-04 21:10:04 +00001262 Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1263 auto Max = std::max_element(
1264 Names.begin(), Names.end(),
1265 [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1266 MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1267 }
Zachary Turner63055452017-06-15 22:24:24 +00001268 void visit(const SectionContrib &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001269 assert(SC.ISect > 0);
Zachary Turner489a7a02017-08-07 20:24:01 +00001270 std::string NameInsert;
1271 if (SC.ISect < Names.size()) {
1272 StringRef SectionName = Names[SC.ISect - 1];
1273 NameInsert = formatv("[{0}]", SectionName).str();
1274 } else
1275 NameInsert = "[???]";
Zachary Turner92e584c2017-08-04 21:10:04 +00001276 P.formatLine("SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1277 "crc = {4}",
1278 formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1279 fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1280 fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1281 AutoIndent Indent(P, MaxNameLen + 2);
Zachary Turner63055452017-06-15 22:24:24 +00001282 P.formatLine(" {0}",
1283 formatSectionCharacteristics(P.getIndentLevel() + 6,
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001284 SC.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001285 }
1286 void visit(const SectionContrib2 &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001287 P.formatLine(
1288 "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1289 "crc = {4}, coff section = {5}",
1290 formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1291 fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1292 fmtle(SC.ISectCoff));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001293 P.formatLine(" {0}", formatSectionCharacteristics(
1294 P.getIndentLevel() + 6,
1295 SC.Base.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001296 }
1297
1298 private:
1299 LinePrinter &P;
Zachary Turner92e584c2017-08-04 21:10:04 +00001300 uint32_t MaxNameLen;
1301 ArrayRef<std::string> Names;
Zachary Turner63055452017-06-15 22:24:24 +00001302 };
1303
Zachary Turner92e584c2017-08-04 21:10:04 +00001304 std::vector<std::string> Names = getSectionNames(File);
1305 Visitor V(P, makeArrayRef(Names));
Zachary Turner63055452017-06-15 22:24:24 +00001306 Dbi.visitSectionContributions(V);
1307 return Error::success();
1308}
1309
Zachary Turner7df69952017-06-22 20:57:39 +00001310Error DumpOutputStyle::dumpSectionMap() {
Zachary Turner63055452017-06-15 22:24:24 +00001311 printHeader(P, "Section Map");
Reid Klecknerdd853e52017-07-27 23:13:18 +00001312 ExitOnError Err("Error dumping section map: ");
Zachary Turner63055452017-06-15 22:24:24 +00001313
1314 AutoIndent Indent(P);
1315 if (!File.hasPDBDbiStream()) {
1316 P.formatLine("Dumping the section map requires a DBI Stream, which could "
1317 "not be loaded");
1318 return Error::success();
1319 }
1320
1321 auto &Dbi = Err(File.getPDBDbiStream());
1322
1323 uint32_t I = 0;
1324 for (auto &M : Dbi.getSectionMap()) {
1325 P.formatLine(
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001326 "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
Zachary Turner63055452017-06-15 22:24:24 +00001327 fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1328 P.formatLine(" class = {0}, offset = {1}, size = {2}",
1329 fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1330 P.formatLine(" flags = {0}",
1331 formatSegMapDescriptorFlag(
1332 P.getIndentLevel() + 13,
1333 static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1334 ++I;
1335 }
1336 return Error::success();
1337}