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" 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 (!ResolveTypeUID(symbol->getSymIndexId())) 463 continue; 464 465 ++num_added; 466 } 467 } 468 }; 469 470 if (sc.function) { 471 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>( 472 sc.function->GetID()); 473 if (!pdb_func) 474 return 0; 475 ParseTypesByTagFn(*pdb_func); 476 } else { 477 ParseTypesByTagFn(*compiland); 478 479 // Also parse global types particularly coming from this compiland. 480 // Unfortunately, PDB has no compiland information for each global type. We 481 // have to parse them all. But ensure we only do this once. 482 static bool parse_all_global_types = false; 483 if (!parse_all_global_types) { 484 ParseTypesByTagFn(*m_global_scope_up); 485 parse_all_global_types = true; 486 } 487 } 488 return num_added; 489 } 490 491 size_t 492 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) { 493 if (!sc.comp_unit) 494 return 0; 495 496 size_t num_added = 0; 497 if (sc.function) { 498 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>( 499 sc.function->GetID()); 500 if (!pdb_func) 501 return 0; 502 503 num_added += ParseVariables(sc, *pdb_func); 504 sc.function->GetBlock(false).SetDidParseVariables(true, true); 505 } else if (sc.comp_unit) { 506 auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID()); 507 if (!compiland) 508 return 0; 509 510 if (sc.comp_unit->GetVariableList(false)) 511 return 0; 512 513 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); 514 if (results && results->getChildCount()) { 515 while (auto result = results->getNext()) { 516 auto cu_id = result->getCompilandId(); 517 // FIXME: We are not able to determine variable's compile unit. 518 if (cu_id == 0) 519 continue; 520 521 if (cu_id == sc.comp_unit->GetID()) 522 num_added += ParseVariables(sc, *result); 523 } 524 } 525 526 // FIXME: A `file static` or `global constant` variable appears both in 527 // compiland's children and global scope's children with unexpectedly 528 // different symbol's Id making it ambiguous. 529 530 // FIXME: 'local constant', for example, const char var[] = "abc", declared 531 // in a function scope, can't be found in PDB. 532 533 // Parse variables in this compiland. 534 num_added += ParseVariables(sc, *compiland); 535 } 536 537 return num_added; 538 } 539 540 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 541 auto find_result = m_types.find(type_uid); 542 if (find_result != m_types.end()) 543 return find_result->second.get(); 544 545 TypeSystem *type_system = 546 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 547 ClangASTContext *clang_type_system = 548 llvm::dyn_cast_or_null<ClangASTContext>(type_system); 549 if (!clang_type_system) 550 return nullptr; 551 PDBASTParser *pdb = 552 llvm::dyn_cast<PDBASTParser>(clang_type_system->GetPDBParser()); 553 if (!pdb) 554 return nullptr; 555 556 auto pdb_type = m_session_up->getSymbolById(type_uid); 557 if (pdb_type == nullptr) 558 return nullptr; 559 560 lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type); 561 if (result) { 562 m_types.insert(std::make_pair(type_uid, result)); 563 auto type_list = GetTypeList(); 564 if (type_list) 565 type_list->Insert(result); 566 } 567 return result.get(); 568 } 569 570 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) { 571 // TODO: Implement this 572 return false; 573 } 574 575 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) { 576 return lldb_private::CompilerDecl(); 577 } 578 579 lldb_private::CompilerDeclContext 580 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) { 581 // PDB always uses the translation unit decl context for everything. We can 582 // improve this later but it's not easy because PDB doesn't provide a high 583 // enough level of type fidelity in this area. 584 return *m_tu_decl_ctx_up; 585 } 586 587 lldb_private::CompilerDeclContext 588 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) { 589 return *m_tu_decl_ctx_up; 590 } 591 592 void SymbolFilePDB::ParseDeclsForContext( 593 lldb_private::CompilerDeclContext decl_ctx) {} 594 595 uint32_t 596 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr, 597 uint32_t resolve_scope, 598 lldb_private::SymbolContext &sc) { 599 uint32_t resolved_flags = 0; 600 if (resolve_scope & eSymbolContextCompUnit || 601 resolve_scope & eSymbolContextVariable || 602 resolve_scope & eSymbolContextFunction || 603 resolve_scope & eSymbolContextBlock || 604 resolve_scope & eSymbolContextLineEntry) { 605 auto cu_sp = GetCompileUnitContainsAddress(so_addr); 606 if (!cu_sp) { 607 if (resolved_flags | eSymbolContextVariable) { 608 // TODO: Resolve variables 609 } 610 return 0; 611 } 612 sc.comp_unit = cu_sp.get(); 613 resolved_flags |= eSymbolContextCompUnit; 614 lldbassert(sc.module_sp == cu_sp->GetModule()); 615 } 616 617 if (resolve_scope & eSymbolContextFunction) { 618 addr_t file_vm_addr = so_addr.GetFileAddress(); 619 auto symbol_up = 620 m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function); 621 if (symbol_up) { 622 auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); 623 assert(pdb_func); 624 auto func_uid = pdb_func->getSymIndexId(); 625 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); 626 if (sc.function == nullptr) 627 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc); 628 if (sc.function) { 629 resolved_flags |= eSymbolContextFunction; 630 if (resolve_scope & eSymbolContextBlock) { 631 Block &block = sc.function->GetBlock(true); 632 sc.block = block.FindBlockByID(sc.function->GetID()); 633 if (sc.block) 634 resolved_flags |= eSymbolContextBlock; 635 } 636 } 637 } 638 } 639 640 if (resolve_scope & eSymbolContextLineEntry) { 641 if (auto *line_table = sc.comp_unit->GetLineTable()) { 642 Address addr(so_addr); 643 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 644 resolved_flags |= eSymbolContextLineEntry; 645 } 646 } 647 648 return resolved_flags; 649 } 650 651 uint32_t SymbolFilePDB::ResolveSymbolContext( 652 const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines, 653 uint32_t resolve_scope, lldb_private::SymbolContextList &sc_list) { 654 const size_t old_size = sc_list.GetSize(); 655 if (resolve_scope & lldb::eSymbolContextCompUnit) { 656 // Locate all compilation units with line numbers referencing the specified 657 // file. For example, if `file_spec` is <vector>, then this should return 658 // all source files and header files that reference <vector>, either 659 // directly or indirectly. 660 auto compilands = m_session_up->findCompilandsForSourceFile( 661 file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive); 662 663 if (!compilands) 664 return 0; 665 666 // For each one, either find its previously parsed data or parse it afresh 667 // and add it to the symbol context list. 668 while (auto compiland = compilands->getNext()) { 669 // If we're not checking inlines, then don't add line information for 670 // this file unless the FileSpec matches. For inline functions, we don't 671 // have to match the FileSpec since they could be defined in headers 672 // other than file specified in FileSpec. 673 if (!check_inlines) { 674 std::string source_file = compiland->getSourceFileFullPath(); 675 if (source_file.empty()) 676 continue; 677 FileSpec this_spec(source_file, false, FileSpec::Style::windows); 678 bool need_full_match = !file_spec.GetDirectory().IsEmpty(); 679 if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0) 680 continue; 681 } 682 683 SymbolContext sc; 684 auto cu = ParseCompileUnitForUID(compiland->getSymIndexId()); 685 if (!cu) 686 continue; 687 sc.comp_unit = cu.get(); 688 sc.module_sp = cu->GetModule(); 689 690 // If we were asked to resolve line entries, add all entries to the line 691 // table that match the requested line (or all lines if `line` == 0). 692 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock | 693 eSymbolContextLineEntry)) { 694 bool has_line_table = ParseCompileUnitLineTable(sc, line); 695 696 if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) { 697 // The query asks for line entries, but we can't get them for the 698 // compile unit. This is not normal for `line` = 0. So just assert 699 // it. 700 assert(line && "Couldn't get all line entries!\n"); 701 702 // Current compiland does not have the requested line. Search next. 703 continue; 704 } 705 706 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { 707 if (!has_line_table) 708 continue; 709 710 auto *line_table = sc.comp_unit->GetLineTable(); 711 lldbassert(line_table); 712 713 uint32_t num_line_entries = line_table->GetSize(); 714 // Skip the terminal line entry. 715 --num_line_entries; 716 717 // If `line `!= 0, see if we can resolve function for each line entry 718 // in the line table. 719 for (uint32_t line_idx = 0; line && line_idx < num_line_entries; 720 ++line_idx) { 721 if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry)) 722 continue; 723 724 auto file_vm_addr = 725 sc.line_entry.range.GetBaseAddress().GetFileAddress(); 726 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 727 continue; 728 729 auto symbol_up = m_session_up->findSymbolByAddress( 730 file_vm_addr, PDB_SymType::Function); 731 if (symbol_up) { 732 auto func_uid = symbol_up->getSymIndexId(); 733 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get(); 734 if (sc.function == nullptr) { 735 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get()); 736 assert(pdb_func); 737 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc); 738 } 739 if (sc.function && (resolve_scope & eSymbolContextBlock)) { 740 Block &block = sc.function->GetBlock(true); 741 sc.block = block.FindBlockByID(sc.function->GetID()); 742 } 743 } 744 sc_list.Append(sc); 745 } 746 } else if (has_line_table) { 747 // We can parse line table for the compile unit. But no query to 748 // resolve function or block. We append `sc` to the list anyway. 749 sc_list.Append(sc); 750 } 751 } else { 752 // No query for line entry, function or block. But we have a valid 753 // compile unit, append `sc` to the list. 754 sc_list.Append(sc); 755 } 756 } 757 } 758 return sc_list.GetSize() - old_size; 759 } 760 761 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) { 762 std::string decorated_name; 763 auto vm_addr = pdb_data.getVirtualAddress(); 764 if (vm_addr != LLDB_INVALID_ADDRESS && vm_addr) { 765 auto result_up = 766 m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol); 767 if (result_up) { 768 while (auto symbol_up = result_up->getNext()) { 769 if (symbol_up->getRawSymbol().getVirtualAddress() == vm_addr) { 770 decorated_name = symbol_up->getRawSymbol().getName(); 771 break; 772 } 773 } 774 } 775 } 776 if (!decorated_name.empty()) 777 return decorated_name; 778 779 return std::string(); 780 } 781 782 VariableSP SymbolFilePDB::ParseVariableForPDBData( 783 const lldb_private::SymbolContext &sc, 784 const llvm::pdb::PDBSymbolData &pdb_data) { 785 VariableSP var_sp; 786 uint32_t var_uid = pdb_data.getSymIndexId(); 787 auto result = m_variables.find(var_uid); 788 if (result != m_variables.end()) 789 return result->second; 790 791 ValueType scope = eValueTypeInvalid; 792 bool is_static_member = false; 793 bool is_external = false; 794 bool is_artificial = false; 795 796 switch (pdb_data.getDataKind()) { 797 case PDB_DataKind::Global: 798 scope = eValueTypeVariableGlobal; 799 is_external = true; 800 break; 801 case PDB_DataKind::Local: 802 scope = eValueTypeVariableLocal; 803 break; 804 case PDB_DataKind::FileStatic: 805 scope = eValueTypeVariableStatic; 806 break; 807 case PDB_DataKind::StaticMember: 808 is_static_member = true; 809 scope = eValueTypeVariableStatic; 810 break; 811 case PDB_DataKind::Member: 812 scope = eValueTypeVariableStatic; 813 break; 814 case PDB_DataKind::Param: 815 scope = eValueTypeVariableArgument; 816 break; 817 case PDB_DataKind::Constant: 818 scope = eValueTypeConstResult; 819 break; 820 default: 821 break; 822 } 823 824 switch (pdb_data.getLocationType()) { 825 case PDB_LocType::TLS: 826 scope = eValueTypeVariableThreadLocal; 827 break; 828 case PDB_LocType::RegRel: { 829 // It is a `this` pointer. 830 if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) { 831 scope = eValueTypeVariableArgument; 832 is_artificial = true; 833 } 834 } break; 835 default: 836 break; 837 } 838 839 Declaration decl; 840 if (!is_artificial && !pdb_data.isCompilerGenerated()) { 841 if (auto lines = pdb_data.getLineNumbers()) { 842 if (auto first_line = lines->getNext()) { 843 uint32_t src_file_id = first_line->getSourceFileId(); 844 auto src_file = m_session_up->getSourceFileById(src_file_id); 845 if (src_file) { 846 FileSpec spec(src_file->getFileName(), /*resolve_path*/ false); 847 decl.SetFile(spec); 848 decl.SetColumn(first_line->getColumnNumber()); 849 decl.SetLine(first_line->getLineNumber()); 850 } 851 } 852 } 853 } 854 855 Variable::RangeList ranges; 856 SymbolContextScope *context_scope = sc.comp_unit; 857 if (scope == eValueTypeVariableLocal) { 858 if (sc.function) { 859 context_scope = sc.function->GetBlock(true).FindBlockByID( 860 pdb_data.getClassParentId()); 861 if (context_scope == nullptr) 862 context_scope = sc.function; 863 } 864 } 865 866 SymbolFileTypeSP type_sp = 867 std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId()); 868 869 auto var_name = pdb_data.getName(); 870 auto mangled = GetMangledForPDBData(pdb_data); 871 auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str(); 872 873 bool is_constant; 874 DWARFExpression location = ConvertPDBLocationToDWARFExpression( 875 GetObjectFile()->GetModule(), pdb_data, is_constant); 876 877 var_sp = std::make_shared<Variable>( 878 var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope, 879 ranges, &decl, location, is_external, is_artificial, is_static_member); 880 var_sp->SetLocationIsConstantValueData(is_constant); 881 882 m_variables.insert(std::make_pair(var_uid, var_sp)); 883 return var_sp; 884 } 885 886 size_t 887 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc, 888 const llvm::pdb::PDBSymbol &pdb_symbol, 889 lldb_private::VariableList *variable_list) { 890 size_t num_added = 0; 891 892 if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) { 893 VariableListSP local_variable_list_sp; 894 895 auto result = m_variables.find(pdb_data->getSymIndexId()); 896 if (result != m_variables.end()) { 897 if (variable_list) 898 variable_list->AddVariableIfUnique(result->second); 899 } else { 900 // Prepare right VariableList for this variable. 901 if (auto lexical_parent = pdb_data->getLexicalParent()) { 902 switch (lexical_parent->getSymTag()) { 903 case PDB_SymType::Exe: 904 assert(sc.comp_unit); 905 LLVM_FALLTHROUGH; 906 case PDB_SymType::Compiland: { 907 if (sc.comp_unit) { 908 local_variable_list_sp = sc.comp_unit->GetVariableList(false); 909 if (!local_variable_list_sp) { 910 local_variable_list_sp = std::make_shared<VariableList>(); 911 sc.comp_unit->SetVariableList(local_variable_list_sp); 912 } 913 } 914 } break; 915 case PDB_SymType::Block: 916 case PDB_SymType::Function: { 917 if (sc.function) { 918 Block *block = sc.function->GetBlock(true).FindBlockByID( 919 lexical_parent->getSymIndexId()); 920 if (block) { 921 local_variable_list_sp = block->GetBlockVariableList(false); 922 if (!local_variable_list_sp) { 923 local_variable_list_sp = std::make_shared<VariableList>(); 924 block->SetVariableList(local_variable_list_sp); 925 } 926 } 927 } 928 } break; 929 default: 930 break; 931 } 932 } 933 934 if (local_variable_list_sp) { 935 if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) { 936 local_variable_list_sp->AddVariableIfUnique(var_sp); 937 if (variable_list) 938 variable_list->AddVariableIfUnique(var_sp); 939 ++num_added; 940 } 941 } 942 } 943 } 944 945 if (auto results = pdb_symbol.findAllChildren()) { 946 while (auto result = results->getNext()) 947 num_added += ParseVariables(sc, *result, variable_list); 948 } 949 950 return num_added; 951 } 952 953 uint32_t SymbolFilePDB::FindGlobalVariables( 954 const lldb_private::ConstString &name, 955 const lldb_private::CompilerDeclContext *parent_decl_ctx, 956 uint32_t max_matches, lldb_private::VariableList &variables) { 957 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 958 return 0; 959 if (name.IsEmpty()) 960 return 0; 961 962 auto results = 963 m_global_scope_up->findChildren(PDB_SymType::Data, name.GetStringRef(), 964 PDB_NameSearchFlags::NS_CaseSensitive); 965 if (!results) 966 return 0; 967 968 uint32_t matches = 0; 969 size_t old_size = variables.GetSize(); 970 while (auto result = results->getNext()) { 971 auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get()); 972 if (max_matches > 0 && matches >= max_matches) 973 break; 974 975 SymbolContext sc; 976 sc.module_sp = m_obj_file->GetModule(); 977 lldbassert(sc.module_sp.get()); 978 979 sc.comp_unit = ParseCompileUnitForUID(pdb_data->getCompilandId()).get(); 980 // FIXME: We are not able to determine the compile unit. 981 if (sc.comp_unit == nullptr) 982 continue; 983 984 ParseVariables(sc, *pdb_data, &variables); 985 matches = variables.GetSize() - old_size; 986 } 987 988 return matches; 989 } 990 991 uint32_t 992 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression ®ex, 993 uint32_t max_matches, 994 lldb_private::VariableList &variables) { 995 if (!regex.IsValid()) 996 return 0; 997 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>(); 998 if (!results) 999 return 0; 1000 1001 uint32_t matches = 0; 1002 size_t old_size = variables.GetSize(); 1003 while (auto pdb_data = results->getNext()) { 1004 if (max_matches > 0 && matches >= max_matches) 1005 break; 1006 1007 auto var_name = pdb_data->getName(); 1008 if (var_name.empty()) 1009 continue; 1010 if (!regex.Execute(var_name)) 1011 continue; 1012 SymbolContext sc; 1013 sc.module_sp = m_obj_file->GetModule(); 1014 lldbassert(sc.module_sp.get()); 1015 1016 sc.comp_unit = ParseCompileUnitForUID(pdb_data->getCompilandId()).get(); 1017 // FIXME: We are not able to determine the compile unit. 1018 if (sc.comp_unit == nullptr) 1019 continue; 1020 1021 ParseVariables(sc, *pdb_data, &variables); 1022 matches = variables.GetSize() - old_size; 1023 } 1024 1025 return matches; 1026 } 1027 1028 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func, 1029 bool include_inlines, 1030 lldb_private::SymbolContextList &sc_list) { 1031 lldb_private::SymbolContext sc; 1032 sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get(); 1033 if (!sc.comp_unit) 1034 return false; 1035 sc.module_sp = sc.comp_unit->GetModule(); 1036 sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, sc); 1037 if (!sc.function) 1038 return false; 1039 1040 sc_list.Append(sc); 1041 return true; 1042 } 1043 1044 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines, 1045 lldb_private::SymbolContextList &sc_list) { 1046 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid); 1047 if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute())) 1048 return false; 1049 return ResolveFunction(*pdb_func_up, include_inlines, sc_list); 1050 } 1051 1052 void SymbolFilePDB::CacheFunctionNames() { 1053 if (!m_func_full_names.IsEmpty()) 1054 return; 1055 1056 std::map<uint64_t, uint32_t> addr_ids; 1057 1058 if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) { 1059 while (auto pdb_func_up = results_up->getNext()) { 1060 if (pdb_func_up->isCompilerGenerated()) 1061 continue; 1062 1063 auto name = pdb_func_up->getName(); 1064 auto demangled_name = pdb_func_up->getUndecoratedName(); 1065 if (name.empty() && demangled_name.empty()) 1066 continue; 1067 1068 auto uid = pdb_func_up->getSymIndexId(); 1069 if (!demangled_name.empty() && pdb_func_up->getVirtualAddress()) 1070 addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid)); 1071 1072 if (auto parent = pdb_func_up->getClassParent()) { 1073 1074 // PDB have symbols for class/struct methods or static methods in Enum 1075 // Class. We won't bother to check if the parent is UDT or Enum here. 1076 m_func_method_names.Append(ConstString(name), uid); 1077 1078 ConstString cstr_name(name); 1079 1080 // To search a method name, like NS::Class:MemberFunc, LLDB searches 1081 // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does 1082 // not have inforamtion of this, we extract base names and cache them 1083 // by our own effort. 1084 llvm::StringRef basename; 1085 CPlusPlusLanguage::MethodName cpp_method(cstr_name); 1086 if (cpp_method.IsValid()) { 1087 llvm::StringRef context; 1088 basename = cpp_method.GetBasename(); 1089 if (basename.empty()) 1090 CPlusPlusLanguage::ExtractContextAndIdentifier(name.c_str(), 1091 context, basename); 1092 } 1093 1094 if (!basename.empty()) 1095 m_func_base_names.Append(ConstString(basename), uid); 1096 else { 1097 m_func_base_names.Append(ConstString(name), uid); 1098 } 1099 1100 if (!demangled_name.empty()) 1101 m_func_full_names.Append(ConstString(demangled_name), uid); 1102 1103 } else { 1104 // Handle not-method symbols. 1105 1106 // The function name might contain namespace, or its lexical scope. It 1107 // is not safe to get its base name by applying same scheme as we deal 1108 // with the method names. 1109 // FIXME: Remove namespace if function is static in a scope. 1110 m_func_base_names.Append(ConstString(name), uid); 1111 1112 if (name == "main") { 1113 m_func_full_names.Append(ConstString(name), uid); 1114 1115 if (!demangled_name.empty() && name != demangled_name) { 1116 m_func_full_names.Append(ConstString(demangled_name), uid); 1117 m_func_base_names.Append(ConstString(demangled_name), uid); 1118 } 1119 } else if (!demangled_name.empty()) { 1120 m_func_full_names.Append(ConstString(demangled_name), uid); 1121 } else { 1122 m_func_full_names.Append(ConstString(name), uid); 1123 } 1124 } 1125 } 1126 } 1127 1128 if (auto results_up = 1129 m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) { 1130 while (auto pub_sym_up = results_up->getNext()) { 1131 if (!pub_sym_up->isFunction()) 1132 continue; 1133 auto name = pub_sym_up->getName(); 1134 if (name.empty()) 1135 continue; 1136 1137 if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) { 1138 auto vm_addr = pub_sym_up->getVirtualAddress(); 1139 1140 // PDB public symbol has mangled name for its associated function. 1141 if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) { 1142 // Cache mangled name. 1143 m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]); 1144 } 1145 } 1146 } 1147 } 1148 // Sort them before value searching is working properly 1149 m_func_full_names.Sort(); 1150 m_func_full_names.SizeToFit(); 1151 m_func_method_names.Sort(); 1152 m_func_method_names.SizeToFit(); 1153 m_func_base_names.Sort(); 1154 m_func_base_names.SizeToFit(); 1155 } 1156 1157 uint32_t SymbolFilePDB::FindFunctions( 1158 const lldb_private::ConstString &name, 1159 const lldb_private::CompilerDeclContext *parent_decl_ctx, 1160 uint32_t name_type_mask, bool include_inlines, bool append, 1161 lldb_private::SymbolContextList &sc_list) { 1162 if (!append) 1163 sc_list.Clear(); 1164 lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0); 1165 1166 if (name_type_mask == eFunctionNameTypeNone) 1167 return 0; 1168 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 1169 return 0; 1170 if (name.IsEmpty()) 1171 return 0; 1172 1173 auto old_size = sc_list.GetSize(); 1174 if (name_type_mask & eFunctionNameTypeFull || 1175 name_type_mask & eFunctionNameTypeBase || 1176 name_type_mask & eFunctionNameTypeMethod) { 1177 CacheFunctionNames(); 1178 1179 std::set<uint32_t> resolved_ids; 1180 auto ResolveFn = [include_inlines, &name, &sc_list, &resolved_ids, 1181 this](UniqueCStringMap<uint32_t> &Names) { 1182 std::vector<uint32_t> ids; 1183 if (Names.GetValues(name, ids)) { 1184 for (auto id : ids) { 1185 if (resolved_ids.find(id) == resolved_ids.end()) { 1186 if (ResolveFunction(id, include_inlines, sc_list)) 1187 resolved_ids.insert(id); 1188 } 1189 } 1190 } 1191 }; 1192 if (name_type_mask & eFunctionNameTypeFull) { 1193 ResolveFn(m_func_full_names); 1194 } 1195 if (name_type_mask & eFunctionNameTypeBase) { 1196 ResolveFn(m_func_base_names); 1197 } 1198 if (name_type_mask & eFunctionNameTypeMethod) { 1199 ResolveFn(m_func_method_names); 1200 } 1201 } 1202 return sc_list.GetSize() - old_size; 1203 } 1204 1205 uint32_t 1206 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex, 1207 bool include_inlines, bool append, 1208 lldb_private::SymbolContextList &sc_list) { 1209 if (!append) 1210 sc_list.Clear(); 1211 if (!regex.IsValid()) 1212 return 0; 1213 1214 auto old_size = sc_list.GetSize(); 1215 CacheFunctionNames(); 1216 1217 std::set<uint32_t> resolved_ids; 1218 auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids, 1219 this](UniqueCStringMap<uint32_t> &Names) { 1220 std::vector<uint32_t> ids; 1221 if (Names.GetValues(regex, ids)) { 1222 for (auto id : ids) { 1223 if (resolved_ids.find(id) == resolved_ids.end()) 1224 if (ResolveFunction(id, include_inlines, sc_list)) 1225 resolved_ids.insert(id); 1226 } 1227 } 1228 }; 1229 ResolveFn(m_func_full_names); 1230 ResolveFn(m_func_base_names); 1231 1232 return sc_list.GetSize() - old_size; 1233 } 1234 1235 void SymbolFilePDB::GetMangledNamesForFunction( 1236 const std::string &scope_qualified_name, 1237 std::vector<lldb_private::ConstString> &mangled_names) {} 1238 1239 uint32_t SymbolFilePDB::FindTypes( 1240 const lldb_private::SymbolContext &sc, 1241 const lldb_private::ConstString &name, 1242 const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append, 1243 uint32_t max_matches, 1244 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 1245 lldb_private::TypeMap &types) { 1246 if (!append) 1247 types.Clear(); 1248 if (!name) 1249 return 0; 1250 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 1251 return 0; 1252 1253 searched_symbol_files.clear(); 1254 searched_symbol_files.insert(this); 1255 1256 std::string name_str = name.AsCString(); 1257 1258 // There is an assumption 'name' is not a regex 1259 FindTypesByName(name_str, max_matches, types); 1260 1261 return types.GetSize(); 1262 } 1263 1264 void SymbolFilePDB::FindTypesByRegex( 1265 const lldb_private::RegularExpression ®ex, uint32_t max_matches, 1266 lldb_private::TypeMap &types) { 1267 // When searching by regex, we need to go out of our way to limit the search 1268 // space as much as possible since this searches EVERYTHING in the PDB, 1269 // manually doing regex comparisons. PDB library isn't optimized for regex 1270 // searches or searches across multiple symbol types at the same time, so the 1271 // best we can do is to search enums, then typedefs, then classes one by one, 1272 // and do a regex comparison against each of them. 1273 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef, 1274 PDB_SymType::UDT}; 1275 std::unique_ptr<IPDBEnumSymbols> results; 1276 1277 uint32_t matches = 0; 1278 1279 for (auto tag : tags_to_search) { 1280 results = m_global_scope_up->findAllChildren(tag); 1281 if (!results) 1282 continue; 1283 1284 while (auto result = results->getNext()) { 1285 if (max_matches > 0 && matches >= max_matches) 1286 break; 1287 1288 std::string type_name; 1289 if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get())) 1290 type_name = enum_type->getName(); 1291 else if (auto typedef_type = 1292 llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get())) 1293 type_name = typedef_type->getName(); 1294 else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get())) 1295 type_name = class_type->getName(); 1296 else { 1297 // We're looking only for types that have names. Skip symbols, as well 1298 // as unnamed types such as arrays, pointers, etc. 1299 continue; 1300 } 1301 1302 if (!regex.Execute(type_name)) 1303 continue; 1304 1305 // This should cause the type to get cached and stored in the `m_types` 1306 // lookup. 1307 if (!ResolveTypeUID(result->getSymIndexId())) 1308 continue; 1309 1310 auto iter = m_types.find(result->getSymIndexId()); 1311 if (iter == m_types.end()) 1312 continue; 1313 types.Insert(iter->second); 1314 ++matches; 1315 } 1316 } 1317 } 1318 1319 void SymbolFilePDB::FindTypesByName(const std::string &name, 1320 uint32_t max_matches, 1321 lldb_private::TypeMap &types) { 1322 std::unique_ptr<IPDBEnumSymbols> results; 1323 if (name.empty()) 1324 return; 1325 results = m_global_scope_up->findChildren(PDB_SymType::None, name, 1326 PDB_NameSearchFlags::NS_Default); 1327 if (!results) 1328 return; 1329 1330 uint32_t matches = 0; 1331 1332 while (auto result = results->getNext()) { 1333 if (max_matches > 0 && matches >= max_matches) 1334 break; 1335 switch (result->getSymTag()) { 1336 case PDB_SymType::Enum: 1337 case PDB_SymType::UDT: 1338 case PDB_SymType::Typedef: 1339 break; 1340 default: 1341 // We're looking only for types that have names. Skip symbols, as well 1342 // as unnamed types such as arrays, pointers, etc. 1343 continue; 1344 } 1345 1346 // This should cause the type to get cached and stored in the `m_types` 1347 // lookup. 1348 if (!ResolveTypeUID(result->getSymIndexId())) 1349 continue; 1350 1351 auto iter = m_types.find(result->getSymIndexId()); 1352 if (iter == m_types.end()) 1353 continue; 1354 types.Insert(iter->second); 1355 ++matches; 1356 } 1357 } 1358 1359 size_t SymbolFilePDB::FindTypes( 1360 const std::vector<lldb_private::CompilerContext> &contexts, bool append, 1361 lldb_private::TypeMap &types) { 1362 return 0; 1363 } 1364 1365 lldb_private::TypeList *SymbolFilePDB::GetTypeList() { 1366 return m_obj_file->GetModule()->GetTypeList(); 1367 } 1368 1369 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol, 1370 uint32_t type_mask, 1371 TypeCollection &type_collection) { 1372 bool can_parse = false; 1373 switch (pdb_symbol.getSymTag()) { 1374 case PDB_SymType::ArrayType: 1375 can_parse = ((type_mask & eTypeClassArray) != 0); 1376 break; 1377 case PDB_SymType::BuiltinType: 1378 can_parse = ((type_mask & eTypeClassBuiltin) != 0); 1379 break; 1380 case PDB_SymType::Enum: 1381 can_parse = ((type_mask & eTypeClassEnumeration) != 0); 1382 break; 1383 case PDB_SymType::Function: 1384 case PDB_SymType::FunctionSig: 1385 can_parse = ((type_mask & eTypeClassFunction) != 0); 1386 break; 1387 case PDB_SymType::PointerType: 1388 can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer | 1389 eTypeClassMemberPointer)) != 0); 1390 break; 1391 case PDB_SymType::Typedef: 1392 can_parse = ((type_mask & eTypeClassTypedef) != 0); 1393 break; 1394 case PDB_SymType::UDT: { 1395 auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol); 1396 assert(udt); 1397 can_parse = (udt->getUdtKind() != PDB_UdtType::Interface && 1398 ((type_mask & (eTypeClassClass | eTypeClassStruct | 1399 eTypeClassUnion)) != 0)); 1400 } break; 1401 default: 1402 break; 1403 } 1404 1405 if (can_parse) { 1406 if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) { 1407 auto result = 1408 std::find(type_collection.begin(), type_collection.end(), type); 1409 if (result == type_collection.end()) 1410 type_collection.push_back(type); 1411 } 1412 } 1413 1414 auto results_up = pdb_symbol.findAllChildren(); 1415 while (auto symbol_up = results_up->getNext()) 1416 GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection); 1417 } 1418 1419 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1420 uint32_t type_mask, 1421 lldb_private::TypeList &type_list) { 1422 TypeCollection type_collection; 1423 uint32_t old_size = type_list.GetSize(); 1424 CompileUnit *cu = 1425 sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr; 1426 if (cu) { 1427 auto compiland_up = GetPDBCompilandByUID(cu->GetID()); 1428 if (!compiland_up) 1429 return 0; 1430 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); 1431 } else { 1432 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) { 1433 auto cu_sp = ParseCompileUnitAtIndex(cu_idx); 1434 if (cu_sp) { 1435 if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID())) 1436 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection); 1437 } 1438 } 1439 } 1440 1441 for (auto type : type_collection) { 1442 type->GetForwardCompilerType(); 1443 type_list.Insert(type->shared_from_this()); 1444 } 1445 return type_list.GetSize() - old_size; 1446 } 1447 1448 lldb_private::TypeSystem * 1449 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1450 auto type_system = 1451 m_obj_file->GetModule()->GetTypeSystemForLanguage(language); 1452 if (type_system) 1453 type_system->SetSymbolFile(this); 1454 return type_system; 1455 } 1456 1457 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace( 1458 const lldb_private::SymbolContext &sc, 1459 const lldb_private::ConstString &name, 1460 const lldb_private::CompilerDeclContext *parent_decl_ctx) { 1461 return lldb_private::CompilerDeclContext(); 1462 } 1463 1464 lldb_private::ConstString SymbolFilePDB::GetPluginName() { 1465 static ConstString g_name("pdb"); 1466 return g_name; 1467 } 1468 1469 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; } 1470 1471 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; } 1472 1473 const IPDBSession &SymbolFilePDB::GetPDBSession() const { 1474 return *m_session_up; 1475 } 1476 1477 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id, 1478 uint32_t index) { 1479 auto found_cu = m_comp_units.find(id); 1480 if (found_cu != m_comp_units.end()) 1481 return found_cu->second; 1482 1483 auto compiland_up = GetPDBCompilandByUID(id); 1484 if (!compiland_up) 1485 return CompUnitSP(); 1486 1487 lldb::LanguageType lang; 1488 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>(); 1489 if (!details) 1490 lang = lldb::eLanguageTypeC_plus_plus; 1491 else 1492 lang = TranslateLanguage(details->getLanguage()); 1493 1494 if (lang == lldb::LanguageType::eLanguageTypeUnknown) 1495 return CompUnitSP(); 1496 1497 std::string path = compiland_up->getSourceFileFullPath(); 1498 if (path.empty()) 1499 return CompUnitSP(); 1500 1501 // Don't support optimized code for now, DebugInfoPDB does not return this 1502 // information. 1503 LazyBool optimized = eLazyBoolNo; 1504 auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, 1505 path.c_str(), id, lang, optimized); 1506 1507 if (!cu_sp) 1508 return CompUnitSP(); 1509 1510 m_comp_units.insert(std::make_pair(id, cu_sp)); 1511 if (index == UINT32_MAX) 1512 GetCompileUnitIndex(*compiland_up, index); 1513 lldbassert(index != UINT32_MAX); 1514 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index, 1515 cu_sp); 1516 return cu_sp; 1517 } 1518 1519 bool SymbolFilePDB::ParseCompileUnitLineTable( 1520 const lldb_private::SymbolContext &sc, uint32_t match_line) { 1521 lldbassert(sc.comp_unit); 1522 1523 auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID()); 1524 if (!compiland_up) 1525 return false; 1526 1527 // LineEntry needs the *index* of the file into the list of support files 1528 // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us 1529 // a globally unique idenfitifier in the namespace of the PDB. So, we have 1530 // to do a mapping so that we can hand out indices. 1531 llvm::DenseMap<uint32_t, uint32_t> index_map; 1532 BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map); 1533 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit); 1534 1535 // Find contributions to `compiland` from all source and header files. 1536 std::string path = sc.comp_unit->GetPath(); 1537 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up); 1538 if (!files) 1539 return false; 1540 1541 // For each source and header file, create a LineSequence for contributions 1542 // to the compiland from that file, and add the sequence. 1543 while (auto file = files->getNext()) { 1544 std::unique_ptr<LineSequence> sequence( 1545 line_table->CreateLineSequenceContainer()); 1546 auto lines = m_session_up->findLineNumbers(*compiland_up, *file); 1547 if (!lines) 1548 continue; 1549 int entry_count = lines->getChildCount(); 1550 1551 uint64_t prev_addr; 1552 uint32_t prev_length; 1553 uint32_t prev_line; 1554 uint32_t prev_source_idx; 1555 1556 for (int i = 0; i < entry_count; ++i) { 1557 auto line = lines->getChildAtIndex(i); 1558 1559 uint64_t lno = line->getLineNumber(); 1560 uint64_t addr = line->getVirtualAddress(); 1561 uint32_t length = line->getLength(); 1562 uint32_t source_id = line->getSourceFileId(); 1563 uint32_t col = line->getColumnNumber(); 1564 uint32_t source_idx = index_map[source_id]; 1565 1566 // There was a gap between the current entry and the previous entry if 1567 // the addresses don't perfectly line up. 1568 bool is_gap = (i > 0) && (prev_addr + prev_length < addr); 1569 1570 // Before inserting the current entry, insert a terminal entry at the end 1571 // of the previous entry's address range if the current entry resulted in 1572 // a gap from the previous entry. 1573 if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) { 1574 line_table->AppendLineEntryToSequence( 1575 sequence.get(), prev_addr + prev_length, prev_line, 0, 1576 prev_source_idx, false, false, false, false, true); 1577 1578 line_table->InsertSequence(sequence.release()); 1579 sequence.reset(line_table->CreateLineSequenceContainer()); 1580 } 1581 1582 if (ShouldAddLine(match_line, lno, length)) { 1583 bool is_statement = line->isStatement(); 1584 bool is_prologue = false; 1585 bool is_epilogue = false; 1586 auto func = 1587 m_session_up->findSymbolByAddress(addr, PDB_SymType::Function); 1588 if (func) { 1589 auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>(); 1590 if (prologue) 1591 is_prologue = (addr == prologue->getVirtualAddress()); 1592 1593 auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>(); 1594 if (epilogue) 1595 is_epilogue = (addr == epilogue->getVirtualAddress()); 1596 } 1597 1598 line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col, 1599 source_idx, is_statement, false, 1600 is_prologue, is_epilogue, false); 1601 } 1602 1603 prev_addr = addr; 1604 prev_length = length; 1605 prev_line = lno; 1606 prev_source_idx = source_idx; 1607 } 1608 1609 if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) { 1610 // The end is always a terminal entry, so insert it regardless. 1611 line_table->AppendLineEntryToSequence( 1612 sequence.get(), prev_addr + prev_length, prev_line, 0, 1613 prev_source_idx, false, false, false, false, true); 1614 } 1615 1616 line_table->InsertSequence(sequence.release()); 1617 } 1618 1619 if (line_table->GetSize()) { 1620 sc.comp_unit->SetLineTable(line_table.release()); 1621 return true; 1622 } 1623 return false; 1624 } 1625 1626 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap( 1627 const PDBSymbolCompiland &compiland, 1628 llvm::DenseMap<uint32_t, uint32_t> &index_map) const { 1629 // This is a hack, but we need to convert the source id into an index into 1630 // the support files array. We don't want to do path comparisons to avoid 1631 // basename / full path issues that may or may not even be a problem, so we 1632 // use the globally unique source file identifiers. Ideally we could use the 1633 // global identifiers everywhere, but LineEntry currently assumes indices. 1634 auto source_files = m_session_up->getSourceFilesForCompiland(compiland); 1635 if (!source_files) 1636 return; 1637 1638 // LLDB uses the DWARF-like file numeration (one based) 1639 int index = 1; 1640 1641 while (auto file = source_files->getNext()) { 1642 uint32_t source_id = file->getUniqueId(); 1643 index_map[source_id] = index++; 1644 } 1645 } 1646 1647 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress( 1648 const lldb_private::Address &so_addr) { 1649 lldb::addr_t file_vm_addr = so_addr.GetFileAddress(); 1650 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 1651 return nullptr; 1652 1653 // If it is a PDB function's vm addr, this is the first sure bet. 1654 if (auto lines = 1655 m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) { 1656 if (auto first_line = lines->getNext()) 1657 return ParseCompileUnitForUID(first_line->getCompilandId()); 1658 } 1659 1660 // Otherwise we resort to section contributions. 1661 if (auto sec_contribs = m_session_up->getSectionContribs()) { 1662 while (auto section = sec_contribs->getNext()) { 1663 auto va = section->getVirtualAddress(); 1664 if (file_vm_addr >= va && file_vm_addr < va + section->getLength()) 1665 return ParseCompileUnitForUID(section->getCompilandId()); 1666 } 1667 } 1668 return nullptr; 1669 } 1670 1671 Mangled 1672 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) { 1673 Mangled mangled; 1674 auto func_name = pdb_func.getName(); 1675 auto func_undecorated_name = pdb_func.getUndecoratedName(); 1676 std::string func_decorated_name; 1677 1678 // Seek from public symbols for non-static function's decorated name if any. 1679 // For static functions, they don't have undecorated names and aren't exposed 1680 // in Public Symbols either. 1681 if (!func_undecorated_name.empty()) { 1682 auto result_up = m_global_scope_up->findChildren( 1683 PDB_SymType::PublicSymbol, func_undecorated_name, 1684 PDB_NameSearchFlags::NS_UndecoratedName); 1685 if (result_up) { 1686 while (auto symbol_up = result_up->getNext()) { 1687 // For a public symbol, it is unique. 1688 lldbassert(result_up->getChildCount() == 1); 1689 if (auto *pdb_public_sym = 1690 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>( 1691 symbol_up.get())) { 1692 if (pdb_public_sym->isFunction()) { 1693 func_decorated_name = pdb_public_sym->getName(); 1694 break; 1695 } 1696 } 1697 } 1698 } 1699 } 1700 if (!func_decorated_name.empty()) { 1701 mangled.SetMangledName(ConstString(func_decorated_name)); 1702 1703 // For MSVC, format of C funciton's decorated name depends on calling 1704 // conventon. Unfortunately none of the format is recognized by current 1705 // LLDB. For example, `_purecall` is a __cdecl C function. From PDB, 1706 // `__purecall` is retrieved as both its decorated and undecorated name 1707 // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall` 1708 // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix). 1709 // Mangled::GetDemangledName method will fail internally and caches an 1710 // empty string as its undecorated name. So we will face a contradition 1711 // here for the same symbol: 1712 // non-empty undecorated name from PDB 1713 // empty undecorated name from LLDB 1714 if (!func_undecorated_name.empty() && 1715 mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty()) 1716 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1717 1718 // LLDB uses several flags to control how a C++ decorated name is 1719 // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the 1720 // yielded name could be different from what we retrieve from 1721 // PDB source unless we also apply same flags in getting undecorated 1722 // name through PDBSymbolFunc::getUndecoratedNameEx method. 1723 if (!func_undecorated_name.empty() && 1724 mangled.GetDemangledName(mangled.GuessLanguage()) != 1725 ConstString(func_undecorated_name)) 1726 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1727 } else if (!func_undecorated_name.empty()) { 1728 mangled.SetDemangledName(ConstString(func_undecorated_name)); 1729 } else if (!func_name.empty()) 1730 mangled.SetValue(ConstString(func_name), false); 1731 1732 return mangled; 1733 } 1734 1735 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile( 1736 const lldb_private::CompilerDeclContext *decl_ctx) { 1737 if (decl_ctx == nullptr || !decl_ctx->IsValid()) 1738 return true; 1739 1740 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem(); 1741 if (!decl_ctx_type_system) 1742 return false; 1743 TypeSystem *type_system = GetTypeSystemForLanguage( 1744 decl_ctx_type_system->GetMinimumLanguage(nullptr)); 1745 if (decl_ctx_type_system == type_system) 1746 return true; // The type systems match, return true 1747 1748 return false; 1749 } 1750