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