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(Buffer->getBuffer());
823 for (unsigned CurrentDoc = 1; CurrentDoc < DocNum; ++CurrentDoc) {
824 if (!In.nextDocument())
825 ExitOnErr(createFileError(
826 F: Path, E: createStringErrorV(Fmt: "cannot find the {0}{1} document", Vals&: DocNum,
827 Vals: getOrdinalSuffix(Val: DocNum))));
828 }
829 pdb::yaml::PdbObject YamlObj(Allocator);
830 In >> YamlObj;
831
832 PDBFileBuilder Builder(Allocator);
833
834 uint32_t BlockSize = 4096;
835 if (YamlObj.Headers)
836 BlockSize = YamlObj.Headers->SuperBlock.BlockSize;
837 ExitOnErr(Builder.initialize(BlockSize));
838 // Add each of the reserved streams. We ignore stream metadata in the
839 // yaml, because we will reconstruct our own view of the streams. For
840 // example, the YAML may say that there were 20 streams in the original
841 // PDB, but maybe we only dump a subset of those 20 streams, so we will
842 // have fewer, and the ones we do have may end up with different indices
843 // than the ones in the original PDB. So we just start with a clean slate.
844 for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
845 ExitOnErr(Builder.getMsfBuilder().addStream(Size: 0));
846
847 auto &Dxc = YamlObj.DXContainerStream;
848 if (Dxc) {
849 // If there is a DXContainer, add add it as a stream #5.
850 ExitOnErr(Builder.getMsfBuilder().addStream(Size: 0));
851 }
852
853 pdb::yaml::PdbInfoStream DefaultInfoStream;
854 const auto &Info = YamlObj.PdbStream.value_or(u&: DefaultInfoStream);
855
856 auto &InfoBuilder = Builder.getInfoBuilder();
857 InfoBuilder.setAge(Info.Age);
858 InfoBuilder.setGuid(Info.Guid);
859 InfoBuilder.setSignature(Info.Signature);
860 InfoBuilder.setVersion(Info.Version);
861 for (auto F : Info.Features)
862 InfoBuilder.addFeature(Sig: F);
863
864 if (Dxc) {
865 auto &Data = Builder.getDXContainerData();
866 llvm::raw_svector_ostream DataStream(*Data);
867 std::string ErrorMsg;
868 llvm::yaml::yaml2dxcontainer(
869 Doc&: Dxc->DXC, Out&: DataStream, EH: [&ErrorMsg](const Twine &Msg) {
870 ErrorMsg = (Twine("DXContainer error: ") + Msg).str();
871 });
872 if (!ErrorMsg.empty())
873 ExitOnErr(createStringError(S: ErrorMsg));
874
875 codeview::GUID IgnoredOutGuid;
876 ExitOnErr(
877 Builder.commit(Filename: opts::yaml2pdb::YamlPdbOutputFile, Guid: &IgnoredOutGuid));
878 // Leave all other streams empty if there is a DXContainer.
879 return;
880 }
881
882 StringsAndChecksums Strings;
883 Strings.setStrings(std::make_shared<DebugStringTableSubsection>());
884
885 if (YamlObj.StringTable) {
886 for (auto S : *YamlObj.StringTable)
887 Strings.strings()->insert(S);
888 }
889
890 pdb::yaml::PdbDbiStream DefaultDbiStream;
891 pdb::yaml::PdbTpiStream DefaultTpiStream;
892 pdb::yaml::PdbTpiStream DefaultIpiStream;
893
894 const auto &Dbi = YamlObj.DbiStream.value_or(u&: DefaultDbiStream);
895 auto &DbiBuilder = Builder.getDbiBuilder();
896 DbiBuilder.setAge(Dbi.Age);
897 DbiBuilder.setBuildNumber(Dbi.BuildNumber);
898 DbiBuilder.setFlags(Dbi.Flags);
899 DbiBuilder.setMachineType(Dbi.MachineType);
900 DbiBuilder.setPdbDllRbld(Dbi.PdbDllRbld);
901 DbiBuilder.setPdbDllVersion(Dbi.PdbDllVersion);
902 DbiBuilder.setVersionHeader(Dbi.VerHeader);
903 for (const auto &MI : Dbi.ModInfos) {
904 auto &ModiBuilder = ExitOnErr(DbiBuilder.addModuleInfo(ModuleName: MI.Mod));
905 ModiBuilder.setObjFileName(MI.Obj);
906
907 for (auto S : MI.SourceFiles)
908 ExitOnErr(DbiBuilder.addModuleSourceFile(Module&: ModiBuilder, File: S));
909 if (MI.Modi) {
910 const auto &ModiStream = *MI.Modi;
911 for (const auto &Symbol : ModiStream.Symbols) {
912 ModiBuilder.addSymbol(
913 Symbol: Symbol.toCodeViewSymbol(Allocator, Container: CodeViewContainer::Pdb));
914 }
915 }
916
917 // Each module has its own checksum subsection, so scan for it every time.
918 Strings.setChecksums(nullptr);
919 CodeViewYAML::initializeStringsAndChecksums(Sections: MI.Subsections, SC&: Strings);
920
921 auto CodeViewSubsections = ExitOnErr(CodeViewYAML::toCodeViewSubsectionList(
922 Allocator, Subsections: MI.Subsections, SC: Strings));
923 for (auto &SS : CodeViewSubsections) {
924 ModiBuilder.addDebugSubsection(Subsection: SS);
925 }
926 }
927
928 if (Dbi.SectionContribs) {
929 // DbiStreamBuilder only supports writing Ver60 section contribs.
930 if (Dbi.SectionContribs->Version !=
931 PdbRaw_DbiSecContribVer::DbiSecContribVer60)
932 ExitOnErr(createStringError(
933 Fmt: "Only DBI section contrib Version Ver60 is supported"));
934
935 for (const auto &Contrib : Dbi.SectionContribs->Items) {
936 SectionContrib SC;
937 SC.ISect = Contrib.ISect;
938 SC.Padding[0] = 0;
939 SC.Padding[1] = 0;
940 SC.Off = Contrib.Off;
941 SC.Size = Contrib.Size;
942 SC.Characteristics = Contrib.Characteristics;
943 SC.Imod = Contrib.Imod;
944 SC.Padding2[0] = 0;
945 SC.Padding2[1] = 0;
946 SC.DataCrc = Contrib.DataCrc;
947 SC.RelocCrc = Contrib.RelocCrc;
948 DbiBuilder.addSectionContrib(SC);
949 }
950 }
951
952 std::vector<object::coff_section> Sections;
953 if (!Dbi.SectionHeaders.empty()) {
954 for (const auto &Hdr : Dbi.SectionHeaders)
955 Sections.emplace_back(args: Hdr.toCoffSection());
956
957 DbiBuilder.createSectionMap(SecHdrs: Sections);
958 ExitOnErr(DbiBuilder.addDbgStream(
959 Type: pdb::DbgHeaderType::SectionHdr,
960 // FIXME: Downcasting to an ArrayRef<uint8_t> should use a helper
961 // function in LLVM
962 Data: ArrayRef<uint8_t>{(const uint8_t *)Sections.data(),
963 Sections.size() * sizeof(object::coff_section)}));
964 }
965
966 auto &TpiBuilder = Builder.getTpiBuilder();
967 const auto &Tpi = YamlObj.TpiStream.value_or(u&: DefaultTpiStream);
968 TpiBuilder.setVersionHeader(Tpi.Version);
969 AppendingTypeTableBuilder TS(Allocator);
970 for (const auto &R : Tpi.Records) {
971 CVType Type = R.toCodeViewRecord(Serializer&: TS);
972 uint32_t Hash = ExitOnErr(llvm::pdb::hashTypeRecord(Type));
973 TpiBuilder.addTypeRecord(Type: Type.RecordData, Hash);
974 }
975
976 const auto &Ipi = YamlObj.IpiStream.value_or(u&: DefaultIpiStream);
977 auto &IpiBuilder = Builder.getIpiBuilder();
978 IpiBuilder.setVersionHeader(Ipi.Version);
979 for (const auto &R : Ipi.Records) {
980 CVType Type = R.toCodeViewRecord(Serializer&: TS);
981 uint32_t Hash = ExitOnErr(llvm::pdb::hashTypeRecord(Type));
982 IpiBuilder.addTypeRecord(Type: Type.RecordData, Hash);
983 }
984
985 if (YamlObj.PublicsStream) {
986 auto &GsiBuilder = Builder.getGsiBuilder();
987 std::vector<BulkPublic> BulkPublics;
988 for (const auto &P : YamlObj.PublicsStream->PubSyms) {
989 CVSymbol CV = P.toCodeViewSymbol(Allocator, Container: CodeViewContainer::Pdb);
990 auto PS = cantFail(ValOrErr: SymbolDeserializer::deserializeAs<PublicSym32>(Symbol: CV));
991
992 BulkPublic BP;
993 BP.Name = PS.Name.data();
994 BP.NameLen = PS.Name.size();
995 BP.setFlags(PS.Flags);
996 BP.Offset = PS.Offset;
997 BP.Segment = PS.Segment;
998 BulkPublics.emplace_back(args&: BP);
999 }
1000 GsiBuilder.addPublicSymbols(PublicsIn: std::move(BulkPublics));
1001 }
1002
1003 Builder.getStringTableBuilder().setStrings(*Strings.strings());
1004
1005 codeview::GUID IgnoredOutGuid;
1006 ExitOnErr(Builder.commit(Filename: opts::yaml2pdb::YamlPdbOutputFile, Guid: &IgnoredOutGuid));
1007}
1008
1009static PDBFile &loadPDB(StringRef Path, std::unique_ptr<IPDBSession> &Session) {
1010 ExitOnErr(loadDataForPDB(Type: PDB_ReaderType::Native, Path, Session));
1011
1012 NativeSession *NS = static_cast<NativeSession *>(Session.get());
1013 return NS->getPDBFile();
1014}
1015
1016static void pdb2Yaml(StringRef Path) {
1017 std::unique_ptr<IPDBSession> Session;
1018 auto &File = loadPDB(Path, Session);
1019
1020 auto O = std::make_unique<YAMLOutputStyle>(args&: File);
1021
1022 ExitOnErr(O->dump());
1023}
1024
1025static void dumpRaw(StringRef Path) {
1026 InputFile IF = ExitOnErr(InputFile::open(Path));
1027
1028 auto O = std::make_unique<DumpOutputStyle>(args&: IF);
1029 ExitOnErr(O->dump());
1030}
1031
1032static void dumpBytes(StringRef Path) {
1033 std::unique_ptr<IPDBSession> Session;
1034 auto &File = loadPDB(Path, Session);
1035
1036 auto O = std::make_unique<BytesOutputStyle>(args&: File);
1037
1038 ExitOnErr(O->dump());
1039}
1040
1041bool opts::pretty::shouldDumpSymLevel(SymLevel Search) {
1042 if (SymTypes.empty())
1043 return true;
1044 if (llvm::is_contained(Range&: SymTypes, Element: Search))
1045 return true;
1046 if (llvm::is_contained(Range&: SymTypes, Element: SymLevel::All))
1047 return true;
1048 return false;
1049}
1050
1051uint32_t llvm::pdb::getTypeLength(const PDBSymbolData &Symbol) {
1052 auto SymbolType = Symbol.getType();
1053 const IPDBRawSymbol &RawType = SymbolType->getRawSymbol();
1054
1055 return RawType.getLength();
1056}
1057
1058bool opts::pretty::compareFunctionSymbols(
1059 const std::unique_ptr<PDBSymbolFunc> &F1,
1060 const std::unique_ptr<PDBSymbolFunc> &F2) {
1061 assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
1062
1063 if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
1064 return F1->getName() < F2->getName();
1065
1066 // Note that we intentionally sort in descending order on length, since
1067 // long functions are more interesting than short functions.
1068 return F1->getLength() > F2->getLength();
1069}
1070
1071bool opts::pretty::compareDataSymbols(
1072 const std::unique_ptr<PDBSymbolData> &F1,
1073 const std::unique_ptr<PDBSymbolData> &F2) {
1074 assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);
1075
1076 if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
1077 return F1->getName() < F2->getName();
1078
1079 // Note that we intentionally sort in descending order on length, since
1080 // large types are more interesting than short ones.
1081 return getTypeLength(Symbol: *F1) > getTypeLength(Symbol: *F2);
1082}
1083
1084static std::string stringOr(std::string Str, std::string IfEmpty) {
1085 return (Str.empty()) ? IfEmpty : Str;
1086}
1087
1088static void dumpInjectedSources(LinePrinter &Printer, IPDBSession &Session) {
1089 auto Sources = Session.getInjectedSources();
1090 if (!Sources || !Sources->getChildCount()) {
1091 Printer.printLine(T: "There are no injected sources.");
1092 return;
1093 }
1094
1095 while (auto IS = Sources->getNext()) {
1096 Printer.NewLine();
1097 std::string File = stringOr(Str: IS->getFileName(), IfEmpty: "<null>");
1098 uint64_t Size = IS->getCodeByteSize();
1099 std::string Obj = stringOr(Str: IS->getObjectFileName(), IfEmpty: "<null>");
1100 std::string VFName = stringOr(Str: IS->getVirtualFileName(), IfEmpty: "<null>");
1101 uint32_t CRC = IS->getCrc32();
1102
1103 WithColor(Printer, PDB_ColorItem::Path).get() << File;
1104 Printer << " (";
1105 WithColor(Printer, PDB_ColorItem::LiteralValue).get() << Size;
1106 Printer << " bytes): ";
1107 WithColor(Printer, PDB_ColorItem::Keyword).get() << "obj";
1108 Printer << "=";
1109 WithColor(Printer, PDB_ColorItem::Path).get() << Obj;
1110 Printer << ", ";
1111 WithColor(Printer, PDB_ColorItem::Keyword).get() << "vname";
1112 Printer << "=";
1113 WithColor(Printer, PDB_ColorItem::Path).get() << VFName;
1114 Printer << ", ";
1115 WithColor(Printer, PDB_ColorItem::Keyword).get() << "crc";
1116 Printer << "=";
1117 WithColor(Printer, PDB_ColorItem::LiteralValue).get() << CRC;
1118 Printer << ", ";
1119 WithColor(Printer, PDB_ColorItem::Keyword).get() << "compression";
1120 Printer << "=";
1121 dumpPDBSourceCompression(
1122 OS&: WithColor(Printer, PDB_ColorItem::LiteralValue).get(),
1123 Compression: IS->getCompression());
1124
1125 if (!opts::pretty::ShowInjectedSourceContent)
1126 continue;
1127
1128 // Set the indent level to 0 when printing file content.
1129 int Indent = Printer.getIndentLevel();
1130 Printer.Unindent(Amount: Indent);
1131
1132 if (IS->getCompression() == PDB_SourceCompression::None)
1133 Printer.printLine(T: IS->getCode());
1134 else
1135 Printer.formatBinary(Label: "Compressed data",
1136 Data: arrayRefFromStringRef(Input: IS->getCode()),
1137 /*StartOffset=*/0);
1138
1139 // Re-indent back to the original level.
1140 Printer.Indent(Amount: Indent);
1141 }
1142}
1143
1144template <typename OuterT, typename ChildT>
1145void diaDumpChildren(PDBSymbol &Outer, PdbSymbolIdField Ids,
1146 PdbSymbolIdField Recurse) {
1147 OuterT *ConcreteOuter = dyn_cast<OuterT>(&Outer);
1148 if (!ConcreteOuter)
1149 return;
1150
1151 auto Children = ConcreteOuter->template findAllChildren<ChildT>();
1152 while (auto Child = Children->getNext()) {
1153 outs() << " {";
1154 Child->defaultDump(outs(), 4, Ids, Recurse);
1155 outs() << "\n }\n";
1156 }
1157}
1158
1159static void dumpDia(StringRef Path) {
1160 std::unique_ptr<IPDBSession> Session;
1161
1162 const auto ReaderType =
1163 opts::diadump::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
1164 ExitOnErr(loadDataForPDB(Type: ReaderType, Path, Session));
1165
1166 auto GlobalScope = Session->getGlobalScope();
1167
1168 std::vector<PDB_SymType> SymTypes;
1169
1170 if (opts::diadump::Compilands)
1171 SymTypes.push_back(x: PDB_SymType::Compiland);
1172 if (opts::diadump::Enums)
1173 SymTypes.push_back(x: PDB_SymType::Enum);
1174 if (opts::diadump::Pointers)
1175 SymTypes.push_back(x: PDB_SymType::PointerType);
1176 if (opts::diadump::UDTs)
1177 SymTypes.push_back(x: PDB_SymType::UDT);
1178 if (opts::diadump::Funcsigs)
1179 SymTypes.push_back(x: PDB_SymType::FunctionSig);
1180 if (opts::diadump::Arrays)
1181 SymTypes.push_back(x: PDB_SymType::ArrayType);
1182 if (opts::diadump::VTShapes)
1183 SymTypes.push_back(x: PDB_SymType::VTableShape);
1184 if (opts::diadump::Typedefs)
1185 SymTypes.push_back(x: PDB_SymType::Typedef);
1186 PdbSymbolIdField Ids = opts::diadump::NoSymIndexIds ? PdbSymbolIdField::None
1187 : PdbSymbolIdField::All;
1188
1189 PdbSymbolIdField Recurse = PdbSymbolIdField::None;
1190 if (opts::diadump::Recurse)
1191 Recurse = PdbSymbolIdField::All;
1192 if (!opts::diadump::ShowClassHierarchy)
1193 Ids &= ~(PdbSymbolIdField::ClassParent | PdbSymbolIdField::LexicalParent);
1194
1195 for (PDB_SymType ST : SymTypes) {
1196 auto Children = GlobalScope->findAllChildren(Type: ST);
1197 while (auto Child = Children->getNext()) {
1198 outs() << "{";
1199 Child->defaultDump(OS&: outs(), Indent: 2, ShowFlags: Ids, RecurseFlags: Recurse);
1200
1201 diaDumpChildren<PDBSymbolTypeEnum, PDBSymbolData>(Outer&: *Child, Ids, Recurse);
1202 outs() << "\n}\n";
1203 }
1204 }
1205}
1206
1207static void dumpPretty(StringRef Path) {
1208 std::unique_ptr<IPDBSession> Session;
1209
1210 const auto ReaderType =
1211 opts::pretty::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
1212 ExitOnErr(loadDataForPDB(Type: ReaderType, Path, Session));
1213
1214 if (opts::pretty::LoadAddress)
1215 Session->setLoadAddress(opts::pretty::LoadAddress);
1216
1217 auto &Stream = outs();
1218 const bool UseColor =
1219 opts::pretty::ColorOutput == cl::boolOrDefault::BOU_UNSET
1220 ? Stream.has_colors()
1221 : opts::pretty::ColorOutput == cl::boolOrDefault::BOU_TRUE;
1222 LinePrinter Printer(2, UseColor, Stream, opts::Filters);
1223
1224 auto GlobalScope(Session->getGlobalScope());
1225 if (!GlobalScope)
1226 return;
1227 std::string FileName(GlobalScope->getSymbolsFileName());
1228
1229 WithColor(Printer, PDB_ColorItem::None).get() << "Summary for ";
1230 WithColor(Printer, PDB_ColorItem::Path).get() << FileName;
1231 Printer.Indent();
1232 uint64_t FileSize = 0;
1233
1234 Printer.NewLine();
1235 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size";
1236 if (!sys::fs::file_size(Path: FileName, Result&: FileSize)) {
1237 Printer << ": " << FileSize << " bytes";
1238 } else {
1239 Printer << ": (Unable to obtain file size)";
1240 }
1241
1242 Printer.NewLine();
1243 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid";
1244 Printer << ": " << GlobalScope->getGuid();
1245
1246 Printer.NewLine();
1247 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age";
1248 Printer << ": " << GlobalScope->getAge();
1249
1250 Printer.NewLine();
1251 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes";
1252 Printer << ": ";
1253 if (GlobalScope->hasCTypes())
1254 outs() << "HasCTypes ";
1255 if (GlobalScope->hasPrivateSymbols())
1256 outs() << "HasPrivateSymbols ";
1257 Printer.Unindent();
1258
1259 if (!opts::pretty::WithName.empty()) {
1260 Printer.NewLine();
1261 WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1262 << "---SYMBOLS & TYPES BY NAME---";
1263
1264 for (StringRef Name : opts::pretty::WithName) {
1265 auto Symbols = GlobalScope->findChildren(
1266 Type: PDB_SymType::None, Name, Flags: PDB_NameSearchFlags::NS_CaseSensitive);
1267 if (!Symbols || Symbols->getChildCount() == 0) {
1268 Printer.formatLine(Fmt: "[not found] - {0}", Items&: Name);
1269 continue;
1270 }
1271 Printer.formatLine(Fmt: "[{0} occurrences] - {1}", Items: Symbols->getChildCount(),
1272 Items&: Name);
1273
1274 AutoIndent Indent(Printer);
1275 Printer.NewLine();
1276
1277 while (auto Symbol = Symbols->getNext()) {
1278 switch (Symbol->getSymTag()) {
1279 case PDB_SymType::Typedef: {
1280 TypedefDumper TD(Printer);
1281 std::unique_ptr<PDBSymbolTypeTypedef> T =
1282 llvm::unique_dyn_cast<PDBSymbolTypeTypedef>(Val: std::move(Symbol));
1283 TD.start(Symbol: *T);
1284 break;
1285 }
1286 case PDB_SymType::Enum: {
1287 EnumDumper ED(Printer);
1288 std::unique_ptr<PDBSymbolTypeEnum> E =
1289 llvm::unique_dyn_cast<PDBSymbolTypeEnum>(Val: std::move(Symbol));
1290 ED.start(Symbol: *E);
1291 break;
1292 }
1293 case PDB_SymType::UDT: {
1294 ClassDefinitionDumper CD(Printer);
1295 std::unique_ptr<PDBSymbolTypeUDT> C =
1296 llvm::unique_dyn_cast<PDBSymbolTypeUDT>(Val: std::move(Symbol));
1297 CD.start(Class: *C);
1298 break;
1299 }
1300 case PDB_SymType::BaseClass:
1301 case PDB_SymType::Friend: {
1302 TypeDumper TD(Printer);
1303 Symbol->dump(Dumper&: TD);
1304 break;
1305 }
1306 case PDB_SymType::Function: {
1307 FunctionDumper FD(Printer);
1308 std::unique_ptr<PDBSymbolFunc> F =
1309 llvm::unique_dyn_cast<PDBSymbolFunc>(Val: std::move(Symbol));
1310 FD.start(Symbol: *F, Pointer: FunctionDumper::PointerType::None);
1311 break;
1312 }
1313 case PDB_SymType::Data: {
1314 VariableDumper VD(Printer);
1315 std::unique_ptr<PDBSymbolData> D =
1316 llvm::unique_dyn_cast<PDBSymbolData>(Val: std::move(Symbol));
1317 VD.start(Var: *D);
1318 break;
1319 }
1320 case PDB_SymType::PublicSymbol: {
1321 ExternalSymbolDumper ED(Printer);
1322 std::unique_ptr<PDBSymbolPublicSymbol> PS =
1323 llvm::unique_dyn_cast<PDBSymbolPublicSymbol>(Val: std::move(Symbol));
1324 ED.dump(Symbol: *PS);
1325 break;
1326 }
1327 default:
1328 llvm_unreachable("Unexpected symbol tag!");
1329 }
1330 }
1331 }
1332 llvm::outs().flush();
1333 }
1334
1335 if (opts::pretty::Compilands) {
1336 Printer.NewLine();
1337 WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1338 << "---COMPILANDS---";
1339 auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
1340
1341 if (Compilands) {
1342 Printer.Indent();
1343 CompilandDumper Dumper(Printer);
1344 CompilandDumpFlags options = CompilandDumper::Flags::None;
1345 if (opts::pretty::Lines)
1346 options = options | CompilandDumper::Flags::Lines;
1347 while (auto Compiland = Compilands->getNext())
1348 Dumper.start(Symbol: *Compiland, flags: options);
1349 Printer.Unindent();
1350 }
1351 }
1352
1353 if (opts::pretty::Classes || opts::pretty::Enums || opts::pretty::Typedefs ||
1354 opts::pretty::Funcsigs || opts::pretty::Pointers ||
1355 opts::pretty::Arrays || opts::pretty::VTShapes) {
1356 Printer.NewLine();
1357 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---";
1358 Printer.Indent();
1359 TypeDumper Dumper(Printer);
1360 Dumper.start(Exe: *GlobalScope);
1361 Printer.Unindent();
1362 }
1363
1364 if (opts::pretty::Symbols) {
1365 Printer.NewLine();
1366 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---";
1367 if (auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>()) {
1368 Printer.Indent();
1369 CompilandDumper Dumper(Printer);
1370 while (auto Compiland = Compilands->getNext())
1371 Dumper.start(Symbol: *Compiland, flags: true);
1372 Printer.Unindent();
1373 }
1374 }
1375
1376 if (opts::pretty::Globals) {
1377 Printer.NewLine();
1378 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---";
1379 Printer.Indent();
1380 if (shouldDumpSymLevel(Search: opts::pretty::SymLevel::Functions)) {
1381 if (auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>()) {
1382 FunctionDumper Dumper(Printer);
1383 if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
1384 while (auto Function = Functions->getNext()) {
1385 Printer.NewLine();
1386 Dumper.start(Symbol: *Function, Pointer: FunctionDumper::PointerType::None);
1387 }
1388 } else {
1389 std::vector<std::unique_ptr<PDBSymbolFunc>> Funcs;
1390 while (auto Func = Functions->getNext())
1391 Funcs.push_back(x: std::move(Func));
1392 llvm::sort(C&: Funcs, Comp: opts::pretty::compareFunctionSymbols);
1393 for (const auto &Func : Funcs) {
1394 Printer.NewLine();
1395 Dumper.start(Symbol: *Func, Pointer: FunctionDumper::PointerType::None);
1396 }
1397 }
1398 }
1399 }
1400 if (shouldDumpSymLevel(Search: opts::pretty::SymLevel::Data)) {
1401 if (auto Vars = GlobalScope->findAllChildren<PDBSymbolData>()) {
1402 VariableDumper Dumper(Printer);
1403 if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
1404 while (auto Var = Vars->getNext())
1405 Dumper.start(Var: *Var);
1406 } else {
1407 std::vector<std::unique_ptr<PDBSymbolData>> Datas;
1408 while (auto Var = Vars->getNext())
1409 Datas.push_back(x: std::move(Var));
1410 llvm::sort(C&: Datas, Comp: opts::pretty::compareDataSymbols);
1411 for (const auto &Var : Datas)
1412 Dumper.start(Var: *Var);
1413 }
1414 }
1415 }
1416 if (shouldDumpSymLevel(Search: opts::pretty::SymLevel::Thunks)) {
1417 if (auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>()) {
1418 CompilandDumper Dumper(Printer);
1419 while (auto Thunk = Thunks->getNext())
1420 Dumper.dump(Symbol: *Thunk);
1421 }
1422 }
1423 Printer.Unindent();
1424 }
1425 if (opts::pretty::Externals) {
1426 Printer.NewLine();
1427 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---";
1428 Printer.Indent();
1429 ExternalSymbolDumper Dumper(Printer);
1430 Dumper.start(Symbol: *GlobalScope);
1431 }
1432 if (opts::pretty::Lines) {
1433 Printer.NewLine();
1434 }
1435 if (opts::pretty::InjectedSources) {
1436 Printer.NewLine();
1437 WithColor(Printer, PDB_ColorItem::SectionHeader).get()
1438 << "---INJECTED SOURCES---";
1439 AutoIndent Indent1(Printer);
1440 dumpInjectedSources(Printer, Session&: *Session);
1441 }
1442
1443 Printer.NewLine();
1444 outs().flush();
1445}
1446
1447static void mergePdbs() {
1448 BumpPtrAllocator Allocator;
1449 MergingTypeTableBuilder MergedTpi(Allocator);
1450 MergingTypeTableBuilder MergedIpi(Allocator);
1451
1452 // Create a Tpi and Ipi type table with all types from all input files.
1453 for (const auto &Path : opts::merge::InputFilenames) {
1454 std::unique_ptr<IPDBSession> Session;
1455 auto &File = loadPDB(Path, Session);
1456 SmallVector<TypeIndex, 128> TypeMap;
1457 SmallVector<TypeIndex, 128> IdMap;
1458 if (File.hasPDBTpiStream()) {
1459 auto &Tpi = ExitOnErr(File.getPDBTpiStream());
1460 ExitOnErr(
1461 codeview::mergeTypeRecords(Dest&: MergedTpi, SourceToDest&: TypeMap, Types: Tpi.typeArray()));
1462 }
1463 if (File.hasPDBIpiStream()) {
1464 auto &Ipi = ExitOnErr(File.getPDBIpiStream());
1465 ExitOnErr(codeview::mergeIdRecords(Dest&: MergedIpi, Types: TypeMap, SourceToDest&: IdMap,
1466 Ids: Ipi.typeArray()));
1467 }
1468 }
1469
1470 // Then write the PDB.
1471 PDBFileBuilder Builder(Allocator);
1472 ExitOnErr(Builder.initialize(BlockSize: 4096));
1473 // Add each of the reserved streams. We might not put any data in them,
1474 // but at least they have to be present.
1475 for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
1476 ExitOnErr(Builder.getMsfBuilder().addStream(Size: 0));
1477
1478 auto &DestTpi = Builder.getTpiBuilder();
1479 auto &DestIpi = Builder.getIpiBuilder();
1480 MergedTpi.ForEachRecord(Func: [&DestTpi](TypeIndex TI, const CVType &Type) {
1481 uint32_t Hash = ExitOnErr(llvm::pdb::hashTypeRecord(Type));
1482 DestTpi.addTypeRecord(Type: Type.RecordData, Hash);
1483 });
1484 MergedIpi.ForEachRecord(Func: [&DestIpi](TypeIndex TI, const CVType &Type) {
1485 uint32_t Hash = ExitOnErr(llvm::pdb::hashTypeRecord(Type));
1486 DestIpi.addTypeRecord(Type: Type.RecordData, Hash);
1487 });
1488 Builder.getInfoBuilder().addFeature(Sig: PdbRaw_FeatureSig::VC140);
1489
1490 SmallString<64> OutFile(opts::merge::PdbOutputFile);
1491 if (OutFile.empty()) {
1492 OutFile = opts::merge::InputFilenames[0];
1493 llvm::sys::path::replace_extension(path&: OutFile, extension: "merged.pdb");
1494 }
1495
1496 codeview::GUID IgnoredOutGuid;
1497 ExitOnErr(Builder.commit(Filename: OutFile, Guid: &IgnoredOutGuid));
1498}
1499
1500static void explain() {
1501 InputFile IF =
1502 ExitOnErr(InputFile::open(Path: opts::explain::InputFilename.front(), AllowUnknownFile: true));
1503
1504 for (uint64_t Off : opts::explain::Offsets) {
1505 auto O = std::make_unique<ExplainOutputStyle>(args&: IF, args&: Off);
1506
1507 ExitOnErr(O->dump());
1508 }
1509}
1510
1511static void exportStream() {
1512 std::unique_ptr<IPDBSession> Session;
1513 PDBFile &File = loadPDB(Path: opts::exportstream::InputFilename.front(), Session);
1514
1515 std::unique_ptr<MappedBlockStream> SourceStream;
1516 uint32_t Index = 0;
1517 bool Success = false;
1518 std::string OutFileName = opts::exportstream::OutputFile;
1519
1520 if (opts::exportstream::DXContainer) {
1521 auto Dxc = File.getDXContainerStream();
1522 if (!Dxc) {
1523 errs() << "Error: DirectX Container is not present.\n";
1524 exit(status: 1);
1525 }
1526 if (!opts::exportstream::Stream.empty()) {
1527 outs() << "Note: option --" << opts::exportstream::Stream.ArgStr
1528 << " was ignored.\n";
1529 }
1530 Index = StreamDXContainer;
1531 outs() << "Dumping contents of DirectX Container stream (index " << Index
1532 << ") to file " << OutFileName << ".\n";
1533 } else {
1534 if (opts::exportstream::Stream.empty()) {
1535 errs() << "llvm-pdbutil: either --" << opts::exportstream::Stream.ArgStr
1536 << " or --" << opts::exportstream::DXContainer.ArgStr
1537 << " must be specified!\n";
1538 exit(status: 1);
1539 }
1540 if (!opts::exportstream::ForceName) {
1541 // First try to parse it as an integer, if it fails fall back to treating
1542 // it as a named stream.
1543 if (to_integer(S: opts::exportstream::Stream, Num&: Index)) {
1544 if (Index >= File.getNumStreams()) {
1545 errs() << "Error: " << Index << " is not a valid stream index.\n";
1546 exit(status: 1);
1547 }
1548 Success = true;
1549 outs() << "Dumping contents of stream index " << Index << " to file "
1550 << OutFileName << ".\n";
1551 }
1552 }
1553
1554 if (!Success) {
1555 InfoStream &IS = cantFail(ValOrErr: File.getPDBInfoStream());
1556 Index = ExitOnErr(IS.getNamedStreamIndex(Name: opts::exportstream::Stream));
1557 outs() << "Dumping contents of stream '" << opts::exportstream::Stream
1558 << "' (index " << Index << ") to file " << OutFileName << ".\n";
1559 }
1560 }
1561
1562 SourceStream = File.createIndexedStream(SN: Index);
1563 auto OutFile = ExitOnErr(
1564 FileOutputBuffer::create(FilePath: OutFileName, Size: SourceStream->getLength()));
1565 FileBufferByteStream DestStream(std::move(OutFile), llvm::endianness::little);
1566 BinaryStreamWriter Writer(DestStream);
1567 ExitOnErr(Writer.writeStreamRef(Ref: *SourceStream));
1568 ExitOnErr(DestStream.commit());
1569}
1570
1571static bool parseRange(StringRef Str,
1572 std::optional<opts::bytes::NumberRange> &Parsed) {
1573 if (Str.empty())
1574 return true;
1575
1576 llvm::Regex R("^([^-]+)(-([^-]+))?$");
1577 llvm::SmallVector<llvm::StringRef, 2> Matches;
1578 if (!R.match(String: Str, Matches: &Matches))
1579 return false;
1580
1581 Parsed.emplace();
1582 if (!to_integer(S: Matches[1], Num&: Parsed->Min))
1583 return false;
1584
1585 if (!Matches[3].empty()) {
1586 Parsed->Max.emplace();
1587 if (!to_integer(S: Matches[3], Num&: *Parsed->Max))
1588 return false;
1589 }
1590 return true;
1591}
1592
1593static void simplifyChunkList(llvm::cl::list<opts::ModuleSubsection> &Chunks) {
1594 // If this list contains "All" plus some other stuff, remove the other stuff
1595 // and just keep "All" in the list.
1596 if (!llvm::is_contained(Range&: Chunks, Element: opts::ModuleSubsection::All))
1597 return;
1598 Chunks.reset();
1599 Chunks.push_back(value: opts::ModuleSubsection::All);
1600}
1601
1602int main(int Argc, const char **Argv) {
1603 InitLLVM X(Argc, Argv);
1604 ExitOnErr.setBanner("llvm-pdbutil: ");
1605
1606 cl::HideUnrelatedOptions(
1607 Categories: {&opts::TypeCategory, &opts::FilterCategory, &opts::OtherOptions});
1608 cl::ParseCommandLineOptions(argc: Argc, argv: Argv, Overview: "LLVM PDB Dumper\n");
1609
1610 if (opts::BytesSubcommand) {
1611 if (!parseRange(Str: opts::bytes::DumpBlockRangeOpt,
1612 Parsed&: opts::bytes::DumpBlockRange)) {
1613 errs() << "Argument '" << opts::bytes::DumpBlockRangeOpt
1614 << "' invalid format.\n";
1615 errs().flush();
1616 exit(status: 1);
1617 }
1618 if (!parseRange(Str: opts::bytes::DumpByteRangeOpt,
1619 Parsed&: opts::bytes::DumpByteRange)) {
1620 errs() << "Argument '" << opts::bytes::DumpByteRangeOpt
1621 << "' invalid format.\n";
1622 errs().flush();
1623 exit(status: 1);
1624 }
1625 }
1626
1627 if (opts::DumpSubcommand) {
1628 if (opts::dump::RawAll) {
1629 opts::dump::DumpDXContainer = true;
1630 opts::dump::DumpGlobals = true;
1631 opts::dump::DumpFpo = true;
1632 opts::dump::DumpInlineeLines = true;
1633 opts::dump::DumpIds = true;
1634 opts::dump::DumpIdExtras = true;
1635 opts::dump::DumpLines = true;
1636 opts::dump::DumpModules = true;
1637 opts::dump::DumpModuleFiles = true;
1638 opts::dump::DumpPublics = true;
1639 opts::dump::DumpSectionContribs = true;
1640 opts::dump::DumpSectionHeaders = true;
1641 opts::dump::DumpSectionMap = true;
1642 opts::dump::DumpStreams = true;
1643 opts::dump::DumpStreamBlocks = true;
1644 opts::dump::DumpStringTable = true;
1645 opts::dump::DumpStringTableDetails = true;
1646 opts::dump::DumpSummary = true;
1647 opts::dump::DumpSymbols = true;
1648 opts::dump::DumpSymbolStats = true;
1649 opts::dump::DumpTypes = true;
1650 opts::dump::DumpTypeExtras = true;
1651 opts::dump::DumpUdtStats = true;
1652 opts::dump::DumpXme = true;
1653 opts::dump::DumpXmi = true;
1654 }
1655 }
1656 if (opts::PdbToYamlSubcommand) {
1657 if (opts::pdb2yaml::All) {
1658 opts::pdb2yaml::StreamMetadata = true;
1659 opts::pdb2yaml::StreamDirectory = true;
1660 opts::pdb2yaml::PdbStream = true;
1661 opts::pdb2yaml::StringTable = true;
1662 opts::pdb2yaml::DbiStream = true;
1663 opts::pdb2yaml::TpiStream = true;
1664 opts::pdb2yaml::IpiStream = true;
1665 opts::pdb2yaml::DXContainerStream = true;
1666 opts::pdb2yaml::PublicsStream = true;
1667 opts::pdb2yaml::DumpModules = true;
1668 opts::pdb2yaml::DumpModuleFiles = true;
1669 opts::pdb2yaml::DumpModuleSyms = true;
1670 opts::pdb2yaml::DumpSectionHeaders = true;
1671 opts::pdb2yaml::DumpSectionContribs = true;
1672 opts::pdb2yaml::DumpModuleSubsections.push_back(
1673 value: opts::ModuleSubsection::All);
1674 }
1675 simplifyChunkList(Chunks&: opts::pdb2yaml::DumpModuleSubsections);
1676
1677 if (opts::pdb2yaml::DumpModuleSyms || opts::pdb2yaml::DumpModuleFiles)
1678 opts::pdb2yaml::DumpModules = true;
1679
1680 if (opts::pdb2yaml::DumpModules || opts::pdb2yaml::DumpSectionHeaders ||
1681 opts::pdb2yaml::DumpSectionContribs)
1682 opts::pdb2yaml::DbiStream = true;
1683 }
1684
1685 llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);
1686
1687 // Initialize the filters for LinePrinter.
1688 auto propagate = [&](auto &Target, auto &Reference) {
1689 llvm::append_range(Target, Reference);
1690 };
1691
1692 propagate(opts::Filters.ExcludeTypes, opts::pretty::ExcludeTypes);
1693 propagate(opts::Filters.ExcludeTypes, opts::pretty::ExcludeTypes);
1694 propagate(opts::Filters.ExcludeSymbols, opts::pretty::ExcludeSymbols);
1695 propagate(opts::Filters.ExcludeCompilands, opts::pretty::ExcludeCompilands);
1696 propagate(opts::Filters.IncludeTypes, opts::pretty::IncludeTypes);
1697 propagate(opts::Filters.IncludeSymbols, opts::pretty::IncludeSymbols);
1698 propagate(opts::Filters.IncludeCompilands, opts::pretty::IncludeCompilands);
1699 opts::Filters.PaddingThreshold = opts::pretty::PaddingThreshold;
1700 opts::Filters.SizeThreshold = opts::pretty::SizeThreshold;
1701 opts::Filters.JustMyCode = opts::dump::JustMyCode;
1702 if (opts::dump::DumpModi.getNumOccurrences() > 0) {
1703 if (opts::dump::DumpModi.getNumOccurrences() != 1) {
1704 errs() << "argument '-modi' specified more than once.\n";
1705 errs().flush();
1706 exit(status: 1);
1707 }
1708 opts::Filters.DumpModi = opts::dump::DumpModi;
1709 }
1710 if (opts::dump::DumpSymbolOffset) {
1711 if (opts::dump::DumpModi.getNumOccurrences() != 1) {
1712 errs()
1713 << "need to specify argument '-modi' when using '-symbol-offset'.\n";
1714 errs().flush();
1715 exit(status: 1);
1716 }
1717 opts::Filters.SymbolOffset = opts::dump::DumpSymbolOffset;
1718 if (opts::dump::DumpParents)
1719 opts::Filters.ParentRecurseDepth = opts::dump::DumpParentDepth;
1720 if (opts::dump::DumpChildren)
1721 opts::Filters.ChildrenRecurseDepth = opts::dump::DumpChildrenDepth;
1722 }
1723
1724 if (opts::PdbToYamlSubcommand) {
1725 pdb2Yaml(Path: opts::pdb2yaml::InputFilename.front());
1726 } else if (opts::YamlToPdbSubcommand) {
1727 if (opts::yaml2pdb::YamlPdbOutputFile.empty()) {
1728 SmallString<16> OutputFilename(opts::yaml2pdb::InputFilename.getValue());
1729 sys::path::replace_extension(path&: OutputFilename, extension: ".pdb");
1730 opts::yaml2pdb::YamlPdbOutputFile = std::string(OutputFilename);
1731 }
1732 yamlToPdb(Path: opts::yaml2pdb::InputFilename, DocNum: opts::yaml2pdb::DocNum);
1733 } else if (opts::DiaDumpSubcommand) {
1734 llvm::for_each(Range&: opts::diadump::InputFilenames, F: dumpDia);
1735 } else if (opts::PrettySubcommand) {
1736 if (opts::pretty::Lines)
1737 opts::pretty::Compilands = true;
1738
1739 if (opts::pretty::All) {
1740 opts::pretty::Compilands = true;
1741 opts::pretty::Symbols = true;
1742 opts::pretty::Globals = true;
1743 opts::pretty::Types = true;
1744 opts::pretty::Externals = true;
1745 opts::pretty::Lines = true;
1746 }
1747
1748 if (opts::pretty::Types) {
1749 opts::pretty::Classes = true;
1750 opts::pretty::Typedefs = true;
1751 opts::pretty::Enums = true;
1752 opts::pretty::Pointers = true;
1753 opts::pretty::Funcsigs = true;
1754 }
1755
1756 // When adding filters for excluded compilands and types, we need to
1757 // remember that these are regexes. So special characters such as * and \
1758 // need to be escaped in the regex. In the case of a literal \, this means
1759 // it needs to be escaped again in the C++. So matching a single \ in the
1760 // input requires 4 \es in the C++.
1761 if (opts::pretty::ExcludeCompilerGenerated) {
1762 opts::Filters.ExcludeTypes.push_back(x: "__vc_attributes");
1763 opts::Filters.ExcludeCompilands.push_back(x: "\\* Linker \\*");
1764 }
1765 if (opts::pretty::ExcludeSystemLibraries) {
1766 opts::Filters.ExcludeCompilands.push_back(
1767 x: "f:\\\\binaries\\\\Intermediate\\\\vctools\\\\crt_bld");
1768 opts::Filters.ExcludeCompilands.push_back(x: "f:\\\\dd\\\\vctools\\\\crt");
1769 opts::Filters.ExcludeCompilands.push_back(
1770 x: "d:\\\\th.obj.x86fre\\\\minkernel");
1771 }
1772 llvm::for_each(Range&: opts::pretty::InputFilenames, F: dumpPretty);
1773 } else if (opts::DumpSubcommand) {
1774 llvm::for_each(Range&: opts::dump::InputFilenames, F: dumpRaw);
1775 } else if (opts::BytesSubcommand) {
1776 llvm::for_each(Range&: opts::bytes::InputFilenames, F: dumpBytes);
1777 } else if (opts::MergeSubcommand) {
1778 if (opts::merge::InputFilenames.size() < 2) {
1779 errs() << "merge subcommand requires at least 2 input files.\n";
1780 exit(status: 1);
1781 }
1782 mergePdbs();
1783 } else if (opts::ExplainSubcommand) {
1784 explain();
1785 } else if (opts::ExportSubcommand) {
1786 exportStream();
1787 }
1788
1789 outs().flush();
1790 return 0;
1791}
1792