1 //===-- SymbolFilePDB.cpp -------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "SymbolFilePDB.h" 10 11 #include "PDBASTParser.h" 12 #include "PDBLocationToDWARFExpression.h" 13 14 #include "clang/Lex/Lexer.h" 15 16 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 17 #include "lldb/Core/Module.h" 18 #include "lldb/Core/PluginManager.h" 19 #include "lldb/Symbol/CompileUnit.h" 20 #include "lldb/Symbol/LineTable.h" 21 #include "lldb/Symbol/ObjectFile.h" 22 #include "lldb/Symbol/SymbolContext.h" 23 #include "lldb/Symbol/SymbolVendor.h" 24 #include "lldb/Symbol/TypeList.h" 25 #include "lldb/Symbol/TypeMap.h" 26 #include "lldb/Symbol/Variable.h" 27 #include "lldb/Utility/LLDBLog.h" 28 #include "lldb/Utility/Log.h" 29 #include "lldb/Utility/RegularExpression.h" 30 31 #include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h" 32 #include "llvm/DebugInfo/PDB/GenericError.h" 33 #include "llvm/DebugInfo/PDB/IPDBDataStream.h" 34 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" 35 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h" 36 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h" 37 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h" 38 #include "llvm/DebugInfo/PDB/IPDBTable.h" 39 #include "llvm/DebugInfo/PDB/PDBSymbol.h" 40 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h" 41 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h" 42 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h" 43 #include "llvm/DebugInfo/PDB/PDBSymbolData.h" 44 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h" 45 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" 46 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" 47 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" 48 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h" 49 #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" 50 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" 51 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" 52 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" 53 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" 54 55 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" 56 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" 57 #include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h" 58 59 #if defined(_WIN32) 60 #include "llvm/Config/llvm-config.h" 61 #endif 62 63 using namespace lldb; 64 using namespace lldb_private; 65 using namespace llvm::pdb; 66 67 LLDB_PLUGIN_DEFINE(SymbolFilePDB) 68 69 char SymbolFilePDB::ID; 70 71 namespace { 72 lldb::LanguageType TranslateLanguage(PDB_Lang lang) { 73 switch (lang) { 74 case PDB_Lang::Cpp: 75 return lldb::LanguageType::eLanguageTypeC_plus_plus; 76 case PDB_Lang::C: 77 return lldb::LanguageType::eLanguageTypeC; 78 case PDB_Lang::Swift: 79 return lldb::LanguageType::eLanguageTypeSwift; 80 case PDB_Lang::Rust: 81 return lldb::LanguageType::eLanguageTypeRust; 82 default: 83 return lldb::LanguageType::eLanguageTypeUnknown; 84 } 85 } 86 87 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line, 88 uint32_t addr_length) { 89 return ((requested_line == 0 || actual_line == requested_line) && 90 addr_length > 0); 91 } 92 } // namespace 93 94 static bool ShouldUseNativeReader() { 95 #if defined(_WIN32) 96 #if LLVM_ENABLE_DIA_SDK 97 llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER"); 98 if (!use_native.equals_insensitive("on") && 99 !use_native.equals_insensitive("yes") && 100 !use_native.equals_insensitive("1") && 101 !use_native.equals_insensitive("true")) 102 return false; 103 #endif 104 #endif 105 return true; 106 } 107 108 void SymbolFilePDB::Initialize() { 109 if (ShouldUseNativeReader()) { 110 npdb::SymbolFileNativePDB::Initialize(); 111 } else { 112 PluginManager::RegisterPlugin(GetPluginNameStatic(), 113 GetPluginDescriptionStatic(), CreateInstance, 114 DebuggerInitialize); 115 } 116 } 117 118 void SymbolFilePDB::Terminate() { 119 if (ShouldUseNativeReader()) { 120 npdb::SymbolFileNativePDB::Terminate(); 121 } else { 122 PluginManager::UnregisterPlugin(CreateInstance); 123 } 124 } 125 126 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {} 127 128 llvm::StringRef SymbolFilePDB::GetPluginDescriptionStatic() { 129 return "Microsoft PDB debug symbol file reader."; 130 } 131 132 lldb_private::SymbolFile * 133 SymbolFilePDB::CreateInstance(ObjectFileSP objfile_sp) { 134 return new SymbolFilePDB(std::move(objfile_sp)); 135 } 136 137 SymbolFilePDB::SymbolFilePDB(lldb::ObjectFileSP objfile_sp) 138 : SymbolFileCommon(std::move(objfile_sp)), m_session_up(), m_global_scope_up() {} 139 140 SymbolFilePDB::~SymbolFilePDB() = default; 141 142 uint32_t SymbolFilePDB::CalculateAbilities() { 143 uint32_t abilities = 0; 144 if (!m_objfile_sp) 145 return 0; 146 147 if (!m_session_up) { 148 // Lazily load and match the PDB file, but only do this once. 149 std::string exePath = m_objfile_sp->GetFileSpec().GetPath(); 150 auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath), 151 m_session_up); 152 if (error) { 153 llvm::consumeError(std::move(error)); 154 auto module_sp = m_objfile_sp->GetModule(); 155 if (!module_sp) 156 return 0; 157 // See if any symbol file is specified through `--symfile` option. 158 FileSpec symfile = module_sp->GetSymbolFileFileSpec(); 159 if (!symfile) 160 return 0; 161 error = loadDataForPDB(PDB_ReaderType::DIA, 162 llvm::StringRef(symfile.GetPath()), m_session_up); 163 if (error) { 164 llvm::consumeError(std::move(error)); 165 return 0; 166 } 167 } 168 } 169 if (!m_session_up) 170 return 0; 171 172 auto enum_tables_up = m_session_up->getEnumTables(); 173 if (!enum_tables_up) 174 return 0; 175 while (auto table_up = enum_tables_up->getNext()) { 176 if (table_up->getItemCount() == 0) 177 continue; 178 auto type = table_up->getTableType(); 179 switch (type) { 180 case PDB_TableType::Symbols: 181 // This table represents a store of symbols with types listed in 182 // PDBSym_Type 183 abilities |= (CompileUnits | Functions | Blocks | GlobalVariables | 184 LocalVariables | VariableTypes); 185 break; 186 case PDB_TableType::LineNumbers: 187 abilities |= LineTables; 188 break; 189 default: 190 break; 191 } 192 } 193 return abilities; 194 } 195 196 void SymbolFilePDB::InitializeObject() { 197 lldb::addr_t obj_load_address = 198 m_objfile_sp->GetBaseAddress().GetFileAddress(); 199 lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS); 200 m_session_up->setLoadAddress(obj_load_address); 201 if (!m_global_scope_up) 202 m_global_scope_up = m_session_up->getGlobalScope(); 203 lldbassert(m_global_scope_up.get()); 204 } 205 206 uint32_t SymbolFilePDB::CalculateNumCompileUnits() { 207 auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); 208 if (!compilands) 209 return 0; 210 211 // The linker could link *.dll (compiland language = LINK), or import 212 // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be 213 // found as a child of the global scope (PDB executable). Usually, such 214 // compilands contain `thunk` symbols in which we are not interested for 215 // now. However we still count them in the compiland list. If we perform 216 // any compiland related activity, like finding symbols through 217 // llvm::pdb::IPDBSession methods, such compilands will all be searched 218 // automatically no matter whether we include them or not. 219 uint32_t compile_unit_count = compilands->getChildCount(); 220 221 // The linker can inject an additional "dummy" compilation unit into the 222 // PDB. Ignore this special compile unit for our purposes, if it is there. 223 // It is always the last one. 224 auto last_compiland_up = compilands->getChildAtIndex(compile_unit_count - 1); 225 lldbassert(last_compiland_up.get()); 226 std::string name = last_compiland_up->getName(); 227 if (name == "* Linker *") 228 --compile_unit_count; 229 return compile_unit_count; 230 } 231 232 void SymbolFilePDB::GetCompileUnitIndex( 233 const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) { 234 auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); 235 if (!results_up) 236 return; 237 auto uid = pdb_compiland.getSymIndexId(); 238 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) { 239 auto compiland_up = results_up->getChildAtIndex(cu_idx); 240 if (!compiland_up) 241 continue; 242 if (compiland_up->getSymIndexId() == uid) { 243 index = cu_idx; 244 return; 245 } 246 } 247 index = UINT32_MAX; 248 } 249 250 std::unique_ptr<llvm::pdb::PDBSymbolCompiland> 251 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) { 252 return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid); 253 } 254 255 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) { 256 if (index >= GetNumCompileUnits()) 257 return CompUnitSP(); 258 259 // Assuming we always retrieve same compilands listed in same order through 260 // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a 261 // compile unit makes no sense. 262 auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>(); 263 if (!results) 264 return CompUnitSP(); 265 auto compiland_up = results->getChildAtIndex(index); 266 if (!compiland_up) 267 return CompUnitSP(); 268 return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index); 269 } 270 271 lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) { 272 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 273 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); 274 if (!compiland_up) 275 return lldb::eLanguageTypeUnknown; 276 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>(); 277 if (!details) 278 return lldb::eLanguageTypeUnknown; 279 return TranslateLanguage(details->getLanguage()); 280 } 281 282 lldb_private::Function * 283 SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func, 284 CompileUnit &comp_unit) { 285 if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId())) 286 return result.get(); 287 288 auto file_vm_addr = pdb_func.getVirtualAddress(); 289 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 290 return nullptr; 291 292 auto func_length = pdb_func.getLength(); 293 AddressRange func_range = 294 AddressRange(file_vm_addr, func_length, 295 GetObjectFile()->GetModule()->GetSectionList()); 296 if (!func_range.GetBaseAddress().IsValid()) 297 return nullptr; 298 299 lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId()); 300 if (!func_type) 301 return nullptr; 302 303 user_id_t func_type_uid = pdb_func.getSignatureId(); 304 305 Mangled mangled = GetMangledForPDBFunc(pdb_func); 306 307 FunctionSP func_sp = 308 std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(), 309 func_type_uid, mangled, func_type, func_range); 310 311 comp_unit.AddFunction(func_sp); 312 313 LanguageType lang = ParseLanguage(comp_unit); 314 auto type_system_or_err = GetTypeSystemForLanguage(lang); 315 if (auto err = type_system_or_err.takeError()) { 316 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 317 "Unable to parse PDBFunc"); 318 return nullptr; 319 } 320 321 TypeSystemClang *clang_type_system = 322 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 323 if (!clang_type_system) 324 return nullptr; 325 clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func); 326 327 return func_sp.get(); 328 } 329 330 size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) { 331 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 332 size_t func_added = 0; 333 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); 334 if (!compiland_up) 335 return 0; 336 auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>(); 337 if (!results_up) 338 return 0; 339 while (auto pdb_func_up = results_up->getNext()) { 340 auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId()); 341 if (!func_sp) { 342 if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit)) 343 ++func_added; 344 } 345 } 346 return func_added; 347 } 348 349 bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) { 350 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 351 if (comp_unit.GetLineTable()) 352 return true; 353 return ParseCompileUnitLineTable(comp_unit, 0); 354 } 355 356 bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) { 357 // PDB doesn't contain information about macros 358 return false; 359 } 360 361 bool SymbolFilePDB::ParseSupportFiles( 362 CompileUnit &comp_unit, lldb_private::FileSpecList &support_files) { 363 364 // In theory this is unnecessary work for us, because all of this information 365 // is easily (and quickly) accessible from DebugInfoPDB, so caching it a 366 // second time seems like a waste. Unfortunately, there's no good way around 367 // this short of a moderate refactor since SymbolVendor depends on being able 368 // to cache this list. 369 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 370 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); 371 if (!compiland_up) 372 return false; 373 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up); 374 if (!files || files->getChildCount() == 0) 375 return false; 376 377 while (auto file = files->getNext()) { 378 FileSpec spec(file->getFileName(), FileSpec::Style::windows); 379 support_files.AppendIfUnique(spec); 380 } 381 382 return true; 383 } 384 385 bool SymbolFilePDB::ParseImportedModules( 386 const lldb_private::SymbolContext &sc, 387 std::vector<SourceModule> &imported_modules) { 388 // PDB does not yet support module debug info 389 return false; 390 } 391 392 static size_t ParseFunctionBlocksForPDBSymbol( 393 uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol, 394 lldb_private::Block *parent_block, bool is_top_parent) { 395 assert(pdb_symbol && parent_block); 396 397 size_t num_added = 0; 398 switch (pdb_symbol->getSymTag()) { 399 case PDB_SymType::Block: 400 case PDB_SymType::Function: { 401 Block *block = nullptr; 402 auto &raw_sym = pdb_symbol->getRawSymbol(); 403 if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) { 404 if (pdb_func->hasNoInlineAttribute()) 405 break; 406 if (is_top_parent) 407 block = parent_block; 408 else 409 break; 410 } else if (llvm::isa<PDBSymbolBlock>(pdb_symbol)) { 411 auto uid = pdb_symbol->getSymIndexId(); 412 if (parent_block->FindBlockByID(uid)) 413 break; 414 if (raw_sym.getVirtualAddress() < func_file_vm_addr) 415 break; 416 417 auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId()); 418 parent_block->AddChild(block_sp); 419 block = block_sp.get(); 420 } else 421 llvm_unreachable("Unexpected PDB symbol!"); 422 423 block->AddRange(Block::Range( 424 raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength())); 425 block->FinalizeRanges(); 426 ++num_added; 427 428 auto results_up = pdb_symbol->findAllChildren(); 429 if (!results_up) 430 break; 431 while (auto symbol_up = results_up->getNext()) { 432 num_added += ParseFunctionBlocksForPDBSymbol( 433 func_file_vm_addr, symbol_up.get(), block, false); 434 } 435 } break; 436 default: 437 break; 438 } 439 return num_added; 440 } 441 442 size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) { 443 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 444 size_t num_added = 0; 445 auto uid = func.GetID(); 446 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid); 447 if (!pdb_func_up) 448 return 0; 449 Block &parent_block = func.GetBlock(false); 450 num_added = ParseFunctionBlocksForPDBSymbol( 451 pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true); 452 return num_added; 453 } 454 455 size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) { 456 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 457 458 size_t num_added = 0; 459 auto compiland = GetPDBCompilandByUID(comp_unit.GetID()); 460 if (!compiland) 461 return 0; 462 463 auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) { 464 std::unique_ptr<IPDBEnumSymbols> results; 465 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef, 466 PDB_SymType::UDT}; 467 for (auto tag : tags_to_search) { 468 results = raw_sym.findAllChildren(tag); 469 if (!results || results->getChildCount() == 0) 470 continue; 471 while (auto symbol = results->getNext()) { 472 switch (symbol->getSymTag()) { 473 case PDB_SymType::Enum: 474 case PDB_SymType::UDT: 475 case PDB_SymType::Typedef: 476 break; 477 default: 478 continue; 479 } 480 481 // This should cause the type to get cached and stored in the `m_types` 482 // lookup. 483 if (auto type = ResolveTypeUID(symbol->getSymIndexId())) { 484 // Resolve the type completely to avoid a completion 485 // (and so a list change, which causes an iterators invalidation) 486 // during a TypeList dumping 487 type->GetFullCompilerType(); 488 ++num_added; 489 } 490 } 491 } 492 }; 493 494 ParseTypesByTagFn(*compiland); 495 496 // Also parse global types particularly coming from this compiland. 497 // Unfortunately, PDB has no compiland information for each global type. We 498 // have to parse them all. But ensure we only do this once. 499 static bool parse_all_global_types = false; 500 if (!parse_all_global_types) { 501 ParseTypesByTagFn(*m_global_scope_up); 502 parse_all_global_types = true; 503 } 504 return num_added; 505 } 506 507 size_t 508 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) { 509 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 510 if (!sc.comp_unit) 511 return 0; 512 513 size_t num_added = 0; 514 if (sc.function) { 515 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>( 516 sc.function->GetID()); 517 if (!pdb_func) 518 return 0; 519 520 num_added += ParseVariables(sc, *pdb_func); 521 sc.function->GetBlock(false).SetDidParseVariables(true, true); 522 } else if (sc.comp_unit) { 523 auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID()); 524 if (!compiland) 525 return 0; 526 527 if (sc.comp_unit->GetVariableList(false)) 528 return 0; 529 530 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); 531 if (results && results->getChildCount()) { 532 while (auto result = results->getNext()) { 533 auto cu_id = GetCompilandId(*result); 534 // FIXME: We are not able to determine variable's compile unit. 535 if (cu_id == 0) 536 continue; 537 538 if (cu_id == sc.comp_unit->GetID()) 539 num_added += ParseVariables(sc, *result); 540 } 541 } 542 543 // FIXME: A `file static` or `global constant` variable appears both in 544 // compiland's children and global scope's children with unexpectedly 545 // different symbol's Id making it ambiguous. 546 547 // FIXME: 'local constant', for example, const char var[] = "abc", declared 548 // in a function scope, can't be found in PDB. 549 550 // Parse variables in this compiland. 551 num_added += ParseVariables(sc, *compiland); 552 } 553 554 return num_added; 555 } 556 557 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 558 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 559 auto find_result = m_types.find(type_uid); 560 if (find_result != m_types.end()) 561 return find_result->second.get(); 562 563 auto type_system_or_err = 564 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 565 if (auto err = type_system_or_err.takeError()) { 566 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 567 "Unable to ResolveTypeUID"); 568 return nullptr; 569 } 570 571 TypeSystemClang *clang_type_system = 572 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 573 if (!clang_type_system) 574 return nullptr; 575 PDBASTParser *pdb = clang_type_system->GetPDBParser(); 576 if (!pdb) 577 return nullptr; 578 579 auto pdb_type = m_session_up->getSymbolById(type_uid); 580 if (pdb_type == nullptr) 581 return nullptr; 582 583 lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type); 584 if (result) { 585 m_types.insert(std::make_pair(type_uid, result)); 586 GetTypeList().Insert(result); 587 } 588 return result.get(); 589 } 590 591 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID( 592 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 593 return llvm::None; 594 } 595 596 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) { 597 std::lock_guard<std::recursive_mutex> guard( 598 GetObjectFile()->GetModule()->GetMutex()); 599 600 auto type_system_or_err = 601 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 602 if (auto err = type_system_or_err.takeError()) { 603 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 604 "Unable to get dynamic array info for UID"); 605 return false; 606 } 607 608 TypeSystemClang *clang_ast_ctx = 609 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 610 611 if (!clang_ast_ctx) 612 return false; 613 614 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); 615 if (!pdb) 616 return false; 617 618 return pdb->CompleteTypeFromPDB(compiler_type); 619 } 620 621 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) { 622 auto type_system_or_err = 623 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 624 if (auto err = type_system_or_err.takeError()) { 625 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 626 "Unable to get decl for UID"); 627 return CompilerDecl(); 628 } 629 630 TypeSystemClang *clang_ast_ctx = 631 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 632 if (!clang_ast_ctx) 633 return CompilerDecl(); 634 635 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); 636 if (!pdb) 637 return CompilerDecl(); 638 639 auto symbol = m_session_up->getSymbolById(uid); 640 if (!symbol) 641 return CompilerDecl(); 642 643 auto decl = pdb->GetDeclForSymbol(*symbol); 644 if (!decl) 645 return CompilerDecl(); 646 647 return clang_ast_ctx->GetCompilerDecl(decl); 648 } 649 650 lldb_private::CompilerDeclContext 651 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) { 652 auto type_system_or_err = 653 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 654 if (auto err = type_system_or_err.takeError()) { 655 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 656 "Unable to get DeclContext for UID"); 657 return CompilerDeclContext(); 658 } 659 660 TypeSystemClang *clang_ast_ctx = 661 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 662 if (!clang_ast_ctx) 663 return CompilerDeclContext(); 664 665 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); 666 if (!pdb) 667 return CompilerDeclContext(); 668 669 auto symbol = m_session_up->getSymbolById(uid); 670 if (!symbol) 671 return CompilerDeclContext(); 672 673 auto decl_context = pdb->GetDeclContextForSymbol(*symbol); 674 if (!decl_context) 675 return GetDeclContextContainingUID(uid); 676 677 return clang_ast_ctx->CreateDeclContext(decl_context); 678 } 679 680 lldb_private::CompilerDeclContext 681 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) { 682 auto type_system_or_err = 683 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 684 if (auto err = type_system_or_err.takeError()) { 685 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 686 "Unable to get DeclContext containing UID"); 687 return CompilerDeclContext(); 688 } 689 690 TypeSystemClang *clang_ast_ctx = 691 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 692 if (!clang_ast_ctx) 693 return CompilerDeclContext(); 694 695 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); 696 if (!pdb) 697 return CompilerDeclContext(); 698 699 auto symbol = m_session_up->getSymbolById(uid); 700 if (!symbol) 701 return CompilerDeclContext(); 702 703 auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol); 704 assert(decl_context); 705 706 return clang_ast_ctx->CreateDeclContext(decl_context); 707 } 708 709 void SymbolFilePDB::ParseDeclsForContext( 710 lldb_private::CompilerDeclContext decl_ctx) { 711 auto type_system_or_err = 712 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 713 if (auto err = type_system_or_err.takeError()) { 714 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 715 "Unable to parse decls for context"); 716 return; 717 } 718 719 TypeSystemClang *clang_ast_ctx = 720 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 721 if (!clang_ast_ctx) 722 return; 723 724 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser(); 725 if (!pdb) 726 return; 727 728 pdb->ParseDeclsForDeclContext( 729 static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext())); 730 } 731 732 uint32_t 733 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr, 734 SymbolContextItem resolve_scope, 735 lldb_private::SymbolContext &sc) { 736 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 737 uint32_t resolved_flags = 0; 738 if (resolve_scope & eSymbolContextCompUnit || 739 resolve_scope & eSymbolContextVariable || 740 resolve_scope & eSymbolContextFunction || 741 resolve_scope & eSymbolContextBlock || 742 resolve_scope & eSymbolContextLineEntry) { 743 auto cu_sp = GetCompileUnitContainsAddress(so_addr); 744 if (!cu_sp) { 745 if (resolved_flags & eSymbolContextVariable) { 746 // TODO: Resolve variables 747 } 748 return 0; 749 } 750 sc.comp_unit = cu_sp.get(); 751 resolved_flags |= eSymbolContextCompUnit; 752 lldbassert(sc.module_sp == cu_sp->GetModule()); 753 } 754 755 if (resolve_scope & eSymbolContextFunction || 756 resolve_scope & eSymbolContextBlock) { 757 addr_t file_vm_addr = so_addr.GetFileAddress(); 758 auto symbol_up = 759 m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function); 760 if (symbol_up) { 761 auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); 762 assert(pdb_func); 763 auto func_uid = pdb_func->getSymIndexId(); 764 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); 765 if (sc.function == nullptr) 766 sc.function = 767 ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit); 768 if (sc.function) { 769 resolved_flags |= eSymbolContextFunction; 770 if (resolve_scope & eSymbolContextBlock) { 771 auto block_symbol = m_session_up->findSymbolByAddress( 772 file_vm_addr, PDB_SymType::Block); 773 auto block_id = block_symbol ? block_symbol->getSymIndexId() 774 : sc.function->GetID(); 775 sc.block = sc.function->GetBlock(true).FindBlockByID(block_id); 776 if (sc.block) 777 resolved_flags |= eSymbolContextBlock; 778 } 779 } 780 } 781 } 782 783 if (resolve_scope & eSymbolContextLineEntry) { 784 if (auto *line_table = sc.comp_unit->GetLineTable()) { 785 Address addr(so_addr); 786 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 787 resolved_flags |= eSymbolContextLineEntry; 788 } 789 } 790 791 return resolved_flags; 792 } 793 794 uint32_t SymbolFilePDB::ResolveSymbolContext( 795 const lldb_private::SourceLocationSpec &src_location_spec, 796 SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) { 797 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 798 const size_t old_size = sc_list.GetSize(); 799 const FileSpec &file_spec = src_location_spec.GetFileSpec(); 800 const uint32_t line = src_location_spec.GetLine().getValueOr(0); 801 if (resolve_scope & lldb::eSymbolContextCompUnit) { 802 // Locate all compilation units with line numbers referencing the specified 803 // file. For example, if `file_spec` is <vector>, then this should return 804 // all source files and header files that reference <vector>, either 805 // directly or indirectly. 806 auto compilands = m_session_up->findCompilandsForSourceFile( 807 file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive); 808 809 if (!compilands) 810 return 0; 811 812 // For each one, either find its previously parsed data or parse it afresh 813 // and add it to the symbol context list. 814 while (auto compiland = compilands->getNext()) { 815 // If we're not checking inlines, then don't add line information for 816 // this file unless the FileSpec matches. For inline functions, we don't 817 // have to match the FileSpec since they could be defined in headers 818 // other than file specified in FileSpec. 819 if (!src_location_spec.GetCheckInlines()) { 820 std::string source_file = compiland->getSourceFileFullPath(); 821 if (source_file.empty()) 822 continue; 823 FileSpec this_spec(source_file, FileSpec::Style::windows); 824 bool need_full_match = !file_spec.GetDirectory().IsEmpty(); 825 if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0) 826 continue; 827 } 828 829 SymbolContext sc; 830 auto cu = ParseCompileUnitForUID(compiland->getSymIndexId()); 831 if (!cu) 832 continue; 833 sc.comp_unit = cu.get(); 834 sc.module_sp = cu->GetModule(); 835 836 // If we were asked to resolve line entries, add all entries to the line 837 // table that match the requested line (or all lines if `line` == 0). 838 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock | 839 eSymbolContextLineEntry)) { 840 bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line); 841 842 if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) { 843 // The query asks for line entries, but we can't get them for the 844 // compile unit. This is not normal for `line` = 0. So just assert 845 // it. 846 assert(line && "Couldn't get all line entries!\n"); 847 848 // Current compiland does not have the requested line. Search next. 849 continue; 850 } 851 852 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { 853 if (!has_line_table) 854 continue; 855 856 auto *line_table = sc.comp_unit->GetLineTable(); 857 lldbassert(line_table); 858 859 uint32_t num_line_entries = line_table->GetSize(); 860 // Skip the terminal line entry. 861 --num_line_entries; 862 863 // If `line `!= 0, see if we can resolve function for each line entry 864 // in the line table. 865 for (uint32_t line_idx = 0; line && line_idx < num_line_entries; 866 ++line_idx) { 867 if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry)) 868 continue; 869 870 auto file_vm_addr = 871 sc.line_entry.range.GetBaseAddress().GetFileAddress(); 872 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 873 continue; 874 875 auto symbol_up = m_session_up->findSymbolByAddress( 876 file_vm_addr, PDB_SymType::Function); 877 if (symbol_up) { 878 auto func_uid = symbol_up->getSymIndexId(); 879 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); 880 if (sc.function == nullptr) { 881 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); 882 assert(pdb_func); 883 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, 884 *sc.comp_unit); 885 } 886 if (sc.function && (resolve_scope & eSymbolContextBlock)) { 887 Block &block = sc.function->GetBlock(true); 888 sc.block = block.FindBlockByID(sc.function->GetID()); 889 } 890 } 891 sc_list.Append(sc); 892 } 893 } else if (has_line_table) { 894 // We can parse line table for the compile unit. But no query to 895 // resolve function or block. We append `sc` to the list anyway. 896 sc_list.Append(sc); 897 } 898 } else { 899 // No query for line entry, function or block. But we have a valid 900 // compile unit, append `sc` to the list. 901 sc_list.Append(sc); 902 } 903 } 904 } 905 return sc_list.GetSize() - old_size; 906 } 907 908 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) { 909 // Cache public names at first 910 if (m_public_names.empty()) 911 if (auto result_up = 912 m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol)) 913 while (auto symbol_up = result_up->getNext()) 914 if (auto addr = symbol_up->getRawSymbol().getVirtualAddress()) 915 m_public_names[addr] = symbol_up->getRawSymbol().getName(); 916 917 // Look up the name in the cache 918 return m_public_names.lookup(pdb_data.getVirtualAddress()); 919 } 920 921 VariableSP SymbolFilePDB::ParseVariableForPDBData( 922 const lldb_private::SymbolContext &sc, 923 const llvm::pdb::PDBSymbolData &pdb_data) { 924 VariableSP var_sp; 925 uint32_t var_uid = pdb_data.getSymIndexId(); 926 auto result = m_variables.find(var_uid); 927 if (result != m_variables.end()) 928 return result->second; 929 930 ValueType scope = eValueTypeInvalid; 931 bool is_static_member = false; 932 bool is_external = false; 933 bool is_artificial = false; 934 935 switch (pdb_data.getDataKind()) { 936 case PDB_DataKind::Global: 937 scope = eValueTypeVariableGlobal; 938 is_external = true; 939 break; 940 case PDB_DataKind::Local: 941 scope = eValueTypeVariableLocal; 942 break; 943 case PDB_DataKind::FileStatic: 944 scope = eValueTypeVariableStatic; 945 break; 946 case PDB_DataKind::StaticMember: 947 is_static_member = true; 948 scope = eValueTypeVariableStatic; 949 break; 950 case PDB_DataKind::Member: 951 scope = eValueTypeVariableStatic; 952 break; 953 case PDB_DataKind::Param: 954 scope = eValueTypeVariableArgument; 955 break; 956 case PDB_DataKind::Constant: 957 scope = eValueTypeConstResult; 958 break; 959 default: 960 break; 961 } 962 963 switch (pdb_data.getLocationType()) { 964 case PDB_LocType::TLS: 965 scope = eValueTypeVariableThreadLocal; 966 break; 967 case PDB_LocType::RegRel: { 968 // It is a `this` pointer. 969 if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) { 970 scope = eValueTypeVariableArgument; 971 is_artificial = true; 972 } 973 } break; 974 default: 975 break; 976 } 977 978 Declaration decl; 979 if (!is_artificial && !pdb_data.isCompilerGenerated()) { 980 if (auto lines = pdb_data.getLineNumbers()) { 981 if (auto first_line = lines->getNext()) { 982 uint32_t src_file_id = first_line->getSourceFileId(); 983 auto src_file = m_session_up->getSourceFileById(src_file_id); 984 if (src_file) { 985 FileSpec spec(src_file->getFileName()); 986 decl.SetFile(spec); 987 decl.SetColumn(first_line->getColumnNumber()); 988 decl.SetLine(first_line->getLineNumber()); 989 } 990 } 991 } 992 } 993 994 Variable::RangeList ranges; 995 SymbolContextScope *context_scope = sc.comp_unit; 996 if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) { 997 if (sc.function) { 998 Block &function_block = sc.function->GetBlock(true); 999 Block *block = 1000 function_block.FindBlockByID(pdb_data.getLexicalParentId()); 1001 if (!block) 1002 block = &function_block; 1003 1004 context_scope = block; 1005 1006 for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges; 1007 ++i) { 1008 AddressRange range; 1009 if (!block->GetRangeAtIndex(i, range)) 1010 continue; 1011 1012 ranges.Append(range.GetBaseAddress().GetFileAddress(), 1013 range.GetByteSize()); 1014 } 1015 } 1016 } 1017 1018 SymbolFileTypeSP type_sp = 1019 std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId()); 1020 1021 auto var_name = pdb_data.getName(); 1022 auto mangled = GetMangledForPDBData(pdb_data); 1023 auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str(); 1024 1025 bool is_constant; 1026 DWARFExpression location = ConvertPDBLocationToDWARFExpression( 1027 GetObjectFile()->GetModule(), pdb_data, ranges, is_constant); 1028 1029 var_sp = std::make_shared<Variable>( 1030 var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope, 1031 ranges, &decl, location, is_external, is_artificial, is_constant, 1032 is_static_member); 1033 1034 m_variables.insert(std::make_pair(var_uid, var_sp)); 1035 return var_sp; 1036 } 1037 1038 size_t 1039 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc, 1040 const llvm::pdb::PDBSymbol &pdb_symbol, 1041 lldb_private::VariableList *variable_list) { 1042 size_t num_added = 0; 1043 1044 if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) { 1045 VariableListSP local_variable_list_sp; 1046 1047 auto result = m_variables.find(pdb_data->getSymIndexId()); 1048 if (result != m_variables.end()) { 1049 if (variable_list) 1050 variable_list->AddVariableIfUnique(result->second); 1051 } else { 1052 // Prepare right VariableList for this variable. 1053 if (auto lexical_parent = pdb_data->getLexicalParent()) { 1054 switch (lexical_parent->getSymTag()) { 1055 case PDB_SymType::Exe: 1056 assert(sc.comp_unit); 1057 LLVM_FALLTHROUGH; 1058 case PDB_SymType::Compiland: { 1059 if (sc.comp_unit) { 1060 local_variable_list_sp = sc.comp_unit->GetVariableList(false); 1061 if (!local_variable_list_sp) { 1062 local_variable_list_sp = std::make_shared<VariableList>(); 1063 sc.comp_unit->SetVariableList(local_variable_list_sp); 1064 } 1065 } 1066 } break; 1067 case PDB_SymType::Block: 1068 case PDB_SymType::Function: { 1069 if (sc.function) { 1070 Block *block = sc.function->GetBlock(true).FindBlockByID( 1071 lexical_parent->getSymIndexId()); 1072 if (block) { 1073 local_variable_list_sp = block->GetBlockVariableList(false); 1074 if (!local_variable_list_sp) { 1075 local_variable_list_sp = std::make_shared<VariableList>(); 1076 block->SetVariableList(local_variable_list_sp); 1077 } 1078 } 1079 } 1080 } break; 1081 default: 1082 break; 1083 } 1084 } 1085 1086 if (local_variable_list_sp) { 1087 if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) { 1088 local_variable_list_sp->AddVariableIfUnique(var_sp); 1089 if (variable_list) 1090 variable_list->AddVariableIfUnique(var_sp); 1091 ++num_added; 1092 PDBASTParser *ast = GetPDBAstParser(); 1093 if (ast) 1094 ast->GetDeclForSymbol(*pdb_data); 1095 } 1096 } 1097 } 1098 } 1099 1100 if (auto results = pdb_symbol.findAllChildren()) { 1101 while (auto result = results->getNext()) 1102 num_added += ParseVariables(sc, *result, variable_list); 1103 } 1104 1105 return num_added; 1106 } 1107 1108 void SymbolFilePDB::FindGlobalVariables( 1109 lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx, 1110 uint32_t max_matches, lldb_private::VariableList &variables) { 1111 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1112 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 1113 return; 1114 if (name.IsEmpty()) 1115 return; 1116 1117 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); 1118 if (!results) 1119 return; 1120 1121 uint32_t matches = 0; 1122 size_t old_size = variables.GetSize(); 1123 while (auto result = results->getNext()) { 1124 auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get()); 1125 if (max_matches > 0 && matches >= max_matches) 1126 break; 1127 1128 SymbolContext sc; 1129 sc.module_sp = m_objfile_sp->GetModule(); 1130 lldbassert(sc.module_sp.get()); 1131 1132 if (!name.GetStringRef().equals( 1133 MSVCUndecoratedNameParser::DropScope(pdb_data->getName()))) 1134 continue; 1135 1136 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get(); 1137 // FIXME: We are not able to determine the compile unit. 1138 if (sc.comp_unit == nullptr) 1139 continue; 1140 1141 if (parent_decl_ctx.IsValid() && 1142 GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx) 1143 continue; 1144 1145 ParseVariables(sc, *pdb_data, &variables); 1146 matches = variables.GetSize() - old_size; 1147 } 1148 } 1149 1150 void SymbolFilePDB::FindGlobalVariables( 1151 const lldb_private::RegularExpression ®ex, uint32_t max_matches, 1152 lldb_private::VariableList &variables) { 1153 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1154 if (!regex.IsValid()) 1155 return; 1156 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); 1157 if (!results) 1158 return; 1159 1160 uint32_t matches = 0; 1161 size_t old_size = variables.GetSize(); 1162 while (auto pdb_data = results->getNext()) { 1163 if (max_matches > 0 && matches >= max_matches) 1164 break; 1165 1166 auto var_name = pdb_data->getName(); 1167 if (var_name.empty()) 1168 continue; 1169 if (!regex.Execute(var_name)) 1170 continue; 1171 SymbolContext sc; 1172 sc.module_sp = m_objfile_sp->GetModule(); 1173 lldbassert(sc.module_sp.get()); 1174 1175 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get(); 1176 // FIXME: We are not able to determine the compile unit. 1177 if (sc.comp_unit == nullptr) 1178 continue; 1179 1180 ParseVariables(sc, *pdb_data, &variables); 1181 matches = variables.GetSize() - old_size; 1182 } 1183 } 1184 1185 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func, 1186 bool include_inlines, 1187 lldb_private::SymbolContextList &sc_list) { 1188 lldb_private::SymbolContext sc; 1189 sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get(); 1190 if (!sc.comp_unit) 1191 return false; 1192 sc.module_sp = sc.comp_unit->GetModule(); 1193 sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit); 1194 if (!sc.function) 1195 return false; 1196 1197 sc_list.Append(sc); 1198 return true; 1199 } 1200 1201 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines, 1202 lldb_private::SymbolContextList &sc_list) { 1203 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid); 1204 if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute())) 1205 return false; 1206 return ResolveFunction(*pdb_func_up, include_inlines, sc_list); 1207 } 1208 1209 void SymbolFilePDB::CacheFunctionNames() { 1210 if (!m_func_full_names.IsEmpty()) 1211 return; 1212 1213 std::map<uint64_t, uint32_t> addr_ids; 1214 1215 if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) { 1216 while (auto pdb_func_up = results_up->getNext()) { 1217 if (pdb_func_up->isCompilerGenerated()) 1218 continue; 1219 1220 auto name = pdb_func_up->getName(); 1221 auto demangled_name = pdb_func_up->getUndecoratedName(); 1222 if (name.empty() && demangled_name.empty()) 1223 continue; 1224 1225 auto uid = pdb_func_up->getSymIndexId(); 1226 if (!demangled_name.empty() && pdb_func_up->getVirtualAddress()) 1227 addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid)); 1228 1229 if (auto parent = pdb_func_up->getClassParent()) { 1230 1231 // PDB have symbols for class/struct methods or static methods in Enum 1232 // Class. We won't bother to check if the parent is UDT or Enum here. 1233 m_func_method_names.Append(ConstString(name), uid); 1234 1235 // To search a method name, like NS::Class:MemberFunc, LLDB searches 1236 // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does 1237 // not have information of this, we extract base names and cache them 1238 // by our own effort. 1239 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name); 1240 if (!basename.empty()) 1241 m_func_base_names.Append(ConstString(basename), uid); 1242 else { 1243 m_func_base_names.Append(ConstString(name), uid); 1244 } 1245 1246 if (!demangled_name.empty()) 1247 m_func_full_names.Append(ConstString(demangled_name), uid); 1248 1249 } else { 1250 // Handle not-method symbols. 1251 1252 // The function name might contain namespace, or its lexical scope. 1253 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name); 1254 if (!basename.empty()) 1255 m_func_base_names.Append(ConstString(basename), uid); 1256 else 1257 m_func_base_names.Append(ConstString(name), uid); 1258 1259 if (name == "main") { 1260 m_func_full_names.Append(ConstString(name), uid); 1261 1262 if (!demangled_name.empty() && name != demangled_name) { 1263 m_func_full_names.Append(ConstString(demangled_name), uid); 1264 m_func_base_names.Append(ConstString(demangled_name), uid); 1265 } 1266 } else if (!demangled_name.empty()) { 1267 m_func_full_names.Append(ConstString(demangled_name), uid); 1268 } else { 1269 m_func_full_names.Append(ConstString(name), uid); 1270 } 1271 } 1272 } 1273 } 1274 1275 if (auto results_up = 1276 m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) { 1277 while (auto pub_sym_up = results_up->getNext()) { 1278 if (!pub_sym_up->isFunction()) 1279 continue; 1280 auto name = pub_sym_up->getName(); 1281 if (name.empty()) 1282 continue; 1283 1284 if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) { 1285 auto vm_addr = pub_sym_up->getVirtualAddress(); 1286 1287 // PDB public symbol has mangled name for its associated function. 1288 if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) { 1289 // Cache mangled name. 1290 m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]); 1291 } 1292 } 1293 } 1294 } 1295 // Sort them before value searching is working properly 1296 m_func_full_names.Sort(); 1297 m_func_full_names.SizeToFit(); 1298 m_func_method_names.Sort(); 1299 m_func_method_names.SizeToFit(); 1300 m_func_base_names.Sort(); 1301 m_func_base_names.SizeToFit(); 1302 } 1303 1304 void SymbolFilePDB::FindFunctions( 1305 lldb_private::ConstString name, 1306 const lldb_private::CompilerDeclContext &parent_decl_ctx, 1307 FunctionNameType name_type_mask, bool include_inlines, 1308 lldb_private::SymbolContextList &sc_list) { 1309 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1310 lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0); 1311 1312 if (name_type_mask == eFunctionNameTypeNone) 1313 return; 1314 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 1315 return; 1316 if (name.IsEmpty()) 1317 return; 1318 1319 if (name_type_mask & eFunctionNameTypeFull || 1320 name_type_mask & eFunctionNameTypeBase || 1321 name_type_mask & eFunctionNameTypeMethod) { 1322 CacheFunctionNames(); 1323 1324 std::set<uint32_t> resolved_ids; 1325 auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list, 1326 &resolved_ids](UniqueCStringMap<uint32_t> &Names) { 1327 std::vector<uint32_t> ids; 1328 if (!Names.GetValues(name, ids)) 1329 return; 1330 1331 for (uint32_t id : ids) { 1332 if (resolved_ids.find(id) != resolved_ids.end()) 1333 continue; 1334 1335 if (parent_decl_ctx.IsValid() && 1336 GetDeclContextContainingUID(id) != parent_decl_ctx) 1337 continue; 1338 1339 if (ResolveFunction(id, include_inlines, sc_list)) 1340 resolved_ids.insert(id); 1341 } 1342 }; 1343 if (name_type_mask & eFunctionNameTypeFull) { 1344 ResolveFn(m_func_full_names); 1345 ResolveFn(m_func_base_names); 1346 ResolveFn(m_func_method_names); 1347 } 1348 if (name_type_mask & eFunctionNameTypeBase) 1349 ResolveFn(m_func_base_names); 1350 if (name_type_mask & eFunctionNameTypeMethod) 1351 ResolveFn(m_func_method_names); 1352 } 1353 } 1354 1355 void SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex, 1356 bool include_inlines, 1357 lldb_private::SymbolContextList &sc_list) { 1358 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1359 if (!regex.IsValid()) 1360 return; 1361 1362 CacheFunctionNames(); 1363 1364 std::set<uint32_t> resolved_ids; 1365 auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids, 1366 this](UniqueCStringMap<uint32_t> &Names) { 1367 std::vector<uint32_t> ids; 1368 if (Names.GetValues(regex, ids)) { 1369 for (auto id : ids) { 1370 if (resolved_ids.find(id) == resolved_ids.end()) 1371 if (ResolveFunction(id, include_inlines, sc_list)) 1372 resolved_ids.insert(id); 1373 } 1374 } 1375 }; 1376 ResolveFn(m_func_full_names); 1377 ResolveFn(m_func_base_names); 1378 } 1379 1380 void SymbolFilePDB::GetMangledNamesForFunction( 1381 const std::string &scope_qualified_name, 1382 std::vector<lldb_private::ConstString> &mangled_names) {} 1383 1384 void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) { 1385 std::set<lldb::addr_t> sym_addresses; 1386 for (size_t i = 0; i < symtab.GetNumSymbols(); i++) 1387 sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress()); 1388 1389 auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>(); 1390 if (!results) 1391 return; 1392 1393 auto section_list = m_objfile_sp->GetSectionList(); 1394 if (!section_list) 1395 return; 1396 1397 while (auto pub_symbol = results->getNext()) { 1398 auto section_id = pub_symbol->getAddressSection(); 1399 1400 auto section = section_list->FindSectionByID(section_id); 1401 if (!section) 1402 continue; 1403 1404 auto offset = pub_symbol->getAddressOffset(); 1405 1406 auto file_addr = section->GetFileAddress() + offset; 1407 if (sym_addresses.find(file_addr) != sym_addresses.end()) 1408 continue; 1409 sym_addresses.insert(file_addr); 1410 1411 auto size = pub_symbol->getLength(); 1412 symtab.AddSymbol( 1413 Symbol(pub_symbol->getSymIndexId(), // symID 1414 pub_symbol->getName().c_str(), // name 1415 pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type 1416 true, // external 1417 false, // is_debug 1418 false, // is_trampoline 1419 false, // is_artificial 1420 section, // section_sp 1421 offset, // value 1422 size, // size 1423 size != 0, // size_is_valid 1424 false, // contains_linker_annotations 1425 0 // flags 1426 )); 1427 } 1428 1429 symtab.Finalize(); 1430 } 1431 1432 void SymbolFilePDB::FindTypes( 1433 lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx, 1434 uint32_t max_matches, 1435 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 1436 lldb_private::TypeMap &types) { 1437 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1438 if (!name) 1439 return; 1440 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 1441 return; 1442 1443 searched_symbol_files.clear(); 1444 searched_symbol_files.insert(this); 1445 1446 // There is an assumption 'name' is not a regex 1447 FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types); 1448 } 1449 1450 void SymbolFilePDB::DumpClangAST(Stream &s) { 1451 auto type_system_or_err = 1452 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 1453 if (auto err = type_system_or_err.takeError()) { 1454 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 1455 "Unable to dump ClangAST"); 1456 return; 1457 } 1458 1459 auto *clang_type_system = 1460 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 1461 if (!clang_type_system) 1462 return; 1463 clang_type_system->Dump(s.AsRawOstream()); 1464 } 1465 1466 void SymbolFilePDB::FindTypesByRegex( 1467 const lldb_private::RegularExpression ®ex, uint32_t max_matches, 1468 lldb_private::TypeMap &types) { 1469 // When searching by regex, we need to go out of our way to limit the search 1470 // space as much as possible since this searches EVERYTHING in the PDB, 1471 // manually doing regex comparisons. PDB library isn't optimized for regex 1472 // searches or searches across multiple symbol types at the same time, so the 1473 // best we can do is to search enums, then typedefs, then classes one by one, 1474 // and do a regex comparison against each of them. 1475 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef, 1476 PDB_SymType::UDT}; 1477 std::unique_ptr<IPDBEnumSymbols> results; 1478 1479 uint32_t matches = 0; 1480 1481 for (auto tag : tags_to_search) { 1482 results = m_global_scope_up->findAllChildren(tag); 1483 if (!results) 1484 continue; 1485 1486 while (auto result = results->getNext()) { 1487 if (max_matches > 0 && matches >= max_matches) 1488 break; 1489 1490 std::string type_name; 1491 if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get())) 1492 type_name = enum_type->getName(); 1493 else if (auto typedef_type = 1494 llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get())) 1495 type_name = typedef_type->getName(); 1496 else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get())) 1497 type_name = class_type->getName(); 1498 else { 1499 // We're looking only for types that have names. Skip symbols, as well 1500 // as unnamed types such as arrays, pointers, etc. 1501 continue; 1502 } 1503 1504 if (!regex.Execute(type_name)) 1505 continue; 1506 1507 // This should cause the type to get cached and stored in the `m_types` 1508 // lookup. 1509 if (!ResolveTypeUID(result->getSymIndexId())) 1510 continue; 1511 1512 auto iter = m_types.find(result->getSymIndexId()); 1513 if (iter == m_types.end()) 1514 continue; 1515 types.Insert(iter->second); 1516 ++matches; 1517 } 1518 } 1519 } 1520 1521 void SymbolFilePDB::FindTypesByName( 1522 llvm::StringRef name, 1523 const lldb_private::CompilerDeclContext &parent_decl_ctx, 1524 uint32_t max_matches, lldb_private::TypeMap &types) { 1525 std::unique_ptr<IPDBEnumSymbols> results; 1526 if (name.empty()) 1527 return; 1528 results = m_global_scope_up->findAllChildren(PDB_SymType::None); 1529 if (!results) 1530 return; 1531 1532 uint32_t matches = 0; 1533 1534 while (auto result = results->getNext()) { 1535 if (max_matches > 0 && matches >= max_matches) 1536 break; 1537 1538 if (MSVCUndecoratedNameParser::DropScope( 1539 result->getRawSymbol().getName()) != name) 1540 continue; 1541 1542 switch (result->getSymTag()) { 1543 case PDB_SymType::Enum: 1544 case PDB_SymType::UDT: 1545 case PDB_SymType::Typedef: 1546 break; 1547 default: 1548 // We're looking only for types that have names. Skip symbols, as well 1549 // as unnamed types such as arrays, pointers, etc. 1550 continue; 1551 } 1552 1553 // This should cause the type to get cached and stored in the `m_types` 1554 // lookup. 1555 if (!ResolveTypeUID(result->getSymIndexId())) 1556 continue; 1557 1558 if (parent_decl_ctx.IsValid() && 1559 GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx) 1560 continue; 1561 1562 auto iter = m_types.find(result->getSymIndexId()); 1563 if (iter == m_types.end()) 1564 continue; 1565 types.Insert(iter->second); 1566 ++matches; 1567 } 1568 } 1569 1570 void SymbolFilePDB::FindTypes( 1571 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, 1572 llvm::DenseSet<SymbolFile *> &searched_symbol_files, 1573 lldb_private::TypeMap &types) {} 1574 1575 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol, 1576 uint32_t type_mask, 1577 TypeCollection &type_collection) { 1578 bool can_parse = false; 1579 switch (pdb_symbol.getSymTag()) { 1580 case PDB_SymType::ArrayType: 1581 can_parse = ((type_mask & eTypeClassArray) != 0); 1582 break; 1583 case PDB_SymType::BuiltinType: 1584 can_parse = ((type_mask & eTypeClassBuiltin) != 0); 1585 break; 1586 case PDB_SymType::Enum: 1587 can_parse = ((type_mask & eTypeClassEnumeration) != 0); 1588 break; 1589 case PDB_SymType::Function: 1590 case PDB_SymType::FunctionSig: 1591 can_parse = ((type_mask & eTypeClassFunction) != 0); 1592 break; 1593 case PDB_SymType::PointerType: 1594 can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer | 1595 eTypeClassMemberPointer)) != 0); 1596 break; 1597 case PDB_SymType::Typedef: 1598 can_parse = ((type_mask & eTypeClassTypedef) != 0); 1599 break; 1600 case PDB_SymType::UDT: { 1601 auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol); 1602 assert(udt); 1603 can_parse = (udt->getUdtKind() != PDB_UdtType::Interface && 1604 ((type_mask & (eTypeClassClass | eTypeClassStruct | 1605 eTypeClassUnion)) != 0)); 1606 } break; 1607 default: 1608 break; 1609 } 1610 1611 if (can_parse) { 1612 if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) { 1613 auto result = 1614 std::find(type_collection.begin(), type_collection.end(), type); 1615 if (result == type_collection.end()) 1616 type_collection.push_back(type); 1617 } 1618 } 1619 1620 auto results_up = pdb_symbol.findAllChildren(); 1621 while (auto symbol_up = results_up->getNext()) 1622 GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection); 1623 } 1624 1625 void SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1626 TypeClass type_mask, 1627 lldb_private::TypeList &type_list) { 1628 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1629 TypeCollection type_collection; 1630 CompileUnit *cu = 1631 sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr; 1632 if (cu) { 1633 auto compiland_up = GetPDBCompilandByUID(cu->GetID()); 1634 if (!compiland_up) 1635 return; 1636 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); 1637 } else { 1638 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) { 1639 auto cu_sp = ParseCompileUnitAtIndex(cu_idx); 1640 if (cu_sp) { 1641 if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID())) 1642 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); 1643 } 1644 } 1645 } 1646 1647 for (auto type : type_collection) { 1648 type->GetForwardCompilerType(); 1649 type_list.Insert(type->shared_from_this()); 1650 } 1651 } 1652 1653 llvm::Expected<lldb_private::TypeSystem &> 1654 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1655 auto type_system_or_err = 1656 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); 1657 if (type_system_or_err) { 1658 type_system_or_err->SetSymbolFile(this); 1659 } 1660 return type_system_or_err; 1661 } 1662 1663 PDBASTParser *SymbolFilePDB::GetPDBAstParser() { 1664 auto type_system_or_err = 1665 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 1666 if (auto err = type_system_or_err.takeError()) { 1667 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 1668 "Unable to get PDB AST parser"); 1669 return nullptr; 1670 } 1671 1672 auto *clang_type_system = 1673 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 1674 if (!clang_type_system) 1675 return nullptr; 1676 1677 return clang_type_system->GetPDBParser(); 1678 } 1679 1680 lldb_private::CompilerDeclContext 1681 SymbolFilePDB::FindNamespace(lldb_private::ConstString name, 1682 const CompilerDeclContext &parent_decl_ctx) { 1683 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1684 auto type_system_or_err = 1685 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 1686 if (auto err = type_system_or_err.takeError()) { 1687 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err), 1688 "Unable to find namespace {}", name.AsCString()); 1689 return CompilerDeclContext(); 1690 } 1691 1692 auto *clang_type_system = 1693 llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get()); 1694 if (!clang_type_system) 1695 return CompilerDeclContext(); 1696 1697 PDBASTParser *pdb = clang_type_system->GetPDBParser(); 1698 if (!pdb) 1699 return CompilerDeclContext(); 1700 1701 clang::DeclContext *decl_context = nullptr; 1702 if (parent_decl_ctx) 1703 decl_context = static_cast<clang::DeclContext *>( 1704 parent_decl_ctx.GetOpaqueDeclContext()); 1705 1706 auto namespace_decl = 1707 pdb->FindNamespaceDecl(decl_context, name.GetStringRef()); 1708 if (!namespace_decl) 1709 return CompilerDeclContext(); 1710 1711 return clang_type_system->CreateDeclContext(namespace_decl); 1712 } 1713 1714 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; } 1715 1716 const IPDBSession &SymbolFilePDB::GetPDBSession() const { 1717 return *m_session_up; 1718 } 1719 1720 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id, 1721 uint32_t index) { 1722 auto found_cu = m_comp_units.find(id); 1723 if (found_cu != m_comp_units.end()) 1724 return found_cu->second; 1725 1726 auto compiland_up = GetPDBCompilandByUID(id); 1727 if (!compiland_up) 1728 return CompUnitSP(); 1729 1730 lldb::LanguageType lang; 1731 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>(); 1732 if (!details) 1733 lang = lldb::eLanguageTypeC_plus_plus; 1734 else 1735 lang = TranslateLanguage(details->getLanguage()); 1736 1737 if (lang == lldb::LanguageType::eLanguageTypeUnknown) 1738 return CompUnitSP(); 1739 1740 std::string path = compiland_up->getSourceFileFullPath(); 1741 if (path.empty()) 1742 return CompUnitSP(); 1743 1744 // Don't support optimized code for now, DebugInfoPDB does not return this 1745 // information. 1746 LazyBool optimized = eLazyBoolNo; 1747 auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, 1748 path.c_str(), id, lang, optimized); 1749 1750 if (!cu_sp) 1751 return CompUnitSP(); 1752 1753 m_comp_units.insert(std::make_pair(id, cu_sp)); 1754 if (index == UINT32_MAX) 1755 GetCompileUnitIndex(*compiland_up, index); 1756 lldbassert(index != UINT32_MAX); 1757 SetCompileUnitAtIndex(index, cu_sp); 1758 return cu_sp; 1759 } 1760 1761 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit, 1762 uint32_t match_line) { 1763 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID()); 1764 if (!compiland_up) 1765 return false; 1766 1767 // LineEntry needs the *index* of the file into the list of support files 1768 // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us 1769 // a globally unique idenfitifier in the namespace of the PDB. So, we have 1770 // to do a mapping so that we can hand out indices. 1771 llvm::DenseMap<uint32_t, uint32_t> index_map; 1772 BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map); 1773 auto line_table = std::make_unique<LineTable>(&comp_unit); 1774 1775 // Find contributions to `compiland` from all source and header files. 1776 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up); 1777 if (!files) 1778 return false; 1779 1780 // For each source and header file, create a LineSequence for contributions 1781 // to the compiland from that file, and add the sequence. 1782 while (auto file = files->getNext()) { 1783 std::unique_ptr<LineSequence> sequence( 1784 line_table->CreateLineSequenceContainer()); 1785 auto lines = m_session_up->findLineNumbers(*compiland_up, *file); 1786 if (!lines) 1787 continue; 1788 int entry_count = lines->getChildCount(); 1789 1790 uint64_t prev_addr; 1791 uint32_t prev_length; 1792 uint32_t prev_line; 1793 uint32_t prev_source_idx; 1794 1795 for (int i = 0; i < entry_count; ++i) { 1796 auto line = lines->getChildAtIndex(i); 1797 1798 uint64_t lno = line->getLineNumber(); 1799 uint64_t addr = line->getVirtualAddress(); 1800 uint32_t length = line->getLength(); 1801 uint32_t source_id = line->getSourceFileId(); 1802 uint32_t col = line->getColumnNumber(); 1803 uint32_t source_idx = index_map[source_id]; 1804 1805 // There was a gap between the current entry and the previous entry if 1806 // the addresses don't perfectly line up. 1807 bool is_gap = (i > 0) && (prev_addr + prev_length < addr); 1808 1809 // Before inserting the current entry, insert a terminal entry at the end 1810 // of the previous entry's address range if the current entry resulted in 1811 // a gap from the previous entry. 1812 if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) { 1813 line_table->AppendLineEntryToSequence( 1814 sequence.get(), prev_addr + prev_length, prev_line, 0, 1815 prev_source_idx, false, false, false, false, true); 1816 1817 line_table->InsertSequence(sequence.get()); 1818 sequence = line_table->CreateLineSequenceContainer(); 1819 } 1820 1821 if (ShouldAddLine(match_line, lno, length)) { 1822 bool is_statement = line->isStatement(); 1823 bool is_prologue = false; 1824 bool is_epilogue = false; 1825 auto func = 1826 m_session_up->findSymbolByAddress(addr, PDB_SymType::Function); 1827 if (func) { 1828 auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>(); 1829 if (prologue) 1830 is_prologue = (addr == prologue->getVirtualAddress()); 1831 1832 auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>(); 1833 if (epilogue) 1834 is_epilogue = (addr == epilogue->getVirtualAddress()); 1835 } 1836 1837 line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col, 1838 source_idx, is_statement, false, 1839 is_prologue, is_epilogue, false); 1840 } 1841 1842 prev_addr = addr; 1843 prev_length = length; 1844 prev_line = lno; 1845 prev_source_idx = source_idx; 1846 } 1847 1848 if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) { 1849 // The end is always a terminal entry, so insert it regardless. 1850 line_table->AppendLineEntryToSequence( 1851 sequence.get(), prev_addr + prev_length, prev_line, 0, 1852 prev_source_idx, false, false, false, false, true); 1853 } 1854 1855 line_table->InsertSequence(sequence.get()); 1856 } 1857 1858 if (line_table->GetSize()) { 1859 comp_unit.SetLineTable(line_table.release()); 1860 return true; 1861 } 1862 return false; 1863 } 1864 1865 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap( 1866 const PDBSymbolCompiland &compiland, 1867 llvm::DenseMap<uint32_t, uint32_t> &index_map) const { 1868 // This is a hack, but we need to convert the source id into an index into 1869 // the support files array. We don't want to do path comparisons to avoid 1870 // basename / full path issues that may or may not even be a problem, so we 1871 // use the globally unique source file identifiers. Ideally we could use the 1872 // global identifiers everywhere, but LineEntry currently assumes indices. 1873 auto source_files = m_session_up->getSourceFilesForCompiland(compiland); 1874 if (!source_files) 1875 return; 1876 1877 int index = 0; 1878 while (auto file = source_files->getNext()) { 1879 uint32_t source_id = file->getUniqueId(); 1880 index_map[source_id] = index++; 1881 } 1882 } 1883 1884 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress( 1885 const lldb_private::Address &so_addr) { 1886 lldb::addr_t file_vm_addr = so_addr.GetFileAddress(); 1887 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 1888 return nullptr; 1889 1890 // If it is a PDB function's vm addr, this is the first sure bet. 1891 if (auto lines = 1892 m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) { 1893 if (auto first_line = lines->getNext()) 1894 return ParseCompileUnitForUID(first_line->getCompilandId()); 1895 } 1896 1897 // Otherwise we resort to section contributions. 1898 if (auto sec_contribs = m_session_up->getSectionContribs()) { 1899 while (auto section = sec_contribs->getNext()) { 1900 auto va = section->getVirtualAddress(); 1901 if (file_vm_addr >= va && file_vm_addr < va + section->getLength()) 1902 return ParseCompileUnitForUID(section->getCompilandId()); 1903 } 1904 } 1905 return nullptr; 1906 } 1907 1908 Mangled 1909 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) { 1910 Mangled mangled; 1911 auto func_name = pdb_func.getName(); 1912 auto func_undecorated_name = pdb_func.getUndecoratedName(); 1913 std::string func_decorated_name; 1914 1915 // Seek from public symbols for non-static function's decorated name if any. 1916 // For static functions, they don't have undecorated names and aren't exposed 1917 // in Public Symbols either. 1918 if (!func_undecorated_name.empty()) { 1919 auto result_up = m_global_scope_up->findChildren( 1920 PDB_SymType::PublicSymbol, func_undecorated_name, 1921 PDB_NameSearchFlags::NS_UndecoratedName); 1922 if (result_up) { 1923 while (auto symbol_up = result_up->getNext()) { 1924 // For a public symbol, it is unique. 1925 lldbassert(result_up->getChildCount() == 1); 1926 if (auto *pdb_public_sym = 1927 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>( 1928 symbol_up.get())) { 1929 if (pdb_public_sym->isFunction()) { 1930 func_decorated_name = pdb_public_sym->getName(); 1931 break; 1932 } 1933 } 1934 } 1935 } 1936 } 1937 if (!func_decorated_name.empty()) { 1938 mangled.SetMangledName(ConstString(func_decorated_name)); 1939 1940 // For MSVC, format of C funciton's decorated name depends on calling 1941 // convention. Unfortunately none of the format is recognized by current 1942 // LLDB. For example, `_purecall` is a __cdecl C function. From PDB, 1943 // `__purecall` is retrieved as both its decorated and undecorated name 1944 // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall` 1945 // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix). 1946 // Mangled::GetDemangledName method will fail internally and caches an 1947 // empty string as its undecorated name. So we will face a contradiction 1948 // here for the same symbol: 1949 // non-empty undecorated name from PDB 1950 // empty undecorated name from LLDB 1951 if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty()) 1952 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1953 1954 // LLDB uses several flags to control how a C++ decorated name is 1955 // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the 1956 // yielded name could be different from what we retrieve from 1957 // PDB source unless we also apply same flags in getting undecorated 1958 // name through PDBSymbolFunc::getUndecoratedNameEx method. 1959 if (!func_undecorated_name.empty() && 1960 mangled.GetDemangledName() != ConstString(func_undecorated_name)) 1961 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1962 } else if (!func_undecorated_name.empty()) { 1963 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1964 } else if (!func_name.empty()) 1965 mangled.SetValue(ConstString(func_name), false); 1966 1967 return mangled; 1968 } 1969 1970 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile( 1971 const lldb_private::CompilerDeclContext &decl_ctx) { 1972 if (!decl_ctx.IsValid()) 1973 return true; 1974 1975 TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem(); 1976 if (!decl_ctx_type_system) 1977 return false; 1978 auto type_system_or_err = GetTypeSystemForLanguage( 1979 decl_ctx_type_system->GetMinimumLanguage(nullptr)); 1980 if (auto err = type_system_or_err.takeError()) { 1981 LLDB_LOG_ERROR( 1982 GetLog(LLDBLog::Symbols), std::move(err), 1983 "Unable to determine if DeclContext matches this symbol file"); 1984 return false; 1985 } 1986 1987 if (decl_ctx_type_system == &type_system_or_err.get()) 1988 return true; // The type systems match, return true 1989 1990 return false; 1991 } 1992 1993 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) { 1994 static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) { 1995 return lhs < rhs.Offset; 1996 }; 1997 1998 // Cache section contributions 1999 if (m_sec_contribs.empty()) { 2000 if (auto SecContribs = m_session_up->getSectionContribs()) { 2001 while (auto SectionContrib = SecContribs->getNext()) { 2002 auto comp_id = SectionContrib->getCompilandId(); 2003 if (!comp_id) 2004 continue; 2005 2006 auto sec = SectionContrib->getAddressSection(); 2007 auto &sec_cs = m_sec_contribs[sec]; 2008 2009 auto offset = SectionContrib->getAddressOffset(); 2010 auto it = 2011 std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper); 2012 2013 auto size = SectionContrib->getLength(); 2014 sec_cs.insert(it, {offset, size, comp_id}); 2015 } 2016 } 2017 } 2018 2019 // Check by line number 2020 if (auto Lines = data.getLineNumbers()) { 2021 if (auto FirstLine = Lines->getNext()) 2022 return FirstLine->getCompilandId(); 2023 } 2024 2025 // Retrieve section + offset 2026 uint32_t DataSection = data.getAddressSection(); 2027 uint32_t DataOffset = data.getAddressOffset(); 2028 if (DataSection == 0) { 2029 if (auto RVA = data.getRelativeVirtualAddress()) 2030 m_session_up->addressForRVA(RVA, DataSection, DataOffset); 2031 } 2032 2033 if (DataSection) { 2034 // Search by section contributions 2035 auto &sec_cs = m_sec_contribs[DataSection]; 2036 auto it = 2037 std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper); 2038 if (it != sec_cs.begin()) { 2039 --it; 2040 if (DataOffset < it->Offset + it->Size) 2041 return it->CompilandId; 2042 } 2043 } else { 2044 // Search in lexical tree 2045 auto LexParentId = data.getLexicalParentId(); 2046 while (auto LexParent = m_session_up->getSymbolById(LexParentId)) { 2047 if (LexParent->getSymTag() == PDB_SymType::Exe) 2048 break; 2049 if (LexParent->getSymTag() == PDB_SymType::Compiland) 2050 return LexParentId; 2051 LexParentId = LexParent->getRawSymbol().getLexicalParentId(); 2052 } 2053 } 2054 2055 return 0; 2056 } 2057