diff options
Diffstat (limited to 'contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB')
6 files changed, 4105 insertions, 0 deletions
diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp new file mode 100644 index 000000000000..d656ca3facf7 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.cpp @@ -0,0 +1,1455 @@ +//===-- PDBASTParser.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "PDBASTParser.h" + +#include "SymbolFilePDB.h" + +#include "clang/AST/CharUnits.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" + +#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" +#include "Plugins/ExpressionParser/Clang/ClangUtil.h" +#include "Plugins/TypeSystem/Clang/TypeSystemClang.h" +#include "lldb/Core/Declaration.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/TypeMap.h" +#include "lldb/Symbol/TypeSystem.h" +#include "lldb/Utility/LLDBLog.h" +#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h" +#include "llvm/DebugInfo/PDB/IPDBLineNumber.h" +#include "llvm/DebugInfo/PDB/IPDBSourceFile.h" +#include "llvm/DebugInfo/PDB/PDBSymbol.h" +#include "llvm/DebugInfo/PDB/PDBSymbolData.h" +#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" + +#include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" +#include <optional> + +using namespace lldb; +using namespace lldb_private; +using namespace llvm::pdb; + +static int TranslateUdtKind(PDB_UdtType pdb_kind) { + switch (pdb_kind) { + case PDB_UdtType::Class: + return llvm::to_underlying(clang::TagTypeKind::Class); + case PDB_UdtType::Struct: + return llvm::to_underlying(clang::TagTypeKind::Struct); + case PDB_UdtType::Union: + return llvm::to_underlying(clang::TagTypeKind::Union); + case PDB_UdtType::Interface: + return llvm::to_underlying(clang::TagTypeKind::Interface); + } + llvm_unreachable("unsuported PDB UDT type"); +} + +static lldb::Encoding TranslateBuiltinEncoding(PDB_BuiltinType type) { + switch (type) { + case PDB_BuiltinType::Float: + return lldb::eEncodingIEEE754; + case PDB_BuiltinType::Int: + case PDB_BuiltinType::Long: + case PDB_BuiltinType::Char: + return lldb::eEncodingSint; + case PDB_BuiltinType::Bool: + case PDB_BuiltinType::Char16: + case PDB_BuiltinType::Char32: + case PDB_BuiltinType::UInt: + case PDB_BuiltinType::ULong: + case PDB_BuiltinType::HResult: + case PDB_BuiltinType::WCharT: + return lldb::eEncodingUint; + default: + return lldb::eEncodingInvalid; + } +} + +static lldb::Encoding TranslateEnumEncoding(PDB_VariantType type) { + switch (type) { + case PDB_VariantType::Int8: + case PDB_VariantType::Int16: + case PDB_VariantType::Int32: + case PDB_VariantType::Int64: + return lldb::eEncodingSint; + + case PDB_VariantType::UInt8: + case PDB_VariantType::UInt16: + case PDB_VariantType::UInt32: + case PDB_VariantType::UInt64: + return lldb::eEncodingUint; + + default: + break; + } + + return lldb::eEncodingSint; +} + +static CompilerType +GetBuiltinTypeForPDBEncodingAndBitSize(TypeSystemClang &clang_ast, + const PDBSymbolTypeBuiltin &pdb_type, + Encoding encoding, uint32_t width) { + clang::ASTContext &ast = clang_ast.getASTContext(); + + switch (pdb_type.getBuiltinType()) { + default: + break; + case PDB_BuiltinType::None: + return CompilerType(); + case PDB_BuiltinType::Void: + return clang_ast.GetBasicType(eBasicTypeVoid); + case PDB_BuiltinType::Char: + return clang_ast.GetBasicType(eBasicTypeChar); + case PDB_BuiltinType::Bool: + return clang_ast.GetBasicType(eBasicTypeBool); + case PDB_BuiltinType::Long: + if (width == ast.getTypeSize(ast.LongTy)) + return CompilerType(clang_ast.weak_from_this(), + ast.LongTy.getAsOpaquePtr()); + if (width == ast.getTypeSize(ast.LongLongTy)) + return CompilerType(clang_ast.weak_from_this(), + ast.LongLongTy.getAsOpaquePtr()); + break; + case PDB_BuiltinType::ULong: + if (width == ast.getTypeSize(ast.UnsignedLongTy)) + return CompilerType(clang_ast.weak_from_this(), + ast.UnsignedLongTy.getAsOpaquePtr()); + if (width == ast.getTypeSize(ast.UnsignedLongLongTy)) + return CompilerType(clang_ast.weak_from_this(), + ast.UnsignedLongLongTy.getAsOpaquePtr()); + break; + case PDB_BuiltinType::WCharT: + if (width == ast.getTypeSize(ast.WCharTy)) + return CompilerType(clang_ast.weak_from_this(), + ast.WCharTy.getAsOpaquePtr()); + break; + case PDB_BuiltinType::Char16: + return CompilerType(clang_ast.weak_from_this(), + ast.Char16Ty.getAsOpaquePtr()); + case PDB_BuiltinType::Char32: + return CompilerType(clang_ast.weak_from_this(), + ast.Char32Ty.getAsOpaquePtr()); + case PDB_BuiltinType::Float: + // Note: types `long double` and `double` have same bit size in MSVC and + // there is no information in the PDB to distinguish them. So when falling + // back to default search, the compiler type of `long double` will be + // represented by the one generated for `double`. + break; + } + // If there is no match on PDB_BuiltinType, fall back to default search by + // encoding and width only + return clang_ast.GetBuiltinTypeForEncodingAndBitSize(encoding, width); +} + +static ConstString GetPDBBuiltinTypeName(const PDBSymbolTypeBuiltin &pdb_type, + CompilerType &compiler_type) { + PDB_BuiltinType kind = pdb_type.getBuiltinType(); + switch (kind) { + default: + break; + case PDB_BuiltinType::Currency: + return ConstString("CURRENCY"); + case PDB_BuiltinType::Date: + return ConstString("DATE"); + case PDB_BuiltinType::Variant: + return ConstString("VARIANT"); + case PDB_BuiltinType::Complex: + return ConstString("complex"); + case PDB_BuiltinType::Bitfield: + return ConstString("bitfield"); + case PDB_BuiltinType::BSTR: + return ConstString("BSTR"); + case PDB_BuiltinType::HResult: + return ConstString("HRESULT"); + case PDB_BuiltinType::BCD: + return ConstString("BCD"); + case PDB_BuiltinType::Char16: + return ConstString("char16_t"); + case PDB_BuiltinType::Char32: + return ConstString("char32_t"); + case PDB_BuiltinType::None: + return ConstString("..."); + } + return compiler_type.GetTypeName(); +} + +static bool AddSourceInfoToDecl(const PDBSymbol &symbol, Declaration &decl) { + auto &raw_sym = symbol.getRawSymbol(); + auto first_line_up = raw_sym.getSrcLineOnTypeDefn(); + + if (!first_line_up) { + auto lines_up = symbol.getSession().findLineNumbersByAddress( + raw_sym.getVirtualAddress(), raw_sym.getLength()); + if (!lines_up) + return false; + first_line_up = lines_up->getNext(); + if (!first_line_up) + return false; + } + uint32_t src_file_id = first_line_up->getSourceFileId(); + auto src_file_up = symbol.getSession().getSourceFileById(src_file_id); + if (!src_file_up) + return false; + + FileSpec spec(src_file_up->getFileName()); + decl.SetFile(spec); + decl.SetColumn(first_line_up->getColumnNumber()); + decl.SetLine(first_line_up->getLineNumber()); + return true; +} + +static AccessType TranslateMemberAccess(PDB_MemberAccess access) { + switch (access) { + case PDB_MemberAccess::Private: + return eAccessPrivate; + case PDB_MemberAccess::Protected: + return eAccessProtected; + case PDB_MemberAccess::Public: + return eAccessPublic; + } + return eAccessNone; +} + +static AccessType GetDefaultAccessibilityForUdtKind(PDB_UdtType udt_kind) { + switch (udt_kind) { + case PDB_UdtType::Struct: + case PDB_UdtType::Union: + return eAccessPublic; + case PDB_UdtType::Class: + case PDB_UdtType::Interface: + return eAccessPrivate; + } + llvm_unreachable("unsupported PDB UDT type"); +} + +static AccessType GetAccessibilityForUdt(const PDBSymbolTypeUDT &udt) { + AccessType access = TranslateMemberAccess(udt.getAccess()); + if (access != lldb::eAccessNone || !udt.isNested()) + return access; + + auto parent = udt.getClassParent(); + if (!parent) + return lldb::eAccessNone; + + auto parent_udt = llvm::dyn_cast<PDBSymbolTypeUDT>(parent.get()); + if (!parent_udt) + return lldb::eAccessNone; + + return GetDefaultAccessibilityForUdtKind(parent_udt->getUdtKind()); +} + +static clang::MSInheritanceAttr::Spelling +GetMSInheritance(const PDBSymbolTypeUDT &udt) { + int base_count = 0; + bool has_virtual = false; + + auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>(); + if (bases_enum) { + while (auto base = bases_enum->getNext()) { + base_count++; + has_virtual |= base->isVirtualBaseClass(); + } + } + + if (has_virtual) + return clang::MSInheritanceAttr::Keyword_virtual_inheritance; + if (base_count > 1) + return clang::MSInheritanceAttr::Keyword_multiple_inheritance; + return clang::MSInheritanceAttr::Keyword_single_inheritance; +} + +static std::unique_ptr<llvm::pdb::PDBSymbol> +GetClassOrFunctionParent(const llvm::pdb::PDBSymbol &symbol) { + const IPDBSession &session = symbol.getSession(); + const IPDBRawSymbol &raw = symbol.getRawSymbol(); + auto tag = symbol.getSymTag(); + + // For items that are nested inside of a class, return the class that it is + // nested inside of. + // Note that only certain items can be nested inside of classes. + switch (tag) { + case PDB_SymType::Function: + case PDB_SymType::Data: + case PDB_SymType::UDT: + case PDB_SymType::Enum: + case PDB_SymType::FunctionSig: + case PDB_SymType::Typedef: + case PDB_SymType::BaseClass: + case PDB_SymType::VTable: { + auto class_parent_id = raw.getClassParentId(); + if (auto class_parent = session.getSymbolById(class_parent_id)) + return class_parent; + break; + } + default: + break; + } + + // Otherwise, if it is nested inside of a function, return the function. + // Note that only certain items can be nested inside of functions. + switch (tag) { + case PDB_SymType::Block: + case PDB_SymType::Data: { + auto lexical_parent_id = raw.getLexicalParentId(); + auto lexical_parent = session.getSymbolById(lexical_parent_id); + if (!lexical_parent) + return nullptr; + + auto lexical_parent_tag = lexical_parent->getSymTag(); + if (lexical_parent_tag == PDB_SymType::Function) + return lexical_parent; + if (lexical_parent_tag == PDB_SymType::Exe) + return nullptr; + + return GetClassOrFunctionParent(*lexical_parent); + } + default: + return nullptr; + } +} + +static clang::NamedDecl * +GetDeclFromContextByName(const clang::ASTContext &ast, + const clang::DeclContext &decl_context, + llvm::StringRef name) { + clang::IdentifierInfo &ident = ast.Idents.get(name); + clang::DeclarationName decl_name = ast.DeclarationNames.getIdentifier(&ident); + clang::DeclContext::lookup_result result = decl_context.lookup(decl_name); + if (result.empty()) + return nullptr; + + return *result.begin(); +} + +static bool IsAnonymousNamespaceName(llvm::StringRef name) { + return name == "`anonymous namespace'" || name == "`anonymous-namespace'"; +} + +static clang::CallingConv TranslateCallingConvention(PDB_CallingConv pdb_cc) { + switch (pdb_cc) { + case llvm::codeview::CallingConvention::NearC: + return clang::CC_C; + case llvm::codeview::CallingConvention::NearStdCall: + return clang::CC_X86StdCall; + case llvm::codeview::CallingConvention::NearFast: + return clang::CC_X86FastCall; + case llvm::codeview::CallingConvention::ThisCall: + return clang::CC_X86ThisCall; + case llvm::codeview::CallingConvention::NearVector: + return clang::CC_X86VectorCall; + case llvm::codeview::CallingConvention::NearPascal: + return clang::CC_X86Pascal; + default: + assert(false && "Unknown calling convention"); + return clang::CC_C; + } +} + +PDBASTParser::PDBASTParser(lldb_private::TypeSystemClang &ast) : m_ast(ast) {} + +PDBASTParser::~PDBASTParser() = default; + +// DebugInfoASTParser interface + +lldb::TypeSP PDBASTParser::CreateLLDBTypeFromPDBType(const PDBSymbol &type) { + Declaration decl; + switch (type.getSymTag()) { + case PDB_SymType::BaseClass: { + auto symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + auto ty = symbol_file->ResolveTypeUID(type.getRawSymbol().getTypeId()); + return ty ? ty->shared_from_this() : nullptr; + } break; + case PDB_SymType::UDT: { + auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&type); + assert(udt); + + // Note that, unnamed UDT being typedef-ed is generated as a UDT symbol + // other than a Typedef symbol in PDB. For example, + // typedef union { short Row; short Col; } Union; + // is generated as a named UDT in PDB: + // union Union { short Row; short Col; } + // Such symbols will be handled here. + + // Some UDT with trival ctor has zero length. Just ignore. + if (udt->getLength() == 0) + return nullptr; + + // Ignore unnamed-tag UDTs. + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(udt->getName())); + if (name.empty()) + return nullptr; + + auto decl_context = GetDeclContextContainingSymbol(type); + + // Check if such an UDT already exists in the current context. + // This may occur with const or volatile types. There are separate type + // symbols in PDB for types with const or volatile modifiers, but we need + // to create only one declaration for them all. + Type::ResolveState type_resolve_state; + CompilerType clang_type = + m_ast.GetTypeForIdentifier<clang::CXXRecordDecl>(name, decl_context); + if (!clang_type.IsValid()) { + auto access = GetAccessibilityForUdt(*udt); + + auto tag_type_kind = TranslateUdtKind(udt->getUdtKind()); + + ClangASTMetadata metadata; + metadata.SetUserID(type.getSymIndexId()); + metadata.SetIsDynamicCXXType(false); + + clang_type = m_ast.CreateRecordType( + decl_context, OptionalClangModuleID(), access, name, tag_type_kind, + lldb::eLanguageTypeC_plus_plus, &metadata); + assert(clang_type.IsValid()); + + auto record_decl = + m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); + assert(record_decl); + m_uid_to_decl[type.getSymIndexId()] = record_decl; + + auto inheritance_attr = clang::MSInheritanceAttr::CreateImplicit( + m_ast.getASTContext(), GetMSInheritance(*udt)); + record_decl->addAttr(inheritance_attr); + + TypeSystemClang::StartTagDeclarationDefinition(clang_type); + + auto children = udt->findAllChildren(); + if (!children || children->getChildCount() == 0) { + // PDB does not have symbol of forwarder. We assume we get an udt w/o + // any fields. Just complete it at this point. + TypeSystemClang::CompleteTagDeclarationDefinition(clang_type); + + TypeSystemClang::SetHasExternalStorage(clang_type.GetOpaqueQualType(), + false); + + type_resolve_state = Type::ResolveState::Full; + } else { + // Add the type to the forward declarations. It will help us to avoid + // an endless recursion in CompleteTypeFromUdt function. + m_forward_decl_to_uid[record_decl] = type.getSymIndexId(); + + TypeSystemClang::SetHasExternalStorage(clang_type.GetOpaqueQualType(), + true); + + type_resolve_state = Type::ResolveState::Forward; + } + } else + type_resolve_state = Type::ResolveState::Forward; + + if (udt->isConstType()) + clang_type = clang_type.AddConstModifier(); + + if (udt->isVolatileType()) + clang_type = clang_type.AddVolatileModifier(); + + AddSourceInfoToDecl(type, decl); + return m_ast.GetSymbolFile()->MakeType( + type.getSymIndexId(), ConstString(name), udt->getLength(), nullptr, + LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, clang_type, + type_resolve_state); + } break; + case PDB_SymType::Enum: { + auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(&type); + assert(enum_type); + + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(enum_type->getName())); + auto decl_context = GetDeclContextContainingSymbol(type); + uint64_t bytes = enum_type->getLength(); + + // Check if such an enum already exists in the current context + CompilerType ast_enum = + m_ast.GetTypeForIdentifier<clang::EnumDecl>(name, decl_context); + if (!ast_enum.IsValid()) { + auto underlying_type_up = enum_type->getUnderlyingType(); + if (!underlying_type_up) + return nullptr; + + lldb::Encoding encoding = + TranslateBuiltinEncoding(underlying_type_up->getBuiltinType()); + // FIXME: Type of underlying builtin is always `Int`. We correct it with + // the very first enumerator's encoding if any. + auto first_child = enum_type->findOneChild<PDBSymbolData>(); + if (first_child) + encoding = TranslateEnumEncoding(first_child->getValue().Type); + + CompilerType builtin_type; + if (bytes > 0) + builtin_type = GetBuiltinTypeForPDBEncodingAndBitSize( + m_ast, *underlying_type_up, encoding, bytes * 8); + else + builtin_type = m_ast.GetBasicType(eBasicTypeInt); + + // FIXME: PDB does not have information about scoped enumeration (Enum + // Class). Set it false for now. + bool isScoped = false; + + ast_enum = m_ast.CreateEnumerationType(name, decl_context, + OptionalClangModuleID(), decl, + builtin_type, isScoped); + + auto enum_decl = TypeSystemClang::GetAsEnumDecl(ast_enum); + assert(enum_decl); + m_uid_to_decl[type.getSymIndexId()] = enum_decl; + + auto enum_values = enum_type->findAllChildren<PDBSymbolData>(); + if (enum_values) { + while (auto enum_value = enum_values->getNext()) { + if (enum_value->getDataKind() != PDB_DataKind::Constant) + continue; + AddEnumValue(ast_enum, *enum_value); + } + } + + if (TypeSystemClang::StartTagDeclarationDefinition(ast_enum)) + TypeSystemClang::CompleteTagDeclarationDefinition(ast_enum); + } + + if (enum_type->isConstType()) + ast_enum = ast_enum.AddConstModifier(); + + if (enum_type->isVolatileType()) + ast_enum = ast_enum.AddVolatileModifier(); + + AddSourceInfoToDecl(type, decl); + return m_ast.GetSymbolFile()->MakeType( + type.getSymIndexId(), ConstString(name), bytes, nullptr, + LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ast_enum, + lldb_private::Type::ResolveState::Full); + } break; + case PDB_SymType::Typedef: { + auto type_def = llvm::dyn_cast<PDBSymbolTypeTypedef>(&type); + assert(type_def); + + SymbolFile *symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + lldb_private::Type *target_type = + symbol_file->ResolveTypeUID(type_def->getTypeId()); + if (!target_type) + return nullptr; + + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(type_def->getName())); + auto decl_ctx = GetDeclContextContainingSymbol(type); + + // Check if such a typedef already exists in the current context + CompilerType ast_typedef = + m_ast.GetTypeForIdentifier<clang::TypedefNameDecl>(name, decl_ctx); + if (!ast_typedef.IsValid()) { + CompilerType target_ast_type = target_type->GetFullCompilerType(); + + ast_typedef = target_ast_type.CreateTypedef( + name.c_str(), m_ast.CreateDeclContext(decl_ctx), 0); + if (!ast_typedef) + return nullptr; + + auto typedef_decl = TypeSystemClang::GetAsTypedefDecl(ast_typedef); + assert(typedef_decl); + m_uid_to_decl[type.getSymIndexId()] = typedef_decl; + } + + if (type_def->isConstType()) + ast_typedef = ast_typedef.AddConstModifier(); + + if (type_def->isVolatileType()) + ast_typedef = ast_typedef.AddVolatileModifier(); + + AddSourceInfoToDecl(type, decl); + std::optional<uint64_t> size; + if (type_def->getLength()) + size = type_def->getLength(); + return m_ast.GetSymbolFile()->MakeType( + type_def->getSymIndexId(), ConstString(name), size, nullptr, + target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID, decl, + ast_typedef, lldb_private::Type::ResolveState::Full); + } break; + case PDB_SymType::Function: + case PDB_SymType::FunctionSig: { + std::string name; + PDBSymbolTypeFunctionSig *func_sig = nullptr; + if (auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(&type)) { + if (pdb_func->isCompilerGenerated()) + return nullptr; + + auto sig = pdb_func->getSignature(); + if (!sig) + return nullptr; + func_sig = sig.release(); + // Function type is named. + name = std::string( + MSVCUndecoratedNameParser::DropScope(pdb_func->getName())); + } else if (auto pdb_func_sig = + llvm::dyn_cast<PDBSymbolTypeFunctionSig>(&type)) { + func_sig = const_cast<PDBSymbolTypeFunctionSig *>(pdb_func_sig); + } else + llvm_unreachable("Unexpected PDB symbol!"); + + auto arg_enum = func_sig->getArguments(); + uint32_t num_args = arg_enum->getChildCount(); + std::vector<CompilerType> arg_list; + + bool is_variadic = func_sig->isCVarArgs(); + // Drop last variadic argument. + if (is_variadic) + --num_args; + for (uint32_t arg_idx = 0; arg_idx < num_args; arg_idx++) { + auto arg = arg_enum->getChildAtIndex(arg_idx); + if (!arg) + break; + + SymbolFile *symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + lldb_private::Type *arg_type = + symbol_file->ResolveTypeUID(arg->getSymIndexId()); + // If there's some error looking up one of the dependent types of this + // function signature, bail. + if (!arg_type) + return nullptr; + CompilerType arg_ast_type = arg_type->GetFullCompilerType(); + arg_list.push_back(arg_ast_type); + } + lldbassert(arg_list.size() <= num_args); + + auto pdb_return_type = func_sig->getReturnType(); + SymbolFile *symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + lldb_private::Type *return_type = + symbol_file->ResolveTypeUID(pdb_return_type->getSymIndexId()); + // If there's some error looking up one of the dependent types of this + // function signature, bail. + if (!return_type) + return nullptr; + CompilerType return_ast_type = return_type->GetFullCompilerType(); + uint32_t type_quals = 0; + if (func_sig->isConstType()) + type_quals |= clang::Qualifiers::Const; + if (func_sig->isVolatileType()) + type_quals |= clang::Qualifiers::Volatile; + auto cc = TranslateCallingConvention(func_sig->getCallingConvention()); + CompilerType func_sig_ast_type = + m_ast.CreateFunctionType(return_ast_type, arg_list.data(), + arg_list.size(), is_variadic, type_quals, cc); + + AddSourceInfoToDecl(type, decl); + return m_ast.GetSymbolFile()->MakeType( + type.getSymIndexId(), ConstString(name), std::nullopt, nullptr, + LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, + func_sig_ast_type, lldb_private::Type::ResolveState::Full); + } break; + case PDB_SymType::ArrayType: { + auto array_type = llvm::dyn_cast<PDBSymbolTypeArray>(&type); + assert(array_type); + uint32_t num_elements = array_type->getCount(); + uint32_t element_uid = array_type->getElementTypeId(); + std::optional<uint64_t> bytes; + if (uint64_t size = array_type->getLength()) + bytes = size; + + SymbolFile *symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + // If array rank > 0, PDB gives the element type at N=0. So element type + // will parsed in the order N=0, N=1,..., N=rank sequentially. + lldb_private::Type *element_type = symbol_file->ResolveTypeUID(element_uid); + if (!element_type) + return nullptr; + + CompilerType element_ast_type = element_type->GetForwardCompilerType(); + // If element type is UDT, it needs to be complete. + if (TypeSystemClang::IsCXXClassType(element_ast_type) && + !element_ast_type.GetCompleteType()) { + if (TypeSystemClang::StartTagDeclarationDefinition(element_ast_type)) { + TypeSystemClang::CompleteTagDeclarationDefinition(element_ast_type); + } else { + // We are not able to start definition. + return nullptr; + } + } + CompilerType array_ast_type = m_ast.CreateArrayType( + element_ast_type, num_elements, /*is_gnu_vector*/ false); + TypeSP type_sp = m_ast.GetSymbolFile()->MakeType( + array_type->getSymIndexId(), ConstString(), bytes, nullptr, + LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, + array_ast_type, lldb_private::Type::ResolveState::Full); + type_sp->SetEncodingType(element_type); + return type_sp; + } break; + case PDB_SymType::BuiltinType: { + auto *builtin_type = llvm::dyn_cast<PDBSymbolTypeBuiltin>(&type); + assert(builtin_type); + PDB_BuiltinType builtin_kind = builtin_type->getBuiltinType(); + if (builtin_kind == PDB_BuiltinType::None) + return nullptr; + + std::optional<uint64_t> bytes; + if (uint64_t size = builtin_type->getLength()) + bytes = size; + Encoding encoding = TranslateBuiltinEncoding(builtin_kind); + CompilerType builtin_ast_type = GetBuiltinTypeForPDBEncodingAndBitSize( + m_ast, *builtin_type, encoding, bytes.value_or(0) * 8); + + if (builtin_type->isConstType()) + builtin_ast_type = builtin_ast_type.AddConstModifier(); + + if (builtin_type->isVolatileType()) + builtin_ast_type = builtin_ast_type.AddVolatileModifier(); + + auto type_name = GetPDBBuiltinTypeName(*builtin_type, builtin_ast_type); + + return m_ast.GetSymbolFile()->MakeType( + builtin_type->getSymIndexId(), type_name, bytes, nullptr, + LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, + builtin_ast_type, lldb_private::Type::ResolveState::Full); + } break; + case PDB_SymType::PointerType: { + auto *pointer_type = llvm::dyn_cast<PDBSymbolTypePointer>(&type); + assert(pointer_type); + + SymbolFile *symbol_file = m_ast.GetSymbolFile(); + if (!symbol_file) + return nullptr; + + Type *pointee_type = symbol_file->ResolveTypeUID( + pointer_type->getPointeeType()->getSymIndexId()); + if (!pointee_type) + return nullptr; + + if (pointer_type->isPointerToDataMember() || + pointer_type->isPointerToMemberFunction()) { + auto class_parent_uid = pointer_type->getRawSymbol().getClassParentId(); + auto class_parent_type = symbol_file->ResolveTypeUID(class_parent_uid); + assert(class_parent_type); + + CompilerType pointer_ast_type; + pointer_ast_type = TypeSystemClang::CreateMemberPointerType( + class_parent_type->GetLayoutCompilerType(), + pointee_type->GetForwardCompilerType()); + assert(pointer_ast_type); + + return m_ast.GetSymbolFile()->MakeType( + pointer_type->getSymIndexId(), ConstString(), + pointer_type->getLength(), nullptr, LLDB_INVALID_UID, + lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type, + lldb_private::Type::ResolveState::Forward); + } + + CompilerType pointer_ast_type; + pointer_ast_type = pointee_type->GetFullCompilerType(); + if (pointer_type->isReference()) + pointer_ast_type = pointer_ast_type.GetLValueReferenceType(); + else if (pointer_type->isRValueReference()) + pointer_ast_type = pointer_ast_type.GetRValueReferenceType(); + else + pointer_ast_type = pointer_ast_type.GetPointerType(); + + if (pointer_type->isConstType()) + pointer_ast_type = pointer_ast_type.AddConstModifier(); + + if (pointer_type->isVolatileType()) + pointer_ast_type = pointer_ast_type.AddVolatileModifier(); + + if (pointer_type->isRestrictedType()) + pointer_ast_type = pointer_ast_type.AddRestrictModifier(); + + return m_ast.GetSymbolFile()->MakeType( + pointer_type->getSymIndexId(), ConstString(), pointer_type->getLength(), + nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, + pointer_ast_type, lldb_private::Type::ResolveState::Full); + } break; + default: + break; + } + return nullptr; +} + +bool PDBASTParser::CompleteTypeFromPDB( + lldb_private::CompilerType &compiler_type) { + if (GetClangASTImporter().CanImport(compiler_type)) + return GetClangASTImporter().CompleteType(compiler_type); + + // Remove the type from the forward declarations to avoid + // an endless recursion for types like a linked list. + clang::CXXRecordDecl *record_decl = + m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType()); + auto uid_it = m_forward_decl_to_uid.find(record_decl); + if (uid_it == m_forward_decl_to_uid.end()) + return true; + + auto symbol_file = static_cast<SymbolFilePDB *>( + m_ast.GetSymbolFile()->GetBackingSymbolFile()); + if (!symbol_file) + return false; + + std::unique_ptr<PDBSymbol> symbol = + symbol_file->GetPDBSession().getSymbolById(uid_it->getSecond()); + if (!symbol) + return false; + + m_forward_decl_to_uid.erase(uid_it); + + TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(), + false); + + switch (symbol->getSymTag()) { + case PDB_SymType::UDT: { + auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(symbol.get()); + if (!udt) + return false; + + return CompleteTypeFromUDT(*symbol_file, compiler_type, *udt); + } + default: + llvm_unreachable("not a forward clang type decl!"); + } +} + +clang::Decl * +PDBASTParser::GetDeclForSymbol(const llvm::pdb::PDBSymbol &symbol) { + uint32_t sym_id = symbol.getSymIndexId(); + auto it = m_uid_to_decl.find(sym_id); + if (it != m_uid_to_decl.end()) + return it->second; + + auto symbol_file = static_cast<SymbolFilePDB *>( + m_ast.GetSymbolFile()->GetBackingSymbolFile()); + if (!symbol_file) + return nullptr; + + // First of all, check if the symbol is a member of a class. Resolve the full + // class type and return the declaration from the cache if so. + auto tag = symbol.getSymTag(); + if (tag == PDB_SymType::Data || tag == PDB_SymType::Function) { + const IPDBSession &session = symbol.getSession(); + const IPDBRawSymbol &raw = symbol.getRawSymbol(); + + auto class_parent_id = raw.getClassParentId(); + if (std::unique_ptr<PDBSymbol> class_parent = + session.getSymbolById(class_parent_id)) { + auto class_parent_type = symbol_file->ResolveTypeUID(class_parent_id); + if (!class_parent_type) + return nullptr; + + CompilerType class_parent_ct = class_parent_type->GetFullCompilerType(); + + // Look a declaration up in the cache after completing the class + clang::Decl *decl = m_uid_to_decl.lookup(sym_id); + if (decl) + return decl; + + // A declaration was not found in the cache. It means that the symbol + // has the class parent, but the class doesn't have the symbol in its + // children list. + if (auto func = llvm::dyn_cast_or_null<PDBSymbolFunc>(&symbol)) { + // Try to find a class child method with the same RVA and use its + // declaration if found. + if (uint32_t rva = func->getRelativeVirtualAddress()) { + if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolFunc>> + methods_enum = + class_parent->findAllChildren<PDBSymbolFunc>()) { + while (std::unique_ptr<PDBSymbolFunc> method = + methods_enum->getNext()) { + if (method->getRelativeVirtualAddress() == rva) { + decl = m_uid_to_decl.lookup(method->getSymIndexId()); + if (decl) + break; + } + } + } + } + + // If no class methods with the same RVA were found, then create a new + // method. It is possible for template methods. + if (!decl) + decl = AddRecordMethod(*symbol_file, class_parent_ct, *func); + } + + if (decl) + m_uid_to_decl[sym_id] = decl; + + return decl; + } + } + + // If we are here, then the symbol is not belonging to a class and is not + // contained in the cache. So create a declaration for it. + switch (symbol.getSymTag()) { + case PDB_SymType::Data: { + auto data = llvm::dyn_cast<PDBSymbolData>(&symbol); + assert(data); + + auto decl_context = GetDeclContextContainingSymbol(symbol); + assert(decl_context); + + // May be the current context is a class really, but we haven't found + // any class parent. This happens e.g. in the case of class static + // variables - they has two symbols, one is a child of the class when + // another is a child of the exe. So always complete the parent and use + // an existing declaration if possible. + if (auto parent_decl = llvm::dyn_cast_or_null<clang::TagDecl>(decl_context)) + m_ast.GetCompleteDecl(parent_decl); + + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(data->getName())); + + // Check if the current context already contains the symbol with the name. + clang::Decl *decl = + GetDeclFromContextByName(m_ast.getASTContext(), *decl_context, name); + if (!decl) { + auto type = symbol_file->ResolveTypeUID(data->getTypeId()); + if (!type) + return nullptr; + + decl = m_ast.CreateVariableDeclaration( + decl_context, OptionalClangModuleID(), name.c_str(), + ClangUtil::GetQualType(type->GetLayoutCompilerType())); + } + + m_uid_to_decl[sym_id] = decl; + + return decl; + } + case PDB_SymType::Function: { + auto func = llvm::dyn_cast<PDBSymbolFunc>(&symbol); + assert(func); + + auto decl_context = GetDeclContextContainingSymbol(symbol); + assert(decl_context); + + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(func->getName())); + + Type *type = symbol_file->ResolveTypeUID(sym_id); + if (!type) + return nullptr; + + auto storage = func->isStatic() ? clang::StorageClass::SC_Static + : clang::StorageClass::SC_None; + + auto decl = m_ast.CreateFunctionDeclaration( + decl_context, OptionalClangModuleID(), name, + type->GetForwardCompilerType(), storage, func->hasInlineAttribute()); + + std::vector<clang::ParmVarDecl *> params; + if (std::unique_ptr<PDBSymbolTypeFunctionSig> sig = func->getSignature()) { + if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolTypeFunctionArg>> + arg_enum = sig->findAllChildren<PDBSymbolTypeFunctionArg>()) { + while (std::unique_ptr<PDBSymbolTypeFunctionArg> arg = + arg_enum->getNext()) { + Type *arg_type = symbol_file->ResolveTypeUID(arg->getTypeId()); + if (!arg_type) + continue; + + clang::ParmVarDecl *param = m_ast.CreateParameterDeclaration( + decl, OptionalClangModuleID(), nullptr, + arg_type->GetForwardCompilerType(), clang::SC_None, true); + if (param) + params.push_back(param); + } + } + } + if (params.size()) + m_ast.SetFunctionParameters(decl, params); + + m_uid_to_decl[sym_id] = decl; + + return decl; + } + default: { + // It's not a variable and not a function, check if it's a type + Type *type = symbol_file->ResolveTypeUID(sym_id); + if (!type) + return nullptr; + + return m_uid_to_decl.lookup(sym_id); + } + } +} + +clang::DeclContext * +PDBASTParser::GetDeclContextForSymbol(const llvm::pdb::PDBSymbol &symbol) { + if (symbol.getSymTag() == PDB_SymType::Function) { + clang::DeclContext *result = + llvm::dyn_cast_or_null<clang::FunctionDecl>(GetDeclForSymbol(symbol)); + + if (result) + m_decl_context_to_uid[result] = symbol.getSymIndexId(); + + return result; + } + + auto symbol_file = static_cast<SymbolFilePDB *>( + m_ast.GetSymbolFile()->GetBackingSymbolFile()); + if (!symbol_file) + return nullptr; + + auto type = symbol_file->ResolveTypeUID(symbol.getSymIndexId()); + if (!type) + return nullptr; + + clang::DeclContext *result = + m_ast.GetDeclContextForType(type->GetForwardCompilerType()); + + if (result) + m_decl_context_to_uid[result] = symbol.getSymIndexId(); + + return result; +} + +clang::DeclContext *PDBASTParser::GetDeclContextContainingSymbol( + const llvm::pdb::PDBSymbol &symbol) { + auto parent = GetClassOrFunctionParent(symbol); + while (parent) { + if (auto parent_context = GetDeclContextForSymbol(*parent)) + return parent_context; + + parent = GetClassOrFunctionParent(*parent); + } + + // We can't find any class or function parent of the symbol. So analyze + // the full symbol name. The symbol may be belonging to a namespace + // or function (or even to a class if it's e.g. a static variable symbol). + + // TODO: Make clang to emit full names for variables in namespaces + // (as MSVC does) + + std::string name(symbol.getRawSymbol().getName()); + MSVCUndecoratedNameParser parser(name); + llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); + if (specs.empty()) + return m_ast.GetTranslationUnitDecl(); + + auto symbol_file = static_cast<SymbolFilePDB *>( + m_ast.GetSymbolFile()->GetBackingSymbolFile()); + if (!symbol_file) + return m_ast.GetTranslationUnitDecl(); + + auto global = symbol_file->GetPDBSession().getGlobalScope(); + if (!global) + return m_ast.GetTranslationUnitDecl(); + + bool has_type_or_function_parent = false; + clang::DeclContext *curr_context = m_ast.GetTranslationUnitDecl(); + for (std::size_t i = 0; i < specs.size() - 1; i++) { + // Check if there is a function or a type with the current context's name. + if (std::unique_ptr<IPDBEnumSymbols> children_enum = global->findChildren( + PDB_SymType::None, specs[i].GetFullName(), NS_CaseSensitive)) { + while (IPDBEnumChildren<PDBSymbol>::ChildTypePtr child = + children_enum->getNext()) { + if (clang::DeclContext *child_context = + GetDeclContextForSymbol(*child)) { + // Note that `GetDeclContextForSymbol' retrieves + // a declaration context for functions and types only, + // so if we are here then `child_context' is guaranteed + // a function or a type declaration context. + has_type_or_function_parent = true; + curr_context = child_context; + } + } + } + + // If there were no functions or types above then retrieve a namespace with + // the current context's name. There can be no namespaces inside a function + // or a type. We check it to avoid fake namespaces such as `__l2': + // `N0::N1::CClass::PrivateFunc::__l2::InnerFuncStruct' + if (!has_type_or_function_parent) { + std::string namespace_name = std::string(specs[i].GetBaseName()); + const char *namespace_name_c_str = + IsAnonymousNamespaceName(namespace_name) ? nullptr + : namespace_name.data(); + clang::NamespaceDecl *namespace_decl = + m_ast.GetUniqueNamespaceDeclaration( + namespace_name_c_str, curr_context, OptionalClangModuleID()); + + m_parent_to_namespaces[curr_context].insert(namespace_decl); + m_namespaces.insert(namespace_decl); + + curr_context = namespace_decl; + } + } + + return curr_context; +} + +void PDBASTParser::ParseDeclsForDeclContext( + const clang::DeclContext *decl_context) { + auto symbol_file = static_cast<SymbolFilePDB *>( + m_ast.GetSymbolFile()->GetBackingSymbolFile()); + if (!symbol_file) + return; + + IPDBSession &session = symbol_file->GetPDBSession(); + auto symbol_up = + session.getSymbolById(m_decl_context_to_uid.lookup(decl_context)); + auto global_up = session.getGlobalScope(); + + PDBSymbol *symbol; + if (symbol_up) + symbol = symbol_up.get(); + else if (global_up) + symbol = global_up.get(); + else + return; + + if (auto children = symbol->findAllChildren()) + while (auto child = children->getNext()) + GetDeclForSymbol(*child); +} + +clang::NamespaceDecl * +PDBASTParser::FindNamespaceDecl(const clang::DeclContext *parent, + llvm::StringRef name) { + NamespacesSet *set; + if (parent) { + auto pit = m_parent_to_namespaces.find(parent); + if (pit == m_parent_to_namespaces.end()) + return nullptr; + + set = &pit->second; + } else { + set = &m_namespaces; + } + assert(set); + + for (clang::NamespaceDecl *namespace_decl : *set) + if (namespace_decl->getName() == name) + return namespace_decl; + + for (clang::NamespaceDecl *namespace_decl : *set) + if (namespace_decl->isAnonymousNamespace()) + return FindNamespaceDecl(namespace_decl, name); + + return nullptr; +} + +bool PDBASTParser::AddEnumValue(CompilerType enum_type, + const PDBSymbolData &enum_value) { + Declaration decl; + Variant v = enum_value.getValue(); + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(enum_value.getName())); + int64_t raw_value; + switch (v.Type) { + case PDB_VariantType::Int8: + raw_value = v.Value.Int8; + break; + case PDB_VariantType::Int16: + raw_value = v.Value.Int16; + break; + case PDB_VariantType::Int32: + raw_value = v.Value.Int32; + break; + case PDB_VariantType::Int64: + raw_value = v.Value.Int64; + break; + case PDB_VariantType::UInt8: + raw_value = v.Value.UInt8; + break; + case PDB_VariantType::UInt16: + raw_value = v.Value.UInt16; + break; + case PDB_VariantType::UInt32: + raw_value = v.Value.UInt32; + break; + case PDB_VariantType::UInt64: + raw_value = v.Value.UInt64; + break; + default: + return false; + } + CompilerType underlying_type = m_ast.GetEnumerationIntegerType(enum_type); + uint32_t byte_size = m_ast.getASTContext().getTypeSize( + ClangUtil::GetQualType(underlying_type)); + auto enum_constant_decl = m_ast.AddEnumerationValueToEnumerationType( + enum_type, decl, name.c_str(), raw_value, byte_size * 8); + if (!enum_constant_decl) + return false; + + m_uid_to_decl[enum_value.getSymIndexId()] = enum_constant_decl; + + return true; +} + +bool PDBASTParser::CompleteTypeFromUDT( + lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &compiler_type, + llvm::pdb::PDBSymbolTypeUDT &udt) { + ClangASTImporter::LayoutInfo layout_info; + layout_info.bit_size = udt.getLength() * 8; + + auto nested_enums = udt.findAllChildren<PDBSymbolTypeUDT>(); + if (nested_enums) + while (auto nested = nested_enums->getNext()) + symbol_file.ResolveTypeUID(nested->getSymIndexId()); + + auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>(); + if (bases_enum) + AddRecordBases(symbol_file, compiler_type, + TranslateUdtKind(udt.getUdtKind()), *bases_enum, + layout_info); + + auto members_enum = udt.findAllChildren<PDBSymbolData>(); + if (members_enum) + AddRecordMembers(symbol_file, compiler_type, *members_enum, layout_info); + + auto methods_enum = udt.findAllChildren<PDBSymbolFunc>(); + if (methods_enum) + AddRecordMethods(symbol_file, compiler_type, *methods_enum); + + m_ast.AddMethodOverridesForCXXRecordType(compiler_type.GetOpaqueQualType()); + TypeSystemClang::BuildIndirectFields(compiler_type); + TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type); + + clang::CXXRecordDecl *record_decl = + m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType()); + if (!record_decl) + return static_cast<bool>(compiler_type); + + GetClangASTImporter().SetRecordLayout(record_decl, layout_info); + + return static_cast<bool>(compiler_type); +} + +void PDBASTParser::AddRecordMembers( + lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + PDBDataSymbolEnumerator &members_enum, + lldb_private::ClangASTImporter::LayoutInfo &layout_info) { + while (auto member = members_enum.getNext()) { + if (member->isCompilerGenerated()) + continue; + + auto member_name = member->getName(); + + auto member_type = symbol_file.ResolveTypeUID(member->getTypeId()); + if (!member_type) + continue; + + auto member_comp_type = member_type->GetLayoutCompilerType(); + if (!member_comp_type.GetCompleteType()) { + symbol_file.GetObjectFile()->GetModule()->ReportError( + ":: Class '{0}' has a member '{1}' of type '{2}' " + "which does not have a complete definition.", + record_type.GetTypeName().GetCString(), member_name.c_str(), + member_comp_type.GetTypeName().GetCString()); + if (TypeSystemClang::StartTagDeclarationDefinition(member_comp_type)) + TypeSystemClang::CompleteTagDeclarationDefinition(member_comp_type); + } + + auto access = TranslateMemberAccess(member->getAccess()); + + switch (member->getDataKind()) { + case PDB_DataKind::Member: { + auto location_type = member->getLocationType(); + + auto bit_size = member->getLength(); + if (location_type == PDB_LocType::ThisRel) + bit_size *= 8; + + auto decl = TypeSystemClang::AddFieldToRecordType( + record_type, member_name.c_str(), member_comp_type, access, bit_size); + if (!decl) + continue; + + m_uid_to_decl[member->getSymIndexId()] = decl; + + auto offset = member->getOffset() * 8; + if (location_type == PDB_LocType::BitField) + offset += member->getBitPosition(); + + layout_info.field_offsets.insert(std::make_pair(decl, offset)); + + break; + } + case PDB_DataKind::StaticMember: { + auto decl = TypeSystemClang::AddVariableToRecordType( + record_type, member_name.c_str(), member_comp_type, access); + if (!decl) + continue; + + // Static constant members may be a const[expr] declaration. + // Query the symbol's value as the variable initializer if valid. + if (member_comp_type.IsConst()) { + auto value = member->getValue(); + if (value.Type == llvm::pdb::Empty) { + LLDB_LOG(GetLog(LLDBLog::AST), + "Class '{0}' has member '{1}' of type '{2}' with an unknown " + "constant size.", + record_type.GetTypeName(), member_name, + member_comp_type.GetTypeName()); + continue; + } + + clang::QualType qual_type = decl->getType(); + unsigned type_width = m_ast.getASTContext().getIntWidth(qual_type); + unsigned constant_width = value.getBitWidth(); + + if (qual_type->isIntegralOrEnumerationType()) { + if (type_width >= constant_width) { + TypeSystemClang::SetIntegerInitializerForVariable( + decl, value.toAPSInt().extOrTrunc(type_width)); + } else { + LLDB_LOG(GetLog(LLDBLog::AST), + "Class '{0}' has a member '{1}' of type '{2}' ({3} bits) " + "which resolves to a wider constant value ({4} bits). " + "Ignoring constant.", + record_type.GetTypeName(), member_name, + member_comp_type.GetTypeName(), type_width, + constant_width); + } + } else { + switch (member_comp_type.GetBasicTypeEnumeration()) { + case lldb::eBasicTypeFloat: + case lldb::eBasicTypeDouble: + case lldb::eBasicTypeLongDouble: + if (type_width == constant_width) { + TypeSystemClang::SetFloatingInitializerForVariable( + decl, value.toAPFloat()); + decl->setConstexpr(true); + } else { + LLDB_LOG(GetLog(LLDBLog::AST), + "Class '{0}' has a member '{1}' of type '{2}' ({3} " + "bits) which resolves to a constant value of mismatched " + "width ({4} bits). Ignoring constant.", + record_type.GetTypeName(), member_name, + member_comp_type.GetTypeName(), type_width, + constant_width); + } + break; + default: + break; + } + } + } + + m_uid_to_decl[member->getSymIndexId()] = decl; + + break; + } + default: + llvm_unreachable("unsupported PDB data kind"); + } + } +} + +void PDBASTParser::AddRecordBases( + lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, int record_kind, + PDBBaseClassSymbolEnumerator &bases_enum, + lldb_private::ClangASTImporter::LayoutInfo &layout_info) const { + std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> base_classes; + + while (auto base = bases_enum.getNext()) { + auto base_type = symbol_file.ResolveTypeUID(base->getTypeId()); + if (!base_type) + continue; + + auto base_comp_type = base_type->GetFullCompilerType(); + if (!base_comp_type.GetCompleteType()) { + symbol_file.GetObjectFile()->GetModule()->ReportError( + ":: Class '{0}' has a base class '{1}' " + "which does not have a complete definition.", + record_type.GetTypeName().GetCString(), + base_comp_type.GetTypeName().GetCString()); + if (TypeSystemClang::StartTagDeclarationDefinition(base_comp_type)) + TypeSystemClang::CompleteTagDeclarationDefinition(base_comp_type); + } + + auto access = TranslateMemberAccess(base->getAccess()); + + auto is_virtual = base->isVirtualBaseClass(); + + std::unique_ptr<clang::CXXBaseSpecifier> base_spec = + m_ast.CreateBaseClassSpecifier( + base_comp_type.GetOpaqueQualType(), access, is_virtual, + record_kind == llvm::to_underlying(clang::TagTypeKind::Class)); + lldbassert(base_spec); + + base_classes.push_back(std::move(base_spec)); + + if (is_virtual) + continue; + + auto decl = m_ast.GetAsCXXRecordDecl(base_comp_type.GetOpaqueQualType()); + if (!decl) + continue; + + auto offset = clang::CharUnits::fromQuantity(base->getOffset()); + layout_info.base_offsets.insert(std::make_pair(decl, offset)); + } + + m_ast.TransferBaseClasses(record_type.GetOpaqueQualType(), + std::move(base_classes)); +} + +void PDBASTParser::AddRecordMethods(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + PDBFuncSymbolEnumerator &methods_enum) { + while (std::unique_ptr<PDBSymbolFunc> method = methods_enum.getNext()) + if (clang::CXXMethodDecl *decl = + AddRecordMethod(symbol_file, record_type, *method)) + m_uid_to_decl[method->getSymIndexId()] = decl; +} + +clang::CXXMethodDecl * +PDBASTParser::AddRecordMethod(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + const llvm::pdb::PDBSymbolFunc &method) const { + std::string name = + std::string(MSVCUndecoratedNameParser::DropScope(method.getName())); + + Type *method_type = symbol_file.ResolveTypeUID(method.getSymIndexId()); + // MSVC specific __vecDelDtor. + if (!method_type) + return nullptr; + + CompilerType method_comp_type = method_type->GetFullCompilerType(); + if (!method_comp_type.GetCompleteType()) { + symbol_file.GetObjectFile()->GetModule()->ReportError( + ":: Class '{0}' has a method '{1}' whose type cannot be completed.", + record_type.GetTypeName().GetCString(), + method_comp_type.GetTypeName().GetCString()); + if (TypeSystemClang::StartTagDeclarationDefinition(method_comp_type)) + TypeSystemClang::CompleteTagDeclarationDefinition(method_comp_type); + } + + AccessType access = TranslateMemberAccess(method.getAccess()); + if (access == eAccessNone) + access = eAccessPublic; + + // TODO: get mangled name for the method. + return m_ast.AddMethodToCXXRecordType( + record_type.GetOpaqueQualType(), name.c_str(), + /*mangled_name*/ nullptr, method_comp_type, access, method.isVirtual(), + method.isStatic(), method.hasInlineAttribute(), + /*is_explicit*/ false, // FIXME: Need this field in CodeView. + /*is_attr_used*/ false, + /*is_artificial*/ method.isCompilerGenerated()); +} diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h new file mode 100644 index 000000000000..06f317f4c4d9 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h @@ -0,0 +1,116 @@ +//===-- PDBASTParser.h ------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_PDBASTPARSER_H +#define LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_PDBASTPARSER_H + +#include "lldb/lldb-forward.h" + +#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" + +class SymbolFilePDB; + +namespace clang { +class CharUnits; +class CXXRecordDecl; +class FieldDecl; +class RecordDecl; +} // namespace clang + +namespace lldb_private { +class TypeSystemClang; +class CompilerType; +} // namespace lldb_private + +namespace llvm { +namespace pdb { +template <typename ChildType> class ConcreteSymbolEnumerator; + +class PDBSymbol; +class PDBSymbolData; +class PDBSymbolFunc; +class PDBSymbolTypeBaseClass; +class PDBSymbolTypeBuiltin; +class PDBSymbolTypeUDT; +} // namespace pdb +} // namespace llvm + +class PDBASTParser { +public: + PDBASTParser(lldb_private::TypeSystemClang &ast); + ~PDBASTParser(); + + lldb::TypeSP CreateLLDBTypeFromPDBType(const llvm::pdb::PDBSymbol &type); + bool CompleteTypeFromPDB(lldb_private::CompilerType &compiler_type); + + clang::Decl *GetDeclForSymbol(const llvm::pdb::PDBSymbol &symbol); + + clang::DeclContext * + GetDeclContextForSymbol(const llvm::pdb::PDBSymbol &symbol); + clang::DeclContext * + GetDeclContextContainingSymbol(const llvm::pdb::PDBSymbol &symbol); + + void ParseDeclsForDeclContext(const clang::DeclContext *decl_context); + + clang::NamespaceDecl *FindNamespaceDecl(const clang::DeclContext *parent, + llvm::StringRef name); + + lldb_private::ClangASTImporter &GetClangASTImporter() { + return m_ast_importer; + } + +private: + typedef llvm::DenseMap<clang::CXXRecordDecl *, lldb::user_id_t> + CXXRecordDeclToUidMap; + typedef llvm::DenseMap<lldb::user_id_t, clang::Decl *> UidToDeclMap; + typedef std::set<clang::NamespaceDecl *> NamespacesSet; + typedef llvm::DenseMap<clang::DeclContext *, NamespacesSet> + ParentToNamespacesMap; + typedef llvm::DenseMap<clang::DeclContext *, lldb::user_id_t> + DeclContextToUidMap; + typedef llvm::pdb::ConcreteSymbolEnumerator<llvm::pdb::PDBSymbolData> + PDBDataSymbolEnumerator; + typedef llvm::pdb::ConcreteSymbolEnumerator<llvm::pdb::PDBSymbolTypeBaseClass> + PDBBaseClassSymbolEnumerator; + typedef llvm::pdb::ConcreteSymbolEnumerator<llvm::pdb::PDBSymbolFunc> + PDBFuncSymbolEnumerator; + + bool AddEnumValue(lldb_private::CompilerType enum_type, + const llvm::pdb::PDBSymbolData &data); + bool CompleteTypeFromUDT(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &compiler_type, + llvm::pdb::PDBSymbolTypeUDT &udt); + void + AddRecordMembers(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + PDBDataSymbolEnumerator &members_enum, + lldb_private::ClangASTImporter::LayoutInfo &layout_info); + void + AddRecordBases(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, int record_kind, + PDBBaseClassSymbolEnumerator &bases_enum, + lldb_private::ClangASTImporter::LayoutInfo &layout_info) const; + void AddRecordMethods(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + PDBFuncSymbolEnumerator &methods_enum); + clang::CXXMethodDecl * + AddRecordMethod(lldb_private::SymbolFile &symbol_file, + lldb_private::CompilerType &record_type, + const llvm::pdb::PDBSymbolFunc &method) const; + + lldb_private::TypeSystemClang &m_ast; + lldb_private::ClangASTImporter m_ast_importer; + + CXXRecordDeclToUidMap m_forward_decl_to_uid; + UidToDeclMap m_uid_to_decl; + ParentToNamespacesMap m_parent_to_namespaces; + NamespacesSet m_namespaces; + DeclContextToUidMap m_decl_context_to_uid; +}; + +#endif // LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_PDBASTPARSER_H diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp new file mode 100644 index 000000000000..95add31385df --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.cpp @@ -0,0 +1,182 @@ +//===-- PDBLocationToDWARFExpression.cpp ----------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "PDBLocationToDWARFExpression.h" + +#include "lldb/Core/Section.h" +#include "lldb/Core/dwarf.h" +#include "lldb/Expression/DWARFExpression.h" +#include "lldb/Symbol/Variable.h" +#include "lldb/Utility/DataBufferHeap.h" +#include "lldb/Utility/StreamBuffer.h" + +#include "llvm/DebugInfo/CodeView/CodeView.h" +#include "llvm/DebugInfo/PDB/IPDBSession.h" +#include "llvm/DebugInfo/PDB/PDBSymbolData.h" + +#include "Plugins/SymbolFile/NativePDB/CodeViewRegisterMapping.h" +#include "Plugins/SymbolFile/NativePDB/PdbFPOProgramToDWARFExpression.h" + +using namespace lldb; +using namespace lldb_private; +using namespace lldb_private::npdb; +using namespace lldb_private::dwarf; +using namespace llvm::pdb; + +static std::unique_ptr<IPDBFrameData> +GetCorrespondingFrameData(const IPDBSession &session, + const Variable::RangeList &ranges) { + auto enumFrameData = session.getFrameData(); + if (!enumFrameData) + return nullptr; + + std::unique_ptr<IPDBFrameData> found; + while (auto fd = enumFrameData->getNext()) { + Range<lldb::addr_t, lldb::addr_t> fdRange(fd->getVirtualAddress(), + fd->getLengthBlock()); + + for (size_t i = 0; i < ranges.GetSize(); i++) { + auto range = ranges.GetEntryAtIndex(i); + if (!range) + continue; + + if (!range->DoesIntersect(fdRange)) + continue; + + found = std::move(fd); + + break; + } + } + + return found; +} + +static bool EmitVFrameEvaluationDWARFExpression( + llvm::StringRef program, llvm::Triple::ArchType arch_type, Stream &stream) { + // VFrame value always stored in $TO pseudo-register + return TranslateFPOProgramToDWARFExpression(program, "$T0", arch_type, + stream); +} + +DWARFExpression ConvertPDBLocationToDWARFExpression( + ModuleSP module, const PDBSymbolData &symbol, + const Variable::RangeList &ranges, bool &is_constant) { + is_constant = true; + + if (!module) + return DWARFExpression(); + + const ArchSpec &architecture = module->GetArchitecture(); + llvm::Triple::ArchType arch_type = architecture.GetMachine(); + ByteOrder byte_order = architecture.GetByteOrder(); + uint32_t address_size = architecture.GetAddressByteSize(); + uint32_t byte_size = architecture.GetDataByteSize(); + if (byte_order == eByteOrderInvalid || address_size == 0) + return DWARFExpression(); + + RegisterKind register_kind = eRegisterKindDWARF; + StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); + switch (symbol.getLocationType()) { + case PDB_LocType::Static: + case PDB_LocType::TLS: { + stream.PutHex8(DW_OP_addr); + + SectionList *section_list = module->GetSectionList(); + if (!section_list) + return DWARFExpression(); + + uint32_t section_id = symbol.getAddressSection(); + + auto section = section_list->FindSectionByID(section_id); + if (!section) + return DWARFExpression(); + + uint32_t offset = symbol.getAddressOffset(); + stream.PutMaxHex64(section->GetFileAddress() + offset, address_size, + byte_order); + + is_constant = false; + + break; + } + case PDB_LocType::RegRel: { + uint32_t reg_num; + auto reg_id = symbol.getRegisterId(); + if (reg_id == llvm::codeview::RegisterId::VFRAME) { + if (auto fd = GetCorrespondingFrameData(symbol.getSession(), ranges)) { + if (EmitVFrameEvaluationDWARFExpression(fd->getProgram(), arch_type, + stream)) { + int32_t offset = symbol.getOffset(); + stream.PutHex8(DW_OP_consts); + stream.PutSLEB128(offset); + stream.PutHex8(DW_OP_plus); + + register_kind = eRegisterKindLLDB; + + is_constant = false; + break; + } + } + + register_kind = eRegisterKindGeneric; + reg_num = LLDB_REGNUM_GENERIC_FP; + } else { + register_kind = eRegisterKindLLDB; + reg_num = GetLLDBRegisterNumber(arch_type, reg_id); + if (reg_num == LLDB_INVALID_REGNUM) + return DWARFExpression(); + } + + if (reg_num > 31) { + stream.PutHex8(DW_OP_bregx); + stream.PutULEB128(reg_num); + } else + stream.PutHex8(DW_OP_breg0 + reg_num); + + int32_t offset = symbol.getOffset(); + stream.PutSLEB128(offset); + + is_constant = false; + + break; + } + case PDB_LocType::Enregistered: { + register_kind = eRegisterKindLLDB; + uint32_t reg_num = GetLLDBRegisterNumber(arch_type, symbol.getRegisterId()); + if (reg_num == LLDB_INVALID_REGNUM) + return DWARFExpression(); + + if (reg_num > 31) { + stream.PutHex8(DW_OP_regx); + stream.PutULEB128(reg_num); + } else + stream.PutHex8(DW_OP_reg0 + reg_num); + + is_constant = false; + + break; + } + case PDB_LocType::Constant: { + Variant value = symbol.getValue(); + stream.PutRawBytes(&value.Value, sizeof(value.Value), + endian::InlHostByteOrder()); + break; + } + default: + return DWARFExpression(); + } + + DataBufferSP buffer = + std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize()); + DataExtractor extractor(buffer, byte_order, address_size, byte_size); + DWARFExpression result(extractor); + result.SetRegisterKind(register_kind); + + return result; +} diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h new file mode 100644 index 000000000000..fd0fef03e2c8 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h @@ -0,0 +1,47 @@ +//===-- PDBLocationToDWARFExpression.h --------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_PDBLOCATIONTODWARFEXPRESSION_H +#define LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_PDBLOCATIONTODWARFEXPRESSION_H + +#include "lldb/Core/Module.h" +#include "lldb/Symbol/Variable.h" + +namespace lldb_private { +class DWARFExpression; +} + +namespace llvm { +namespace pdb { +class PDBSymbolData; +} +} // namespace llvm + +/// Converts a location information from a PDB symbol to a DWARF expression +/// +/// \param[in] module +/// The module \a symbol belongs to. +/// +/// \param[in] symbol +/// The symbol with a location information to convert. +/// +/// \param[in] ranges +/// Ranges where this variable is valid. +/// +/// \param[out] is_constant +/// Set to \b true if the result expression is a constant value data, +/// and \b false if it is a DWARF bytecode. +/// +/// \return +/// The DWARF expression corresponding to the location data of \a symbol. +lldb_private::DWARFExpression +ConvertPDBLocationToDWARFExpression(lldb::ModuleSP module, + const llvm::pdb::PDBSymbolData &symbol, + const lldb_private::Variable::RangeList &ranges, + bool &is_constant); +#endif diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp new file mode 100644 index 000000000000..9a282acae91f --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp @@ -0,0 +1,2053 @@ +//===-- SymbolFilePDB.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "SymbolFilePDB.h" + +#include "PDBASTParser.h" +#include "PDBLocationToDWARFExpression.h" + +#include "clang/Lex/Lexer.h" + +#include "Plugins/TypeSystem/Clang/TypeSystemClang.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/LineTable.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Symbol/SymbolVendor.h" +#include "lldb/Symbol/TypeList.h" +#include "lldb/Symbol/TypeMap.h" +#include "lldb/Symbol/Variable.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/RegularExpression.h" + +#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h" +#include "llvm/DebugInfo/PDB/GenericError.h" +#include "llvm/DebugInfo/PDB/IPDBDataStream.h" +#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" +#include "llvm/DebugInfo/PDB/IPDBLineNumber.h" +#include "llvm/DebugInfo/PDB/IPDBSectionContrib.h" +#include "llvm/DebugInfo/PDB/IPDBSourceFile.h" +#include "llvm/DebugInfo/PDB/IPDBTable.h" +#include "llvm/DebugInfo/PDB/PDBSymbol.h" +#include "llvm/DebugInfo/PDB/PDBSymbolBlock.h" +#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h" +#include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h" +#include "llvm/DebugInfo/PDB/PDBSymbolData.h" +#include "llvm/DebugInfo/PDB/PDBSymbolExe.h" +#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" +#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" +#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" +#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" +#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" + +#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" +#include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" +#include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h" + +#if defined(_WIN32) +#include "llvm/Config/llvm-config.h" +#include <optional> +#endif + +using namespace lldb; +using namespace lldb_private; +using namespace llvm::pdb; + +LLDB_PLUGIN_DEFINE(SymbolFilePDB) + +char SymbolFilePDB::ID; + +namespace { +lldb::LanguageType TranslateLanguage(PDB_Lang lang) { + switch (lang) { + case PDB_Lang::Cpp: + return lldb::LanguageType::eLanguageTypeC_plus_plus; + case PDB_Lang::C: + return lldb::LanguageType::eLanguageTypeC; + case PDB_Lang::Swift: + return lldb::LanguageType::eLanguageTypeSwift; + case PDB_Lang::Rust: + return lldb::LanguageType::eLanguageTypeRust; + case PDB_Lang::ObjC: + return lldb::LanguageType::eLanguageTypeObjC; + case PDB_Lang::ObjCpp: + return lldb::LanguageType::eLanguageTypeObjC_plus_plus; + default: + return lldb::LanguageType::eLanguageTypeUnknown; + } +} + +bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line, + uint32_t addr_length) { + return ((requested_line == 0 || actual_line == requested_line) && + addr_length > 0); +} +} // namespace + +static bool ShouldUseNativeReader() { +#if defined(_WIN32) +#if LLVM_ENABLE_DIA_SDK + llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER"); + if (!use_native.equals_insensitive("on") && + !use_native.equals_insensitive("yes") && + !use_native.equals_insensitive("1") && + !use_native.equals_insensitive("true")) + return false; +#endif +#endif + return true; +} + +void SymbolFilePDB::Initialize() { + if (ShouldUseNativeReader()) { + npdb::SymbolFileNativePDB::Initialize(); + } else { + PluginManager::RegisterPlugin(GetPluginNameStatic(), + GetPluginDescriptionStatic(), CreateInstance, + DebuggerInitialize); + } +} + +void SymbolFilePDB::Terminate() { + if (ShouldUseNativeReader()) { + npdb::SymbolFileNativePDB::Terminate(); + } else { + PluginManager::UnregisterPlugin(CreateInstance); + } +} + +void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {} + +llvm::StringRef SymbolFilePDB::GetPluginDescriptionStatic() { + return "Microsoft PDB debug symbol file reader."; +} + +lldb_private::SymbolFile * +SymbolFilePDB::CreateInstance(ObjectFileSP objfile_sp) { + return new SymbolFilePDB(std::move(objfile_sp)); +} + +SymbolFilePDB::SymbolFilePDB(lldb::ObjectFileSP objfile_sp) + : SymbolFileCommon(std::move(objfile_sp)), m_session_up(), m_global_scope_up() {} + +SymbolFilePDB::~SymbolFilePDB() = default; + +uint32_t SymbolFilePDB::CalculateAbilities() { + uint32_t abilities = 0; + if (!m_objfile_sp) + return 0; + + if (!m_session_up) { + // Lazily load and match the PDB file, but only do this once. + std::string exePath = m_objfile_sp->GetFileSpec().GetPath(); + auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath), + m_session_up); + if (error) { + llvm::consumeError(std::move(error)); + auto module_sp = m_objfile_sp->GetModule(); + if (!module_sp) + return 0; + // See if any symbol file is specified through `--symfile` option. + FileSpec symfile = module_sp->GetSymbolFileFileSpec(); + if (!symfile) + return 0; + error = loadDataForPDB(PDB_ReaderType::DIA, + llvm::StringRef(symfile.GetPath()), m_session_up); + if (error) { + llvm::consumeError(std::move(error)); + return 0; + } + } + } + if (!m_session_up) + return 0; + + auto enum_tables_up = m_session_up->getEnumTables(); + if (!enum_tables_up) + return 0; + while (auto table_up = enum_tables_up->getNext()) { + if (table_up->getItemCount() == 0) + continue; + auto type = table_up->getTableType(); + switch (type) { + case PDB_TableType::Symbols: + // This table represents a store of symbols with types listed in + // PDBSym_Type + abilities |= (CompileUnits | Functions | Blocks | GlobalVariables | + LocalVariables | VariableTypes); + break; + case PDB_TableType::LineNumbers: + abilities |= LineTables; + break; + default: + break; + } + } + return abilities; +} + +void SymbolFilePDB::InitializeObject() { + lldb::addr_t obj_load_address = + m_objfile_sp->GetBaseAddress().GetFileAddress(); + lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS); + m_session_up->setLoadAddress(obj_load_address); + if (!m_global_scope_up) + m_global_scope_up = m_session_up->getGlobalScope(); + lldbassert(m_global_scope_up.get()); +} + +uint32_t SymbolFilePDB::CalculateNumCompileUnits() { + auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); + if (!compilands) + return 0; + + // The linker could link *.dll (compiland language = LINK), or import + // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be + // found as a child of the global scope (PDB executable). Usually, such + // compilands contain `thunk` symbols in which we are not interested for + // now. However we still count them in the compiland list. If we perform + // any compiland related activity, like finding symbols through + // llvm::pdb::IPDBSession methods, such compilands will all be searched + // automatically no matter whether we include them or not. + uint32_t compile_unit_count = compilands->getChildCount(); + + // The linker can inject an additional "dummy" compilation unit into the + // PDB. Ignore this special compile unit for our purposes, if it is there. + // It is always the last one. + auto last_compiland_up = compilands->getChildAtIndex(compile_unit_count - 1); + lldbassert(last_compiland_up.get()); + std::string name = last_compiland_up->getName(); + if (name == "* Linker *") + --compile_unit_count; + return compile_unit_count; +} + +void SymbolFilePDB::GetCompileUnitIndex( + const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) { + auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); + if (!results_up) + return; + auto uid = pdb_compiland.getSymIndexId(); + for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) { + auto compiland_up = results_up->getChildAtIndex(cu_idx); + if (!compiland_up) + continue; + if (compiland_up->getSymIndexId() == uid) { + index = cu_idx; + return; + } + } + index = UINT32_MAX; +} + +std::unique_ptr<llvm::pdb::PDBSymbolCompiland> +SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) { + return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid); +} + +lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) { + if (index >= GetNumCompileUnits()) + return CompUnitSP(); + + // Assuming we always retrieve same compilands listed in same order through + // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a + // compile unit makes no sense. + auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); + if (!results) + return CompUnitSP(); + auto compiland_up = results->getChildAtIndex(index); + if (!compiland_up) + return CompUnitSP(); + return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index); +} + +lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); + if (!compiland_up) + return lldb::eLanguageTypeUnknown; + auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>(); + if (!details) + return lldb::eLanguageTypeUnknown; + return TranslateLanguage(details->getLanguage()); +} + +lldb_private::Function * +SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func, + CompileUnit &comp_unit) { + if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId())) + return result.get(); + + auto file_vm_addr = pdb_func.getVirtualAddress(); + if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) + return nullptr; + + auto func_length = pdb_func.getLength(); + AddressRange func_range = + AddressRange(file_vm_addr, func_length, + GetObjectFile()->GetModule()->GetSectionList()); + if (!func_range.GetBaseAddress().IsValid()) + return nullptr; + + lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId()); + if (!func_type) + return nullptr; + + user_id_t func_type_uid = pdb_func.getSignatureId(); + + Mangled mangled = GetMangledForPDBFunc(pdb_func); + + FunctionSP func_sp = + std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(), + func_type_uid, mangled, func_type, func_range); + + comp_unit.AddFunction(func_sp); + + LanguageType lang = ParseLanguage(comp_unit); + auto type_system_or_err = GetTypeSystemForLanguage(lang); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to parse PDBFunc: {0}"); + return nullptr; + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_type_system = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_type_system) + return nullptr; + clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func); + + return func_sp.get(); +} + +size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + size_t func_added = 0; + auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); + if (!compiland_up) + return 0; + auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>(); + if (!results_up) + return 0; + while (auto pdb_func_up = results_up->getNext()) { + auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId()); + if (!func_sp) { + if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit)) + ++func_added; + } + } + return func_added; +} + +bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + if (comp_unit.GetLineTable()) + return true; + return ParseCompileUnitLineTable(comp_unit, 0); +} + +bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) { + // PDB doesn't contain information about macros + return false; +} + +bool SymbolFilePDB::ParseSupportFiles( + CompileUnit &comp_unit, lldb_private::SupportFileList &support_files) { + + // In theory this is unnecessary work for us, because all of this information + // is easily (and quickly) accessible from DebugInfoPDB, so caching it a + // second time seems like a waste. Unfortunately, there's no good way around + // this short of a moderate refactor since SymbolVendor depends on being able + // to cache this list. + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); + if (!compiland_up) + return false; + auto files = m_session_up->getSourceFilesForCompiland(*compiland_up); + if (!files || files->getChildCount() == 0) + return false; + + while (auto file = files->getNext()) { + FileSpec spec(file->getFileName(), FileSpec::Style::windows); + support_files.AppendIfUnique(spec); + } + + return true; +} + +bool SymbolFilePDB::ParseImportedModules( + const lldb_private::SymbolContext &sc, + std::vector<SourceModule> &imported_modules) { + // PDB does not yet support module debug info + return false; +} + +static size_t ParseFunctionBlocksForPDBSymbol( + uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol, + lldb_private::Block *parent_block, bool is_top_parent) { + assert(pdb_symbol && parent_block); + + size_t num_added = 0; + switch (pdb_symbol->getSymTag()) { + case PDB_SymType::Block: + case PDB_SymType::Function: { + Block *block = nullptr; + auto &raw_sym = pdb_symbol->getRawSymbol(); + if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) { + if (pdb_func->hasNoInlineAttribute()) + break; + if (is_top_parent) + block = parent_block; + else + break; + } else if (llvm::isa<PDBSymbolBlock>(pdb_symbol)) { + auto uid = pdb_symbol->getSymIndexId(); + if (parent_block->FindBlockByID(uid)) + break; + if (raw_sym.getVirtualAddress() < func_file_vm_addr) + break; + + auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId()); + parent_block->AddChild(block_sp); + block = block_sp.get(); + } else + llvm_unreachable("Unexpected PDB symbol!"); + + block->AddRange(Block::Range( + raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength())); + block->FinalizeRanges(); + ++num_added; + + auto results_up = pdb_symbol->findAllChildren(); + if (!results_up) + break; + while (auto symbol_up = results_up->getNext()) { + num_added += ParseFunctionBlocksForPDBSymbol( + func_file_vm_addr, symbol_up.get(), block, false); + } + } break; + default: + break; + } + return num_added; +} + +size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + size_t num_added = 0; + auto uid = func.GetID(); + auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid); + if (!pdb_func_up) + return 0; + Block &parent_block = func.GetBlock(false); + num_added = ParseFunctionBlocksForPDBSymbol( + pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true); + return num_added; +} + +size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + + size_t num_added = 0; + auto compiland = GetPDBCompilandByUID(comp_unit.GetID()); + if (!compiland) + return 0; + + auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) { + std::unique_ptr<IPDBEnumSymbols> results; + PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef, + PDB_SymType::UDT}; + for (auto tag : tags_to_search) { + results = raw_sym.findAllChildren(tag); + if (!results || results->getChildCount() == 0) + continue; + while (auto symbol = results->getNext()) { + switch (symbol->getSymTag()) { + case PDB_SymType::Enum: + case PDB_SymType::UDT: + case PDB_SymType::Typedef: + break; + default: + continue; + } + + // This should cause the type to get cached and stored in the `m_types` + // lookup. + if (auto type = ResolveTypeUID(symbol->getSymIndexId())) { + // Resolve the type completely to avoid a completion + // (and so a list change, which causes an iterators invalidation) + // during a TypeList dumping + type->GetFullCompilerType(); + ++num_added; + } + } + } + }; + + ParseTypesByTagFn(*compiland); + + // Also parse global types particularly coming from this compiland. + // Unfortunately, PDB has no compiland information for each global type. We + // have to parse them all. But ensure we only do this once. + static bool parse_all_global_types = false; + if (!parse_all_global_types) { + ParseTypesByTagFn(*m_global_scope_up); + parse_all_global_types = true; + } + return num_added; +} + +size_t +SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + if (!sc.comp_unit) + return 0; + + size_t num_added = 0; + if (sc.function) { + auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>( + sc.function->GetID()); + if (!pdb_func) + return 0; + + num_added += ParseVariables(sc, *pdb_func); + sc.function->GetBlock(false).SetDidParseVariables(true, true); + } else if (sc.comp_unit) { + auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID()); + if (!compiland) + return 0; + + if (sc.comp_unit->GetVariableList(false)) + return 0; + + auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); + if (results && results->getChildCount()) { + while (auto result = results->getNext()) { + auto cu_id = GetCompilandId(*result); + // FIXME: We are not able to determine variable's compile unit. + if (cu_id == 0) + continue; + + if (cu_id == sc.comp_unit->GetID()) + num_added += ParseVariables(sc, *result); + } + } + + // FIXME: A `file static` or `global constant` variable appears both in + // compiland's children and global scope's children with unexpectedly + // different symbol's Id making it ambiguous. + + // FIXME: 'local constant', for example, const char var[] = "abc", declared + // in a function scope, can't be found in PDB. + + // Parse variables in this compiland. + num_added += ParseVariables(sc, *compiland); + } + + return num_added; +} + +lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + auto find_result = m_types.find(type_uid); + if (find_result != m_types.end()) + return find_result->second.get(); + + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to ResolveTypeUID: {0}"); + return nullptr; + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_type_system = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_type_system) + return nullptr; + PDBASTParser *pdb = clang_type_system->GetPDBParser(); + if (!pdb) + return nullptr; + + auto pdb_type = m_session_up->getSymbolById(type_uid); + if (pdb_type == nullptr) + return nullptr; + + lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type); + if (result) { + m_types.insert(std::make_pair(type_uid, result)); + } + return result.get(); +} + +std::optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID( + lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { + return std::nullopt; +} + +bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) { + std::lock_guard<std::recursive_mutex> guard( + GetObjectFile()->GetModule()->GetMutex()); + + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to get dynamic array info for UID: {0}"); + return false; + } + auto ts = *type_system_or_err; + TypeSystemClang *clang_ast_ctx = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + + if (!clang_ast_ctx) + return false; + + PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); + if (!pdb) + return false; + + return pdb->CompleteTypeFromPDB(compiler_type); +} + +lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to get decl for UID: {0}"); + return CompilerDecl(); + } + auto ts = *type_system_or_err; + TypeSystemClang *clang_ast_ctx = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_ast_ctx) + return CompilerDecl(); + + PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); + if (!pdb) + return CompilerDecl(); + + auto symbol = m_session_up->getSymbolById(uid); + if (!symbol) + return CompilerDecl(); + + auto decl = pdb->GetDeclForSymbol(*symbol); + if (!decl) + return CompilerDecl(); + + return clang_ast_ctx->GetCompilerDecl(decl); +} + +lldb_private::CompilerDeclContext +SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to get DeclContext for UID: {0}"); + return CompilerDeclContext(); + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_ast_ctx = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_ast_ctx) + return CompilerDeclContext(); + + PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); + if (!pdb) + return CompilerDeclContext(); + + auto symbol = m_session_up->getSymbolById(uid); + if (!symbol) + return CompilerDeclContext(); + + auto decl_context = pdb->GetDeclContextForSymbol(*symbol); + if (!decl_context) + return GetDeclContextContainingUID(uid); + + return clang_ast_ctx->CreateDeclContext(decl_context); +} + +lldb_private::CompilerDeclContext +SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to get DeclContext containing UID: {0}"); + return CompilerDeclContext(); + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_ast_ctx = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_ast_ctx) + return CompilerDeclContext(); + + PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); + if (!pdb) + return CompilerDeclContext(); + + auto symbol = m_session_up->getSymbolById(uid); + if (!symbol) + return CompilerDeclContext(); + + auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol); + assert(decl_context); + + return clang_ast_ctx->CreateDeclContext(decl_context); +} + +void SymbolFilePDB::ParseDeclsForContext( + lldb_private::CompilerDeclContext decl_ctx) { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to parse decls for context: {0}"); + return; + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_ast_ctx = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_ast_ctx) + return; + + PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); + if (!pdb) + return; + + pdb->ParseDeclsForDeclContext( + static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext())); +} + +uint32_t +SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr, + SymbolContextItem resolve_scope, + lldb_private::SymbolContext &sc) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + uint32_t resolved_flags = 0; + if (resolve_scope & eSymbolContextCompUnit || + resolve_scope & eSymbolContextVariable || + resolve_scope & eSymbolContextFunction || + resolve_scope & eSymbolContextBlock || + resolve_scope & eSymbolContextLineEntry) { + auto cu_sp = GetCompileUnitContainsAddress(so_addr); + if (!cu_sp) { + if (resolved_flags & eSymbolContextVariable) { + // TODO: Resolve variables + } + return 0; + } + sc.comp_unit = cu_sp.get(); + resolved_flags |= eSymbolContextCompUnit; + lldbassert(sc.module_sp == cu_sp->GetModule()); + } + + if (resolve_scope & eSymbolContextFunction || + resolve_scope & eSymbolContextBlock) { + addr_t file_vm_addr = so_addr.GetFileAddress(); + auto symbol_up = + m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function); + if (symbol_up) { + auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); + assert(pdb_func); + auto func_uid = pdb_func->getSymIndexId(); + sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); + if (sc.function == nullptr) + sc.function = + ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit); + if (sc.function) { + resolved_flags |= eSymbolContextFunction; + if (resolve_scope & eSymbolContextBlock) { + auto block_symbol = m_session_up->findSymbolByAddress( + file_vm_addr, PDB_SymType::Block); + auto block_id = block_symbol ? block_symbol->getSymIndexId() + : sc.function->GetID(); + sc.block = sc.function->GetBlock(true).FindBlockByID(block_id); + if (sc.block) + resolved_flags |= eSymbolContextBlock; + } + } + } + } + + if (resolve_scope & eSymbolContextLineEntry) { + if (auto *line_table = sc.comp_unit->GetLineTable()) { + Address addr(so_addr); + if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) + resolved_flags |= eSymbolContextLineEntry; + } + } + + return resolved_flags; +} + +uint32_t SymbolFilePDB::ResolveSymbolContext( + const lldb_private::SourceLocationSpec &src_location_spec, + SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + const size_t old_size = sc_list.GetSize(); + const FileSpec &file_spec = src_location_spec.GetFileSpec(); + const uint32_t line = src_location_spec.GetLine().value_or(0); + if (resolve_scope & lldb::eSymbolContextCompUnit) { + // Locate all compilation units with line numbers referencing the specified + // file. For example, if `file_spec` is <vector>, then this should return + // all source files and header files that reference <vector>, either + // directly or indirectly. + auto compilands = m_session_up->findCompilandsForSourceFile( + file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive); + + if (!compilands) + return 0; + + // For each one, either find its previously parsed data or parse it afresh + // and add it to the symbol context list. + while (auto compiland = compilands->getNext()) { + // If we're not checking inlines, then don't add line information for + // this file unless the FileSpec matches. For inline functions, we don't + // have to match the FileSpec since they could be defined in headers + // other than file specified in FileSpec. + if (!src_location_spec.GetCheckInlines()) { + std::string source_file = compiland->getSourceFileFullPath(); + if (source_file.empty()) + continue; + FileSpec this_spec(source_file, FileSpec::Style::windows); + bool need_full_match = !file_spec.GetDirectory().IsEmpty(); + if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0) + continue; + } + + SymbolContext sc; + auto cu = ParseCompileUnitForUID(compiland->getSymIndexId()); + if (!cu) + continue; + sc.comp_unit = cu.get(); + sc.module_sp = cu->GetModule(); + + // If we were asked to resolve line entries, add all entries to the line + // table that match the requested line (or all lines if `line` == 0). + if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock | + eSymbolContextLineEntry)) { + bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line); + + if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) { + // The query asks for line entries, but we can't get them for the + // compile unit. This is not normal for `line` = 0. So just assert + // it. + assert(line && "Couldn't get all line entries!\n"); + + // Current compiland does not have the requested line. Search next. + continue; + } + + if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { + if (!has_line_table) + continue; + + auto *line_table = sc.comp_unit->GetLineTable(); + lldbassert(line_table); + + uint32_t num_line_entries = line_table->GetSize(); + // Skip the terminal line entry. + --num_line_entries; + + // If `line `!= 0, see if we can resolve function for each line entry + // in the line table. + for (uint32_t line_idx = 0; line && line_idx < num_line_entries; + ++line_idx) { + if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry)) + continue; + + auto file_vm_addr = + sc.line_entry.range.GetBaseAddress().GetFileAddress(); + if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) + continue; + + auto symbol_up = m_session_up->findSymbolByAddress( + file_vm_addr, PDB_SymType::Function); + if (symbol_up) { + auto func_uid = symbol_up->getSymIndexId(); + sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); + if (sc.function == nullptr) { + auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); + assert(pdb_func); + sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, + *sc.comp_unit); + } + if (sc.function && (resolve_scope & eSymbolContextBlock)) { + Block &block = sc.function->GetBlock(true); + sc.block = block.FindBlockByID(sc.function->GetID()); + } + } + sc_list.Append(sc); + } + } else if (has_line_table) { + // We can parse line table for the compile unit. But no query to + // resolve function or block. We append `sc` to the list anyway. + sc_list.Append(sc); + } + } else { + // No query for line entry, function or block. But we have a valid + // compile unit, append `sc` to the list. + sc_list.Append(sc); + } + } + } + return sc_list.GetSize() - old_size; +} + +std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) { + // Cache public names at first + if (m_public_names.empty()) + if (auto result_up = + m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol)) + while (auto symbol_up = result_up->getNext()) + if (auto addr = symbol_up->getRawSymbol().getVirtualAddress()) + m_public_names[addr] = symbol_up->getRawSymbol().getName(); + + // Look up the name in the cache + return m_public_names.lookup(pdb_data.getVirtualAddress()); +} + +VariableSP SymbolFilePDB::ParseVariableForPDBData( + const lldb_private::SymbolContext &sc, + const llvm::pdb::PDBSymbolData &pdb_data) { + VariableSP var_sp; + uint32_t var_uid = pdb_data.getSymIndexId(); + auto result = m_variables.find(var_uid); + if (result != m_variables.end()) + return result->second; + + ValueType scope = eValueTypeInvalid; + bool is_static_member = false; + bool is_external = false; + bool is_artificial = false; + + switch (pdb_data.getDataKind()) { + case PDB_DataKind::Global: + scope = eValueTypeVariableGlobal; + is_external = true; + break; + case PDB_DataKind::Local: + scope = eValueTypeVariableLocal; + break; + case PDB_DataKind::FileStatic: + scope = eValueTypeVariableStatic; + break; + case PDB_DataKind::StaticMember: + is_static_member = true; + scope = eValueTypeVariableStatic; + break; + case PDB_DataKind::Member: + scope = eValueTypeVariableStatic; + break; + case PDB_DataKind::Param: + scope = eValueTypeVariableArgument; + break; + case PDB_DataKind::Constant: + scope = eValueTypeConstResult; + break; + default: + break; + } + + switch (pdb_data.getLocationType()) { + case PDB_LocType::TLS: + scope = eValueTypeVariableThreadLocal; + break; + case PDB_LocType::RegRel: { + // It is a `this` pointer. + if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) { + scope = eValueTypeVariableArgument; + is_artificial = true; + } + } break; + default: + break; + } + + Declaration decl; + if (!is_artificial && !pdb_data.isCompilerGenerated()) { + if (auto lines = pdb_data.getLineNumbers()) { + if (auto first_line = lines->getNext()) { + uint32_t src_file_id = first_line->getSourceFileId(); + auto src_file = m_session_up->getSourceFileById(src_file_id); + if (src_file) { + FileSpec spec(src_file->getFileName()); + decl.SetFile(spec); + decl.SetColumn(first_line->getColumnNumber()); + decl.SetLine(first_line->getLineNumber()); + } + } + } + } + + Variable::RangeList ranges; + SymbolContextScope *context_scope = sc.comp_unit; + if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) { + if (sc.function) { + Block &function_block = sc.function->GetBlock(true); + Block *block = + function_block.FindBlockByID(pdb_data.getLexicalParentId()); + if (!block) + block = &function_block; + + context_scope = block; + + for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges; + ++i) { + AddressRange range; + if (!block->GetRangeAtIndex(i, range)) + continue; + + ranges.Append(range.GetBaseAddress().GetFileAddress(), + range.GetByteSize()); + } + } + } + + SymbolFileTypeSP type_sp = + std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId()); + + auto var_name = pdb_data.getName(); + auto mangled = GetMangledForPDBData(pdb_data); + auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str(); + + bool is_constant; + ModuleSP module_sp = GetObjectFile()->GetModule(); + DWARFExpressionList location(module_sp, + ConvertPDBLocationToDWARFExpression( + module_sp, pdb_data, ranges, is_constant), + nullptr); + + var_sp = std::make_shared<Variable>( + var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope, + ranges, &decl, location, is_external, is_artificial, is_constant, + is_static_member); + + m_variables.insert(std::make_pair(var_uid, var_sp)); + return var_sp; +} + +size_t +SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc, + const llvm::pdb::PDBSymbol &pdb_symbol, + lldb_private::VariableList *variable_list) { + size_t num_added = 0; + + if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) { + VariableListSP local_variable_list_sp; + + auto result = m_variables.find(pdb_data->getSymIndexId()); + if (result != m_variables.end()) { + if (variable_list) + variable_list->AddVariableIfUnique(result->second); + } else { + // Prepare right VariableList for this variable. + if (auto lexical_parent = pdb_data->getLexicalParent()) { + switch (lexical_parent->getSymTag()) { + case PDB_SymType::Exe: + assert(sc.comp_unit); + [[fallthrough]]; + case PDB_SymType::Compiland: { + if (sc.comp_unit) { + local_variable_list_sp = sc.comp_unit->GetVariableList(false); + if (!local_variable_list_sp) { + local_variable_list_sp = std::make_shared<VariableList>(); + sc.comp_unit->SetVariableList(local_variable_list_sp); + } + } + } break; + case PDB_SymType::Block: + case PDB_SymType::Function: { + if (sc.function) { + Block *block = sc.function->GetBlock(true).FindBlockByID( + lexical_parent->getSymIndexId()); + if (block) { + local_variable_list_sp = block->GetBlockVariableList(false); + if (!local_variable_list_sp) { + local_variable_list_sp = std::make_shared<VariableList>(); + block->SetVariableList(local_variable_list_sp); + } + } + } + } break; + default: + break; + } + } + + if (local_variable_list_sp) { + if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) { + local_variable_list_sp->AddVariableIfUnique(var_sp); + if (variable_list) + variable_list->AddVariableIfUnique(var_sp); + ++num_added; + PDBASTParser *ast = GetPDBAstParser(); + if (ast) + ast->GetDeclForSymbol(*pdb_data); + } + } + } + } + + if (auto results = pdb_symbol.findAllChildren()) { + while (auto result = results->getNext()) + num_added += ParseVariables(sc, *result, variable_list); + } + + return num_added; +} + +void SymbolFilePDB::FindGlobalVariables( + lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx, + uint32_t max_matches, lldb_private::VariableList &variables) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) + return; + if (name.IsEmpty()) + return; + + auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); + if (!results) + return; + + uint32_t matches = 0; + size_t old_size = variables.GetSize(); + while (auto result = results->getNext()) { + auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get()); + if (max_matches > 0 && matches >= max_matches) + break; + + SymbolContext sc; + sc.module_sp = m_objfile_sp->GetModule(); + lldbassert(sc.module_sp.get()); + + if (name.GetStringRef() != + MSVCUndecoratedNameParser::DropScope(pdb_data->getName())) + continue; + + sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get(); + // FIXME: We are not able to determine the compile unit. + if (sc.comp_unit == nullptr) + continue; + + if (parent_decl_ctx.IsValid() && + GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx) + continue; + + ParseVariables(sc, *pdb_data, &variables); + matches = variables.GetSize() - old_size; + } +} + +void SymbolFilePDB::FindGlobalVariables( + const lldb_private::RegularExpression ®ex, uint32_t max_matches, + lldb_private::VariableList &variables) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + if (!regex.IsValid()) + return; + auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); + if (!results) + return; + + uint32_t matches = 0; + size_t old_size = variables.GetSize(); + while (auto pdb_data = results->getNext()) { + if (max_matches > 0 && matches >= max_matches) + break; + + auto var_name = pdb_data->getName(); + if (var_name.empty()) + continue; + if (!regex.Execute(var_name)) + continue; + SymbolContext sc; + sc.module_sp = m_objfile_sp->GetModule(); + lldbassert(sc.module_sp.get()); + + sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get(); + // FIXME: We are not able to determine the compile unit. + if (sc.comp_unit == nullptr) + continue; + + ParseVariables(sc, *pdb_data, &variables); + matches = variables.GetSize() - old_size; + } +} + +bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func, + bool include_inlines, + lldb_private::SymbolContextList &sc_list) { + lldb_private::SymbolContext sc; + sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get(); + if (!sc.comp_unit) + return false; + sc.module_sp = sc.comp_unit->GetModule(); + sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit); + if (!sc.function) + return false; + + sc_list.Append(sc); + return true; +} + +bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines, + lldb_private::SymbolContextList &sc_list) { + auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid); + if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute())) + return false; + return ResolveFunction(*pdb_func_up, include_inlines, sc_list); +} + +void SymbolFilePDB::CacheFunctionNames() { + if (!m_func_full_names.IsEmpty()) + return; + + std::map<uint64_t, uint32_t> addr_ids; + + if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) { + while (auto pdb_func_up = results_up->getNext()) { + if (pdb_func_up->isCompilerGenerated()) + continue; + + auto name = pdb_func_up->getName(); + auto demangled_name = pdb_func_up->getUndecoratedName(); + if (name.empty() && demangled_name.empty()) + continue; + + auto uid = pdb_func_up->getSymIndexId(); + if (!demangled_name.empty() && pdb_func_up->getVirtualAddress()) + addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid)); + + if (auto parent = pdb_func_up->getClassParent()) { + + // PDB have symbols for class/struct methods or static methods in Enum + // Class. We won't bother to check if the parent is UDT or Enum here. + m_func_method_names.Append(ConstString(name), uid); + + // To search a method name, like NS::Class:MemberFunc, LLDB searches + // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does + // not have information of this, we extract base names and cache them + // by our own effort. + llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name); + if (!basename.empty()) + m_func_base_names.Append(ConstString(basename), uid); + else { + m_func_base_names.Append(ConstString(name), uid); + } + + if (!demangled_name.empty()) + m_func_full_names.Append(ConstString(demangled_name), uid); + + } else { + // Handle not-method symbols. + + // The function name might contain namespace, or its lexical scope. + llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name); + if (!basename.empty()) + m_func_base_names.Append(ConstString(basename), uid); + else + m_func_base_names.Append(ConstString(name), uid); + + if (name == "main") { + m_func_full_names.Append(ConstString(name), uid); + + if (!demangled_name.empty() && name != demangled_name) { + m_func_full_names.Append(ConstString(demangled_name), uid); + m_func_base_names.Append(ConstString(demangled_name), uid); + } + } else if (!demangled_name.empty()) { + m_func_full_names.Append(ConstString(demangled_name), uid); + } else { + m_func_full_names.Append(ConstString(name), uid); + } + } + } + } + + if (auto results_up = + m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) { + while (auto pub_sym_up = results_up->getNext()) { + if (!pub_sym_up->isFunction()) + continue; + auto name = pub_sym_up->getName(); + if (name.empty()) + continue; + + if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) { + auto vm_addr = pub_sym_up->getVirtualAddress(); + + // PDB public symbol has mangled name for its associated function. + if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) { + // Cache mangled name. + m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]); + } + } + } + } + // Sort them before value searching is working properly + m_func_full_names.Sort(); + m_func_full_names.SizeToFit(); + m_func_method_names.Sort(); + m_func_method_names.SizeToFit(); + m_func_base_names.Sort(); + m_func_base_names.SizeToFit(); +} + +void SymbolFilePDB::FindFunctions( + const lldb_private::Module::LookupInfo &lookup_info, + const lldb_private::CompilerDeclContext &parent_decl_ctx, + bool include_inlines, + lldb_private::SymbolContextList &sc_list) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + ConstString name = lookup_info.GetLookupName(); + FunctionNameType name_type_mask = lookup_info.GetNameTypeMask(); + lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0); + + if (name_type_mask & eFunctionNameTypeFull) + name = lookup_info.GetName(); + + if (name_type_mask == eFunctionNameTypeNone) + return; + if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) + return; + if (name.IsEmpty()) + return; + + if (name_type_mask & eFunctionNameTypeFull || + name_type_mask & eFunctionNameTypeBase || + name_type_mask & eFunctionNameTypeMethod) { + CacheFunctionNames(); + + std::set<uint32_t> resolved_ids; + auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list, + &resolved_ids](UniqueCStringMap<uint32_t> &Names) { + std::vector<uint32_t> ids; + if (!Names.GetValues(name, ids)) + return; + + for (uint32_t id : ids) { + if (resolved_ids.find(id) != resolved_ids.end()) + continue; + + if (parent_decl_ctx.IsValid() && + GetDeclContextContainingUID(id) != parent_decl_ctx) + continue; + + if (ResolveFunction(id, include_inlines, sc_list)) + resolved_ids.insert(id); + } + }; + if (name_type_mask & eFunctionNameTypeFull) { + ResolveFn(m_func_full_names); + ResolveFn(m_func_base_names); + ResolveFn(m_func_method_names); + } + if (name_type_mask & eFunctionNameTypeBase) + ResolveFn(m_func_base_names); + if (name_type_mask & eFunctionNameTypeMethod) + ResolveFn(m_func_method_names); + } +} + +void SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex, + bool include_inlines, + lldb_private::SymbolContextList &sc_list) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + if (!regex.IsValid()) + return; + + CacheFunctionNames(); + + std::set<uint32_t> resolved_ids; + auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids, + this](UniqueCStringMap<uint32_t> &Names) { + std::vector<uint32_t> ids; + if (Names.GetValues(regex, ids)) { + for (auto id : ids) { + if (resolved_ids.find(id) == resolved_ids.end()) + if (ResolveFunction(id, include_inlines, sc_list)) + resolved_ids.insert(id); + } + } + }; + ResolveFn(m_func_full_names); + ResolveFn(m_func_base_names); +} + +void SymbolFilePDB::GetMangledNamesForFunction( + const std::string &scope_qualified_name, + std::vector<lldb_private::ConstString> &mangled_names) {} + +void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) { + std::set<lldb::addr_t> sym_addresses; + for (size_t i = 0; i < symtab.GetNumSymbols(); i++) + sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress()); + + auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>(); + if (!results) + return; + + auto section_list = m_objfile_sp->GetSectionList(); + if (!section_list) + return; + + while (auto pub_symbol = results->getNext()) { + auto section_id = pub_symbol->getAddressSection(); + + auto section = section_list->FindSectionByID(section_id); + if (!section) + continue; + + auto offset = pub_symbol->getAddressOffset(); + + auto file_addr = section->GetFileAddress() + offset; + if (sym_addresses.find(file_addr) != sym_addresses.end()) + continue; + sym_addresses.insert(file_addr); + + auto size = pub_symbol->getLength(); + symtab.AddSymbol( + Symbol(pub_symbol->getSymIndexId(), // symID + pub_symbol->getName().c_str(), // name + pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type + true, // external + false, // is_debug + false, // is_trampoline + false, // is_artificial + section, // section_sp + offset, // value + size, // size + size != 0, // size_is_valid + false, // contains_linker_annotations + 0 // flags + )); + } + + symtab.Finalize(); +} + +void SymbolFilePDB::DumpClangAST(Stream &s) { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to dump ClangAST: {0}"); + return; + } + + auto ts = *type_system_or_err; + TypeSystemClang *clang_type_system = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_type_system) + return; + clang_type_system->Dump(s.AsRawOstream()); +} + +void SymbolFilePDB::FindTypesByRegex( + const lldb_private::RegularExpression ®ex, uint32_t max_matches, + lldb_private::TypeMap &types) { + // When searching by regex, we need to go out of our way to limit the search + // space as much as possible since this searches EVERYTHING in the PDB, + // manually doing regex comparisons. PDB library isn't optimized for regex + // searches or searches across multiple symbol types at the same time, so the + // best we can do is to search enums, then typedefs, then classes one by one, + // and do a regex comparison against each of them. + PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef, + PDB_SymType::UDT}; + std::unique_ptr<IPDBEnumSymbols> results; + + uint32_t matches = 0; + + for (auto tag : tags_to_search) { + results = m_global_scope_up->findAllChildren(tag); + if (!results) + continue; + + while (auto result = results->getNext()) { + if (max_matches > 0 && matches >= max_matches) + break; + + std::string type_name; + if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get())) + type_name = enum_type->getName(); + else if (auto typedef_type = + llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get())) + type_name = typedef_type->getName(); + else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get())) + type_name = class_type->getName(); + else { + // We're looking only for types that have names. Skip symbols, as well + // as unnamed types such as arrays, pointers, etc. + continue; + } + + if (!regex.Execute(type_name)) + continue; + + // This should cause the type to get cached and stored in the `m_types` + // lookup. + if (!ResolveTypeUID(result->getSymIndexId())) + continue; + + auto iter = m_types.find(result->getSymIndexId()); + if (iter == m_types.end()) + continue; + types.Insert(iter->second); + ++matches; + } + } +} + +void SymbolFilePDB::FindTypes(const lldb_private::TypeQuery &query, + lldb_private::TypeResults &type_results) { + + // Make sure we haven't already searched this SymbolFile before. + if (type_results.AlreadySearched(this)) + return; + + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + + std::unique_ptr<IPDBEnumSymbols> results; + llvm::StringRef basename = query.GetTypeBasename().GetStringRef(); + if (basename.empty()) + return; + results = m_global_scope_up->findAllChildren(PDB_SymType::None); + if (!results) + return; + + while (auto result = results->getNext()) { + + switch (result->getSymTag()) { + case PDB_SymType::Enum: + case PDB_SymType::UDT: + case PDB_SymType::Typedef: + break; + default: + // We're looking only for types that have names. Skip symbols, as well + // as unnamed types such as arrays, pointers, etc. + continue; + } + + if (MSVCUndecoratedNameParser::DropScope( + result->getRawSymbol().getName()) != basename) + continue; + + // This should cause the type to get cached and stored in the `m_types` + // lookup. + if (!ResolveTypeUID(result->getSymIndexId())) + continue; + + auto iter = m_types.find(result->getSymIndexId()); + if (iter == m_types.end()) + continue; + // We resolved a type. Get the fully qualified name to ensure it matches. + ConstString name = iter->second->GetQualifiedName(); + TypeQuery type_match(name.GetStringRef(), TypeQueryOptions::e_exact_match); + if (query.ContextMatches(type_match.GetContextRef())) { + type_results.InsertUnique(iter->second); + if (type_results.Done(query)) + return; + } + } +} + +void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol, + uint32_t type_mask, + TypeCollection &type_collection) { + bool can_parse = false; + switch (pdb_symbol.getSymTag()) { + case PDB_SymType::ArrayType: + can_parse = ((type_mask & eTypeClassArray) != 0); + break; + case PDB_SymType::BuiltinType: + can_parse = ((type_mask & eTypeClassBuiltin) != 0); + break; + case PDB_SymType::Enum: + can_parse = ((type_mask & eTypeClassEnumeration) != 0); + break; + case PDB_SymType::Function: + case PDB_SymType::FunctionSig: + can_parse = ((type_mask & eTypeClassFunction) != 0); + break; + case PDB_SymType::PointerType: + can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer | + eTypeClassMemberPointer)) != 0); + break; + case PDB_SymType::Typedef: + can_parse = ((type_mask & eTypeClassTypedef) != 0); + break; + case PDB_SymType::UDT: { + auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol); + assert(udt); + can_parse = (udt->getUdtKind() != PDB_UdtType::Interface && + ((type_mask & (eTypeClassClass | eTypeClassStruct | + eTypeClassUnion)) != 0)); + } break; + default: + break; + } + + if (can_parse) { + if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) { + if (!llvm::is_contained(type_collection, type)) + type_collection.push_back(type); + } + } + + auto results_up = pdb_symbol.findAllChildren(); + while (auto symbol_up = results_up->getNext()) + GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection); +} + +void SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, + TypeClass type_mask, + lldb_private::TypeList &type_list) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + TypeCollection type_collection; + CompileUnit *cu = + sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr; + if (cu) { + auto compiland_up = GetPDBCompilandByUID(cu->GetID()); + if (!compiland_up) + return; + GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); + } else { + for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) { + auto cu_sp = ParseCompileUnitAtIndex(cu_idx); + if (cu_sp) { + if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID())) + GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); + } + } + } + + for (auto type : type_collection) { + type->GetForwardCompilerType(); + type_list.Insert(type->shared_from_this()); + } +} + +llvm::Expected<lldb::TypeSystemSP> +SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { + auto type_system_or_err = + m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); + if (type_system_or_err) { + if (auto ts = *type_system_or_err) + ts->SetSymbolFile(this); + } + return type_system_or_err; +} + +PDBASTParser *SymbolFilePDB::GetPDBAstParser() { + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to get PDB AST parser: {0}"); + return nullptr; + } + + auto ts = *type_system_or_err; + auto *clang_type_system = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_type_system) + return nullptr; + + return clang_type_system->GetPDBParser(); +} + +lldb_private::CompilerDeclContext +SymbolFilePDB::FindNamespace(lldb_private::ConstString name, + const CompilerDeclContext &parent_decl_ctx, bool) { + std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); + auto type_system_or_err = + GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), + "Unable to find namespace {1}: {0}", name.AsCString()); + return CompilerDeclContext(); + } + auto ts = *type_system_or_err; + auto *clang_type_system = + llvm::dyn_cast_or_null<TypeSystemClang>(ts.get()); + if (!clang_type_system) + return CompilerDeclContext(); + + PDBASTParser *pdb = clang_type_system->GetPDBParser(); + if (!pdb) + return CompilerDeclContext(); + + clang::DeclContext *decl_context = nullptr; + if (parent_decl_ctx) + decl_context = static_cast<clang::DeclContext *>( + parent_decl_ctx.GetOpaqueDeclContext()); + + auto namespace_decl = + pdb->FindNamespaceDecl(decl_context, name.GetStringRef()); + if (!namespace_decl) + return CompilerDeclContext(); + + return clang_type_system->CreateDeclContext(namespace_decl); +} + +IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; } + +const IPDBSession &SymbolFilePDB::GetPDBSession() const { + return *m_session_up; +} + +lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id, + uint32_t index) { + auto found_cu = m_comp_units.find(id); + if (found_cu != m_comp_units.end()) + return found_cu->second; + + auto compiland_up = GetPDBCompilandByUID(id); + if (!compiland_up) + return CompUnitSP(); + + lldb::LanguageType lang; + auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>(); + if (!details) + lang = lldb::eLanguageTypeC_plus_plus; + else + lang = TranslateLanguage(details->getLanguage()); + + if (lang == lldb::LanguageType::eLanguageTypeUnknown) + return CompUnitSP(); + + std::string path = compiland_up->getSourceFileFullPath(); + if (path.empty()) + return CompUnitSP(); + + // Don't support optimized code for now, DebugInfoPDB does not return this + // information. + LazyBool optimized = eLazyBoolNo; + auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, + path.c_str(), id, lang, optimized); + + if (!cu_sp) + return CompUnitSP(); + + m_comp_units.insert(std::make_pair(id, cu_sp)); + if (index == UINT32_MAX) + GetCompileUnitIndex(*compiland_up, index); + lldbassert(index != UINT32_MAX); + SetCompileUnitAtIndex(index, cu_sp); + return cu_sp; +} + +bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit, + uint32_t match_line) { + auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); + if (!compiland_up) + return false; + + // LineEntry needs the *index* of the file into the list of support files + // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us + // a globally unique idenfitifier in the namespace of the PDB. So, we have + // to do a mapping so that we can hand out indices. + llvm::DenseMap<uint32_t, uint32_t> index_map; + BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map); + auto line_table = std::make_unique<LineTable>(&comp_unit); + + // Find contributions to `compiland` from all source and header files. + auto files = m_session_up->getSourceFilesForCompiland(*compiland_up); + if (!files) + return false; + + // For each source and header file, create a LineSequence for contributions + // to the compiland from that file, and add the sequence. + while (auto file = files->getNext()) { + std::unique_ptr<LineSequence> sequence( + line_table->CreateLineSequenceContainer()); + auto lines = m_session_up->findLineNumbers(*compiland_up, *file); + if (!lines) + continue; + int entry_count = lines->getChildCount(); + + uint64_t prev_addr; + uint32_t prev_length; + uint32_t prev_line; + uint32_t prev_source_idx; + + for (int i = 0; i < entry_count; ++i) { + auto line = lines->getChildAtIndex(i); + + uint64_t lno = line->getLineNumber(); + uint64_t addr = line->getVirtualAddress(); + uint32_t length = line->getLength(); + uint32_t source_id = line->getSourceFileId(); + uint32_t col = line->getColumnNumber(); + uint32_t source_idx = index_map[source_id]; + + // There was a gap between the current entry and the previous entry if + // the addresses don't perfectly line up. + bool is_gap = (i > 0) && (prev_addr + prev_length < addr); + + // Before inserting the current entry, insert a terminal entry at the end + // of the previous entry's address range if the current entry resulted in + // a gap from the previous entry. + if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) { + line_table->AppendLineEntryToSequence( + sequence.get(), prev_addr + prev_length, prev_line, 0, + prev_source_idx, false, false, false, false, true); + + line_table->InsertSequence(sequence.get()); + sequence = line_table->CreateLineSequenceContainer(); + } + + if (ShouldAddLine(match_line, lno, length)) { + bool is_statement = line->isStatement(); + bool is_prologue = false; + bool is_epilogue = false; + auto func = + m_session_up->findSymbolByAddress(addr, PDB_SymType::Function); + if (func) { + auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>(); + if (prologue) + is_prologue = (addr == prologue->getVirtualAddress()); + + auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>(); + if (epilogue) + is_epilogue = (addr == epilogue->getVirtualAddress()); + } + + line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col, + source_idx, is_statement, false, + is_prologue, is_epilogue, false); + } + + prev_addr = addr; + prev_length = length; + prev_line = lno; + prev_source_idx = source_idx; + } + + if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) { + // The end is always a terminal entry, so insert it regardless. + line_table->AppendLineEntryToSequence( + sequence.get(), prev_addr + prev_length, prev_line, 0, + prev_source_idx, false, false, false, false, true); + } + + line_table->InsertSequence(sequence.get()); + } + + if (line_table->GetSize()) { + comp_unit.SetLineTable(line_table.release()); + return true; + } + return false; +} + +void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap( + const PDBSymbolCompiland &compiland, + llvm::DenseMap<uint32_t, uint32_t> &index_map) const { + // This is a hack, but we need to convert the source id into an index into + // the support files array. We don't want to do path comparisons to avoid + // basename / full path issues that may or may not even be a problem, so we + // use the globally unique source file identifiers. Ideally we could use the + // global identifiers everywhere, but LineEntry currently assumes indices. + auto source_files = m_session_up->getSourceFilesForCompiland(compiland); + if (!source_files) + return; + + int index = 0; + while (auto file = source_files->getNext()) { + uint32_t source_id = file->getUniqueId(); + index_map[source_id] = index++; + } +} + +lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress( + const lldb_private::Address &so_addr) { + lldb::addr_t file_vm_addr = so_addr.GetFileAddress(); + if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) + return nullptr; + + // If it is a PDB function's vm addr, this is the first sure bet. + if (auto lines = + m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) { + if (auto first_line = lines->getNext()) + return ParseCompileUnitForUID(first_line->getCompilandId()); + } + + // Otherwise we resort to section contributions. + if (auto sec_contribs = m_session_up->getSectionContribs()) { + while (auto section = sec_contribs->getNext()) { + auto va = section->getVirtualAddress(); + if (file_vm_addr >= va && file_vm_addr < va + section->getLength()) + return ParseCompileUnitForUID(section->getCompilandId()); + } + } + return nullptr; +} + +Mangled +SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) { + Mangled mangled; + auto func_name = pdb_func.getName(); + auto func_undecorated_name = pdb_func.getUndecoratedName(); + std::string func_decorated_name; + + // Seek from public symbols for non-static function's decorated name if any. + // For static functions, they don't have undecorated names and aren't exposed + // in Public Symbols either. + if (!func_undecorated_name.empty()) { + auto result_up = m_global_scope_up->findChildren( + PDB_SymType::PublicSymbol, func_undecorated_name, + PDB_NameSearchFlags::NS_UndecoratedName); + if (result_up) { + while (auto symbol_up = result_up->getNext()) { + // For a public symbol, it is unique. + lldbassert(result_up->getChildCount() == 1); + if (auto *pdb_public_sym = + llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>( + symbol_up.get())) { + if (pdb_public_sym->isFunction()) { + func_decorated_name = pdb_public_sym->getName(); + break; + } + } + } + } + } + if (!func_decorated_name.empty()) { + mangled.SetMangledName(ConstString(func_decorated_name)); + + // For MSVC, format of C function's decorated name depends on calling + // convention. Unfortunately none of the format is recognized by current + // LLDB. For example, `_purecall` is a __cdecl C function. From PDB, + // `__purecall` is retrieved as both its decorated and undecorated name + // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall` + // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix). + // Mangled::GetDemangledName method will fail internally and caches an + // empty string as its undecorated name. So we will face a contradiction + // here for the same symbol: + // non-empty undecorated name from PDB + // empty undecorated name from LLDB + if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty()) + mangled.SetDemangledName(ConstString(func_undecorated_name)); + + // LLDB uses several flags to control how a C++ decorated name is + // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the + // yielded name could be different from what we retrieve from + // PDB source unless we also apply same flags in getting undecorated + // name through PDBSymbolFunc::getUndecoratedNameEx method. + if (!func_undecorated_name.empty() && + mangled.GetDemangledName() != ConstString(func_undecorated_name)) + mangled.SetDemangledName(ConstString(func_undecorated_name)); + } else if (!func_undecorated_name.empty()) { + mangled.SetDemangledName(ConstString(func_undecorated_name)); + } else if (!func_name.empty()) + mangled.SetValue(ConstString(func_name)); + + return mangled; +} + +bool SymbolFilePDB::DeclContextMatchesThisSymbolFile( + const lldb_private::CompilerDeclContext &decl_ctx) { + if (!decl_ctx.IsValid()) + return true; + + TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem(); + if (!decl_ctx_type_system) + return false; + auto type_system_or_err = GetTypeSystemForLanguage( + decl_ctx_type_system->GetMinimumLanguage(nullptr)); + if (auto err = type_system_or_err.takeError()) { + LLDB_LOG_ERROR( + GetLog(LLDBLog::Symbols), std::move(err), + "Unable to determine if DeclContext matches this symbol file: {0}"); + return false; + } + + if (decl_ctx_type_system == type_system_or_err->get()) + return true; // The type systems match, return true + + return false; +} + +uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) { + static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) { + return lhs < rhs.Offset; + }; + + // Cache section contributions + if (m_sec_contribs.empty()) { + if (auto SecContribs = m_session_up->getSectionContribs()) { + while (auto SectionContrib = SecContribs->getNext()) { + auto comp_id = SectionContrib->getCompilandId(); + if (!comp_id) + continue; + + auto sec = SectionContrib->getAddressSection(); + auto &sec_cs = m_sec_contribs[sec]; + + auto offset = SectionContrib->getAddressOffset(); + auto it = llvm::upper_bound(sec_cs, offset, pred_upper); + + auto size = SectionContrib->getLength(); + sec_cs.insert(it, {offset, size, comp_id}); + } + } + } + + // Check by line number + if (auto Lines = data.getLineNumbers()) { + if (auto FirstLine = Lines->getNext()) + return FirstLine->getCompilandId(); + } + + // Retrieve section + offset + uint32_t DataSection = data.getAddressSection(); + uint32_t DataOffset = data.getAddressOffset(); + if (DataSection == 0) { + if (auto RVA = data.getRelativeVirtualAddress()) + m_session_up->addressForRVA(RVA, DataSection, DataOffset); + } + + if (DataSection) { + // Search by section contributions + auto &sec_cs = m_sec_contribs[DataSection]; + auto it = llvm::upper_bound(sec_cs, DataOffset, pred_upper); + if (it != sec_cs.begin()) { + --it; + if (DataOffset < it->Offset + it->Size) + return it->CompilandId; + } + } else { + // Search in lexical tree + auto LexParentId = data.getLexicalParentId(); + while (auto LexParent = m_session_up->getSymbolById(LexParentId)) { + if (LexParent->getSymTag() == PDB_SymType::Exe) + break; + if (LexParent->getSymTag() == PDB_SymType::Compiland) + return LexParentId; + LexParentId = LexParent->getRawSymbol().getLexicalParentId(); + } + } + + return 0; +} diff --git a/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h new file mode 100644 index 000000000000..ea495c575f1f --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h @@ -0,0 +1,252 @@ +//===-- SymbolFilePDB.h -------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_SYMBOLFILEPDB_H +#define LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_SYMBOLFILEPDB_H + +#include "lldb/Core/UniqueCStringMap.h" +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Utility/UserID.h" + +#include "llvm/ADT/DenseMap.h" +#include "llvm/DebugInfo/PDB/IPDBSession.h" +#include "llvm/DebugInfo/PDB/PDB.h" +#include "llvm/DebugInfo/PDB/PDBSymbolExe.h" +#include <optional> + +class PDBASTParser; + +class SymbolFilePDB : public lldb_private::SymbolFileCommon { + /// LLVM RTTI support. + static char ID; + +public: + /// LLVM RTTI support. + /// \{ + bool isA(const void *ClassID) const override { + return ClassID == &ID || SymbolFileCommon::isA(ClassID); + } + static bool classof(const SymbolFile *obj) { return obj->isA(&ID); } + /// \} + + // Static Functions + static void Initialize(); + + static void Terminate(); + + static void DebuggerInitialize(lldb_private::Debugger &debugger); + + static llvm::StringRef GetPluginNameStatic() { return "pdb"; } + + static llvm::StringRef GetPluginDescriptionStatic(); + + static lldb_private::SymbolFile * + CreateInstance(lldb::ObjectFileSP objfile_sp); + + // Constructors and Destructors + SymbolFilePDB(lldb::ObjectFileSP objfile_sp); + + ~SymbolFilePDB() override; + + uint32_t CalculateAbilities() override; + + void InitializeObject() override; + + // Compile Unit function calls + + lldb::LanguageType + ParseLanguage(lldb_private::CompileUnit &comp_unit) override; + + size_t ParseFunctions(lldb_private::CompileUnit &comp_unit) override; + + bool ParseLineTable(lldb_private::CompileUnit &comp_unit) override; + + bool ParseDebugMacros(lldb_private::CompileUnit &comp_unit) override; + + bool ParseSupportFiles(lldb_private::CompileUnit &comp_unit, + lldb_private::SupportFileList &support_files) override; + + size_t ParseTypes(lldb_private::CompileUnit &comp_unit) override; + + bool ParseImportedModules( + const lldb_private::SymbolContext &sc, + std::vector<lldb_private::SourceModule> &imported_modules) override; + + size_t ParseBlocksRecursive(lldb_private::Function &func) override; + + size_t + ParseVariablesForContext(const lldb_private::SymbolContext &sc) override; + + lldb_private::Type *ResolveTypeUID(lldb::user_id_t type_uid) override; + std::optional<ArrayInfo> GetDynamicArrayInfoForUID( + lldb::user_id_t type_uid, + const lldb_private::ExecutionContext *exe_ctx) override; + + bool CompleteType(lldb_private::CompilerType &compiler_type) override; + + lldb_private::CompilerDecl GetDeclForUID(lldb::user_id_t uid) override; + + lldb_private::CompilerDeclContext + GetDeclContextForUID(lldb::user_id_t uid) override; + + lldb_private::CompilerDeclContext + GetDeclContextContainingUID(lldb::user_id_t uid) override; + + void + ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx) override; + + uint32_t ResolveSymbolContext(const lldb_private::Address &so_addr, + lldb::SymbolContextItem resolve_scope, + lldb_private::SymbolContext &sc) override; + + uint32_t ResolveSymbolContext( + const lldb_private::SourceLocationSpec &src_location_spec, + lldb::SymbolContextItem resolve_scope, + lldb_private::SymbolContextList &sc_list) override; + + void + FindGlobalVariables(lldb_private::ConstString name, + const lldb_private::CompilerDeclContext &parent_decl_ctx, + uint32_t max_matches, + lldb_private::VariableList &variables) override; + + void FindGlobalVariables(const lldb_private::RegularExpression ®ex, + uint32_t max_matches, + lldb_private::VariableList &variables) override; + + void FindFunctions(const lldb_private::Module::LookupInfo &lookup_info, + const lldb_private::CompilerDeclContext &parent_decl_ctx, + bool include_inlines, + lldb_private::SymbolContextList &sc_list) override; + + void FindFunctions(const lldb_private::RegularExpression ®ex, + bool include_inlines, + lldb_private::SymbolContextList &sc_list) override; + + void GetMangledNamesForFunction( + const std::string &scope_qualified_name, + std::vector<lldb_private::ConstString> &mangled_names) override; + + void AddSymbols(lldb_private::Symtab &symtab) override; + void FindTypes(const lldb_private::TypeQuery &match, + lldb_private::TypeResults &results) override; + void FindTypesByRegex(const lldb_private::RegularExpression ®ex, + uint32_t max_matches, lldb_private::TypeMap &types); + + void GetTypes(lldb_private::SymbolContextScope *sc_scope, + lldb::TypeClass type_mask, + lldb_private::TypeList &type_list) override; + + llvm::Expected<lldb::TypeSystemSP> + GetTypeSystemForLanguage(lldb::LanguageType language) override; + + lldb_private::CompilerDeclContext + FindNamespace(lldb_private::ConstString name, + const lldb_private::CompilerDeclContext &parent_decl_ctx, + bool only_root_namespaces) override; + + llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); } + + llvm::pdb::IPDBSession &GetPDBSession(); + + const llvm::pdb::IPDBSession &GetPDBSession() const; + + void DumpClangAST(lldb_private::Stream &s) override; + +private: + struct SecContribInfo { + uint32_t Offset; + uint32_t Size; + uint32_t CompilandId; + }; + using SecContribsMap = std::map<uint32_t, std::vector<SecContribInfo>>; + + uint32_t CalculateNumCompileUnits() override; + + lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override; + + lldb::CompUnitSP ParseCompileUnitForUID(uint32_t id, + uint32_t index = UINT32_MAX); + + bool ParseCompileUnitLineTable(lldb_private::CompileUnit &comp_unit, + uint32_t match_line); + + void BuildSupportFileIdToSupportFileIndexMap( + const llvm::pdb::PDBSymbolCompiland &pdb_compiland, + llvm::DenseMap<uint32_t, uint32_t> &index_map) const; + + void FindTypesByName(llvm::StringRef name, + const lldb_private::CompilerDeclContext &parent_decl_ctx, + uint32_t max_matches, lldb_private::TypeMap &types); + + std::string GetMangledForPDBData(const llvm::pdb::PDBSymbolData &pdb_data); + + lldb::VariableSP + ParseVariableForPDBData(const lldb_private::SymbolContext &sc, + const llvm::pdb::PDBSymbolData &pdb_data); + + size_t ParseVariables(const lldb_private::SymbolContext &sc, + const llvm::pdb::PDBSymbol &pdb_data, + lldb_private::VariableList *variable_list = nullptr); + + lldb::CompUnitSP + GetCompileUnitContainsAddress(const lldb_private::Address &so_addr); + + typedef std::vector<lldb_private::Type *> TypeCollection; + + void GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol, + uint32_t type_mask, + TypeCollection &type_collection); + + lldb_private::Function * + ParseCompileUnitFunctionForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func, + lldb_private::CompileUnit &comp_unit); + + void GetCompileUnitIndex(const llvm::pdb::PDBSymbolCompiland &pdb_compiland, + uint32_t &index); + + PDBASTParser *GetPDBAstParser(); + + std::unique_ptr<llvm::pdb::PDBSymbolCompiland> + GetPDBCompilandByUID(uint32_t uid); + + lldb_private::Mangled + GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func); + + bool ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func, + bool include_inlines, + lldb_private::SymbolContextList &sc_list); + + bool ResolveFunction(uint32_t uid, bool include_inlines, + lldb_private::SymbolContextList &sc_list); + + void CacheFunctionNames(); + + bool DeclContextMatchesThisSymbolFile( + const lldb_private::CompilerDeclContext &decl_ctx); + + uint32_t GetCompilandId(const llvm::pdb::PDBSymbolData &data); + + llvm::DenseMap<uint32_t, lldb::CompUnitSP> m_comp_units; + llvm::DenseMap<uint32_t, lldb::TypeSP> m_types; + llvm::DenseMap<uint32_t, lldb::VariableSP> m_variables; + llvm::DenseMap<uint64_t, std::string> m_public_names; + + SecContribsMap m_sec_contribs; + + std::vector<lldb::TypeSP> m_builtin_types; + std::unique_ptr<llvm::pdb::IPDBSession> m_session_up; + std::unique_ptr<llvm::pdb::PDBSymbolExe> m_global_scope_up; + + lldb_private::UniqueCStringMap<uint32_t> m_func_full_names; + lldb_private::UniqueCStringMap<uint32_t> m_func_base_names; + lldb_private::UniqueCStringMap<uint32_t> m_func_method_names; +}; + +#endif // LLDB_SOURCE_PLUGINS_SYMBOLFILE_PDB_SYMBOLFILEPDB_H |