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