Path: blob/main/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp
39644 views
//===-- SymbolFilePDB.cpp -------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "SymbolFilePDB.h"910#include "PDBASTParser.h"11#include "PDBLocationToDWARFExpression.h"1213#include "clang/Lex/Lexer.h"1415#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"16#include "lldb/Core/Module.h"17#include "lldb/Core/PluginManager.h"18#include "lldb/Symbol/CompileUnit.h"19#include "lldb/Symbol/LineTable.h"20#include "lldb/Symbol/ObjectFile.h"21#include "lldb/Symbol/SymbolContext.h"22#include "lldb/Symbol/SymbolVendor.h"23#include "lldb/Symbol/TypeList.h"24#include "lldb/Symbol/TypeMap.h"25#include "lldb/Symbol/Variable.h"26#include "lldb/Utility/LLDBLog.h"27#include "lldb/Utility/Log.h"28#include "lldb/Utility/RegularExpression.h"2930#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"31#include "llvm/DebugInfo/PDB/GenericError.h"32#include "llvm/DebugInfo/PDB/IPDBDataStream.h"33#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"34#include "llvm/DebugInfo/PDB/IPDBLineNumber.h"35#include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"36#include "llvm/DebugInfo/PDB/IPDBSourceFile.h"37#include "llvm/DebugInfo/PDB/IPDBTable.h"38#include "llvm/DebugInfo/PDB/PDBSymbol.h"39#include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"40#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"41#include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"42#include "llvm/DebugInfo/PDB/PDBSymbolData.h"43#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"44#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"45#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"46#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"47#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"48#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"49#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"50#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"51#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"52#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"5354#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"55#include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"56#include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h"5758#if defined(_WIN32)59#include "llvm/Config/llvm-config.h"60#include <optional>61#endif6263using namespace lldb;64using namespace lldb_private;65using namespace llvm::pdb;6667LLDB_PLUGIN_DEFINE(SymbolFilePDB)6869char SymbolFilePDB::ID;7071namespace {72lldb::LanguageType TranslateLanguage(PDB_Lang lang) {73switch (lang) {74case PDB_Lang::Cpp:75return lldb::LanguageType::eLanguageTypeC_plus_plus;76case PDB_Lang::C:77return lldb::LanguageType::eLanguageTypeC;78case PDB_Lang::Swift:79return lldb::LanguageType::eLanguageTypeSwift;80case PDB_Lang::Rust:81return lldb::LanguageType::eLanguageTypeRust;82case PDB_Lang::ObjC:83return lldb::LanguageType::eLanguageTypeObjC;84case PDB_Lang::ObjCpp:85return lldb::LanguageType::eLanguageTypeObjC_plus_plus;86default:87return lldb::LanguageType::eLanguageTypeUnknown;88}89}9091bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,92uint32_t addr_length) {93return ((requested_line == 0 || actual_line == requested_line) &&94addr_length > 0);95}96} // namespace9798static bool ShouldUseNativeReader() {99#if defined(_WIN32)100#if LLVM_ENABLE_DIA_SDK101llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER");102if (!use_native.equals_insensitive("on") &&103!use_native.equals_insensitive("yes") &&104!use_native.equals_insensitive("1") &&105!use_native.equals_insensitive("true"))106return false;107#endif108#endif109return true;110}111112void SymbolFilePDB::Initialize() {113if (ShouldUseNativeReader()) {114npdb::SymbolFileNativePDB::Initialize();115} else {116PluginManager::RegisterPlugin(GetPluginNameStatic(),117GetPluginDescriptionStatic(), CreateInstance,118DebuggerInitialize);119}120}121122void SymbolFilePDB::Terminate() {123if (ShouldUseNativeReader()) {124npdb::SymbolFileNativePDB::Terminate();125} else {126PluginManager::UnregisterPlugin(CreateInstance);127}128}129130void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}131132llvm::StringRef SymbolFilePDB::GetPluginDescriptionStatic() {133return "Microsoft PDB debug symbol file reader.";134}135136lldb_private::SymbolFile *137SymbolFilePDB::CreateInstance(ObjectFileSP objfile_sp) {138return new SymbolFilePDB(std::move(objfile_sp));139}140141SymbolFilePDB::SymbolFilePDB(lldb::ObjectFileSP objfile_sp)142: SymbolFileCommon(std::move(objfile_sp)), m_session_up(), m_global_scope_up() {}143144SymbolFilePDB::~SymbolFilePDB() = default;145146uint32_t SymbolFilePDB::CalculateAbilities() {147uint32_t abilities = 0;148if (!m_objfile_sp)149return 0;150151if (!m_session_up) {152// Lazily load and match the PDB file, but only do this once.153std::string exePath = m_objfile_sp->GetFileSpec().GetPath();154auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),155m_session_up);156if (error) {157llvm::consumeError(std::move(error));158auto module_sp = m_objfile_sp->GetModule();159if (!module_sp)160return 0;161// See if any symbol file is specified through `--symfile` option.162FileSpec symfile = module_sp->GetSymbolFileFileSpec();163if (!symfile)164return 0;165error = loadDataForPDB(PDB_ReaderType::DIA,166llvm::StringRef(symfile.GetPath()), m_session_up);167if (error) {168llvm::consumeError(std::move(error));169return 0;170}171}172}173if (!m_session_up)174return 0;175176auto enum_tables_up = m_session_up->getEnumTables();177if (!enum_tables_up)178return 0;179while (auto table_up = enum_tables_up->getNext()) {180if (table_up->getItemCount() == 0)181continue;182auto type = table_up->getTableType();183switch (type) {184case PDB_TableType::Symbols:185// This table represents a store of symbols with types listed in186// PDBSym_Type187abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |188LocalVariables | VariableTypes);189break;190case PDB_TableType::LineNumbers:191abilities |= LineTables;192break;193default:194break;195}196}197return abilities;198}199200void SymbolFilePDB::InitializeObject() {201lldb::addr_t obj_load_address =202m_objfile_sp->GetBaseAddress().GetFileAddress();203lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);204m_session_up->setLoadAddress(obj_load_address);205if (!m_global_scope_up)206m_global_scope_up = m_session_up->getGlobalScope();207lldbassert(m_global_scope_up.get());208}209210uint32_t SymbolFilePDB::CalculateNumCompileUnits() {211auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();212if (!compilands)213return 0;214215// The linker could link *.dll (compiland language = LINK), or import216// *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be217// found as a child of the global scope (PDB executable). Usually, such218// compilands contain `thunk` symbols in which we are not interested for219// now. However we still count them in the compiland list. If we perform220// any compiland related activity, like finding symbols through221// llvm::pdb::IPDBSession methods, such compilands will all be searched222// automatically no matter whether we include them or not.223uint32_t compile_unit_count = compilands->getChildCount();224225// The linker can inject an additional "dummy" compilation unit into the226// PDB. Ignore this special compile unit for our purposes, if it is there.227// It is always the last one.228auto last_compiland_up = compilands->getChildAtIndex(compile_unit_count - 1);229lldbassert(last_compiland_up.get());230std::string name = last_compiland_up->getName();231if (name == "* Linker *")232--compile_unit_count;233return compile_unit_count;234}235236void SymbolFilePDB::GetCompileUnitIndex(237const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {238auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();239if (!results_up)240return;241auto uid = pdb_compiland.getSymIndexId();242for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {243auto compiland_up = results_up->getChildAtIndex(cu_idx);244if (!compiland_up)245continue;246if (compiland_up->getSymIndexId() == uid) {247index = cu_idx;248return;249}250}251index = UINT32_MAX;252}253254std::unique_ptr<llvm::pdb::PDBSymbolCompiland>255SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {256return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);257}258259lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {260if (index >= GetNumCompileUnits())261return CompUnitSP();262263// Assuming we always retrieve same compilands listed in same order through264// `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a265// compile unit makes no sense.266auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();267if (!results)268return CompUnitSP();269auto compiland_up = results->getChildAtIndex(index);270if (!compiland_up)271return CompUnitSP();272return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);273}274275lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) {276std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());277auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());278if (!compiland_up)279return lldb::eLanguageTypeUnknown;280auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();281if (!details)282return lldb::eLanguageTypeUnknown;283return TranslateLanguage(details->getLanguage());284}285286lldb_private::Function *287SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func,288CompileUnit &comp_unit) {289if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId()))290return result.get();291292auto file_vm_addr = pdb_func.getVirtualAddress();293if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)294return nullptr;295296auto func_length = pdb_func.getLength();297AddressRange func_range =298AddressRange(file_vm_addr, func_length,299GetObjectFile()->GetModule()->GetSectionList());300if (!func_range.GetBaseAddress().IsValid())301return nullptr;302303lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());304if (!func_type)305return nullptr;306307user_id_t func_type_uid = pdb_func.getSignatureId();308309Mangled mangled = GetMangledForPDBFunc(pdb_func);310311FunctionSP func_sp =312std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(),313func_type_uid, mangled, func_type, func_range);314315comp_unit.AddFunction(func_sp);316317LanguageType lang = ParseLanguage(comp_unit);318auto type_system_or_err = GetTypeSystemForLanguage(lang);319if (auto err = type_system_or_err.takeError()) {320LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),321"Unable to parse PDBFunc: {0}");322return nullptr;323}324325auto ts = *type_system_or_err;326TypeSystemClang *clang_type_system =327llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());328if (!clang_type_system)329return nullptr;330clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func);331332return func_sp.get();333}334335size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) {336std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());337size_t func_added = 0;338auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());339if (!compiland_up)340return 0;341auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();342if (!results_up)343return 0;344while (auto pdb_func_up = results_up->getNext()) {345auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId());346if (!func_sp) {347if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit))348++func_added;349}350}351return func_added;352}353354bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) {355std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());356if (comp_unit.GetLineTable())357return true;358return ParseCompileUnitLineTable(comp_unit, 0);359}360361bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) {362// PDB doesn't contain information about macros363return false;364}365366bool SymbolFilePDB::ParseSupportFiles(367CompileUnit &comp_unit, lldb_private::SupportFileList &support_files) {368369// In theory this is unnecessary work for us, because all of this information370// is easily (and quickly) accessible from DebugInfoPDB, so caching it a371// second time seems like a waste. Unfortunately, there's no good way around372// this short of a moderate refactor since SymbolVendor depends on being able373// to cache this list.374std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());375auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());376if (!compiland_up)377return false;378auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);379if (!files || files->getChildCount() == 0)380return false;381382while (auto file = files->getNext()) {383FileSpec spec(file->getFileName(), FileSpec::Style::windows);384support_files.AppendIfUnique(spec);385}386387return true;388}389390bool SymbolFilePDB::ParseImportedModules(391const lldb_private::SymbolContext &sc,392std::vector<SourceModule> &imported_modules) {393// PDB does not yet support module debug info394return false;395}396397static size_t ParseFunctionBlocksForPDBSymbol(398uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol,399lldb_private::Block *parent_block, bool is_top_parent) {400assert(pdb_symbol && parent_block);401402size_t num_added = 0;403switch (pdb_symbol->getSymTag()) {404case PDB_SymType::Block:405case PDB_SymType::Function: {406Block *block = nullptr;407auto &raw_sym = pdb_symbol->getRawSymbol();408if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {409if (pdb_func->hasNoInlineAttribute())410break;411if (is_top_parent)412block = parent_block;413else414break;415} else if (llvm::isa<PDBSymbolBlock>(pdb_symbol)) {416auto uid = pdb_symbol->getSymIndexId();417if (parent_block->FindBlockByID(uid))418break;419if (raw_sym.getVirtualAddress() < func_file_vm_addr)420break;421422auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());423parent_block->AddChild(block_sp);424block = block_sp.get();425} else426llvm_unreachable("Unexpected PDB symbol!");427428block->AddRange(Block::Range(429raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));430block->FinalizeRanges();431++num_added;432433auto results_up = pdb_symbol->findAllChildren();434if (!results_up)435break;436while (auto symbol_up = results_up->getNext()) {437num_added += ParseFunctionBlocksForPDBSymbol(438func_file_vm_addr, symbol_up.get(), block, false);439}440} break;441default:442break;443}444return num_added;445}446447size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) {448std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());449size_t num_added = 0;450auto uid = func.GetID();451auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);452if (!pdb_func_up)453return 0;454Block &parent_block = func.GetBlock(false);455num_added = ParseFunctionBlocksForPDBSymbol(456pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true);457return num_added;458}459460size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) {461std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());462463size_t num_added = 0;464auto compiland = GetPDBCompilandByUID(comp_unit.GetID());465if (!compiland)466return 0;467468auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {469std::unique_ptr<IPDBEnumSymbols> results;470PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,471PDB_SymType::UDT};472for (auto tag : tags_to_search) {473results = raw_sym.findAllChildren(tag);474if (!results || results->getChildCount() == 0)475continue;476while (auto symbol = results->getNext()) {477switch (symbol->getSymTag()) {478case PDB_SymType::Enum:479case PDB_SymType::UDT:480case PDB_SymType::Typedef:481break;482default:483continue;484}485486// This should cause the type to get cached and stored in the `m_types`487// lookup.488if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {489// Resolve the type completely to avoid a completion490// (and so a list change, which causes an iterators invalidation)491// during a TypeList dumping492type->GetFullCompilerType();493++num_added;494}495}496}497};498499ParseTypesByTagFn(*compiland);500501// Also parse global types particularly coming from this compiland.502// Unfortunately, PDB has no compiland information for each global type. We503// have to parse them all. But ensure we only do this once.504static bool parse_all_global_types = false;505if (!parse_all_global_types) {506ParseTypesByTagFn(*m_global_scope_up);507parse_all_global_types = true;508}509return num_added;510}511512size_t513SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {514std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());515if (!sc.comp_unit)516return 0;517518size_t num_added = 0;519if (sc.function) {520auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(521sc.function->GetID());522if (!pdb_func)523return 0;524525num_added += ParseVariables(sc, *pdb_func);526sc.function->GetBlock(false).SetDidParseVariables(true, true);527} else if (sc.comp_unit) {528auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());529if (!compiland)530return 0;531532if (sc.comp_unit->GetVariableList(false))533return 0;534535auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();536if (results && results->getChildCount()) {537while (auto result = results->getNext()) {538auto cu_id = GetCompilandId(*result);539// FIXME: We are not able to determine variable's compile unit.540if (cu_id == 0)541continue;542543if (cu_id == sc.comp_unit->GetID())544num_added += ParseVariables(sc, *result);545}546}547548// FIXME: A `file static` or `global constant` variable appears both in549// compiland's children and global scope's children with unexpectedly550// different symbol's Id making it ambiguous.551552// FIXME: 'local constant', for example, const char var[] = "abc", declared553// in a function scope, can't be found in PDB.554555// Parse variables in this compiland.556num_added += ParseVariables(sc, *compiland);557}558559return num_added;560}561562lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {563std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());564auto find_result = m_types.find(type_uid);565if (find_result != m_types.end())566return find_result->second.get();567568auto type_system_or_err =569GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);570if (auto err = type_system_or_err.takeError()) {571LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),572"Unable to ResolveTypeUID: {0}");573return nullptr;574}575576auto ts = *type_system_or_err;577TypeSystemClang *clang_type_system =578llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());579if (!clang_type_system)580return nullptr;581PDBASTParser *pdb = clang_type_system->GetPDBParser();582if (!pdb)583return nullptr;584585auto pdb_type = m_session_up->getSymbolById(type_uid);586if (pdb_type == nullptr)587return nullptr;588589lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);590if (result) {591m_types.insert(std::make_pair(type_uid, result));592}593return result.get();594}595596std::optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(597lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {598return std::nullopt;599}600601bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {602std::lock_guard<std::recursive_mutex> guard(603GetObjectFile()->GetModule()->GetMutex());604605auto type_system_or_err =606GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);607if (auto err = type_system_or_err.takeError()) {608LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),609"Unable to get dynamic array info for UID: {0}");610return false;611}612auto ts = *type_system_or_err;613TypeSystemClang *clang_ast_ctx =614llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());615616if (!clang_ast_ctx)617return false;618619PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();620if (!pdb)621return false;622623return pdb->CompleteTypeFromPDB(compiler_type);624}625626lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {627auto type_system_or_err =628GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);629if (auto err = type_system_or_err.takeError()) {630LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),631"Unable to get decl for UID: {0}");632return CompilerDecl();633}634auto ts = *type_system_or_err;635TypeSystemClang *clang_ast_ctx =636llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());637if (!clang_ast_ctx)638return CompilerDecl();639640PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();641if (!pdb)642return CompilerDecl();643644auto symbol = m_session_up->getSymbolById(uid);645if (!symbol)646return CompilerDecl();647648auto decl = pdb->GetDeclForSymbol(*symbol);649if (!decl)650return CompilerDecl();651652return clang_ast_ctx->GetCompilerDecl(decl);653}654655lldb_private::CompilerDeclContext656SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {657auto type_system_or_err =658GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);659if (auto err = type_system_or_err.takeError()) {660LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),661"Unable to get DeclContext for UID: {0}");662return CompilerDeclContext();663}664665auto ts = *type_system_or_err;666TypeSystemClang *clang_ast_ctx =667llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());668if (!clang_ast_ctx)669return CompilerDeclContext();670671PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();672if (!pdb)673return CompilerDeclContext();674675auto symbol = m_session_up->getSymbolById(uid);676if (!symbol)677return CompilerDeclContext();678679auto decl_context = pdb->GetDeclContextForSymbol(*symbol);680if (!decl_context)681return GetDeclContextContainingUID(uid);682683return clang_ast_ctx->CreateDeclContext(decl_context);684}685686lldb_private::CompilerDeclContext687SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {688auto type_system_or_err =689GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);690if (auto err = type_system_or_err.takeError()) {691LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),692"Unable to get DeclContext containing UID: {0}");693return CompilerDeclContext();694}695696auto ts = *type_system_or_err;697TypeSystemClang *clang_ast_ctx =698llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());699if (!clang_ast_ctx)700return CompilerDeclContext();701702PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();703if (!pdb)704return CompilerDeclContext();705706auto symbol = m_session_up->getSymbolById(uid);707if (!symbol)708return CompilerDeclContext();709710auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);711assert(decl_context);712713return clang_ast_ctx->CreateDeclContext(decl_context);714}715716void SymbolFilePDB::ParseDeclsForContext(717lldb_private::CompilerDeclContext decl_ctx) {718auto type_system_or_err =719GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);720if (auto err = type_system_or_err.takeError()) {721LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),722"Unable to parse decls for context: {0}");723return;724}725726auto ts = *type_system_or_err;727TypeSystemClang *clang_ast_ctx =728llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());729if (!clang_ast_ctx)730return;731732PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();733if (!pdb)734return;735736pdb->ParseDeclsForDeclContext(737static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));738}739740uint32_t741SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,742SymbolContextItem resolve_scope,743lldb_private::SymbolContext &sc) {744std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());745uint32_t resolved_flags = 0;746if (resolve_scope & eSymbolContextCompUnit ||747resolve_scope & eSymbolContextVariable ||748resolve_scope & eSymbolContextFunction ||749resolve_scope & eSymbolContextBlock ||750resolve_scope & eSymbolContextLineEntry) {751auto cu_sp = GetCompileUnitContainsAddress(so_addr);752if (!cu_sp) {753if (resolved_flags & eSymbolContextVariable) {754// TODO: Resolve variables755}756return 0;757}758sc.comp_unit = cu_sp.get();759resolved_flags |= eSymbolContextCompUnit;760lldbassert(sc.module_sp == cu_sp->GetModule());761}762763if (resolve_scope & eSymbolContextFunction ||764resolve_scope & eSymbolContextBlock) {765addr_t file_vm_addr = so_addr.GetFileAddress();766auto symbol_up =767m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);768if (symbol_up) {769auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());770assert(pdb_func);771auto func_uid = pdb_func->getSymIndexId();772sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();773if (sc.function == nullptr)774sc.function =775ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit);776if (sc.function) {777resolved_flags |= eSymbolContextFunction;778if (resolve_scope & eSymbolContextBlock) {779auto block_symbol = m_session_up->findSymbolByAddress(780file_vm_addr, PDB_SymType::Block);781auto block_id = block_symbol ? block_symbol->getSymIndexId()782: sc.function->GetID();783sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);784if (sc.block)785resolved_flags |= eSymbolContextBlock;786}787}788}789}790791if (resolve_scope & eSymbolContextLineEntry) {792if (auto *line_table = sc.comp_unit->GetLineTable()) {793Address addr(so_addr);794if (line_table->FindLineEntryByAddress(addr, sc.line_entry))795resolved_flags |= eSymbolContextLineEntry;796}797}798799return resolved_flags;800}801802uint32_t SymbolFilePDB::ResolveSymbolContext(803const lldb_private::SourceLocationSpec &src_location_spec,804SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {805std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());806const size_t old_size = sc_list.GetSize();807const FileSpec &file_spec = src_location_spec.GetFileSpec();808const uint32_t line = src_location_spec.GetLine().value_or(0);809if (resolve_scope & lldb::eSymbolContextCompUnit) {810// Locate all compilation units with line numbers referencing the specified811// file. For example, if `file_spec` is <vector>, then this should return812// all source files and header files that reference <vector>, either813// directly or indirectly.814auto compilands = m_session_up->findCompilandsForSourceFile(815file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);816817if (!compilands)818return 0;819820// For each one, either find its previously parsed data or parse it afresh821// and add it to the symbol context list.822while (auto compiland = compilands->getNext()) {823// If we're not checking inlines, then don't add line information for824// this file unless the FileSpec matches. For inline functions, we don't825// have to match the FileSpec since they could be defined in headers826// other than file specified in FileSpec.827if (!src_location_spec.GetCheckInlines()) {828std::string source_file = compiland->getSourceFileFullPath();829if (source_file.empty())830continue;831FileSpec this_spec(source_file, FileSpec::Style::windows);832bool need_full_match = !file_spec.GetDirectory().IsEmpty();833if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)834continue;835}836837SymbolContext sc;838auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());839if (!cu)840continue;841sc.comp_unit = cu.get();842sc.module_sp = cu->GetModule();843844// If we were asked to resolve line entries, add all entries to the line845// table that match the requested line (or all lines if `line` == 0).846if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |847eSymbolContextLineEntry)) {848bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line);849850if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {851// The query asks for line entries, but we can't get them for the852// compile unit. This is not normal for `line` = 0. So just assert853// it.854assert(line && "Couldn't get all line entries!\n");855856// Current compiland does not have the requested line. Search next.857continue;858}859860if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {861if (!has_line_table)862continue;863864auto *line_table = sc.comp_unit->GetLineTable();865lldbassert(line_table);866867uint32_t num_line_entries = line_table->GetSize();868// Skip the terminal line entry.869--num_line_entries;870871// If `line `!= 0, see if we can resolve function for each line entry872// in the line table.873for (uint32_t line_idx = 0; line && line_idx < num_line_entries;874++line_idx) {875if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))876continue;877878auto file_vm_addr =879sc.line_entry.range.GetBaseAddress().GetFileAddress();880if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)881continue;882883auto symbol_up = m_session_up->findSymbolByAddress(884file_vm_addr, PDB_SymType::Function);885if (symbol_up) {886auto func_uid = symbol_up->getSymIndexId();887sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();888if (sc.function == nullptr) {889auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());890assert(pdb_func);891sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func,892*sc.comp_unit);893}894if (sc.function && (resolve_scope & eSymbolContextBlock)) {895Block &block = sc.function->GetBlock(true);896sc.block = block.FindBlockByID(sc.function->GetID());897}898}899sc_list.Append(sc);900}901} else if (has_line_table) {902// We can parse line table for the compile unit. But no query to903// resolve function or block. We append `sc` to the list anyway.904sc_list.Append(sc);905}906} else {907// No query for line entry, function or block. But we have a valid908// compile unit, append `sc` to the list.909sc_list.Append(sc);910}911}912}913return sc_list.GetSize() - old_size;914}915916std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {917// Cache public names at first918if (m_public_names.empty())919if (auto result_up =920m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))921while (auto symbol_up = result_up->getNext())922if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())923m_public_names[addr] = symbol_up->getRawSymbol().getName();924925// Look up the name in the cache926return m_public_names.lookup(pdb_data.getVirtualAddress());927}928929VariableSP SymbolFilePDB::ParseVariableForPDBData(930const lldb_private::SymbolContext &sc,931const llvm::pdb::PDBSymbolData &pdb_data) {932VariableSP var_sp;933uint32_t var_uid = pdb_data.getSymIndexId();934auto result = m_variables.find(var_uid);935if (result != m_variables.end())936return result->second;937938ValueType scope = eValueTypeInvalid;939bool is_static_member = false;940bool is_external = false;941bool is_artificial = false;942943switch (pdb_data.getDataKind()) {944case PDB_DataKind::Global:945scope = eValueTypeVariableGlobal;946is_external = true;947break;948case PDB_DataKind::Local:949scope = eValueTypeVariableLocal;950break;951case PDB_DataKind::FileStatic:952scope = eValueTypeVariableStatic;953break;954case PDB_DataKind::StaticMember:955is_static_member = true;956scope = eValueTypeVariableStatic;957break;958case PDB_DataKind::Member:959scope = eValueTypeVariableStatic;960break;961case PDB_DataKind::Param:962scope = eValueTypeVariableArgument;963break;964case PDB_DataKind::Constant:965scope = eValueTypeConstResult;966break;967default:968break;969}970971switch (pdb_data.getLocationType()) {972case PDB_LocType::TLS:973scope = eValueTypeVariableThreadLocal;974break;975case PDB_LocType::RegRel: {976// It is a `this` pointer.977if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {978scope = eValueTypeVariableArgument;979is_artificial = true;980}981} break;982default:983break;984}985986Declaration decl;987if (!is_artificial && !pdb_data.isCompilerGenerated()) {988if (auto lines = pdb_data.getLineNumbers()) {989if (auto first_line = lines->getNext()) {990uint32_t src_file_id = first_line->getSourceFileId();991auto src_file = m_session_up->getSourceFileById(src_file_id);992if (src_file) {993FileSpec spec(src_file->getFileName());994decl.SetFile(spec);995decl.SetColumn(first_line->getColumnNumber());996decl.SetLine(first_line->getLineNumber());997}998}999}1000}10011002Variable::RangeList ranges;1003SymbolContextScope *context_scope = sc.comp_unit;1004if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) {1005if (sc.function) {1006Block &function_block = sc.function->GetBlock(true);1007Block *block =1008function_block.FindBlockByID(pdb_data.getLexicalParentId());1009if (!block)1010block = &function_block;10111012context_scope = block;10131014for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges;1015++i) {1016AddressRange range;1017if (!block->GetRangeAtIndex(i, range))1018continue;10191020ranges.Append(range.GetBaseAddress().GetFileAddress(),1021range.GetByteSize());1022}1023}1024}10251026SymbolFileTypeSP type_sp =1027std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());10281029auto var_name = pdb_data.getName();1030auto mangled = GetMangledForPDBData(pdb_data);1031auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();10321033bool is_constant;1034ModuleSP module_sp = GetObjectFile()->GetModule();1035DWARFExpressionList location(module_sp,1036ConvertPDBLocationToDWARFExpression(1037module_sp, pdb_data, ranges, is_constant),1038nullptr);10391040var_sp = std::make_shared<Variable>(1041var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,1042ranges, &decl, location, is_external, is_artificial, is_constant,1043is_static_member);10441045m_variables.insert(std::make_pair(var_uid, var_sp));1046return var_sp;1047}10481049size_t1050SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,1051const llvm::pdb::PDBSymbol &pdb_symbol,1052lldb_private::VariableList *variable_list) {1053size_t num_added = 0;10541055if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {1056VariableListSP local_variable_list_sp;10571058auto result = m_variables.find(pdb_data->getSymIndexId());1059if (result != m_variables.end()) {1060if (variable_list)1061variable_list->AddVariableIfUnique(result->second);1062} else {1063// Prepare right VariableList for this variable.1064if (auto lexical_parent = pdb_data->getLexicalParent()) {1065switch (lexical_parent->getSymTag()) {1066case PDB_SymType::Exe:1067assert(sc.comp_unit);1068[[fallthrough]];1069case PDB_SymType::Compiland: {1070if (sc.comp_unit) {1071local_variable_list_sp = sc.comp_unit->GetVariableList(false);1072if (!local_variable_list_sp) {1073local_variable_list_sp = std::make_shared<VariableList>();1074sc.comp_unit->SetVariableList(local_variable_list_sp);1075}1076}1077} break;1078case PDB_SymType::Block:1079case PDB_SymType::Function: {1080if (sc.function) {1081Block *block = sc.function->GetBlock(true).FindBlockByID(1082lexical_parent->getSymIndexId());1083if (block) {1084local_variable_list_sp = block->GetBlockVariableList(false);1085if (!local_variable_list_sp) {1086local_variable_list_sp = std::make_shared<VariableList>();1087block->SetVariableList(local_variable_list_sp);1088}1089}1090}1091} break;1092default:1093break;1094}1095}10961097if (local_variable_list_sp) {1098if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {1099local_variable_list_sp->AddVariableIfUnique(var_sp);1100if (variable_list)1101variable_list->AddVariableIfUnique(var_sp);1102++num_added;1103PDBASTParser *ast = GetPDBAstParser();1104if (ast)1105ast->GetDeclForSymbol(*pdb_data);1106}1107}1108}1109}11101111if (auto results = pdb_symbol.findAllChildren()) {1112while (auto result = results->getNext())1113num_added += ParseVariables(sc, *result, variable_list);1114}11151116return num_added;1117}11181119void SymbolFilePDB::FindGlobalVariables(1120lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx,1121uint32_t max_matches, lldb_private::VariableList &variables) {1122std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1123if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))1124return;1125if (name.IsEmpty())1126return;11271128auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();1129if (!results)1130return;11311132uint32_t matches = 0;1133size_t old_size = variables.GetSize();1134while (auto result = results->getNext()) {1135auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());1136if (max_matches > 0 && matches >= max_matches)1137break;11381139SymbolContext sc;1140sc.module_sp = m_objfile_sp->GetModule();1141lldbassert(sc.module_sp.get());11421143if (name.GetStringRef() !=1144MSVCUndecoratedNameParser::DropScope(pdb_data->getName()))1145continue;11461147sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();1148// FIXME: We are not able to determine the compile unit.1149if (sc.comp_unit == nullptr)1150continue;11511152if (parent_decl_ctx.IsValid() &&1153GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx)1154continue;11551156ParseVariables(sc, *pdb_data, &variables);1157matches = variables.GetSize() - old_size;1158}1159}11601161void SymbolFilePDB::FindGlobalVariables(1162const lldb_private::RegularExpression ®ex, uint32_t max_matches,1163lldb_private::VariableList &variables) {1164std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1165if (!regex.IsValid())1166return;1167auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();1168if (!results)1169return;11701171uint32_t matches = 0;1172size_t old_size = variables.GetSize();1173while (auto pdb_data = results->getNext()) {1174if (max_matches > 0 && matches >= max_matches)1175break;11761177auto var_name = pdb_data->getName();1178if (var_name.empty())1179continue;1180if (!regex.Execute(var_name))1181continue;1182SymbolContext sc;1183sc.module_sp = m_objfile_sp->GetModule();1184lldbassert(sc.module_sp.get());11851186sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();1187// FIXME: We are not able to determine the compile unit.1188if (sc.comp_unit == nullptr)1189continue;11901191ParseVariables(sc, *pdb_data, &variables);1192matches = variables.GetSize() - old_size;1193}1194}11951196bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,1197bool include_inlines,1198lldb_private::SymbolContextList &sc_list) {1199lldb_private::SymbolContext sc;1200sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();1201if (!sc.comp_unit)1202return false;1203sc.module_sp = sc.comp_unit->GetModule();1204sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit);1205if (!sc.function)1206return false;12071208sc_list.Append(sc);1209return true;1210}12111212bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,1213lldb_private::SymbolContextList &sc_list) {1214auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);1215if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))1216return false;1217return ResolveFunction(*pdb_func_up, include_inlines, sc_list);1218}12191220void SymbolFilePDB::CacheFunctionNames() {1221if (!m_func_full_names.IsEmpty())1222return;12231224std::map<uint64_t, uint32_t> addr_ids;12251226if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {1227while (auto pdb_func_up = results_up->getNext()) {1228if (pdb_func_up->isCompilerGenerated())1229continue;12301231auto name = pdb_func_up->getName();1232auto demangled_name = pdb_func_up->getUndecoratedName();1233if (name.empty() && demangled_name.empty())1234continue;12351236auto uid = pdb_func_up->getSymIndexId();1237if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())1238addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));12391240if (auto parent = pdb_func_up->getClassParent()) {12411242// PDB have symbols for class/struct methods or static methods in Enum1243// Class. We won't bother to check if the parent is UDT or Enum here.1244m_func_method_names.Append(ConstString(name), uid);12451246// To search a method name, like NS::Class:MemberFunc, LLDB searches1247// its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does1248// not have information of this, we extract base names and cache them1249// by our own effort.1250llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);1251if (!basename.empty())1252m_func_base_names.Append(ConstString(basename), uid);1253else {1254m_func_base_names.Append(ConstString(name), uid);1255}12561257if (!demangled_name.empty())1258m_func_full_names.Append(ConstString(demangled_name), uid);12591260} else {1261// Handle not-method symbols.12621263// The function name might contain namespace, or its lexical scope.1264llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);1265if (!basename.empty())1266m_func_base_names.Append(ConstString(basename), uid);1267else1268m_func_base_names.Append(ConstString(name), uid);12691270if (name == "main") {1271m_func_full_names.Append(ConstString(name), uid);12721273if (!demangled_name.empty() && name != demangled_name) {1274m_func_full_names.Append(ConstString(demangled_name), uid);1275m_func_base_names.Append(ConstString(demangled_name), uid);1276}1277} else if (!demangled_name.empty()) {1278m_func_full_names.Append(ConstString(demangled_name), uid);1279} else {1280m_func_full_names.Append(ConstString(name), uid);1281}1282}1283}1284}12851286if (auto results_up =1287m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {1288while (auto pub_sym_up = results_up->getNext()) {1289if (!pub_sym_up->isFunction())1290continue;1291auto name = pub_sym_up->getName();1292if (name.empty())1293continue;12941295if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {1296auto vm_addr = pub_sym_up->getVirtualAddress();12971298// PDB public symbol has mangled name for its associated function.1299if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {1300// Cache mangled name.1301m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);1302}1303}1304}1305}1306// Sort them before value searching is working properly1307m_func_full_names.Sort();1308m_func_full_names.SizeToFit();1309m_func_method_names.Sort();1310m_func_method_names.SizeToFit();1311m_func_base_names.Sort();1312m_func_base_names.SizeToFit();1313}13141315void SymbolFilePDB::FindFunctions(1316const lldb_private::Module::LookupInfo &lookup_info,1317const lldb_private::CompilerDeclContext &parent_decl_ctx,1318bool include_inlines,1319lldb_private::SymbolContextList &sc_list) {1320std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1321ConstString name = lookup_info.GetLookupName();1322FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();1323lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);13241325if (name_type_mask & eFunctionNameTypeFull)1326name = lookup_info.GetName();13271328if (name_type_mask == eFunctionNameTypeNone)1329return;1330if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))1331return;1332if (name.IsEmpty())1333return;13341335if (name_type_mask & eFunctionNameTypeFull ||1336name_type_mask & eFunctionNameTypeBase ||1337name_type_mask & eFunctionNameTypeMethod) {1338CacheFunctionNames();13391340std::set<uint32_t> resolved_ids;1341auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,1342&resolved_ids](UniqueCStringMap<uint32_t> &Names) {1343std::vector<uint32_t> ids;1344if (!Names.GetValues(name, ids))1345return;13461347for (uint32_t id : ids) {1348if (resolved_ids.find(id) != resolved_ids.end())1349continue;13501351if (parent_decl_ctx.IsValid() &&1352GetDeclContextContainingUID(id) != parent_decl_ctx)1353continue;13541355if (ResolveFunction(id, include_inlines, sc_list))1356resolved_ids.insert(id);1357}1358};1359if (name_type_mask & eFunctionNameTypeFull) {1360ResolveFn(m_func_full_names);1361ResolveFn(m_func_base_names);1362ResolveFn(m_func_method_names);1363}1364if (name_type_mask & eFunctionNameTypeBase)1365ResolveFn(m_func_base_names);1366if (name_type_mask & eFunctionNameTypeMethod)1367ResolveFn(m_func_method_names);1368}1369}13701371void SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex,1372bool include_inlines,1373lldb_private::SymbolContextList &sc_list) {1374std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1375if (!regex.IsValid())1376return;13771378CacheFunctionNames();13791380std::set<uint32_t> resolved_ids;1381auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids,1382this](UniqueCStringMap<uint32_t> &Names) {1383std::vector<uint32_t> ids;1384if (Names.GetValues(regex, ids)) {1385for (auto id : ids) {1386if (resolved_ids.find(id) == resolved_ids.end())1387if (ResolveFunction(id, include_inlines, sc_list))1388resolved_ids.insert(id);1389}1390}1391};1392ResolveFn(m_func_full_names);1393ResolveFn(m_func_base_names);1394}13951396void SymbolFilePDB::GetMangledNamesForFunction(1397const std::string &scope_qualified_name,1398std::vector<lldb_private::ConstString> &mangled_names) {}13991400void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) {1401std::set<lldb::addr_t> sym_addresses;1402for (size_t i = 0; i < symtab.GetNumSymbols(); i++)1403sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());14041405auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();1406if (!results)1407return;14081409auto section_list = m_objfile_sp->GetSectionList();1410if (!section_list)1411return;14121413while (auto pub_symbol = results->getNext()) {1414auto section_id = pub_symbol->getAddressSection();14151416auto section = section_list->FindSectionByID(section_id);1417if (!section)1418continue;14191420auto offset = pub_symbol->getAddressOffset();14211422auto file_addr = section->GetFileAddress() + offset;1423if (sym_addresses.find(file_addr) != sym_addresses.end())1424continue;1425sym_addresses.insert(file_addr);14261427auto size = pub_symbol->getLength();1428symtab.AddSymbol(1429Symbol(pub_symbol->getSymIndexId(), // symID1430pub_symbol->getName().c_str(), // name1431pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type1432true, // external1433false, // is_debug1434false, // is_trampoline1435false, // is_artificial1436section, // section_sp1437offset, // value1438size, // size1439size != 0, // size_is_valid1440false, // contains_linker_annotations14410 // flags1442));1443}14441445symtab.Finalize();1446}14471448void SymbolFilePDB::DumpClangAST(Stream &s) {1449auto type_system_or_err =1450GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);1451if (auto err = type_system_or_err.takeError()) {1452LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),1453"Unable to dump ClangAST: {0}");1454return;1455}14561457auto ts = *type_system_or_err;1458TypeSystemClang *clang_type_system =1459llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());1460if (!clang_type_system)1461return;1462clang_type_system->Dump(s.AsRawOstream());1463}14641465void SymbolFilePDB::FindTypesByRegex(1466const lldb_private::RegularExpression ®ex, uint32_t max_matches,1467lldb_private::TypeMap &types) {1468// When searching by regex, we need to go out of our way to limit the search1469// space as much as possible since this searches EVERYTHING in the PDB,1470// manually doing regex comparisons. PDB library isn't optimized for regex1471// searches or searches across multiple symbol types at the same time, so the1472// best we can do is to search enums, then typedefs, then classes one by one,1473// and do a regex comparison against each of them.1474PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,1475PDB_SymType::UDT};1476std::unique_ptr<IPDBEnumSymbols> results;14771478uint32_t matches = 0;14791480for (auto tag : tags_to_search) {1481results = m_global_scope_up->findAllChildren(tag);1482if (!results)1483continue;14841485while (auto result = results->getNext()) {1486if (max_matches > 0 && matches >= max_matches)1487break;14881489std::string type_name;1490if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))1491type_name = enum_type->getName();1492else if (auto typedef_type =1493llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))1494type_name = typedef_type->getName();1495else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))1496type_name = class_type->getName();1497else {1498// We're looking only for types that have names. Skip symbols, as well1499// as unnamed types such as arrays, pointers, etc.1500continue;1501}15021503if (!regex.Execute(type_name))1504continue;15051506// This should cause the type to get cached and stored in the `m_types`1507// lookup.1508if (!ResolveTypeUID(result->getSymIndexId()))1509continue;15101511auto iter = m_types.find(result->getSymIndexId());1512if (iter == m_types.end())1513continue;1514types.Insert(iter->second);1515++matches;1516}1517}1518}15191520void SymbolFilePDB::FindTypes(const lldb_private::TypeQuery &query,1521lldb_private::TypeResults &type_results) {15221523// Make sure we haven't already searched this SymbolFile before.1524if (type_results.AlreadySearched(this))1525return;15261527std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());15281529std::unique_ptr<IPDBEnumSymbols> results;1530llvm::StringRef basename = query.GetTypeBasename().GetStringRef();1531if (basename.empty())1532return;1533results = m_global_scope_up->findAllChildren(PDB_SymType::None);1534if (!results)1535return;15361537while (auto result = results->getNext()) {15381539switch (result->getSymTag()) {1540case PDB_SymType::Enum:1541case PDB_SymType::UDT:1542case PDB_SymType::Typedef:1543break;1544default:1545// We're looking only for types that have names. Skip symbols, as well1546// as unnamed types such as arrays, pointers, etc.1547continue;1548}15491550if (MSVCUndecoratedNameParser::DropScope(1551result->getRawSymbol().getName()) != basename)1552continue;15531554// This should cause the type to get cached and stored in the `m_types`1555// lookup.1556if (!ResolveTypeUID(result->getSymIndexId()))1557continue;15581559auto iter = m_types.find(result->getSymIndexId());1560if (iter == m_types.end())1561continue;1562// We resolved a type. Get the fully qualified name to ensure it matches.1563ConstString name = iter->second->GetQualifiedName();1564TypeQuery type_match(name.GetStringRef(), TypeQueryOptions::e_exact_match);1565if (query.ContextMatches(type_match.GetContextRef())) {1566type_results.InsertUnique(iter->second);1567if (type_results.Done(query))1568return;1569}1570}1571}15721573void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,1574uint32_t type_mask,1575TypeCollection &type_collection) {1576bool can_parse = false;1577switch (pdb_symbol.getSymTag()) {1578case PDB_SymType::ArrayType:1579can_parse = ((type_mask & eTypeClassArray) != 0);1580break;1581case PDB_SymType::BuiltinType:1582can_parse = ((type_mask & eTypeClassBuiltin) != 0);1583break;1584case PDB_SymType::Enum:1585can_parse = ((type_mask & eTypeClassEnumeration) != 0);1586break;1587case PDB_SymType::Function:1588case PDB_SymType::FunctionSig:1589can_parse = ((type_mask & eTypeClassFunction) != 0);1590break;1591case PDB_SymType::PointerType:1592can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |1593eTypeClassMemberPointer)) != 0);1594break;1595case PDB_SymType::Typedef:1596can_parse = ((type_mask & eTypeClassTypedef) != 0);1597break;1598case PDB_SymType::UDT: {1599auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);1600assert(udt);1601can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&1602((type_mask & (eTypeClassClass | eTypeClassStruct |1603eTypeClassUnion)) != 0));1604} break;1605default:1606break;1607}16081609if (can_parse) {1610if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {1611if (!llvm::is_contained(type_collection, type))1612type_collection.push_back(type);1613}1614}16151616auto results_up = pdb_symbol.findAllChildren();1617while (auto symbol_up = results_up->getNext())1618GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);1619}16201621void SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,1622TypeClass type_mask,1623lldb_private::TypeList &type_list) {1624std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1625TypeCollection type_collection;1626CompileUnit *cu =1627sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;1628if (cu) {1629auto compiland_up = GetPDBCompilandByUID(cu->GetID());1630if (!compiland_up)1631return;1632GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);1633} else {1634for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {1635auto cu_sp = ParseCompileUnitAtIndex(cu_idx);1636if (cu_sp) {1637if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))1638GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);1639}1640}1641}16421643for (auto type : type_collection) {1644type->GetForwardCompilerType();1645type_list.Insert(type->shared_from_this());1646}1647}16481649llvm::Expected<lldb::TypeSystemSP>1650SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {1651auto type_system_or_err =1652m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);1653if (type_system_or_err) {1654if (auto ts = *type_system_or_err)1655ts->SetSymbolFile(this);1656}1657return type_system_or_err;1658}16591660PDBASTParser *SymbolFilePDB::GetPDBAstParser() {1661auto type_system_or_err =1662GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);1663if (auto err = type_system_or_err.takeError()) {1664LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),1665"Unable to get PDB AST parser: {0}");1666return nullptr;1667}16681669auto ts = *type_system_or_err;1670auto *clang_type_system =1671llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());1672if (!clang_type_system)1673return nullptr;16741675return clang_type_system->GetPDBParser();1676}16771678lldb_private::CompilerDeclContext1679SymbolFilePDB::FindNamespace(lldb_private::ConstString name,1680const CompilerDeclContext &parent_decl_ctx, bool) {1681std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());1682auto type_system_or_err =1683GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);1684if (auto err = type_system_or_err.takeError()) {1685LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),1686"Unable to find namespace {1}: {0}", name.AsCString());1687return CompilerDeclContext();1688}1689auto ts = *type_system_or_err;1690auto *clang_type_system =1691llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());1692if (!clang_type_system)1693return CompilerDeclContext();16941695PDBASTParser *pdb = clang_type_system->GetPDBParser();1696if (!pdb)1697return CompilerDeclContext();16981699clang::DeclContext *decl_context = nullptr;1700if (parent_decl_ctx)1701decl_context = static_cast<clang::DeclContext *>(1702parent_decl_ctx.GetOpaqueDeclContext());17031704auto namespace_decl =1705pdb->FindNamespaceDecl(decl_context, name.GetStringRef());1706if (!namespace_decl)1707return CompilerDeclContext();17081709return clang_type_system->CreateDeclContext(namespace_decl);1710}17111712IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }17131714const IPDBSession &SymbolFilePDB::GetPDBSession() const {1715return *m_session_up;1716}17171718lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,1719uint32_t index) {1720auto found_cu = m_comp_units.find(id);1721if (found_cu != m_comp_units.end())1722return found_cu->second;17231724auto compiland_up = GetPDBCompilandByUID(id);1725if (!compiland_up)1726return CompUnitSP();17271728lldb::LanguageType lang;1729auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();1730if (!details)1731lang = lldb::eLanguageTypeC_plus_plus;1732else1733lang = TranslateLanguage(details->getLanguage());17341735if (lang == lldb::LanguageType::eLanguageTypeUnknown)1736return CompUnitSP();17371738std::string path = compiland_up->getSourceFileFullPath();1739if (path.empty())1740return CompUnitSP();17411742// Don't support optimized code for now, DebugInfoPDB does not return this1743// information.1744LazyBool optimized = eLazyBoolNo;1745auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr,1746path.c_str(), id, lang, optimized);17471748if (!cu_sp)1749return CompUnitSP();17501751m_comp_units.insert(std::make_pair(id, cu_sp));1752if (index == UINT32_MAX)1753GetCompileUnitIndex(*compiland_up, index);1754lldbassert(index != UINT32_MAX);1755SetCompileUnitAtIndex(index, cu_sp);1756return cu_sp;1757}17581759bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,1760uint32_t match_line) {1761auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());1762if (!compiland_up)1763return false;17641765// LineEntry needs the *index* of the file into the list of support files1766// returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us1767// a globally unique idenfitifier in the namespace of the PDB. So, we have1768// to do a mapping so that we can hand out indices.1769llvm::DenseMap<uint32_t, uint32_t> index_map;1770BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);1771auto line_table = std::make_unique<LineTable>(&comp_unit);17721773// Find contributions to `compiland` from all source and header files.1774auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);1775if (!files)1776return false;17771778// For each source and header file, create a LineSequence for contributions1779// to the compiland from that file, and add the sequence.1780while (auto file = files->getNext()) {1781std::unique_ptr<LineSequence> sequence(1782line_table->CreateLineSequenceContainer());1783auto lines = m_session_up->findLineNumbers(*compiland_up, *file);1784if (!lines)1785continue;1786int entry_count = lines->getChildCount();17871788uint64_t prev_addr;1789uint32_t prev_length;1790uint32_t prev_line;1791uint32_t prev_source_idx;17921793for (int i = 0; i < entry_count; ++i) {1794auto line = lines->getChildAtIndex(i);17951796uint64_t lno = line->getLineNumber();1797uint64_t addr = line->getVirtualAddress();1798uint32_t length = line->getLength();1799uint32_t source_id = line->getSourceFileId();1800uint32_t col = line->getColumnNumber();1801uint32_t source_idx = index_map[source_id];18021803// There was a gap between the current entry and the previous entry if1804// the addresses don't perfectly line up.1805bool is_gap = (i > 0) && (prev_addr + prev_length < addr);18061807// Before inserting the current entry, insert a terminal entry at the end1808// of the previous entry's address range if the current entry resulted in1809// a gap from the previous entry.1810if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {1811line_table->AppendLineEntryToSequence(1812sequence.get(), prev_addr + prev_length, prev_line, 0,1813prev_source_idx, false, false, false, false, true);18141815line_table->InsertSequence(sequence.get());1816sequence = line_table->CreateLineSequenceContainer();1817}18181819if (ShouldAddLine(match_line, lno, length)) {1820bool is_statement = line->isStatement();1821bool is_prologue = false;1822bool is_epilogue = false;1823auto func =1824m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);1825if (func) {1826auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();1827if (prologue)1828is_prologue = (addr == prologue->getVirtualAddress());18291830auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();1831if (epilogue)1832is_epilogue = (addr == epilogue->getVirtualAddress());1833}18341835line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,1836source_idx, is_statement, false,1837is_prologue, is_epilogue, false);1838}18391840prev_addr = addr;1841prev_length = length;1842prev_line = lno;1843prev_source_idx = source_idx;1844}18451846if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {1847// The end is always a terminal entry, so insert it regardless.1848line_table->AppendLineEntryToSequence(1849sequence.get(), prev_addr + prev_length, prev_line, 0,1850prev_source_idx, false, false, false, false, true);1851}18521853line_table->InsertSequence(sequence.get());1854}18551856if (line_table->GetSize()) {1857comp_unit.SetLineTable(line_table.release());1858return true;1859}1860return false;1861}18621863void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(1864const PDBSymbolCompiland &compiland,1865llvm::DenseMap<uint32_t, uint32_t> &index_map) const {1866// This is a hack, but we need to convert the source id into an index into1867// the support files array. We don't want to do path comparisons to avoid1868// basename / full path issues that may or may not even be a problem, so we1869// use the globally unique source file identifiers. Ideally we could use the1870// global identifiers everywhere, but LineEntry currently assumes indices.1871auto source_files = m_session_up->getSourceFilesForCompiland(compiland);1872if (!source_files)1873return;18741875int index = 0;1876while (auto file = source_files->getNext()) {1877uint32_t source_id = file->getUniqueId();1878index_map[source_id] = index++;1879}1880}18811882lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(1883const lldb_private::Address &so_addr) {1884lldb::addr_t file_vm_addr = so_addr.GetFileAddress();1885if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)1886return nullptr;18871888// If it is a PDB function's vm addr, this is the first sure bet.1889if (auto lines =1890m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {1891if (auto first_line = lines->getNext())1892return ParseCompileUnitForUID(first_line->getCompilandId());1893}18941895// Otherwise we resort to section contributions.1896if (auto sec_contribs = m_session_up->getSectionContribs()) {1897while (auto section = sec_contribs->getNext()) {1898auto va = section->getVirtualAddress();1899if (file_vm_addr >= va && file_vm_addr < va + section->getLength())1900return ParseCompileUnitForUID(section->getCompilandId());1901}1902}1903return nullptr;1904}19051906Mangled1907SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {1908Mangled mangled;1909auto func_name = pdb_func.getName();1910auto func_undecorated_name = pdb_func.getUndecoratedName();1911std::string func_decorated_name;19121913// Seek from public symbols for non-static function's decorated name if any.1914// For static functions, they don't have undecorated names and aren't exposed1915// in Public Symbols either.1916if (!func_undecorated_name.empty()) {1917auto result_up = m_global_scope_up->findChildren(1918PDB_SymType::PublicSymbol, func_undecorated_name,1919PDB_NameSearchFlags::NS_UndecoratedName);1920if (result_up) {1921while (auto symbol_up = result_up->getNext()) {1922// For a public symbol, it is unique.1923lldbassert(result_up->getChildCount() == 1);1924if (auto *pdb_public_sym =1925llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(1926symbol_up.get())) {1927if (pdb_public_sym->isFunction()) {1928func_decorated_name = pdb_public_sym->getName();1929break;1930}1931}1932}1933}1934}1935if (!func_decorated_name.empty()) {1936mangled.SetMangledName(ConstString(func_decorated_name));19371938// For MSVC, format of C function's decorated name depends on calling1939// convention. Unfortunately none of the format is recognized by current1940// LLDB. For example, `_purecall` is a __cdecl C function. From PDB,1941// `__purecall` is retrieved as both its decorated and undecorated name1942// (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`1943// string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).1944// Mangled::GetDemangledName method will fail internally and caches an1945// empty string as its undecorated name. So we will face a contradiction1946// here for the same symbol:1947// non-empty undecorated name from PDB1948// empty undecorated name from LLDB1949if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty())1950mangled.SetDemangledName(ConstString(func_undecorated_name));19511952// LLDB uses several flags to control how a C++ decorated name is1953// undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the1954// yielded name could be different from what we retrieve from1955// PDB source unless we also apply same flags in getting undecorated1956// name through PDBSymbolFunc::getUndecoratedNameEx method.1957if (!func_undecorated_name.empty() &&1958mangled.GetDemangledName() != ConstString(func_undecorated_name))1959mangled.SetDemangledName(ConstString(func_undecorated_name));1960} else if (!func_undecorated_name.empty()) {1961mangled.SetDemangledName(ConstString(func_undecorated_name));1962} else if (!func_name.empty())1963mangled.SetValue(ConstString(func_name));19641965return mangled;1966}19671968bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(1969const lldb_private::CompilerDeclContext &decl_ctx) {1970if (!decl_ctx.IsValid())1971return true;19721973TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();1974if (!decl_ctx_type_system)1975return false;1976auto type_system_or_err = GetTypeSystemForLanguage(1977decl_ctx_type_system->GetMinimumLanguage(nullptr));1978if (auto err = type_system_or_err.takeError()) {1979LLDB_LOG_ERROR(1980GetLog(LLDBLog::Symbols), std::move(err),1981"Unable to determine if DeclContext matches this symbol file: {0}");1982return false;1983}19841985if (decl_ctx_type_system == type_system_or_err->get())1986return true; // The type systems match, return true19871988return false;1989}19901991uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {1992static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {1993return lhs < rhs.Offset;1994};19951996// Cache section contributions1997if (m_sec_contribs.empty()) {1998if (auto SecContribs = m_session_up->getSectionContribs()) {1999while (auto SectionContrib = SecContribs->getNext()) {2000auto comp_id = SectionContrib->getCompilandId();2001if (!comp_id)2002continue;20032004auto sec = SectionContrib->getAddressSection();2005auto &sec_cs = m_sec_contribs[sec];20062007auto offset = SectionContrib->getAddressOffset();2008auto it = llvm::upper_bound(sec_cs, offset, pred_upper);20092010auto size = SectionContrib->getLength();2011sec_cs.insert(it, {offset, size, comp_id});2012}2013}2014}20152016// Check by line number2017if (auto Lines = data.getLineNumbers()) {2018if (auto FirstLine = Lines->getNext())2019return FirstLine->getCompilandId();2020}20212022// Retrieve section + offset2023uint32_t DataSection = data.getAddressSection();2024uint32_t DataOffset = data.getAddressOffset();2025if (DataSection == 0) {2026if (auto RVA = data.getRelativeVirtualAddress())2027m_session_up->addressForRVA(RVA, DataSection, DataOffset);2028}20292030if (DataSection) {2031// Search by section contributions2032auto &sec_cs = m_sec_contribs[DataSection];2033auto it = llvm::upper_bound(sec_cs, DataOffset, pred_upper);2034if (it != sec_cs.begin()) {2035--it;2036if (DataOffset < it->Offset + it->Size)2037return it->CompilandId;2038}2039} else {2040// Search in lexical tree2041auto LexParentId = data.getLexicalParentId();2042while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {2043if (LexParent->getSymTag() == PDB_SymType::Exe)2044break;2045if (LexParent->getSymTag() == PDB_SymType::Compiland)2046return LexParentId;2047LexParentId = LexParent->getRawSymbol().getLexicalParentId();2048}2049}20502051return 0;2052}205320542055