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