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