OSDN Git Service

[llvm-pdbutil] Print detailed S_UDT stats.
[android-x86/external-llvm.git] / tools / llvm-pdbutil / DumpOutputStyle.cpp
1 //===- DumpOutputStyle.cpp ------------------------------------ *- C++ --*-===//
2 //
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
10 #include "DumpOutputStyle.h"
11
12 #include "FormatUtil.h"
13 #include "MinimalSymbolDumper.h"
14 #include "MinimalTypeDumper.h"
15 #include "StreamUtil.h"
16 #include "llvm-pdbutil.h"
17
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h"
20 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
21 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
22 #include "llvm/DebugInfo/CodeView/DebugCrossExSubsection.h"
23 #include "llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h"
24 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
25 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h"
29 #include "llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h"
30 #include "llvm/DebugInfo/CodeView/DebugUnknownSubsection.h"
31 #include "llvm/DebugInfo/CodeView/EnumTables.h"
32 #include "llvm/DebugInfo/CodeView/Formatters.h"
33 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
34 #include "llvm/DebugInfo/CodeView/Line.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
36 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
37 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h"
38 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
39 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
40 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
41 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
42 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
43 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h"
44 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
45 #include "llvm/DebugInfo/PDB/Native/EnumTables.h"
46 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
47 #include "llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h"
48 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
49 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
50 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
51 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
52 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
53 #include "llvm/DebugInfo/PDB/Native/RawError.h"
54 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
55 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
56 #include "llvm/DebugInfo/PDB/PDBExtras.h"
57 #include "llvm/Object/COFF.h"
58 #include "llvm/Support/BinaryStreamReader.h"
59 #include "llvm/Support/FormatAdapters.h"
60 #include "llvm/Support/FormatVariadic.h"
61
62 #include <cctype>
63 #include <unordered_map>
64
65 using namespace llvm;
66 using namespace llvm::codeview;
67 using namespace llvm::msf;
68 using namespace llvm::pdb;
69
70 DumpOutputStyle::DumpOutputStyle(PDBFile &File)
71     : File(File), P(2, false, outs()) {}
72
73 Error DumpOutputStyle::dump() {
74   if (opts::dump::DumpSummary) {
75     if (auto EC = dumpFileSummary())
76       return EC;
77     P.NewLine();
78   }
79
80   if (opts::dump::DumpStreams) {
81     if (auto EC = dumpStreamSummary())
82       return EC;
83     P.NewLine();
84   }
85
86   if (opts::dump::DumpSymbolStats.getNumOccurrences() > 0) {
87     if (auto EC = dumpSymbolStats())
88       return EC;
89     P.NewLine();
90   }
91
92   if (opts::dump::DumpUdtStats.getNumOccurrences() > 0) {
93     if (auto EC = dumpUdtStats())
94       return EC;
95     P.NewLine();
96   }
97
98   if (opts::dump::DumpStringTable) {
99     if (auto EC = dumpStringTable())
100       return EC;
101     P.NewLine();
102   }
103
104   if (opts::dump::DumpModules) {
105     if (auto EC = dumpModules())
106       return EC;
107   }
108
109   if (opts::dump::DumpModuleFiles) {
110     if (auto EC = dumpModuleFiles())
111       return EC;
112   }
113
114   if (opts::dump::DumpLines) {
115     if (auto EC = dumpLines())
116       return EC;
117   }
118
119   if (opts::dump::DumpInlineeLines) {
120     if (auto EC = dumpInlineeLines())
121       return EC;
122   }
123
124   if (opts::dump::DumpXmi) {
125     if (auto EC = dumpXmi())
126       return EC;
127   }
128
129   if (opts::dump::DumpXme) {
130     if (auto EC = dumpXme())
131       return EC;
132   }
133
134   if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
135       opts::dump::DumpTypeExtras) {
136     if (auto EC = dumpTpiStream(StreamTPI))
137       return EC;
138   }
139
140   if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
141       opts::dump::DumpIdExtras) {
142     if (auto EC = dumpTpiStream(StreamIPI))
143       return EC;
144   }
145
146   if (opts::dump::DumpGlobals) {
147     if (auto EC = dumpGlobals())
148       return EC;
149   }
150
151   if (opts::dump::DumpPublics) {
152     if (auto EC = dumpPublics())
153       return EC;
154   }
155
156   if (opts::dump::DumpSymbols) {
157     if (auto EC = dumpModuleSyms())
158       return EC;
159   }
160
161   if (opts::dump::DumpSectionHeaders) {
162     if (auto EC = dumpSectionHeaders())
163       return EC;
164   }
165
166   if (opts::dump::DumpSectionContribs) {
167     if (auto EC = dumpSectionContribs())
168       return EC;
169   }
170
171   if (opts::dump::DumpSectionMap) {
172     if (auto EC = dumpSectionMap())
173       return EC;
174   }
175
176   return Error::success();
177 }
178
179 static void printHeader(LinePrinter &P, const Twine &S) {
180   P.NewLine();
181   P.formatLine("{0,=60}", S);
182   P.formatLine("{0}", fmt_repeat('=', 60));
183 }
184
185 Error DumpOutputStyle::dumpFileSummary() {
186   printHeader(P, "Summary");
187
188   ExitOnError Err("Invalid PDB Format: ");
189
190   AutoIndent Indent(P);
191   P.formatLine("Block Size: {0}", File.getBlockSize());
192   P.formatLine("Number of blocks: {0}", File.getBlockCount());
193   P.formatLine("Number of streams: {0}", File.getNumStreams());
194
195   auto &PS = Err(File.getPDBInfoStream());
196   P.formatLine("Signature: {0}", PS.getSignature());
197   P.formatLine("Age: {0}", PS.getAge());
198   P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
199   P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
200   P.formatLine("Has Debug Info: {0}", File.hasPDBDbiStream());
201   P.formatLine("Has Types: {0}", File.hasPDBTpiStream());
202   P.formatLine("Has IDs: {0}", File.hasPDBIpiStream());
203   P.formatLine("Has Globals: {0}", File.hasPDBGlobalsStream());
204   P.formatLine("Has Publics: {0}", File.hasPDBPublicsStream());
205   if (File.hasPDBDbiStream()) {
206     auto &DBI = Err(File.getPDBDbiStream());
207     P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
208     P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
209     P.formatLine("Is stripped: {0}", DBI.isStripped());
210   }
211
212   return Error::success();
213 }
214
215 static StatCollection getSymbolStats(ModuleDebugStreamRef MDS,
216                                      StatCollection &CumulativeStats) {
217   StatCollection Stats;
218   for (const auto &S : MDS.symbols(nullptr)) {
219     Stats.update(S.kind(), S.length());
220     CumulativeStats.update(S.kind(), S.length());
221   }
222   return Stats;
223 }
224
225 static StatCollection getChunkStats(ModuleDebugStreamRef MDS,
226                                     StatCollection &CumulativeStats) {
227   StatCollection Stats;
228   for (const auto &Chunk : MDS.subsections()) {
229     Stats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
230     CumulativeStats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
231   }
232   return Stats;
233 }
234
235 static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
236   return formatChunkKind(K, false);
237 }
238
239 static inline std::string formatModuleDetailKind(SymbolKind K) {
240   return formatSymbolKind(K);
241 }
242
243 template <typename Kind>
244 static void printModuleDetailStats(LinePrinter &P, StringRef Label,
245                                    const StatCollection &Stats) {
246   P.NewLine();
247   P.formatLine("  {0}", Label);
248   AutoIndent Indent(P);
249   P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
250                Stats.Totals.Count, Stats.Totals.Size);
251   P.formatLine("{0}", fmt_repeat('-', 74));
252   for (const auto &K : Stats.Individual) {
253     std::string KindName = formatModuleDetailKind(Kind(K.first));
254     P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName,
255                  K.second.Count, K.second.Size);
256   }
257 }
258
259 static bool isMyCode(const DbiModuleDescriptor &Desc) {
260   StringRef Name = Desc.getModuleName();
261   if (Name.startswith("Import:"))
262     return false;
263   if (Name.endswith_lower(".dll"))
264     return false;
265   if (Name.equals_lower("* linker *"))
266     return false;
267   if (Name.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
268     return false;
269   if (Name.startswith_lower("f:\\dd\\vctools\\crt"))
270     return false;
271   return true;
272 }
273
274 static bool shouldDumpModule(uint32_t Modi, const DbiModuleDescriptor &Desc) {
275   if (opts::dump::JustMyCode && !isMyCode(Desc))
276     return false;
277
278   // If the arg was not specified on the command line, always dump all modules.
279   if (opts::dump::DumpModi.getNumOccurrences() == 0)
280     return true;
281
282   // Otherwise, only dump if this is the same module specified.
283   return (opts::dump::DumpModi == Modi);
284 }
285
286 Error DumpOutputStyle::dumpStreamSummary() {
287   printHeader(P, "Streams");
288
289   if (StreamPurposes.empty())
290     discoverStreamPurposes(File, StreamPurposes);
291
292   AutoIndent Indent(P);
293   uint32_t StreamCount = File.getNumStreams();
294   uint32_t MaxStreamSize = File.getMaxStreamSize();
295
296   for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
297     P.formatLine(
298         "Stream {0} ({1} bytes): [{2}]",
299         fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
300         fmt_align(File.getStreamByteSize(StreamIdx), AlignStyle::Right,
301                   NumDigits(MaxStreamSize)),
302         StreamPurposes[StreamIdx].getLongName());
303
304     if (opts::dump::DumpStreamBlocks) {
305       auto Blocks = File.getStreamBlockList(StreamIdx);
306       std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
307       P.formatLine("       {0}  Blocks: [{1}]",
308                    fmt_repeat(' ', NumDigits(StreamCount)),
309                    make_range(BV.begin(), BV.end()));
310     }
311   }
312
313   return Error::success();
314 }
315
316 static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
317                                                            uint32_t Index) {
318   ExitOnError Err("Unexpected error: ");
319
320   auto &Dbi = Err(File.getPDBDbiStream());
321   const auto &Modules = Dbi.modules();
322   auto Modi = Modules.getModuleDescriptor(Index);
323
324   uint16_t ModiStream = Modi.getModuleStreamIndex();
325   if (ModiStream == kInvalidStreamIndex)
326     return make_error<RawError>(raw_error_code::no_stream,
327                                 "Module stream not present");
328
329   auto ModStreamData = MappedBlockStream::createIndexedStream(
330       File.getMsfLayout(), File.getMsfBuffer(), ModiStream,
331       File.getAllocator());
332
333   ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
334   if (auto EC = ModS.reload())
335     return make_error<RawError>(raw_error_code::corrupt_file,
336                                 "Invalid module stream");
337
338   return std::move(ModS);
339 }
340
341 static std::string formatChecksumKind(FileChecksumKind Kind) {
342   switch (Kind) {
343     RETURN_CASE(FileChecksumKind, None, "None");
344     RETURN_CASE(FileChecksumKind, MD5, "MD5");
345     RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
346     RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
347   }
348   return formatUnknownEnum(Kind);
349 }
350
351 namespace {
352 class StringsAndChecksumsPrinter {
353   const DebugStringTableSubsectionRef &extractStringTable(PDBFile &File) {
354     ExitOnError Err("Unexpected error processing modules: ");
355     return Err(File.getStringTable()).getStringTable();
356   }
357
358   template <typename... Args>
359   void formatInternal(LinePrinter &Printer, bool Append,
360                       Args &&... args) const {
361     if (Append)
362       Printer.format(std::forward<Args>(args)...);
363     else
364       Printer.formatLine(std::forward<Args>(args)...);
365   }
366
367 public:
368   StringsAndChecksumsPrinter(PDBFile &File, uint32_t Modi)
369       : Records(extractStringTable(File)) {
370     auto MDS = getModuleDebugStream(File, Modi);
371     if (!MDS) {
372       consumeError(MDS.takeError());
373       return;
374     }
375
376     DebugStream = llvm::make_unique<ModuleDebugStreamRef>(std::move(*MDS));
377     Records.initialize(MDS->subsections());
378     if (Records.hasChecksums()) {
379       for (const auto &Entry : Records.checksums()) {
380         auto S = Records.strings().getString(Entry.FileNameOffset);
381         if (!S)
382           continue;
383         ChecksumsByFile[*S] = Entry;
384       }
385     }
386   }
387
388   Expected<StringRef> getNameFromStringTable(uint32_t Offset) const {
389     return Records.strings().getString(Offset);
390   }
391
392   void formatFromFileName(LinePrinter &Printer, StringRef File,
393                           bool Append = false) const {
394     auto FC = ChecksumsByFile.find(File);
395     if (FC == ChecksumsByFile.end()) {
396       formatInternal(Printer, Append, "- (no checksum) {0}", File);
397       return;
398     }
399
400     formatInternal(Printer, Append, "- ({0}: {1}) {2}",
401                    formatChecksumKind(FC->getValue().Kind),
402                    toHex(FC->getValue().Checksum), File);
403   }
404
405   void formatFromChecksumsOffset(LinePrinter &Printer, uint32_t Offset,
406                                  bool Append = false) const {
407     if (!Records.hasChecksums()) {
408       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
409       return;
410     }
411
412     auto Iter = Records.checksums().getArray().at(Offset);
413     if (Iter == Records.checksums().getArray().end()) {
414       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
415       return;
416     }
417
418     uint32_t FO = Iter->FileNameOffset;
419     auto ExpectedFile = getNameFromStringTable(FO);
420     if (!ExpectedFile) {
421       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
422       consumeError(ExpectedFile.takeError());
423       return;
424     }
425     if (Iter->Kind == FileChecksumKind::None) {
426       formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
427     } else {
428       formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
429                      formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
430     }
431   }
432
433   std::unique_ptr<ModuleDebugStreamRef> DebugStream;
434   StringsAndChecksumsRef Records;
435   StringMap<FileChecksumEntry> ChecksumsByFile;
436 };
437 } // namespace
438
439 template <typename CallbackT>
440 static void iterateOneModule(PDBFile &File, LinePrinter &P,
441                              const DbiModuleDescriptor &Descriptor,
442                              uint32_t Modi, uint32_t IndentLevel,
443                              uint32_t Digits, CallbackT Callback) {
444   P.formatLine(
445       "Mod {0:4} | `{1}`: ", fmt_align(Modi, AlignStyle::Right, Digits),
446       Descriptor.getModuleName());
447
448   StringsAndChecksumsPrinter Strings(File, Modi);
449   AutoIndent Indent2(P, IndentLevel);
450   Callback(Modi, Strings);
451 }
452
453 template <typename CallbackT>
454 static void iterateModules(PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
455                            CallbackT Callback) {
456   AutoIndent Indent(P);
457   if (!File.hasPDBDbiStream()) {
458     P.formatLine("DBI Stream not present");
459     return;
460   }
461
462   ExitOnError Err("Unexpected error processing modules: ");
463
464   auto &Stream = Err(File.getPDBDbiStream());
465
466   const DbiModuleList &Modules = Stream.modules();
467
468   if (opts::dump::DumpModi.getNumOccurrences() > 0) {
469     assert(opts::dump::DumpModi.getNumOccurrences() == 1);
470     uint32_t Modi = opts::dump::DumpModi;
471     auto Descriptor = Modules.getModuleDescriptor(Modi);
472     iterateOneModule(File, P, Descriptor, Modi, IndentLevel, NumDigits(Modi),
473                      Callback);
474     return;
475   }
476
477   uint32_t Count = Modules.getModuleCount();
478   uint32_t Digits = NumDigits(Count);
479   for (uint32_t I = 0; I < Count; ++I) {
480     auto Desc = Modules.getModuleDescriptor(I);
481     if (!shouldDumpModule(I, Desc))
482       continue;
483     iterateOneModule(File, P, Desc, I, IndentLevel, Digits, Callback);
484   }
485 }
486
487 template <typename SubsectionT>
488 static void iterateModuleSubsections(
489     PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
490     llvm::function_ref<void(uint32_t, StringsAndChecksumsPrinter &,
491                             SubsectionT &)>
492         Callback) {
493
494   iterateModules(
495       File, P, IndentLevel,
496       [&File, &Callback](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
497         auto MDS = getModuleDebugStream(File, Modi);
498         if (!MDS) {
499           consumeError(MDS.takeError());
500           return;
501         }
502
503         for (const auto &SS : MDS->subsections()) {
504           SubsectionT Subsection;
505
506           if (SS.kind() != Subsection.kind())
507             continue;
508
509           BinaryStreamReader Reader(SS.getRecordData());
510           if (auto EC = Subsection.initialize(Reader))
511             continue;
512           Callback(Modi, Strings, Subsection);
513         }
514       });
515 }
516
517 Error DumpOutputStyle::dumpModules() {
518   printHeader(P, "Modules");
519
520   AutoIndent Indent(P);
521   if (!File.hasPDBDbiStream()) {
522     P.formatLine("DBI Stream not present");
523     return Error::success();
524   }
525
526   ExitOnError Err("Unexpected error processing modules: ");
527
528   auto &Stream = Err(File.getPDBDbiStream());
529
530   const DbiModuleList &Modules = Stream.modules();
531   iterateModules(
532       File, P, 11, [&](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
533         auto Desc = Modules.getModuleDescriptor(Modi);
534         P.formatLine("Obj: `{0}`: ", Desc.getObjFileName());
535         P.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
536                      Desc.getModuleStreamIndex(), Desc.getNumberOfFiles(),
537                      Desc.hasECInfo());
538         StringRef PdbFilePath =
539             Err(Stream.getECName(Desc.getPdbFilePathNameIndex()));
540         StringRef SrcFilePath =
541             Err(Stream.getECName(Desc.getSourceFileNameIndex()));
542         P.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
543                      Desc.getPdbFilePathNameIndex(), PdbFilePath,
544                      Desc.getSourceFileNameIndex(), SrcFilePath);
545       });
546   return Error::success();
547 }
548
549 Error DumpOutputStyle::dumpModuleFiles() {
550   printHeader(P, "Files");
551
552   ExitOnError Err("Unexpected error processing modules: ");
553
554   iterateModules(
555       File, P, 11,
556       [this, &Err](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
557         auto &Stream = Err(File.getPDBDbiStream());
558
559         const DbiModuleList &Modules = Stream.modules();
560         for (const auto &F : Modules.source_files(Modi)) {
561           Strings.formatFromFileName(P, F);
562         }
563       });
564   return Error::success();
565 }
566
567 Error DumpOutputStyle::dumpSymbolStats() {
568   printHeader(P, "Module Stats");
569
570   ExitOnError Err("Unexpected error processing modules: ");
571
572   StatCollection SymStats;
573   StatCollection ChunkStats;
574   auto &Stream = Err(File.getPDBDbiStream());
575
576   const DbiModuleList &Modules = Stream.modules();
577   uint32_t ModCount = Modules.getModuleCount();
578
579   iterateModules(File, P, 0, [&](uint32_t Modi,
580                                  StringsAndChecksumsPrinter &Strings) {
581     DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
582     uint32_t StreamIdx = Desc.getModuleStreamIndex();
583
584     if (StreamIdx == kInvalidStreamIndex) {
585       P.formatLine("Mod {0} (debug info not present): [{1}]",
586                    fmt_align(Modi, AlignStyle::Right, NumDigits(ModCount)),
587                    Desc.getModuleName());
588       return;
589     }
590
591     P.formatLine("Stream {0}, {1} bytes", StreamIdx,
592                  File.getStreamByteSize(StreamIdx));
593
594     ModuleDebugStreamRef MDS(Desc, File.createIndexedStream(StreamIdx));
595     if (auto EC = MDS.reload()) {
596       P.printLine("- Error parsing debug info stream");
597       consumeError(std::move(EC));
598       return;
599     }
600
601     printModuleDetailStats<SymbolKind>(P, "Symbols",
602                                        getSymbolStats(MDS, SymStats));
603     printModuleDetailStats<DebugSubsectionKind>(P, "Chunks",
604                                                 getChunkStats(MDS, ChunkStats));
605   });
606
607   P.printLine("  Summary |");
608   AutoIndent Indent(P, 4);
609   if (SymStats.Totals.Count > 0) {
610     printModuleDetailStats<SymbolKind>(P, "Symbols", SymStats);
611     printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", ChunkStats);
612   }
613
614   return Error::success();
615 }
616
617 static bool isValidNamespaceIdentifier(StringRef S) {
618   if (S.empty())
619     return false;
620
621   if (std::isdigit(S[0]))
622     return false;
623
624   return llvm::all_of(S, [](char C) { return std::isalnum(C); });
625 }
626
627 namespace {
628 constexpr uint32_t kNoneUdtKind = 0;
629 constexpr uint32_t kSimpleUdtKind = 1;
630 constexpr uint32_t kUnknownUdtKind = 2;
631 const StringRef NoneLabel("<none type>");
632 const StringRef SimpleLabel("<simple type>");
633 const StringRef UnknownLabel("<unknown type>");
634
635 } // namespace
636
637 static StringRef getUdtStatLabel(uint32_t Kind) {
638   if (Kind == kNoneUdtKind)
639     return NoneLabel;
640
641   if (Kind == kSimpleUdtKind)
642     return SimpleLabel;
643
644   if (Kind == kUnknownUdtKind)
645     return UnknownLabel;
646
647   return formatTypeLeafKind(static_cast<TypeLeafKind>(Kind));
648 }
649
650 static uint32_t getLongestTypeLeafName(const StatCollection &Stats) {
651   size_t L = 0;
652   for (const auto &Stat : Stats.Individual) {
653     StringRef Label = getUdtStatLabel(Stat.first);
654     L = std::max(L, Label.size());
655   }
656   return static_cast<uint32_t>(L);
657 }
658
659 Error DumpOutputStyle::dumpUdtStats() {
660   printHeader(P, "S_UDT Record Stats");
661
662   StatCollection UdtStats;
663   StatCollection UdtTargetStats;
664   if (!File.hasPDBGlobalsStream()) {
665     P.printLine("- Error: globals stream not present");
666     return Error::success();
667   }
668
669   AutoIndent Indent(P, 4);
670
671   auto &SymbolRecords = cantFail(File.getPDBSymbolStream());
672   auto &Globals = cantFail(File.getPDBGlobalsStream());
673   auto &TpiTypes = cantFail(initializeTypes(StreamTPI));
674
675   StringMap<StatCollection::Stat> NamespacedStats;
676
677   P.NewLine();
678
679   size_t LongestNamespace = 0;
680   for (uint32_t PubSymOff : Globals.getGlobalsTable()) {
681     CVSymbol Sym = SymbolRecords.readRecord(PubSymOff);
682     if (Sym.kind() != SymbolKind::S_UDT)
683       continue;
684     UdtStats.update(SymbolKind::S_UDT, Sym.length());
685
686     UDTSym UDT = cantFail(SymbolDeserializer::deserializeAs<UDTSym>(Sym));
687
688     uint32_t Kind = 0;
689     uint32_t RecordSize = 0;
690     if (UDT.Type.isSimple() ||
691         (UDT.Type.toArrayIndex() >= TpiTypes.capacity())) {
692       if (UDT.Type.isNoneType())
693         Kind = kNoneUdtKind;
694       else if (UDT.Type.isSimple())
695         Kind = kSimpleUdtKind;
696       else
697         Kind = kUnknownUdtKind;
698     } else {
699       CVType T = TpiTypes.getType(UDT.Type);
700       Kind = T.kind();
701       RecordSize = T.length();
702     }
703
704     UdtTargetStats.update(Kind, RecordSize);
705
706     size_t Pos = UDT.Name.find("::");
707     if (Pos == StringRef::npos)
708       continue;
709
710     StringRef Scope = UDT.Name.take_front(Pos);
711     if (Scope.empty() || !isValidNamespaceIdentifier(Scope))
712       continue;
713
714     LongestNamespace = std::max(LongestNamespace, Scope.size());
715     NamespacedStats[Scope].update(RecordSize);
716   }
717
718   LongestNamespace += StringRef(" namespace ''").size();
719   uint32_t LongestTypeLeafKind = getLongestTypeLeafName(UdtTargetStats);
720   uint32_t FieldWidth = std::max(LongestNamespace, LongestTypeLeafKind);
721
722   // Compute the max number of digits for count and size fields, including comma
723   // separators.
724   StringRef CountHeader("Count");
725   StringRef SizeHeader("Size");
726   uint32_t CD = NumDigits(UdtStats.Totals.Count);
727   CD += (CD - 1) / 3;
728   CD = std::max(CD, CountHeader.size());
729
730   uint32_t SD = NumDigits(UdtStats.Totals.Size);
731   SD += (SD - 1) / 3;
732   SD = std::max(SD, SizeHeader.size());
733
734   uint32_t TableWidth = FieldWidth + 3 + CD + 2 + SD + 1;
735
736   P.formatLine("{0} | {1}  {2}",
737                fmt_align("Record Kind", AlignStyle::Right, FieldWidth),
738                fmt_align(CountHeader, AlignStyle::Right, CD),
739                fmt_align(SizeHeader, AlignStyle::Right, SD));
740
741   P.formatLine("{0}", fmt_repeat('-', TableWidth));
742   for (const auto &Stat : UdtTargetStats.Individual) {
743     StringRef Label = getUdtStatLabel(Stat.first);
744     P.formatLine("{0} | {1:N}  {2:N}",
745                  fmt_align(Label, AlignStyle::Right, FieldWidth),
746                  fmt_align(Stat.second.Count, AlignStyle::Right, CD),
747                  fmt_align(Stat.second.Size, AlignStyle::Right, SD));
748   }
749   P.formatLine("{0}", fmt_repeat('-', TableWidth));
750   P.formatLine("{0} | {1:N}  {2:N}",
751                fmt_align("Total (S_UDT)", AlignStyle::Right, FieldWidth),
752                fmt_align(UdtStats.Totals.Count, AlignStyle::Right, CD),
753                fmt_align(UdtStats.Totals.Size, AlignStyle::Right, SD));
754   P.formatLine("{0}", fmt_repeat('-', TableWidth));
755   for (const auto &Stat : NamespacedStats) {
756     std::string Label = formatv("namespace '{0}'", Stat.getKey());
757     P.formatLine("{0} | {1:N}  {2:N}",
758                  fmt_align(Label, AlignStyle::Right, FieldWidth),
759                  fmt_align(Stat.second.Count, AlignStyle::Right, CD),
760                  fmt_align(Stat.second.Size, AlignStyle::Right, SD));
761   }
762   return Error::success();
763 }
764
765 static void typesetLinesAndColumns(PDBFile &File, LinePrinter &P,
766                                    uint32_t Start, const LineColumnEntry &E) {
767   const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
768   uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
769
770   // Let's try to keep it under 100 characters
771   constexpr uint32_t kMaxRowLength = 100;
772   // At least 3 spaces between columns.
773   uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
774   uint32_t ItemsLeft = E.LineNumbers.size();
775   auto LineIter = E.LineNumbers.begin();
776   while (ItemsLeft != 0) {
777     uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
778     for (uint32_t I = 0; I < RowColumns; ++I) {
779       LineInfo Line(LineIter->Flags);
780       std::string LineStr;
781       if (Line.isAlwaysStepInto())
782         LineStr = "ASI";
783       else if (Line.isNeverStepInto())
784         LineStr = "NSI";
785       else
786         LineStr = utostr(Line.getStartLine());
787       char Statement = Line.isStatement() ? ' ' : '!';
788       P.format("{0} {1:X-} {2} ",
789                fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
790                fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
791                Statement);
792       ++LineIter;
793       --ItemsLeft;
794     }
795     P.NewLine();
796   }
797 }
798
799 Error DumpOutputStyle::dumpLines() {
800   printHeader(P, "Lines");
801
802   uint32_t LastModi = UINT32_MAX;
803   uint32_t LastNameIndex = UINT32_MAX;
804   iterateModuleSubsections<DebugLinesSubsectionRef>(
805       File, P, 4,
806       [this, &LastModi, &LastNameIndex](uint32_t Modi,
807                                         StringsAndChecksumsPrinter &Strings,
808                                         DebugLinesSubsectionRef &Lines) {
809         uint16_t Segment = Lines.header()->RelocSegment;
810         uint32_t Begin = Lines.header()->RelocOffset;
811         uint32_t End = Begin + Lines.header()->CodeSize;
812         for (const auto &Block : Lines) {
813           if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
814             LastModi = Modi;
815             LastNameIndex = Block.NameIndex;
816             Strings.formatFromChecksumsOffset(P, Block.NameIndex);
817           }
818
819           AutoIndent Indent(P, 2);
820           P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
821           uint32_t Count = Block.LineNumbers.size();
822           if (Lines.hasColumnInfo())
823             P.format("line/column/addr entries = {0}", Count);
824           else
825             P.format("line/addr entries = {0}", Count);
826
827           P.NewLine();
828           typesetLinesAndColumns(File, P, Begin, Block);
829         }
830       });
831
832   return Error::success();
833 }
834
835 Error DumpOutputStyle::dumpInlineeLines() {
836   printHeader(P, "Inlinee Lines");
837
838   iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
839       File, P, 2,
840       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
841              DebugInlineeLinesSubsectionRef &Lines) {
842         P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
843         for (const auto &Entry : Lines) {
844           P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
845                        fmtle(Entry.Header->SourceLineNum));
846           Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
847         }
848         P.NewLine();
849       });
850
851   return Error::success();
852 }
853
854 Error DumpOutputStyle::dumpXmi() {
855   printHeader(P, "Cross Module Imports");
856   iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
857       File, P, 2,
858       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
859              DebugCrossModuleImportsSubsectionRef &Imports) {
860         P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
861
862         for (const auto &Xmi : Imports) {
863           auto ExpectedModule =
864               Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
865           StringRef Module;
866           SmallString<32> ModuleStorage;
867           if (!ExpectedModule) {
868             Module = "(unknown module)";
869             consumeError(ExpectedModule.takeError());
870           } else
871             Module = *ExpectedModule;
872           if (Module.size() > 32) {
873             ModuleStorage = "...";
874             ModuleStorage += Module.take_back(32 - 3);
875             Module = ModuleStorage;
876           }
877           std::vector<std::string> TIs;
878           for (const auto I : Xmi.Imports)
879             TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
880           std::string Result =
881               typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
882           P.formatLine("{0,+32} | {1}", Module, Result);
883         }
884       });
885
886   return Error::success();
887 }
888
889 Error DumpOutputStyle::dumpXme() {
890   printHeader(P, "Cross Module Exports");
891
892   iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
893       File, P, 2,
894       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
895              DebugCrossModuleExportsSubsectionRef &Exports) {
896         P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
897         for (const auto &Export : Exports) {
898           P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
899                        TypeIndex(Export.Global));
900         }
901       });
902
903   return Error::success();
904 }
905
906 Error DumpOutputStyle::dumpStringTable() {
907   printHeader(P, "String Table");
908
909   AutoIndent Indent(P);
910   auto IS = File.getStringTable();
911   if (!IS) {
912     P.formatLine("Not present in file");
913     consumeError(IS.takeError());
914     return Error::success();
915   }
916
917   if (IS->name_ids().empty()) {
918     P.formatLine("Empty");
919     return Error::success();
920   }
921
922   auto MaxID = std::max_element(IS->name_ids().begin(), IS->name_ids().end());
923   uint32_t Digits = NumDigits(*MaxID);
924
925   P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
926                "String");
927
928   std::vector<uint32_t> SortedIDs(IS->name_ids().begin(), IS->name_ids().end());
929   std::sort(SortedIDs.begin(), SortedIDs.end());
930   for (uint32_t I : SortedIDs) {
931     auto ES = IS->getStringForID(I);
932     llvm::SmallString<32> Str;
933     if (!ES) {
934       consumeError(ES.takeError());
935       Str = "Error reading string";
936     } else if (!ES->empty()) {
937       Str.append("'");
938       Str.append(*ES);
939       Str.append("'");
940     }
941
942     if (!Str.empty())
943       P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits), Str);
944   }
945   return Error::success();
946 }
947
948 static void buildDepSet(LazyRandomTypeCollection &Types,
949                         ArrayRef<TypeIndex> Indices,
950                         std::map<TypeIndex, CVType> &DepSet) {
951   SmallVector<TypeIndex, 4> DepList;
952   for (const auto &I : Indices) {
953     TypeIndex TI(I);
954     if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
955       continue;
956
957     CVType Type = Types.getType(TI);
958     DepSet[TI] = Type;
959     codeview::discoverTypeIndices(Type, DepList);
960     buildDepSet(Types, DepList, DepSet);
961   }
962 }
963
964 static void dumpFullTypeStream(LinePrinter &Printer,
965                                LazyRandomTypeCollection &Types,
966                                TpiStream &Stream, bool Bytes, bool Extras) {
967   Printer.formatLine("Showing {0:N} records", Stream.getNumTypeRecords());
968   uint32_t Width =
969       NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
970
971   MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
972                            Stream.getNumHashBuckets(), Stream.getHashValues());
973
974   if (auto EC = codeview::visitTypeStream(Types, V)) {
975     Printer.formatLine("An error occurred dumping type records: {0}",
976                        toString(std::move(EC)));
977   }
978 }
979
980 static void dumpPartialTypeStream(LinePrinter &Printer,
981                                   LazyRandomTypeCollection &Types,
982                                   TpiStream &Stream, ArrayRef<TypeIndex> TiList,
983                                   bool Bytes, bool Extras, bool Deps) {
984   uint32_t Width =
985       NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
986
987   MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
988                            Stream.getNumHashBuckets(), Stream.getHashValues());
989
990   if (opts::dump::DumpTypeDependents) {
991     // If we need to dump all dependents, then iterate each index and find
992     // all dependents, adding them to a map ordered by TypeIndex.
993     std::map<TypeIndex, CVType> DepSet;
994     buildDepSet(Types, TiList, DepSet);
995
996     Printer.formatLine(
997         "Showing {0:N} records and their dependents ({1:N} records total)",
998         TiList.size(), DepSet.size());
999
1000     for (auto &Dep : DepSet) {
1001       if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
1002         Printer.formatLine("An error occurred dumping type record {0}: {1}",
1003                            Dep.first, toString(std::move(EC)));
1004     }
1005   } else {
1006     Printer.formatLine("Showing {0:N} records.", TiList.size());
1007
1008     for (const auto &I : TiList) {
1009       TypeIndex TI(I);
1010       CVType Type = Types.getType(TI);
1011       if (auto EC = codeview::visitTypeRecord(Type, TI, V))
1012         Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
1013                            toString(std::move(EC)));
1014     }
1015   }
1016 }
1017
1018 Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
1019   assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
1020
1021   bool Present = false;
1022   bool DumpTypes = false;
1023   bool DumpBytes = false;
1024   bool DumpExtras = false;
1025   std::vector<uint32_t> Indices;
1026   if (StreamIdx == StreamTPI) {
1027     printHeader(P, "Types (TPI Stream)");
1028     Present = File.hasPDBTpiStream();
1029     DumpTypes = opts::dump::DumpTypes;
1030     DumpBytes = opts::dump::DumpTypeData;
1031     DumpExtras = opts::dump::DumpTypeExtras;
1032     Indices.assign(opts::dump::DumpTypeIndex.begin(),
1033                    opts::dump::DumpTypeIndex.end());
1034   } else if (StreamIdx == StreamIPI) {
1035     printHeader(P, "Types (IPI Stream)");
1036     Present = File.hasPDBIpiStream();
1037     DumpTypes = opts::dump::DumpIds;
1038     DumpBytes = opts::dump::DumpIdData;
1039     DumpExtras = opts::dump::DumpIdExtras;
1040     Indices.assign(opts::dump::DumpIdIndex.begin(),
1041                    opts::dump::DumpIdIndex.end());
1042   }
1043
1044   AutoIndent Indent(P);
1045   if (!Present) {
1046     P.formatLine("Stream not present");
1047     return Error::success();
1048   }
1049
1050   ExitOnError Err("Unexpected error processing types: ");
1051
1052   auto &Stream = Err((StreamIdx == StreamTPI) ? File.getPDBTpiStream()
1053                                               : File.getPDBIpiStream());
1054
1055   auto &Types = Err(initializeTypes(StreamIdx));
1056
1057   if (DumpTypes || !Indices.empty()) {
1058     if (Indices.empty())
1059       dumpFullTypeStream(P, Types, Stream, DumpBytes, DumpExtras);
1060     else {
1061       std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
1062       dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
1063                             opts::dump::DumpTypeDependents);
1064     }
1065   }
1066
1067   if (DumpExtras) {
1068     P.NewLine();
1069     auto IndexOffsets = Stream.getTypeIndexOffsets();
1070     P.formatLine("Type Index Offsets:");
1071     for (const auto &IO : IndexOffsets) {
1072       AutoIndent Indent2(P);
1073       P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
1074     }
1075
1076     P.NewLine();
1077     P.formatLine("Hash Adjusters:");
1078     auto &Adjusters = Stream.getHashAdjusters();
1079     auto &Strings = Err(File.getStringTable());
1080     for (const auto &A : Adjusters) {
1081       AutoIndent Indent2(P);
1082       auto ExpectedStr = Strings.getStringForID(A.first);
1083       TypeIndex TI(A.second);
1084       if (ExpectedStr)
1085         P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
1086       else {
1087         P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
1088         consumeError(ExpectedStr.takeError());
1089       }
1090     }
1091   }
1092   return Error::success();
1093 }
1094
1095 Expected<codeview::LazyRandomTypeCollection &>
1096 DumpOutputStyle::initializeTypes(uint32_t SN) {
1097   auto &TypeCollection = (SN == StreamTPI) ? TpiTypes : IpiTypes;
1098   auto Tpi =
1099       (SN == StreamTPI) ? File.getPDBTpiStream() : File.getPDBIpiStream();
1100   if (!Tpi)
1101     return Tpi.takeError();
1102
1103   if (!TypeCollection) {
1104     auto &Types = Tpi->typeArray();
1105     uint32_t Count = Tpi->getNumTypeRecords();
1106     auto Offsets = Tpi->getTypeIndexOffsets();
1107     TypeCollection =
1108         llvm::make_unique<LazyRandomTypeCollection>(Types, Count, Offsets);
1109   }
1110
1111   return *TypeCollection;
1112 }
1113
1114 Error DumpOutputStyle::dumpModuleSyms() {
1115   printHeader(P, "Symbols");
1116
1117   AutoIndent Indent(P);
1118   if (!File.hasPDBDbiStream()) {
1119     P.formatLine("DBI Stream not present");
1120     return Error::success();
1121   }
1122
1123   ExitOnError Err("Unexpected error processing symbols: ");
1124
1125   auto &Ids = Err(initializeTypes(StreamIPI));
1126   auto &Types = Err(initializeTypes(StreamTPI));
1127
1128   iterateModules(
1129       File, P, 2, [&](uint32_t I, StringsAndChecksumsPrinter &Strings) {
1130         auto ExpectedModS = getModuleDebugStream(File, I);
1131         if (!ExpectedModS) {
1132           P.formatLine("Error loading module stream {0}.  {1}", I,
1133                        toString(ExpectedModS.takeError()));
1134           return;
1135         }
1136
1137         ModuleDebugStreamRef &ModS = *ExpectedModS;
1138
1139         SymbolVisitorCallbackPipeline Pipeline;
1140         SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1141         MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids,
1142                                    Types);
1143
1144         Pipeline.addCallbackToPipeline(Deserializer);
1145         Pipeline.addCallbackToPipeline(Dumper);
1146         CVSymbolVisitor Visitor(Pipeline);
1147         auto SS = ModS.getSymbolsSubstream();
1148         if (auto EC =
1149                 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
1150           P.formatLine("Error while processing symbol records.  {0}",
1151                        toString(std::move(EC)));
1152           return;
1153         }
1154       });
1155   return Error::success();
1156 }
1157
1158 Error DumpOutputStyle::dumpGlobals() {
1159   printHeader(P, "Global Symbols");
1160   AutoIndent Indent(P);
1161   if (!File.hasPDBGlobalsStream()) {
1162     P.formatLine("Globals stream not present");
1163     return Error::success();
1164   }
1165   ExitOnError Err("Error dumping globals stream: ");
1166   auto &Globals = Err(File.getPDBGlobalsStream());
1167
1168   const GSIHashTable &Table = Globals.getGlobalsTable();
1169   Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
1170   return Error::success();
1171 }
1172
1173 Error DumpOutputStyle::dumpPublics() {
1174   printHeader(P, "Public Symbols");
1175   AutoIndent Indent(P);
1176   if (!File.hasPDBPublicsStream()) {
1177     P.formatLine("Publics stream not present");
1178     return Error::success();
1179   }
1180   ExitOnError Err("Error dumping publics stream: ");
1181   auto &Publics = Err(File.getPDBPublicsStream());
1182
1183   const GSIHashTable &PublicsTable = Publics.getPublicsTable();
1184   if (opts::dump::DumpPublicExtras) {
1185     P.printLine("Publics Header");
1186     AutoIndent Indent(P);
1187     P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
1188                  formatSegmentOffset(Publics.getThunkTableSection(),
1189                                      Publics.getThunkTableOffset()));
1190   }
1191   Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
1192
1193   // Skip the rest if we aren't dumping extras.
1194   if (!opts::dump::DumpPublicExtras)
1195     return Error::success();
1196
1197   P.formatLine("Address Map");
1198   {
1199     // These are offsets into the publics stream sorted by secidx:secrel.
1200     AutoIndent Indent2(P);
1201     for (uint32_t Addr : Publics.getAddressMap())
1202       P.formatLine("off = {0}", Addr);
1203   }
1204
1205   // The thunk map is optional debug info used for ILT thunks.
1206   if (!Publics.getThunkMap().empty()) {
1207     P.formatLine("Thunk Map");
1208     AutoIndent Indent2(P);
1209     for (uint32_t Addr : Publics.getThunkMap())
1210       P.formatLine("{0:x8}", Addr);
1211   }
1212
1213   // The section offsets table appears to be empty when incremental linking
1214   // isn't in use.
1215   if (!Publics.getSectionOffsets().empty()) {
1216     P.formatLine("Section Offsets");
1217     AutoIndent Indent2(P);
1218     for (const SectionOffset &SO : Publics.getSectionOffsets())
1219       P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
1220   }
1221
1222   return Error::success();
1223 }
1224
1225 Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1226                                           bool HashExtras) {
1227   auto ExpectedSyms = File.getPDBSymbolStream();
1228   if (!ExpectedSyms)
1229     return ExpectedSyms.takeError();
1230   auto ExpectedTypes = initializeTypes(StreamTPI);
1231   if (!ExpectedTypes)
1232     return ExpectedTypes.takeError();
1233   auto ExpectedIds = initializeTypes(StreamIPI);
1234   if (!ExpectedIds)
1235     return ExpectedIds.takeError();
1236
1237   if (HashExtras) {
1238     P.printLine("GSI Header");
1239     AutoIndent Indent(P);
1240     P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1241                  Table.getVerSignature(), Table.getVerHeader(),
1242                  Table.getHashRecordSize(), Table.getNumBuckets());
1243   }
1244
1245   {
1246     P.printLine("Records");
1247     SymbolVisitorCallbackPipeline Pipeline;
1248     SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
1249     MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, *ExpectedIds,
1250                                *ExpectedTypes);
1251
1252     Pipeline.addCallbackToPipeline(Deserializer);
1253     Pipeline.addCallbackToPipeline(Dumper);
1254     CVSymbolVisitor Visitor(Pipeline);
1255
1256     BinaryStreamRef SymStream =
1257         ExpectedSyms->getSymbolArray().getUnderlyingStream();
1258     for (uint32_t PubSymOff : Table) {
1259       Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
1260       if (!Sym)
1261         return Sym.takeError();
1262       if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
1263         return E;
1264     }
1265   }
1266
1267   // Return early if we aren't dumping public hash table and address map info.
1268   if (!HashExtras)
1269     return Error::success();
1270
1271   P.formatLine("Hash Entries");
1272   {
1273     AutoIndent Indent2(P);
1274     for (const PSHashRecord &HR : Table.HashRecords)
1275       P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
1276                    uint32_t(HR.CRef));
1277   }
1278
1279   // FIXME: Dump the bitmap.
1280
1281   P.formatLine("Hash Buckets");
1282   {
1283     AutoIndent Indent2(P);
1284     for (uint32_t Hash : Table.HashBuckets)
1285       P.formatLine("{0:x8}", Hash);
1286   }
1287
1288   return Error::success();
1289 }
1290
1291 static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1292                                               OMFSegDescFlags Flags) {
1293   std::vector<std::string> Opts;
1294   if (Flags == OMFSegDescFlags::None)
1295     return "none";
1296
1297   PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1298   PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1299   PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1300   PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1301   PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1302   PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1303   PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
1304   return typesetItemList(Opts, IndentLevel, 4, " | ");
1305 }
1306
1307 Error DumpOutputStyle::dumpSectionHeaders() {
1308   dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1309   dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1310   return Error::success();
1311 }
1312
1313 static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1314                           ArrayRef<llvm::object::coff_section>>>
1315 loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1316   if (!File.hasPDBDbiStream())
1317     return make_error<StringError>(
1318         "Section headers require a DBI Stream, which could not be loaded",
1319         inconvertibleErrorCode());
1320
1321   auto &Dbi = cantFail(File.getPDBDbiStream());
1322   uint32_t SI = Dbi.getDebugStreamIndex(Type);
1323
1324   if (SI == kInvalidStreamIndex)
1325     return make_error<StringError>(
1326         "PDB does not contain the requested image section header type",
1327         inconvertibleErrorCode());
1328
1329   auto Stream = MappedBlockStream::createIndexedStream(
1330       File.getMsfLayout(), File.getMsfBuffer(), SI, File.getAllocator());
1331   if (!Stream)
1332     return make_error<StringError>("Could not load the required stream data",
1333                                    inconvertibleErrorCode());
1334
1335   ArrayRef<object::coff_section> Headers;
1336   if (Stream->getLength() % sizeof(object::coff_section) != 0)
1337     return make_error<StringError>(
1338         "Section header array size is not a multiple of section header size",
1339         inconvertibleErrorCode());
1340
1341   uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1342   BinaryStreamReader Reader(*Stream);
1343   cantFail(Reader.readArray(Headers, NumHeaders));
1344   return std::make_pair(std::move(Stream), Headers);
1345 }
1346
1347 void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1348   printHeader(P, Label);
1349   ExitOnError Err("Error dumping publics stream: ");
1350
1351   AutoIndent Indent(P);
1352   std::unique_ptr<MappedBlockStream> Stream;
1353   ArrayRef<object::coff_section> Headers;
1354   auto ExpectedHeaders = loadSectionHeaders(File, Type);
1355   if (!ExpectedHeaders) {
1356     P.printLine(toString(ExpectedHeaders.takeError()));
1357     return;
1358   }
1359   std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1360
1361   uint32_t I = 1;
1362   for (const auto &Header : Headers) {
1363     P.NewLine();
1364     P.formatLine("SECTION HEADER #{0}", I);
1365     P.formatLine("{0,8} name", Header.Name);
1366     P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1367     P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1368     P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1369     P.formatLine("{0,8:X-} file pointer to raw data",
1370                  uint32_t(Header.PointerToRawData));
1371     P.formatLine("{0,8:X-} file pointer to relocation table",
1372                  uint32_t(Header.PointerToRelocations));
1373     P.formatLine("{0,8:X-} file pointer to line numbers",
1374                  uint32_t(Header.PointerToLinenumbers));
1375     P.formatLine("{0,8:X-} number of relocations",
1376                  uint32_t(Header.NumberOfRelocations));
1377     P.formatLine("{0,8:X-} number of line numbers",
1378                  uint32_t(Header.NumberOfLinenumbers));
1379     P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1380     AutoIndent IndentMore(P, 9);
1381     P.formatLine("{0}", formatSectionCharacteristics(
1382                             P.getIndentLevel(), Header.Characteristics, 1, ""));
1383     ++I;
1384   }
1385   return;
1386 }
1387
1388 std::vector<std::string> getSectionNames(PDBFile &File) {
1389   auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1390   if (!ExpectedHeaders)
1391     return {};
1392
1393   std::unique_ptr<MappedBlockStream> Stream;
1394   ArrayRef<object::coff_section> Headers;
1395   std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1396   std::vector<std::string> Names;
1397   for (const auto &H : Headers)
1398     Names.push_back(H.Name);
1399   return Names;
1400 }
1401
1402 Error DumpOutputStyle::dumpSectionContribs() {
1403   printHeader(P, "Section Contributions");
1404   ExitOnError Err("Error dumping publics stream: ");
1405
1406   AutoIndent Indent(P);
1407   if (!File.hasPDBDbiStream()) {
1408     P.formatLine(
1409         "Section contribs require a DBI Stream, which could not be loaded");
1410     return Error::success();
1411   }
1412
1413   auto &Dbi = Err(File.getPDBDbiStream());
1414
1415   class Visitor : public ISectionContribVisitor {
1416   public:
1417     Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1418       auto Max = std::max_element(
1419           Names.begin(), Names.end(),
1420           [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1421       MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1422     }
1423     void visit(const SectionContrib &SC) override {
1424       assert(SC.ISect > 0);
1425       std::string NameInsert;
1426       if (SC.ISect < Names.size()) {
1427         StringRef SectionName = Names[SC.ISect - 1];
1428         NameInsert = formatv("[{0}]", SectionName).str();
1429       } else
1430         NameInsert = "[???]";
1431       P.formatLine("SC{5}  | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1432                    "crc = {4}",
1433                    formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1434                    fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1435                    fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1436       AutoIndent Indent(P, MaxNameLen + 2);
1437       P.formatLine("      {0}",
1438                    formatSectionCharacteristics(P.getIndentLevel() + 6,
1439                                                 SC.Characteristics, 3, " | "));
1440     }
1441     void visit(const SectionContrib2 &SC) override {
1442       P.formatLine(
1443           "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1444           "crc = {4}, coff section = {5}",
1445           formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1446           fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1447           fmtle(SC.ISectCoff));
1448       P.formatLine("      {0}", formatSectionCharacteristics(
1449                                     P.getIndentLevel() + 6,
1450                                     SC.Base.Characteristics, 3, " | "));
1451     }
1452
1453   private:
1454     LinePrinter &P;
1455     uint32_t MaxNameLen;
1456     ArrayRef<std::string> Names;
1457   };
1458
1459   std::vector<std::string> Names = getSectionNames(File);
1460   Visitor V(P, makeArrayRef(Names));
1461   Dbi.visitSectionContributions(V);
1462   return Error::success();
1463 }
1464
1465 Error DumpOutputStyle::dumpSectionMap() {
1466   printHeader(P, "Section Map");
1467   ExitOnError Err("Error dumping section map: ");
1468
1469   AutoIndent Indent(P);
1470   if (!File.hasPDBDbiStream()) {
1471     P.formatLine("Dumping the section map requires a DBI Stream, which could "
1472                  "not be loaded");
1473     return Error::success();
1474   }
1475
1476   auto &Dbi = Err(File.getPDBDbiStream());
1477
1478   uint32_t I = 0;
1479   for (auto &M : Dbi.getSectionMap()) {
1480     P.formatLine(
1481         "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
1482         fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1483     P.formatLine("               class = {0}, offset = {1}, size = {2}",
1484                  fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1485     P.formatLine("               flags = {0}",
1486                  formatSegMapDescriptorFlag(
1487                      P.getIndentLevel() + 13,
1488                      static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1489     ++I;
1490   }
1491   return Error::success();
1492 }