1 //===- llvm-pdbdump.cpp - Dump debug info from a PDB file -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Dumps debug information present in PDB files. This utility makes use of
11 // the Microsoft Windows SDK, so will not compile or run on non-Windows
14 //===----------------------------------------------------------------------===//
16 #include "llvm-pdbdump.h"
17 #include "CompilandDumper.h"
18 #include "ExternalSymbolDumper.h"
19 #include "FunctionDumper.h"
20 #include "LinePrinter.h"
21 #include "TypeDumper.h"
22 #include "VariableDumper.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Config/config.h"
29 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
30 #include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
31 #include "llvm/DebugInfo/PDB/IPDBSession.h"
32 #include "llvm/DebugInfo/PDB/PDB.h"
33 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
34 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
35 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
36 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/PrettyStackTrace.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Support/Signals.h"
49 #if defined(HAVE_DIA_SDK)
57 enum class PDB_DumpType { ByType, ByObjFile, Both };
59 cl::list<std::string> InputFilenames(cl::Positional,
60 cl::desc("<input PDB files>"),
63 cl::OptionCategory TypeCategory("Symbol Type Options");
64 cl::OptionCategory FilterCategory("Filtering Options");
65 cl::OptionCategory OtherOptions("Other Options");
67 cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"),
68 cl::cat(TypeCategory));
69 cl::opt<bool> Symbols("symbols", cl::desc("Display symbols for each compiland"),
70 cl::cat(TypeCategory));
71 cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"),
72 cl::cat(TypeCategory));
73 cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"),
74 cl::cat(TypeCategory));
75 cl::opt<bool> Types("types", cl::desc("Display types"), cl::cat(TypeCategory));
77 All("all", cl::desc("Implies all other options in 'Symbol Types' category"),
78 cl::cat(TypeCategory));
80 cl::opt<uint64_t> LoadAddress(
82 cl::desc("Assume the module is loaded at the specified address"),
83 cl::cat(OtherOptions));
85 cl::opt<bool> DumpHeaders("dump-headers", cl::desc("dump PDB headers"),
86 cl::cat(OtherOptions));
87 cl::opt<bool> DumpStreamSizes("dump-stream-sizes",
88 cl::desc("dump PDB stream sizes"),
89 cl::cat(OtherOptions));
90 cl::opt<bool> DumpStreamBlocks("dump-stream-blocks",
91 cl::desc("dump PDB stream blocks"),
92 cl::cat(OtherOptions));
93 cl::opt<std::string> DumpStreamData("dump-stream", cl::desc("dump stream data"),
94 cl::cat(OtherOptions));
97 ExcludeTypes("exclude-types",
98 cl::desc("Exclude types by regular expression"),
99 cl::ZeroOrMore, cl::cat(FilterCategory));
100 cl::list<std::string>
101 ExcludeSymbols("exclude-symbols",
102 cl::desc("Exclude symbols by regular expression"),
103 cl::ZeroOrMore, cl::cat(FilterCategory));
104 cl::list<std::string>
105 ExcludeCompilands("exclude-compilands",
106 cl::desc("Exclude compilands by regular expression"),
107 cl::ZeroOrMore, cl::cat(FilterCategory));
109 cl::list<std::string> IncludeTypes(
111 cl::desc("Include only types which match a regular expression"),
112 cl::ZeroOrMore, cl::cat(FilterCategory));
113 cl::list<std::string> IncludeSymbols(
115 cl::desc("Include only symbols which match a regular expression"),
116 cl::ZeroOrMore, cl::cat(FilterCategory));
117 cl::list<std::string> IncludeCompilands(
118 "include-compilands",
119 cl::desc("Include only compilands those which match a regular expression"),
120 cl::ZeroOrMore, cl::cat(FilterCategory));
122 cl::opt<bool> ExcludeCompilerGenerated(
123 "no-compiler-generated",
124 cl::desc("Don't show compiler generated types and symbols"),
125 cl::cat(FilterCategory));
127 ExcludeSystemLibraries("no-system-libs",
128 cl::desc("Don't show symbols from system libraries"),
129 cl::cat(FilterCategory));
130 cl::opt<bool> NoClassDefs("no-class-definitions",
131 cl::desc("Don't display full class definitions"),
132 cl::cat(FilterCategory));
133 cl::opt<bool> NoEnumDefs("no-enum-definitions",
134 cl::desc("Don't display full enum definitions"),
135 cl::cat(FilterCategory));
139 static void reportError(StringRef Input, StringRef Message) {
142 errs() << Input << ": " << Message << "\n";
147 static void reportError(StringRef Input, std::error_code EC) {
148 reportError(Input, EC.message());
151 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
152 const uint64_t Size) {
153 if (Addr + Size < Addr || Addr + Size < Size ||
154 Addr + Size > uintptr_t(M.getBufferEnd()) ||
155 Addr < uintptr_t(M.getBufferStart())) {
156 return std::make_error_code(std::errc::bad_address);
158 return std::error_code();
161 template <typename T>
162 static std::error_code checkOffset(MemoryBufferRef M, ArrayRef<T> AR) {
163 return checkOffset(M, uintptr_t(AR.data()), (uint64_t)AR.size() * sizeof(T));
166 static std::error_code checkOffset(MemoryBufferRef M, StringRef SR) {
167 return checkOffset(M, uintptr_t(SR.data()), SR.size());
170 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
171 // Returns unexpected_eof if error.
172 template <typename T>
173 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
175 const uint64_t Size = sizeof(T)) {
176 uintptr_t Addr = uintptr_t(Ptr);
177 if (std::error_code EC = checkOffset(M, Addr, Size))
179 Obj = reinterpret_cast<const T *>(Addr);
180 return std::error_code();
183 static uint64_t bytesToBlocks(uint64_t NumBytes, uint64_t BlockSize) {
184 return RoundUpToAlignment(NumBytes, BlockSize) / BlockSize;
187 static uint64_t blockToOffset(uint64_t BlockNumber, uint64_t BlockSize) {
188 return BlockNumber * BlockSize;
191 static void dumpStructure(MemoryBufferRef M) {
192 const PDB::SuperBlock *SB;
193 if (auto EC = getObject(SB, M, M.getBufferStart()))
194 reportError(M.getBufferIdentifier(), EC);
196 if (opts::DumpHeaders) {
197 outs() << "BlockSize: " << SB->BlockSize << '\n';
198 outs() << "Unknown0: " << SB->Unknown0 << '\n';
199 outs() << "NumBlocks: " << SB->NumBlocks << '\n';
200 outs() << "NumDirectoryBytes: " << SB->NumDirectoryBytes << '\n';
201 outs() << "Unknown1: " << SB->Unknown1 << '\n';
202 outs() << "BlockMapAddr: " << SB->BlockMapAddr << '\n';
205 // We don't support blocksizes which aren't a multiple of four bytes.
206 if (SB->BlockSize % sizeof(support::ulittle32_t) != 0)
207 reportError(M.getBufferIdentifier(),
208 std::make_error_code(std::errc::illegal_byte_sequence));
210 // We don't support directories whose sizes aren't a multiple of four bytes.
211 if (SB->NumDirectoryBytes % sizeof(support::ulittle32_t) != 0)
212 reportError(M.getBufferIdentifier(),
213 std::make_error_code(std::errc::illegal_byte_sequence));
215 // The number of blocks which comprise the directory is a simple function of
216 // the number of bytes it contains.
217 uint64_t NumDirectoryBlocks =
218 bytesToBlocks(SB->NumDirectoryBytes, SB->BlockSize);
219 if (opts::DumpHeaders)
220 outs() << "NumDirectoryBlocks: " << NumDirectoryBlocks << '\n';
222 // The block map, as we understand it, is a block which consists of a list of
224 // It is unclear what would happen if the number of blocks couldn't fit on a
226 if (NumDirectoryBlocks > SB->BlockSize / sizeof(support::ulittle32_t))
227 reportError(M.getBufferIdentifier(),
228 std::make_error_code(std::errc::illegal_byte_sequence));
231 uint64_t BlockMapOffset = (uint64_t)SB->BlockMapAddr * SB->BlockSize;
232 if (opts::DumpHeaders)
233 outs() << "BlockMapOffset: " << BlockMapOffset << '\n';
235 // The directory is not contiguous. Instead, the block map contains a
236 // contiguous list of block numbers whose contents, when concatenated in
237 // order, make up the directory.
238 auto DirectoryBlocks =
239 makeArrayRef(reinterpret_cast<const support::ulittle32_t *>(
240 M.getBufferStart() + BlockMapOffset),
242 if (auto EC = checkOffset(M, DirectoryBlocks))
243 reportError(M.getBufferIdentifier(), EC);
245 if (opts::DumpHeaders) {
246 outs() << "DirectoryBlocks: [";
247 for (const support::ulittle32_t &DirectoryBlockAddr : DirectoryBlocks) {
248 if (&DirectoryBlockAddr != &DirectoryBlocks.front())
250 outs() << DirectoryBlockAddr;
255 bool SeenNumStreams = false;
256 uint32_t NumStreams = 0;
257 std::vector<uint32_t> StreamSizes;
258 DenseMap<uint32_t, std::vector<uint32_t>> StreamMap;
259 uint32_t StreamIdx = 0;
260 uint64_t DirectoryBytesRead = 0;
261 // The structure of the directory is as follows:
262 // struct PDBDirectory {
263 // uint32_t NumStreams;
264 // uint32_t StreamSizes[NumStreams];
265 // uint32_t StreamMap[NumStreams][];
268 // Empty streams don't consume entries in the StreamMap.
269 for (uint32_t DirectoryBlockAddr : DirectoryBlocks) {
270 uint64_t DirectoryBlockOffset =
271 blockToOffset(DirectoryBlockAddr, SB->BlockSize);
272 auto DirectoryBlock =
273 makeArrayRef(reinterpret_cast<const support::ulittle32_t *>(
274 M.getBufferStart() + DirectoryBlockOffset),
275 SB->BlockSize / sizeof(support::ulittle32_t));
276 if (auto EC = checkOffset(M, DirectoryBlock))
277 reportError(M.getBufferIdentifier(), EC);
279 // We read data out of the directory four bytes at a time. Depending on
280 // where we are in the directory, the contents may be: the number of streams
281 // in the directory, a stream's size, or a block in the stream map.
282 for (uint32_t Data : DirectoryBlock) {
283 // Don't read beyond the end of the directory.
284 if (DirectoryBytesRead == SB->NumDirectoryBytes)
287 DirectoryBytesRead += sizeof(Data);
289 // This data must be the number of streams if we haven't seen it yet.
290 if (!SeenNumStreams) {
292 SeenNumStreams = true;
295 // This data must be a stream size if we have not seen them all yet.
296 if (StreamSizes.size() < NumStreams) {
297 // It seems like some streams have their set to -1 when their contents
298 // are not present. Treat them like empty streams for now.
299 if (Data == UINT32_MAX)
300 StreamSizes.push_back(0);
302 StreamSizes.push_back(Data);
306 // This data must be a stream block number if we have seen all of the
308 std::vector<uint32_t> *StreamBlocks = nullptr;
309 // Figure out which stream this block number belongs to.
310 while (StreamIdx < NumStreams) {
311 uint64_t NumExpectedStreamBlocks =
312 bytesToBlocks(StreamSizes[StreamIdx], SB->BlockSize);
313 StreamBlocks = &StreamMap[StreamIdx];
314 if (NumExpectedStreamBlocks > StreamBlocks->size())
318 // It seems this block doesn't belong to any stream? The stream is either
319 // corrupt or something more mysterious is going on.
320 if (StreamIdx == NumStreams)
321 reportError(M.getBufferIdentifier(),
322 std::make_error_code(std::errc::illegal_byte_sequence));
324 StreamBlocks->push_back(Data);
328 // We should have read exactly SB->NumDirectoryBytes bytes.
329 assert(DirectoryBytesRead == SB->NumDirectoryBytes);
331 if (opts::DumpHeaders)
332 outs() << "NumStreams: " << NumStreams << '\n';
333 if (opts::DumpStreamSizes)
334 for (uint32_t StreamIdx = 0; StreamIdx < NumStreams; ++StreamIdx)
335 outs() << "StreamSizes[" << StreamIdx << "]: " << StreamSizes[StreamIdx]
338 if (opts::DumpStreamBlocks) {
339 for (uint32_t StreamIdx = 0; StreamIdx < NumStreams; ++StreamIdx) {
340 outs() << "StreamBlocks[" << StreamIdx << "]: [";
341 std::vector<uint32_t> &StreamBlocks = StreamMap[StreamIdx];
342 for (uint32_t &StreamBlock : StreamBlocks) {
343 if (&StreamBlock != &StreamBlocks.front())
345 outs() << StreamBlock;
351 StringRef DumpStreamStr = opts::DumpStreamData;
352 uint32_t DumpStreamNum;
353 if (!DumpStreamStr.getAsInteger(/*Radix=*/0U, DumpStreamNum) &&
354 DumpStreamNum < NumStreams) {
355 uint32_t StreamBytesRead = 0;
356 uint32_t StreamSize = StreamSizes[DumpStreamNum];
357 std::vector<uint32_t> &StreamBlocks = StreamMap[DumpStreamNum];
358 for (uint32_t &StreamBlockAddr : StreamBlocks) {
359 uint64_t StreamBlockOffset = blockToOffset(StreamBlockAddr, SB->BlockSize);
360 uint32_t BytesLeftToReadInStream = StreamSize - StreamBytesRead;
361 if (BytesLeftToReadInStream == 0)
364 uint32_t BytesToReadInBlock =
365 std::min(BytesLeftToReadInStream, static_cast<uint32_t>(SB->BlockSize));
366 auto StreamBlockData =
367 StringRef(M.getBufferStart() + StreamBlockOffset, BytesToReadInBlock);
368 if (auto EC = checkOffset(M, StreamBlockData))
369 reportError(M.getBufferIdentifier(), EC);
371 outs() << StreamBlockData;
372 StreamBytesRead += StreamBlockData.size();
377 static void dumpInput(StringRef Path) {
378 if (opts::DumpHeaders || !opts::DumpStreamData.empty()) {
379 ErrorOr<std::unique_ptr<MemoryBuffer>> ErrorOrBuffer =
380 MemoryBuffer::getFileOrSTDIN(Path, /*FileSize=*/-1,
381 /*RequiresNullTerminator=*/false);
383 if (std::error_code EC = ErrorOrBuffer.getError())
384 reportError(Path, EC);
386 std::unique_ptr<MemoryBuffer> &Buffer = ErrorOrBuffer.get();
388 dumpStructure(Buffer->getMemBufferRef());
394 std::unique_ptr<IPDBSession> Session;
395 PDB_ErrorCode Error = loadDataForPDB(PDB_ReaderType::DIA, Path, Session);
397 case PDB_ErrorCode::Success:
399 case PDB_ErrorCode::NoPdbImpl:
400 outs() << "Reading PDBs is not supported on this platform.\n";
402 case PDB_ErrorCode::InvalidPath:
403 outs() << "Unable to load PDB at '" << Path
404 << "'. Check that the file exists and is readable.\n";
406 case PDB_ErrorCode::InvalidFileFormat:
407 outs() << "Unable to load PDB at '" << Path
408 << "'. The file has an unrecognized format.\n";
411 outs() << "Unable to load PDB at '" << Path
412 << "'. An unknown error occured.\n";
415 if (opts::LoadAddress)
416 Session->setLoadAddress(opts::LoadAddress);
418 LinePrinter Printer(2, outs());
420 auto GlobalScope(Session->getGlobalScope());
421 std::string FileName(GlobalScope->getSymbolsFileName());
423 WithColor(Printer, PDB_ColorItem::None).get() << "Summary for ";
424 WithColor(Printer, PDB_ColorItem::Path).get() << FileName;
426 uint64_t FileSize = 0;
429 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size";
430 if (!sys::fs::file_size(FileName, FileSize)) {
431 Printer << ": " << FileSize << " bytes";
433 Printer << ": (Unable to obtain file size)";
437 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid";
438 Printer << ": " << GlobalScope->getGuid();
441 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age";
442 Printer << ": " << GlobalScope->getAge();
445 WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes";
447 if (GlobalScope->hasCTypes())
448 outs() << "HasCTypes ";
449 if (GlobalScope->hasPrivateSymbols())
450 outs() << "HasPrivateSymbols ";
453 if (opts::Compilands) {
455 WithColor(Printer, PDB_ColorItem::SectionHeader).get()
456 << "---COMPILANDS---";
458 auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
459 CompilandDumper Dumper(Printer);
460 while (auto Compiland = Compilands->getNext())
461 Dumper.start(*Compiland, false);
467 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---";
469 TypeDumper Dumper(Printer);
470 Dumper.start(*GlobalScope);
476 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---";
478 auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
479 CompilandDumper Dumper(Printer);
480 while (auto Compiland = Compilands->getNext())
481 Dumper.start(*Compiland, true);
487 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---";
490 FunctionDumper Dumper(Printer);
491 auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>();
492 while (auto Function = Functions->getNext()) {
494 Dumper.start(*Function, FunctionDumper::PointerType::None);
498 auto Vars = GlobalScope->findAllChildren<PDBSymbolData>();
499 VariableDumper Dumper(Printer);
500 while (auto Var = Vars->getNext())
504 auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>();
505 CompilandDumper Dumper(Printer);
506 while (auto Thunk = Thunks->getNext())
511 if (opts::Externals) {
513 WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---";
515 ExternalSymbolDumper Dumper(Printer);
516 Dumper.start(*GlobalScope);
521 int main(int argc_, const char *argv_[]) {
522 // Print a stack trace if we signal out.
523 sys::PrintStackTraceOnErrorSignal();
524 PrettyStackTraceProgram X(argc_, argv_);
526 SmallVector<const char *, 256> argv;
527 SpecificBumpPtrAllocator<char> ArgAllocator;
528 std::error_code EC = sys::Process::GetArgumentVector(
529 argv, makeArrayRef(argv_, argc_), ArgAllocator);
531 errs() << "error: couldn't get arguments: " << EC.message() << '\n';
535 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
537 cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");
539 opts::Compilands = true;
540 opts::Symbols = true;
541 opts::Globals = true;
543 opts::Externals = true;
545 if (opts::ExcludeCompilerGenerated) {
546 opts::ExcludeTypes.push_back("__vc_attributes");
547 opts::ExcludeCompilands.push_back("* Linker *");
549 if (opts::ExcludeSystemLibraries) {
550 opts::ExcludeCompilands.push_back(
551 "f:\\binaries\\Intermediate\\vctools\\crt_bld");
554 #if defined(HAVE_DIA_SDK)
555 CoInitializeEx(nullptr, COINIT_MULTITHREADED);
558 std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
561 #if defined(HAVE_DIA_SDK)