1 //===- llvm-pdbutil.cpp - Dump debug info from a PDB file -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Dumps debug information present in PDB files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm-pdbutil.h"
14 
15 #include "BytesOutputStyle.h"
16 #include "DumpOutputStyle.h"
17 #include "ExplainOutputStyle.h"
18 #include "InputFile.h"
19 #include "LinePrinter.h"
20 #include "OutputStyle.h"
21 #include "PrettyClassDefinitionDumper.h"
22 #include "PrettyCompilandDumper.h"
23 #include "PrettyEnumDumper.h"
24 #include "PrettyExternalSymbolDumper.h"
25 #include "PrettyFunctionDumper.h"
26 #include "PrettyTypeDumper.h"
27 #include "PrettyTypedefDumper.h"
28 #include "PrettyVariableDumper.h"
29 #include "YAMLOutputStyle.h"
30 
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/BinaryFormat/Magic.h"
37 #include "llvm/Config/config.h"
38 #include "llvm/DebugInfo/CodeView/AppendingTypeTableBuilder.h"
39 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
40 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
41 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
42 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
43 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
44 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
45 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
46 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
47 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
48 #include "llvm/DebugInfo/PDB/IPDBInjectedSource.h"
49 #include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
50 #include "llvm/DebugInfo/PDB/IPDBSession.h"
51 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
52 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
53 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
54 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
55 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
56 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
57 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
58 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
59 #include "llvm/DebugInfo/PDB/Native/RawConstants.h"
60 #include "llvm/DebugInfo/PDB/Native/RawError.h"
61 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
62 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
63 #include "llvm/DebugInfo/PDB/PDB.h"
64 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
65 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
66 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
67 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
68 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
69 #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
70 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
71 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
72 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
73 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
74 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
75 #include "llvm/Support/BinaryByteStream.h"
76 #include "llvm/Support/COM.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/ConvertUTF.h"
79 #include "llvm/Support/FileOutputBuffer.h"
80 #include "llvm/Support/FileSystem.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/InitLLVM.h"
83 #include "llvm/Support/LineIterator.h"
84 #include "llvm/Support/ManagedStatic.h"
85 #include "llvm/Support/MemoryBuffer.h"
86 #include "llvm/Support/Path.h"
87 #include "llvm/Support/PrettyStackTrace.h"
88 #include "llvm/Support/Process.h"
89 #include "llvm/Support/Regex.h"
90 #include "llvm/Support/ScopedPrinter.h"
91 #include "llvm/Support/Signals.h"
92 #include "llvm/Support/raw_ostream.h"
93 
94 using namespace llvm;
95 using namespace llvm::codeview;
96 using namespace llvm::msf;
97 using namespace llvm::pdb;
98 
99 namespace opts {
100 
101 cl::SubCommand DumpSubcommand("dump", "Dump MSF and CodeView debug info");
102 cl::SubCommand BytesSubcommand("bytes", "Dump raw bytes from the PDB file");
103 
104 cl::SubCommand DiaDumpSubcommand("diadump",
105                                  "Dump debug information using a DIA-like API");
106 
107 cl::SubCommand
108     PrettySubcommand("pretty",
109                      "Dump semantic information about types and symbols");
110 
111 cl::SubCommand
112     YamlToPdbSubcommand("yaml2pdb",
113                         "Generate a PDB file from a YAML description");
114 cl::SubCommand
115     PdbToYamlSubcommand("pdb2yaml",
116                         "Generate a detailed YAML description of a PDB File");
117 
118 cl::SubCommand MergeSubcommand("merge",
119                                "Merge multiple PDBs into a single PDB");
120 
121 cl::SubCommand ExplainSubcommand("explain",
122                                  "Explain the meaning of a file offset");
123 
124 cl::SubCommand ExportSubcommand("export",
125                                 "Write binary data from a stream to a file");
126 
127 cl::OptionCategory TypeCategory("Symbol Type Options");
128 cl::OptionCategory FilterCategory("Filtering and Sorting Options");
129 cl::OptionCategory OtherOptions("Other Options");
130 
131 cl::ValuesClass ChunkValues = cl::values(
132     clEnumValN(ModuleSubsection::CrossScopeExports, "cme",
133                "Cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
134     clEnumValN(ModuleSubsection::CrossScopeImports, "cmi",
135                "Cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
136     clEnumValN(ModuleSubsection::FileChecksums, "fc",
137                "File checksums (DEBUG_S_CHECKSUMS subsection)"),
138     clEnumValN(ModuleSubsection::InlineeLines, "ilines",
139                "Inlinee lines (DEBUG_S_INLINEELINES subsection)"),
140     clEnumValN(ModuleSubsection::Lines, "lines",
141                "Lines (DEBUG_S_LINES subsection)"),
142     clEnumValN(ModuleSubsection::StringTable, "strings",
143                "String Table (DEBUG_S_STRINGTABLE subsection) (not "
144                "typically present in PDB file)"),
145     clEnumValN(ModuleSubsection::FrameData, "frames",
146                "Frame Data (DEBUG_S_FRAMEDATA subsection)"),
147     clEnumValN(ModuleSubsection::Symbols, "symbols",
148                "Symbols (DEBUG_S_SYMBOLS subsection) (not typically "
149                "present in PDB file)"),
150     clEnumValN(ModuleSubsection::CoffSymbolRVAs, "rvas",
151                "COFF Symbol RVAs (DEBUG_S_COFF_SYMBOL_RVA subsection)"),
152     clEnumValN(ModuleSubsection::Unknown, "unknown",
153                "Any subsection not covered by another option"),
154     clEnumValN(ModuleSubsection::All, "all", "All known subsections"));
155 
156 namespace diadump {
157 cl::list<std::string> InputFilenames(cl::Positional,
158                                      cl::desc("<input PDB files>"),
159                                      cl::OneOrMore, cl::sub(DiaDumpSubcommand));
160 
161 cl::opt<bool> Native("native", cl::desc("Use native PDB reader instead of DIA"),
162                      cl::sub(DiaDumpSubcommand));
163 
164 static cl::opt<bool>
165     ShowClassHierarchy("hierarchy", cl::desc("Show lexical and class parents"),
166                        cl::sub(DiaDumpSubcommand));
167 static cl::opt<bool> NoSymIndexIds(
168     "no-ids",
169     cl::desc("Don't show any SymIndexId fields (overrides -hierarchy)"),
170     cl::sub(DiaDumpSubcommand));
171 
172 static cl::opt<bool>
173     Recurse("recurse",
174             cl::desc("When dumping a SymIndexId, dump the full details of the "
175                      "corresponding record"),
176             cl::sub(DiaDumpSubcommand));
177 
178 static cl::opt<bool> Enums("enums", cl::desc("Dump enum types"),
179                            cl::sub(DiaDumpSubcommand));
180 static cl::opt<bool> Pointers("pointers", cl::desc("Dump enum types"),
181                               cl::sub(DiaDumpSubcommand));
182 static cl::opt<bool> UDTs("udts", cl::desc("Dump udt types"),
183                           cl::sub(DiaDumpSubcommand));
184 static cl::opt<bool> Compilands("compilands",
185                                 cl::desc("Dump compiland information"),
186                                 cl::sub(DiaDumpSubcommand));
187 static cl::opt<bool> Funcsigs("funcsigs",
188                               cl::desc("Dump function signature information"),
189                               cl::sub(DiaDumpSubcommand));
190 static cl::opt<bool> Arrays("arrays", cl::desc("Dump array types"),
191                             cl::sub(DiaDumpSubcommand));
192 static cl::opt<bool> VTShapes("vtshapes", cl::desc("Dump virtual table shapes"),
193                               cl::sub(DiaDumpSubcommand));
194 static cl::opt<bool> Typedefs("typedefs", cl::desc("Dump typedefs"),
195                               cl::sub(DiaDumpSubcommand));
196 } // namespace diadump
197 
198 namespace pretty {
199 cl::list<std::string> InputFilenames(cl::Positional,
200                                      cl::desc("<input PDB files>"),
201                                      cl::OneOrMore, cl::sub(PrettySubcommand));
202 
203 cl::opt<bool> InjectedSources("injected-sources",
204                               cl::desc("Display injected sources"),
205                               cl::cat(OtherOptions), cl::sub(PrettySubcommand));
206 cl::opt<bool> ShowInjectedSourceContent(
207     "injected-source-content",
208     cl::desc("When displaying an injected source, display the file content"),
209     cl::cat(OtherOptions), cl::sub(PrettySubcommand));
210 
211 cl::list<std::string> WithName(
212     "with-name",
213     cl::desc("Display any symbol or type with the specified exact name"),
214     cl::cat(TypeCategory), cl::ZeroOrMore, cl::sub(PrettySubcommand));
215 
216 cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"),
217                          cl::cat(TypeCategory), cl::sub(PrettySubcommand));
218 cl::opt<bool> Symbols("module-syms",
219                       cl::desc("Display symbols for each compiland"),
220                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
221 cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"),
222                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
223 cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"),
224                         cl::cat(TypeCategory), cl::sub(PrettySubcommand));
225 cl::list<SymLevel> SymTypes(
226     "sym-types", cl::desc("Type of symbols to dump (default all)"),
227     cl::cat(TypeCategory), cl::sub(PrettySubcommand), cl::ZeroOrMore,
228     cl::values(
229         clEnumValN(SymLevel::Thunks, "thunks", "Display thunk symbols"),
230         clEnumValN(SymLevel::Data, "data", "Display data symbols"),
231         clEnumValN(SymLevel::Functions, "funcs", "Display function symbols"),
232         clEnumValN(SymLevel::All, "all", "Display all symbols (default)")));
233 
234 cl::opt<bool>
235     Types("types",
236           cl::desc("Display all types (implies -classes, -enums, -typedefs)"),
237           cl::cat(TypeCategory), cl::sub(PrettySubcommand));
238 cl::opt<bool> Classes("classes", cl::desc("Display class types"),
239                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
240 cl::opt<bool> Enums("enums", cl::desc("Display enum types"),
241                     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
242 cl::opt<bool> Typedefs("typedefs", cl::desc("Display typedef types"),
243                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
244 cl::opt<bool> Funcsigs("funcsigs", cl::desc("Display function signatures"),
245                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
246 cl::opt<bool> Pointers("pointers", cl::desc("Display pointer types"),
247                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
248 cl::opt<bool> Arrays("arrays", cl::desc("Display arrays"),
249                      cl::cat(TypeCategory), cl::sub(PrettySubcommand));
250 cl::opt<bool> VTShapes("vtshapes", cl::desc("Display vftable shapes"),
251                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
252 
253 cl::opt<SymbolSortMode> SymbolOrder(
254     "symbol-order", cl::desc("symbol sort order"),
255     cl::init(SymbolSortMode::None),
256     cl::values(clEnumValN(SymbolSortMode::None, "none",
257                           "Undefined / no particular sort order"),
258                clEnumValN(SymbolSortMode::Name, "name", "Sort symbols by name"),
259                clEnumValN(SymbolSortMode::Size, "size",
260                           "Sort symbols by size")),
261     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
262 
263 cl::opt<ClassSortMode> ClassOrder(
264     "class-order", cl::desc("Class sort order"), cl::init(ClassSortMode::None),
265     cl::values(
266         clEnumValN(ClassSortMode::None, "none",
267                    "Undefined / no particular sort order"),
268         clEnumValN(ClassSortMode::Name, "name", "Sort classes by name"),
269         clEnumValN(ClassSortMode::Size, "size", "Sort classes by size"),
270         clEnumValN(ClassSortMode::Padding, "padding",
271                    "Sort classes by amount of padding"),
272         clEnumValN(ClassSortMode::PaddingPct, "padding-pct",
273                    "Sort classes by percentage of space consumed by padding"),
274         clEnumValN(ClassSortMode::PaddingImmediate, "padding-imm",
275                    "Sort classes by amount of immediate padding"),
276         clEnumValN(ClassSortMode::PaddingPctImmediate, "padding-pct-imm",
277                    "Sort classes by percentage of space consumed by immediate "
278                    "padding")),
279     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
280 
281 cl::opt<ClassDefinitionFormat> ClassFormat(
282     "class-definitions", cl::desc("Class definition format"),
283     cl::init(ClassDefinitionFormat::All),
284     cl::values(
285         clEnumValN(ClassDefinitionFormat::All, "all",
286                    "Display all class members including data, constants, "
287                    "typedefs, functions, etc"),
288         clEnumValN(ClassDefinitionFormat::Layout, "layout",
289                    "Only display members that contribute to class size."),
290         clEnumValN(ClassDefinitionFormat::None, "none",
291                    "Don't display class definitions")),
292     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
293 cl::opt<uint32_t> ClassRecursionDepth(
294     "class-recurse-depth", cl::desc("Class recursion depth (0=no limit)"),
295     cl::init(0), cl::cat(TypeCategory), cl::sub(PrettySubcommand));
296 
297 cl::opt<bool> Lines("lines", cl::desc("Line tables"), cl::cat(TypeCategory),
298                     cl::sub(PrettySubcommand));
299 cl::opt<bool>
300     All("all", cl::desc("Implies all other options in 'Symbol Types' category"),
301         cl::cat(TypeCategory), cl::sub(PrettySubcommand));
302 
303 cl::opt<uint64_t> LoadAddress(
304     "load-address",
305     cl::desc("Assume the module is loaded at the specified address"),
306     cl::cat(OtherOptions), cl::sub(PrettySubcommand));
307 cl::opt<bool> Native("native", cl::desc("Use native PDB reader instead of DIA"),
308                      cl::cat(OtherOptions), cl::sub(PrettySubcommand));
309 cl::opt<cl::boolOrDefault>
310     ColorOutput("color-output",
311                 cl::desc("Override use of color (default = isatty)"),
312                 cl::cat(OtherOptions), cl::sub(PrettySubcommand));
313 cl::list<std::string> ExcludeTypes(
314     "exclude-types", cl::desc("Exclude types by regular expression"),
315     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
316 cl::list<std::string> ExcludeSymbols(
317     "exclude-symbols", cl::desc("Exclude symbols by regular expression"),
318     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
319 cl::list<std::string> ExcludeCompilands(
320     "exclude-compilands", cl::desc("Exclude compilands by regular expression"),
321     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
322 
323 cl::list<std::string> IncludeTypes(
324     "include-types",
325     cl::desc("Include only types which match a regular expression"),
326     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
327 cl::list<std::string> IncludeSymbols(
328     "include-symbols",
329     cl::desc("Include only symbols which match a regular expression"),
330     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
331 cl::list<std::string> IncludeCompilands(
332     "include-compilands",
333     cl::desc("Include only compilands those which match a regular expression"),
334     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
335 cl::opt<uint32_t> SizeThreshold(
336     "min-type-size", cl::desc("Displays only those types which are greater "
337                               "than or equal to the specified size."),
338     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
339 cl::opt<uint32_t> PaddingThreshold(
340     "min-class-padding", cl::desc("Displays only those classes which have at "
341                                   "least the specified amount of padding."),
342     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
343 cl::opt<uint32_t> ImmediatePaddingThreshold(
344     "min-class-padding-imm",
345     cl::desc("Displays only those classes which have at least the specified "
346              "amount of immediate padding, ignoring padding internal to bases "
347              "and aggregates."),
348     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
349 
350 cl::opt<bool> ExcludeCompilerGenerated(
351     "no-compiler-generated",
352     cl::desc("Don't show compiler generated types and symbols"),
353     cl::cat(FilterCategory), cl::sub(PrettySubcommand));
354 cl::opt<bool>
355     ExcludeSystemLibraries("no-system-libs",
356                            cl::desc("Don't show symbols from system libraries"),
357                            cl::cat(FilterCategory), cl::sub(PrettySubcommand));
358 
359 cl::opt<bool> NoEnumDefs("no-enum-definitions",
360                          cl::desc("Don't display full enum definitions"),
361                          cl::cat(FilterCategory), cl::sub(PrettySubcommand));
362 }
363 
364 cl::OptionCategory FileOptions("Module & File Options");
365 
366 namespace bytes {
367 cl::OptionCategory MsfBytes("MSF File Options");
368 cl::OptionCategory DbiBytes("Dbi Stream Options");
369 cl::OptionCategory PdbBytes("PDB Stream Options");
370 cl::OptionCategory Types("Type Options");
371 cl::OptionCategory ModuleCategory("Module Options");
372 
373 llvm::Optional<NumberRange> DumpBlockRange;
374 llvm::Optional<NumberRange> DumpByteRange;
375 
376 cl::opt<std::string> DumpBlockRangeOpt(
377     "block-range", cl::value_desc("start[-end]"),
378     cl::desc("Dump binary data from specified range of blocks."),
379     cl::sub(BytesSubcommand), cl::cat(MsfBytes));
380 
381 cl::opt<std::string>
382     DumpByteRangeOpt("byte-range", cl::value_desc("start[-end]"),
383                      cl::desc("Dump binary data from specified range of bytes"),
384                      cl::sub(BytesSubcommand), cl::cat(MsfBytes));
385 
386 cl::list<std::string>
387     DumpStreamData("stream-data", cl::CommaSeparated, cl::ZeroOrMore,
388                    cl::desc("Dump binary data from specified streams.  Format "
389                             "is SN[:Start][@Size]"),
390                    cl::sub(BytesSubcommand), cl::cat(MsfBytes));
391 
392 cl::opt<bool> NameMap("name-map", cl::desc("Dump bytes of PDB Name Map"),
393                       cl::sub(BytesSubcommand), cl::cat(PdbBytes));
394 cl::opt<bool> Fpm("fpm", cl::desc("Dump free page map"),
395                   cl::sub(BytesSubcommand), cl::cat(MsfBytes));
396 
397 cl::opt<bool> SectionContributions("sc", cl::desc("Dump section contributions"),
398                                    cl::sub(BytesSubcommand), cl::cat(DbiBytes));
399 cl::opt<bool> SectionMap("sm", cl::desc("Dump section map"),
400                          cl::sub(BytesSubcommand), cl::cat(DbiBytes));
401 cl::opt<bool> ModuleInfos("modi", cl::desc("Dump module info"),
402                           cl::sub(BytesSubcommand), cl::cat(DbiBytes));
403 cl::opt<bool> FileInfo("files", cl::desc("Dump source file info"),
404                        cl::sub(BytesSubcommand), cl::cat(DbiBytes));
405 cl::opt<bool> TypeServerMap("type-server", cl::desc("Dump type server map"),
406                             cl::sub(BytesSubcommand), cl::cat(DbiBytes));
407 cl::opt<bool> ECData("ec", cl::desc("Dump edit and continue map"),
408                      cl::sub(BytesSubcommand), cl::cat(DbiBytes));
409 
410 cl::list<uint32_t>
411     TypeIndex("type",
412               cl::desc("Dump the type record with the given type index"),
413               cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
414               cl::cat(TypeCategory));
415 cl::list<uint32_t>
416     IdIndex("id", cl::desc("Dump the id record with the given type index"),
417             cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
418             cl::cat(TypeCategory));
419 
420 cl::opt<uint32_t> ModuleIndex(
421     "mod",
422     cl::desc(
423         "Limit options in the Modules category to the specified module index"),
424     cl::Optional, cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
425 cl::opt<bool> ModuleSyms("syms", cl::desc("Dump symbol record substream"),
426                          cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
427 cl::opt<bool> ModuleC11("c11-chunks", cl::Hidden,
428                         cl::desc("Dump C11 CodeView debug chunks"),
429                         cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
430 cl::opt<bool> ModuleC13("chunks",
431                         cl::desc("Dump C13 CodeView debug chunk subsection"),
432                         cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
433 cl::opt<bool> SplitChunks(
434     "split-chunks",
435     cl::desc(
436         "When dumping debug chunks, show a different section for each chunk"),
437     cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
438 cl::list<std::string> InputFilenames(cl::Positional,
439                                      cl::desc("<input PDB files>"),
440                                      cl::OneOrMore, cl::sub(BytesSubcommand));
441 
442 } // namespace bytes
443 
444 namespace dump {
445 
446 cl::OptionCategory MsfOptions("MSF Container Options");
447 cl::OptionCategory TypeOptions("Type Record Options");
448 cl::OptionCategory SymbolOptions("Symbol Options");
449 cl::OptionCategory MiscOptions("Miscellaneous Options");
450 
451 // MSF OPTIONS
452 cl::opt<bool> DumpSummary("summary", cl::desc("dump file summary"),
453                           cl::cat(MsfOptions), cl::sub(DumpSubcommand));
454 cl::opt<bool> DumpStreams("streams",
455                           cl::desc("dump summary of the PDB streams"),
456                           cl::cat(MsfOptions), cl::sub(DumpSubcommand));
457 cl::opt<bool> DumpStreamBlocks(
458     "stream-blocks",
459     cl::desc("Add block information to the output of -streams"),
460     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
461 cl::opt<bool> DumpSymbolStats(
462     "sym-stats",
463     cl::desc("Dump a detailed breakdown of symbol usage/size for each module"),
464     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
465 cl::opt<bool> DumpTypeStats(
466     "type-stats",
467     cl::desc("Dump a detailed breakdown of type usage/size"),
468     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
469 cl::opt<bool> DumpIDStats(
470     "id-stats",
471     cl::desc("Dump a detailed breakdown of IPI types usage/size"),
472     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
473 cl::opt<bool> DumpUdtStats(
474     "udt-stats",
475     cl::desc("Dump a detailed breakdown of S_UDT record usage / stats"),
476     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
477 
478 // TYPE OPTIONS
479 cl::opt<bool> DumpTypes("types",
480                         cl::desc("dump CodeView type records from TPI stream"),
481                         cl::cat(TypeOptions), cl::sub(DumpSubcommand));
482 cl::opt<bool> DumpTypeData(
483     "type-data",
484     cl::desc("dump CodeView type record raw bytes from TPI stream"),
485     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
486 cl::opt<bool>
487     DumpTypeRefStats("type-ref-stats",
488                      cl::desc("dump statistics on the number and size of types "
489                               "transitively referenced by symbol records"),
490                      cl::cat(TypeOptions), cl::sub(DumpSubcommand));
491 
492 cl::opt<bool> DumpTypeExtras("type-extras",
493                              cl::desc("dump type hashes and index offsets"),
494                              cl::cat(TypeOptions), cl::sub(DumpSubcommand));
495 
496 cl::opt<bool> DontResolveForwardRefs(
497     "dont-resolve-forward-refs",
498     cl::desc("When dumping type records for classes, unions, enums, and "
499              "structs, don't try to resolve forward references"),
500     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
501 
502 cl::list<uint32_t> DumpTypeIndex(
503     "type-index", cl::ZeroOrMore, cl::CommaSeparated,
504     cl::desc("only dump types with the specified hexadecimal type index"),
505     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
506 
507 cl::opt<bool> DumpIds("ids",
508                       cl::desc("dump CodeView type records from IPI stream"),
509                       cl::cat(TypeOptions), cl::sub(DumpSubcommand));
510 cl::opt<bool>
511     DumpIdData("id-data",
512                cl::desc("dump CodeView type record raw bytes from IPI stream"),
513                cl::cat(TypeOptions), cl::sub(DumpSubcommand));
514 
515 cl::opt<bool> DumpIdExtras("id-extras",
516                            cl::desc("dump id hashes and index offsets"),
517                            cl::cat(TypeOptions), cl::sub(DumpSubcommand));
518 cl::list<uint32_t> DumpIdIndex(
519     "id-index", cl::ZeroOrMore, cl::CommaSeparated,
520     cl::desc("only dump ids with the specified hexadecimal type index"),
521     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
522 
523 cl::opt<bool> DumpTypeDependents(
524     "dependents",
525     cl::desc("In conjunection with -type-index and -id-index, dumps the entire "
526              "dependency graph for the specified index instead of "
527              "just the single record with the specified index"),
528     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
529 
530 // SYMBOL OPTIONS
531 cl::opt<bool> DumpGlobals("globals", cl::desc("dump Globals symbol records"),
532                           cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
533 cl::opt<bool> DumpGlobalExtras("global-extras", cl::desc("dump Globals hashes"),
534                                cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
535 cl::list<std::string> DumpGlobalNames(
536     "global-name",
537     cl::desc(
538         "With -globals, only dump globals whose name matches the given value"),
539     cl::cat(SymbolOptions), cl::sub(DumpSubcommand), cl::ZeroOrMore);
540 cl::opt<bool> DumpPublics("publics", cl::desc("dump Publics stream data"),
541                           cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
542 cl::opt<bool> DumpPublicExtras("public-extras",
543                                cl::desc("dump Publics hashes and address maps"),
544                                cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
545 cl::opt<bool>
546     DumpGSIRecords("gsi-records",
547                    cl::desc("dump public / global common record stream"),
548                    cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
549 cl::opt<bool> DumpSymbols("symbols", cl::desc("dump module symbols"),
550                           cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
551 
552 cl::opt<bool>
553     DumpSymRecordBytes("sym-data",
554                        cl::desc("dump CodeView symbol record raw bytes"),
555                        cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
556 
557 cl::opt<bool> DumpFpo("fpo", cl::desc("dump FPO records"),
558                       cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
559 
560 // MODULE & FILE OPTIONS
561 cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
562                           cl::cat(FileOptions), cl::sub(DumpSubcommand));
563 cl::opt<bool> DumpModuleFiles(
564     "files",
565     cl::desc("Dump the source files that contribute to each module's."),
566     cl::cat(FileOptions), cl::sub(DumpSubcommand));
567 cl::opt<bool> DumpLines(
568     "l",
569     cl::desc("dump source file/line information (DEBUG_S_LINES subsection)"),
570     cl::cat(FileOptions), cl::sub(DumpSubcommand));
571 cl::opt<bool> DumpInlineeLines(
572     "il",
573     cl::desc("dump inlinee line information (DEBUG_S_INLINEELINES subsection)"),
574     cl::cat(FileOptions), cl::sub(DumpSubcommand));
575 cl::opt<bool> DumpXmi(
576     "xmi",
577     cl::desc(
578         "dump cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
579     cl::cat(FileOptions), cl::sub(DumpSubcommand));
580 cl::opt<bool> DumpXme(
581     "xme",
582     cl::desc(
583         "dump cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
584     cl::cat(FileOptions), cl::sub(DumpSubcommand));
585 cl::opt<uint32_t> DumpModi("modi", cl::Optional,
586                            cl::desc("For all options that iterate over "
587                                     "modules, limit to the specified module"),
588                            cl::cat(FileOptions), cl::sub(DumpSubcommand));
589 cl::opt<bool> JustMyCode("jmc", cl::Optional,
590                          cl::desc("For all options that iterate over modules, "
591                                   "ignore modules from system libraries"),
592                          cl::cat(FileOptions), cl::sub(DumpSubcommand));
593 
594 // MISCELLANEOUS OPTIONS
595 cl::opt<bool> DumpNamedStreams("named-streams",
596                                cl::desc("dump PDB named stream table"),
597                                cl::cat(MiscOptions), cl::sub(DumpSubcommand));
598 
599 cl::opt<bool> DumpStringTable("string-table", cl::desc("dump PDB String Table"),
600                               cl::cat(MiscOptions), cl::sub(DumpSubcommand));
601 cl::opt<bool> DumpStringTableDetails("string-table-details",
602                                      cl::desc("dump PDB String Table Details"),
603                                      cl::cat(MiscOptions),
604                                      cl::sub(DumpSubcommand));
605 
606 cl::opt<bool> DumpSectionContribs("section-contribs",
607                                   cl::desc("dump section contributions"),
608                                   cl::cat(MiscOptions),
609                                   cl::sub(DumpSubcommand));
610 cl::opt<bool> DumpSectionMap("section-map", cl::desc("dump section map"),
611                              cl::cat(MiscOptions), cl::sub(DumpSubcommand));
612 cl::opt<bool> DumpSectionHeaders("section-headers",
613                                  cl::desc("Dump image section headers"),
614                                  cl::cat(MiscOptions), cl::sub(DumpSubcommand));
615 
616 cl::opt<bool> RawAll("all", cl::desc("Implies most other options."),
617                      cl::cat(MiscOptions), cl::sub(DumpSubcommand));
618 
619 cl::list<std::string> InputFilenames(cl::Positional,
620                                      cl::desc("<input PDB files>"),
621                                      cl::OneOrMore, cl::sub(DumpSubcommand));
622 }
623 
624 namespace yaml2pdb {
625 cl::opt<std::string>
626     YamlPdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
627                       cl::sub(YamlToPdbSubcommand));
628 
629 cl::opt<std::string> InputFilename(cl::Positional,
630                                    cl::desc("<input YAML file>"), cl::Required,
631                                    cl::sub(YamlToPdbSubcommand));
632 }
633 
634 namespace pdb2yaml {
635 cl::opt<bool> All("all",
636                   cl::desc("Dump everything we know how to dump."),
637                   cl::sub(PdbToYamlSubcommand), cl::init(false));
638 cl::opt<bool> NoFileHeaders("no-file-headers",
639                             cl::desc("Do not dump MSF file headers"),
640                             cl::sub(PdbToYamlSubcommand), cl::init(false));
641 cl::opt<bool> Minimal("minimal",
642                       cl::desc("Don't write fields with default values"),
643                       cl::sub(PdbToYamlSubcommand), cl::init(false));
644 
645 cl::opt<bool> StreamMetadata(
646     "stream-metadata",
647     cl::desc("Dump the number of streams and each stream's size"),
648     cl::sub(PdbToYamlSubcommand), cl::init(false));
649 cl::opt<bool> StreamDirectory(
650     "stream-directory",
651     cl::desc("Dump each stream's block map (implies -stream-metadata)"),
652     cl::sub(PdbToYamlSubcommand), cl::init(false));
653 cl::opt<bool> PdbStream("pdb-stream",
654                         cl::desc("Dump the PDB Stream (Stream 1)"),
655                         cl::sub(PdbToYamlSubcommand), cl::init(false));
656 
657 cl::opt<bool> StringTable("string-table", cl::desc("Dump the PDB String Table"),
658                           cl::sub(PdbToYamlSubcommand), cl::init(false));
659 
660 cl::opt<bool> DbiStream("dbi-stream",
661                         cl::desc("Dump the DBI Stream Headers (Stream 2)"),
662                         cl::sub(PdbToYamlSubcommand), cl::init(false));
663 
664 cl::opt<bool> TpiStream("tpi-stream",
665                         cl::desc("Dump the TPI Stream (Stream 3)"),
666                         cl::sub(PdbToYamlSubcommand), cl::init(false));
667 
668 cl::opt<bool> IpiStream("ipi-stream",
669                         cl::desc("Dump the IPI Stream (Stream 5)"),
670                         cl::sub(PdbToYamlSubcommand), cl::init(false));
671 
672 cl::opt<bool> PublicsStream("publics-stream",
673                             cl::desc("Dump the Publics Stream"),
674                             cl::sub(PdbToYamlSubcommand), cl::init(false));
675 
676 // MODULE & FILE OPTIONS
677 cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
678                           cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
679 cl::opt<bool> DumpModuleFiles("module-files", cl::desc("dump file information"),
680                               cl::cat(FileOptions),
681                               cl::sub(PdbToYamlSubcommand));
682 cl::list<ModuleSubsection> DumpModuleSubsections(
683     "subsections", cl::ZeroOrMore, cl::CommaSeparated,
684     cl::desc("dump subsections from each module's debug stream"), ChunkValues,
685     cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
686 cl::opt<bool> DumpModuleSyms("module-syms", cl::desc("dump module symbols"),
687                              cl::cat(FileOptions),
688                              cl::sub(PdbToYamlSubcommand));
689 
690 cl::list<std::string> InputFilename(cl::Positional,
691                                     cl::desc("<input PDB file>"), cl::Required,
692                                     cl::sub(PdbToYamlSubcommand));
693 } // namespace pdb2yaml
694 
695 namespace merge {
696 cl::list<std::string> InputFilenames(cl::Positional,
697                                      cl::desc("<input PDB files>"),
698                                      cl::OneOrMore, cl::sub(MergeSubcommand));
699 cl::opt<std::string>
700     PdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
701                   cl::sub(MergeSubcommand));
702 }
703 
704 namespace explain {
705 cl::list<std::string> InputFilename(cl::Positional,
706                                     cl::desc("<input PDB file>"), cl::Required,
707                                     cl::sub(ExplainSubcommand));
708 
709 cl::list<uint64_t> Offsets("offset", cl::desc("The file offset to explain"),
710                            cl::sub(ExplainSubcommand), cl::OneOrMore);
711 
712 cl::opt<InputFileType> InputType(
713     "input-type", cl::desc("Specify how to interpret the input file"),
714     cl::init(InputFileType::PDBFile), cl::Optional, cl::sub(ExplainSubcommand),
715     cl::values(clEnumValN(InputFileType::PDBFile, "pdb-file",
716                           "Treat input as a PDB file (default)"),
717                clEnumValN(InputFileType::PDBStream, "pdb-stream",
718                           "Treat input as raw contents of PDB stream"),
719                clEnumValN(InputFileType::DBIStream, "dbi-stream",
720                           "Treat input as raw contents of DBI stream"),
721                clEnumValN(InputFileType::Names, "names-stream",
722                           "Treat input as raw contents of /names named stream"),
723                clEnumValN(InputFileType::ModuleStream, "mod-stream",
724                           "Treat input as raw contents of a module stream")));
725 } // namespace explain
726 
727 namespace exportstream {
728 cl::list<std::string> InputFilename(cl::Positional,
729                                     cl::desc("<input PDB file>"), cl::Required,
730                                     cl::sub(ExportSubcommand));
731 cl::opt<std::string> OutputFile("out",
732                                 cl::desc("The file to write the stream to"),
733                                 cl::Required, cl::sub(ExportSubcommand));
734 cl::opt<std::string>
735     Stream("stream", cl::Required,
736            cl::desc("The index or name of the stream whose contents to export"),
737            cl::sub(ExportSubcommand));
738 cl::opt<bool> ForceName("name",
739                         cl::desc("Force the interpretation of -stream as a "
740                                  "string, even if it is a valid integer"),
741                         cl::sub(ExportSubcommand), cl::Optional,
742                         cl::init(false));
743 } // namespace exportstream
744 }
745 
746 static ExitOnError ExitOnErr;
747 
yamlToPdb(StringRef Path)748 static void yamlToPdb(StringRef Path) {
749   BumpPtrAllocator Allocator;
750   ErrorOr<std::unique_ptr<MemoryBuffer>> ErrorOrBuffer =
751       MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/false,
752                                    /*RequiresNullTerminator=*/false);
753 
754   if (ErrorOrBuffer.getError()) {
755     ExitOnErr(createFileError(Path, errorCodeToError(ErrorOrBuffer.getError())));
756   }
757 
758   std::unique_ptr<MemoryBuffer> &Buffer = ErrorOrBuffer.get();
759 
760   llvm::yaml::Input In(Buffer->getBuffer());
761   pdb::yaml::PdbObject YamlObj(Allocator);
762   In >> YamlObj;
763 
764   PDBFileBuilder Builder(Allocator);
765 
766   uint32_t BlockSize = 4096;
767   if (YamlObj.Headers.hasValue())
768     BlockSize = YamlObj.Headers->SuperBlock.BlockSize;
769   ExitOnErr(Builder.initialize(BlockSize));
770   // Add each of the reserved streams.  We ignore stream metadata in the
771   // yaml, because we will reconstruct our own view of the streams.  For
772   // example, the YAML may say that there were 20 streams in the original
773   // PDB, but maybe we only dump a subset of those 20 streams, so we will
774   // have fewer, and the ones we do have may end up with different indices
775   // than the ones in the original PDB.  So we just start with a clean slate.
776   for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
777     ExitOnErr(Builder.getMsfBuilder().addStream(0));
778 
779   StringsAndChecksums Strings;
780   Strings.setStrings(std::make_shared<DebugStringTableSubsection>());
781 
782   if (YamlObj.StringTable.hasValue()) {
783     for (auto S : *YamlObj.StringTable)
784       Strings.strings()->insert(S);
785   }
786 
787   pdb::yaml::PdbInfoStream DefaultInfoStream;
788   pdb::yaml::PdbDbiStream DefaultDbiStream;
789   pdb::yaml::PdbTpiStream DefaultTpiStream;
790   pdb::yaml::PdbTpiStream DefaultIpiStream;
791 
792   const auto &Info = YamlObj.PdbStream.getValueOr(DefaultInfoStream);
793 
794   auto &InfoBuilder = Builder.getInfoBuilder();
795   InfoBuilder.setAge(Info.Age);
796   InfoBuilder.setGuid(Info.Guid);
797   InfoBuilder.setSignature(Info.Signature);
798   InfoBuilder.setVersion(Info.Version);
799   for (auto F : Info.Features)
800     InfoBuilder.addFeature(F);
801 
802   const auto &Dbi = YamlObj.DbiStream.getValueOr(DefaultDbiStream);
803   auto &DbiBuilder = Builder.getDbiBuilder();
804   DbiBuilder.setAge(Dbi.Age);
805   DbiBuilder.setBuildNumber(Dbi.BuildNumber);
806   DbiBuilder.setFlags(Dbi.Flags);
807   DbiBuilder.setMachineType(Dbi.MachineType);
808   DbiBuilder.setPdbDllRbld(Dbi.PdbDllRbld);
809   DbiBuilder.setPdbDllVersion(Dbi.PdbDllVersion);
810   DbiBuilder.setVersionHeader(Dbi.VerHeader);
811   for (const auto &MI : Dbi.ModInfos) {
812     auto &ModiBuilder = ExitOnErr(DbiBuilder.addModuleInfo(MI.Mod));
813     ModiBuilder.setObjFileName(MI.Obj);
814 
815     for (auto S : MI.SourceFiles)
816       ExitOnErr(DbiBuilder.addModuleSourceFile(ModiBuilder, S));
817     if (MI.Modi.hasValue()) {
818       const auto &ModiStream = *MI.Modi;
819       for (auto Symbol : ModiStream.Symbols) {
820         ModiBuilder.addSymbol(
821             Symbol.toCodeViewSymbol(Allocator, CodeViewContainer::Pdb));
822       }
823     }
824 
825     // Each module has its own checksum subsection, so scan for it every time.
826     Strings.setChecksums(nullptr);
827     CodeViewYAML::initializeStringsAndChecksums(MI.Subsections, Strings);
828 
829     auto CodeViewSubsections = ExitOnErr(CodeViewYAML::toCodeViewSubsectionList(
830         Allocator, MI.Subsections, Strings));
831     for (auto &SS : CodeViewSubsections) {
832       ModiBuilder.addDebugSubsection(SS);
833     }
834   }
835 
836   auto &TpiBuilder = Builder.getTpiBuilder();
837   const auto &Tpi = YamlObj.TpiStream.getValueOr(DefaultTpiStream);
838   TpiBuilder.setVersionHeader(Tpi.Version);
839   AppendingTypeTableBuilder TS(Allocator);
840   for (const auto &R : Tpi.Records) {
841     CVType Type = R.toCodeViewRecord(TS);
842     TpiBuilder.addTypeRecord(Type.RecordData, None);
843   }
844 
845   const auto &Ipi = YamlObj.IpiStream.getValueOr(DefaultIpiStream);
846   auto &IpiBuilder = Builder.getIpiBuilder();
847   IpiBuilder.setVersionHeader(Ipi.Version);
848   for (const auto &R : Ipi.Records) {
849     CVType Type = R.toCodeViewRecord(TS);
850     IpiBuilder.addTypeRecord(Type.RecordData, None);
851   }
852 
853   Builder.getStringTableBuilder().setStrings(*Strings.strings());
854 
855   codeview::GUID IgnoredOutGuid;
856   ExitOnErr(Builder.commit(opts::yaml2pdb::YamlPdbOutputFile, &IgnoredOutGuid));
857 }
858 
loadPDB(StringRef Path,std::unique_ptr<IPDBSession> & Session)859 static PDBFile &loadPDB(StringRef Path, std::unique_ptr<IPDBSession> &Session) {
860   ExitOnErr(loadDataForPDB(PDB_ReaderType::Native, Path, Session));
861 
862   NativeSession *NS = static_cast<NativeSession *>(Session.get());
863   return NS->getPDBFile();
864 }
865 
pdb2Yaml(StringRef Path)866 static void pdb2Yaml(StringRef Path) {
867   std::unique_ptr<IPDBSession> Session;
868   auto &File = loadPDB(Path, Session);
869 
870   auto O = std::make_unique<YAMLOutputStyle>(File);
871 
872   ExitOnErr(O->dump());
873 }
874 
dumpRaw(StringRef Path)875 static void dumpRaw(StringRef Path) {
876   InputFile IF = ExitOnErr(InputFile::open(Path));
877 
878   auto O = std::make_unique<DumpOutputStyle>(IF);
879   ExitOnErr(O->dump());
880 }
881 
dumpBytes(StringRef Path)882 static void dumpBytes(StringRef Path) {
883   std::unique_ptr<IPDBSession> Session;
884   auto &File = loadPDB(Path, Session);
885 
886   auto O = std::make_unique<BytesOutputStyle>(File);
887 
888   ExitOnErr(O->dump());
889 }
890 
shouldDumpSymLevel(SymLevel Search)891 bool opts::pretty::shouldDumpSymLevel(SymLevel Search) {
892   if (SymTypes.empty())
893     return true;
894   if (llvm::is_contained(SymTypes, Search))
895     return true;
896   if (llvm::is_contained(SymTypes, SymLevel::All))
897     return true;
898   return false;
899 }
900 
getTypeLength(const PDBSymbolData & Symbol)901 uint32_t llvm::pdb::getTypeLength(const PDBSymbolData &Symbol) {
902   auto SymbolType = Symbol.getType();
903   const IPDBRawSymbol &RawType = SymbolType->getRawSymbol();
904 
905   return RawType.getLength();
906 }
907 
compareFunctionSymbols(const std::unique_ptr<PDBSymbolFunc> & F1,const std::unique_ptr<PDBSymbolFunc> & F2)908 bool opts::pretty::compareFunctionSymbols(
909     const std::unique_ptr<PDBSymbolFunc> &F1,
910     const std::unique_ptr<PDBSymbolFunc> &F2) {
911   assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
912 
913   if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
914     return F1->getName() < F2->getName();
915 
916   // Note that we intentionally sort in descending order on length, since
917   // long functions are more interesting than short functions.
918   return F1->getLength() > F2->getLength();
919 }
920 
compareDataSymbols(const std::unique_ptr<PDBSymbolData> & F1,const std::unique_ptr<PDBSymbolData> & F2)921 bool opts::pretty::compareDataSymbols(
922     const std::unique_ptr<PDBSymbolData> &F1,
923     const std::unique_ptr<PDBSymbolData> &F2) {
924   assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
925 
926   if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
927     return F1->getName() < F2->getName();
928 
929   // Note that we intentionally sort in descending order on length, since
930   // large types are more interesting than short ones.
931   return getTypeLength(*F1) > getTypeLength(*F2);
932 }
933 
stringOr(std::string Str,std::string IfEmpty)934 static std::string stringOr(std::string Str, std::string IfEmpty) {
935   return (Str.empty()) ? IfEmpty : Str;
936 }
937 
dumpInjectedSources(LinePrinter & Printer,IPDBSession & Session)938 static void dumpInjectedSources(LinePrinter &Printer, IPDBSession &Session) {
939   auto Sources = Session.getInjectedSources();
940   if (!Sources || !Sources->getChildCount()) {
941     Printer.printLine("There are no injected sources.");
942     return;
943   }
944 
945   while (auto IS = Sources->getNext()) {
946     Printer.NewLine();
947     std::string File = stringOr(IS->getFileName(), "<null>");
948     uint64_t Size = IS->getCodeByteSize();
949     std::string Obj = stringOr(IS->getObjectFileName(), "<null>");
950     std::string VFName = stringOr(IS->getVirtualFileName(), "<null>");
951     uint32_t CRC = IS->getCrc32();
952 
953     WithColor(Printer, PDB_ColorItem::Path).get() << File;
954     Printer << " (";
955     WithColor(Printer, PDB_ColorItem::LiteralValue).get() << Size;
956     Printer << " bytes): ";
957     WithColor(Printer, PDB_ColorItem::Keyword).get() << "obj";
958     Printer << "=";
959     WithColor(Printer, PDB_ColorItem::Path).get() << Obj;
960     Printer << ", ";
961     WithColor(Printer, PDB_ColorItem::Keyword).get() << "vname";
962     Printer << "=";
963     WithColor(Printer, PDB_ColorItem::Path).get() << VFName;
964     Printer << ", ";
965     WithColor(Printer, PDB_ColorItem::Keyword).get() << "crc";
966     Printer << "=";
967     WithColor(Printer, PDB_ColorItem::LiteralValue).get() << CRC;
968     Printer << ", ";
969     WithColor(Printer, PDB_ColorItem::Keyword).get() << "compression";
970     Printer << "=";
971     dumpPDBSourceCompression(
972         WithColor(Printer, PDB_ColorItem::LiteralValue).get(),
973         IS->getCompression());
974 
975     if (!opts::pretty::ShowInjectedSourceContent)
976       continue;
977 
978     // Set the indent level to 0 when printing file content.
979     int Indent = Printer.getIndentLevel();
980     Printer.Unindent(Indent);
981 
982     if (IS->getCompression() == PDB_SourceCompression::None)
983       Printer.printLine(IS->getCode());
984     else
985       Printer.formatBinary("Compressed data",
986                            arrayRefFromStringRef(IS->getCode()),
987                            /*StartOffset=*/0);
988 
989     // Re-indent back to the original level.
990     Printer.Indent(Indent);
991   }
992 }
993 
994 template <typename OuterT, typename ChildT>
diaDumpChildren(PDBSymbol & Outer,PdbSymbolIdField Ids,PdbSymbolIdField Recurse)995 void diaDumpChildren(PDBSymbol &Outer, PdbSymbolIdField Ids,
996                      PdbSymbolIdField Recurse) {
997   OuterT *ConcreteOuter = dyn_cast<OuterT>(&Outer);
998   if (!ConcreteOuter)
999     return;
1000 
1001   auto Children = ConcreteOuter->template findAllChildren<ChildT>();
1002   while (auto Child = Children->getNext()) {
1003     outs() << "  {";
1004     Child->defaultDump(outs(), 4, Ids, Recurse);
1005     outs() << "\n  }\n";
1006   }
1007 }
1008 
dumpDia(StringRef Path)1009 static void dumpDia(StringRef Path) {
1010   std::unique_ptr<IPDBSession> Session;
1011 
1012   const auto ReaderType =
1013       opts::diadump::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
1014   ExitOnErr(loadDataForPDB(ReaderType, Path, Session));
1015 
1016   auto GlobalScope = Session->getGlobalScope();
1017 
1018   std::vector<PDB_SymType> SymTypes;
1019 
1020   if (opts::diadump::Compilands)
1021     SymTypes.push_back(PDB_SymType::Compiland);
1022   if (opts::diadump::Enums)
1023     SymTypes.push_back(PDB_SymType::Enum);
1024   if (opts::diadump::Pointers)
1025     SymTypes.push_back(PDB_SymType::PointerType);
1026   if (opts::diadump::UDTs)
1027     SymTypes.push_back(PDB_SymType::UDT);
1028   if (opts::diadump::Funcsigs)
1029     SymTypes.push_back(PDB_SymType::FunctionSig);
1030   if (opts::diadump::Arrays)
1031     SymTypes.push_back(PDB_SymType::ArrayType);
1032   if (opts::diadump::VTShapes)
1033     SymTypes.push_back(PDB_SymType::VTableShape);
1034   if (opts::diadump::Typedefs)
1035     SymTypes.push_back(PDB_SymType::Typedef);
1036   PdbSymbolIdField Ids = opts::diadump::NoSymIndexIds ? PdbSymbolIdField::None
1037                                                       : PdbSymbolIdField::All;
1038 
1039   PdbSymbolIdField Recurse = PdbSymbolIdField::None;
1040   if (opts::diadump::Recurse)
1041     Recurse = PdbSymbolIdField::All;
1042   if (!opts::diadump::ShowClassHierarchy)
1043     Ids &= ~(PdbSymbolIdField::ClassParent | PdbSymbolIdField::LexicalParent);
1044 
1045   for (PDB_SymType ST : SymTypes) {
1046     auto Children = GlobalScope->findAllChildren(ST);
1047     while (auto Child = Children->getNext()) {
1048       outs() << "{";
1049       Child->defaultDump(outs(), 2, Ids, Recurse);
1050 
1051       diaDumpChildren<PDBSymbolTypeEnum, PDBSymbolData>(*Child, Ids, Recurse);
1052       outs() << "\n}\n";
1053     }
1054   }
1055 }
1056 
dumpPretty(StringRef Path)1057 static void dumpPretty(StringRef Path) {
1058   std::unique_ptr<IPDBSession> Session;
1059 
1060   const auto ReaderType =
1061       opts::pretty::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
1062   ExitOnErr(loadDataForPDB(ReaderType, Path, Session));
1063 
1064   if (opts::pretty::LoadAddress)
1065     Session->setLoadAddress(opts::pretty::LoadAddress);
1066 
1067   auto &Stream = outs();
1068   const bool UseColor = opts::pretty::ColorOutput == cl::BOU_UNSET
1069                             ? Stream.has_colors()
1070                             : opts::pretty::ColorOutput == cl::BOU_TRUE;
1071   LinePrinter Printer(2, UseColor, Stream);
1072 
1073   auto GlobalScope(Session->getGlobalScope());
1074   if (!GlobalScope)
1075     return;
1076   std::string FileName(GlobalScope->getSymbolsFileName());
1077 
1078   WithColor(Printer, PDB_ColorItem::None).get() << "Summary for ";
1079   WithColor(Printer, PDB_ColorItem::Path).get() << FileName;
1080   Printer.Indent();
1081   uint64_t FileSize = 0;
1082 
1083   Printer.NewLine();
1084   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size";
1085   if (!sys::fs::file_size(FileName, FileSize)) {
1086     Printer << ": " << FileSize << " bytes";
1087   } else {
1088     Printer << ": (Unable to obtain file size)";
1089   }
1090 
1091   Printer.NewLine();
1092   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid";
1093   Printer << ": " << GlobalScope->getGuid();
1094 
1095   Printer.NewLine();
1096   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age";
1097   Printer << ": " << GlobalScope->getAge();
1098 
1099   Printer.NewLine();
1100   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes";
1101   Printer << ": ";
1102   if (GlobalScope->hasCTypes())
1103     outs() << "HasCTypes ";
1104   if (GlobalScope->hasPrivateSymbols())
1105     outs() << "HasPrivateSymbols ";
1106   Printer.Unindent();
1107 
1108   if (!opts::pretty::WithName.empty()) {
1109     Printer.NewLine();
1110     WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1111         << "---SYMBOLS & TYPES BY NAME---";
1112 
1113     for (StringRef Name : opts::pretty::WithName) {
1114       auto Symbols = GlobalScope->findChildren(
1115           PDB_SymType::None, Name, PDB_NameSearchFlags::NS_CaseSensitive);
1116       if (!Symbols || Symbols->getChildCount() == 0) {
1117         Printer.formatLine("[not found] - {0}", Name);
1118         continue;
1119       }
1120       Printer.formatLine("[{0} occurrences] - {1}", Symbols->getChildCount(),
1121                          Name);
1122 
1123       AutoIndent Indent(Printer);
1124       Printer.NewLine();
1125 
1126       while (auto Symbol = Symbols->getNext()) {
1127         switch (Symbol->getSymTag()) {
1128         case PDB_SymType::Typedef: {
1129           TypedefDumper TD(Printer);
1130           std::unique_ptr<PDBSymbolTypeTypedef> T =
1131               llvm::unique_dyn_cast<PDBSymbolTypeTypedef>(std::move(Symbol));
1132           TD.start(*T);
1133           break;
1134         }
1135         case PDB_SymType::Enum: {
1136           EnumDumper ED(Printer);
1137           std::unique_ptr<PDBSymbolTypeEnum> E =
1138               llvm::unique_dyn_cast<PDBSymbolTypeEnum>(std::move(Symbol));
1139           ED.start(*E);
1140           break;
1141         }
1142         case PDB_SymType::UDT: {
1143           ClassDefinitionDumper CD(Printer);
1144           std::unique_ptr<PDBSymbolTypeUDT> C =
1145               llvm::unique_dyn_cast<PDBSymbolTypeUDT>(std::move(Symbol));
1146           CD.start(*C);
1147           break;
1148         }
1149         case PDB_SymType::BaseClass:
1150         case PDB_SymType::Friend: {
1151           TypeDumper TD(Printer);
1152           Symbol->dump(TD);
1153           break;
1154         }
1155         case PDB_SymType::Function: {
1156           FunctionDumper FD(Printer);
1157           std::unique_ptr<PDBSymbolFunc> F =
1158               llvm::unique_dyn_cast<PDBSymbolFunc>(std::move(Symbol));
1159           FD.start(*F, FunctionDumper::PointerType::None);
1160           break;
1161         }
1162         case PDB_SymType::Data: {
1163           VariableDumper VD(Printer);
1164           std::unique_ptr<PDBSymbolData> D =
1165               llvm::unique_dyn_cast<PDBSymbolData>(std::move(Symbol));
1166           VD.start(*D);
1167           break;
1168         }
1169         case PDB_SymType::PublicSymbol: {
1170           ExternalSymbolDumper ED(Printer);
1171           std::unique_ptr<PDBSymbolPublicSymbol> PS =
1172               llvm::unique_dyn_cast<PDBSymbolPublicSymbol>(std::move(Symbol));
1173           ED.dump(*PS);
1174           break;
1175         }
1176         default:
1177           llvm_unreachable("Unexpected symbol tag!");
1178         }
1179       }
1180     }
1181     llvm::outs().flush();
1182   }
1183 
1184   if (opts::pretty::Compilands) {
1185     Printer.NewLine();
1186     WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1187         << "---COMPILANDS---";
1188     auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
1189 
1190     if (Compilands) {
1191       Printer.Indent();
1192       CompilandDumper Dumper(Printer);
1193       CompilandDumpFlags options = CompilandDumper::Flags::None;
1194       if (opts::pretty::Lines)
1195         options = options | CompilandDumper::Flags::Lines;
1196       while (auto Compiland = Compilands->getNext())
1197         Dumper.start(*Compiland, options);
1198       Printer.Unindent();
1199     }
1200   }
1201 
1202   if (opts::pretty::Classes || opts::pretty::Enums || opts::pretty::Typedefs ||
1203       opts::pretty::Funcsigs || opts::pretty::Pointers ||
1204       opts::pretty::Arrays || opts::pretty::VTShapes) {
1205     Printer.NewLine();
1206     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---";
1207     Printer.Indent();
1208     TypeDumper Dumper(Printer);
1209     Dumper.start(*GlobalScope);
1210     Printer.Unindent();
1211   }
1212 
1213   if (opts::pretty::Symbols) {
1214     Printer.NewLine();
1215     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---";
1216     if (auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>()) {
1217       Printer.Indent();
1218       CompilandDumper Dumper(Printer);
1219       while (auto Compiland = Compilands->getNext())
1220         Dumper.start(*Compiland, true);
1221       Printer.Unindent();
1222     }
1223   }
1224 
1225   if (opts::pretty::Globals) {
1226     Printer.NewLine();
1227     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---";
1228     Printer.Indent();
1229     if (shouldDumpSymLevel(opts::pretty::SymLevel::Functions)) {
1230       if (auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>()) {
1231         FunctionDumper Dumper(Printer);
1232         if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
1233           while (auto Function = Functions->getNext()) {
1234             Printer.NewLine();
1235             Dumper.start(*Function, FunctionDumper::PointerType::None);
1236           }
1237         } else {
1238           std::vector<std::unique_ptr<PDBSymbolFunc>> Funcs;
1239           while (auto Func = Functions->getNext())
1240             Funcs.push_back(std::move(Func));
1241           llvm::sort(Funcs, opts::pretty::compareFunctionSymbols);
1242           for (const auto &Func : Funcs) {
1243             Printer.NewLine();
1244             Dumper.start(*Func, FunctionDumper::PointerType::None);
1245           }
1246         }
1247       }
1248     }
1249     if (shouldDumpSymLevel(opts::pretty::SymLevel::Data)) {
1250       if (auto Vars = GlobalScope->findAllChildren<PDBSymbolData>()) {
1251         VariableDumper Dumper(Printer);
1252         if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
1253           while (auto Var = Vars->getNext())
1254             Dumper.start(*Var);
1255         } else {
1256           std::vector<std::unique_ptr<PDBSymbolData>> Datas;
1257           while (auto Var = Vars->getNext())
1258             Datas.push_back(std::move(Var));
1259           llvm::sort(Datas, opts::pretty::compareDataSymbols);
1260           for (const auto &Var : Datas)
1261             Dumper.start(*Var);
1262         }
1263       }
1264     }
1265     if (shouldDumpSymLevel(opts::pretty::SymLevel::Thunks)) {
1266       if (auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>()) {
1267         CompilandDumper Dumper(Printer);
1268         while (auto Thunk = Thunks->getNext())
1269           Dumper.dump(*Thunk);
1270       }
1271     }
1272     Printer.Unindent();
1273   }
1274   if (opts::pretty::Externals) {
1275     Printer.NewLine();
1276     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---";
1277     Printer.Indent();
1278     ExternalSymbolDumper Dumper(Printer);
1279     Dumper.start(*GlobalScope);
1280   }
1281   if (opts::pretty::Lines) {
1282     Printer.NewLine();
1283   }
1284   if (opts::pretty::InjectedSources) {
1285     Printer.NewLine();
1286     WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1287         << "---INJECTED SOURCES---";
1288     AutoIndent Indent1(Printer);
1289     dumpInjectedSources(Printer, *Session);
1290   }
1291 
1292   Printer.NewLine();
1293   outs().flush();
1294 }
1295 
mergePdbs()1296 static void mergePdbs() {
1297   BumpPtrAllocator Allocator;
1298   MergingTypeTableBuilder MergedTpi(Allocator);
1299   MergingTypeTableBuilder MergedIpi(Allocator);
1300 
1301   // Create a Tpi and Ipi type table with all types from all input files.
1302   for (const auto &Path : opts::merge::InputFilenames) {
1303     std::unique_ptr<IPDBSession> Session;
1304     auto &File = loadPDB(Path, Session);
1305     SmallVector<TypeIndex, 128> TypeMap;
1306     SmallVector<TypeIndex, 128> IdMap;
1307     if (File.hasPDBTpiStream()) {
1308       auto &Tpi = ExitOnErr(File.getPDBTpiStream());
1309       ExitOnErr(
1310           codeview::mergeTypeRecords(MergedTpi, TypeMap, Tpi.typeArray()));
1311     }
1312     if (File.hasPDBIpiStream()) {
1313       auto &Ipi = ExitOnErr(File.getPDBIpiStream());
1314       ExitOnErr(codeview::mergeIdRecords(MergedIpi, TypeMap, IdMap,
1315                                          Ipi.typeArray()));
1316     }
1317   }
1318 
1319   // Then write the PDB.
1320   PDBFileBuilder Builder(Allocator);
1321   ExitOnErr(Builder.initialize(4096));
1322   // Add each of the reserved streams.  We might not put any data in them,
1323   // but at least they have to be present.
1324   for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
1325     ExitOnErr(Builder.getMsfBuilder().addStream(0));
1326 
1327   auto &DestTpi = Builder.getTpiBuilder();
1328   auto &DestIpi = Builder.getIpiBuilder();
1329   MergedTpi.ForEachRecord([&DestTpi](TypeIndex TI, const CVType &Type) {
1330     DestTpi.addTypeRecord(Type.RecordData, None);
1331   });
1332   MergedIpi.ForEachRecord([&DestIpi](TypeIndex TI, const CVType &Type) {
1333     DestIpi.addTypeRecord(Type.RecordData, None);
1334   });
1335   Builder.getInfoBuilder().addFeature(PdbRaw_FeatureSig::VC140);
1336 
1337   SmallString<64> OutFile(opts::merge::PdbOutputFile);
1338   if (OutFile.empty()) {
1339     OutFile = opts::merge::InputFilenames[0];
1340     llvm::sys::path::replace_extension(OutFile, "merged.pdb");
1341   }
1342 
1343   codeview::GUID IgnoredOutGuid;
1344   ExitOnErr(Builder.commit(OutFile, &IgnoredOutGuid));
1345 }
1346 
explain()1347 static void explain() {
1348   std::unique_ptr<IPDBSession> Session;
1349   InputFile IF =
1350       ExitOnErr(InputFile::open(opts::explain::InputFilename.front(), true));
1351 
1352   for (uint64_t Off : opts::explain::Offsets) {
1353     auto O = std::make_unique<ExplainOutputStyle>(IF, Off);
1354 
1355     ExitOnErr(O->dump());
1356   }
1357 }
1358 
exportStream()1359 static void exportStream() {
1360   std::unique_ptr<IPDBSession> Session;
1361   PDBFile &File = loadPDB(opts::exportstream::InputFilename.front(), Session);
1362 
1363   std::unique_ptr<MappedBlockStream> SourceStream;
1364   uint32_t Index = 0;
1365   bool Success = false;
1366   std::string OutFileName = opts::exportstream::OutputFile;
1367 
1368   if (!opts::exportstream::ForceName) {
1369     // First try to parse it as an integer, if it fails fall back to treating it
1370     // as a named stream.
1371     if (to_integer(opts::exportstream::Stream, Index)) {
1372       if (Index >= File.getNumStreams()) {
1373         errs() << "Error: " << Index << " is not a valid stream index.\n";
1374         exit(1);
1375       }
1376       Success = true;
1377       outs() << "Dumping contents of stream index " << Index << " to file "
1378              << OutFileName << ".\n";
1379     }
1380   }
1381 
1382   if (!Success) {
1383     InfoStream &IS = cantFail(File.getPDBInfoStream());
1384     Index = ExitOnErr(IS.getNamedStreamIndex(opts::exportstream::Stream));
1385     outs() << "Dumping contents of stream '" << opts::exportstream::Stream
1386            << "' (index " << Index << ") to file " << OutFileName << ".\n";
1387   }
1388 
1389   SourceStream = File.createIndexedStream(Index);
1390   auto OutFile = ExitOnErr(
1391       FileOutputBuffer::create(OutFileName, SourceStream->getLength()));
1392   FileBufferByteStream DestStream(std::move(OutFile), llvm::support::little);
1393   BinaryStreamWriter Writer(DestStream);
1394   ExitOnErr(Writer.writeStreamRef(*SourceStream));
1395   ExitOnErr(DestStream.commit());
1396 }
1397 
parseRange(StringRef Str,Optional<opts::bytes::NumberRange> & Parsed)1398 static bool parseRange(StringRef Str,
1399                        Optional<opts::bytes::NumberRange> &Parsed) {
1400   if (Str.empty())
1401     return true;
1402 
1403   llvm::Regex R("^([^-]+)(-([^-]+))?$");
1404   llvm::SmallVector<llvm::StringRef, 2> Matches;
1405   if (!R.match(Str, &Matches))
1406     return false;
1407 
1408   Parsed.emplace();
1409   if (!to_integer(Matches[1], Parsed->Min))
1410     return false;
1411 
1412   if (!Matches[3].empty()) {
1413     Parsed->Max.emplace();
1414     if (!to_integer(Matches[3], *Parsed->Max))
1415       return false;
1416   }
1417   return true;
1418 }
1419 
simplifyChunkList(llvm::cl::list<opts::ModuleSubsection> & Chunks)1420 static void simplifyChunkList(llvm::cl::list<opts::ModuleSubsection> &Chunks) {
1421   // If this list contains "All" plus some other stuff, remove the other stuff
1422   // and just keep "All" in the list.
1423   if (!llvm::is_contained(Chunks, opts::ModuleSubsection::All))
1424     return;
1425   Chunks.reset();
1426   Chunks.push_back(opts::ModuleSubsection::All);
1427 }
1428 
main(int Argc,const char ** Argv)1429 int main(int Argc, const char **Argv) {
1430   InitLLVM X(Argc, Argv);
1431   ExitOnErr.setBanner("llvm-pdbutil: ");
1432 
1433   cl::ParseCommandLineOptions(Argc, Argv, "LLVM PDB Dumper\n");
1434 
1435   if (opts::BytesSubcommand) {
1436     if (!parseRange(opts::bytes::DumpBlockRangeOpt,
1437                     opts::bytes::DumpBlockRange)) {
1438       errs() << "Argument '" << opts::bytes::DumpBlockRangeOpt
1439              << "' invalid format.\n";
1440       errs().flush();
1441       exit(1);
1442     }
1443     if (!parseRange(opts::bytes::DumpByteRangeOpt,
1444                     opts::bytes::DumpByteRange)) {
1445       errs() << "Argument '" << opts::bytes::DumpByteRangeOpt
1446              << "' invalid format.\n";
1447       errs().flush();
1448       exit(1);
1449     }
1450   }
1451 
1452   if (opts::DumpSubcommand) {
1453     if (opts::dump::RawAll) {
1454       opts::dump::DumpGlobals = true;
1455       opts::dump::DumpFpo = true;
1456       opts::dump::DumpInlineeLines = true;
1457       opts::dump::DumpIds = true;
1458       opts::dump::DumpIdExtras = true;
1459       opts::dump::DumpLines = true;
1460       opts::dump::DumpModules = true;
1461       opts::dump::DumpModuleFiles = true;
1462       opts::dump::DumpPublics = true;
1463       opts::dump::DumpSectionContribs = true;
1464       opts::dump::DumpSectionHeaders = true;
1465       opts::dump::DumpSectionMap = true;
1466       opts::dump::DumpStreams = true;
1467       opts::dump::DumpStreamBlocks = true;
1468       opts::dump::DumpStringTable = true;
1469       opts::dump::DumpStringTableDetails = true;
1470       opts::dump::DumpSummary = true;
1471       opts::dump::DumpSymbols = true;
1472       opts::dump::DumpSymbolStats = true;
1473       opts::dump::DumpTypes = true;
1474       opts::dump::DumpTypeExtras = true;
1475       opts::dump::DumpUdtStats = true;
1476       opts::dump::DumpXme = true;
1477       opts::dump::DumpXmi = true;
1478     }
1479   }
1480   if (opts::PdbToYamlSubcommand) {
1481     if (opts::pdb2yaml::All) {
1482       opts::pdb2yaml::StreamMetadata = true;
1483       opts::pdb2yaml::StreamDirectory = true;
1484       opts::pdb2yaml::PdbStream = true;
1485       opts::pdb2yaml::StringTable = true;
1486       opts::pdb2yaml::DbiStream = true;
1487       opts::pdb2yaml::TpiStream = true;
1488       opts::pdb2yaml::IpiStream = true;
1489       opts::pdb2yaml::PublicsStream = true;
1490       opts::pdb2yaml::DumpModules = true;
1491       opts::pdb2yaml::DumpModuleFiles = true;
1492       opts::pdb2yaml::DumpModuleSyms = true;
1493       opts::pdb2yaml::DumpModuleSubsections.push_back(
1494           opts::ModuleSubsection::All);
1495     }
1496     simplifyChunkList(opts::pdb2yaml::DumpModuleSubsections);
1497 
1498     if (opts::pdb2yaml::DumpModuleSyms || opts::pdb2yaml::DumpModuleFiles)
1499       opts::pdb2yaml::DumpModules = true;
1500 
1501     if (opts::pdb2yaml::DumpModules)
1502       opts::pdb2yaml::DbiStream = true;
1503   }
1504 
1505   llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);
1506 
1507   if (opts::PdbToYamlSubcommand) {
1508     pdb2Yaml(opts::pdb2yaml::InputFilename.front());
1509   } else if (opts::YamlToPdbSubcommand) {
1510     if (opts::yaml2pdb::YamlPdbOutputFile.empty()) {
1511       SmallString<16> OutputFilename(opts::yaml2pdb::InputFilename.getValue());
1512       sys::path::replace_extension(OutputFilename, ".pdb");
1513       opts::yaml2pdb::YamlPdbOutputFile = std::string(OutputFilename.str());
1514     }
1515     yamlToPdb(opts::yaml2pdb::InputFilename);
1516   } else if (opts::DiaDumpSubcommand) {
1517     llvm::for_each(opts::diadump::InputFilenames, dumpDia);
1518   } else if (opts::PrettySubcommand) {
1519     if (opts::pretty::Lines)
1520       opts::pretty::Compilands = true;
1521 
1522     if (opts::pretty::All) {
1523       opts::pretty::Compilands = true;
1524       opts::pretty::Symbols = true;
1525       opts::pretty::Globals = true;
1526       opts::pretty::Types = true;
1527       opts::pretty::Externals = true;
1528       opts::pretty::Lines = true;
1529     }
1530 
1531     if (opts::pretty::Types) {
1532       opts::pretty::Classes = true;
1533       opts::pretty::Typedefs = true;
1534       opts::pretty::Enums = true;
1535       opts::pretty::Pointers = true;
1536       opts::pretty::Funcsigs = true;
1537     }
1538 
1539     // When adding filters for excluded compilands and types, we need to
1540     // remember that these are regexes.  So special characters such as * and \
1541     // need to be escaped in the regex.  In the case of a literal \, this means
1542     // it needs to be escaped again in the C++.  So matching a single \ in the
1543     // input requires 4 \es in the C++.
1544     if (opts::pretty::ExcludeCompilerGenerated) {
1545       opts::pretty::ExcludeTypes.push_back("__vc_attributes");
1546       opts::pretty::ExcludeCompilands.push_back("\\* Linker \\*");
1547     }
1548     if (opts::pretty::ExcludeSystemLibraries) {
1549       opts::pretty::ExcludeCompilands.push_back(
1550           "f:\\\\binaries\\\\Intermediate\\\\vctools\\\\crt_bld");
1551       opts::pretty::ExcludeCompilands.push_back("f:\\\\dd\\\\vctools\\\\crt");
1552       opts::pretty::ExcludeCompilands.push_back(
1553           "d:\\\\th.obj.x86fre\\\\minkernel");
1554     }
1555     llvm::for_each(opts::pretty::InputFilenames, dumpPretty);
1556   } else if (opts::DumpSubcommand) {
1557     llvm::for_each(opts::dump::InputFilenames, dumpRaw);
1558   } else if (opts::BytesSubcommand) {
1559     llvm::for_each(opts::bytes::InputFilenames, dumpBytes);
1560   } else if (opts::MergeSubcommand) {
1561     if (opts::merge::InputFilenames.size() < 2) {
1562       errs() << "merge subcommand requires at least 2 input files.\n";
1563       exit(1);
1564     }
1565     mergePdbs();
1566   } else if (opts::ExplainSubcommand) {
1567     explain();
1568   } else if (opts::ExportSubcommand) {
1569     exportStream();
1570   }
1571 
1572   outs().flush();
1573   return 0;
1574 }
1575