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