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