blob: 6694a215d7c79926453fd1daf25fb7f736a70610 [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 Turnera6fb5362018-03-23 18:43:39 +000093 if (opts::dump::DumpNamedStreams) {
94 if (auto EC = dumpNamedStreams())
95 return EC;
96 P.NewLine();
97 }
98
99 if (opts::dump::DumpStringTable || opts::dump::DumpStringTableDetails) {
Zachary Turner63055452017-06-15 22:24:24 +0000100 if (auto EC = dumpStringTable())
101 return EC;
102 P.NewLine();
103 }
104
Zachary Turner7df69952017-06-22 20:57:39 +0000105 if (opts::dump::DumpModules) {
Zachary Turner63055452017-06-15 22:24:24 +0000106 if (auto EC = dumpModules())
107 return EC;
108 }
109
Zachary Turner7df69952017-06-22 20:57:39 +0000110 if (opts::dump::DumpModuleFiles) {
Zachary Turner0e327d02017-06-15 23:12:41 +0000111 if (auto EC = dumpModuleFiles())
112 return EC;
113 }
114
Zachary Turner7df69952017-06-22 20:57:39 +0000115 if (opts::dump::DumpLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000116 if (auto EC = dumpLines())
117 return EC;
118 }
119
Zachary Turner7df69952017-06-22 20:57:39 +0000120 if (opts::dump::DumpInlineeLines) {
Zachary Turner4e950642017-06-15 23:56:19 +0000121 if (auto EC = dumpInlineeLines())
122 return EC;
123 }
124
Zachary Turner7df69952017-06-22 20:57:39 +0000125 if (opts::dump::DumpXmi) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000126 if (auto EC = dumpXmi())
127 return EC;
128 }
129
Zachary Turner7df69952017-06-22 20:57:39 +0000130 if (opts::dump::DumpXme) {
Zachary Turner47d9a562017-06-16 00:04:24 +0000131 if (auto EC = dumpXme())
132 return EC;
133 }
134
Zachary Turner376d4372017-12-05 23:58:18 +0000135 if (File.isObj()) {
136 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
137 opts::dump::DumpTypeExtras)
138 if (auto EC = dumpTypesFromObjectFile())
139 return EC;
140 } else {
141 if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() ||
142 opts::dump::DumpTypeExtras) {
143 if (auto EC = dumpTpiStream(StreamTPI))
144 return EC;
145 }
Zachary Turner63055452017-06-15 22:24:24 +0000146
Zachary Turner376d4372017-12-05 23:58:18 +0000147 if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() ||
148 opts::dump::DumpIdExtras) {
149 if (auto EC = dumpTpiStream(StreamIPI))
150 return EC;
151 }
Zachary Turner63055452017-06-15 22:24:24 +0000152 }
153
Reid Kleckner14d90fd2017-07-26 00:40:36 +0000154 if (opts::dump::DumpGlobals) {
155 if (auto EC = dumpGlobals())
156 return EC;
157 }
158
Zachary Turner7df69952017-06-22 20:57:39 +0000159 if (opts::dump::DumpPublics) {
Zachary Turner63055452017-06-15 22:24:24 +0000160 if (auto EC = dumpPublics())
161 return EC;
162 }
163
Zachary Turner7df69952017-06-22 20:57:39 +0000164 if (opts::dump::DumpSymbols) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000165 auto EC = File.isPdb() ? dumpModuleSymsForPdb() : dumpModuleSymsForObj();
166 if (EC)
Zachary Turner63055452017-06-15 22:24:24 +0000167 return EC;
168 }
169
Zachary Turnerfb1cd502017-08-04 20:02:38 +0000170 if (opts::dump::DumpSectionHeaders) {
171 if (auto EC = dumpSectionHeaders())
172 return EC;
173 }
174
Zachary Turner7df69952017-06-22 20:57:39 +0000175 if (opts::dump::DumpSectionContribs) {
Zachary Turner63055452017-06-15 22:24:24 +0000176 if (auto EC = dumpSectionContribs())
177 return EC;
178 }
179
Zachary Turner7df69952017-06-22 20:57:39 +0000180 if (opts::dump::DumpSectionMap) {
Zachary Turner63055452017-06-15 22:24:24 +0000181 if (auto EC = dumpSectionMap())
182 return EC;
183 }
184
185 return Error::success();
186}
187
188static void printHeader(LinePrinter &P, const Twine &S) {
189 P.NewLine();
190 P.formatLine("{0,=60}", S);
191 P.formatLine("{0}", fmt_repeat('=', 60));
192}
193
Zachary Turner7df69952017-06-22 20:57:39 +0000194Error DumpOutputStyle::dumpFileSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000195 printHeader(P, "Summary");
196
Reid Klecknerdd853e52017-07-27 23:13:18 +0000197 ExitOnError Err("Invalid PDB Format: ");
Zachary Turner63055452017-06-15 22:24:24 +0000198
199 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000200 if (File.isObj()) {
201 P.formatLine("Dumping File summary is not valid for object files");
202 return Error::success();
203 }
Zachary Turner63055452017-06-15 22:24:24 +0000204
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000205 P.formatLine("Block Size: {0}", getPdb().getBlockSize());
206 P.formatLine("Number of blocks: {0}", getPdb().getBlockCount());
207 P.formatLine("Number of streams: {0}", getPdb().getNumStreams());
208
209 auto &PS = Err(getPdb().getPDBInfoStream());
Zachary Turner63055452017-06-15 22:24:24 +0000210 P.formatLine("Signature: {0}", PS.getSignature());
211 P.formatLine("Age: {0}", PS.getAge());
212 P.formatLine("GUID: {0}", fmt_guid(PS.getGuid().Guid));
213 P.formatLine("Features: {0:x+}", static_cast<uint32_t>(PS.getFeatures()));
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000214 P.formatLine("Has Debug Info: {0}", getPdb().hasPDBDbiStream());
215 P.formatLine("Has Types: {0}", getPdb().hasPDBTpiStream());
216 P.formatLine("Has IDs: {0}", getPdb().hasPDBIpiStream());
217 P.formatLine("Has Globals: {0}", getPdb().hasPDBGlobalsStream());
218 P.formatLine("Has Publics: {0}", getPdb().hasPDBPublicsStream());
219 if (getPdb().hasPDBDbiStream()) {
220 auto &DBI = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +0000221 P.formatLine("Is incrementally linked: {0}", DBI.isIncrementallyLinked());
222 P.formatLine("Has conflicting types: {0}", DBI.hasCTypes());
223 P.formatLine("Is stripped: {0}", DBI.isStripped());
224 }
225
226 return Error::success();
227}
228
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000229static StatCollection getSymbolStats(const SymbolGroup &SG,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000230 StatCollection &CumulativeStats) {
231 StatCollection Stats;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000232 if (SG.getFile().isPdb()) {
233 // For PDB files, all symbols are packed into one stream.
234 for (const auto &S : SG.getPdbModuleStream().symbols(nullptr)) {
235 Stats.update(S.kind(), S.length());
236 CumulativeStats.update(S.kind(), S.length());
237 }
238 return Stats;
239 }
240
241 for (const auto &SS : SG.getDebugSubsections()) {
242 // For object files, all symbols are spread across multiple Symbol
243 // subsections of a given .debug$S section.
244 if (SS.kind() != DebugSubsectionKind::Symbols)
245 continue;
246 DebugSymbolsSubsectionRef Symbols;
247 BinaryStreamReader Reader(SS.getRecordData());
248 cantFail(Symbols.initialize(Reader));
249 for (const auto &S : Symbols) {
250 Stats.update(S.kind(), S.length());
251 CumulativeStats.update(S.kind(), S.length());
252 }
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000253 }
254 return Stats;
255}
256
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000257static StatCollection getChunkStats(const SymbolGroup &SG,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000258 StatCollection &CumulativeStats) {
259 StatCollection Stats;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000260 for (const auto &Chunk : SG.getDebugSubsections()) {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000261 Stats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
262 CumulativeStats.update(uint32_t(Chunk.kind()), Chunk.getRecordLength());
263 }
264 return Stats;
265}
266
267static inline std::string formatModuleDetailKind(DebugSubsectionKind K) {
268 return formatChunkKind(K, false);
269}
270
271static inline std::string formatModuleDetailKind(SymbolKind K) {
272 return formatSymbolKind(K);
273}
274
275template <typename Kind>
276static void printModuleDetailStats(LinePrinter &P, StringRef Label,
277 const StatCollection &Stats) {
278 P.NewLine();
279 P.formatLine(" {0}", Label);
280 AutoIndent Indent(P);
281 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", "Total",
282 Stats.Totals.Count, Stats.Totals.Size);
283 P.formatLine("{0}", fmt_repeat('-', 74));
284 for (const auto &K : Stats.Individual) {
285 std::string KindName = formatModuleDetailKind(Kind(K.first));
286 P.formatLine("{0,40}: {1,7} entries ({2,8} bytes)", KindName,
287 K.second.Count, K.second.Size);
288 }
289}
290
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000291static bool isMyCode(const SymbolGroup &Group) {
292 if (Group.getFile().isObj())
293 return true;
294
295 StringRef Name = Group.name();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000296 if (Name.startswith("Import:"))
297 return false;
298 if (Name.endswith_lower(".dll"))
299 return false;
300 if (Name.equals_lower("* linker *"))
301 return false;
302 if (Name.startswith_lower("f:\\binaries\\Intermediate\\vctools"))
303 return false;
304 if (Name.startswith_lower("f:\\dd\\vctools\\crt"))
305 return false;
306 return true;
307}
308
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000309static bool shouldDumpSymbolGroup(uint32_t Idx, const SymbolGroup &Group) {
310 if (opts::dump::JustMyCode && !isMyCode(Group))
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000311 return false;
312
313 // If the arg was not specified on the command line, always dump all modules.
314 if (opts::dump::DumpModi.getNumOccurrences() == 0)
315 return true;
316
317 // Otherwise, only dump if this is the same module specified.
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000318 return (opts::dump::DumpModi == Idx);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000319}
320
Zachary Turner7df69952017-06-22 20:57:39 +0000321Error DumpOutputStyle::dumpStreamSummary() {
Zachary Turner63055452017-06-15 22:24:24 +0000322 printHeader(P, "Streams");
323
Zachary Turner63055452017-06-15 22:24:24 +0000324 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000325 if (File.isObj()) {
326 P.formatLine("Dumping streams is not valid for object files");
327 return Error::success();
328 }
329
330 if (StreamPurposes.empty())
331 discoverStreamPurposes(getPdb(), StreamPurposes);
332
333 uint32_t StreamCount = getPdb().getNumStreams();
334 uint32_t MaxStreamSize = getPdb().getMaxStreamSize();
Zachary Turner63055452017-06-15 22:24:24 +0000335
336 for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) {
337 P.formatLine(
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000338 "Stream {0} ({1} bytes): [{2}]",
Zachary Turner63055452017-06-15 22:24:24 +0000339 fmt_align(StreamIdx, AlignStyle::Right, NumDigits(StreamCount)),
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000340 fmt_align(getPdb().getStreamByteSize(StreamIdx), AlignStyle::Right,
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000341 NumDigits(MaxStreamSize)),
342 StreamPurposes[StreamIdx].getLongName());
343
Zachary Turner5f098522017-06-23 20:28:14 +0000344 if (opts::dump::DumpStreamBlocks) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000345 auto Blocks = getPdb().getStreamBlockList(StreamIdx);
Zachary Turner5f098522017-06-23 20:28:14 +0000346 std::vector<uint32_t> BV(Blocks.begin(), Blocks.end());
347 P.formatLine(" {0} Blocks: [{1}]",
348 fmt_repeat(' ', NumDigits(StreamCount)),
349 make_range(BV.begin(), BV.end()));
350 }
Zachary Turner63055452017-06-15 22:24:24 +0000351 }
352
353 return Error::success();
354}
355
Zachary Turner0e327d02017-06-15 23:12:41 +0000356static Expected<ModuleDebugStreamRef> getModuleDebugStream(PDBFile &File,
357 uint32_t Index) {
Reid Klecknerdd853e52017-07-27 23:13:18 +0000358 ExitOnError Err("Unexpected error: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000359
360 auto &Dbi = Err(File.getPDBDbiStream());
361 const auto &Modules = Dbi.modules();
362 auto Modi = Modules.getModuleDescriptor(Index);
363
364 uint16_t ModiStream = Modi.getModuleStreamIndex();
365 if (ModiStream == kInvalidStreamIndex)
366 return make_error<RawError>(raw_error_code::no_stream,
367 "Module stream not present");
368
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000369 auto ModStreamData = File.createIndexedStream(ModiStream);
Zachary Turner0e327d02017-06-15 23:12:41 +0000370
371 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
372 if (auto EC = ModS.reload())
373 return make_error<RawError>(raw_error_code::corrupt_file,
374 "Invalid module stream");
375
376 return std::move(ModS);
377}
378
Zachary Turnerf2872b92017-06-15 23:59:56 +0000379template <typename CallbackT>
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000380static void
381iterateOneModule(InputFile &File, const Optional<PrintScope> &HeaderScope,
382 const SymbolGroup &SG, uint32_t Modi, CallbackT Callback) {
383 if (HeaderScope) {
384 HeaderScope->P.formatLine(
385 "Mod {0:4} | `{1}`: ",
386 fmt_align(Modi, AlignStyle::Right, HeaderScope->LabelWidth), SG.name());
387 }
Zachary Turner58699362017-08-03 23:11:52 +0000388
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000389 AutoIndent Indent(HeaderScope);
390 Callback(Modi, SG);
Zachary Turner58699362017-08-03 23:11:52 +0000391}
392
393template <typename CallbackT>
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000394static void iterateSymbolGroups(InputFile &Input,
395 const Optional<PrintScope> &HeaderScope,
396 CallbackT Callback) {
397 AutoIndent Indent(HeaderScope);
Zachary Turnerf2872b92017-06-15 23:59:56 +0000398
Reid Klecknerdd853e52017-07-27 23:13:18 +0000399 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turnerf2872b92017-06-15 23:59:56 +0000400
Zachary Turner58699362017-08-03 23:11:52 +0000401 if (opts::dump::DumpModi.getNumOccurrences() > 0) {
402 assert(opts::dump::DumpModi.getNumOccurrences() == 1);
403 uint32_t Modi = opts::dump::DumpModi;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000404 SymbolGroup SG(&Input, Modi);
405 iterateOneModule(Input, withLabelWidth(HeaderScope, NumDigits(Modi)), SG,
406 Modi, Callback);
Zachary Turner58699362017-08-03 23:11:52 +0000407 return;
408 }
409
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000410 uint32_t I = 0;
411
412 for (const auto &SG : Input.symbol_groups()) {
413 if (shouldDumpSymbolGroup(I, SG))
414 iterateOneModule(Input, withLabelWidth(HeaderScope, NumDigits(I)), SG, I,
415 Callback);
416
417 ++I;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000418 }
419}
420
421template <typename SubsectionT>
422static void iterateModuleSubsections(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000423 InputFile &File, const Optional<PrintScope> &HeaderScope,
424 llvm::function_ref<void(uint32_t, const SymbolGroup &, SubsectionT &)>
Zachary Turnerf2872b92017-06-15 23:59:56 +0000425 Callback) {
426
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000427 iterateSymbolGroups(File, HeaderScope,
428 [&](uint32_t Modi, const SymbolGroup &SG) {
429 for (const auto &SS : SG.getDebugSubsections()) {
430 SubsectionT Subsection;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000431
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000432 if (SS.kind() != Subsection.kind())
433 continue;
Zachary Turnerf2872b92017-06-15 23:59:56 +0000434
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000435 BinaryStreamReader Reader(SS.getRecordData());
436 if (auto EC = Subsection.initialize(Reader))
437 continue;
438 Callback(Modi, SG, Subsection);
439 }
440 });
Zachary Turnerf2872b92017-06-15 23:59:56 +0000441}
442
Zachary Turner7df69952017-06-22 20:57:39 +0000443Error DumpOutputStyle::dumpModules() {
Zachary Turner63055452017-06-15 22:24:24 +0000444 printHeader(P, "Modules");
Zachary Turner63055452017-06-15 22:24:24 +0000445 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000446
447 if (File.isObj()) {
448 P.formatLine("Dumping modules is not supported for object files");
449 return Error::success();
450 }
451
452 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +0000453 P.formatLine("DBI Stream not present");
454 return Error::success();
455 }
456
Reid Klecknerdd853e52017-07-27 23:13:18 +0000457 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner63055452017-06-15 22:24:24 +0000458
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000459 auto &Stream = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +0000460
461 const DbiModuleList &Modules = Stream.modules();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000462 iterateSymbolGroups(
463 File, PrintScope{P, 11}, [&](uint32_t Modi, const SymbolGroup &Strings) {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000464 auto Desc = Modules.getModuleDescriptor(Modi);
465 P.formatLine("Obj: `{0}`: ", Desc.getObjFileName());
466 P.formatLine("debug stream: {0}, # files: {1}, has ec info: {2}",
467 Desc.getModuleStreamIndex(), Desc.getNumberOfFiles(),
468 Desc.hasECInfo());
469 StringRef PdbFilePath =
470 Err(Stream.getECName(Desc.getPdbFilePathNameIndex()));
471 StringRef SrcFilePath =
472 Err(Stream.getECName(Desc.getSourceFileNameIndex()));
473 P.formatLine("pdb file ni: {0} `{1}`, src file ni: {2} `{3}`",
474 Desc.getPdbFilePathNameIndex(), PdbFilePath,
475 Desc.getSourceFileNameIndex(), SrcFilePath);
476 });
Zachary Turner0e327d02017-06-15 23:12:41 +0000477 return Error::success();
478}
479
Zachary Turner7df69952017-06-22 20:57:39 +0000480Error DumpOutputStyle::dumpModuleFiles() {
Zachary Turner0e327d02017-06-15 23:12:41 +0000481 printHeader(P, "Files");
482
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000483 if (File.isObj()) {
484 P.formatLine("Dumping files is not valid for object files");
485 return Error::success();
486 }
487
Reid Klecknerdd853e52017-07-27 23:13:18 +0000488 ExitOnError Err("Unexpected error processing modules: ");
Zachary Turner0e327d02017-06-15 23:12:41 +0000489
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000490 iterateSymbolGroups(File, PrintScope{P, 11},
491 [this, &Err](uint32_t Modi, const SymbolGroup &Strings) {
492 auto &Stream = Err(getPdb().getPDBDbiStream());
Zachary Turner0e327d02017-06-15 23:12:41 +0000493
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000494 const DbiModuleList &Modules = Stream.modules();
495 for (const auto &F : Modules.source_files(Modi)) {
496 Strings.formatFromFileName(P, F);
497 }
498 });
Zachary Turner4e950642017-06-15 23:56:19 +0000499 return Error::success();
500}
501
Zachary Turner99c69822017-08-31 20:43:22 +0000502Error DumpOutputStyle::dumpSymbolStats() {
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000503 printHeader(P, "Module Stats");
504
505 ExitOnError Err("Unexpected error processing modules: ");
506
507 StatCollection SymStats;
508 StatCollection ChunkStats;
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000509
Zachary Turner41f07062017-09-01 20:17:20 +0000510 Optional<PrintScope> Scope;
511 if (File.isPdb())
512 Scope.emplace(P, 2);
513
514 iterateSymbolGroups(File, Scope, [&](uint32_t Modi, const SymbolGroup &SG) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000515 StatCollection SS = getSymbolStats(SG, SymStats);
516 StatCollection CS = getChunkStats(SG, ChunkStats);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000517
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000518 if (SG.getFile().isPdb()) {
Zachary Turner41f07062017-09-01 20:17:20 +0000519 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000520 auto Modules = cantFail(File.pdb().getPDBDbiStream()).modules();
521 uint32_t ModCount = Modules.getModuleCount();
522 DbiModuleDescriptor Desc = Modules.getModuleDescriptor(Modi);
523 uint32_t StreamIdx = Desc.getModuleStreamIndex();
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000524
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000525 if (StreamIdx == kInvalidStreamIndex) {
526 P.formatLine("Mod {0} (debug info not present): [{1}]",
527 fmt_align(Modi, AlignStyle::Right, NumDigits(ModCount)),
528 Desc.getModuleName());
529 return;
530 }
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000531 P.formatLine("Stream {0}, {1} bytes", StreamIdx,
532 getPdb().getStreamByteSize(StreamIdx));
533
534 printModuleDetailStats<SymbolKind>(P, "Symbols", SS);
535 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", CS);
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000536 }
Zachary Turnerd1de2f42017-08-21 14:53:25 +0000537 });
538
539 P.printLine(" Summary |");
540 AutoIndent Indent(P, 4);
541 if (SymStats.Totals.Count > 0) {
542 printModuleDetailStats<SymbolKind>(P, "Symbols", SymStats);
543 printModuleDetailStats<DebugSubsectionKind>(P, "Chunks", ChunkStats);
544 }
545
546 return Error::success();
547}
548
Zachary Turner99c69822017-08-31 20:43:22 +0000549static bool isValidNamespaceIdentifier(StringRef S) {
550 if (S.empty())
551 return false;
552
553 if (std::isdigit(S[0]))
554 return false;
555
556 return llvm::all_of(S, [](char C) { return std::isalnum(C); });
557}
558
559namespace {
560constexpr uint32_t kNoneUdtKind = 0;
561constexpr uint32_t kSimpleUdtKind = 1;
562constexpr uint32_t kUnknownUdtKind = 2;
563const StringRef NoneLabel("<none type>");
564const StringRef SimpleLabel("<simple type>");
565const StringRef UnknownLabel("<unknown type>");
566
567} // namespace
568
569static StringRef getUdtStatLabel(uint32_t Kind) {
570 if (Kind == kNoneUdtKind)
571 return NoneLabel;
572
573 if (Kind == kSimpleUdtKind)
574 return SimpleLabel;
575
576 if (Kind == kUnknownUdtKind)
577 return UnknownLabel;
578
579 return formatTypeLeafKind(static_cast<TypeLeafKind>(Kind));
580}
581
582static uint32_t getLongestTypeLeafName(const StatCollection &Stats) {
583 size_t L = 0;
584 for (const auto &Stat : Stats.Individual) {
585 StringRef Label = getUdtStatLabel(Stat.first);
586 L = std::max(L, Label.size());
587 }
588 return static_cast<uint32_t>(L);
589}
590
591Error DumpOutputStyle::dumpUdtStats() {
592 printHeader(P, "S_UDT Record Stats");
593
594 StatCollection UdtStats;
595 StatCollection UdtTargetStats;
Zachary Turner99c69822017-08-31 20:43:22 +0000596 AutoIndent Indent(P, 4);
597
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000598 auto &TpiTypes = File.types();
Zachary Turner99c69822017-08-31 20:43:22 +0000599
600 StringMap<StatCollection::Stat> NamespacedStats;
601
Zachary Turner99c69822017-08-31 20:43:22 +0000602 size_t LongestNamespace = 0;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000603 auto HandleOneSymbol = [&](const CVSymbol &Sym) {
Zachary Turner99c69822017-08-31 20:43:22 +0000604 if (Sym.kind() != SymbolKind::S_UDT)
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000605 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000606 UdtStats.update(SymbolKind::S_UDT, Sym.length());
607
608 UDTSym UDT = cantFail(SymbolDeserializer::deserializeAs<UDTSym>(Sym));
609
610 uint32_t Kind = 0;
611 uint32_t RecordSize = 0;
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000612
613 if (UDT.Type.isNoneType())
614 Kind = kNoneUdtKind;
615 else if (UDT.Type.isSimple())
616 Kind = kSimpleUdtKind;
617 else if (Optional<CVType> T = TpiTypes.tryGetType(UDT.Type)) {
618 Kind = T->kind();
619 RecordSize = T->length();
620 } else
621 Kind = kUnknownUdtKind;
Zachary Turner99c69822017-08-31 20:43:22 +0000622
623 UdtTargetStats.update(Kind, RecordSize);
624
625 size_t Pos = UDT.Name.find("::");
626 if (Pos == StringRef::npos)
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000627 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000628
629 StringRef Scope = UDT.Name.take_front(Pos);
630 if (Scope.empty() || !isValidNamespaceIdentifier(Scope))
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000631 return;
Zachary Turner99c69822017-08-31 20:43:22 +0000632
633 LongestNamespace = std::max(LongestNamespace, Scope.size());
634 NamespacedStats[Scope].update(RecordSize);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000635 };
636
637 P.NewLine();
638
639 if (File.isPdb()) {
640 if (!getPdb().hasPDBGlobalsStream()) {
641 P.printLine("- Error: globals stream not present");
642 return Error::success();
643 }
644
645 auto &SymbolRecords = cantFail(getPdb().getPDBSymbolStream());
Reid Kleckner145090f2017-10-27 00:45:51 +0000646 auto ExpGlobals = getPdb().getPDBGlobalsStream();
647 if (!ExpGlobals)
648 return ExpGlobals.takeError();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000649
Reid Kleckner145090f2017-10-27 00:45:51 +0000650 for (uint32_t PubSymOff : ExpGlobals->getGlobalsTable()) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000651 CVSymbol Sym = SymbolRecords.readRecord(PubSymOff);
652 HandleOneSymbol(Sym);
653 }
654 } else {
655 for (const auto &Sec : File.symbol_groups()) {
656 for (const auto &SS : Sec.getDebugSubsections()) {
657 if (SS.kind() != DebugSubsectionKind::Symbols)
658 continue;
659
660 DebugSymbolsSubsectionRef Symbols;
661 BinaryStreamReader Reader(SS.getRecordData());
662 cantFail(Symbols.initialize(Reader));
663 for (const auto &S : Symbols)
664 HandleOneSymbol(S);
665 }
666 }
Zachary Turner99c69822017-08-31 20:43:22 +0000667 }
668
669 LongestNamespace += StringRef(" namespace ''").size();
Zachary Turner4c806612017-08-31 20:50:25 +0000670 size_t LongestTypeLeafKind = getLongestTypeLeafName(UdtTargetStats);
671 size_t FieldWidth = std::max(LongestNamespace, LongestTypeLeafKind);
Zachary Turner99c69822017-08-31 20:43:22 +0000672
673 // Compute the max number of digits for count and size fields, including comma
674 // separators.
675 StringRef CountHeader("Count");
676 StringRef SizeHeader("Size");
Zachary Turner4c806612017-08-31 20:50:25 +0000677 size_t CD = NumDigits(UdtStats.Totals.Count);
Zachary Turner99c69822017-08-31 20:43:22 +0000678 CD += (CD - 1) / 3;
679 CD = std::max(CD, CountHeader.size());
680
Zachary Turner4c806612017-08-31 20:50:25 +0000681 size_t SD = NumDigits(UdtStats.Totals.Size);
Zachary Turner99c69822017-08-31 20:43:22 +0000682 SD += (SD - 1) / 3;
683 SD = std::max(SD, SizeHeader.size());
684
685 uint32_t TableWidth = FieldWidth + 3 + CD + 2 + SD + 1;
686
687 P.formatLine("{0} | {1} {2}",
688 fmt_align("Record Kind", AlignStyle::Right, FieldWidth),
689 fmt_align(CountHeader, AlignStyle::Right, CD),
690 fmt_align(SizeHeader, AlignStyle::Right, SD));
691
692 P.formatLine("{0}", fmt_repeat('-', TableWidth));
693 for (const auto &Stat : UdtTargetStats.Individual) {
694 StringRef Label = getUdtStatLabel(Stat.first);
695 P.formatLine("{0} | {1:N} {2:N}",
696 fmt_align(Label, AlignStyle::Right, FieldWidth),
697 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
698 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
699 }
700 P.formatLine("{0}", fmt_repeat('-', TableWidth));
701 P.formatLine("{0} | {1:N} {2:N}",
702 fmt_align("Total (S_UDT)", AlignStyle::Right, FieldWidth),
703 fmt_align(UdtStats.Totals.Count, AlignStyle::Right, CD),
704 fmt_align(UdtStats.Totals.Size, AlignStyle::Right, SD));
705 P.formatLine("{0}", fmt_repeat('-', TableWidth));
706 for (const auto &Stat : NamespacedStats) {
707 std::string Label = formatv("namespace '{0}'", Stat.getKey());
708 P.formatLine("{0} | {1:N} {2:N}",
709 fmt_align(Label, AlignStyle::Right, FieldWidth),
710 fmt_align(Stat.second.Count, AlignStyle::Right, CD),
711 fmt_align(Stat.second.Size, AlignStyle::Right, SD));
712 }
713 return Error::success();
714}
715
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000716static void typesetLinesAndColumns(LinePrinter &P, uint32_t Start,
717 const LineColumnEntry &E) {
Zachary Turner4e950642017-06-15 23:56:19 +0000718 const uint32_t kMaxCharsPerLineNumber = 4; // 4 digit line number
719 uint32_t MinColumnWidth = kMaxCharsPerLineNumber + 5;
720
721 // Let's try to keep it under 100 characters
722 constexpr uint32_t kMaxRowLength = 100;
723 // At least 3 spaces between columns.
724 uint32_t ColumnsPerRow = kMaxRowLength / (MinColumnWidth + 3);
725 uint32_t ItemsLeft = E.LineNumbers.size();
726 auto LineIter = E.LineNumbers.begin();
727 while (ItemsLeft != 0) {
728 uint32_t RowColumns = std::min(ItemsLeft, ColumnsPerRow);
729 for (uint32_t I = 0; I < RowColumns; ++I) {
730 LineInfo Line(LineIter->Flags);
731 std::string LineStr;
732 if (Line.isAlwaysStepInto())
733 LineStr = "ASI";
734 else if (Line.isNeverStepInto())
735 LineStr = "NSI";
Zachary Turner0e327d02017-06-15 23:12:41 +0000736 else
Zachary Turner4e950642017-06-15 23:56:19 +0000737 LineStr = utostr(Line.getStartLine());
738 char Statement = Line.isStatement() ? ' ' : '!';
739 P.format("{0} {1:X-} {2} ",
740 fmt_align(LineStr, AlignStyle::Right, kMaxCharsPerLineNumber),
741 fmt_align(Start + LineIter->Offset, AlignStyle::Right, 8, '0'),
742 Statement);
743 ++LineIter;
744 --ItemsLeft;
Zachary Turner63055452017-06-15 22:24:24 +0000745 }
Zachary Turner4e950642017-06-15 23:56:19 +0000746 P.NewLine();
Zachary Turner63055452017-06-15 22:24:24 +0000747 }
Zachary Turner4e950642017-06-15 23:56:19 +0000748}
749
Zachary Turner7df69952017-06-22 20:57:39 +0000750Error DumpOutputStyle::dumpLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000751 printHeader(P, "Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000752
Zachary Turnerf2872b92017-06-15 23:59:56 +0000753 uint32_t LastModi = UINT32_MAX;
754 uint32_t LastNameIndex = UINT32_MAX;
755 iterateModuleSubsections<DebugLinesSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000756 File, PrintScope{P, 4},
Zachary Turnerf2872b92017-06-15 23:59:56 +0000757 [this, &LastModi, &LastNameIndex](uint32_t Modi,
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000758 const SymbolGroup &Strings,
Zachary Turnerf2872b92017-06-15 23:59:56 +0000759 DebugLinesSubsectionRef &Lines) {
760 uint16_t Segment = Lines.header()->RelocSegment;
761 uint32_t Begin = Lines.header()->RelocOffset;
762 uint32_t End = Begin + Lines.header()->CodeSize;
763 for (const auto &Block : Lines) {
764 if (LastModi != Modi || LastNameIndex != Block.NameIndex) {
765 LastModi = Modi;
766 LastNameIndex = Block.NameIndex;
767 Strings.formatFromChecksumsOffset(P, Block.NameIndex);
Zachary Turner4e950642017-06-15 23:56:19 +0000768 }
769
Zachary Turnerf2872b92017-06-15 23:59:56 +0000770 AutoIndent Indent(P, 2);
771 P.formatLine("{0:X-4}:{1:X-8}-{2:X-8}, ", Segment, Begin, End);
772 uint32_t Count = Block.LineNumbers.size();
773 if (Lines.hasColumnInfo())
774 P.format("line/column/addr entries = {0}", Count);
775 else
776 P.format("line/addr entries = {0}", Count);
Zachary Turner4e950642017-06-15 23:56:19 +0000777
Zachary Turnerf2872b92017-06-15 23:59:56 +0000778 P.NewLine();
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000779 typesetLinesAndColumns(P, Begin, Block);
Zachary Turner4e950642017-06-15 23:56:19 +0000780 }
781 });
782
783 return Error::success();
784}
785
Zachary Turner7df69952017-06-22 20:57:39 +0000786Error DumpOutputStyle::dumpInlineeLines() {
Zachary Turner4e950642017-06-15 23:56:19 +0000787 printHeader(P, "Inlinee Lines");
Zachary Turner4e950642017-06-15 23:56:19 +0000788
Zachary Turnerf2872b92017-06-15 23:59:56 +0000789 iterateModuleSubsections<DebugInlineeLinesSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000790 File, PrintScope{P, 2},
791 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turnerf2872b92017-06-15 23:59:56 +0000792 DebugInlineeLinesSubsectionRef &Lines) {
793 P.formatLine("{0,+8} | {1,+5} | {2}", "Inlinee", "Line", "Source File");
794 for (const auto &Entry : Lines) {
795 P.formatLine("{0,+8} | {1,+5} | ", Entry.Header->Inlinee,
796 fmtle(Entry.Header->SourceLineNum));
797 Strings.formatFromChecksumsOffset(P, Entry.Header->FileID, true);
Zachary Turner4e950642017-06-15 23:56:19 +0000798 }
Zachary Turnerf2872b92017-06-15 23:59:56 +0000799 P.NewLine();
Zachary Turner4e950642017-06-15 23:56:19 +0000800 });
801
Zachary Turner63055452017-06-15 22:24:24 +0000802 return Error::success();
803}
Zachary Turner0e327d02017-06-15 23:12:41 +0000804
Zachary Turner7df69952017-06-22 20:57:39 +0000805Error DumpOutputStyle::dumpXmi() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000806 printHeader(P, "Cross Module Imports");
807 iterateModuleSubsections<DebugCrossModuleImportsSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000808 File, PrintScope{P, 2},
809 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turner47d9a562017-06-16 00:04:24 +0000810 DebugCrossModuleImportsSubsectionRef &Imports) {
811 P.formatLine("{0,=32} | {1}", "Imported Module", "Type IDs");
812
813 for (const auto &Xmi : Imports) {
814 auto ExpectedModule =
815 Strings.getNameFromStringTable(Xmi.Header->ModuleNameOffset);
816 StringRef Module;
817 SmallString<32> ModuleStorage;
818 if (!ExpectedModule) {
819 Module = "(unknown module)";
820 consumeError(ExpectedModule.takeError());
821 } else
822 Module = *ExpectedModule;
823 if (Module.size() > 32) {
824 ModuleStorage = "...";
825 ModuleStorage += Module.take_back(32 - 3);
826 Module = ModuleStorage;
827 }
828 std::vector<std::string> TIs;
829 for (const auto I : Xmi.Imports)
830 TIs.push_back(formatv("{0,+10:X+}", fmtle(I)));
831 std::string Result =
832 typesetItemList(TIs, P.getIndentLevel() + 35, 12, " ");
833 P.formatLine("{0,+32} | {1}", Module, Result);
834 }
835 });
836
837 return Error::success();
838}
839
Zachary Turner7df69952017-06-22 20:57:39 +0000840Error DumpOutputStyle::dumpXme() {
Zachary Turner47d9a562017-06-16 00:04:24 +0000841 printHeader(P, "Cross Module Exports");
842
843 iterateModuleSubsections<DebugCrossModuleExportsSubsectionRef>(
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000844 File, PrintScope{P, 2},
845 [this](uint32_t Modi, const SymbolGroup &Strings,
Zachary Turner47d9a562017-06-16 00:04:24 +0000846 DebugCrossModuleExportsSubsectionRef &Exports) {
847 P.formatLine("{0,-10} | {1}", "Local ID", "Global ID");
848 for (const auto &Export : Exports) {
849 P.formatLine("{0,+10:X+} | {1}", TypeIndex(Export.Local),
850 TypeIndex(Export.Global));
851 }
852 });
853
854 return Error::success();
855}
856
Zachary Turner60478582018-01-05 19:12:40 +0000857Error DumpOutputStyle::dumpStringTableFromPdb() {
Zachary Turner63055452017-06-15 22:24:24 +0000858 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +0000859 auto IS = getPdb().getStringTable();
Zachary Turner63055452017-06-15 22:24:24 +0000860 if (!IS) {
861 P.formatLine("Not present in file");
862 consumeError(IS.takeError());
863 return Error::success();
864 }
865
Zachary Turnera6fb5362018-03-23 18:43:39 +0000866 if (opts::dump::DumpStringTable) {
867 if (IS->name_ids().empty())
868 P.formatLine("Empty");
869 else {
870 auto MaxID =
871 std::max_element(IS->name_ids().begin(), IS->name_ids().end());
872 uint32_t Digits = NumDigits(*MaxID);
873
874 P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
875 "String");
876
877 std::vector<uint32_t> SortedIDs(IS->name_ids().begin(),
878 IS->name_ids().end());
879 std::sort(SortedIDs.begin(), SortedIDs.end());
880 for (uint32_t I : SortedIDs) {
881 auto ES = IS->getStringForID(I);
882 llvm::SmallString<32> Str;
883 if (!ES) {
884 consumeError(ES.takeError());
885 Str = "Error reading string";
886 } else if (!ES->empty()) {
887 Str.append("'");
888 Str.append(*ES);
889 Str.append("'");
890 }
891
892 if (!Str.empty())
893 P.formatLine("{0} | {1}", fmt_align(I, AlignStyle::Right, Digits),
894 Str);
895 }
896 }
Zachary Turner63055452017-06-15 22:24:24 +0000897 }
898
Zachary Turnera6fb5362018-03-23 18:43:39 +0000899 if (opts::dump::DumpStringTableDetails) {
900 P.NewLine();
901 {
902 P.printLine("String Table Header:");
903 AutoIndent Indent(P);
904 P.formatLine("Signature: {0}", IS->getSignature());
905 P.formatLine("Hash Version: {0}", IS->getHashVersion());
906 P.formatLine("Name Buffer Size: {0}", IS->getByteSize());
907 P.NewLine();
Zachary Turner63055452017-06-15 22:24:24 +0000908 }
909
Zachary Turnera6fb5362018-03-23 18:43:39 +0000910 BinaryStreamRef NameBuffer = IS->getStringTable().getBuffer();
911 ArrayRef<uint8_t> Contents;
912 cantFail(NameBuffer.readBytes(0, NameBuffer.getLength(), Contents));
913 P.formatBinary("Name Buffer", Contents, 0);
914 P.NewLine();
915 {
916 P.printLine("Hash Table:");
917 AutoIndent Indent(P);
918 P.formatLine("Bucket Count: {0}", IS->name_ids().size());
919 for (const auto &Entry : enumerate(IS->name_ids()))
920 P.formatLine("Bucket[{0}] : {1}", Entry.index(),
921 uint32_t(Entry.value()));
922 P.formatLine("Name Count: {0}", IS->getNameCount());
923 }
Zachary Turner63055452017-06-15 22:24:24 +0000924 }
925 return Error::success();
926}
927
Zachary Turner60478582018-01-05 19:12:40 +0000928Error DumpOutputStyle::dumpStringTableFromObj() {
929 iterateModuleSubsections<DebugStringTableSubsectionRef>(
930 File, PrintScope{P, 4},
931 [&](uint32_t Modi, const SymbolGroup &Strings,
932 DebugStringTableSubsectionRef &Strings2) {
933 BinaryStreamRef StringTableBuffer = Strings2.getBuffer();
934 BinaryStreamReader Reader(StringTableBuffer);
935 while (Reader.bytesRemaining() > 0) {
936 StringRef Str;
937 uint32_t Offset = Reader.getOffset();
938 cantFail(Reader.readCString(Str));
939 if (Str.empty())
940 continue;
941
942 P.formatLine("{0} | {1}", fmt_align(Offset, AlignStyle::Right, 4),
943 Str);
944 }
945 });
946 return Error::success();
947}
948
Zachary Turnera6fb5362018-03-23 18:43:39 +0000949Error DumpOutputStyle::dumpNamedStreams() {
950 printHeader(P, "Named Streams");
951 AutoIndent Indent(P, 2);
952
953 if (File.isObj()) {
954 P.formatLine("Dumping Named Streams is only supported for PDB files.");
955 return Error::success();
956 }
957 ExitOnError Err("Invalid PDB File: ");
958
959 auto &IS = Err(File.pdb().getPDBInfoStream());
960 const NamedStreamMap &NS = IS.getNamedStreams();
961 for (const auto &Entry : NS.entries()) {
962 P.printLine(Entry.getKey());
963 AutoIndent Indent2(P, 2);
964 P.formatLine("Index: {0}", Entry.getValue());
965 P.formatLine("Size in bytes: {0}",
966 File.pdb().getStreamByteSize(Entry.getValue()));
967 }
968
969 return Error::success();
970}
971
Zachary Turner60478582018-01-05 19:12:40 +0000972Error DumpOutputStyle::dumpStringTable() {
973 printHeader(P, "String Table");
974
975 if (File.isPdb())
976 return dumpStringTableFromPdb();
977
978 return dumpStringTableFromObj();
979}
980
Zachary Turner02a26772017-06-30 18:15:47 +0000981static void buildDepSet(LazyRandomTypeCollection &Types,
982 ArrayRef<TypeIndex> Indices,
983 std::map<TypeIndex, CVType> &DepSet) {
984 SmallVector<TypeIndex, 4> DepList;
985 for (const auto &I : Indices) {
986 TypeIndex TI(I);
987 if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType())
988 continue;
989
990 CVType Type = Types.getType(TI);
991 DepSet[TI] = Type;
992 codeview::discoverTypeIndices(Type, DepList);
993 buildDepSet(Types, DepList, DepSet);
994 }
995}
996
Zachary Turner376d4372017-12-05 23:58:18 +0000997static void
998dumpFullTypeStream(LinePrinter &Printer, LazyRandomTypeCollection &Types,
Zachary Turner2ed069e2017-12-06 00:26:43 +0000999 uint32_t NumTypeRecords, uint32_t NumHashBuckets,
Zachary Turner376d4372017-12-05 23:58:18 +00001000 FixedStreamArray<support::ulittle32_t> HashValues,
1001 bool Bytes, bool Extras) {
1002
Zachary Turner2ed069e2017-12-06 00:26:43 +00001003 Printer.formatLine("Showing {0:N} records", NumTypeRecords);
1004 uint32_t Width = NumDigits(TypeIndex::FirstNonSimpleIndex + NumTypeRecords);
Zachary Turner02a26772017-06-30 18:15:47 +00001005
1006 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Zachary Turner376d4372017-12-05 23:58:18 +00001007 NumHashBuckets, HashValues);
Zachary Turner02a26772017-06-30 18:15:47 +00001008
1009 if (auto EC = codeview::visitTypeStream(Types, V)) {
1010 Printer.formatLine("An error occurred dumping type records: {0}",
1011 toString(std::move(EC)));
1012 }
1013}
1014
1015static void dumpPartialTypeStream(LinePrinter &Printer,
1016 LazyRandomTypeCollection &Types,
1017 TpiStream &Stream, ArrayRef<TypeIndex> TiList,
1018 bool Bytes, bool Extras, bool Deps) {
1019 uint32_t Width =
1020 NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords());
1021
1022 MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types,
Reid Klecknerc50349d2017-07-18 00:33:45 +00001023 Stream.getNumHashBuckets(), Stream.getHashValues());
Zachary Turner02a26772017-06-30 18:15:47 +00001024
1025 if (opts::dump::DumpTypeDependents) {
1026 // If we need to dump all dependents, then iterate each index and find
1027 // all dependents, adding them to a map ordered by TypeIndex.
1028 std::map<TypeIndex, CVType> DepSet;
1029 buildDepSet(Types, TiList, DepSet);
1030
1031 Printer.formatLine(
1032 "Showing {0:N} records and their dependents ({1:N} records total)",
1033 TiList.size(), DepSet.size());
1034
1035 for (auto &Dep : DepSet) {
1036 if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V))
1037 Printer.formatLine("An error occurred dumping type record {0}: {1}",
1038 Dep.first, toString(std::move(EC)));
1039 }
1040 } else {
1041 Printer.formatLine("Showing {0:N} records.", TiList.size());
1042
1043 for (const auto &I : TiList) {
1044 TypeIndex TI(I);
1045 CVType Type = Types.getType(TI);
1046 if (auto EC = codeview::visitTypeRecord(Type, TI, V))
1047 Printer.formatLine("An error occurred dumping type record {0}: {1}", TI,
1048 toString(std::move(EC)));
1049 }
1050 }
1051}
1052
Zachary Turner376d4372017-12-05 23:58:18 +00001053Error DumpOutputStyle::dumpTypesFromObjectFile() {
1054 LazyRandomTypeCollection Types(100);
1055
1056 for (const auto &S : getObj().sections()) {
1057 StringRef SectionName;
1058 if (auto EC = S.getName(SectionName))
1059 return errorCodeToError(EC);
1060
1061 if (SectionName != ".debug$T")
1062 continue;
1063 StringRef Contents;
1064 if (auto EC = S.getContents(Contents))
1065 return errorCodeToError(EC);
1066
1067 uint32_t Magic;
1068 BinaryStreamReader Reader(Contents, llvm::support::little);
1069 if (auto EC = Reader.readInteger(Magic))
1070 return EC;
1071 if (Magic != COFF::DEBUG_SECTION_MAGIC)
1072 return make_error<StringError>("Invalid CodeView debug section.",
1073 inconvertibleErrorCode());
1074
1075 Types.reset(Reader, 100);
1076
1077 if (opts::dump::DumpTypes) {
Zachary Turner2ed069e2017-12-06 00:26:43 +00001078 dumpFullTypeStream(P, Types, 0, 0, {}, opts::dump::DumpTypeData, false);
Zachary Turner376d4372017-12-05 23:58:18 +00001079 } else if (opts::dump::DumpTypeExtras) {
1080 auto LocalHashes = LocallyHashedType::hashTypeCollection(Types);
1081 auto GlobalHashes = GloballyHashedType::hashTypeCollection(Types);
1082 assert(LocalHashes.size() == GlobalHashes.size());
1083
1084 P.formatLine("Local / Global hashes:");
1085 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
1086 for (const auto &H : zip(LocalHashes, GlobalHashes)) {
1087 AutoIndent Indent2(P);
1088 LocallyHashedType &L = std::get<0>(H);
1089 GloballyHashedType &G = std::get<1>(H);
1090
1091 P.formatLine("TI: {0}, LocalHash: {1:X}, GlobalHash: {2}", TI, L, G);
1092
1093 ++TI;
1094 }
1095 P.NewLine();
1096 }
1097 }
1098
1099 return Error::success();
1100}
1101
Zachary Turner7df69952017-06-22 20:57:39 +00001102Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) {
Zachary Turner63055452017-06-15 22:24:24 +00001103 assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI);
1104
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001105 if (StreamIdx == StreamTPI) {
1106 printHeader(P, "Types (TPI Stream)");
1107 } else if (StreamIdx == StreamIPI) {
1108 printHeader(P, "Types (IPI Stream)");
1109 }
1110
1111 AutoIndent Indent(P);
Zachary Turner376d4372017-12-05 23:58:18 +00001112 assert(!File.isObj());
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001113
Zachary Turner63055452017-06-15 22:24:24 +00001114 bool Present = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001115 bool DumpTypes = false;
Zachary Turner63055452017-06-15 22:24:24 +00001116 bool DumpBytes = false;
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001117 bool DumpExtras = false;
Zachary Turner59224cb2017-06-16 23:42:15 +00001118 std::vector<uint32_t> Indices;
Zachary Turner63055452017-06-15 22:24:24 +00001119 if (StreamIdx == StreamTPI) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001120 Present = getPdb().hasPDBTpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +00001121 DumpTypes = opts::dump::DumpTypes;
1122 DumpBytes = opts::dump::DumpTypeData;
1123 DumpExtras = opts::dump::DumpTypeExtras;
1124 Indices.assign(opts::dump::DumpTypeIndex.begin(),
1125 opts::dump::DumpTypeIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +00001126 } else if (StreamIdx == StreamIPI) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001127 Present = getPdb().hasPDBIpiStream();
Zachary Turner7df69952017-06-22 20:57:39 +00001128 DumpTypes = opts::dump::DumpIds;
1129 DumpBytes = opts::dump::DumpIdData;
1130 DumpExtras = opts::dump::DumpIdExtras;
1131 Indices.assign(opts::dump::DumpIdIndex.begin(),
1132 opts::dump::DumpIdIndex.end());
Zachary Turner63055452017-06-15 22:24:24 +00001133 }
1134
Zachary Turner63055452017-06-15 22:24:24 +00001135 if (!Present) {
1136 P.formatLine("Stream not present");
1137 return Error::success();
1138 }
1139
Reid Klecknerdd853e52017-07-27 23:13:18 +00001140 ExitOnError Err("Unexpected error processing types: ");
Zachary Turner63055452017-06-15 22:24:24 +00001141
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001142 auto &Stream = Err((StreamIdx == StreamTPI) ? getPdb().getPDBTpiStream()
1143 : getPdb().getPDBIpiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001144
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001145 auto &Types = (StreamIdx == StreamTPI) ? File.types() : File.ids();
Zachary Turner63055452017-06-15 22:24:24 +00001146
Zachary Turner02a26772017-06-30 18:15:47 +00001147 if (DumpTypes || !Indices.empty()) {
1148 if (Indices.empty())
Zachary Turner2ed069e2017-12-06 00:26:43 +00001149 dumpFullTypeStream(P, Types, Stream.getNumTypeRecords(),
1150 Stream.getNumHashBuckets(), Stream.getHashValues(),
1151 DumpBytes, DumpExtras);
Zachary Turner02a26772017-06-30 18:15:47 +00001152 else {
1153 std::vector<TypeIndex> TiList(Indices.begin(), Indices.end());
1154 dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras,
1155 opts::dump::DumpTypeDependents);
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001156 }
1157 }
1158
1159 if (DumpExtras) {
1160 P.NewLine();
1161 auto IndexOffsets = Stream.getTypeIndexOffsets();
1162 P.formatLine("Type Index Offsets:");
1163 for (const auto &IO : IndexOffsets) {
1164 AutoIndent Indent2(P);
1165 P.formatLine("TI: {0}, Offset: {1}", IO.Type, fmtle(IO.Offset));
1166 }
1167
1168 P.NewLine();
1169 P.formatLine("Hash Adjusters:");
1170 auto &Adjusters = Stream.getHashAdjusters();
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001171 auto &Strings = Err(getPdb().getStringTable());
Zachary Turnerf8a2e042017-06-15 23:04:42 +00001172 for (const auto &A : Adjusters) {
1173 AutoIndent Indent2(P);
1174 auto ExpectedStr = Strings.getStringForID(A.first);
1175 TypeIndex TI(A.second);
1176 if (ExpectedStr)
1177 P.formatLine("`{0}` -> {1}", *ExpectedStr, TI);
1178 else {
1179 P.formatLine("unknown str id ({0}) -> {1}", A.first, TI);
1180 consumeError(ExpectedStr.takeError());
1181 }
1182 }
Zachary Turner63055452017-06-15 22:24:24 +00001183 }
1184 return Error::success();
1185}
1186
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001187Error DumpOutputStyle::dumpModuleSymsForObj() {
Zachary Turner63055452017-06-15 22:24:24 +00001188 printHeader(P, "Symbols");
1189
1190 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001191
1192 ExitOnError Err("Unexpected error processing symbols: ");
1193
1194 auto &Types = File.types();
1195
1196 SymbolVisitorCallbackPipeline Pipeline;
1197 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::ObjectFile);
1198 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Types, Types);
1199
1200 Pipeline.addCallbackToPipeline(Deserializer);
1201 Pipeline.addCallbackToPipeline(Dumper);
1202 CVSymbolVisitor Visitor(Pipeline);
1203
1204 std::unique_ptr<llvm::Error> SymbolError;
1205
1206 iterateModuleSubsections<DebugSymbolsSubsectionRef>(
1207 File, PrintScope{P, 2},
1208 [&](uint32_t Modi, const SymbolGroup &Strings,
1209 DebugSymbolsSubsectionRef &Symbols) {
Zachary Turner60478582018-01-05 19:12:40 +00001210 Dumper.setSymbolGroup(&Strings);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001211 for (auto Symbol : Symbols) {
1212 if (auto EC = Visitor.visitSymbolRecord(Symbol)) {
1213 SymbolError = llvm::make_unique<Error>(std::move(EC));
1214 return;
1215 }
1216 }
1217 });
1218
1219 if (SymbolError)
1220 return std::move(*SymbolError);
1221
1222 return Error::success();
1223}
1224
1225Error DumpOutputStyle::dumpModuleSymsForPdb() {
1226 printHeader(P, "Symbols");
1227
1228 AutoIndent Indent(P);
1229 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001230 P.formatLine("DBI Stream not present");
1231 return Error::success();
1232 }
1233
Reid Klecknerdd853e52017-07-27 23:13:18 +00001234 ExitOnError Err("Unexpected error processing symbols: ");
Zachary Turner63055452017-06-15 22:24:24 +00001235
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001236 auto &Ids = File.ids();
1237 auto &Types = File.types();
Zachary Turner63055452017-06-15 22:24:24 +00001238
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001239 iterateSymbolGroups(
1240 File, PrintScope{P, 2}, [&](uint32_t I, const SymbolGroup &Strings) {
1241 auto ExpectedModS = getModuleDebugStream(File.pdb(), I);
Zachary Turner58699362017-08-03 23:11:52 +00001242 if (!ExpectedModS) {
1243 P.formatLine("Error loading module stream {0}. {1}", I,
1244 toString(ExpectedModS.takeError()));
1245 return;
1246 }
Zachary Turner63055452017-06-15 22:24:24 +00001247
Zachary Turner58699362017-08-03 23:11:52 +00001248 ModuleDebugStreamRef &ModS = *ExpectedModS;
Zachary Turner63055452017-06-15 22:24:24 +00001249
Zachary Turner58699362017-08-03 23:11:52 +00001250 SymbolVisitorCallbackPipeline Pipeline;
1251 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
Zachary Turner60478582018-01-05 19:12:40 +00001252 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Strings,
1253 Ids, Types);
Zachary Turner63055452017-06-15 22:24:24 +00001254
Zachary Turner58699362017-08-03 23:11:52 +00001255 Pipeline.addCallbackToPipeline(Deserializer);
1256 Pipeline.addCallbackToPipeline(Dumper);
1257 CVSymbolVisitor Visitor(Pipeline);
1258 auto SS = ModS.getSymbolsSubstream();
1259 if (auto EC =
1260 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) {
1261 P.formatLine("Error while processing symbol records. {0}",
1262 toString(std::move(EC)));
1263 return;
1264 }
1265 });
Zachary Turner63055452017-06-15 22:24:24 +00001266 return Error::success();
1267}
1268
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001269Error DumpOutputStyle::dumpGlobals() {
1270 printHeader(P, "Global Symbols");
1271 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001272
1273 if (File.isObj()) {
1274 P.formatLine("Dumping Globals is not supported for object files");
1275 return Error::success();
1276 }
1277
1278 if (!getPdb().hasPDBGlobalsStream()) {
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001279 P.formatLine("Globals stream not present");
1280 return Error::success();
1281 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001282 ExitOnError Err("Error dumping globals stream: ");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001283 auto &Globals = Err(getPdb().getPDBGlobalsStream());
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001284
1285 const GSIHashTable &Table = Globals.getGlobalsTable();
1286 Err(dumpSymbolsFromGSI(Table, opts::dump::DumpGlobalExtras));
1287 return Error::success();
1288}
1289
Zachary Turner7df69952017-06-22 20:57:39 +00001290Error DumpOutputStyle::dumpPublics() {
Zachary Turner63055452017-06-15 22:24:24 +00001291 printHeader(P, "Public Symbols");
Zachary Turner63055452017-06-15 22:24:24 +00001292 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001293
1294 if (File.isObj()) {
1295 P.formatLine("Dumping Globals is not supported for object files");
1296 return Error::success();
1297 }
1298
1299 if (!getPdb().hasPDBPublicsStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001300 P.formatLine("Publics stream not present");
1301 return Error::success();
1302 }
Reid Klecknerdd853e52017-07-27 23:13:18 +00001303 ExitOnError Err("Error dumping publics stream: ");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001304 auto &Publics = Err(getPdb().getPDBPublicsStream());
Zachary Turner63055452017-06-15 22:24:24 +00001305
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001306 const GSIHashTable &PublicsTable = Publics.getPublicsTable();
Zachary Turner5448dab2017-08-09 04:23:59 +00001307 if (opts::dump::DumpPublicExtras) {
1308 P.printLine("Publics Header");
1309 AutoIndent Indent(P);
1310 P.formatLine("sym hash = {0}, thunk table addr = {1}", Publics.getSymHash(),
1311 formatSegmentOffset(Publics.getThunkTableSection(),
1312 Publics.getThunkTableOffset()));
1313 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001314 Err(dumpSymbolsFromGSI(PublicsTable, opts::dump::DumpPublicExtras));
Zachary Turneraf8c75a2017-06-30 21:35:00 +00001315
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001316 // Skip the rest if we aren't dumping extras.
Reid Kleckner686f1212017-07-21 18:28:55 +00001317 if (!opts::dump::DumpPublicExtras)
1318 return Error::success();
1319
Reid Kleckner686f1212017-07-21 18:28:55 +00001320 P.formatLine("Address Map");
1321 {
1322 // These are offsets into the publics stream sorted by secidx:secrel.
1323 AutoIndent Indent2(P);
1324 for (uint32_t Addr : Publics.getAddressMap())
1325 P.formatLine("off = {0}", Addr);
1326 }
1327
1328 // The thunk map is optional debug info used for ILT thunks.
1329 if (!Publics.getThunkMap().empty()) {
1330 P.formatLine("Thunk Map");
1331 AutoIndent Indent2(P);
1332 for (uint32_t Addr : Publics.getThunkMap())
1333 P.formatLine("{0:x8}", Addr);
1334 }
1335
1336 // The section offsets table appears to be empty when incremental linking
1337 // isn't in use.
1338 if (!Publics.getSectionOffsets().empty()) {
1339 P.formatLine("Section Offsets");
1340 AutoIndent Indent2(P);
1341 for (const SectionOffset &SO : Publics.getSectionOffsets())
1342 P.formatLine("{0:x4}:{1:x8}", uint16_t(SO.Isect), uint32_t(SO.Off));
1343 }
1344
Zachary Turner63055452017-06-15 22:24:24 +00001345 return Error::success();
1346}
1347
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001348Error DumpOutputStyle::dumpSymbolsFromGSI(const GSIHashTable &Table,
1349 bool HashExtras) {
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001350 auto ExpectedSyms = getPdb().getPDBSymbolStream();
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001351 if (!ExpectedSyms)
1352 return ExpectedSyms.takeError();
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001353 auto &Types = File.types();
1354 auto &Ids = File.ids();
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001355
Zachary Turner5448dab2017-08-09 04:23:59 +00001356 if (HashExtras) {
1357 P.printLine("GSI Header");
1358 AutoIndent Indent(P);
1359 P.formatLine("sig = {0:X}, hdr = {1:X}, hr size = {2}, num buckets = {3}",
1360 Table.getVerSignature(), Table.getVerHeader(),
1361 Table.getHashRecordSize(), Table.getNumBuckets());
1362 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001363
Zachary Turner5448dab2017-08-09 04:23:59 +00001364 {
1365 P.printLine("Records");
1366 SymbolVisitorCallbackPipeline Pipeline;
1367 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001368 MinimalSymbolDumper Dumper(P, opts::dump::DumpSymRecordBytes, Ids, Types);
Zachary Turner5448dab2017-08-09 04:23:59 +00001369
1370 Pipeline.addCallbackToPipeline(Deserializer);
1371 Pipeline.addCallbackToPipeline(Dumper);
1372 CVSymbolVisitor Visitor(Pipeline);
1373
1374 BinaryStreamRef SymStream =
1375 ExpectedSyms->getSymbolArray().getUnderlyingStream();
1376 for (uint32_t PubSymOff : Table) {
1377 Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff);
1378 if (!Sym)
1379 return Sym.takeError();
1380 if (auto E = Visitor.visitSymbolRecord(*Sym, PubSymOff))
1381 return E;
1382 }
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001383 }
1384
1385 // Return early if we aren't dumping public hash table and address map info.
1386 if (!HashExtras)
1387 return Error::success();
1388
Zachary Turner5448dab2017-08-09 04:23:59 +00001389 P.formatLine("Hash Entries");
Reid Kleckner14d90fd2017-07-26 00:40:36 +00001390 {
1391 AutoIndent Indent2(P);
1392 for (const PSHashRecord &HR : Table.HashRecords)
1393 P.formatLine("off = {0}, refcnt = {1}", uint32_t(HR.Off),
1394 uint32_t(HR.CRef));
1395 }
1396
1397 // FIXME: Dump the bitmap.
1398
1399 P.formatLine("Hash Buckets");
1400 {
1401 AutoIndent Indent2(P);
1402 for (uint32_t Hash : Table.HashBuckets)
1403 P.formatLine("{0:x8}", Hash);
1404 }
1405
1406 return Error::success();
1407}
1408
Zachary Turner63055452017-06-15 22:24:24 +00001409static std::string formatSegMapDescriptorFlag(uint32_t IndentLevel,
1410 OMFSegDescFlags Flags) {
1411 std::vector<std::string> Opts;
1412 if (Flags == OMFSegDescFlags::None)
1413 return "none";
1414
1415 PUSH_FLAG(OMFSegDescFlags, Read, Flags, "read");
1416 PUSH_FLAG(OMFSegDescFlags, Write, Flags, "write");
1417 PUSH_FLAG(OMFSegDescFlags, Execute, Flags, "execute");
1418 PUSH_FLAG(OMFSegDescFlags, AddressIs32Bit, Flags, "32 bit addr");
1419 PUSH_FLAG(OMFSegDescFlags, IsSelector, Flags, "selector");
1420 PUSH_FLAG(OMFSegDescFlags, IsAbsoluteAddress, Flags, "absolute addr");
1421 PUSH_FLAG(OMFSegDescFlags, IsGroup, Flags, "group");
Zachary Turner47d9a562017-06-16 00:04:24 +00001422 return typesetItemList(Opts, IndentLevel, 4, " | ");
Zachary Turner63055452017-06-15 22:24:24 +00001423}
1424
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001425Error DumpOutputStyle::dumpSectionHeaders() {
1426 dumpSectionHeaders("Section Headers", DbgHeaderType::SectionHdr);
1427 dumpSectionHeaders("Original Section Headers", DbgHeaderType::SectionHdrOrig);
1428 return Error::success();
1429}
1430
Zachary Turner92e584c2017-08-04 21:10:04 +00001431static Expected<std::pair<std::unique_ptr<MappedBlockStream>,
1432 ArrayRef<llvm::object::coff_section>>>
1433loadSectionHeaders(PDBFile &File, DbgHeaderType Type) {
1434 if (!File.hasPDBDbiStream())
1435 return make_error<StringError>(
1436 "Section headers require a DBI Stream, which could not be loaded",
1437 inconvertibleErrorCode());
1438
1439 auto &Dbi = cantFail(File.getPDBDbiStream());
1440 uint32_t SI = Dbi.getDebugStreamIndex(Type);
1441
1442 if (SI == kInvalidStreamIndex)
1443 return make_error<StringError>(
1444 "PDB does not contain the requested image section header type",
1445 inconvertibleErrorCode());
1446
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001447 auto Stream = File.createIndexedStream(SI);
Zachary Turner92e584c2017-08-04 21:10:04 +00001448 if (!Stream)
1449 return make_error<StringError>("Could not load the required stream data",
1450 inconvertibleErrorCode());
1451
1452 ArrayRef<object::coff_section> Headers;
1453 if (Stream->getLength() % sizeof(object::coff_section) != 0)
1454 return make_error<StringError>(
1455 "Section header array size is not a multiple of section header size",
1456 inconvertibleErrorCode());
1457
1458 uint32_t NumHeaders = Stream->getLength() / sizeof(object::coff_section);
1459 BinaryStreamReader Reader(*Stream);
1460 cantFail(Reader.readArray(Headers, NumHeaders));
1461 return std::make_pair(std::move(Stream), Headers);
1462}
1463
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001464void DumpOutputStyle::dumpSectionHeaders(StringRef Label, DbgHeaderType Type) {
1465 printHeader(P, Label);
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001466
1467 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001468 if (File.isObj()) {
1469 P.formatLine("Dumping Section Headers is not supported for object files");
1470 return;
1471 }
1472
1473 ExitOnError Err("Error dumping section headers: ");
Zachary Turner92e584c2017-08-04 21:10:04 +00001474 std::unique_ptr<MappedBlockStream> Stream;
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001475 ArrayRef<object::coff_section> Headers;
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001476 auto ExpectedHeaders = loadSectionHeaders(getPdb(), Type);
Zachary Turner92e584c2017-08-04 21:10:04 +00001477 if (!ExpectedHeaders) {
1478 P.printLine(toString(ExpectedHeaders.takeError()));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001479 return;
1480 }
Zachary Turner92e584c2017-08-04 21:10:04 +00001481 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001482
1483 uint32_t I = 1;
1484 for (const auto &Header : Headers) {
1485 P.NewLine();
1486 P.formatLine("SECTION HEADER #{0}", I);
1487 P.formatLine("{0,8} name", Header.Name);
1488 P.formatLine("{0,8:X-} virtual size", uint32_t(Header.VirtualSize));
1489 P.formatLine("{0,8:X-} virtual address", uint32_t(Header.VirtualAddress));
1490 P.formatLine("{0,8:X-} size of raw data", uint32_t(Header.SizeOfRawData));
1491 P.formatLine("{0,8:X-} file pointer to raw data",
1492 uint32_t(Header.PointerToRawData));
1493 P.formatLine("{0,8:X-} file pointer to relocation table",
1494 uint32_t(Header.PointerToRelocations));
1495 P.formatLine("{0,8:X-} file pointer to line numbers",
1496 uint32_t(Header.PointerToLinenumbers));
1497 P.formatLine("{0,8:X-} number of relocations",
1498 uint32_t(Header.NumberOfRelocations));
1499 P.formatLine("{0,8:X-} number of line numbers",
1500 uint32_t(Header.NumberOfLinenumbers));
1501 P.formatLine("{0,8:X-} flags", uint32_t(Header.Characteristics));
1502 AutoIndent IndentMore(P, 9);
1503 P.formatLine("{0}", formatSectionCharacteristics(
1504 P.getIndentLevel(), Header.Characteristics, 1, ""));
1505 ++I;
1506 }
1507 return;
1508}
1509
Zachary Turner92e584c2017-08-04 21:10:04 +00001510std::vector<std::string> getSectionNames(PDBFile &File) {
1511 auto ExpectedHeaders = loadSectionHeaders(File, DbgHeaderType::SectionHdr);
1512 if (!ExpectedHeaders)
1513 return {};
1514
1515 std::unique_ptr<MappedBlockStream> Stream;
1516 ArrayRef<object::coff_section> Headers;
1517 std::tie(Stream, Headers) = std::move(*ExpectedHeaders);
1518 std::vector<std::string> Names;
1519 for (const auto &H : Headers)
1520 Names.push_back(H.Name);
1521 return Names;
1522}
1523
Zachary Turner7df69952017-06-22 20:57:39 +00001524Error DumpOutputStyle::dumpSectionContribs() {
Zachary Turner63055452017-06-15 22:24:24 +00001525 printHeader(P, "Section Contributions");
Zachary Turner63055452017-06-15 22:24:24 +00001526
1527 AutoIndent Indent(P);
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001528 if (File.isObj()) {
1529 P.formatLine(
1530 "Dumping section contributions is not supported for object files");
1531 return Error::success();
1532 }
1533
1534 ExitOnError Err("Error dumping section contributions: ");
1535 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001536 P.formatLine(
1537 "Section contribs require a DBI Stream, which could not be loaded");
1538 return Error::success();
1539 }
1540
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001541 auto &Dbi = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001542
1543 class Visitor : public ISectionContribVisitor {
1544 public:
Zachary Turner92e584c2017-08-04 21:10:04 +00001545 Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
1546 auto Max = std::max_element(
1547 Names.begin(), Names.end(),
1548 [](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
1549 MaxNameLen = (Max == Names.end() ? 0 : Max->size());
1550 }
Zachary Turner63055452017-06-15 22:24:24 +00001551 void visit(const SectionContrib &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001552 assert(SC.ISect > 0);
Zachary Turner489a7a02017-08-07 20:24:01 +00001553 std::string NameInsert;
1554 if (SC.ISect < Names.size()) {
1555 StringRef SectionName = Names[SC.ISect - 1];
1556 NameInsert = formatv("[{0}]", SectionName).str();
1557 } else
1558 NameInsert = "[???]";
Zachary Turner92e584c2017-08-04 21:10:04 +00001559 P.formatLine("SC{5} | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1560 "crc = {4}",
1561 formatSegmentOffset(SC.ISect, SC.Off), fmtle(SC.Size),
1562 fmtle(SC.Imod), fmtle(SC.DataCrc), fmtle(SC.RelocCrc),
1563 fmt_align(NameInsert, AlignStyle::Left, MaxNameLen + 2));
1564 AutoIndent Indent(P, MaxNameLen + 2);
Zachary Turner63055452017-06-15 22:24:24 +00001565 P.formatLine(" {0}",
1566 formatSectionCharacteristics(P.getIndentLevel() + 6,
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001567 SC.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001568 }
1569 void visit(const SectionContrib2 &SC) override {
Zachary Turner92e584c2017-08-04 21:10:04 +00001570 P.formatLine(
1571 "SC2[{6}] | mod = {2}, {0}, size = {1}, data crc = {3}, reloc "
1572 "crc = {4}, coff section = {5}",
1573 formatSegmentOffset(SC.Base.ISect, SC.Base.Off), fmtle(SC.Base.Size),
1574 fmtle(SC.Base.Imod), fmtle(SC.Base.DataCrc), fmtle(SC.Base.RelocCrc),
1575 fmtle(SC.ISectCoff));
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001576 P.formatLine(" {0}", formatSectionCharacteristics(
1577 P.getIndentLevel() + 6,
1578 SC.Base.Characteristics, 3, " | "));
Zachary Turner63055452017-06-15 22:24:24 +00001579 }
1580
1581 private:
1582 LinePrinter &P;
Zachary Turner92e584c2017-08-04 21:10:04 +00001583 uint32_t MaxNameLen;
1584 ArrayRef<std::string> Names;
Zachary Turner63055452017-06-15 22:24:24 +00001585 };
1586
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001587 std::vector<std::string> Names = getSectionNames(getPdb());
Zachary Turner92e584c2017-08-04 21:10:04 +00001588 Visitor V(P, makeArrayRef(Names));
Zachary Turner63055452017-06-15 22:24:24 +00001589 Dbi.visitSectionContributions(V);
1590 return Error::success();
1591}
1592
Zachary Turner7df69952017-06-22 20:57:39 +00001593Error DumpOutputStyle::dumpSectionMap() {
Zachary Turner63055452017-06-15 22:24:24 +00001594 printHeader(P, "Section Map");
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001595 AutoIndent Indent(P);
1596
1597 if (File.isObj()) {
1598 P.formatLine("Dumping section map is not supported for object files");
1599 return Error::success();
1600 }
1601
Reid Klecknerdd853e52017-07-27 23:13:18 +00001602 ExitOnError Err("Error dumping section map: ");
Zachary Turner63055452017-06-15 22:24:24 +00001603
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001604 if (!getPdb().hasPDBDbiStream()) {
Zachary Turner63055452017-06-15 22:24:24 +00001605 P.formatLine("Dumping the section map requires a DBI Stream, which could "
1606 "not be loaded");
1607 return Error::success();
1608 }
1609
Zachary Turnerabb17cc2017-09-01 20:06:56 +00001610 auto &Dbi = Err(getPdb().getPDBDbiStream());
Zachary Turner63055452017-06-15 22:24:24 +00001611
1612 uint32_t I = 0;
1613 for (auto &M : Dbi.getSectionMap()) {
1614 P.formatLine(
Zachary Turnerfb1cd502017-08-04 20:02:38 +00001615 "Section {0:4} | ovl = {1}, group = {2}, frame = {3}, name = {4}", I,
Zachary Turner63055452017-06-15 22:24:24 +00001616 fmtle(M.Ovl), fmtle(M.Group), fmtle(M.Frame), fmtle(M.SecName));
1617 P.formatLine(" class = {0}, offset = {1}, size = {2}",
1618 fmtle(M.ClassName), fmtle(M.Offset), fmtle(M.SecByteLength));
1619 P.formatLine(" flags = {0}",
1620 formatSegMapDescriptorFlag(
1621 P.getIndentLevel() + 13,
1622 static_cast<OMFSegDescFlags>(uint16_t(M.Flags))));
1623 ++I;
1624 }
1625 return Error::success();
1626}