blob: 365386f0a27dbaab10689a52a1e7dd19adb307cf [file] [log] [blame]
Zachary Turner7df69952017-06-22 20:57:39 +00001//===- DumpOutputStyle.cpp ------------------------------------ *- C++ --*-===//
Zachary Turner63055452017-06-15 22:24:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Zachary Turner7df69952017-06-22 20:57:39 +000010#include "DumpOutputStyle.h"
Zachary Turner63055452017-06-15 22:24:24 +000011
Zachary Turner63055452017-06-15 22:24:24 +000012#include "FormatUtil.h"
Zachary Turnerabb17cc2017-09-01 20:06:56 +000013#include "InputFile.h"
Zachary Turner63055452017-06-15 22:24:24 +000014#include "MinimalSymbolDumper.h"
15#include "MinimalTypeDumper.h"
16#include "StreamUtil.h"
17#include "llvm-pdbutil.h"
18
Zachary Turnerf2872b92017-06-15 23:59:56 +000019#include "llvm/ADT/STLExtras.h"
Zachary Turner63055452017-06-15 22:24:24 +000020#include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h"
21#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
22#include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
23#include "llvm/DebugInfo/CodeView/DebugCrossExSubsection.h"
24#include "llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h"
Zachary Turner63055452017-06-15 22:24:24 +000025#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
26#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
27#include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
Zachary Turner63055452017-06-15 22:24:24 +000028#include "llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h"
Zachary Turner63055452017-06-15 22:24:24 +000029#include "llvm/DebugInfo/CodeView/Formatters.h"
30#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
31#include "llvm/DebugInfo/CodeView/Line.h"
32#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner63055452017-06-15 22:24:24 +000033#include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h"
34#include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
Zachary Turner376d4372017-12-05 23:58:18 +000035#include "llvm/DebugInfo/CodeView/TypeHashing.h"
Zachary Turner02a26772017-06-30 18:15:47 +000036#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Zachary Turner63055452017-06-15 22:24:24 +000037#include "llvm/DebugInfo/MSF/MappedBlockStream.h"
38#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h"
39#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
Zachary Turner63055452017-06-15 22:24:24 +000040#include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
41#include "llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h"
42#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
43#include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
44#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
45#include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
46#include "llvm/DebugInfo/PDB/Native/RawError.h"
Zachary Turner376d4372017-12-05 23:58:18 +000047#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
Zachary Turner63055452017-06-15 22:24:24 +000048#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
49#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
Zachary Turner63055452017-06-15 22:24:24 +000050#include "llvm/Object/COFF.h"
51#include "llvm/Support/BinaryStreamReader.h"
52#include "llvm/Support/FormatAdapters.h"
53#include "llvm/Support/FormatVariadic.h"
54
Michael Zolotukhin67b04bd2017-12-13 22:21:02 +000055#include <cctype>
Zachary Turner63055452017-06-15 22:24:24 +000056
57using namespace llvm;
58using namespace llvm::codeview;
59using namespace llvm::msf;
60using namespace llvm::pdb;
61
Zachary Turnerabb17cc2017-09-01 20:06:56 +000062DumpOutputStyle::DumpOutputStyle(InputFile &File)
Zachary Turner63055452017-06-15 22:24:24 +000063 : File(File), P(2, false, outs()) {}
64
Zachary Turnerabb17cc2017-09-01 20:06:56 +000065PDBFile &DumpOutputStyle::getPdb() { return File.pdb(); }
66object::COFFObjectFile &DumpOutputStyle::getObj() { return File.obj(); }
67
Zachary Turner7df69952017-06-22 20:57:39 +000068Error DumpOutputStyle::dump() {
69 if (opts::dump::DumpSummary) {
Zachary Turner63055452017-06-15 22:24:24 +000070 if (auto EC = dumpFileSummary())
71 return EC;
72 P.NewLine();
73 }
74
Zachary Turner7df69952017-06-22 20:57:39 +000075 if (opts::dump::DumpStreams) {
Zachary Turner63055452017-06-15 22:24:24 +000076 if (auto EC = dumpStreamSummary())
77 return EC;
78 P.NewLine();
79 }
80
Zachary Turnerabb17cc2017-09-01 20:06:56 +000081 if (opts::dump::DumpSymbolStats) {
Zachary Turner99c69822017-08-31 20:43:22 +000082 if (auto EC = dumpSymbolStats())
83 return EC;
84 P.NewLine();
85 }
86
Zachary Turnerabb17cc2017-09-01 20:06:56 +000087 if (opts::dump::DumpUdtStats) {
Zachary Turner99c69822017-08-31 20:43:22 +000088 if (auto EC = dumpUdtStats())
Zachary Turnerd1de2f42017-08-21 14:53:25 +000089 return EC;
90 P.NewLine();
91 }
92
Zachary Turner7df69952017-06-22 20:57:39 +000093 if (opts::dump::DumpStringTable) {
Zachary Turner63055452017-06-15 22:24:24 +000094 if (auto EC = dumpStringTable())
95 return EC;
96 P.NewLine();
97 }
98
Zachary Turner7df69952017-06-22 20:57:39 +000099 if (opts::dump::DumpModules) {
Zachary Turner63055452017-06-15 22:24:24 +0000100 if (auto EC = dumpModules())
101 return EC;
102 }
103
Zachary Turner7df69952017-06-22 20:57:39 +0000104 if (opts::dump::DumpModuleFiles) {
Zachary Turner0e327d02017-06-15 23:12:41 +0000105 if (auto EC = dumpModuleFiles())
106 return EC;
107 }
108
Zachary Turner7df69952017-06-22 20:57:39 +0000109 if (opts::dump::DumpLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000110 if (auto EC = dumpLines())
111 return EC;
112 }
113
Zachary Turner7df69952017-06-22 20:57:39 +0000114 if (opts::dump::DumpInlineeLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000115 if (auto EC = dumpInlineeLines())
116 return EC;
117 }
118
Zachary Turner7df69952017-06-22 20:57:39 +0000119 if (opts::dump::DumpXmi) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000120 if (auto EC = dumpXmi())
121 return EC;
122 }
123
Zachary Turner7df69952017-06-22 20:57:39 +0000124 if (opts::dump::DumpXme) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000125 if (auto EC = dumpXme())
126 return EC;
127 }
128
Zachary Turner376d4372017-12-05 23:58:18 +0000129 if (File.isObj()) {
130 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
131 opts::dump::DumpTypeExtras)
132 if (auto EC = dumpTypesFromObjectFile())
133 return EC;
134 } else {
135 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
136 opts::dump::DumpTypeExtras) {
137 if (auto EC = dumpTpiStream(StreamTPI))
138 return EC;
139 }
Zachary Turner63055452017-06-15 22:24:24 +0000140
Zachary Turner376d4372017-12-05 23:58:18 +0000141 if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
142 opts::dump::DumpIdExtras) {
143 if (auto EC = dumpTpiStream(StreamIPI))
144 return EC;
145 }
Zachary Turner63055452017-06-15 22:24:24 +0000146 }
147
Reid Kleckner14d90fd2017-07-26 00:40:36 +0000148 if (opts::dump::DumpGlobals) {
149 if (auto EC = dumpGlobals())
150 return EC;
151 }
152
Zachary Turner7df69952017-06-22 20:57:39 +0000153 if (opts::dump::DumpPublics) {
Zachary Turner63055452017-06-15 22:24:24 +0000154 if (auto EC = dumpPublics())
155 return EC;
156 }
157
Zachary Turner7df69952017-06-22 20:57:39 +0000158 if (opts::dump::DumpSymbols) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000159 auto EC = File.isPdb() ? dumpModuleSymsForPdb() : dumpModuleSymsForObj();
160 if (EC)
Zachary Turner63055452017-06-15 22:24:24 +0000161 return EC;
162 }
163
Zachary Turnerfb1cd502017-08-04 20:02:38 +0000164 if (opts::dump::DumpSectionHeaders) {
165 if (auto EC = dumpSectionHeaders())
166 return EC;
167 }
168
Zachary Turner7df69952017-06-22 20:57:39 +0000169 if (opts::dump::DumpSectionContribs) {
Zachary Turner63055452017-06-15 22:24:24 +0000170 if (auto EC = dumpSectionContribs())
171 return EC;
172 }
173
Zachary Turner7df69952017-06-22 20:57:39 +0000174 if (opts::dump::DumpSectionMap) {
Zachary Turner63055452017-06-15 22:24:24 +0000175 if (auto EC = dumpSectionMap())
176 return EC;
177 }
178
179 return Error::success();
180}
181
182static void printHeader(LinePrinter &P, const Twine &S) {
183 P.NewLine();
184 P.formatLine("{0,=60}", S);
185 P.formatLine("{0}", fmt_repeat('=', 60));
186}
187
Zachary Turner7df69952017-06-22 20:57:39 +0000188Error DumpOutputStyle::dumpFileSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000189 printHeader(P, "Summary");
190
Reid Klecknerdd853e52017-07-27 23:13:18 +0000191 ExitOnError Err("Invalid PDB Format: ");
Zachary Turner63055452017-06-15 22:24:24 +0000192
193 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000194 if (File.isObj()) {
195 P.formatLine("Dumping File summary is not valid for object files");
196 return Error::success();
197 }
Zachary Turner63055452017-06-15 22:24:24 +0000198
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000199 P.formatLine("Block Size: {0}", getPdb().getBlockSize());
200 P.formatLine("Number of blocks: {0}", getPdb().getBlockCount());
201 P.formatLine("Number of streams: {0}", getPdb().getNumStreams());
202
203 auto &PS = Err(getPdb().getPDBInfoStream());
Zachary Turner63055452017-06-15 22:24:24 +0000204 P.formatLine("Signature: {0}", PS.getSignature());
205 P.formatLine("Age: {0}", PS.getAge());
206 P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
207 P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000208 P.formatLine("Has Debug Info: {0}", getPdb().hasPDBDbiStream());
209 P.formatLine("Has Types: {0}", getPdb().hasPDBTpiStream());
210 P.formatLine("Has IDs: {0}", getPdb().hasPDBIpiStream());
211 P.formatLine("Has Globals: {0}", getPdb().hasPDBGlobalsStream());
212 P.formatLine("Has Publics: {0}", getPdb().hasPDBPublicsStream());
213 if (getPdb().hasPDBDbiStream()) {
214 auto &DBI = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +0000215 P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
216 P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
217 P.formatLine("Is stripped: {0}", DBI.isStripped());
218 }
219
220 return Error::success();
221}
222
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000223static StatCollection getSymbolStats(const SymbolGroup &SG,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000224 StatCollection &CumulativeStats) {
225 StatCollection Stats;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000226 if (SG.getFile().isPdb()) {
227 // For PDB files, all symbols are packed into one stream.
228 for (const auto &S : SG.getPdbModuleStream().symbols(nullptr)) {
229 Stats.update(S.kind(), S.length());
230 CumulativeStats.update(S.kind(), S.length());
231 }
232 return Stats;
233 }
234
235 for (const auto &SS : SG.getDebugSubsections()) {
236 // For object files, all symbols are spread across multiple Symbol
237 // subsections of a given .debug$S section.
238 if (SS.kind() != DebugSubsectionKind::Symbols)
239 continue;
240 DebugSymbolsSubsectionRef Symbols;
241 BinaryStreamReader Reader(SS.getRecordData());
242 cantFail(Symbols.initialize(Reader));
243 for (const auto &S : Symbols) {
244 Stats.update(S.kind(), S.length());
245 CumulativeStats.update(S.kind(), S.length());
246 }
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000247 }
248 return Stats;
249}
250
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000251static StatCollection getChunkStats(const SymbolGroup &SG,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000252 StatCollection &CumulativeStats) {
253 StatCollection Stats;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000254 for (const auto &Chunk : SG.getDebugSubsections()) {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000255 Stats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
256 CumulativeStats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
257 }
258 return Stats;
259}
260
261static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
262 return formatChunkKind(K, false);
263}
264
265static inline std::string formatModuleDetailKind(SymbolKind K) {
266 return formatSymbolKind(K);
267}
268
269template <typename Kind>
270static void printModuleDetailStats(LinePrinter &P, StringRef Label,
271 const StatCollection &Stats) {
272 P.NewLine();
273 P.formatLine(" {0}", Label);
274 AutoIndent Indent(P);
275 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
276 Stats.Totals.Count, Stats.Totals.Size);
277 P.formatLine("{0}", fmt_repeat('-', 74));
278 for (const auto &K : Stats.Individual) {
279 std::string KindName = formatModuleDetailKind(Kind(K.first));
280 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName,
281 K.second.Count, K.second.Size);
282 }
283}
284
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000285static bool isMyCode(const SymbolGroup &Group) {
286 if (Group.getFile().isObj())
287 return true;
288
289 StringRef Name = Group.name();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000290 if (Name.startswith("Import:"))
291 return false;
292 if (Name.endswith_lower(".dll"))
293 return false;
294 if (Name.equals_lower("* linker *"))
295 return false;
296 if (Name.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
297 return false;
298 if (Name.startswith_lower("f:\\dd\\vctools\\crt"))
299 return false;
300 return true;
301}
302
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000303static bool shouldDumpSymbolGroup(uint32_t Idx, const SymbolGroup &Group) {
304 if (opts::dump::JustMyCode && !isMyCode(Group))
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000305 return false;
306
307 // If the arg was not specified on the command line, always dump all modules.
308 if (opts::dump::DumpModi.getNumOccurrences() == 0)
309 return true;
310
311 // Otherwise, only dump if this is the same module specified.
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000312 return (opts::dump::DumpModi == Idx);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000313}
314
Zachary Turner7df69952017-06-22 20:57:39 +0000315Error DumpOutputStyle::dumpStreamSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000316 printHeader(P, "Streams");
317
Zachary Turner63055452017-06-15 22:24:24 +0000318 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000319 if (File.isObj()) {
320 P.formatLine("Dumping streams is not valid for object files");
321 return Error::success();
322 }
323
324 if (StreamPurposes.empty())
325 discoverStreamPurposes(getPdb(), StreamPurposes);
326
327 uint32_t StreamCount = getPdb().getNumStreams();
328 uint32_t MaxStreamSize = getPdb().getMaxStreamSize();
Zachary Turner63055452017-06-15 22:24:24 +0000329
330 for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
331 P.formatLine(
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000332 "Stream {0} ({1} bytes): [{2}]",
Zachary Turner63055452017-06-15 22:24:24 +0000333 fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000334 fmt_align(getPdb().getStreamByteSize(StreamIdx), AlignStyle::Right,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000335 NumDigits(MaxStreamSize)),
336 StreamPurposes[StreamIdx].getLongName());
337
Zachary Turner5f098522017-06-23 20:28:14 +0000338 if (opts::dump::DumpStreamBlocks) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000339 auto Blocks = getPdb().getStreamBlockList(StreamIdx);
Zachary Turner5f098522017-06-23 20:28:14 +0000340 std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
341 P.formatLine(" {0} Blocks: [{1}]",
342 fmt_repeat(' ', NumDigits(StreamCount)),
343 make_range(BV.begin(), BV.end()));
344 }
Zachary Turner63055452017-06-15 22:24:24 +0000345 }
346
347 return Error::success();
348}
349
Zachary Turner0e327d02017-06-15 23:12:41 +0000350static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
351 uint32_t Index) {
Reid Klecknerdd853e52017-07-27 23:13:18 +0000352 ExitOnError Err("Unexpected error: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000353
354 auto &Dbi = Err(File.getPDBDbiStream());
355 const auto &Modules = Dbi.modules();
356 auto Modi = Modules.getModuleDescriptor(Index);
357
358 uint16_t ModiStream = Modi.getModuleStreamIndex();
359 if (ModiStream == kInvalidStreamIndex)
360 return make_error<RawError>(raw_error_code::no_stream,
361 "Module stream not present");
362
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000363 auto ModStreamData = File.createIndexedStream(ModiStream);
Zachary Turner0e327d02017-06-15 23:12:41 +0000364
365 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
366 if (auto EC = ModS.reload())
367 return make_error<RawError>(raw_error_code::corrupt_file,
368 "Invalid module stream");
369
370 return std::move(ModS);
371}
372
Zachary Turnerf2872b92017-06-15 23:59:56 +0000373template <typename CallbackT>
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000374static void
375iterateOneModule(InputFile &File, const Optional<PrintScope> &HeaderScope,
376 const SymbolGroup &SG, uint32_t Modi, CallbackT Callback) {
377 if (HeaderScope) {
378 HeaderScope->P.formatLine(
379 "Mod {0:4} | `{1}`: ",
380 fmt_align(Modi, AlignStyle::Right, HeaderScope->LabelWidth), SG.name());
381 }
Zachary Turner58699362017-08-03 23:11:52 +0000382
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000383 AutoIndent Indent(HeaderScope);
384 Callback(Modi, SG);
Zachary Turner58699362017-08-03 23:11:52 +0000385}
386
387template <typename CallbackT>
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000388static void iterateSymbolGroups(InputFile &Input,
389 const Optional<PrintScope> &HeaderScope,
390 CallbackT Callback) {
391 AutoIndent Indent(HeaderScope);
Zachary Turnerf2872b92017-06-15 23:59:56 +0000392
Reid Klecknerdd853e52017-07-27 23:13:18 +0000393 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turnerf2872b92017-06-15 23:59:56 +0000394
Zachary Turner58699362017-08-03 23:11:52 +0000395 if (opts::dump::DumpModi.getNumOccurrences() > 0) {
396 assert(opts::dump::DumpModi.getNumOccurrences() == 1);
397 uint32_t Modi = opts::dump::DumpModi;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000398 SymbolGroup SG(&Input, Modi);
399 iterateOneModule(Input, withLabelWidth(HeaderScope, NumDigits(Modi)), SG,
400 Modi, Callback);
Zachary Turner58699362017-08-03 23:11:52 +0000401 return;
402 }
403
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000404 uint32_t I = 0;
405
406 for (const auto &SG : Input.symbol_groups()) {
407 if (shouldDumpSymbolGroup(I, SG))
408 iterateOneModule(Input, withLabelWidth(HeaderScope, NumDigits(I)), SG, I,
409 Callback);
410
411 ++I;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000412 }
413}
414
415template <typename SubsectionT>
416static void iterateModuleSubsections(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000417 InputFile &File, const Optional<PrintScope> &HeaderScope,
418 llvm::function_ref<void(uint32_t, const SymbolGroup &, SubsectionT &)>
Zachary Turnerf2872b92017-06-15 23:59:56 +0000419 Callback) {
420
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000421 iterateSymbolGroups(File, HeaderScope,
422 [&](uint32_t Modi, const SymbolGroup &SG) {
423 for (const auto &SS : SG.getDebugSubsections()) {
424 SubsectionT Subsection;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000425
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000426 if (SS.kind() != Subsection.kind())
427 continue;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000428
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000429 BinaryStreamReader Reader(SS.getRecordData());
430 if (auto EC = Subsection.initialize(Reader))
431 continue;
432 Callback(Modi, SG, Subsection);
433 }
434 });
Zachary Turnerf2872b92017-06-15 23:59:56 +0000435}
436
Zachary Turner7df69952017-06-22 20:57:39 +0000437Error DumpOutputStyle::dumpModules() {
Zachary Turner63055452017-06-15 22:24:24 +0000438 printHeader(P, "Modules");
Zachary Turner63055452017-06-15 22:24:24 +0000439 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000440
441 if (File.isObj()) {
442 P.formatLine("Dumping modules is not supported for object files");
443 return Error::success();
444 }
445
446 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +0000447 P.formatLine("DBI Stream not present");
448 return Error::success();
449 }
450
Reid Klecknerdd853e52017-07-27 23:13:18 +0000451 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner63055452017-06-15 22:24:24 +0000452
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000453 auto &Stream = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +0000454
455 const DbiModuleList &Modules = Stream.modules();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000456 iterateSymbolGroups(
457 File, PrintScope{P, 11}, [&](uint32_t Modi, const SymbolGroup &Strings) {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000458 auto Desc = Modules.getModuleDescriptor(Modi);
459 P.formatLine("Obj: `{0}`: ", Desc.getObjFileName());
460 P.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
461 Desc.getModuleStreamIndex(), Desc.getNumberOfFiles(),
462 Desc.hasECInfo());
463 StringRef PdbFilePath =
464 Err(Stream.getECName(Desc.getPdbFilePathNameIndex()));
465 StringRef SrcFilePath =
466 Err(Stream.getECName(Desc.getSourceFileNameIndex()));
467 P.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
468 Desc.getPdbFilePathNameIndex(), PdbFilePath,
469 Desc.getSourceFileNameIndex(), SrcFilePath);
470 });
Zachary Turner0e327d02017-06-15 23:12:41 +0000471 return Error::success();
472}
473
Zachary Turner7df69952017-06-22 20:57:39 +0000474Error DumpOutputStyle::dumpModuleFiles() {
Zachary Turner0e327d02017-06-15 23:12:41 +0000475 printHeader(P, "Files");
476
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000477 if (File.isObj()) {
478 P.formatLine("Dumping files is not valid for object files");
479 return Error::success();
480 }
481
Reid Klecknerdd853e52017-07-27 23:13:18 +0000482 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000483
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000484 iterateSymbolGroups(File, PrintScope{P, 11},
485 [this, &Err](uint32_t Modi, const SymbolGroup &Strings) {
486 auto &Stream = Err(getPdb().getPDBDbiStream());
Zachary Turner0e327d02017-06-15 23:12:41 +0000487
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000488 const DbiModuleList &Modules = Stream.modules();
489 for (const auto &F : Modules.source_files(Modi)) {
490 Strings.formatFromFileName(P, F);
491 }
492 });
Zachary Turner4e950642017-06-15 23:56:19 +0000493 return Error::success();
494}
495
Zachary Turner99c69822017-08-31 20:43:22 +0000496Error DumpOutputStyle::dumpSymbolStats() {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000497 printHeader(P, "Module Stats");
498
499 ExitOnError Err("Unexpected error processing modules: ");
500
501 StatCollection SymStats;
502 StatCollection ChunkStats;
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000503
Zachary Turner41f07062017-09-01 20:17:20 +0000504 Optional<PrintScope> Scope;
505 if (File.isPdb())
506 Scope.emplace(P, 2);
507
508 iterateSymbolGroups(File, Scope, [&](uint32_t Modi, const SymbolGroup &SG) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000509 StatCollection SS = getSymbolStats(SG, SymStats);
510 StatCollection CS = getChunkStats(SG, ChunkStats);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000511
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000512 if (SG.getFile().isPdb()) {
Zachary Turner41f07062017-09-01 20:17:20 +0000513 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000514 auto Modules = cantFail(File.pdb().getPDBDbiStream()).modules();
515 uint32_t ModCount = Modules.getModuleCount();
516 DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
517 uint32_t StreamIdx = Desc.getModuleStreamIndex();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000518
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000519 if (StreamIdx == kInvalidStreamIndex) {
520 P.formatLine("Mod {0} (debug info not present): [{1}]",
521 fmt_align(Modi, AlignStyle::Right, NumDigits(ModCount)),
522 Desc.getModuleName());
523 return;
524 }
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000525 P.formatLine("Stream {0}, {1} bytes", StreamIdx,
526 getPdb().getStreamByteSize(StreamIdx));
527
528 printModuleDetailStats<SymbolKind>(P, "Symbols", SS);
529 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", CS);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000530 }
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000531 });
532
533 P.printLine(" Summary |");
534 AutoIndent Indent(P, 4);
535 if (SymStats.Totals.Count > 0) {
536 printModuleDetailStats<SymbolKind>(P, "Symbols", SymStats);
537 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", ChunkStats);
538 }
539
540 return Error::success();
541}
542
Zachary Turner99c69822017-08-31 20:43:22 +0000543static bool isValidNamespaceIdentifier(StringRef S) {
544 if (S.empty())
545 return false;
546
547 if (std::isdigit(S[0]))
548 return false;
549
550 return llvm::all_of(S, [](char C) { return std::isalnum(C); });
551}
552
553namespace {
554constexpr uint32_t kNoneUdtKind = 0;
555constexpr uint32_t kSimpleUdtKind = 1;
556constexpr uint32_t kUnknownUdtKind = 2;
557const StringRef NoneLabel("<none type>");
558const StringRef SimpleLabel("<simple type>");
559const StringRef UnknownLabel("<unknown type>");
560
561} // namespace
562
563static StringRef getUdtStatLabel(uint32_t Kind) {
564 if (Kind == kNoneUdtKind)
565 return NoneLabel;
566
567 if (Kind == kSimpleUdtKind)
568 return SimpleLabel;
569
570 if (Kind == kUnknownUdtKind)
571 return UnknownLabel;
572
573 return formatTypeLeafKind(static_cast<TypeLeafKind>(Kind));
574}
575
576static uint32_t getLongestTypeLeafName(const StatCollection &Stats) {
577 size_t L = 0;
578 for (const auto &Stat : Stats.Individual) {
579 StringRef Label = getUdtStatLabel(Stat.first);
580 L = std::max(L, Label.size());
581 }
582 return static_cast<uint32_t>(L);
583}
584
585Error DumpOutputStyle::dumpUdtStats() {
586 printHeader(P, "S_UDT Record Stats");
587
588 StatCollection UdtStats;
589 StatCollection UdtTargetStats;
Zachary Turner99c69822017-08-31 20:43:22 +0000590 AutoIndent Indent(P, 4);
591
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000592 auto &TpiTypes = File.types();
Zachary Turner99c69822017-08-31 20:43:22 +0000593
594 StringMap<StatCollection::Stat> NamespacedStats;
595
Zachary Turner99c69822017-08-31 20:43:22 +0000596 size_t LongestNamespace = 0;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000597 auto HandleOneSymbol = [&](const CVSymbol &Sym) {
Zachary Turner99c69822017-08-31 20:43:22 +0000598 if (Sym.kind() != SymbolKind::S_UDT)
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000599 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000600 UdtStats.update(SymbolKind::S_UDT, Sym.length());
601
602 UDTSym UDT = cantFail(SymbolDeserializer::deserializeAs<UDTSym>(Sym));
603
604 uint32_t Kind = 0;
605 uint32_t RecordSize = 0;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000606
607 if (UDT.Type.isNoneType())
608 Kind = kNoneUdtKind;
609 else if (UDT.Type.isSimple())
610 Kind = kSimpleUdtKind;
611 else if (Optional<CVType> T = TpiTypes.tryGetType(UDT.Type)) {
612 Kind = T->kind();
613 RecordSize = T->length();
614 } else
615 Kind = kUnknownUdtKind;
Zachary Turner99c69822017-08-31 20:43:22 +0000616
617 UdtTargetStats.update(Kind, RecordSize);
618
619 size_t Pos = UDT.Name.find("::");
620 if (Pos == StringRef::npos)
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000621 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000622
623 StringRef Scope = UDT.Name.take_front(Pos);
624 if (Scope.empty() || !isValidNamespaceIdentifier(Scope))
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000625 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000626
627 LongestNamespace = std::max(LongestNamespace, Scope.size());
628 NamespacedStats[Scope].update(RecordSize);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000629 };
630
631 P.NewLine();
632
633 if (File.isPdb()) {
634 if (!getPdb().hasPDBGlobalsStream()) {
635 P.printLine("- Error: globals stream not present");
636 return Error::success();
637 }
638
639 auto &SymbolRecords = cantFail(getPdb().getPDBSymbolStream());
Reid Kleckner145090f2017-10-27 00:45:51 +0000640 auto ExpGlobals = getPdb().getPDBGlobalsStream();
641 if (!ExpGlobals)
642 return ExpGlobals.takeError();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000643
Reid Kleckner145090f2017-10-27 00:45:51 +0000644 for (uint32_t PubSymOff : ExpGlobals->getGlobalsTable()) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000645 CVSymbol Sym = SymbolRecords.readRecord(PubSymOff);
646 HandleOneSymbol(Sym);
647 }
648 } else {
649 for (const auto &Sec : File.symbol_groups()) {
650 for (const auto &SS : Sec.getDebugSubsections()) {
651 if (SS.kind() != DebugSubsectionKind::Symbols)
652 continue;
653
654 DebugSymbolsSubsectionRef Symbols;
655 BinaryStreamReader Reader(SS.getRecordData());
656 cantFail(Symbols.initialize(Reader));
657 for (const auto &S : Symbols)
658 HandleOneSymbol(S);
659 }
660 }
Zachary Turner99c69822017-08-31 20:43:22 +0000661 }
662
663 LongestNamespace += StringRef(" namespace ''").size();
Zachary Turner4c806612017-08-31 20:50:25 +0000664 size_t LongestTypeLeafKind = getLongestTypeLeafName(UdtTargetStats);
665 size_t FieldWidth = std::max(LongestNamespace, LongestTypeLeafKind);
Zachary Turner99c69822017-08-31 20:43:22 +0000666
667 // Compute the max number of digits for count and size fields, including comma
668 // separators.
669 StringRef CountHeader("Count");
670 StringRef SizeHeader("Size");
Zachary Turner4c806612017-08-31 20:50:25 +0000671 size_t CD = NumDigits(UdtStats.Totals.Count);
Zachary Turner99c69822017-08-31 20:43:22 +0000672 CD += (CD - 1) / 3;
673 CD = std::max(CD, CountHeader.size());
674
Zachary Turner4c806612017-08-31 20:50:25 +0000675 size_t SD = NumDigits(UdtStats.Totals.Size);
Zachary Turner99c69822017-08-31 20:43:22 +0000676 SD += (SD - 1) / 3;
677 SD = std::max(SD, SizeHeader.size());
678
679 uint32_t TableWidth = FieldWidth + 3 + CD + 2 + SD + 1;
680
681 P.formatLine("{0} | {1} {2}",
682 fmt_align("Record Kind", AlignStyle::Right, FieldWidth),
683 fmt_align(CountHeader, AlignStyle::Right, CD),
684 fmt_align(SizeHeader, AlignStyle::Right, SD));
685
686 P.formatLine("{0}", fmt_repeat('-', TableWidth));
687 for (const auto &Stat : UdtTargetStats.Individual) {
688 StringRef Label = getUdtStatLabel(Stat.first);
689 P.formatLine("{0} | {1:N} {2:N}",
690 fmt_align(Label, AlignStyle::Right, FieldWidth),
691 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
692 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
693 }
694 P.formatLine("{0}", fmt_repeat('-', TableWidth));
695 P.formatLine("{0} | {1:N} {2:N}",
696 fmt_align("Total (S_UDT)", AlignStyle::Right, FieldWidth),
697 fmt_align(UdtStats.Totals.Count, AlignStyle::Right, CD),
698 fmt_align(UdtStats.Totals.Size, AlignStyle::Right, SD));
699 P.formatLine("{0}", fmt_repeat('-', TableWidth));
700 for (const auto &Stat : NamespacedStats) {
701 std::string Label = formatv("namespace '{0}'", Stat.getKey());
702 P.formatLine("{0} | {1:N} {2:N}",
703 fmt_align(Label, AlignStyle::Right, FieldWidth),
704 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
705 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
706 }
707 return Error::success();
708}
709
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000710static void typesetLinesAndColumns(LinePrinter &P, uint32_t Start,
711 const LineColumnEntry &E) {
Zachary Turner4e950642017-06-15 23:56:19 +0000712 const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
713 uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
714
715 // Let's try to keep it under 100 characters
716 constexpr uint32_t kMaxRowLength = 100;
717 // At least 3 spaces between columns.
718 uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
719 uint32_t ItemsLeft = E.LineNumbers.size();
720 auto LineIter = E.LineNumbers.begin();
721 while (ItemsLeft != 0) {
722 uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
723 for (uint32_t I = 0; I < RowColumns; ++I) {
724 LineInfo Line(LineIter->Flags);
725 std::string LineStr;
726 if (Line.isAlwaysStepInto())
727 LineStr = "ASI";
728 else if (Line.isNeverStepInto())
729 LineStr = "NSI";
Zachary Turner0e327d02017-06-15 23:12:41 +0000730 else
Zachary Turner4e950642017-06-15 23:56:19 +0000731 LineStr = utostr(Line.getStartLine());
732 char Statement = Line.isStatement() ? ' ' : '!';
733 P.format("{0} {1:X-} {2} ",
734 fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
735 fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
736 Statement);
737 ++LineIter;
738 --ItemsLeft;
Zachary Turner63055452017-06-15 22:24:24 +0000739 }
Zachary Turner4e950642017-06-15 23:56:19 +0000740 P.NewLine();
Zachary Turner63055452017-06-15 22:24:24 +0000741 }
Zachary Turner4e950642017-06-15 23:56:19 +0000742}
743
Zachary Turner7df69952017-06-22 20:57:39 +0000744Error DumpOutputStyle::dumpLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000745 printHeader(P, "Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000746
Zachary Turnerf2872b92017-06-15 23:59:56 +0000747 uint32_t LastModi = UINT32_MAX;
748 uint32_t LastNameIndex = UINT32_MAX;
749 iterateModuleSubsections<DebugLinesSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000750 File, PrintScope{P, 4},
Zachary Turnerf2872b92017-06-15 23:59:56 +0000751 [this, &LastModi, &LastNameIndex](uint32_t Modi,
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000752 const SymbolGroup &Strings,
Zachary Turnerf2872b92017-06-15 23:59:56 +0000753 DebugLinesSubsectionRef &Lines) {
754 uint16_t Segment = Lines.header()->RelocSegment;
755 uint32_t Begin = Lines.header()->RelocOffset;
756 uint32_t End = Begin + Lines.header()->CodeSize;
757 for (const auto &Block : Lines) {
758 if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
759 LastModi = Modi;
760 LastNameIndex = Block.NameIndex;
761 Strings.formatFromChecksumsOffset(P, Block.NameIndex);
Zachary Turner4e950642017-06-15 23:56:19 +0000762 }
763
Zachary Turnerf2872b92017-06-15 23:59:56 +0000764 AutoIndent Indent(P, 2);
765 P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
766 uint32_t Count = Block.LineNumbers.size();
767 if (Lines.hasColumnInfo())
768 P.format("line/column/addr entries = {0}", Count);
769 else
770 P.format("line/addr entries = {0}", Count);
Zachary Turner4e950642017-06-15 23:56:19 +0000771
Zachary Turnerf2872b92017-06-15 23:59:56 +0000772 P.NewLine();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000773 typesetLinesAndColumns(P, Begin, Block);
Zachary Turner4e950642017-06-15 23:56:19 +0000774 }
775 });
776
777 return Error::success();
778}
779
Zachary Turner7df69952017-06-22 20:57:39 +0000780Error DumpOutputStyle::dumpInlineeLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000781 printHeader(P, "Inlinee Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000782
Zachary Turnerf2872b92017-06-15 23:59:56 +0000783 iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000784 File, PrintScope{P, 2},
785 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turnerf2872b92017-06-15 23:59:56 +0000786 DebugInlineeLinesSubsectionRef &Lines) {
787 P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
788 for (const auto &Entry : Lines) {
789 P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
790 fmtle(Entry.Header->SourceLineNum));
791 Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
Zachary Turner4e950642017-06-15 23:56:19 +0000792 }
Zachary Turnerf2872b92017-06-15 23:59:56 +0000793 P.NewLine();
Zachary Turner4e950642017-06-15 23:56:19 +0000794 });
795
Zachary Turner63055452017-06-15 22:24:24 +0000796 return Error::success();
797}
Zachary Turner0e327d02017-06-15 23:12:41 +0000798
Zachary Turner7df69952017-06-22 20:57:39 +0000799Error DumpOutputStyle::dumpXmi() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000800 printHeader(P, "Cross Module Imports");
801 iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000802 File, PrintScope{P, 2},
803 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turner47d9a562017-06-16 00:04:24 +0000804 DebugCrossModuleImportsSubsectionRef &Imports) {
805 P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
806
807 for (const auto &Xmi : Imports) {
808 auto ExpectedModule =
809 Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
810 StringRef Module;
811 SmallString<32> ModuleStorage;
812 if (!ExpectedModule) {
813 Module = "(unknown module)";
814 consumeError(ExpectedModule.takeError());
815 } else
816 Module = *ExpectedModule;
817 if (Module.size() > 32) {
818 ModuleStorage = "...";
819 ModuleStorage += Module.take_back(32 - 3);
820 Module = ModuleStorage;
821 }
822 std::vector<std::string> TIs;
823 for (const auto I : Xmi.Imports)
824 TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
825 std::string Result =
826 typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
827 P.formatLine("{0,+32} | {1}", Module, Result);
828 }
829 });
830
831 return Error::success();
832}
833
Zachary Turner7df69952017-06-22 20:57:39 +0000834Error DumpOutputStyle::dumpXme() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000835 printHeader(P, "Cross Module Exports");
836
837 iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000838 File, PrintScope{P, 2},
839 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turner47d9a562017-06-16 00:04:24 +0000840 DebugCrossModuleExportsSubsectionRef &Exports) {
841 P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
842 for (const auto &Export : Exports) {
843 P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
844 TypeIndex(Export.Global));
845 }
846 });
847
848 return Error::success();
849}
850
Zachary Turner60478582018-01-05 19:12:40 +0000851Error DumpOutputStyle::dumpStringTableFromPdb() {
Zachary Turner63055452017-06-15 22:24:24 +0000852 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000853 auto IS = getPdb().getStringTable();
Zachary Turner63055452017-06-15 22:24:24 +0000854 if (!IS) {
855 P.formatLine("Not present in file");
856 consumeError(IS.takeError());
857 return Error::success();
858 }
859
860 if (IS->name_ids().empty()) {
861 P.formatLine("Empty");
862 return Error::success();
863 }
864
865 auto MaxID = std::max_element(IS->name_ids().begin(), IS->name_ids().end());
866 uint32_t Digits = NumDigits(*MaxID);
867
868 P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
869 "String");
870
871 std::vector<uint32_t> SortedIDs(IS->name_ids().begin(), IS->name_ids().end());
872 std::sort(SortedIDs.begin(), SortedIDs.end());
873 for (uint32_t I : SortedIDs) {
874 auto ES = IS->getStringForID(I);
875 llvm::SmallString<32> Str;
876 if (!ES) {
877 consumeError(ES.takeError());
878 Str = "Error reading string";
879 } else if (!ES->empty()) {
880 Str.append("'");
881 Str.append(*ES);
882 Str.append("'");
883 }
884
885 if (!Str.empty())
886 P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits), Str);
887 }
888 return Error::success();
889}
890
Zachary Turner60478582018-01-05 19:12:40 +0000891Error DumpOutputStyle::dumpStringTableFromObj() {
892 iterateModuleSubsections<DebugStringTableSubsectionRef>(
893 File, PrintScope{P, 4},
894 [&](uint32_t Modi, const SymbolGroup &Strings,
895 DebugStringTableSubsectionRef &Strings2) {
896 BinaryStreamRef StringTableBuffer = Strings2.getBuffer();
897 BinaryStreamReader Reader(StringTableBuffer);
898 while (Reader.bytesRemaining() > 0) {
899 StringRef Str;
900 uint32_t Offset = Reader.getOffset();
901 cantFail(Reader.readCString(Str));
902 if (Str.empty())
903 continue;
904
905 P.formatLine("{0} | {1}", fmt_align(Offset, AlignStyle::Right, 4),
906 Str);
907 }
908 });
909 return Error::success();
910}
911
912Error DumpOutputStyle::dumpStringTable() {
913 printHeader(P, "String Table");
914
915 if (File.isPdb())
916 return dumpStringTableFromPdb();
917
918 return dumpStringTableFromObj();
919}
920
Zachary Turner02a26772017-06-30 18:15:47 +0000921static void buildDepSet(LazyRandomTypeCollection &Types,
922 ArrayRef<TypeIndex> Indices,
923 std::map<TypeIndex, CVType> &DepSet) {
924 SmallVector<TypeIndex, 4> DepList;
925 for (const auto &I : Indices) {
926 TypeIndex TI(I);
927 if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
928 continue;
929
930 CVType Type = Types.getType(TI);
931 DepSet[TI] = Type;
932 codeview::discoverTypeIndices(Type, DepList);
933 buildDepSet(Types, DepList, DepSet);
934 }
935}
936
Zachary Turner376d4372017-12-05 23:58:18 +0000937static void
938dumpFullTypeStream(LinePrinter &Printer, LazyRandomTypeCollection &Types,
Zachary Turner2ed069e2017-12-06 00:26:43 +0000939 uint32_t NumTypeRecords, uint32_t NumHashBuckets,
Zachary Turner376d4372017-12-05 23:58:18 +0000940 FixedStreamArray<support::ulittle32_t> HashValues,
941 bool Bytes, bool Extras) {
942
Zachary Turner2ed069e2017-12-06 00:26:43 +0000943 Printer.formatLine("Showing {0:N} records", NumTypeRecords);
944 uint32_t Width = NumDigits(TypeIndex::FirstNonSimpleIndex + NumTypeRecords);
Zachary Turner02a26772017-06-30 18:15:47 +0000945
946 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Zachary Turner376d4372017-12-05 23:58:18 +0000947 NumHashBuckets, HashValues);
Zachary Turner02a26772017-06-30 18:15:47 +0000948
949 if (auto EC = codeview::visitTypeStream(Types, V)) {
950 Printer.formatLine("An error occurred dumping type records: {0}",
951 toString(std::move(EC)));
952 }
953}
954
955static void dumpPartialTypeStream(LinePrinter &Printer,
956 LazyRandomTypeCollection &Types,
957 TpiStream &Stream, ArrayRef<TypeIndex> TiList,
958 bool Bytes, bool Extras, bool Deps) {
959 uint32_t Width =
960 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
961
962 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Reid Klecknerc50349d2017-07-18 00:33:45 +0000963 Stream.getNumHashBuckets(), Stream.getHashValues());
Zachary Turner02a26772017-06-30 18:15:47 +0000964
965 if (opts::dump::DumpTypeDependents) {
966 // If we need to dump all dependents, then iterate each index and find
967 // all dependents, adding them to a map ordered by TypeIndex.
968 std::map<TypeIndex, CVType> DepSet;
969 buildDepSet(Types, TiList, DepSet);
970
971 Printer.formatLine(
972 "Showing {0:N} records and their dependents ({1:N} records total)",
973 TiList.size(), DepSet.size());
974
975 for (auto &Dep : DepSet) {
976 if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
977 Printer.formatLine("An error occurred dumping type record {0}: {1}",
978 Dep.first, toString(std::move(EC)));
979 }
980 } else {
981 Printer.formatLine("Showing {0:N} records.", TiList.size());
982
983 for (const auto &I : TiList) {
984 TypeIndex TI(I);
985 CVType Type = Types.getType(TI);
986 if (auto EC = codeview::visitTypeRecord(Type, TI, V))
987 Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
988 toString(std::move(EC)));
989 }
990 }
991}
992
Zachary Turner376d4372017-12-05 23:58:18 +0000993Error DumpOutputStyle::dumpTypesFromObjectFile() {
994 LazyRandomTypeCollection Types(100);
995
996 for (const auto &S : getObj().sections()) {
997 StringRef SectionName;
998 if (auto EC = S.getName(SectionName))
999 return errorCodeToError(EC);
1000
1001 if (SectionName != ".debug$T")
1002 continue;
1003 StringRef Contents;
1004 if (auto EC = S.getContents(Contents))
1005 return errorCodeToError(EC);
1006
1007 uint32_t Magic;
1008 BinaryStreamReader Reader(Contents, llvm::support::little);
1009 if (auto EC = Reader.readInteger(Magic))
1010 return EC;
1011 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1012 return make_error<StringError>("Invalid CodeView debug section.",
1013 inconvertibleErrorCode());
1014
1015 Types.reset(Reader, 100);
1016
1017 if (opts::dump::DumpTypes) {
Zachary Turner2ed069e2017-12-06 00:26:43 +00001018 dumpFullTypeStream(P, Types, 0, 0, {}, opts::dump::DumpTypeData, false);
Zachary Turner376d4372017-12-05 23:58:18 +00001019 } else if (opts::dump::DumpTypeExtras) {
1020 auto LocalHashes = LocallyHashedType::hashTypeCollection(Types);
1021 auto GlobalHashes = GloballyHashedType::hashTypeCollection(Types);
1022 assert(LocalHashes.size() == GlobalHashes.size());
1023
1024 P.formatLine("Local / Global hashes:");
1025 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
1026 for (const auto &H : zip(LocalHashes, GlobalHashes)) {
1027 AutoIndent Indent2(P);
1028 LocallyHashedType &L = std::get<0>(H);
1029 GloballyHashedType &G = std::get<1>(H);
1030
1031 P.formatLine("TI: {0}, LocalHash: {1:X}, GlobalHash: {2}", TI, L, G);
1032
1033 ++TI;
1034 }
1035 P.NewLine();
1036 }
1037 }
1038
1039 return Error::success();
1040}
1041
Zachary Turner7df69952017-06-22 20:57:39 +00001042Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
Zachary Turner63055452017-06-15 22:24:24 +00001043 assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
1044
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001045 if (StreamIdx == StreamTPI) {
1046 printHeader(P, "Types (TPI Stream)");
1047 } else if (StreamIdx == StreamIPI) {
1048 printHeader(P, "Types (IPI Stream)");
1049 }
1050
1051 AutoIndent Indent(P);
Zachary Turner376d4372017-12-05 23:58:18 +00001052 assert(!File.isObj());
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001053
Zachary Turner63055452017-06-15 22:24:24 +00001054 bool Present = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001055 bool DumpTypes = false;
Zachary Turner63055452017-06-15 22:24:24 +00001056 bool DumpBytes = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001057 bool DumpExtras = false;
Zachary Turner59224cb2017-06-16 23:42:15 +00001058 std::vector<uint32_t> Indices;
Zachary Turner63055452017-06-15 22:24:24 +00001059 if (StreamIdx == StreamTPI) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001060 Present = getPdb().hasPDBTpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +00001061 DumpTypes = opts::dump::DumpTypes;
1062 DumpBytes = opts::dump::DumpTypeData;
1063 DumpExtras = opts::dump::DumpTypeExtras;
1064 Indices.assign(opts::dump::DumpTypeIndex.begin(),
1065 opts::dump::DumpTypeIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +00001066 } else if (StreamIdx == StreamIPI) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001067 Present = getPdb().hasPDBIpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +00001068 DumpTypes = opts::dump::DumpIds;
1069 DumpBytes = opts::dump::DumpIdData;
1070 DumpExtras = opts::dump::DumpIdExtras;
1071 Indices.assign(opts::dump::DumpIdIndex.begin(),
1072 opts::dump::DumpIdIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +00001073 }
1074
Zachary Turner63055452017-06-15 22:24:24 +00001075 if (!Present) {
1076 P.formatLine("Stream not present");
1077 return Error::success();
1078 }
1079
Reid Klecknerdd853e52017-07-27 23:13:18 +00001080 ExitOnError Err("Unexpected error processing types: ");
Zachary Turner63055452017-06-15 22:24:24 +00001081
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001082 auto &Stream = Err((StreamIdx == StreamTPI) ? getPdb().getPDBTpiStream()
1083 : getPdb().getPDBIpiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001084
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001085 auto &Types = (StreamIdx == StreamTPI) ? File.types() : File.ids();
Zachary Turner63055452017-06-15 22:24:24 +00001086
Zachary Turner02a26772017-06-30 18:15:47 +00001087 if (DumpTypes || !Indices.empty()) {
1088 if (Indices.empty())
Zachary Turner2ed069e2017-12-06 00:26:43 +00001089 dumpFullTypeStream(P, Types, Stream.getNumTypeRecords(),
1090 Stream.getNumHashBuckets(), Stream.getHashValues(),
1091 DumpBytes, DumpExtras);
Zachary Turner02a26772017-06-30 18:15:47 +00001092 else {
1093 std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
1094 dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
1095 opts::dump::DumpTypeDependents);
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001096 }
1097 }
1098
1099 if (DumpExtras) {
1100 P.NewLine();
1101 auto IndexOffsets = Stream.getTypeIndexOffsets();
1102 P.formatLine("Type Index Offsets:");
1103 for (const auto &IO : IndexOffsets) {
1104 AutoIndent Indent2(P);
1105 P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
1106 }
1107
1108 P.NewLine();
1109 P.formatLine("Hash Adjusters:");
1110 auto &Adjusters = Stream.getHashAdjusters();
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001111 auto &Strings = Err(getPdb().getStringTable());
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001112 for (const auto &A : Adjusters) {
1113 AutoIndent Indent2(P);
1114 auto ExpectedStr = Strings.getStringForID(A.first);
1115 TypeIndex TI(A.second);
1116 if (ExpectedStr)
1117 P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
1118 else {
1119 P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
1120 consumeError(ExpectedStr.takeError());
1121 }
1122 }
Zachary Turner63055452017-06-15 22:24:24 +00001123 }
1124 return Error::success();
1125}
1126
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001127Error DumpOutputStyle::dumpModuleSymsForObj() {
Zachary Turner63055452017-06-15 22:24:24 +00001128 printHeader(P, "Symbols");
1129
1130 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001131
1132 ExitOnError Err("Unexpected error processing symbols: ");
1133
1134 auto &Types = File.types();
1135
1136 SymbolVisitorCallbackPipeline Pipeline;
1137 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::ObjectFile);
1138 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Types, Types);
1139
1140 Pipeline.addCallbackToPipeline(Deserializer);
1141 Pipeline.addCallbackToPipeline(Dumper);
1142 CVSymbolVisitor Visitor(Pipeline);
1143
1144 std::unique_ptr<llvm::Error> SymbolError;
1145
1146 iterateModuleSubsections<DebugSymbolsSubsectionRef>(
1147 File, PrintScope{P, 2},
1148 [&](uint32_t Modi, const SymbolGroup &Strings,
1149 DebugSymbolsSubsectionRef &Symbols) {
Zachary Turner60478582018-01-05 19:12:40 +00001150 Dumper.setSymbolGroup(&Strings);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001151 for (auto Symbol : Symbols) {
1152 if (auto EC = Visitor.visitSymbolRecord(Symbol)) {
1153 SymbolError = llvm::make_unique<Error>(std::move(EC));
1154 return;
1155 }
1156 }
1157 });
1158
1159 if (SymbolError)
1160 return std::move(*SymbolError);
1161
1162 return Error::success();
1163}
1164
1165Error DumpOutputStyle::dumpModuleSymsForPdb() {
1166 printHeader(P, "Symbols");
1167
1168 AutoIndent Indent(P);
1169 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001170 P.formatLine("DBI Stream not present");
1171 return Error::success();
1172 }
1173
Reid Klecknerdd853e52017-07-27 23:13:18 +00001174 ExitOnError Err("Unexpected error processing symbols: ");
Zachary Turner63055452017-06-15 22:24:24 +00001175
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001176 auto &Ids = File.ids();
1177 auto &Types = File.types();
Zachary Turner63055452017-06-15 22:24:24 +00001178
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001179 iterateSymbolGroups(
1180 File, PrintScope{P, 2}, [&](uint32_t I, const SymbolGroup &Strings) {
1181 auto ExpectedModS = getModuleDebugStream(File.pdb(), I);
Zachary Turner58699362017-08-03 23:11:52 +00001182 if (!ExpectedModS) {
1183 P.formatLine("Error loading module stream {0}. {1}", I,
1184 toString(ExpectedModS.takeError()));
1185 return;
1186 }
Zachary Turner63055452017-06-15 22:24:24 +00001187
Zachary Turner58699362017-08-03 23:11:52 +00001188 ModuleDebugStreamRef &ModS = *ExpectedModS;
Zachary Turner63055452017-06-15 22:24:24 +00001189
Zachary Turner58699362017-08-03 23:11:52 +00001190 SymbolVisitorCallbackPipeline Pipeline;
1191 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
Zachary Turner60478582018-01-05 19:12:40 +00001192 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Strings,
1193 Ids, Types);
Zachary Turner63055452017-06-15 22:24:24 +00001194
Zachary Turner58699362017-08-03 23:11:52 +00001195 Pipeline.addCallbackToPipeline(Deserializer);
1196 Pipeline.addCallbackToPipeline(Dumper);
1197 CVSymbolVisitor Visitor(Pipeline);
1198 auto SS = ModS.getSymbolsSubstream();
1199 if (auto EC =
1200 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
1201 P.formatLine("Error while processing symbol records. {0}",
1202 toString(std::move(EC)));
1203 return;
1204 }
1205 });
Zachary Turner63055452017-06-15 22:24:24 +00001206 return Error::success();
1207}
1208
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001209Error DumpOutputStyle::dumpGlobals() {
1210 printHeader(P, "Global Symbols");
1211 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001212
1213 if (File.isObj()) {
1214 P.formatLine("Dumping Globals is not supported for object files");
1215 return Error::success();
1216 }
1217
1218 if (!getPdb().hasPDBGlobalsStream()) {
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001219 P.formatLine("Globals stream not present");
1220 return Error::success();
1221 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001222 ExitOnError Err("Error dumping globals stream: ");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001223 auto &Globals = Err(getPdb().getPDBGlobalsStream());
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001224
1225 const GSIHashTable &Table = Globals.getGlobalsTable();
1226 Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
1227 return Error::success();
1228}
1229
Zachary Turner7df69952017-06-22 20:57:39 +00001230Error DumpOutputStyle::dumpPublics() {
Zachary Turner63055452017-06-15 22:24:24 +00001231 printHeader(P, "Public Symbols");
Zachary Turner63055452017-06-15 22:24:24 +00001232 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001233
1234 if (File.isObj()) {
1235 P.formatLine("Dumping Globals is not supported for object files");
1236 return Error::success();
1237 }
1238
1239 if (!getPdb().hasPDBPublicsStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001240 P.formatLine("Publics stream not present");
1241 return Error::success();
1242 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001243 ExitOnError Err("Error dumping publics stream: ");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001244 auto &Publics = Err(getPdb().getPDBPublicsStream());
Zachary Turner63055452017-06-15 22:24:24 +00001245
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001246 const GSIHashTable &PublicsTable = Publics.getPublicsTable();
Zachary Turner5448dab2017-08-09 04:23:59 +00001247 if (opts::dump::DumpPublicExtras) {
1248 P.printLine("Publics Header");
1249 AutoIndent Indent(P);
1250 P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
1251 formatSegmentOffset(Publics.getThunkTableSection(),
1252 Publics.getThunkTableOffset()));
1253 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001254 Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
Zachary Turneraf8c75a2017-06-30 21:35:00 +00001255
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001256 // Skip the rest if we aren't dumping extras.
Reid Kleckner686f1212017-07-21 18:28:55 +00001257 if (!opts::dump::DumpPublicExtras)
1258 return Error::success();
1259
Reid Kleckner686f1212017-07-21 18:28:55 +00001260 P.formatLine("Address Map");
1261 {
1262 // These are offsets into the publics stream sorted by secidx:secrel.
1263 AutoIndent Indent2(P);
1264 for (uint32_t Addr : Publics.getAddressMap())
1265 P.formatLine("off = {0}", Addr);
1266 }
1267
1268 // The thunk map is optional debug info used for ILT thunks.
1269 if (!Publics.getThunkMap().empty()) {
1270 P.formatLine("Thunk Map");
1271 AutoIndent Indent2(P);
1272 for (uint32_t Addr : Publics.getThunkMap())
1273 P.formatLine("{0:x8}", Addr);
1274 }
1275
1276 // The section offsets table appears to be empty when incremental linking
1277 // isn't in use.
1278 if (!Publics.getSectionOffsets().empty()) {
1279 P.formatLine("Section Offsets");
1280 AutoIndent Indent2(P);
1281 for (const SectionOffset &SO : Publics.getSectionOffsets())
1282 P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
1283 }
1284
Zachary Turner63055452017-06-15 22:24:24 +00001285 return Error::success();
1286}
1287
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001288Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1289 bool HashExtras) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001290 auto ExpectedSyms = getPdb().getPDBSymbolStream();
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001291 if (!ExpectedSyms)
1292 return ExpectedSyms.takeError();
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001293 auto &Types = File.types();
1294 auto &Ids = File.ids();
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001295
Zachary Turner5448dab2017-08-09 04:23:59 +00001296 if (HashExtras) {
1297 P.printLine("GSI Header");
1298 AutoIndent Indent(P);
1299 P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1300 Table.getVerSignature(), Table.getVerHeader(),
1301 Table.getHashRecordSize(), Table.getNumBuckets());
1302 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001303
Zachary Turner5448dab2017-08-09 04:23:59 +00001304 {
1305 P.printLine("Records");
1306 SymbolVisitorCallbackPipeline Pipeline;
1307 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001308 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids, Types);
Zachary Turner5448dab2017-08-09 04:23:59 +00001309
1310 Pipeline.addCallbackToPipeline(Deserializer);
1311 Pipeline.addCallbackToPipeline(Dumper);
1312 CVSymbolVisitor Visitor(Pipeline);
1313
1314 BinaryStreamRef SymStream =
1315 ExpectedSyms->getSymbolArray().getUnderlyingStream();
1316 for (uint32_t PubSymOff : Table) {
1317 Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
1318 if (!Sym)
1319 return Sym.takeError();
1320 if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
1321 return E;
1322 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001323 }
1324
1325 // Return early if we aren't dumping public hash table and address map info.
1326 if (!HashExtras)
1327 return Error::success();
1328
Zachary Turner5448dab2017-08-09 04:23:59 +00001329 P.formatLine("Hash Entries");
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001330 {
1331 AutoIndent Indent2(P);
1332 for (const PSHashRecord &HR : Table.HashRecords)
1333 P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
1334 uint32_t(HR.CRef));
1335 }
1336
1337 // FIXME: Dump the bitmap.
1338
1339 P.formatLine("Hash Buckets");
1340 {
1341 AutoIndent Indent2(P);
1342 for (uint32_t Hash : Table.HashBuckets)
1343 P.formatLine("{0:x8}", Hash);
1344 }
1345
1346 return Error::success();
1347}
1348
Zachary Turner63055452017-06-15 22:24:24 +00001349static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1350 OMFSegDescFlags Flags) {
1351 std::vector<std::string> Opts;
1352 if (Flags == OMFSegDescFlags::None)
1353 return "none";
1354
1355 PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1356 PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1357 PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1358 PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1359 PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1360 PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1361 PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
Zachary Turner47d9a562017-06-16 00:04:24 +00001362 return typesetItemList(Opts, IndentLevel, 4, " | ");
Zachary Turner63055452017-06-15 22:24:24 +00001363}
1364
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001365Error DumpOutputStyle::dumpSectionHeaders() {
1366 dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1367 dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1368 return Error::success();
1369}
1370
Zachary Turner92e584c2017-08-04 21:10:04 +00001371static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1372 ArrayRef<llvm::object::coff_section>>>
1373loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1374 if (!File.hasPDBDbiStream())
1375 return make_error<StringError>(
1376 "Section headers require a DBI Stream, which could not be loaded",
1377 inconvertibleErrorCode());
1378
1379 auto &Dbi = cantFail(File.getPDBDbiStream());
1380 uint32_t SI = Dbi.getDebugStreamIndex(Type);
1381
1382 if (SI == kInvalidStreamIndex)
1383 return make_error<StringError>(
1384 "PDB does not contain the requested image section header type",
1385 inconvertibleErrorCode());
1386
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001387 auto Stream = File.createIndexedStream(SI);
Zachary Turner92e584c2017-08-04 21:10:04 +00001388 if (!Stream)
1389 return make_error<StringError>("Could not load the required stream data",
1390 inconvertibleErrorCode());
1391
1392 ArrayRef<object::coff_section> Headers;
1393 if (Stream->getLength() % sizeof(object::coff_section) != 0)
1394 return make_error<StringError>(
1395 "Section header array size is not a multiple of section header size",
1396 inconvertibleErrorCode());
1397
1398 uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1399 BinaryStreamReader Reader(*Stream);
1400 cantFail(Reader.readArray(Headers, NumHeaders));
1401 return std::make_pair(std::move(Stream), Headers);
1402}
1403
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001404void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1405 printHeader(P, Label);
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001406
1407 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001408 if (File.isObj()) {
1409 P.formatLine("Dumping Section Headers is not supported for object files");
1410 return;
1411 }
1412
1413 ExitOnError Err("Error dumping section headers: ");
Zachary Turner92e584c2017-08-04 21:10:04 +00001414 std::unique_ptr<MappedBlockStream> Stream;
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001415 ArrayRef<object::coff_section> Headers;
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001416 auto ExpectedHeaders = loadSectionHeaders(getPdb(), Type);
Zachary Turner92e584c2017-08-04 21:10:04 +00001417 if (!ExpectedHeaders) {
1418 P.printLine(toString(ExpectedHeaders.takeError()));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001419 return;
1420 }
Zachary Turner92e584c2017-08-04 21:10:04 +00001421 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001422
1423 uint32_t I = 1;
1424 for (const auto &Header : Headers) {
1425 P.NewLine();
1426 P.formatLine("SECTION HEADER #{0}", I);
1427 P.formatLine("{0,8} name", Header.Name);
1428 P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1429 P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1430 P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1431 P.formatLine("{0,8:X-} file pointer to raw data",
1432 uint32_t(Header.PointerToRawData));
1433 P.formatLine("{0,8:X-} file pointer to relocation table",
1434 uint32_t(Header.PointerToRelocations));
1435 P.formatLine("{0,8:X-} file pointer to line numbers",
1436 uint32_t(Header.PointerToLinenumbers));
1437 P.formatLine("{0,8:X-} number of relocations",
1438 uint32_t(Header.NumberOfRelocations));
1439 P.formatLine("{0,8:X-} number of line numbers",
1440 uint32_t(Header.NumberOfLinenumbers));
1441 P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1442 AutoIndent IndentMore(P, 9);
1443 P.formatLine("{0}", formatSectionCharacteristics(
1444 P.getIndentLevel(), Header.Characteristics, 1, ""));
1445 ++I;
1446 }
1447 return;
1448}
1449
Zachary Turner92e584c2017-08-04 21:10:04 +00001450std::vector<std::string> getSectionNames(PDBFile &File) {
1451 auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1452 if (!ExpectedHeaders)
1453 return {};
1454
1455 std::unique_ptr<MappedBlockStream> Stream;
1456 ArrayRef<object::coff_section> Headers;
1457 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1458 std::vector<std::string> Names;
1459 for (const auto &H : Headers)
1460 Names.push_back(H.Name);
1461 return Names;
1462}
1463
Zachary Turner7df69952017-06-22 20:57:39 +00001464Error DumpOutputStyle::dumpSectionContribs() {
Zachary Turner63055452017-06-15 22:24:24 +00001465 printHeader(P, "Section Contributions");
Zachary Turner63055452017-06-15 22:24:24 +00001466
1467 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001468 if (File.isObj()) {
1469 P.formatLine(
1470 "Dumping section contributions is not supported for object files");
1471 return Error::success();
1472 }
1473
1474 ExitOnError Err("Error dumping section contributions: ");
1475 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001476 P.formatLine(
1477 "Section contribs require a DBI Stream, which could not be loaded");
1478 return Error::success();
1479 }
1480
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001481 auto &Dbi = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001482
1483 class Visitor : public ISectionContribVisitor {
1484 public:
Zachary Turner92e584c2017-08-04 21:10:04 +00001485 Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1486 auto Max = std::max_element(
1487 Names.begin(), Names.end(),
1488 [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1489 MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1490 }
Zachary Turner63055452017-06-15 22:24:24 +00001491 void visit(const SectionContrib &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001492 assert(SC.ISect > 0);
Zachary Turner489a7a02017-08-07 20:24:01 +00001493 std::string NameInsert;
1494 if (SC.ISect < Names.size()) {
1495 StringRef SectionName = Names[SC.ISect - 1];
1496 NameInsert = formatv("[{0}]", SectionName).str();
1497 } else
1498 NameInsert = "[???]";
Zachary Turner92e584c2017-08-04 21:10:04 +00001499 P.formatLine("SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1500 "crc = {4}",
1501 formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1502 fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1503 fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1504 AutoIndent Indent(P, MaxNameLen + 2);
Zachary Turner63055452017-06-15 22:24:24 +00001505 P.formatLine(" {0}",
1506 formatSectionCharacteristics(P.getIndentLevel() + 6,
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001507 SC.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001508 }
1509 void visit(const SectionContrib2 &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001510 P.formatLine(
1511 "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1512 "crc = {4}, coff section = {5}",
1513 formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1514 fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1515 fmtle(SC.ISectCoff));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001516 P.formatLine(" {0}", formatSectionCharacteristics(
1517 P.getIndentLevel() + 6,
1518 SC.Base.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001519 }
1520
1521 private:
1522 LinePrinter &P;
Zachary Turner92e584c2017-08-04 21:10:04 +00001523 uint32_t MaxNameLen;
1524 ArrayRef<std::string> Names;
Zachary Turner63055452017-06-15 22:24:24 +00001525 };
1526
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001527 std::vector<std::string> Names = getSectionNames(getPdb());
Zachary Turner92e584c2017-08-04 21:10:04 +00001528 Visitor V(P, makeArrayRef(Names));
Zachary Turner63055452017-06-15 22:24:24 +00001529 Dbi.visitSectionContributions(V);
1530 return Error::success();
1531}
1532
Zachary Turner7df69952017-06-22 20:57:39 +00001533Error DumpOutputStyle::dumpSectionMap() {
Zachary Turner63055452017-06-15 22:24:24 +00001534 printHeader(P, "Section Map");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001535 AutoIndent Indent(P);
1536
1537 if (File.isObj()) {
1538 P.formatLine("Dumping section map is not supported for object files");
1539 return Error::success();
1540 }
1541
Reid Klecknerdd853e52017-07-27 23:13:18 +00001542 ExitOnError Err("Error dumping section map: ");
Zachary Turner63055452017-06-15 22:24:24 +00001543
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001544 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001545 P.formatLine("Dumping the section map requires a DBI Stream, which could "
1546 "not be loaded");
1547 return Error::success();
1548 }
1549
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001550 auto &Dbi = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001551
1552 uint32_t I = 0;
1553 for (auto &M : Dbi.getSectionMap()) {
1554 P.formatLine(
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001555 "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
Zachary Turner63055452017-06-15 22:24:24 +00001556 fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1557 P.formatLine(" class = {0}, offset = {1}, size = {2}",
1558 fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1559 P.formatLine(" flags = {0}",
1560 formatSegMapDescriptorFlag(
1561 P.getIndentLevel() + 13,
1562 static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1563 ++I;
1564 }
1565 return Error::success();
1566}