]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[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 "Analyze.h"
17 #include "BytesOutputStyle.h"
18 #include "Diff.h"
19 #include "DumpOutputStyle.h"
20 #include "LinePrinter.h"
21 #include "OutputStyle.h"
22 #include "PrettyCompilandDumper.h"
23 #include "PrettyExternalSymbolDumper.h"
24 #include "PrettyFunctionDumper.h"
25 #include "PrettyTypeDumper.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/Config/config.h"
35 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
36 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
37 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
38 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
39 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
40 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
41 #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
42 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
43 #include "llvm/DebugInfo/PDB/GenericError.h"
44 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
45 #include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
46 #include "llvm/DebugInfo/PDB/IPDBSession.h"
47 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
48 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
49 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
50 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
51 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
52 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
53 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
54 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
55 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
56 #include "llvm/DebugInfo/PDB/Native/RawConstants.h"
57 #include "llvm/DebugInfo/PDB/Native/RawError.h"
58 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
59 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
60 #include "llvm/DebugInfo/PDB/PDB.h"
61 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
62 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
63 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
64 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
65 #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
66 #include "llvm/Support/BinaryByteStream.h"
67 #include "llvm/Support/COM.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/ConvertUTF.h"
70 #include "llvm/Support/FileOutputBuffer.h"
71 #include "llvm/Support/FileSystem.h"
72 #include "llvm/Support/Format.h"
73 #include "llvm/Support/ManagedStatic.h"
74 #include "llvm/Support/MemoryBuffer.h"
75 #include "llvm/Support/Path.h"
76 #include "llvm/Support/PrettyStackTrace.h"
77 #include "llvm/Support/Process.h"
78 #include "llvm/Support/Regex.h"
79 #include "llvm/Support/ScopedPrinter.h"
80 #include "llvm/Support/Signals.h"
81 #include "llvm/Support/raw_ostream.h"
82
83 using namespace llvm;
84 using namespace llvm::codeview;
85 using namespace llvm::msf;
86 using namespace llvm::pdb;
87
88 namespace opts {
89
90 cl::SubCommand DumpSubcommand("dump", "Dump MSF and CodeView debug info");
91 cl::SubCommand BytesSubcommand("bytes", "Dump raw bytes from the PDB file");
92
93 cl::SubCommand
94     PrettySubcommand("pretty",
95                      "Dump semantic information about types and symbols");
96
97 cl::SubCommand DiffSubcommand("diff", "Diff the contents of 2 PDB files");
98
99 cl::SubCommand
100     YamlToPdbSubcommand("yaml2pdb",
101                         "Generate a PDB file from a YAML description");
102 cl::SubCommand
103     PdbToYamlSubcommand("pdb2yaml",
104                         "Generate a detailed YAML description of a PDB File");
105
106 cl::SubCommand
107     AnalyzeSubcommand("analyze",
108                       "Analyze various aspects of a PDB's structure");
109
110 cl::SubCommand MergeSubcommand("merge",
111                                "Merge multiple PDBs into a single PDB");
112
113 cl::OptionCategory TypeCategory("Symbol Type Options");
114 cl::OptionCategory FilterCategory("Filtering and Sorting Options");
115 cl::OptionCategory OtherOptions("Other Options");
116
117 cl::ValuesClass ChunkValues = cl::values(
118     clEnumValN(ModuleSubsection::CrossScopeExports, "cme",
119                "Cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
120     clEnumValN(ModuleSubsection::CrossScopeImports, "cmi",
121                "Cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
122     clEnumValN(ModuleSubsection::FileChecksums, "fc",
123                "File checksums (DEBUG_S_CHECKSUMS subsection)"),
124     clEnumValN(ModuleSubsection::InlineeLines, "ilines",
125                "Inlinee lines (DEBUG_S_INLINEELINES subsection)"),
126     clEnumValN(ModuleSubsection::Lines, "lines",
127                "Lines (DEBUG_S_LINES subsection)"),
128     clEnumValN(ModuleSubsection::StringTable, "strings",
129                "String Table (DEBUG_S_STRINGTABLE subsection) (not "
130                "typically present in PDB file)"),
131     clEnumValN(ModuleSubsection::FrameData, "frames",
132                "Frame Data (DEBUG_S_FRAMEDATA subsection)"),
133     clEnumValN(ModuleSubsection::Symbols, "symbols",
134                "Symbols (DEBUG_S_SYMBOLS subsection) (not typically "
135                "present in PDB file)"),
136     clEnumValN(ModuleSubsection::CoffSymbolRVAs, "rvas",
137                "COFF Symbol RVAs (DEBUG_S_COFF_SYMBOL_RVA subsection)"),
138     clEnumValN(ModuleSubsection::Unknown, "unknown",
139                "Any subsection not covered by another option"),
140     clEnumValN(ModuleSubsection::All, "all", "All known subsections"));
141
142 namespace pretty {
143 cl::list<std::string> InputFilenames(cl::Positional,
144                                      cl::desc("<input PDB files>"),
145                                      cl::OneOrMore, cl::sub(PrettySubcommand));
146
147 cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"),
148                          cl::cat(TypeCategory), cl::sub(PrettySubcommand));
149 cl::opt<bool> Symbols("module-syms",
150                       cl::desc("Display symbols for each compiland"),
151                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
152 cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"),
153                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
154 cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"),
155                         cl::cat(TypeCategory), cl::sub(PrettySubcommand));
156 cl::list<SymLevel> SymTypes(
157     "sym-types", cl::desc("Type of symbols to dump (default all)"),
158     cl::cat(TypeCategory), cl::sub(PrettySubcommand), cl::ZeroOrMore,
159     cl::values(
160         clEnumValN(SymLevel::Thunks, "thunks", "Display thunk symbols"),
161         clEnumValN(SymLevel::Data, "data", "Display data symbols"),
162         clEnumValN(SymLevel::Functions, "funcs", "Display function symbols"),
163         clEnumValN(SymLevel::All, "all", "Display all symbols (default)")));
164
165 cl::opt<bool>
166     Types("types",
167           cl::desc("Display all types (implies -classes, -enums, -typedefs)"),
168           cl::cat(TypeCategory), cl::sub(PrettySubcommand));
169 cl::opt<bool> Classes("classes", cl::desc("Display class types"),
170                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
171 cl::opt<bool> Enums("enums", cl::desc("Display enum types"),
172                     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
173 cl::opt<bool> Typedefs("typedefs", cl::desc("Display typedef types"),
174                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
175 cl::opt<SymbolSortMode> SymbolOrder(
176     "symbol-order", cl::desc("symbol sort order"),
177     cl::init(SymbolSortMode::None),
178     cl::values(clEnumValN(SymbolSortMode::None, "none",
179                           "Undefined / no particular sort order"),
180                clEnumValN(SymbolSortMode::Name, "name", "Sort symbols by name"),
181                clEnumValN(SymbolSortMode::Size, "size",
182                           "Sort symbols by size")),
183     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
184
185 cl::opt<ClassSortMode> ClassOrder(
186     "class-order", cl::desc("Class sort order"), cl::init(ClassSortMode::None),
187     cl::values(
188         clEnumValN(ClassSortMode::None, "none",
189                    "Undefined / no particular sort order"),
190         clEnumValN(ClassSortMode::Name, "name", "Sort classes by name"),
191         clEnumValN(ClassSortMode::Size, "size", "Sort classes by size"),
192         clEnumValN(ClassSortMode::Padding, "padding",
193                    "Sort classes by amount of padding"),
194         clEnumValN(ClassSortMode::PaddingPct, "padding-pct",
195                    "Sort classes by percentage of space consumed by padding"),
196         clEnumValN(ClassSortMode::PaddingImmediate, "padding-imm",
197                    "Sort classes by amount of immediate padding"),
198         clEnumValN(ClassSortMode::PaddingPctImmediate, "padding-pct-imm",
199                    "Sort classes by percentage of space consumed by immediate "
200                    "padding")),
201     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
202
203 cl::opt<ClassDefinitionFormat> ClassFormat(
204     "class-definitions", cl::desc("Class definition format"),
205     cl::init(ClassDefinitionFormat::All),
206     cl::values(
207         clEnumValN(ClassDefinitionFormat::All, "all",
208                    "Display all class members including data, constants, "
209                    "typedefs, functions, etc"),
210         clEnumValN(ClassDefinitionFormat::Layout, "layout",
211                    "Only display members that contribute to class size."),
212         clEnumValN(ClassDefinitionFormat::None, "none",
213                    "Don't display class definitions")),
214     cl::cat(TypeCategory), cl::sub(PrettySubcommand));
215 cl::opt<uint32_t> ClassRecursionDepth(
216     "class-recurse-depth", cl::desc("Class recursion depth (0=no limit)"),
217     cl::init(0), cl::cat(TypeCategory), cl::sub(PrettySubcommand));
218
219 cl::opt<bool> Lines("lines", cl::desc("Line tables"), cl::cat(TypeCategory),
220                     cl::sub(PrettySubcommand));
221 cl::opt<bool>
222     All("all", cl::desc("Implies all other options in 'Symbol Types' category"),
223         cl::cat(TypeCategory), cl::sub(PrettySubcommand));
224
225 cl::opt<uint64_t> LoadAddress(
226     "load-address",
227     cl::desc("Assume the module is loaded at the specified address"),
228     cl::cat(OtherOptions), cl::sub(PrettySubcommand));
229 cl::opt<bool> Native("native", cl::desc("Use native PDB reader instead of DIA"),
230                      cl::cat(OtherOptions), cl::sub(PrettySubcommand));
231 cl::opt<cl::boolOrDefault>
232     ColorOutput("color-output",
233                 cl::desc("Override use of color (default = isatty)"),
234                 cl::cat(OtherOptions), cl::sub(PrettySubcommand));
235 cl::list<std::string> ExcludeTypes(
236     "exclude-types", cl::desc("Exclude types by regular expression"),
237     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
238 cl::list<std::string> ExcludeSymbols(
239     "exclude-symbols", cl::desc("Exclude symbols by regular expression"),
240     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
241 cl::list<std::string> ExcludeCompilands(
242     "exclude-compilands", cl::desc("Exclude compilands by regular expression"),
243     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
244
245 cl::list<std::string> IncludeTypes(
246     "include-types",
247     cl::desc("Include only types which match a regular expression"),
248     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
249 cl::list<std::string> IncludeSymbols(
250     "include-symbols",
251     cl::desc("Include only symbols which match a regular expression"),
252     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
253 cl::list<std::string> IncludeCompilands(
254     "include-compilands",
255     cl::desc("Include only compilands those which match a regular expression"),
256     cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
257 cl::opt<uint32_t> SizeThreshold(
258     "min-type-size", cl::desc("Displays only those types which are greater "
259                               "than or equal to the specified size."),
260     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
261 cl::opt<uint32_t> PaddingThreshold(
262     "min-class-padding", cl::desc("Displays only those classes which have at "
263                                   "least the specified amount of padding."),
264     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
265 cl::opt<uint32_t> ImmediatePaddingThreshold(
266     "min-class-padding-imm",
267     cl::desc("Displays only those classes which have at least the specified "
268              "amount of immediate padding, ignoring padding internal to bases "
269              "and aggregates."),
270     cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
271
272 cl::opt<bool> ExcludeCompilerGenerated(
273     "no-compiler-generated",
274     cl::desc("Don't show compiler generated types and symbols"),
275     cl::cat(FilterCategory), cl::sub(PrettySubcommand));
276 cl::opt<bool>
277     ExcludeSystemLibraries("no-system-libs",
278                            cl::desc("Don't show symbols from system libraries"),
279                            cl::cat(FilterCategory), cl::sub(PrettySubcommand));
280
281 cl::opt<bool> NoEnumDefs("no-enum-definitions",
282                          cl::desc("Don't display full enum definitions"),
283                          cl::cat(FilterCategory), cl::sub(PrettySubcommand));
284 }
285
286 namespace diff {
287 cl::list<std::string> InputFilenames(cl::Positional,
288                                      cl::desc("<first> <second>"),
289                                      cl::OneOrMore, cl::sub(DiffSubcommand));
290 }
291
292 cl::OptionCategory FileOptions("Module & File Options");
293
294 namespace bytes {
295 cl::OptionCategory MsfBytes("MSF File Options");
296 cl::OptionCategory DbiBytes("Dbi Stream Options");
297 cl::OptionCategory PdbBytes("PDB Stream Options");
298 cl::OptionCategory Types("Type Options");
299 cl::OptionCategory ModuleCategory("Module Options");
300
301 llvm::Optional<NumberRange> DumpBlockRange;
302 llvm::Optional<NumberRange> DumpByteRange;
303
304 cl::opt<std::string> DumpBlockRangeOpt(
305     "block-range", cl::value_desc("start[-end]"),
306     cl::desc("Dump binary data from specified range of blocks."),
307     cl::sub(BytesSubcommand), cl::cat(MsfBytes));
308
309 cl::opt<std::string>
310     DumpByteRangeOpt("byte-range", cl::value_desc("start[-end]"),
311                      cl::desc("Dump binary data from specified range of bytes"),
312                      cl::sub(BytesSubcommand), cl::cat(MsfBytes));
313
314 cl::list<std::string>
315     DumpStreamData("stream-data", cl::CommaSeparated, cl::ZeroOrMore,
316                    cl::desc("Dump binary data from specified streams.  Format "
317                             "is SN[:Start][@Size]"),
318                    cl::sub(BytesSubcommand), cl::cat(MsfBytes));
319
320 cl::opt<bool> NameMap("name-map", cl::desc("Dump bytes of PDB Name Map"),
321                       cl::sub(BytesSubcommand), cl::cat(PdbBytes));
322
323 cl::opt<bool> SectionContributions("sc", cl::desc("Dump section contributions"),
324                                    cl::sub(BytesSubcommand), cl::cat(DbiBytes));
325 cl::opt<bool> SectionMap("sm", cl::desc("Dump section map"),
326                          cl::sub(BytesSubcommand), cl::cat(DbiBytes));
327 cl::opt<bool> ModuleInfos("modi", cl::desc("Dump module info"),
328                           cl::sub(BytesSubcommand), cl::cat(DbiBytes));
329 cl::opt<bool> FileInfo("files", cl::desc("Dump source file info"),
330                        cl::sub(BytesSubcommand), cl::cat(DbiBytes));
331 cl::opt<bool> TypeServerMap("type-server", cl::desc("Dump type server map"),
332                             cl::sub(BytesSubcommand), cl::cat(DbiBytes));
333 cl::opt<bool> ECData("ec", cl::desc("Dump edit and continue map"),
334                      cl::sub(BytesSubcommand), cl::cat(DbiBytes));
335
336 cl::list<uint32_t>
337     TypeIndex("type",
338               cl::desc("Dump the type record with the given type index"),
339               cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
340               cl::cat(TypeCategory));
341 cl::list<uint32_t>
342     IdIndex("id", cl::desc("Dump the id record with the given type index"),
343             cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
344             cl::cat(TypeCategory));
345
346 cl::opt<uint32_t> ModuleIndex(
347     "mod",
348     cl::desc(
349         "Limit options in the Modules category to the specified module index"),
350     cl::Optional, cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
351 cl::opt<bool> ModuleSyms("syms", cl::desc("Dump symbol record substream"),
352                          cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
353 cl::opt<bool> ModuleC11("c11-chunks", cl::Hidden,
354                         cl::desc("Dump C11 CodeView debug chunks"),
355                         cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
356 cl::opt<bool> ModuleC13("chunks",
357                         cl::desc("Dump C13 CodeView debug chunk subsection"),
358                         cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
359 cl::opt<bool> SplitChunks(
360     "split-chunks",
361     cl::desc(
362         "When dumping debug chunks, show a different section for each chunk"),
363     cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
364 cl::list<std::string> InputFilenames(cl::Positional,
365                                      cl::desc("<input PDB files>"),
366                                      cl::OneOrMore, cl::sub(BytesSubcommand));
367
368 } // namespace bytes
369
370 namespace dump {
371
372 cl::OptionCategory MsfOptions("MSF Container Options");
373 cl::OptionCategory TypeOptions("Type Record Options");
374 cl::OptionCategory SymbolOptions("Symbol Options");
375 cl::OptionCategory MiscOptions("Miscellaneous Options");
376
377 // MSF OPTIONS
378 cl::opt<bool> DumpSummary("summary", cl::desc("dump file summary"),
379                           cl::cat(MsfOptions), cl::sub(DumpSubcommand));
380 cl::opt<bool> DumpStreams("streams",
381                           cl::desc("dump summary of the PDB streams"),
382                           cl::cat(MsfOptions), cl::sub(DumpSubcommand));
383 cl::opt<bool> DumpStreamBlocks(
384     "stream-blocks",
385     cl::desc("Add block information to the output of -streams"),
386     cl::cat(MsfOptions), cl::sub(DumpSubcommand));
387
388 // TYPE OPTIONS
389 cl::opt<bool> DumpTypes("types",
390                         cl::desc("dump CodeView type records from TPI stream"),
391                         cl::cat(TypeOptions), cl::sub(DumpSubcommand));
392 cl::opt<bool> DumpTypeData(
393     "type-data",
394     cl::desc("dump CodeView type record raw bytes from TPI stream"),
395     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
396
397 cl::opt<bool> DumpTypeExtras("type-extras",
398                              cl::desc("dump type hashes and index offsets"),
399                              cl::cat(TypeOptions), cl::sub(DumpSubcommand));
400
401 cl::list<uint32_t> DumpTypeIndex(
402     "type-index", cl::ZeroOrMore,
403     cl::desc("only dump types with the specified hexadecimal type index"),
404     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
405
406 cl::opt<bool> DumpIds("ids",
407                       cl::desc("dump CodeView type records from IPI stream"),
408                       cl::cat(TypeOptions), cl::sub(DumpSubcommand));
409 cl::opt<bool>
410     DumpIdData("id-data",
411                cl::desc("dump CodeView type record raw bytes from IPI stream"),
412                cl::cat(TypeOptions), cl::sub(DumpSubcommand));
413
414 cl::opt<bool> DumpIdExtras("id-extras",
415                            cl::desc("dump id hashes and index offsets"),
416                            cl::cat(TypeOptions), cl::sub(DumpSubcommand));
417 cl::list<uint32_t> DumpIdIndex(
418     "id-index", cl::ZeroOrMore,
419     cl::desc("only dump ids with the specified hexadecimal type index"),
420     cl::cat(TypeOptions), cl::sub(DumpSubcommand));
421
422 // SYMBOL OPTIONS
423 cl::opt<bool> DumpPublics("publics", cl::desc("dump Publics stream data"),
424                           cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
425 cl::opt<bool> DumpSymbols("symbols", cl::desc("dump module symbols"),
426                           cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
427
428 cl::opt<bool>
429     DumpSymRecordBytes("sym-data",
430                        cl::desc("dump CodeView symbol record raw bytes"),
431                        cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
432
433 // MODULE & FILE OPTIONS
434 cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
435                           cl::cat(FileOptions), cl::sub(DumpSubcommand));
436 cl::opt<bool> DumpModuleFiles(
437     "files",
438     cl::desc("Dump the source files that contribute to each module's."),
439     cl::cat(FileOptions), cl::sub(DumpSubcommand));
440 cl::opt<bool> DumpLines(
441     "l",
442     cl::desc("dump source file/line information (DEBUG_S_LINES subsection)"),
443     cl::cat(FileOptions), cl::sub(DumpSubcommand));
444 cl::opt<bool> DumpInlineeLines(
445     "il",
446     cl::desc("dump inlinee line information (DEBUG_S_INLINEELINES subsection)"),
447     cl::cat(FileOptions), cl::sub(DumpSubcommand));
448 cl::opt<bool> DumpXmi(
449     "xmi",
450     cl::desc(
451         "dump cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
452     cl::cat(FileOptions), cl::sub(DumpSubcommand));
453 cl::opt<bool> DumpXme(
454     "xme",
455     cl::desc(
456         "dump cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
457     cl::cat(FileOptions), cl::sub(DumpSubcommand));
458
459 // MISCELLANEOUS OPTIONS
460 cl::opt<bool> DumpStringTable("string-table", cl::desc("dump PDB String Table"),
461                               cl::cat(MiscOptions), cl::sub(DumpSubcommand));
462
463 cl::opt<bool> DumpSectionContribs("section-contribs",
464                                   cl::desc("dump section contributions"),
465                                   cl::cat(MiscOptions),
466                                   cl::sub(DumpSubcommand));
467 cl::opt<bool> DumpSectionMap("section-map", cl::desc("dump section map"),
468                              cl::cat(MiscOptions), cl::sub(DumpSubcommand));
469
470 cl::opt<bool> RawAll("all", cl::desc("Implies most other options."),
471                      cl::cat(MiscOptions), cl::sub(DumpSubcommand));
472
473 cl::list<std::string> InputFilenames(cl::Positional,
474                                      cl::desc("<input PDB files>"),
475                                      cl::OneOrMore, cl::sub(DumpSubcommand));
476 }
477
478 namespace yaml2pdb {
479 cl::opt<std::string>
480     YamlPdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
481                       cl::sub(YamlToPdbSubcommand));
482
483 cl::opt<std::string> InputFilename(cl::Positional,
484                                    cl::desc("<input YAML file>"), cl::Required,
485                                    cl::sub(YamlToPdbSubcommand));
486 }
487
488 namespace pdb2yaml {
489 cl::opt<bool> All("all",
490                   cl::desc("Dump everything we know how to dump."),
491                   cl::sub(PdbToYamlSubcommand), cl::init(false));
492 cl::opt<bool> NoFileHeaders("no-file-headers",
493                             cl::desc("Do not dump MSF file headers"),
494                             cl::sub(PdbToYamlSubcommand), cl::init(false));
495 cl::opt<bool> Minimal("minimal",
496                       cl::desc("Don't write fields with default values"),
497                       cl::sub(PdbToYamlSubcommand), cl::init(false));
498
499 cl::opt<bool> StreamMetadata(
500     "stream-metadata",
501     cl::desc("Dump the number of streams and each stream's size"),
502     cl::sub(PdbToYamlSubcommand), cl::init(false));
503 cl::opt<bool> StreamDirectory(
504     "stream-directory",
505     cl::desc("Dump each stream's block map (implies -stream-metadata)"),
506     cl::sub(PdbToYamlSubcommand), cl::init(false));
507 cl::opt<bool> PdbStream("pdb-stream",
508                         cl::desc("Dump the PDB Stream (Stream 1)"),
509                         cl::sub(PdbToYamlSubcommand), cl::init(false));
510
511 cl::opt<bool> StringTable("string-table", cl::desc("Dump the PDB String Table"),
512                           cl::sub(PdbToYamlSubcommand), cl::init(false));
513
514 cl::opt<bool> DbiStream("dbi-stream",
515                         cl::desc("Dump the DBI Stream Headers (Stream 2)"),
516                         cl::sub(PdbToYamlSubcommand), cl::init(false));
517
518 cl::opt<bool> TpiStream("tpi-stream",
519                         cl::desc("Dump the TPI Stream (Stream 3)"),
520                         cl::sub(PdbToYamlSubcommand), cl::init(false));
521
522 cl::opt<bool> IpiStream("ipi-stream",
523                         cl::desc("Dump the IPI Stream (Stream 5)"),
524                         cl::sub(PdbToYamlSubcommand), cl::init(false));
525
526 // MODULE & FILE OPTIONS
527 cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
528                           cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
529 cl::opt<bool> DumpModuleFiles("module-files", cl::desc("dump file information"),
530                               cl::cat(FileOptions),
531                               cl::sub(PdbToYamlSubcommand));
532 cl::list<ModuleSubsection> DumpModuleSubsections(
533     "subsections", cl::ZeroOrMore, cl::CommaSeparated,
534     cl::desc("dump subsections from each module's debug stream"), ChunkValues,
535     cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
536 cl::opt<bool> DumpModuleSyms("module-syms", cl::desc("dump module symbols"),
537                              cl::cat(FileOptions),
538                              cl::sub(PdbToYamlSubcommand));
539
540 cl::list<std::string> InputFilename(cl::Positional,
541                                     cl::desc("<input PDB file>"), cl::Required,
542                                     cl::sub(PdbToYamlSubcommand));
543 } // namespace pdb2yaml
544
545 namespace analyze {
546 cl::opt<bool> StringTable("hash-collisions", cl::desc("Find hash collisions"),
547                           cl::sub(AnalyzeSubcommand), cl::init(false));
548 cl::list<std::string> InputFilename(cl::Positional,
549                                     cl::desc("<input PDB file>"), cl::Required,
550                                     cl::sub(AnalyzeSubcommand));
551 }
552
553 namespace merge {
554 cl::list<std::string> InputFilenames(cl::Positional,
555                                      cl::desc("<input PDB files>"),
556                                      cl::OneOrMore, cl::sub(MergeSubcommand));
557 cl::opt<std::string>
558     PdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
559                   cl::sub(MergeSubcommand));
560 }
561 }
562
563 static ExitOnError ExitOnErr;
564
565 static void yamlToPdb(StringRef Path) {
566   BumpPtrAllocator Allocator;
567   ErrorOr<std::unique_ptr<MemoryBuffer>> ErrorOrBuffer =
568       MemoryBuffer::getFileOrSTDIN(Path, /*FileSize=*/-1,
569                                    /*RequiresNullTerminator=*/false);
570
571   if (ErrorOrBuffer.getError()) {
572     ExitOnErr(make_error<GenericError>(generic_error_code::invalid_path, Path));
573   }
574
575   std::unique_ptr<MemoryBuffer> &Buffer = ErrorOrBuffer.get();
576
577   llvm::yaml::Input In(Buffer->getBuffer());
578   pdb::yaml::PdbObject YamlObj(Allocator);
579   In >> YamlObj;
580
581   PDBFileBuilder Builder(Allocator);
582
583   uint32_t BlockSize = 4096;
584   if (YamlObj.Headers.hasValue())
585     BlockSize = YamlObj.Headers->SuperBlock.BlockSize;
586   ExitOnErr(Builder.initialize(BlockSize));
587   // Add each of the reserved streams.  We ignore stream metadata in the
588   // yaml, because we will reconstruct our own view of the streams.  For
589   // example, the YAML may say that there were 20 streams in the original
590   // PDB, but maybe we only dump a subset of those 20 streams, so we will
591   // have fewer, and the ones we do have may end up with different indices
592   // than the ones in the original PDB.  So we just start with a clean slate.
593   for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
594     ExitOnErr(Builder.getMsfBuilder().addStream(0));
595
596   StringsAndChecksums Strings;
597   Strings.setStrings(std::make_shared<DebugStringTableSubsection>());
598
599   if (YamlObj.StringTable.hasValue()) {
600     for (auto S : *YamlObj.StringTable)
601       Strings.strings()->insert(S);
602   }
603
604   pdb::yaml::PdbInfoStream DefaultInfoStream;
605   pdb::yaml::PdbDbiStream DefaultDbiStream;
606   pdb::yaml::PdbTpiStream DefaultTpiStream;
607   pdb::yaml::PdbTpiStream DefaultIpiStream;
608
609   const auto &Info = YamlObj.PdbStream.getValueOr(DefaultInfoStream);
610
611   auto &InfoBuilder = Builder.getInfoBuilder();
612   InfoBuilder.setAge(Info.Age);
613   InfoBuilder.setGuid(Info.Guid);
614   InfoBuilder.setSignature(Info.Signature);
615   InfoBuilder.setVersion(Info.Version);
616   for (auto F : Info.Features)
617     InfoBuilder.addFeature(F);
618
619   const auto &Dbi = YamlObj.DbiStream.getValueOr(DefaultDbiStream);
620   auto &DbiBuilder = Builder.getDbiBuilder();
621   DbiBuilder.setAge(Dbi.Age);
622   DbiBuilder.setBuildNumber(Dbi.BuildNumber);
623   DbiBuilder.setFlags(Dbi.Flags);
624   DbiBuilder.setMachineType(Dbi.MachineType);
625   DbiBuilder.setPdbDllRbld(Dbi.PdbDllRbld);
626   DbiBuilder.setPdbDllVersion(Dbi.PdbDllVersion);
627   DbiBuilder.setVersionHeader(Dbi.VerHeader);
628   for (const auto &MI : Dbi.ModInfos) {
629     auto &ModiBuilder = ExitOnErr(DbiBuilder.addModuleInfo(MI.Mod));
630     ModiBuilder.setObjFileName(MI.Obj);
631
632     for (auto S : MI.SourceFiles)
633       ExitOnErr(DbiBuilder.addModuleSourceFile(MI.Mod, S));
634     if (MI.Modi.hasValue()) {
635       const auto &ModiStream = *MI.Modi;
636       for (auto Symbol : ModiStream.Symbols) {
637         ModiBuilder.addSymbol(
638             Symbol.toCodeViewSymbol(Allocator, CodeViewContainer::Pdb));
639       }
640     }
641
642     // Each module has its own checksum subsection, so scan for it every time.
643     Strings.setChecksums(nullptr);
644     CodeViewYAML::initializeStringsAndChecksums(MI.Subsections, Strings);
645
646     auto CodeViewSubsections = ExitOnErr(CodeViewYAML::toCodeViewSubsectionList(
647         Allocator, MI.Subsections, Strings));
648     for (auto &SS : CodeViewSubsections) {
649       ModiBuilder.addDebugSubsection(SS);
650     }
651   }
652
653   auto &TpiBuilder = Builder.getTpiBuilder();
654   const auto &Tpi = YamlObj.TpiStream.getValueOr(DefaultTpiStream);
655   TpiBuilder.setVersionHeader(Tpi.Version);
656   for (const auto &R : Tpi.Records) {
657     CVType Type = R.toCodeViewRecord(Allocator);
658     TpiBuilder.addTypeRecord(Type.RecordData, None);
659   }
660
661   const auto &Ipi = YamlObj.IpiStream.getValueOr(DefaultIpiStream);
662   auto &IpiBuilder = Builder.getIpiBuilder();
663   IpiBuilder.setVersionHeader(Ipi.Version);
664   for (const auto &R : Ipi.Records) {
665     CVType Type = R.toCodeViewRecord(Allocator);
666     IpiBuilder.addTypeRecord(Type.RecordData, None);
667   }
668
669   Builder.getStringTableBuilder().setStrings(*Strings.strings());
670
671   ExitOnErr(Builder.commit(opts::yaml2pdb::YamlPdbOutputFile));
672 }
673
674 static PDBFile &loadPDB(StringRef Path, std::unique_ptr<IPDBSession> &Session) {
675   ExitOnErr(loadDataForPDB(PDB_ReaderType::Native, Path, Session));
676
677   NativeSession *NS = static_cast<NativeSession *>(Session.get());
678   return NS->getPDBFile();
679 }
680
681 static void pdb2Yaml(StringRef Path) {
682   std::unique_ptr<IPDBSession> Session;
683   auto &File = loadPDB(Path, Session);
684
685   auto O = llvm::make_unique<YAMLOutputStyle>(File);
686   O = llvm::make_unique<YAMLOutputStyle>(File);
687
688   ExitOnErr(O->dump());
689 }
690
691 static void dumpRaw(StringRef Path) {
692   std::unique_ptr<IPDBSession> Session;
693   auto &File = loadPDB(Path, Session);
694
695   auto O = llvm::make_unique<DumpOutputStyle>(File);
696
697   ExitOnErr(O->dump());
698 }
699
700 static void dumpBytes(StringRef Path) {
701   std::unique_ptr<IPDBSession> Session;
702   auto &File = loadPDB(Path, Session);
703
704   auto O = llvm::make_unique<BytesOutputStyle>(File);
705
706   ExitOnErr(O->dump());
707 }
708
709 static void dumpAnalysis(StringRef Path) {
710   std::unique_ptr<IPDBSession> Session;
711   auto &File = loadPDB(Path, Session);
712   auto O = llvm::make_unique<AnalysisStyle>(File);
713
714   ExitOnErr(O->dump());
715 }
716
717 static void diff(StringRef Path1, StringRef Path2) {
718   std::unique_ptr<IPDBSession> Session1;
719   std::unique_ptr<IPDBSession> Session2;
720
721   auto &File1 = loadPDB(Path1, Session1);
722   auto &File2 = loadPDB(Path2, Session2);
723
724   auto O = llvm::make_unique<DiffStyle>(File1, File2);
725
726   ExitOnErr(O->dump());
727 }
728
729 bool opts::pretty::shouldDumpSymLevel(SymLevel Search) {
730   if (SymTypes.empty())
731     return true;
732   if (llvm::find(SymTypes, Search) != SymTypes.end())
733     return true;
734   if (llvm::find(SymTypes, SymLevel::All) != SymTypes.end())
735     return true;
736   return false;
737 }
738
739 uint32_t llvm::pdb::getTypeLength(const PDBSymbolData &Symbol) {
740   auto SymbolType = Symbol.getType();
741   const IPDBRawSymbol &RawType = SymbolType->getRawSymbol();
742
743   return RawType.getLength();
744 }
745
746 bool opts::pretty::compareFunctionSymbols(
747     const std::unique_ptr<PDBSymbolFunc> &F1,
748     const std::unique_ptr<PDBSymbolFunc> &F2) {
749   assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
750
751   if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
752     return F1->getName() < F2->getName();
753
754   // Note that we intentionally sort in descending order on length, since
755   // long functions are more interesting than short functions.
756   return F1->getLength() > F2->getLength();
757 }
758
759 bool opts::pretty::compareDataSymbols(
760     const std::unique_ptr<PDBSymbolData> &F1,
761     const std::unique_ptr<PDBSymbolData> &F2) {
762   assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
763
764   if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
765     return F1->getName() < F2->getName();
766
767   // Note that we intentionally sort in descending order on length, since
768   // large types are more interesting than short ones.
769   return getTypeLength(*F1) > getTypeLength(*F2);
770 }
771
772 static void dumpPretty(StringRef Path) {
773   std::unique_ptr<IPDBSession> Session;
774
775   const auto ReaderType =
776       opts::pretty::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
777   ExitOnErr(loadDataForPDB(ReaderType, Path, Session));
778
779   if (opts::pretty::LoadAddress)
780     Session->setLoadAddress(opts::pretty::LoadAddress);
781
782   auto &Stream = outs();
783   const bool UseColor = opts::pretty::ColorOutput == cl::BOU_UNSET
784                             ? Stream.has_colors()
785                             : opts::pretty::ColorOutput == cl::BOU_TRUE;
786   LinePrinter Printer(2, UseColor, Stream);
787
788   auto GlobalScope(Session->getGlobalScope());
789   std::string FileName(GlobalScope->getSymbolsFileName());
790
791   WithColor(Printer, PDB_ColorItem::None).get() << "Summary for ";
792   WithColor(Printer, PDB_ColorItem::Path).get() << FileName;
793   Printer.Indent();
794   uint64_t FileSize = 0;
795
796   Printer.NewLine();
797   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size";
798   if (!sys::fs::file_size(FileName, FileSize)) {
799     Printer << ": " << FileSize << " bytes";
800   } else {
801     Printer << ": (Unable to obtain file size)";
802   }
803
804   Printer.NewLine();
805   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid";
806   Printer << ": " << GlobalScope->getGuid();
807
808   Printer.NewLine();
809   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age";
810   Printer << ": " << GlobalScope->getAge();
811
812   Printer.NewLine();
813   WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes";
814   Printer << ": ";
815   if (GlobalScope->hasCTypes())
816     outs() << "HasCTypes ";
817   if (GlobalScope->hasPrivateSymbols())
818     outs() << "HasPrivateSymbols ";
819   Printer.Unindent();
820
821   if (opts::pretty::Compilands) {
822     Printer.NewLine();
823     WithColor(Printer, PDB_ColorItem::SectionHeader).get()
824         << "---COMPILANDS---";
825     Printer.Indent();
826     auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
827     CompilandDumper Dumper(Printer);
828     CompilandDumpFlags options = CompilandDumper::Flags::None;
829     if (opts::pretty::Lines)
830       options = options | CompilandDumper::Flags::Lines;
831     while (auto Compiland = Compilands->getNext())
832       Dumper.start(*Compiland, options);
833     Printer.Unindent();
834   }
835
836   if (opts::pretty::Classes || opts::pretty::Enums || opts::pretty::Typedefs) {
837     Printer.NewLine();
838     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---";
839     Printer.Indent();
840     TypeDumper Dumper(Printer);
841     Dumper.start(*GlobalScope);
842     Printer.Unindent();
843   }
844
845   if (opts::pretty::Symbols) {
846     Printer.NewLine();
847     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---";
848     Printer.Indent();
849     auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
850     CompilandDumper Dumper(Printer);
851     while (auto Compiland = Compilands->getNext())
852       Dumper.start(*Compiland, true);
853     Printer.Unindent();
854   }
855
856   if (opts::pretty::Globals) {
857     Printer.NewLine();
858     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---";
859     Printer.Indent();
860     if (shouldDumpSymLevel(opts::pretty::SymLevel::Functions)) {
861       FunctionDumper Dumper(Printer);
862       auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>();
863       if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
864         while (auto Function = Functions->getNext()) {
865           Printer.NewLine();
866           Dumper.start(*Function, FunctionDumper::PointerType::None);
867         }
868       } else {
869         std::vector<std::unique_ptr<PDBSymbolFunc>> Funcs;
870         while (auto Func = Functions->getNext())
871           Funcs.push_back(std::move(Func));
872         std::sort(Funcs.begin(), Funcs.end(),
873                   opts::pretty::compareFunctionSymbols);
874         for (const auto &Func : Funcs) {
875           Printer.NewLine();
876           Dumper.start(*Func, FunctionDumper::PointerType::None);
877         }
878       }
879     }
880     if (shouldDumpSymLevel(opts::pretty::SymLevel::Data)) {
881       auto Vars = GlobalScope->findAllChildren<PDBSymbolData>();
882       VariableDumper Dumper(Printer);
883       if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
884         while (auto Var = Vars->getNext())
885           Dumper.start(*Var);
886       } else {
887         std::vector<std::unique_ptr<PDBSymbolData>> Datas;
888         while (auto Var = Vars->getNext())
889           Datas.push_back(std::move(Var));
890         std::sort(Datas.begin(), Datas.end(), opts::pretty::compareDataSymbols);
891         for (const auto &Var : Datas)
892           Dumper.start(*Var);
893       }
894     }
895     if (shouldDumpSymLevel(opts::pretty::SymLevel::Thunks)) {
896       auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>();
897       CompilandDumper Dumper(Printer);
898       while (auto Thunk = Thunks->getNext())
899         Dumper.dump(*Thunk);
900     }
901     Printer.Unindent();
902   }
903   if (opts::pretty::Externals) {
904     Printer.NewLine();
905     WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---";
906     Printer.Indent();
907     ExternalSymbolDumper Dumper(Printer);
908     Dumper.start(*GlobalScope);
909   }
910   if (opts::pretty::Lines) {
911     Printer.NewLine();
912   }
913   outs().flush();
914 }
915
916 static void mergePdbs() {
917   BumpPtrAllocator Allocator;
918   TypeTableBuilder MergedTpi(Allocator);
919   TypeTableBuilder MergedIpi(Allocator);
920
921   // Create a Tpi and Ipi type table with all types from all input files.
922   for (const auto &Path : opts::merge::InputFilenames) {
923     std::unique_ptr<IPDBSession> Session;
924     auto &File = loadPDB(Path, Session);
925     SmallVector<TypeIndex, 128> TypeMap;
926     SmallVector<TypeIndex, 128> IdMap;
927     if (File.hasPDBTpiStream()) {
928       auto &Tpi = ExitOnErr(File.getPDBTpiStream());
929       ExitOnErr(codeview::mergeTypeRecords(MergedTpi, TypeMap, nullptr,
930                                            Tpi.typeArray()));
931     }
932     if (File.hasPDBIpiStream()) {
933       auto &Ipi = ExitOnErr(File.getPDBIpiStream());
934       ExitOnErr(codeview::mergeIdRecords(MergedIpi, TypeMap, IdMap,
935                                          Ipi.typeArray()));
936     }
937   }
938
939   // Then write the PDB.
940   PDBFileBuilder Builder(Allocator);
941   ExitOnErr(Builder.initialize(4096));
942   // Add each of the reserved streams.  We might not put any data in them,
943   // but at least they have to be present.
944   for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
945     ExitOnErr(Builder.getMsfBuilder().addStream(0));
946
947   auto &DestTpi = Builder.getTpiBuilder();
948   auto &DestIpi = Builder.getIpiBuilder();
949   MergedTpi.ForEachRecord([&DestTpi](TypeIndex TI, ArrayRef<uint8_t> Data) {
950     DestTpi.addTypeRecord(Data, None);
951   });
952   MergedIpi.ForEachRecord([&DestIpi](TypeIndex TI, ArrayRef<uint8_t> Data) {
953     DestIpi.addTypeRecord(Data, None);
954   });
955   Builder.getInfoBuilder().addFeature(PdbRaw_FeatureSig::VC140);
956
957   SmallString<64> OutFile(opts::merge::PdbOutputFile);
958   if (OutFile.empty()) {
959     OutFile = opts::merge::InputFilenames[0];
960     llvm::sys::path::replace_extension(OutFile, "merged.pdb");
961   }
962   ExitOnErr(Builder.commit(OutFile));
963 }
964
965 static bool parseRange(StringRef Str,
966                        Optional<opts::bytes::NumberRange> &Parsed) {
967   if (Str.empty())
968     return true;
969
970   llvm::Regex R("^([^-]+)(-([^-]+))?$");
971   llvm::SmallVector<llvm::StringRef, 2> Matches;
972   if (!R.match(Str, &Matches))
973     return false;
974
975   Parsed.emplace();
976   if (!to_integer(Matches[1], Parsed->Min))
977     return false;
978
979   if (!Matches[3].empty()) {
980     Parsed->Max.emplace();
981     if (!to_integer(Matches[3], *Parsed->Max))
982       return false;
983   }
984   return true;
985 }
986
987 static void simplifyChunkList(llvm::cl::list<opts::ModuleSubsection> &Chunks) {
988   // If this list contains "All" plus some other stuff, remove the other stuff
989   // and just keep "All" in the list.
990   if (!llvm::is_contained(Chunks, opts::ModuleSubsection::All))
991     return;
992   Chunks.reset();
993   Chunks.push_back(opts::ModuleSubsection::All);
994 }
995
996 int main(int argc_, const char *argv_[]) {
997   // Print a stack trace if we signal out.
998   sys::PrintStackTraceOnErrorSignal(argv_[0]);
999   PrettyStackTraceProgram X(argc_, argv_);
1000
1001   ExitOnErr.setBanner("llvm-pdbutil: ");
1002
1003   SmallVector<const char *, 256> argv;
1004   SpecificBumpPtrAllocator<char> ArgAllocator;
1005   ExitOnErr(errorCodeToError(sys::Process::GetArgumentVector(
1006       argv, makeArrayRef(argv_, argc_), ArgAllocator)));
1007
1008   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1009
1010   cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");
1011
1012   if (opts::BytesSubcommand) {
1013     if (!parseRange(opts::bytes::DumpBlockRangeOpt,
1014                     opts::bytes::DumpBlockRange)) {
1015       errs() << "Argument '" << opts::bytes::DumpBlockRangeOpt
1016              << "' invalid format.\n";
1017       errs().flush();
1018       exit(1);
1019     }
1020     if (!parseRange(opts::bytes::DumpByteRangeOpt,
1021                     opts::bytes::DumpByteRange)) {
1022       errs() << "Argument '" << opts::bytes::DumpByteRangeOpt
1023              << "' invalid format.\n";
1024       errs().flush();
1025       exit(1);
1026     }
1027   }
1028
1029   if (opts::DumpSubcommand) {
1030     if (opts::dump::RawAll) {
1031       opts::dump::DumpLines = true;
1032       opts::dump::DumpInlineeLines = true;
1033       opts::dump::DumpXme = true;
1034       opts::dump::DumpXmi = true;
1035       opts::dump::DumpIds = true;
1036       opts::dump::DumpPublics = true;
1037       opts::dump::DumpSectionContribs = true;
1038       opts::dump::DumpSectionMap = true;
1039       opts::dump::DumpStreams = true;
1040       opts::dump::DumpStreamBlocks = true;
1041       opts::dump::DumpStringTable = true;
1042       opts::dump::DumpSummary = true;
1043       opts::dump::DumpSymbols = true;
1044       opts::dump::DumpIds = true;
1045       opts::dump::DumpIdExtras = true;
1046       opts::dump::DumpTypes = true;
1047       opts::dump::DumpTypeExtras = true;
1048       opts::dump::DumpModules = true;
1049       opts::dump::DumpModuleFiles = true;
1050     }
1051   }
1052   if (opts::PdbToYamlSubcommand) {
1053     if (opts::pdb2yaml::All) {
1054       opts::pdb2yaml::StreamMetadata = true;
1055       opts::pdb2yaml::StreamDirectory = true;
1056       opts::pdb2yaml::PdbStream = true;
1057       opts::pdb2yaml::StringTable = true;
1058       opts::pdb2yaml::DbiStream = true;
1059       opts::pdb2yaml::TpiStream = true;
1060       opts::pdb2yaml::IpiStream = true;
1061       opts::pdb2yaml::DumpModules = true;
1062       opts::pdb2yaml::DumpModuleFiles = true;
1063       opts::pdb2yaml::DumpModuleSyms = true;
1064       opts::pdb2yaml::DumpModuleSubsections.push_back(
1065           opts::ModuleSubsection::All);
1066     }
1067     simplifyChunkList(opts::pdb2yaml::DumpModuleSubsections);
1068
1069     if (opts::pdb2yaml::DumpModuleSyms || opts::pdb2yaml::DumpModuleFiles)
1070       opts::pdb2yaml::DumpModules = true;
1071
1072     if (opts::pdb2yaml::DumpModules)
1073       opts::pdb2yaml::DbiStream = true;
1074   }
1075
1076   llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);
1077
1078   if (opts::PdbToYamlSubcommand) {
1079     pdb2Yaml(opts::pdb2yaml::InputFilename.front());
1080   } else if (opts::YamlToPdbSubcommand) {
1081     if (opts::yaml2pdb::YamlPdbOutputFile.empty()) {
1082       SmallString<16> OutputFilename(opts::yaml2pdb::InputFilename.getValue());
1083       sys::path::replace_extension(OutputFilename, ".pdb");
1084       opts::yaml2pdb::YamlPdbOutputFile = OutputFilename.str();
1085     }
1086     yamlToPdb(opts::yaml2pdb::InputFilename);
1087   } else if (opts::AnalyzeSubcommand) {
1088     dumpAnalysis(opts::analyze::InputFilename.front());
1089   } else if (opts::PrettySubcommand) {
1090     if (opts::pretty::Lines)
1091       opts::pretty::Compilands = true;
1092
1093     if (opts::pretty::All) {
1094       opts::pretty::Compilands = true;
1095       opts::pretty::Symbols = true;
1096       opts::pretty::Globals = true;
1097       opts::pretty::Types = true;
1098       opts::pretty::Externals = true;
1099       opts::pretty::Lines = true;
1100     }
1101
1102     if (opts::pretty::Types) {
1103       opts::pretty::Classes = true;
1104       opts::pretty::Typedefs = true;
1105       opts::pretty::Enums = true;
1106     }
1107
1108     // When adding filters for excluded compilands and types, we need to
1109     // remember that these are regexes.  So special characters such as * and \
1110     // need to be escaped in the regex.  In the case of a literal \, this means
1111     // it needs to be escaped again in the C++.  So matching a single \ in the
1112     // input requires 4 \es in the C++.
1113     if (opts::pretty::ExcludeCompilerGenerated) {
1114       opts::pretty::ExcludeTypes.push_back("__vc_attributes");
1115       opts::pretty::ExcludeCompilands.push_back("\\* Linker \\*");
1116     }
1117     if (opts::pretty::ExcludeSystemLibraries) {
1118       opts::pretty::ExcludeCompilands.push_back(
1119           "f:\\\\binaries\\\\Intermediate\\\\vctools\\\\crt_bld");
1120       opts::pretty::ExcludeCompilands.push_back("f:\\\\dd\\\\vctools\\\\crt");
1121       opts::pretty::ExcludeCompilands.push_back(
1122           "d:\\\\th.obj.x86fre\\\\minkernel");
1123     }
1124     std::for_each(opts::pretty::InputFilenames.begin(),
1125                   opts::pretty::InputFilenames.end(), dumpPretty);
1126   } else if (opts::DumpSubcommand) {
1127     std::for_each(opts::dump::InputFilenames.begin(),
1128                   opts::dump::InputFilenames.end(), dumpRaw);
1129   } else if (opts::BytesSubcommand) {
1130     std::for_each(opts::bytes::InputFilenames.begin(),
1131                   opts::bytes::InputFilenames.end(), dumpBytes);
1132   } else if (opts::DiffSubcommand) {
1133     if (opts::diff::InputFilenames.size() != 2) {
1134       errs() << "diff subcommand expects exactly 2 arguments.\n";
1135       exit(1);
1136     }
1137     diff(opts::diff::InputFilenames[0], opts::diff::InputFilenames[1]);
1138   } else if (opts::MergeSubcommand) {
1139     if (opts::merge::InputFilenames.size() < 2) {
1140       errs() << "merge subcommand requires at least 2 input files.\n";
1141       exit(1);
1142     }
1143     mergePdbs();
1144   }
1145
1146   outs().flush();
1147   return 0;
1148 }