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