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