1 //===-- SymbolFilePDB.cpp ---------------------------------------*- 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 #include "SymbolFilePDB.h"
12 #include "PDBASTParser.h"
13 #include "PDBLocationToDWARFExpression.h"
15 #include "clang/Lex/Lexer.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/CompileUnit.h"
21 #include "lldb/Symbol/LineTable.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Symbol/SymbolVendor.h"
25 #include "lldb/Symbol/TypeList.h"
26 #include "lldb/Symbol/TypeMap.h"
27 #include "lldb/Symbol/Variable.h"
28 #include "lldb/Utility/RegularExpression.h"
30 #include "llvm/DebugInfo/PDB/GenericError.h"
31 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
32 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
33 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
34 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
35 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
36 #include "llvm/DebugInfo/PDB/IPDBTable.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
43 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
44 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
45 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
46 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
47 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
48 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
49 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
51 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
52 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
53 #include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h"
58 using namespace lldb_private;
59 using namespace llvm::pdb;
62 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
65 return lldb::LanguageType::eLanguageTypeC_plus_plus;
67 return lldb::LanguageType::eLanguageTypeC;
69 return lldb::LanguageType::eLanguageTypeUnknown;
73 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
74 uint32_t addr_length) {
75 return ((requested_line == 0 || actual_line == requested_line) &&
80 static bool ShouldUseNativeReader() {
82 llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER");
83 return use_native.equals_lower("on") || use_native.equals_lower("yes") ||
84 use_native.equals_lower("1") || use_native.equals_lower("true");
90 void SymbolFilePDB::Initialize() {
91 if (ShouldUseNativeReader()) {
92 npdb::SymbolFileNativePDB::Initialize();
94 PluginManager::RegisterPlugin(GetPluginNameStatic(),
95 GetPluginDescriptionStatic(), CreateInstance,
100 void SymbolFilePDB::Terminate() {
101 if (ShouldUseNativeReader()) {
102 npdb::SymbolFileNativePDB::Terminate();
104 PluginManager::UnregisterPlugin(CreateInstance);
108 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
110 lldb_private::ConstString SymbolFilePDB::GetPluginNameStatic() {
111 static ConstString g_name("pdb");
115 const char *SymbolFilePDB::GetPluginDescriptionStatic() {
116 return "Microsoft PDB debug symbol file reader.";
119 lldb_private::SymbolFile *
120 SymbolFilePDB::CreateInstance(lldb_private::ObjectFile *obj_file) {
121 return new SymbolFilePDB(obj_file);
124 SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file)
125 : SymbolFile(object_file), m_session_up(), m_global_scope_up(),
126 m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {}
128 SymbolFilePDB::~SymbolFilePDB() {}
130 uint32_t SymbolFilePDB::CalculateAbilities() {
131 uint32_t abilities = 0;
136 // Lazily load and match the PDB file, but only do this once.
137 std::string exePath = m_obj_file->GetFileSpec().GetPath();
138 auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
141 llvm::consumeError(std::move(error));
142 auto module_sp = m_obj_file->GetModule();
145 // See if any symbol file is specified through `--symfile` option.
146 FileSpec symfile = module_sp->GetSymbolFileFileSpec();
149 error = loadDataForPDB(PDB_ReaderType::DIA,
150 llvm::StringRef(symfile.GetPath()), m_session_up);
152 llvm::consumeError(std::move(error));
160 auto enum_tables_up = m_session_up->getEnumTables();
163 while (auto table_up = enum_tables_up->getNext()) {
164 if (table_up->getItemCount() == 0)
166 auto type = table_up->getTableType();
168 case PDB_TableType::Symbols:
169 // This table represents a store of symbols with types listed in
171 abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
172 LocalVariables | VariableTypes);
174 case PDB_TableType::LineNumbers:
175 abilities |= LineTables;
184 void SymbolFilePDB::InitializeObject() {
185 lldb::addr_t obj_load_address = m_obj_file->GetFileOffset();
186 lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
187 m_session_up->setLoadAddress(obj_load_address);
188 if (!m_global_scope_up)
189 m_global_scope_up = m_session_up->getGlobalScope();
190 lldbassert(m_global_scope_up.get());
192 TypeSystem *type_system =
193 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
194 ClangASTContext *clang_type_system =
195 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
196 lldbassert(clang_type_system);
197 m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>(
198 type_system, clang_type_system->GetTranslationUnitDecl());
201 uint32_t SymbolFilePDB::GetNumCompileUnits() {
202 if (m_cached_compile_unit_count == 0) {
203 auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
207 // The linker could link *.dll (compiland language = LINK), or import
208 // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
209 // found as a child of the global scope (PDB executable). Usually, such
210 // compilands contain `thunk` symbols in which we are not interested for
211 // now. However we still count them in the compiland list. If we perform
212 // any compiland related activity, like finding symbols through
213 // llvm::pdb::IPDBSession methods, such compilands will all be searched
214 // automatically no matter whether we include them or not.
215 m_cached_compile_unit_count = compilands->getChildCount();
217 // The linker can inject an additional "dummy" compilation unit into the
218 // PDB. Ignore this special compile unit for our purposes, if it is there.
219 // It is always the last one.
220 auto last_compiland_up =
221 compilands->getChildAtIndex(m_cached_compile_unit_count - 1);
222 lldbassert(last_compiland_up.get());
223 std::string name = last_compiland_up->getName();
224 if (name == "* Linker *")
225 --m_cached_compile_unit_count;
227 return m_cached_compile_unit_count;
230 void SymbolFilePDB::GetCompileUnitIndex(
231 const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
232 auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
235 auto uid = pdb_compiland.getSymIndexId();
236 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
237 auto compiland_up = results_up->getChildAtIndex(cu_idx);
240 if (compiland_up->getSymIndexId() == uid) {
249 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
250 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
251 return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
254 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
255 if (index >= GetNumCompileUnits())
258 // Assuming we always retrieve same compilands listed in same order through
259 // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
260 // compile unit makes no sense.
261 auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
264 auto compiland_up = results->getChildAtIndex(index);
267 return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
270 lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) {
271 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
273 return lldb::eLanguageTypeUnknown;
274 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
276 return lldb::eLanguageTypeUnknown;
277 return TranslateLanguage(details->getLanguage());
280 lldb_private::Function *
281 SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func,
282 CompileUnit &comp_unit) {
283 if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId()))
286 auto file_vm_addr = pdb_func.getVirtualAddress();
287 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
290 auto func_length = pdb_func.getLength();
291 AddressRange func_range =
292 AddressRange(file_vm_addr, func_length,
293 GetObjectFile()->GetModule()->GetSectionList());
294 if (!func_range.GetBaseAddress().IsValid())
297 lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
301 user_id_t func_type_uid = pdb_func.getSignatureId();
303 Mangled mangled = GetMangledForPDBFunc(pdb_func);
306 std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(),
307 func_type_uid, mangled, func_type, func_range);
309 comp_unit.AddFunction(func_sp);
311 TypeSystem *type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
314 ClangASTContext *clang_type_system =
315 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
316 if (!clang_type_system)
318 clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func);
320 return func_sp.get();
323 size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) {
324 size_t func_added = 0;
325 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
328 auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
331 while (auto pdb_func_up = results_up->getNext()) {
332 auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId());
334 if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit))
341 bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) {
342 if (comp_unit.GetLineTable())
344 return ParseCompileUnitLineTable(comp_unit, 0);
347 bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) {
348 // PDB doesn't contain information about macros
352 bool SymbolFilePDB::ParseSupportFiles(
353 CompileUnit &comp_unit, lldb_private::FileSpecList &support_files) {
355 // In theory this is unnecessary work for us, because all of this information
356 // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
357 // second time seems like a waste. Unfortunately, there's no good way around
358 // this short of a moderate refactor since SymbolVendor depends on being able
359 // to cache this list.
360 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
363 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
364 if (!files || files->getChildCount() == 0)
367 while (auto file = files->getNext()) {
368 FileSpec spec(file->getFileName(), FileSpec::Style::windows);
369 support_files.AppendIfUnique(spec);
372 // LLDB uses the DWARF-like file numeration (one based),
373 // the zeroth file is the compile unit itself
374 support_files.Insert(0, comp_unit);
379 bool SymbolFilePDB::ParseImportedModules(
380 const lldb_private::SymbolContext &sc,
381 std::vector<lldb_private::ConstString> &imported_modules) {
382 // PDB does not yet support module debug info
386 static size_t ParseFunctionBlocksForPDBSymbol(
387 uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol,
388 lldb_private::Block *parent_block, bool is_top_parent) {
389 assert(pdb_symbol && parent_block);
391 size_t num_added = 0;
392 switch (pdb_symbol->getSymTag()) {
393 case PDB_SymType::Block:
394 case PDB_SymType::Function: {
395 Block *block = nullptr;
396 auto &raw_sym = pdb_symbol->getRawSymbol();
397 if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {
398 if (pdb_func->hasNoInlineAttribute())
401 block = parent_block;
404 } else if (llvm::dyn_cast<PDBSymbolBlock>(pdb_symbol)) {
405 auto uid = pdb_symbol->getSymIndexId();
406 if (parent_block->FindBlockByID(uid))
408 if (raw_sym.getVirtualAddress() < func_file_vm_addr)
411 auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());
412 parent_block->AddChild(block_sp);
413 block = block_sp.get();
415 llvm_unreachable("Unexpected PDB symbol!");
417 block->AddRange(Block::Range(
418 raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
419 block->FinalizeRanges();
422 auto results_up = pdb_symbol->findAllChildren();
425 while (auto symbol_up = results_up->getNext()) {
426 num_added += ParseFunctionBlocksForPDBSymbol(
427 func_file_vm_addr, symbol_up.get(), block, false);
436 size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) {
437 size_t num_added = 0;
438 auto uid = func.GetID();
439 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
442 Block &parent_block = func.GetBlock(false);
443 num_added = ParseFunctionBlocksForPDBSymbol(
444 pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true);
448 size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) {
450 size_t num_added = 0;
451 auto compiland = GetPDBCompilandByUID(comp_unit.GetID());
455 auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
456 std::unique_ptr<IPDBEnumSymbols> results;
457 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
459 for (auto tag : tags_to_search) {
460 results = raw_sym.findAllChildren(tag);
461 if (!results || results->getChildCount() == 0)
463 while (auto symbol = results->getNext()) {
464 switch (symbol->getSymTag()) {
465 case PDB_SymType::Enum:
466 case PDB_SymType::UDT:
467 case PDB_SymType::Typedef:
473 // This should cause the type to get cached and stored in the `m_types`
475 if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
476 // Resolve the type completely to avoid a completion
477 // (and so a list change, which causes an iterators invalidation)
478 // during a TypeList dumping
479 type->GetFullCompilerType();
486 ParseTypesByTagFn(*compiland);
488 // Also parse global types particularly coming from this compiland.
489 // Unfortunately, PDB has no compiland information for each global type. We
490 // have to parse them all. But ensure we only do this once.
491 static bool parse_all_global_types = false;
492 if (!parse_all_global_types) {
493 ParseTypesByTagFn(*m_global_scope_up);
494 parse_all_global_types = true;
500 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
504 size_t num_added = 0;
506 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
507 sc.function->GetID());
511 num_added += ParseVariables(sc, *pdb_func);
512 sc.function->GetBlock(false).SetDidParseVariables(true, true);
513 } else if (sc.comp_unit) {
514 auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
518 if (sc.comp_unit->GetVariableList(false))
521 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
522 if (results && results->getChildCount()) {
523 while (auto result = results->getNext()) {
524 auto cu_id = GetCompilandId(*result);
525 // FIXME: We are not able to determine variable's compile unit.
529 if (cu_id == sc.comp_unit->GetID())
530 num_added += ParseVariables(sc, *result);
534 // FIXME: A `file static` or `global constant` variable appears both in
535 // compiland's children and global scope's children with unexpectedly
536 // different symbol's Id making it ambiguous.
538 // FIXME: 'local constant', for example, const char var[] = "abc", declared
539 // in a function scope, can't be found in PDB.
541 // Parse variables in this compiland.
542 num_added += ParseVariables(sc, *compiland);
548 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
549 auto find_result = m_types.find(type_uid);
550 if (find_result != m_types.end())
551 return find_result->second.get();
553 TypeSystem *type_system =
554 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
555 ClangASTContext *clang_type_system =
556 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
557 if (!clang_type_system)
559 PDBASTParser *pdb = clang_type_system->GetPDBParser();
563 auto pdb_type = m_session_up->getSymbolById(type_uid);
564 if (pdb_type == nullptr)
567 lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
569 m_types.insert(std::make_pair(type_uid, result));
570 auto type_list = GetTypeList();
572 type_list->Insert(result);
577 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
578 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
582 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
583 std::lock_guard<std::recursive_mutex> guard(
584 GetObjectFile()->GetModule()->GetMutex());
586 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
587 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
591 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
595 return pdb->CompleteTypeFromPDB(compiler_type);
598 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
599 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
600 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
602 return CompilerDecl();
604 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
606 return CompilerDecl();
608 auto symbol = m_session_up->getSymbolById(uid);
610 return CompilerDecl();
612 auto decl = pdb->GetDeclForSymbol(*symbol);
614 return CompilerDecl();
616 return CompilerDecl(clang_ast_ctx, decl);
619 lldb_private::CompilerDeclContext
620 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
621 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
622 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
624 return CompilerDeclContext();
626 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
628 return CompilerDeclContext();
630 auto symbol = m_session_up->getSymbolById(uid);
632 return CompilerDeclContext();
634 auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
636 return GetDeclContextContainingUID(uid);
638 return CompilerDeclContext(clang_ast_ctx, decl_context);
641 lldb_private::CompilerDeclContext
642 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
643 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
644 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
646 return CompilerDeclContext();
648 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
650 return CompilerDeclContext();
652 auto symbol = m_session_up->getSymbolById(uid);
654 return CompilerDeclContext();
656 auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
657 assert(decl_context);
659 return CompilerDeclContext(clang_ast_ctx, decl_context);
662 void SymbolFilePDB::ParseDeclsForContext(
663 lldb_private::CompilerDeclContext decl_ctx) {
664 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
665 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
669 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
673 pdb->ParseDeclsForDeclContext(
674 static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
678 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
679 SymbolContextItem resolve_scope,
680 lldb_private::SymbolContext &sc) {
681 uint32_t resolved_flags = 0;
682 if (resolve_scope & eSymbolContextCompUnit ||
683 resolve_scope & eSymbolContextVariable ||
684 resolve_scope & eSymbolContextFunction ||
685 resolve_scope & eSymbolContextBlock ||
686 resolve_scope & eSymbolContextLineEntry) {
687 auto cu_sp = GetCompileUnitContainsAddress(so_addr);
689 if (resolved_flags | eSymbolContextVariable) {
690 // TODO: Resolve variables
694 sc.comp_unit = cu_sp.get();
695 resolved_flags |= eSymbolContextCompUnit;
696 lldbassert(sc.module_sp == cu_sp->GetModule());
699 if (resolve_scope & eSymbolContextFunction ||
700 resolve_scope & eSymbolContextBlock) {
701 addr_t file_vm_addr = so_addr.GetFileAddress();
703 m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
705 auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
707 auto func_uid = pdb_func->getSymIndexId();
708 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
709 if (sc.function == nullptr)
711 ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit);
713 resolved_flags |= eSymbolContextFunction;
714 if (resolve_scope & eSymbolContextBlock) {
715 auto block_symbol = m_session_up->findSymbolByAddress(
716 file_vm_addr, PDB_SymType::Block);
717 auto block_id = block_symbol ? block_symbol->getSymIndexId()
718 : sc.function->GetID();
719 sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
721 resolved_flags |= eSymbolContextBlock;
727 if (resolve_scope & eSymbolContextLineEntry) {
728 if (auto *line_table = sc.comp_unit->GetLineTable()) {
729 Address addr(so_addr);
730 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
731 resolved_flags |= eSymbolContextLineEntry;
735 return resolved_flags;
738 uint32_t SymbolFilePDB::ResolveSymbolContext(
739 const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
740 SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
741 const size_t old_size = sc_list.GetSize();
742 if (resolve_scope & lldb::eSymbolContextCompUnit) {
743 // Locate all compilation units with line numbers referencing the specified
744 // file. For example, if `file_spec` is <vector>, then this should return
745 // all source files and header files that reference <vector>, either
746 // directly or indirectly.
747 auto compilands = m_session_up->findCompilandsForSourceFile(
748 file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
753 // For each one, either find its previously parsed data or parse it afresh
754 // and add it to the symbol context list.
755 while (auto compiland = compilands->getNext()) {
756 // If we're not checking inlines, then don't add line information for
757 // this file unless the FileSpec matches. For inline functions, we don't
758 // have to match the FileSpec since they could be defined in headers
759 // other than file specified in FileSpec.
760 if (!check_inlines) {
761 std::string source_file = compiland->getSourceFileFullPath();
762 if (source_file.empty())
764 FileSpec this_spec(source_file, FileSpec::Style::windows);
765 bool need_full_match = !file_spec.GetDirectory().IsEmpty();
766 if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
771 auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
774 sc.comp_unit = cu.get();
775 sc.module_sp = cu->GetModule();
777 // If we were asked to resolve line entries, add all entries to the line
778 // table that match the requested line (or all lines if `line` == 0).
779 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
780 eSymbolContextLineEntry)) {
781 bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line);
783 if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
784 // The query asks for line entries, but we can't get them for the
785 // compile unit. This is not normal for `line` = 0. So just assert
787 assert(line && "Couldn't get all line entries!\n");
789 // Current compiland does not have the requested line. Search next.
793 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
797 auto *line_table = sc.comp_unit->GetLineTable();
798 lldbassert(line_table);
800 uint32_t num_line_entries = line_table->GetSize();
801 // Skip the terminal line entry.
804 // If `line `!= 0, see if we can resolve function for each line entry
805 // in the line table.
806 for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
808 if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
812 sc.line_entry.range.GetBaseAddress().GetFileAddress();
813 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
816 auto symbol_up = m_session_up->findSymbolByAddress(
817 file_vm_addr, PDB_SymType::Function);
819 auto func_uid = symbol_up->getSymIndexId();
820 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
821 if (sc.function == nullptr) {
822 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
824 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func,
827 if (sc.function && (resolve_scope & eSymbolContextBlock)) {
828 Block &block = sc.function->GetBlock(true);
829 sc.block = block.FindBlockByID(sc.function->GetID());
834 } else if (has_line_table) {
835 // We can parse line table for the compile unit. But no query to
836 // resolve function or block. We append `sc` to the list anyway.
840 // No query for line entry, function or block. But we have a valid
841 // compile unit, append `sc` to the list.
846 return sc_list.GetSize() - old_size;
849 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
850 // Cache public names at first
851 if (m_public_names.empty())
853 m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
854 while (auto symbol_up = result_up->getNext())
855 if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
856 m_public_names[addr] = symbol_up->getRawSymbol().getName();
858 // Look up the name in the cache
859 return m_public_names.lookup(pdb_data.getVirtualAddress());
862 VariableSP SymbolFilePDB::ParseVariableForPDBData(
863 const lldb_private::SymbolContext &sc,
864 const llvm::pdb::PDBSymbolData &pdb_data) {
866 uint32_t var_uid = pdb_data.getSymIndexId();
867 auto result = m_variables.find(var_uid);
868 if (result != m_variables.end())
869 return result->second;
871 ValueType scope = eValueTypeInvalid;
872 bool is_static_member = false;
873 bool is_external = false;
874 bool is_artificial = false;
876 switch (pdb_data.getDataKind()) {
877 case PDB_DataKind::Global:
878 scope = eValueTypeVariableGlobal;
881 case PDB_DataKind::Local:
882 scope = eValueTypeVariableLocal;
884 case PDB_DataKind::FileStatic:
885 scope = eValueTypeVariableStatic;
887 case PDB_DataKind::StaticMember:
888 is_static_member = true;
889 scope = eValueTypeVariableStatic;
891 case PDB_DataKind::Member:
892 scope = eValueTypeVariableStatic;
894 case PDB_DataKind::Param:
895 scope = eValueTypeVariableArgument;
897 case PDB_DataKind::Constant:
898 scope = eValueTypeConstResult;
904 switch (pdb_data.getLocationType()) {
905 case PDB_LocType::TLS:
906 scope = eValueTypeVariableThreadLocal;
908 case PDB_LocType::RegRel: {
909 // It is a `this` pointer.
910 if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
911 scope = eValueTypeVariableArgument;
912 is_artificial = true;
920 if (!is_artificial && !pdb_data.isCompilerGenerated()) {
921 if (auto lines = pdb_data.getLineNumbers()) {
922 if (auto first_line = lines->getNext()) {
923 uint32_t src_file_id = first_line->getSourceFileId();
924 auto src_file = m_session_up->getSourceFileById(src_file_id);
926 FileSpec spec(src_file->getFileName());
928 decl.SetColumn(first_line->getColumnNumber());
929 decl.SetLine(first_line->getLineNumber());
935 Variable::RangeList ranges;
936 SymbolContextScope *context_scope = sc.comp_unit;
937 if (scope == eValueTypeVariableLocal) {
939 context_scope = sc.function->GetBlock(true).FindBlockByID(
940 pdb_data.getLexicalParentId());
941 if (context_scope == nullptr)
942 context_scope = sc.function;
946 SymbolFileTypeSP type_sp =
947 std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
949 auto var_name = pdb_data.getName();
950 auto mangled = GetMangledForPDBData(pdb_data);
951 auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
954 DWARFExpression location = ConvertPDBLocationToDWARFExpression(
955 GetObjectFile()->GetModule(), pdb_data, is_constant);
957 var_sp = std::make_shared<Variable>(
958 var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
959 ranges, &decl, location, is_external, is_artificial, is_static_member);
960 var_sp->SetLocationIsConstantValueData(is_constant);
962 m_variables.insert(std::make_pair(var_uid, var_sp));
967 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
968 const llvm::pdb::PDBSymbol &pdb_symbol,
969 lldb_private::VariableList *variable_list) {
970 size_t num_added = 0;
972 if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
973 VariableListSP local_variable_list_sp;
975 auto result = m_variables.find(pdb_data->getSymIndexId());
976 if (result != m_variables.end()) {
978 variable_list->AddVariableIfUnique(result->second);
980 // Prepare right VariableList for this variable.
981 if (auto lexical_parent = pdb_data->getLexicalParent()) {
982 switch (lexical_parent->getSymTag()) {
983 case PDB_SymType::Exe:
984 assert(sc.comp_unit);
986 case PDB_SymType::Compiland: {
988 local_variable_list_sp = sc.comp_unit->GetVariableList(false);
989 if (!local_variable_list_sp) {
990 local_variable_list_sp = std::make_shared<VariableList>();
991 sc.comp_unit->SetVariableList(local_variable_list_sp);
995 case PDB_SymType::Block:
996 case PDB_SymType::Function: {
998 Block *block = sc.function->GetBlock(true).FindBlockByID(
999 lexical_parent->getSymIndexId());
1001 local_variable_list_sp = block->GetBlockVariableList(false);
1002 if (!local_variable_list_sp) {
1003 local_variable_list_sp = std::make_shared<VariableList>();
1004 block->SetVariableList(local_variable_list_sp);
1014 if (local_variable_list_sp) {
1015 if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1016 local_variable_list_sp->AddVariableIfUnique(var_sp);
1018 variable_list->AddVariableIfUnique(var_sp);
1020 PDBASTParser *ast = GetPDBAstParser();
1022 ast->GetDeclForSymbol(*pdb_data);
1028 if (auto results = pdb_symbol.findAllChildren()) {
1029 while (auto result = results->getNext())
1030 num_added += ParseVariables(sc, *result, variable_list);
1036 uint32_t SymbolFilePDB::FindGlobalVariables(
1037 const lldb_private::ConstString &name,
1038 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1039 uint32_t max_matches, lldb_private::VariableList &variables) {
1040 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1045 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1049 uint32_t matches = 0;
1050 size_t old_size = variables.GetSize();
1051 while (auto result = results->getNext()) {
1052 auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1053 if (max_matches > 0 && matches >= max_matches)
1057 sc.module_sp = m_obj_file->GetModule();
1058 lldbassert(sc.module_sp.get());
1060 if (!name.GetStringRef().equals(
1061 MSVCUndecoratedNameParser::DropScope(pdb_data->getName())))
1064 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1065 // FIXME: We are not able to determine the compile unit.
1066 if (sc.comp_unit == nullptr)
1069 if (parent_decl_ctx && GetDeclContextContainingUID(
1070 result->getSymIndexId()) != *parent_decl_ctx)
1073 ParseVariables(sc, *pdb_data, &variables);
1074 matches = variables.GetSize() - old_size;
1081 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression ®ex,
1082 uint32_t max_matches,
1083 lldb_private::VariableList &variables) {
1084 if (!regex.IsValid())
1086 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1090 uint32_t matches = 0;
1091 size_t old_size = variables.GetSize();
1092 while (auto pdb_data = results->getNext()) {
1093 if (max_matches > 0 && matches >= max_matches)
1096 auto var_name = pdb_data->getName();
1097 if (var_name.empty())
1099 if (!regex.Execute(var_name))
1102 sc.module_sp = m_obj_file->GetModule();
1103 lldbassert(sc.module_sp.get());
1105 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1106 // FIXME: We are not able to determine the compile unit.
1107 if (sc.comp_unit == nullptr)
1110 ParseVariables(sc, *pdb_data, &variables);
1111 matches = variables.GetSize() - old_size;
1117 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1118 bool include_inlines,
1119 lldb_private::SymbolContextList &sc_list) {
1120 lldb_private::SymbolContext sc;
1121 sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1124 sc.module_sp = sc.comp_unit->GetModule();
1125 sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit);
1133 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1134 lldb_private::SymbolContextList &sc_list) {
1135 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1136 if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1138 return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1141 void SymbolFilePDB::CacheFunctionNames() {
1142 if (!m_func_full_names.IsEmpty())
1145 std::map<uint64_t, uint32_t> addr_ids;
1147 if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1148 while (auto pdb_func_up = results_up->getNext()) {
1149 if (pdb_func_up->isCompilerGenerated())
1152 auto name = pdb_func_up->getName();
1153 auto demangled_name = pdb_func_up->getUndecoratedName();
1154 if (name.empty() && demangled_name.empty())
1157 auto uid = pdb_func_up->getSymIndexId();
1158 if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1159 addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1161 if (auto parent = pdb_func_up->getClassParent()) {
1163 // PDB have symbols for class/struct methods or static methods in Enum
1164 // Class. We won't bother to check if the parent is UDT or Enum here.
1165 m_func_method_names.Append(ConstString(name), uid);
1167 // To search a method name, like NS::Class:MemberFunc, LLDB searches
1168 // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1169 // not have inforamtion of this, we extract base names and cache them
1170 // by our own effort.
1171 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1172 if (!basename.empty())
1173 m_func_base_names.Append(ConstString(basename), uid);
1175 m_func_base_names.Append(ConstString(name), uid);
1178 if (!demangled_name.empty())
1179 m_func_full_names.Append(ConstString(demangled_name), uid);
1182 // Handle not-method symbols.
1184 // The function name might contain namespace, or its lexical scope.
1185 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1186 if (!basename.empty())
1187 m_func_base_names.Append(ConstString(basename), uid);
1189 m_func_base_names.Append(ConstString(name), uid);
1191 if (name == "main") {
1192 m_func_full_names.Append(ConstString(name), uid);
1194 if (!demangled_name.empty() && name != demangled_name) {
1195 m_func_full_names.Append(ConstString(demangled_name), uid);
1196 m_func_base_names.Append(ConstString(demangled_name), uid);
1198 } else if (!demangled_name.empty()) {
1199 m_func_full_names.Append(ConstString(demangled_name), uid);
1201 m_func_full_names.Append(ConstString(name), uid);
1207 if (auto results_up =
1208 m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1209 while (auto pub_sym_up = results_up->getNext()) {
1210 if (!pub_sym_up->isFunction())
1212 auto name = pub_sym_up->getName();
1216 if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1217 auto vm_addr = pub_sym_up->getVirtualAddress();
1219 // PDB public symbol has mangled name for its associated function.
1220 if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1221 // Cache mangled name.
1222 m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1227 // Sort them before value searching is working properly
1228 m_func_full_names.Sort();
1229 m_func_full_names.SizeToFit();
1230 m_func_method_names.Sort();
1231 m_func_method_names.SizeToFit();
1232 m_func_base_names.Sort();
1233 m_func_base_names.SizeToFit();
1236 uint32_t SymbolFilePDB::FindFunctions(
1237 const lldb_private::ConstString &name,
1238 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1239 FunctionNameType name_type_mask, bool include_inlines, bool append,
1240 lldb_private::SymbolContextList &sc_list) {
1243 lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1245 if (name_type_mask == eFunctionNameTypeNone)
1247 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1252 auto old_size = sc_list.GetSize();
1253 if (name_type_mask & eFunctionNameTypeFull ||
1254 name_type_mask & eFunctionNameTypeBase ||
1255 name_type_mask & eFunctionNameTypeMethod) {
1256 CacheFunctionNames();
1258 std::set<uint32_t> resolved_ids;
1259 auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,
1260 &resolved_ids](UniqueCStringMap<uint32_t> &Names) {
1261 std::vector<uint32_t> ids;
1262 if (!Names.GetValues(name, ids))
1265 for (uint32_t id : ids) {
1266 if (resolved_ids.find(id) != resolved_ids.end())
1269 if (parent_decl_ctx &&
1270 GetDeclContextContainingUID(id) != *parent_decl_ctx)
1273 if (ResolveFunction(id, include_inlines, sc_list))
1274 resolved_ids.insert(id);
1277 if (name_type_mask & eFunctionNameTypeFull) {
1278 ResolveFn(m_func_full_names);
1279 ResolveFn(m_func_base_names);
1280 ResolveFn(m_func_method_names);
1282 if (name_type_mask & eFunctionNameTypeBase) {
1283 ResolveFn(m_func_base_names);
1285 if (name_type_mask & eFunctionNameTypeMethod) {
1286 ResolveFn(m_func_method_names);
1289 return sc_list.GetSize() - old_size;
1293 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex,
1294 bool include_inlines, bool append,
1295 lldb_private::SymbolContextList &sc_list) {
1298 if (!regex.IsValid())
1301 auto old_size = sc_list.GetSize();
1302 CacheFunctionNames();
1304 std::set<uint32_t> resolved_ids;
1305 auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids,
1306 this](UniqueCStringMap<uint32_t> &Names) {
1307 std::vector<uint32_t> ids;
1308 if (Names.GetValues(regex, ids)) {
1309 for (auto id : ids) {
1310 if (resolved_ids.find(id) == resolved_ids.end())
1311 if (ResolveFunction(id, include_inlines, sc_list))
1312 resolved_ids.insert(id);
1316 ResolveFn(m_func_full_names);
1317 ResolveFn(m_func_base_names);
1319 return sc_list.GetSize() - old_size;
1322 void SymbolFilePDB::GetMangledNamesForFunction(
1323 const std::string &scope_qualified_name,
1324 std::vector<lldb_private::ConstString> &mangled_names) {}
1326 void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) {
1327 std::set<lldb::addr_t> sym_addresses;
1328 for (size_t i = 0; i < symtab.GetNumSymbols(); i++)
1329 sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());
1331 auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();
1335 auto section_list = m_obj_file->GetSectionList();
1339 while (auto pub_symbol = results->getNext()) {
1340 auto section_idx = pub_symbol->getAddressSection() - 1;
1341 if (section_idx >= section_list->GetSize())
1344 auto section = section_list->GetSectionAtIndex(section_idx);
1348 auto offset = pub_symbol->getAddressOffset();
1350 auto file_addr = section->GetFileAddress() + offset;
1351 if (sym_addresses.find(file_addr) != sym_addresses.end())
1353 sym_addresses.insert(file_addr);
1355 auto size = pub_symbol->getLength();
1357 Symbol(pub_symbol->getSymIndexId(), // symID
1358 pub_symbol->getName().c_str(), // name
1359 true, // name_is_mangled
1360 pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type
1363 false, // is_trampoline
1364 false, // is_artificial
1365 section, // section_sp
1368 size != 0, // size_is_valid
1369 false, // contains_linker_annotations
1374 symtab.CalculateSymbolSizes();
1378 uint32_t SymbolFilePDB::FindTypes(
1379 const lldb_private::ConstString &name,
1380 const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1381 uint32_t max_matches,
1382 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1383 lldb_private::TypeMap &types) {
1388 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1391 searched_symbol_files.clear();
1392 searched_symbol_files.insert(this);
1394 // There is an assumption 'name' is not a regex
1395 FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1397 return types.GetSize();
1400 void SymbolFilePDB::DumpClangAST(Stream &s) {
1401 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1402 auto clang = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1408 void SymbolFilePDB::FindTypesByRegex(
1409 const lldb_private::RegularExpression ®ex, uint32_t max_matches,
1410 lldb_private::TypeMap &types) {
1411 // When searching by regex, we need to go out of our way to limit the search
1412 // space as much as possible since this searches EVERYTHING in the PDB,
1413 // manually doing regex comparisons. PDB library isn't optimized for regex
1414 // searches or searches across multiple symbol types at the same time, so the
1415 // best we can do is to search enums, then typedefs, then classes one by one,
1416 // and do a regex comparison against each of them.
1417 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1419 std::unique_ptr<IPDBEnumSymbols> results;
1421 uint32_t matches = 0;
1423 for (auto tag : tags_to_search) {
1424 results = m_global_scope_up->findAllChildren(tag);
1428 while (auto result = results->getNext()) {
1429 if (max_matches > 0 && matches >= max_matches)
1432 std::string type_name;
1433 if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1434 type_name = enum_type->getName();
1435 else if (auto typedef_type =
1436 llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1437 type_name = typedef_type->getName();
1438 else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1439 type_name = class_type->getName();
1441 // We're looking only for types that have names. Skip symbols, as well
1442 // as unnamed types such as arrays, pointers, etc.
1446 if (!regex.Execute(type_name))
1449 // This should cause the type to get cached and stored in the `m_types`
1451 if (!ResolveTypeUID(result->getSymIndexId()))
1454 auto iter = m_types.find(result->getSymIndexId());
1455 if (iter == m_types.end())
1457 types.Insert(iter->second);
1463 void SymbolFilePDB::FindTypesByName(
1464 llvm::StringRef name,
1465 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1466 uint32_t max_matches, lldb_private::TypeMap &types) {
1467 std::unique_ptr<IPDBEnumSymbols> results;
1470 results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1474 uint32_t matches = 0;
1476 while (auto result = results->getNext()) {
1477 if (max_matches > 0 && matches >= max_matches)
1480 if (MSVCUndecoratedNameParser::DropScope(
1481 result->getRawSymbol().getName()) != name)
1484 switch (result->getSymTag()) {
1485 case PDB_SymType::Enum:
1486 case PDB_SymType::UDT:
1487 case PDB_SymType::Typedef:
1490 // We're looking only for types that have names. Skip symbols, as well
1491 // as unnamed types such as arrays, pointers, etc.
1495 // This should cause the type to get cached and stored in the `m_types`
1497 if (!ResolveTypeUID(result->getSymIndexId()))
1500 if (parent_decl_ctx && GetDeclContextContainingUID(
1501 result->getSymIndexId()) != *parent_decl_ctx)
1504 auto iter = m_types.find(result->getSymIndexId());
1505 if (iter == m_types.end())
1507 types.Insert(iter->second);
1512 size_t SymbolFilePDB::FindTypes(
1513 const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1514 lldb_private::TypeMap &types) {
1518 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1519 return m_obj_file->GetModule()->GetTypeList();
1522 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1524 TypeCollection &type_collection) {
1525 bool can_parse = false;
1526 switch (pdb_symbol.getSymTag()) {
1527 case PDB_SymType::ArrayType:
1528 can_parse = ((type_mask & eTypeClassArray) != 0);
1530 case PDB_SymType::BuiltinType:
1531 can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1533 case PDB_SymType::Enum:
1534 can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1536 case PDB_SymType::Function:
1537 case PDB_SymType::FunctionSig:
1538 can_parse = ((type_mask & eTypeClassFunction) != 0);
1540 case PDB_SymType::PointerType:
1541 can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1542 eTypeClassMemberPointer)) != 0);
1544 case PDB_SymType::Typedef:
1545 can_parse = ((type_mask & eTypeClassTypedef) != 0);
1547 case PDB_SymType::UDT: {
1548 auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1550 can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1551 ((type_mask & (eTypeClassClass | eTypeClassStruct |
1552 eTypeClassUnion)) != 0));
1559 if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1561 std::find(type_collection.begin(), type_collection.end(), type);
1562 if (result == type_collection.end())
1563 type_collection.push_back(type);
1567 auto results_up = pdb_symbol.findAllChildren();
1568 while (auto symbol_up = results_up->getNext())
1569 GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1572 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1573 TypeClass type_mask,
1574 lldb_private::TypeList &type_list) {
1575 TypeCollection type_collection;
1576 uint32_t old_size = type_list.GetSize();
1578 sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1580 auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1583 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1585 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1586 auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1588 if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1589 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1594 for (auto type : type_collection) {
1595 type->GetForwardCompilerType();
1596 type_list.Insert(type->shared_from_this());
1598 return type_list.GetSize() - old_size;
1601 lldb_private::TypeSystem *
1602 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1604 m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1606 type_system->SetSymbolFile(this);
1610 PDBASTParser *SymbolFilePDB::GetPDBAstParser() {
1611 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1612 auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1613 if (!clang_type_system)
1616 return clang_type_system->GetPDBParser();
1620 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1621 const lldb_private::ConstString &name,
1622 const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1623 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1624 auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1625 if (!clang_type_system)
1626 return CompilerDeclContext();
1628 PDBASTParser *pdb = clang_type_system->GetPDBParser();
1630 return CompilerDeclContext();
1632 clang::DeclContext *decl_context = nullptr;
1633 if (parent_decl_ctx)
1634 decl_context = static_cast<clang::DeclContext *>(
1635 parent_decl_ctx->GetOpaqueDeclContext());
1637 auto namespace_decl =
1638 pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1639 if (!namespace_decl)
1640 return CompilerDeclContext();
1642 return CompilerDeclContext(type_system,
1643 static_cast<clang::DeclContext *>(namespace_decl));
1646 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1647 static ConstString g_name("pdb");
1651 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1653 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1655 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1656 return *m_session_up;
1659 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1661 auto found_cu = m_comp_units.find(id);
1662 if (found_cu != m_comp_units.end())
1663 return found_cu->second;
1665 auto compiland_up = GetPDBCompilandByUID(id);
1667 return CompUnitSP();
1669 lldb::LanguageType lang;
1670 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1672 lang = lldb::eLanguageTypeC_plus_plus;
1674 lang = TranslateLanguage(details->getLanguage());
1676 if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1677 return CompUnitSP();
1679 std::string path = compiland_up->getSourceFileFullPath();
1681 return CompUnitSP();
1683 // Don't support optimized code for now, DebugInfoPDB does not return this
1685 LazyBool optimized = eLazyBoolNo;
1686 auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1687 path.c_str(), id, lang, optimized);
1690 return CompUnitSP();
1692 m_comp_units.insert(std::make_pair(id, cu_sp));
1693 if (index == UINT32_MAX)
1694 GetCompileUnitIndex(*compiland_up, index);
1695 lldbassert(index != UINT32_MAX);
1696 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1701 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,
1702 uint32_t match_line) {
1703 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1707 // LineEntry needs the *index* of the file into the list of support files
1708 // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us
1709 // a globally unique idenfitifier in the namespace of the PDB. So, we have
1710 // to do a mapping so that we can hand out indices.
1711 llvm::DenseMap<uint32_t, uint32_t> index_map;
1712 BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1713 auto line_table = llvm::make_unique<LineTable>(&comp_unit);
1715 // Find contributions to `compiland` from all source and header files.
1716 std::string path = comp_unit.GetPath();
1717 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1721 // For each source and header file, create a LineSequence for contributions
1722 // to the compiland from that file, and add the sequence.
1723 while (auto file = files->getNext()) {
1724 std::unique_ptr<LineSequence> sequence(
1725 line_table->CreateLineSequenceContainer());
1726 auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1729 int entry_count = lines->getChildCount();
1732 uint32_t prev_length;
1734 uint32_t prev_source_idx;
1736 for (int i = 0; i < entry_count; ++i) {
1737 auto line = lines->getChildAtIndex(i);
1739 uint64_t lno = line->getLineNumber();
1740 uint64_t addr = line->getVirtualAddress();
1741 uint32_t length = line->getLength();
1742 uint32_t source_id = line->getSourceFileId();
1743 uint32_t col = line->getColumnNumber();
1744 uint32_t source_idx = index_map[source_id];
1746 // There was a gap between the current entry and the previous entry if
1747 // the addresses don't perfectly line up.
1748 bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1750 // Before inserting the current entry, insert a terminal entry at the end
1751 // of the previous entry's address range if the current entry resulted in
1752 // a gap from the previous entry.
1753 if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1754 line_table->AppendLineEntryToSequence(
1755 sequence.get(), prev_addr + prev_length, prev_line, 0,
1756 prev_source_idx, false, false, false, false, true);
1758 line_table->InsertSequence(sequence.release());
1759 sequence.reset(line_table->CreateLineSequenceContainer());
1762 if (ShouldAddLine(match_line, lno, length)) {
1763 bool is_statement = line->isStatement();
1764 bool is_prologue = false;
1765 bool is_epilogue = false;
1767 m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1769 auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1771 is_prologue = (addr == prologue->getVirtualAddress());
1773 auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1775 is_epilogue = (addr == epilogue->getVirtualAddress());
1778 line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1779 source_idx, is_statement, false,
1780 is_prologue, is_epilogue, false);
1784 prev_length = length;
1786 prev_source_idx = source_idx;
1789 if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1790 // The end is always a terminal entry, so insert it regardless.
1791 line_table->AppendLineEntryToSequence(
1792 sequence.get(), prev_addr + prev_length, prev_line, 0,
1793 prev_source_idx, false, false, false, false, true);
1796 line_table->InsertSequence(sequence.release());
1799 if (line_table->GetSize()) {
1800 comp_unit.SetLineTable(line_table.release());
1806 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1807 const PDBSymbolCompiland &compiland,
1808 llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1809 // This is a hack, but we need to convert the source id into an index into
1810 // the support files array. We don't want to do path comparisons to avoid
1811 // basename / full path issues that may or may not even be a problem, so we
1812 // use the globally unique source file identifiers. Ideally we could use the
1813 // global identifiers everywhere, but LineEntry currently assumes indices.
1814 auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1818 // LLDB uses the DWARF-like file numeration (one based)
1821 while (auto file = source_files->getNext()) {
1822 uint32_t source_id = file->getUniqueId();
1823 index_map[source_id] = index++;
1827 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1828 const lldb_private::Address &so_addr) {
1829 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1830 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1833 // If it is a PDB function's vm addr, this is the first sure bet.
1835 m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1836 if (auto first_line = lines->getNext())
1837 return ParseCompileUnitForUID(first_line->getCompilandId());
1840 // Otherwise we resort to section contributions.
1841 if (auto sec_contribs = m_session_up->getSectionContribs()) {
1842 while (auto section = sec_contribs->getNext()) {
1843 auto va = section->getVirtualAddress();
1844 if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1845 return ParseCompileUnitForUID(section->getCompilandId());
1852 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1854 auto func_name = pdb_func.getName();
1855 auto func_undecorated_name = pdb_func.getUndecoratedName();
1856 std::string func_decorated_name;
1858 // Seek from public symbols for non-static function's decorated name if any.
1859 // For static functions, they don't have undecorated names and aren't exposed
1860 // in Public Symbols either.
1861 if (!func_undecorated_name.empty()) {
1862 auto result_up = m_global_scope_up->findChildren(
1863 PDB_SymType::PublicSymbol, func_undecorated_name,
1864 PDB_NameSearchFlags::NS_UndecoratedName);
1866 while (auto symbol_up = result_up->getNext()) {
1867 // For a public symbol, it is unique.
1868 lldbassert(result_up->getChildCount() == 1);
1869 if (auto *pdb_public_sym =
1870 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1872 if (pdb_public_sym->isFunction()) {
1873 func_decorated_name = pdb_public_sym->getName();
1880 if (!func_decorated_name.empty()) {
1881 mangled.SetMangledName(ConstString(func_decorated_name));
1883 // For MSVC, format of C funciton's decorated name depends on calling
1884 // conventon. Unfortunately none of the format is recognized by current
1885 // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1886 // `__purecall` is retrieved as both its decorated and undecorated name
1887 // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1888 // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1889 // Mangled::GetDemangledName method will fail internally and caches an
1890 // empty string as its undecorated name. So we will face a contradition
1891 // here for the same symbol:
1892 // non-empty undecorated name from PDB
1893 // empty undecorated name from LLDB
1894 if (!func_undecorated_name.empty() &&
1895 mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1896 mangled.SetDemangledName(ConstString(func_undecorated_name));
1898 // LLDB uses several flags to control how a C++ decorated name is
1899 // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1900 // yielded name could be different from what we retrieve from
1901 // PDB source unless we also apply same flags in getting undecorated
1902 // name through PDBSymbolFunc::getUndecoratedNameEx method.
1903 if (!func_undecorated_name.empty() &&
1904 mangled.GetDemangledName(mangled.GuessLanguage()) !=
1905 ConstString(func_undecorated_name))
1906 mangled.SetDemangledName(ConstString(func_undecorated_name));
1907 } else if (!func_undecorated_name.empty()) {
1908 mangled.SetDemangledName(ConstString(func_undecorated_name));
1909 } else if (!func_name.empty())
1910 mangled.SetValue(ConstString(func_name), false);
1915 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1916 const lldb_private::CompilerDeclContext *decl_ctx) {
1917 if (decl_ctx == nullptr || !decl_ctx->IsValid())
1920 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1921 if (!decl_ctx_type_system)
1923 TypeSystem *type_system = GetTypeSystemForLanguage(
1924 decl_ctx_type_system->GetMinimumLanguage(nullptr));
1925 if (decl_ctx_type_system == type_system)
1926 return true; // The type systems match, return true
1931 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1932 static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1933 return lhs < rhs.Offset;
1936 // Cache section contributions
1937 if (m_sec_contribs.empty()) {
1938 if (auto SecContribs = m_session_up->getSectionContribs()) {
1939 while (auto SectionContrib = SecContribs->getNext()) {
1940 auto comp_id = SectionContrib->getCompilandId();
1944 auto sec = SectionContrib->getAddressSection();
1945 auto &sec_cs = m_sec_contribs[sec];
1947 auto offset = SectionContrib->getAddressOffset();
1949 std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
1951 auto size = SectionContrib->getLength();
1952 sec_cs.insert(it, {offset, size, comp_id});
1957 // Check by line number
1958 if (auto Lines = data.getLineNumbers()) {
1959 if (auto FirstLine = Lines->getNext())
1960 return FirstLine->getCompilandId();
1963 // Retrieve section + offset
1964 uint32_t DataSection = data.getAddressSection();
1965 uint32_t DataOffset = data.getAddressOffset();
1966 if (DataSection == 0) {
1967 if (auto RVA = data.getRelativeVirtualAddress())
1968 m_session_up->addressForRVA(RVA, DataSection, DataOffset);
1972 // Search by section contributions
1973 auto &sec_cs = m_sec_contribs[DataSection];
1975 std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
1976 if (it != sec_cs.begin()) {
1978 if (DataOffset < it->Offset + it->Size)
1979 return it->CompilandId;
1982 // Search in lexical tree
1983 auto LexParentId = data.getLexicalParentId();
1984 while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
1985 if (LexParent->getSymTag() == PDB_SymType::Exe)
1987 if (LexParent->getSymTag() == PDB_SymType::Compiland)
1989 LexParentId = LexParent->getRawSymbol().getLexicalParentId();