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 <unordered_map>
63 
64 using namespace llvm;
65 using namespace llvm::codeview;
66 using namespace llvm::msf;
67 using namespace llvm::pdb;
68 
69 DumpOutputStyle::DumpOutputStyle(PDBFile &File)
70     : File(File), P(2, false, outs()) {}
71 
72 Error DumpOutputStyle::dump() {
73   if (opts::dump::DumpSummary) {
74     if (auto EC = dumpFileSummary())
75       return EC;
76     P.NewLine();
77   }
78 
79   if (opts::dump::DumpStreams) {
80     if (auto EC = dumpStreamSummary())
81       return EC;
82     P.NewLine();
83   }
84 
85   if (opts::dump::DumpStringTable) {
86     if (auto EC = dumpStringTable())
87       return EC;
88     P.NewLine();
89   }
90 
91   if (opts::dump::DumpModules) {
92     if (auto EC = dumpModules())
93       return EC;
94   }
95 
96   if (opts::dump::DumpModuleFiles) {
97     if (auto EC = dumpModuleFiles())
98       return EC;
99   }
100 
101   if (opts::dump::DumpLines) {
102     if (auto EC = dumpLines())
103       return EC;
104   }
105 
106   if (opts::dump::DumpInlineeLines) {
107     if (auto EC = dumpInlineeLines())
108       return EC;
109   }
110 
111   if (opts::dump::DumpXmi) {
112     if (auto EC = dumpXmi())
113       return EC;
114   }
115 
116   if (opts::dump::DumpXme) {
117     if (auto EC = dumpXme())
118       return EC;
119   }
120 
121   if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
122       opts::dump::DumpTypeExtras) {
123     if (auto EC = dumpTpiStream(StreamTPI))
124       return EC;
125   }
126 
127   if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
128       opts::dump::DumpIdExtras) {
129     if (auto EC = dumpTpiStream(StreamIPI))
130       return EC;
131   }
132 
133   if (opts::dump::DumpGlobals) {
134     if (auto EC = dumpGlobals())
135       return EC;
136   }
137 
138   if (opts::dump::DumpPublics) {
139     if (auto EC = dumpPublics())
140       return EC;
141   }
142 
143   if (opts::dump::DumpSymbols) {
144     if (auto EC = dumpModuleSyms())
145       return EC;
146   }
147 
148   if (opts::dump::DumpSectionHeaders) {
149     if (auto EC = dumpSectionHeaders())
150       return EC;
151   }
152 
153   if (opts::dump::DumpSectionContribs) {
154     if (auto EC = dumpSectionContribs())
155       return EC;
156   }
157 
158   if (opts::dump::DumpSectionMap) {
159     if (auto EC = dumpSectionMap())
160       return EC;
161   }
162 
163   return Error::success();
164 }
165 
166 static void printHeader(LinePrinter &P, const Twine &S) {
167   P.NewLine();
168   P.formatLine("{0,=60}", S);
169   P.formatLine("{0}", fmt_repeat('=', 60));
170 }
171 
172 Error DumpOutputStyle::dumpFileSummary() {
173   printHeader(P, "Summary");
174 
175   ExitOnError Err("Invalid PDB Format: ");
176 
177   AutoIndent Indent(P);
178   P.formatLine("Block Size: {0}", File.getBlockSize());
179   P.formatLine("Number of blocks: {0}", File.getBlockCount());
180   P.formatLine("Number of streams: {0}", File.getNumStreams());
181 
182   auto &PS = Err(File.getPDBInfoStream());
183   P.formatLine("Signature: {0}", PS.getSignature());
184   P.formatLine("Age: {0}", PS.getAge());
185   P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
186   P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
187   P.formatLine("Has Debug Info: {0}", File.hasPDBDbiStream());
188   P.formatLine("Has Types: {0}", File.hasPDBTpiStream());
189   P.formatLine("Has IDs: {0}", File.hasPDBIpiStream());
190   P.formatLine("Has Globals: {0}", File.hasPDBGlobalsStream());
191   P.formatLine("Has Publics: {0}", File.hasPDBPublicsStream());
192   if (File.hasPDBDbiStream()) {
193     auto &DBI = Err(File.getPDBDbiStream());
194     P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
195     P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
196     P.formatLine("Is stripped: {0}", DBI.isStripped());
197   }
198 
199   return Error::success();
200 }
201 
202 Error DumpOutputStyle::dumpStreamSummary() {
203   printHeader(P, "Streams");
204 
205   if (StreamPurposes.empty())
206     discoverStreamPurposes(File, StreamPurposes);
207 
208   AutoIndent Indent(P);
209   uint32_t StreamCount = File.getNumStreams();
210 
211   for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
212     P.formatLine(
213         "Stream {0}: [{1}] ({2} bytes)",
214         fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
215         StreamPurposes[StreamIdx], File.getStreamByteSize(StreamIdx));
216     if (opts::dump::DumpStreamBlocks) {
217       auto Blocks = File.getStreamBlockList(StreamIdx);
218       std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
219       P.formatLine("       {0}  Blocks: [{1}]",
220                    fmt_repeat(' ', NumDigits(StreamCount)),
221                    make_range(BV.begin(), BV.end()));
222     }
223   }
224 
225   return Error::success();
226 }
227 
228 static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
229                                                            uint32_t Index) {
230   ExitOnError Err("Unexpected error: ");
231 
232   auto &Dbi = Err(File.getPDBDbiStream());
233   const auto &Modules = Dbi.modules();
234   auto Modi = Modules.getModuleDescriptor(Index);
235 
236   uint16_t ModiStream = Modi.getModuleStreamIndex();
237   if (ModiStream == kInvalidStreamIndex)
238     return make_error<RawError>(raw_error_code::no_stream,
239                                 "Module stream not present");
240 
241   auto ModStreamData = MappedBlockStream::createIndexedStream(
242       File.getMsfLayout(), File.getMsfBuffer(), ModiStream,
243       File.getAllocator());
244 
245   ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
246   if (auto EC = ModS.reload())
247     return make_error<RawError>(raw_error_code::corrupt_file,
248                                 "Invalid module stream");
249 
250   return std::move(ModS);
251 }
252 
253 static std::string formatChecksumKind(FileChecksumKind Kind) {
254   switch (Kind) {
255     RETURN_CASE(FileChecksumKind, None, "None");
256     RETURN_CASE(FileChecksumKind, MD5, "MD5");
257     RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
258     RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
259   }
260   return formatUnknownEnum(Kind);
261 }
262 
263 namespace {
264 class StringsAndChecksumsPrinter {
265   const DebugStringTableSubsectionRef &extractStringTable(PDBFile &File) {
266     ExitOnError Err("Unexpected error processing modules: ");
267     return Err(File.getStringTable()).getStringTable();
268   }
269 
270   template <typename... Args>
271   void formatInternal(LinePrinter &Printer, bool Append,
272                       Args &&... args) const {
273     if (Append)
274       Printer.format(std::forward<Args>(args)...);
275     else
276       Printer.formatLine(std::forward<Args>(args)...);
277   }
278 
279 public:
280   StringsAndChecksumsPrinter(PDBFile &File, uint32_t Modi)
281       : Records(extractStringTable(File)) {
282     auto MDS = getModuleDebugStream(File, Modi);
283     if (!MDS) {
284       consumeError(MDS.takeError());
285       return;
286     }
287 
288     DebugStream = llvm::make_unique<ModuleDebugStreamRef>(std::move(*MDS));
289     Records.initialize(MDS->subsections());
290     if (Records.hasChecksums()) {
291       for (const auto &Entry : Records.checksums()) {
292         auto S = Records.strings().getString(Entry.FileNameOffset);
293         if (!S)
294           continue;
295         ChecksumsByFile[*S] = Entry;
296       }
297     }
298   }
299 
300   Expected<StringRef> getNameFromStringTable(uint32_t Offset) const {
301     return Records.strings().getString(Offset);
302   }
303 
304   void formatFromFileName(LinePrinter &Printer, StringRef File,
305                           bool Append = false) const {
306     auto FC = ChecksumsByFile.find(File);
307     if (FC == ChecksumsByFile.end()) {
308       formatInternal(Printer, Append, "- (no checksum) {0}", File);
309       return;
310     }
311 
312     formatInternal(Printer, Append, "- ({0}: {1}) {2}",
313                    formatChecksumKind(FC->getValue().Kind),
314                    toHex(FC->getValue().Checksum), File);
315   }
316 
317   void formatFromChecksumsOffset(LinePrinter &Printer, uint32_t Offset,
318                                  bool Append = false) const {
319     if (!Records.hasChecksums()) {
320       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
321       return;
322     }
323 
324     auto Iter = Records.checksums().getArray().at(Offset);
325     if (Iter == Records.checksums().getArray().end()) {
326       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
327       return;
328     }
329 
330     uint32_t FO = Iter->FileNameOffset;
331     auto ExpectedFile = getNameFromStringTable(FO);
332     if (!ExpectedFile) {
333       formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
334       consumeError(ExpectedFile.takeError());
335       return;
336     }
337     if (Iter->Kind == FileChecksumKind::None) {
338       formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
339     } else {
340       formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
341                      formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
342     }
343   }
344 
345   std::unique_ptr<ModuleDebugStreamRef> DebugStream;
346   StringsAndChecksumsRef Records;
347   StringMap<FileChecksumEntry> ChecksumsByFile;
348 };
349 } // namespace
350 
351 template <typename CallbackT>
352 static void iterateOneModule(PDBFile &File, LinePrinter &P,
353                              const DbiModuleDescriptor &Descriptor,
354                              uint32_t Modi, uint32_t IndentLevel,
355                              uint32_t Digits, CallbackT Callback) {
356   P.formatLine(
357       "Mod {0:4} | `{1}`: ", fmt_align(Modi, AlignStyle::Right, Digits),
358       Descriptor.getModuleName());
359 
360   StringsAndChecksumsPrinter Strings(File, Modi);
361   AutoIndent Indent2(P, IndentLevel);
362   Callback(Modi, Strings);
363 }
364 
365 template <typename CallbackT>
366 static void iterateModules(PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
367                            CallbackT Callback) {
368   AutoIndent Indent(P);
369   if (!File.hasPDBDbiStream()) {
370     P.formatLine("DBI Stream not present");
371     return;
372   }
373 
374   ExitOnError Err("Unexpected error processing modules: ");
375 
376   auto &Stream = Err(File.getPDBDbiStream());
377 
378   const DbiModuleList &Modules = Stream.modules();
379 
380   if (opts::dump::DumpModi.getNumOccurrences() > 0) {
381     assert(opts::dump::DumpModi.getNumOccurrences() == 1);
382     uint32_t Modi = opts::dump::DumpModi;
383     auto Descriptor = Modules.getModuleDescriptor(Modi);
384     iterateOneModule(File, P, Descriptor, Modi, IndentLevel, NumDigits(Modi),
385                      Callback);
386     return;
387   }
388 
389   uint32_t Count = Modules.getModuleCount();
390   uint32_t Digits = NumDigits(Count);
391   for (uint32_t I = 0; I < Count; ++I) {
392     auto Descriptor = Modules.getModuleDescriptor(I);
393     iterateOneModule(File, P, Descriptor, I, IndentLevel, Digits, Callback);
394   }
395 }
396 
397 template <typename SubsectionT>
398 static void iterateModuleSubsections(
399     PDBFile &File, LinePrinter &P, uint32_t IndentLevel,
400     llvm::function_ref<void(uint32_t, StringsAndChecksumsPrinter &,
401                             SubsectionT &)>
402         Callback) {
403 
404   iterateModules(
405       File, P, IndentLevel,
406       [&File, &Callback](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
407         auto MDS = getModuleDebugStream(File, Modi);
408         if (!MDS) {
409           consumeError(MDS.takeError());
410           return;
411         }
412 
413         for (const auto &SS : MDS->subsections()) {
414           SubsectionT Subsection;
415 
416           if (SS.kind() != Subsection.kind())
417             continue;
418 
419           BinaryStreamReader Reader(SS.getRecordData());
420           if (auto EC = Subsection.initialize(Reader))
421             continue;
422           Callback(Modi, Strings, Subsection);
423         }
424       });
425 }
426 
427 Error DumpOutputStyle::dumpModules() {
428   printHeader(P, "Modules");
429 
430   AutoIndent Indent(P);
431   if (!File.hasPDBDbiStream()) {
432     P.formatLine("DBI Stream not present");
433     return Error::success();
434   }
435 
436   ExitOnError Err("Unexpected error processing modules: ");
437 
438   auto &Stream = Err(File.getPDBDbiStream());
439 
440   const DbiModuleList &Modules = Stream.modules();
441   uint32_t Count = Modules.getModuleCount();
442   uint32_t Digits = NumDigits(Count);
443   for (uint32_t I = 0; I < Count; ++I) {
444     auto Modi = Modules.getModuleDescriptor(I);
445     P.formatLine("Mod {0:4} | Name: `{1}`: ",
446                  fmt_align(I, AlignStyle::Right, Digits), Modi.getModuleName());
447     P.formatLine("           Obj: `{0}`: ", Modi.getObjFileName());
448     P.formatLine("           debug stream: {0}, # files: {1}, has ec info: {2}",
449                  Modi.getModuleStreamIndex(), Modi.getNumberOfFiles(),
450                  Modi.hasECInfo());
451     StringRef PdbFilePath =
452         Err(Stream.getECName(Modi.getPdbFilePathNameIndex()));
453     StringRef SrcFilePath =
454         Err(Stream.getECName(Modi.getSourceFileNameIndex()));
455     P.formatLine("           pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
456                  Modi.getPdbFilePathNameIndex(), PdbFilePath,
457                  Modi.getSourceFileNameIndex(), SrcFilePath);
458   }
459   return Error::success();
460 }
461 
462 Error DumpOutputStyle::dumpModuleFiles() {
463   printHeader(P, "Files");
464 
465   ExitOnError Err("Unexpected error processing modules: ");
466 
467   iterateModules(
468       File, P, 11,
469       [this, &Err](uint32_t Modi, StringsAndChecksumsPrinter &Strings) {
470         auto &Stream = Err(File.getPDBDbiStream());
471 
472         const DbiModuleList &Modules = Stream.modules();
473         for (const auto &F : Modules.source_files(Modi)) {
474           Strings.formatFromFileName(P, F);
475         }
476       });
477   return Error::success();
478 }
479 
480 static void typesetLinesAndColumns(PDBFile &File, LinePrinter &P,
481                                    uint32_t Start, const LineColumnEntry &E) {
482   const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
483   uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
484 
485   // Let's try to keep it under 100 characters
486   constexpr uint32_t kMaxRowLength = 100;
487   // At least 3 spaces between columns.
488   uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
489   uint32_t ItemsLeft = E.LineNumbers.size();
490   auto LineIter = E.LineNumbers.begin();
491   while (ItemsLeft != 0) {
492     uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
493     for (uint32_t I = 0; I < RowColumns; ++I) {
494       LineInfo Line(LineIter->Flags);
495       std::string LineStr;
496       if (Line.isAlwaysStepInto())
497         LineStr = "ASI";
498       else if (Line.isNeverStepInto())
499         LineStr = "NSI";
500       else
501         LineStr = utostr(Line.getStartLine());
502       char Statement = Line.isStatement() ? ' ' : '!';
503       P.format("{0} {1:X-} {2} ",
504                fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
505                fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
506                Statement);
507       ++LineIter;
508       --ItemsLeft;
509     }
510     P.NewLine();
511   }
512 }
513 
514 Error DumpOutputStyle::dumpLines() {
515   printHeader(P, "Lines");
516 
517   uint32_t LastModi = UINT32_MAX;
518   uint32_t LastNameIndex = UINT32_MAX;
519   iterateModuleSubsections<DebugLinesSubsectionRef>(
520       File, P, 4,
521       [this, &LastModi, &LastNameIndex](uint32_t Modi,
522                                         StringsAndChecksumsPrinter &Strings,
523                                         DebugLinesSubsectionRef &Lines) {
524         uint16_t Segment = Lines.header()->RelocSegment;
525         uint32_t Begin = Lines.header()->RelocOffset;
526         uint32_t End = Begin + Lines.header()->CodeSize;
527         for (const auto &Block : Lines) {
528           if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
529             LastModi = Modi;
530             LastNameIndex = Block.NameIndex;
531             Strings.formatFromChecksumsOffset(P, Block.NameIndex);
532           }
533 
534           AutoIndent Indent(P, 2);
535           P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
536           uint32_t Count = Block.LineNumbers.size();
537           if (Lines.hasColumnInfo())
538             P.format("line/column/addr entries = {0}", Count);
539           else
540             P.format("line/addr entries = {0}", Count);
541 
542           P.NewLine();
543           typesetLinesAndColumns(File, P, Begin, Block);
544         }
545       });
546 
547   return Error::success();
548 }
549 
550 Error DumpOutputStyle::dumpInlineeLines() {
551   printHeader(P, "Inlinee Lines");
552 
553   iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
554       File, P, 2,
555       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
556              DebugInlineeLinesSubsectionRef &Lines) {
557         P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
558         for (const auto &Entry : Lines) {
559           P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
560                        fmtle(Entry.Header->SourceLineNum));
561           Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
562         }
563         P.NewLine();
564       });
565 
566   return Error::success();
567 }
568 
569 Error DumpOutputStyle::dumpXmi() {
570   printHeader(P, "Cross Module Imports");
571   iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
572       File, P, 2,
573       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
574              DebugCrossModuleImportsSubsectionRef &Imports) {
575         P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
576 
577         for (const auto &Xmi : Imports) {
578           auto ExpectedModule =
579               Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
580           StringRef Module;
581           SmallString<32> ModuleStorage;
582           if (!ExpectedModule) {
583             Module = "(unknown module)";
584             consumeError(ExpectedModule.takeError());
585           } else
586             Module = *ExpectedModule;
587           if (Module.size() > 32) {
588             ModuleStorage = "...";
589             ModuleStorage += Module.take_back(32 - 3);
590             Module = ModuleStorage;
591           }
592           std::vector<std::string> TIs;
593           for (const auto I : Xmi.Imports)
594             TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
595           std::string Result =
596               typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
597           P.formatLine("{0,+32} | {1}", Module, Result);
598         }
599       });
600 
601   return Error::success();
602 }
603 
604 Error DumpOutputStyle::dumpXme() {
605   printHeader(P, "Cross Module Exports");
606 
607   iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
608       File, P, 2,
609       [this](uint32_t Modi, StringsAndChecksumsPrinter &Strings,
610              DebugCrossModuleExportsSubsectionRef &Exports) {
611         P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
612         for (const auto &Export : Exports) {
613           P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
614                        TypeIndex(Export.Global));
615         }
616       });
617 
618   return Error::success();
619 }
620 
621 Error DumpOutputStyle::dumpStringTable() {
622   printHeader(P, "String Table");
623 
624   AutoIndent Indent(P);
625   auto IS = File.getStringTable();
626   if (!IS) {
627     P.formatLine("Not present in file");
628     consumeError(IS.takeError());
629     return Error::success();
630   }
631 
632   if (IS->name_ids().empty()) {
633     P.formatLine("Empty");
634     return Error::success();
635   }
636 
637   auto MaxID = std::max_element(IS->name_ids().begin(), IS->name_ids().end());
638   uint32_t Digits = NumDigits(*MaxID);
639 
640   P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
641                "String");
642 
643   std::vector<uint32_t> SortedIDs(IS->name_ids().begin(), IS->name_ids().end());
644   std::sort(SortedIDs.begin(), SortedIDs.end());
645   for (uint32_t I : SortedIDs) {
646     auto ES = IS->getStringForID(I);
647     llvm::SmallString<32> Str;
648     if (!ES) {
649       consumeError(ES.takeError());
650       Str = "Error reading string";
651     } else if (!ES->empty()) {
652       Str.append("'");
653       Str.append(*ES);
654       Str.append("'");
655     }
656 
657     if (!Str.empty())
658       P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits), Str);
659   }
660   return Error::success();
661 }
662 
663 static void buildDepSet(LazyRandomTypeCollection &Types,
664                         ArrayRef<TypeIndex> Indices,
665                         std::map<TypeIndex, CVType> &DepSet) {
666   SmallVector<TypeIndex, 4> DepList;
667   for (const auto &I : Indices) {
668     TypeIndex TI(I);
669     if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
670       continue;
671 
672     CVType Type = Types.getType(TI);
673     DepSet[TI] = Type;
674     codeview::discoverTypeIndices(Type, DepList);
675     buildDepSet(Types, DepList, DepSet);
676   }
677 }
678 
679 static void dumpFullTypeStream(LinePrinter &Printer,
680                                LazyRandomTypeCollection &Types,
681                                TpiStream &Stream, bool Bytes, bool Extras) {
682   Printer.formatLine("Showing {0:N} records", Stream.getNumTypeRecords());
683   uint32_t Width =
684       NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
685 
686   MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
687                            Stream.getNumHashBuckets(), Stream.getHashValues());
688 
689   if (auto EC = codeview::visitTypeStream(Types, V)) {
690     Printer.formatLine("An error occurred dumping type records: {0}",
691                        toString(std::move(EC)));
692   }
693 }
694 
695 static void dumpPartialTypeStream(LinePrinter &Printer,
696                                   LazyRandomTypeCollection &Types,
697                                   TpiStream &Stream, ArrayRef<TypeIndex> TiList,
698                                   bool Bytes, bool Extras, bool Deps) {
699   uint32_t Width =
700       NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
701 
702   MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
703                            Stream.getNumHashBuckets(), Stream.getHashValues());
704 
705   if (opts::dump::DumpTypeDependents) {
706     // If we need to dump all dependents, then iterate each index and find
707     // all dependents, adding them to a map ordered by TypeIndex.
708     std::map<TypeIndex, CVType> DepSet;
709     buildDepSet(Types, TiList, DepSet);
710 
711     Printer.formatLine(
712         "Showing {0:N} records and their dependents ({1:N} records total)",
713         TiList.size(), DepSet.size());
714 
715     for (auto &Dep : DepSet) {
716       if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
717         Printer.formatLine("An error occurred dumping type record {0}: {1}",
718                            Dep.first, toString(std::move(EC)));
719     }
720   } else {
721     Printer.formatLine("Showing {0:N} records.", TiList.size());
722 
723     for (const auto &I : TiList) {
724       TypeIndex TI(I);
725       CVType Type = Types.getType(TI);
726       if (auto EC = codeview::visitTypeRecord(Type, TI, V))
727         Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
728                            toString(std::move(EC)));
729     }
730   }
731 }
732 
733 Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
734   assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
735 
736   bool Present = false;
737   bool DumpTypes = false;
738   bool DumpBytes = false;
739   bool DumpExtras = false;
740   std::vector<uint32_t> Indices;
741   if (StreamIdx == StreamTPI) {
742     printHeader(P, "Types (TPI Stream)");
743     Present = File.hasPDBTpiStream();
744     DumpTypes = opts::dump::DumpTypes;
745     DumpBytes = opts::dump::DumpTypeData;
746     DumpExtras = opts::dump::DumpTypeExtras;
747     Indices.assign(opts::dump::DumpTypeIndex.begin(),
748                    opts::dump::DumpTypeIndex.end());
749   } else if (StreamIdx == StreamIPI) {
750     printHeader(P, "Types (IPI Stream)");
751     Present = File.hasPDBIpiStream();
752     DumpTypes = opts::dump::DumpIds;
753     DumpBytes = opts::dump::DumpIdData;
754     DumpExtras = opts::dump::DumpIdExtras;
755     Indices.assign(opts::dump::DumpIdIndex.begin(),
756                    opts::dump::DumpIdIndex.end());
757   }
758 
759   AutoIndent Indent(P);
760   if (!Present) {
761     P.formatLine("Stream not present");
762     return Error::success();
763   }
764 
765   ExitOnError Err("Unexpected error processing types: ");
766 
767   auto &Stream = Err((StreamIdx == StreamTPI) ? File.getPDBTpiStream()
768                                               : File.getPDBIpiStream());
769 
770   auto &Types = Err(initializeTypes(StreamIdx));
771 
772   if (DumpTypes || !Indices.empty()) {
773     if (Indices.empty())
774       dumpFullTypeStream(P, Types, Stream, DumpBytes, DumpExtras);
775     else {
776       std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
777       dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
778                             opts::dump::DumpTypeDependents);
779     }
780   }
781 
782   if (DumpExtras) {
783     P.NewLine();
784     auto IndexOffsets = Stream.getTypeIndexOffsets();
785     P.formatLine("Type Index Offsets:");
786     for (const auto &IO : IndexOffsets) {
787       AutoIndent Indent2(P);
788       P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
789     }
790 
791     P.NewLine();
792     P.formatLine("Hash Adjusters:");
793     auto &Adjusters = Stream.getHashAdjusters();
794     auto &Strings = Err(File.getStringTable());
795     for (const auto &A : Adjusters) {
796       AutoIndent Indent2(P);
797       auto ExpectedStr = Strings.getStringForID(A.first);
798       TypeIndex TI(A.second);
799       if (ExpectedStr)
800         P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
801       else {
802         P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
803         consumeError(ExpectedStr.takeError());
804       }
805     }
806   }
807   return Error::success();
808 }
809 
810 Expected<codeview::LazyRandomTypeCollection &>
811 DumpOutputStyle::initializeTypes(uint32_t SN) {
812   auto &TypeCollection = (SN == StreamTPI) ? TpiTypes : IpiTypes;
813   auto Tpi =
814       (SN == StreamTPI) ? File.getPDBTpiStream() : File.getPDBIpiStream();
815   if (!Tpi)
816     return Tpi.takeError();
817 
818   if (!TypeCollection) {
819     auto &Types = Tpi->typeArray();
820     uint32_t Count = Tpi->getNumTypeRecords();
821     auto Offsets = Tpi->getTypeIndexOffsets();
822     TypeCollection =
823         llvm::make_unique<LazyRandomTypeCollection>(Types, Count, Offsets);
824   }
825 
826   return *TypeCollection;
827 }
828 
829 Error DumpOutputStyle::dumpModuleSyms() {
830   printHeader(P, "Symbols");
831 
832   AutoIndent Indent(P);
833   if (!File.hasPDBDbiStream()) {
834     P.formatLine("DBI Stream not present");
835     return Error::success();
836   }
837 
838   ExitOnError Err("Unexpected error processing symbols: ");
839 
840   auto &Ids = Err(initializeTypes(StreamIPI));
841   auto &Types = Err(initializeTypes(StreamTPI));
842 
843   iterateModules(
844       File, P, 2, [&](uint32_t I, StringsAndChecksumsPrinter &Strings) {
845         auto ExpectedModS = getModuleDebugStream(File, I);
846         if (!ExpectedModS) {
847           P.formatLine("Error loading module stream {0}.  {1}", I,
848                        toString(ExpectedModS.takeError()));
849           return;
850         }
851 
852         ModuleDebugStreamRef &ModS = *ExpectedModS;
853 
854         SymbolVisitorCallbackPipeline Pipeline;
855         SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
856         MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids,
857                                    Types);
858 
859         Pipeline.addCallbackToPipeline(Deserializer);
860         Pipeline.addCallbackToPipeline(Dumper);
861         CVSymbolVisitor Visitor(Pipeline);
862         auto SS = ModS.getSymbolsSubstream();
863         if (auto EC =
864                 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
865           P.formatLine("Error while processing symbol records.  {0}",
866                        toString(std::move(EC)));
867           return;
868         }
869       });
870   return Error::success();
871 }
872 
873 Error DumpOutputStyle::dumpGlobals() {
874   printHeader(P, "Global Symbols");
875   AutoIndent Indent(P);
876   if (!File.hasPDBGlobalsStream()) {
877     P.formatLine("Globals stream not present");
878     return Error::success();
879   }
880   ExitOnError Err("Error dumping globals stream: ");
881   auto &Globals = Err(File.getPDBGlobalsStream());
882 
883   const GSIHashTable &Table = Globals.getGlobalsTable();
884   Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
885   return Error::success();
886 }
887 
888 Error DumpOutputStyle::dumpPublics() {
889   printHeader(P, "Public Symbols");
890   AutoIndent Indent(P);
891   if (!File.hasPDBPublicsStream()) {
892     P.formatLine("Publics stream not present");
893     return Error::success();
894   }
895   ExitOnError Err("Error dumping publics stream: ");
896   auto &Publics = Err(File.getPDBPublicsStream());
897 
898   const GSIHashTable &PublicsTable = Publics.getPublicsTable();
899   if (opts::dump::DumpPublicExtras) {
900     P.printLine("Publics Header");
901     AutoIndent Indent(P);
902     P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
903                  formatSegmentOffset(Publics.getThunkTableSection(),
904                                      Publics.getThunkTableOffset()));
905   }
906   Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
907 
908   // Skip the rest if we aren't dumping extras.
909   if (!opts::dump::DumpPublicExtras)
910     return Error::success();
911 
912   P.formatLine("Address Map");
913   {
914     // These are offsets into the publics stream sorted by secidx:secrel.
915     AutoIndent Indent2(P);
916     for (uint32_t Addr : Publics.getAddressMap())
917       P.formatLine("off = {0}", Addr);
918   }
919 
920   // The thunk map is optional debug info used for ILT thunks.
921   if (!Publics.getThunkMap().empty()) {
922     P.formatLine("Thunk Map");
923     AutoIndent Indent2(P);
924     for (uint32_t Addr : Publics.getThunkMap())
925       P.formatLine("{0:x8}", Addr);
926   }
927 
928   // The section offsets table appears to be empty when incremental linking
929   // isn't in use.
930   if (!Publics.getSectionOffsets().empty()) {
931     P.formatLine("Section Offsets");
932     AutoIndent Indent2(P);
933     for (const SectionOffset &SO : Publics.getSectionOffsets())
934       P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
935   }
936 
937   return Error::success();
938 }
939 
940 Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
941                                           bool HashExtras) {
942   auto ExpectedSyms = File.getPDBSymbolStream();
943   if (!ExpectedSyms)
944     return ExpectedSyms.takeError();
945   auto ExpectedTypes = initializeTypes(StreamTPI);
946   if (!ExpectedTypes)
947     return ExpectedTypes.takeError();
948   auto ExpectedIds = initializeTypes(StreamIPI);
949   if (!ExpectedIds)
950     return ExpectedIds.takeError();
951 
952   if (HashExtras) {
953     P.printLine("GSI Header");
954     AutoIndent Indent(P);
955     P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
956                  Table.getVerSignature(), Table.getVerHeader(),
957                  Table.getHashRecordSize(), Table.getNumBuckets());
958   }
959 
960   {
961     P.printLine("Records");
962     SymbolVisitorCallbackPipeline Pipeline;
963     SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
964     MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, *ExpectedIds,
965                                *ExpectedTypes);
966 
967     Pipeline.addCallbackToPipeline(Deserializer);
968     Pipeline.addCallbackToPipeline(Dumper);
969     CVSymbolVisitor Visitor(Pipeline);
970 
971     BinaryStreamRef SymStream =
972         ExpectedSyms->getSymbolArray().getUnderlyingStream();
973     for (uint32_t PubSymOff : Table) {
974       Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
975       if (!Sym)
976         return Sym.takeError();
977       if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
978         return E;
979     }
980   }
981 
982   // Return early if we aren't dumping public hash table and address map info.
983   if (!HashExtras)
984     return Error::success();
985 
986   P.formatLine("Hash Entries");
987   {
988     AutoIndent Indent2(P);
989     for (const PSHashRecord &HR : Table.HashRecords)
990       P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
991                    uint32_t(HR.CRef));
992   }
993 
994   // FIXME: Dump the bitmap.
995 
996   P.formatLine("Hash Buckets");
997   {
998     AutoIndent Indent2(P);
999     for (uint32_t Hash : Table.HashBuckets)
1000       P.formatLine("{0:x8}", Hash);
1001   }
1002 
1003   return Error::success();
1004 }
1005 
1006 static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1007                                               OMFSegDescFlags Flags) {
1008   std::vector<std::string> Opts;
1009   if (Flags == OMFSegDescFlags::None)
1010     return "none";
1011 
1012   PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1013   PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1014   PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1015   PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1016   PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1017   PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1018   PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
1019   return typesetItemList(Opts, IndentLevel, 4, " | ");
1020 }
1021 
1022 Error DumpOutputStyle::dumpSectionHeaders() {
1023   dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1024   dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1025   return Error::success();
1026 }
1027 
1028 static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1029                           ArrayRef<llvm::object::coff_section>>>
1030 loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1031   if (!File.hasPDBDbiStream())
1032     return make_error<StringError>(
1033         "Section headers require a DBI Stream, which could not be loaded",
1034         inconvertibleErrorCode());
1035 
1036   auto &Dbi = cantFail(File.getPDBDbiStream());
1037   uint32_t SI = Dbi.getDebugStreamIndex(Type);
1038 
1039   if (SI == kInvalidStreamIndex)
1040     return make_error<StringError>(
1041         "PDB does not contain the requested image section header type",
1042         inconvertibleErrorCode());
1043 
1044   auto Stream = MappedBlockStream::createIndexedStream(
1045       File.getMsfLayout(), File.getMsfBuffer(), SI, File.getAllocator());
1046   if (!Stream)
1047     return make_error<StringError>("Could not load the required stream data",
1048                                    inconvertibleErrorCode());
1049 
1050   ArrayRef<object::coff_section> Headers;
1051   if (Stream->getLength() % sizeof(object::coff_section) != 0)
1052     return make_error<StringError>(
1053         "Section header array size is not a multiple of section header size",
1054         inconvertibleErrorCode());
1055 
1056   uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1057   BinaryStreamReader Reader(*Stream);
1058   cantFail(Reader.readArray(Headers, NumHeaders));
1059   return std::make_pair(std::move(Stream), Headers);
1060 }
1061 
1062 void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1063   printHeader(P, Label);
1064   ExitOnError Err("Error dumping publics stream: ");
1065 
1066   AutoIndent Indent(P);
1067   std::unique_ptr<MappedBlockStream> Stream;
1068   ArrayRef<object::coff_section> Headers;
1069   auto ExpectedHeaders = loadSectionHeaders(File, Type);
1070   if (!ExpectedHeaders) {
1071     P.printLine(toString(ExpectedHeaders.takeError()));
1072     return;
1073   }
1074   std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1075 
1076   uint32_t I = 1;
1077   for (const auto &Header : Headers) {
1078     P.NewLine();
1079     P.formatLine("SECTION HEADER #{0}", I);
1080     P.formatLine("{0,8} name", Header.Name);
1081     P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1082     P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1083     P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1084     P.formatLine("{0,8:X-} file pointer to raw data",
1085                  uint32_t(Header.PointerToRawData));
1086     P.formatLine("{0,8:X-} file pointer to relocation table",
1087                  uint32_t(Header.PointerToRelocations));
1088     P.formatLine("{0,8:X-} file pointer to line numbers",
1089                  uint32_t(Header.PointerToLinenumbers));
1090     P.formatLine("{0,8:X-} number of relocations",
1091                  uint32_t(Header.NumberOfRelocations));
1092     P.formatLine("{0,8:X-} number of line numbers",
1093                  uint32_t(Header.NumberOfLinenumbers));
1094     P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1095     AutoIndent IndentMore(P, 9);
1096     P.formatLine("{0}", formatSectionCharacteristics(
1097                             P.getIndentLevel(), Header.Characteristics, 1, ""));
1098     ++I;
1099   }
1100   return;
1101 }
1102 
1103 std::vector<std::string> getSectionNames(PDBFile &File) {
1104   auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1105   if (!ExpectedHeaders)
1106     return {};
1107 
1108   std::unique_ptr<MappedBlockStream> Stream;
1109   ArrayRef<object::coff_section> Headers;
1110   std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1111   std::vector<std::string> Names;
1112   for (const auto &H : Headers)
1113     Names.push_back(H.Name);
1114   return Names;
1115 }
1116 
1117 Error DumpOutputStyle::dumpSectionContribs() {
1118   printHeader(P, "Section Contributions");
1119   ExitOnError Err("Error dumping publics stream: ");
1120 
1121   AutoIndent Indent(P);
1122   if (!File.hasPDBDbiStream()) {
1123     P.formatLine(
1124         "Section contribs require a DBI Stream, which could not be loaded");
1125     return Error::success();
1126   }
1127 
1128   auto &Dbi = Err(File.getPDBDbiStream());
1129 
1130   class Visitor : public ISectionContribVisitor {
1131   public:
1132     Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1133       auto Max = std::max_element(
1134           Names.begin(), Names.end(),
1135           [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1136       MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1137     }
1138     void visit(const SectionContrib &SC) override {
1139       assert(SC.ISect > 0);
1140       std::string NameInsert;
1141       if (SC.ISect < Names.size()) {
1142         StringRef SectionName = Names[SC.ISect - 1];
1143         NameInsert = formatv("[{0}]", SectionName).str();
1144       } else
1145         NameInsert = "[???]";
1146       P.formatLine("SC{5}  | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1147                    "crc = {4}",
1148                    formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1149                    fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1150                    fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1151       AutoIndent Indent(P, MaxNameLen + 2);
1152       P.formatLine("      {0}",
1153                    formatSectionCharacteristics(P.getIndentLevel() + 6,
1154                                                 SC.Characteristics, 3, " | "));
1155     }
1156     void visit(const SectionContrib2 &SC) override {
1157       P.formatLine(
1158           "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1159           "crc = {4}, coff section = {5}",
1160           formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1161           fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1162           fmtle(SC.ISectCoff));
1163       P.formatLine("      {0}", formatSectionCharacteristics(
1164                                     P.getIndentLevel() + 6,
1165                                     SC.Base.Characteristics, 3, " | "));
1166     }
1167 
1168   private:
1169     LinePrinter &P;
1170     uint32_t MaxNameLen;
1171     ArrayRef<std::string> Names;
1172   };
1173 
1174   std::vector<std::string> Names = getSectionNames(File);
1175   Visitor V(P, makeArrayRef(Names));
1176   Dbi.visitSectionContributions(V);
1177   return Error::success();
1178 }
1179 
1180 Error DumpOutputStyle::dumpSectionMap() {
1181   printHeader(P, "Section Map");
1182   ExitOnError Err("Error dumping section map: ");
1183 
1184   AutoIndent Indent(P);
1185   if (!File.hasPDBDbiStream()) {
1186     P.formatLine("Dumping the section map requires a DBI Stream, which could "
1187                  "not be loaded");
1188     return Error::success();
1189   }
1190 
1191   auto &Dbi = Err(File.getPDBDbiStream());
1192 
1193   uint32_t I = 0;
1194   for (auto &M : Dbi.getSectionMap()) {
1195     P.formatLine(
1196         "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
1197         fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1198     P.formatLine("               class = {0}, offset = {1}, size = {2}",
1199                  fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1200     P.formatLine("               flags = {0}",
1201                  formatSegMapDescriptorFlag(
1202                      P.getIndentLevel() + 13,
1203                      static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1204     ++I;
1205   }
1206   return Error::success();
1207 }
1208