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