1 //===-- SymbolFileNativePDB.cpp -------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "SymbolFileNativePDB.h" 10 11 #include "clang/AST/Attr.h" 12 #include "clang/AST/CharUnits.h" 13 #include "clang/AST/Decl.h" 14 #include "clang/AST/DeclCXX.h" 15 #include "clang/AST/Type.h" 16 17 #include "Plugins/ExpressionParser/Clang/ClangUtil.h" 18 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" 19 #include "Plugins/ObjectFile/PDB/ObjectFilePDB.h" 20 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 21 #include "lldb/Core/Module.h" 22 #include "lldb/Core/PluginManager.h" 23 #include "lldb/Core/StreamBuffer.h" 24 #include "lldb/Core/StreamFile.h" 25 #include "lldb/Symbol/CompileUnit.h" 26 #include "lldb/Symbol/LineTable.h" 27 #include "lldb/Symbol/ObjectFile.h" 28 #include "lldb/Symbol/SymbolContext.h" 29 #include "lldb/Symbol/SymbolVendor.h" 30 #include "lldb/Symbol/Variable.h" 31 #include "lldb/Symbol/VariableList.h" 32 #include "lldb/Utility/Log.h" 33 34 #include "llvm/DebugInfo/CodeView/CVRecord.h" 35 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 36 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h" 37 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" 38 #include "llvm/DebugInfo/CodeView/RecordName.h" 39 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 40 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h" 41 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" 42 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 43 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" 44 #include "llvm/DebugInfo/PDB/Native/InfoStream.h" 45 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h" 46 #include "llvm/DebugInfo/PDB/Native/NativeSession.h" 47 #include "llvm/DebugInfo/PDB/Native/PDBFile.h" 48 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" 49 #include "llvm/DebugInfo/PDB/Native/TpiStream.h" 50 #include "llvm/DebugInfo/PDB/PDB.h" 51 #include "llvm/DebugInfo/PDB/PDBTypes.h" 52 #include "llvm/Demangle/MicrosoftDemangle.h" 53 #include "llvm/Object/COFF.h" 54 #include "llvm/Support/Allocator.h" 55 #include "llvm/Support/BinaryStreamReader.h" 56 #include "llvm/Support/Error.h" 57 #include "llvm/Support/ErrorOr.h" 58 #include "llvm/Support/MemoryBuffer.h" 59 60 #include "DWARFLocationExpression.h" 61 #include "PdbAstBuilder.h" 62 #include "PdbSymUid.h" 63 #include "PdbUtil.h" 64 #include "UdtRecordCompleter.h" 65 66 using namespace lldb; 67 using namespace lldb_private; 68 using namespace npdb; 69 using namespace llvm::codeview; 70 using namespace llvm::pdb; 71 72 char SymbolFileNativePDB::ID; 73 74 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) { 75 switch (lang) { 76 case PDB_Lang::Cpp: 77 return lldb::LanguageType::eLanguageTypeC_plus_plus; 78 case PDB_Lang::C: 79 return lldb::LanguageType::eLanguageTypeC; 80 case PDB_Lang::Swift: 81 return lldb::LanguageType::eLanguageTypeSwift; 82 default: 83 return lldb::LanguageType::eLanguageTypeUnknown; 84 } 85 } 86 87 static std::unique_ptr<PDBFile> 88 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) { 89 // Try to find a matching PDB for an EXE. 90 using namespace llvm::object; 91 auto expected_binary = createBinary(exe_path); 92 93 // If the file isn't a PE/COFF executable, fail. 94 if (!expected_binary) { 95 llvm::consumeError(expected_binary.takeError()); 96 return nullptr; 97 } 98 OwningBinary<Binary> binary = std::move(*expected_binary); 99 100 // TODO: Avoid opening the PE/COFF binary twice by reading this information 101 // directly from the lldb_private::ObjectFile. 102 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary()); 103 if (!obj) 104 return nullptr; 105 const llvm::codeview::DebugInfo *pdb_info = nullptr; 106 107 // If it doesn't have a debug directory, fail. 108 llvm::StringRef pdb_file; 109 if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) { 110 consumeError(std::move(e)); 111 return nullptr; 112 } 113 114 // If the file doesn't exist, perhaps the path specified at build time 115 // doesn't match the PDB's current location, so check the location of the 116 // executable. 117 if (!FileSystem::Instance().Exists(pdb_file)) { 118 const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent(); 119 const auto pdb_name = FileSpec(pdb_file).GetFilename().GetCString(); 120 pdb_file = exe_dir.CopyByAppendingPathComponent(pdb_name).GetCString(); 121 } 122 123 // If the file is not a PDB or if it doesn't have a matching GUID, fail. 124 auto pdb = ObjectFilePDB::loadPDBFile(std::string(pdb_file), allocator); 125 if (!pdb) 126 return nullptr; 127 128 auto expected_info = pdb->getPDBInfoStream(); 129 if (!expected_info) { 130 llvm::consumeError(expected_info.takeError()); 131 return nullptr; 132 } 133 llvm::codeview::GUID guid; 134 memcpy(&guid, pdb_info->PDB70.Signature, 16); 135 136 if (expected_info->getGuid() != guid) 137 return nullptr; 138 return pdb; 139 } 140 141 static bool IsFunctionPrologue(const CompilandIndexItem &cci, 142 lldb::addr_t addr) { 143 // FIXME: Implement this. 144 return false; 145 } 146 147 static bool IsFunctionEpilogue(const CompilandIndexItem &cci, 148 lldb::addr_t addr) { 149 // FIXME: Implement this. 150 return false; 151 } 152 153 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) { 154 switch (kind) { 155 case SimpleTypeKind::Boolean128: 156 case SimpleTypeKind::Boolean16: 157 case SimpleTypeKind::Boolean32: 158 case SimpleTypeKind::Boolean64: 159 case SimpleTypeKind::Boolean8: 160 return "bool"; 161 case SimpleTypeKind::Byte: 162 case SimpleTypeKind::UnsignedCharacter: 163 return "unsigned char"; 164 case SimpleTypeKind::NarrowCharacter: 165 return "char"; 166 case SimpleTypeKind::SignedCharacter: 167 case SimpleTypeKind::SByte: 168 return "signed char"; 169 case SimpleTypeKind::Character16: 170 return "char16_t"; 171 case SimpleTypeKind::Character32: 172 return "char32_t"; 173 case SimpleTypeKind::Complex80: 174 case SimpleTypeKind::Complex64: 175 case SimpleTypeKind::Complex32: 176 return "complex"; 177 case SimpleTypeKind::Float128: 178 case SimpleTypeKind::Float80: 179 return "long double"; 180 case SimpleTypeKind::Float64: 181 return "double"; 182 case SimpleTypeKind::Float32: 183 return "float"; 184 case SimpleTypeKind::Float16: 185 return "single"; 186 case SimpleTypeKind::Int128: 187 return "__int128"; 188 case SimpleTypeKind::Int64: 189 case SimpleTypeKind::Int64Quad: 190 return "int64_t"; 191 case SimpleTypeKind::Int32: 192 return "int"; 193 case SimpleTypeKind::Int16: 194 return "short"; 195 case SimpleTypeKind::UInt128: 196 return "unsigned __int128"; 197 case SimpleTypeKind::UInt64: 198 case SimpleTypeKind::UInt64Quad: 199 return "uint64_t"; 200 case SimpleTypeKind::HResult: 201 return "HRESULT"; 202 case SimpleTypeKind::UInt32: 203 return "unsigned"; 204 case SimpleTypeKind::UInt16: 205 case SimpleTypeKind::UInt16Short: 206 return "unsigned short"; 207 case SimpleTypeKind::Int32Long: 208 return "long"; 209 case SimpleTypeKind::UInt32Long: 210 return "unsigned long"; 211 case SimpleTypeKind::Void: 212 return "void"; 213 case SimpleTypeKind::WideCharacter: 214 return "wchar_t"; 215 default: 216 return ""; 217 } 218 } 219 220 static bool IsClassRecord(TypeLeafKind kind) { 221 switch (kind) { 222 case LF_STRUCTURE: 223 case LF_CLASS: 224 case LF_INTERFACE: 225 return true; 226 default: 227 return false; 228 } 229 } 230 231 void SymbolFileNativePDB::Initialize() { 232 PluginManager::RegisterPlugin(GetPluginNameStatic(), 233 GetPluginDescriptionStatic(), CreateInstance, 234 DebuggerInitialize); 235 } 236 237 void SymbolFileNativePDB::Terminate() { 238 PluginManager::UnregisterPlugin(CreateInstance); 239 } 240 241 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {} 242 243 ConstString SymbolFileNativePDB::GetPluginNameStatic() { 244 static ConstString g_name("native-pdb"); 245 return g_name; 246 } 247 248 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() { 249 return "Microsoft PDB debug symbol cross-platform file reader."; 250 } 251 252 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) { 253 return new SymbolFileNativePDB(std::move(objfile_sp)); 254 } 255 256 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp) 257 : SymbolFile(std::move(objfile_sp)) {} 258 259 SymbolFileNativePDB::~SymbolFileNativePDB() {} 260 261 uint32_t SymbolFileNativePDB::CalculateAbilities() { 262 uint32_t abilities = 0; 263 if (!m_objfile_sp) 264 return 0; 265 266 if (!m_index) { 267 // Lazily load and match the PDB file, but only do this once. 268 PDBFile *pdb_file; 269 if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) { 270 pdb_file = &pdb->GetPDBFile(); 271 } else { 272 m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(), 273 m_allocator); 274 pdb_file = m_file_up.get(); 275 } 276 277 if (!pdb_file) 278 return 0; 279 280 auto expected_index = PdbIndex::create(pdb_file); 281 if (!expected_index) { 282 llvm::consumeError(expected_index.takeError()); 283 return 0; 284 } 285 m_index = std::move(*expected_index); 286 } 287 if (!m_index) 288 return 0; 289 290 // We don't especially have to be precise here. We only distinguish between 291 // stripped and not stripped. 292 abilities = kAllAbilities; 293 294 if (m_index->dbi().isStripped()) 295 abilities &= ~(Blocks | LocalVariables); 296 return abilities; 297 } 298 299 void SymbolFileNativePDB::InitializeObject() { 300 m_obj_load_address = m_objfile_sp->GetModule() 301 ->GetObjectFile() 302 ->GetBaseAddress() 303 .GetFileAddress(); 304 m_index->SetLoadAddress(m_obj_load_address); 305 m_index->ParseSectionContribs(); 306 307 auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage( 308 lldb::eLanguageTypeC_plus_plus); 309 if (auto err = ts_or_err.takeError()) { 310 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 311 std::move(err), "Failed to initialize"); 312 } else { 313 ts_or_err->SetSymbolFile(this); 314 auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get()); 315 lldbassert(clang); 316 m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang); 317 } 318 } 319 320 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() { 321 const DbiModuleList &modules = m_index->dbi().modules(); 322 uint32_t count = modules.getModuleCount(); 323 if (count == 0) 324 return count; 325 326 // The linker can inject an additional "dummy" compilation unit into the 327 // PDB. Ignore this special compile unit for our purposes, if it is there. 328 // It is always the last one. 329 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1); 330 if (last.getModuleName() == "* Linker *") 331 --count; 332 return count; 333 } 334 335 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) { 336 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi); 337 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset); 338 339 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) { 340 // This is a function. It must be global. Creating the Function entry for 341 // it automatically creates a block for it. 342 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii); 343 return GetOrCreateFunction(block_id, *comp_unit)->GetBlock(false); 344 } 345 346 lldbassert(sym.kind() == S_BLOCK32); 347 348 // This is a block. Its parent is either a function or another block. In 349 // either case, its parent can be viewed as a block (e.g. a function contains 350 // 1 big block. So just get the parent block and add this block to it. 351 BlockSym block(static_cast<SymbolRecordKind>(sym.kind())); 352 cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block)); 353 lldbassert(block.Parent != 0); 354 PdbCompilandSymId parent_id(block_id.modi, block.Parent); 355 Block &parent_block = GetOrCreateBlock(parent_id); 356 lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id); 357 BlockSP child_block = std::make_shared<Block>(opaque_block_uid); 358 parent_block.AddChild(child_block); 359 360 m_ast->GetOrCreateBlockDecl(block_id); 361 362 m_blocks.insert({opaque_block_uid, child_block}); 363 return *child_block; 364 } 365 366 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id, 367 CompileUnit &comp_unit) { 368 const CompilandIndexItem *cci = 369 m_index->compilands().GetCompiland(func_id.modi); 370 lldbassert(cci); 371 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset); 372 373 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32); 374 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record); 375 376 auto file_vm_addr = m_index->MakeVirtualAddress(sol.so); 377 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 378 return nullptr; 379 380 AddressRange func_range(file_vm_addr, sol.length, 381 comp_unit.GetModule()->GetSectionList()); 382 if (!func_range.GetBaseAddress().IsValid()) 383 return nullptr; 384 385 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind())); 386 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)); 387 if (proc.FunctionType == TypeIndex::None()) 388 return nullptr; 389 TypeSP func_type = GetOrCreateType(proc.FunctionType); 390 if (!func_type) 391 return nullptr; 392 393 PdbTypeSymId sig_id(proc.FunctionType, false); 394 Mangled mangled(proc.Name); 395 FunctionSP func_sp = std::make_shared<Function>( 396 &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled, 397 func_type.get(), func_range); 398 399 comp_unit.AddFunction(func_sp); 400 401 m_ast->GetOrCreateFunctionDecl(func_id); 402 403 return func_sp; 404 } 405 406 CompUnitSP 407 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) { 408 lldb::LanguageType lang = 409 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage()) 410 : lldb::eLanguageTypeUnknown; 411 412 LazyBool optimized = eLazyBoolNo; 413 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations()) 414 optimized = eLazyBoolYes; 415 416 llvm::SmallString<64> source_file_name = 417 m_index->compilands().GetMainSourceFile(cci); 418 FileSpec fs(source_file_name); 419 420 CompUnitSP cu_sp = 421 std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs, 422 toOpaqueUid(cci.m_id), lang, optimized); 423 424 SetCompileUnitAtIndex(cci.m_id.modi, cu_sp); 425 return cu_sp; 426 } 427 428 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id, 429 const ModifierRecord &mr, 430 CompilerType ct) { 431 TpiStream &stream = m_index->tpi(); 432 433 std::string name; 434 if (mr.ModifiedType.isSimple()) 435 name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind())); 436 else 437 name = computeTypeName(stream.typeCollection(), mr.ModifiedType); 438 Declaration decl; 439 lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType); 440 441 return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name), 442 modified_type->GetByteSize(nullptr), nullptr, 443 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 444 ct, Type::ResolveState::Full); 445 } 446 447 lldb::TypeSP 448 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id, 449 const llvm::codeview::PointerRecord &pr, 450 CompilerType ct) { 451 TypeSP pointee = GetOrCreateType(pr.ReferentType); 452 if (!pointee) 453 return nullptr; 454 455 if (pr.isPointerToMember()) { 456 MemberPointerInfo mpi = pr.getMemberInfo(); 457 GetOrCreateType(mpi.ContainingType); 458 } 459 460 Declaration decl; 461 return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(), 462 pr.getSize(), nullptr, LLDB_INVALID_UID, 463 Type::eEncodingIsUID, decl, ct, 464 Type::ResolveState::Full); 465 } 466 467 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti, 468 CompilerType ct) { 469 uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false)); 470 if (ti == TypeIndex::NullptrT()) { 471 Declaration decl; 472 return std::make_shared<Type>( 473 uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID, 474 Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full); 475 } 476 477 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 478 TypeSP direct_sp = GetOrCreateType(ti.makeDirect()); 479 uint32_t pointer_size = 0; 480 switch (ti.getSimpleMode()) { 481 case SimpleTypeMode::FarPointer32: 482 case SimpleTypeMode::NearPointer32: 483 pointer_size = 4; 484 break; 485 case SimpleTypeMode::NearPointer64: 486 pointer_size = 8; 487 break; 488 default: 489 // 128-bit and 16-bit pointers unsupported. 490 return nullptr; 491 } 492 Declaration decl; 493 return std::make_shared<Type>( 494 uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID, 495 Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full); 496 } 497 498 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 499 return nullptr; 500 501 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind()); 502 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind()); 503 504 Declaration decl; 505 return std::make_shared<Type>(uid, this, ConstString(type_name), size, 506 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, 507 decl, ct, Type::ResolveState::Full); 508 } 509 510 static std::string GetUnqualifiedTypeName(const TagRecord &record) { 511 if (!record.hasUniqueName()) { 512 MSVCUndecoratedNameParser parser(record.Name); 513 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); 514 515 return std::string(specs.back().GetBaseName()); 516 } 517 518 llvm::ms_demangle::Demangler demangler; 519 StringView sv(record.UniqueName.begin(), record.UniqueName.size()); 520 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); 521 if (demangler.Error) 522 return std::string(record.Name); 523 524 llvm::ms_demangle::IdentifierNode *idn = 525 ttn->QualifiedName->getUnqualifiedIdentifier(); 526 return idn->toString(); 527 } 528 529 lldb::TypeSP 530 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id, 531 const TagRecord &record, 532 size_t size, CompilerType ct) { 533 534 std::string uname = GetUnqualifiedTypeName(record); 535 536 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE. 537 Declaration decl; 538 return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname), 539 size, nullptr, LLDB_INVALID_UID, 540 Type::eEncodingIsUID, decl, ct, 541 Type::ResolveState::Forward); 542 } 543 544 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 545 const ClassRecord &cr, 546 CompilerType ct) { 547 return CreateClassStructUnion(type_id, cr, cr.getSize(), ct); 548 } 549 550 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 551 const UnionRecord &ur, 552 CompilerType ct) { 553 return CreateClassStructUnion(type_id, ur, ur.getSize(), ct); 554 } 555 556 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 557 const EnumRecord &er, 558 CompilerType ct) { 559 std::string uname = GetUnqualifiedTypeName(er); 560 561 Declaration decl; 562 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType); 563 564 return std::make_shared<lldb_private::Type>( 565 toOpaqueUid(type_id), this, ConstString(uname), 566 underlying_type->GetByteSize(nullptr), nullptr, LLDB_INVALID_UID, 567 lldb_private::Type::eEncodingIsUID, decl, ct, 568 lldb_private::Type::ResolveState::Forward); 569 } 570 571 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id, 572 const ArrayRecord &ar, 573 CompilerType ct) { 574 TypeSP element_type = GetOrCreateType(ar.ElementType); 575 576 Declaration decl; 577 TypeSP array_sp = std::make_shared<lldb_private::Type>( 578 toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr, 579 LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct, 580 lldb_private::Type::ResolveState::Full); 581 array_sp->SetEncodingType(element_type.get()); 582 return array_sp; 583 } 584 585 586 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id, 587 const MemberFunctionRecord &mfr, 588 CompilerType ct) { 589 Declaration decl; 590 return std::make_shared<lldb_private::Type>( 591 toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID, 592 lldb_private::Type::eEncodingIsUID, decl, ct, 593 lldb_private::Type::ResolveState::Full); 594 } 595 596 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id, 597 const ProcedureRecord &pr, 598 CompilerType ct) { 599 Declaration decl; 600 return std::make_shared<lldb_private::Type>( 601 toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID, 602 lldb_private::Type::eEncodingIsUID, decl, ct, 603 lldb_private::Type::ResolveState::Full); 604 } 605 606 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) { 607 if (type_id.index.isSimple()) 608 return CreateSimpleType(type_id.index, ct); 609 610 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi(); 611 CVType cvt = stream.getType(type_id.index); 612 613 if (cvt.kind() == LF_MODIFIER) { 614 ModifierRecord modifier; 615 llvm::cantFail( 616 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 617 return CreateModifierType(type_id, modifier, ct); 618 } 619 620 if (cvt.kind() == LF_POINTER) { 621 PointerRecord pointer; 622 llvm::cantFail( 623 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 624 return CreatePointerType(type_id, pointer, ct); 625 } 626 627 if (IsClassRecord(cvt.kind())) { 628 ClassRecord cr; 629 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr)); 630 return CreateTagType(type_id, cr, ct); 631 } 632 633 if (cvt.kind() == LF_ENUM) { 634 EnumRecord er; 635 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)); 636 return CreateTagType(type_id, er, ct); 637 } 638 639 if (cvt.kind() == LF_UNION) { 640 UnionRecord ur; 641 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur)); 642 return CreateTagType(type_id, ur, ct); 643 } 644 645 if (cvt.kind() == LF_ARRAY) { 646 ArrayRecord ar; 647 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 648 return CreateArrayType(type_id, ar, ct); 649 } 650 651 if (cvt.kind() == LF_PROCEDURE) { 652 ProcedureRecord pr; 653 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 654 return CreateProcedureType(type_id, pr, ct); 655 } 656 if (cvt.kind() == LF_MFUNCTION) { 657 MemberFunctionRecord mfr; 658 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); 659 return CreateFunctionType(type_id, mfr, ct); 660 } 661 662 return nullptr; 663 } 664 665 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) { 666 // If they search for a UDT which is a forward ref, try and resolve the full 667 // decl and just map the forward ref uid to the full decl record. 668 llvm::Optional<PdbTypeSymId> full_decl_uid; 669 if (IsForwardRefUdt(type_id, m_index->tpi())) { 670 auto expected_full_ti = 671 m_index->tpi().findFullDeclForForwardRef(type_id.index); 672 if (!expected_full_ti) 673 llvm::consumeError(expected_full_ti.takeError()); 674 else if (*expected_full_ti != type_id.index) { 675 full_decl_uid = PdbTypeSymId(*expected_full_ti, false); 676 677 // It's possible that a lookup would occur for the full decl causing it 678 // to be cached, then a second lookup would occur for the forward decl. 679 // We don't want to create a second full decl, so make sure the full 680 // decl hasn't already been cached. 681 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid)); 682 if (full_iter != m_types.end()) { 683 TypeSP result = full_iter->second; 684 // Map the forward decl to the TypeSP for the full decl so we can take 685 // the fast path next time. 686 m_types[toOpaqueUid(type_id)] = result; 687 return result; 688 } 689 } 690 } 691 692 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id; 693 694 clang::QualType qt = m_ast->GetOrCreateType(best_decl_id); 695 696 TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt)); 697 if (!result) 698 return nullptr; 699 700 uint64_t best_uid = toOpaqueUid(best_decl_id); 701 m_types[best_uid] = result; 702 // If we had both a forward decl and a full decl, make both point to the new 703 // type. 704 if (full_decl_uid) 705 m_types[toOpaqueUid(type_id)] = result; 706 707 return result; 708 } 709 710 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) { 711 // We can't use try_emplace / overwrite here because the process of creating 712 // a type could create nested types, which could invalidate iterators. So 713 // we have to do a 2-phase lookup / insert. 714 auto iter = m_types.find(toOpaqueUid(type_id)); 715 if (iter != m_types.end()) 716 return iter->second; 717 718 TypeSP type = CreateAndCacheType(type_id); 719 if (type) 720 GetTypeList().Insert(type); 721 return type; 722 } 723 724 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) { 725 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset); 726 if (sym.kind() == S_CONSTANT) 727 return CreateConstantSymbol(var_id, sym); 728 729 lldb::ValueType scope = eValueTypeInvalid; 730 TypeIndex ti; 731 llvm::StringRef name; 732 lldb::addr_t addr = 0; 733 uint16_t section = 0; 734 uint32_t offset = 0; 735 bool is_external = false; 736 switch (sym.kind()) { 737 case S_GDATA32: 738 is_external = true; 739 LLVM_FALLTHROUGH; 740 case S_LDATA32: { 741 DataSym ds(sym.kind()); 742 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds)); 743 ti = ds.Type; 744 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal 745 : eValueTypeVariableStatic; 746 name = ds.Name; 747 section = ds.Segment; 748 offset = ds.DataOffset; 749 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset); 750 break; 751 } 752 case S_GTHREAD32: 753 is_external = true; 754 LLVM_FALLTHROUGH; 755 case S_LTHREAD32: { 756 ThreadLocalDataSym tlds(sym.kind()); 757 llvm::cantFail( 758 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)); 759 ti = tlds.Type; 760 name = tlds.Name; 761 section = tlds.Segment; 762 offset = tlds.DataOffset; 763 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset); 764 scope = eValueTypeVariableThreadLocal; 765 break; 766 } 767 default: 768 llvm_unreachable("unreachable!"); 769 } 770 771 CompUnitSP comp_unit; 772 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr); 773 if (modi) { 774 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi); 775 comp_unit = GetOrCreateCompileUnit(cci); 776 } 777 778 Declaration decl; 779 PdbTypeSymId tid(ti, false); 780 SymbolFileTypeSP type_sp = 781 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 782 Variable::RangeList ranges; 783 784 m_ast->GetOrCreateVariableDecl(var_id); 785 786 DWARFExpression location = MakeGlobalLocationExpression( 787 section, offset, GetObjectFile()->GetModule()); 788 789 std::string global_name("::"); 790 global_name += name; 791 bool artificial = false; 792 bool location_is_constant_data = false; 793 bool static_member = false; 794 VariableSP var_sp = std::make_shared<Variable>( 795 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp, 796 scope, comp_unit.get(), ranges, &decl, location, is_external, artificial, 797 location_is_constant_data, static_member); 798 799 return var_sp; 800 } 801 802 lldb::VariableSP 803 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id, 804 const CVSymbol &cvs) { 805 TpiStream &tpi = m_index->tpi(); 806 ConstantSym constant(cvs.kind()); 807 808 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)); 809 std::string global_name("::"); 810 global_name += constant.Name; 811 PdbTypeSymId tid(constant.Type, false); 812 SymbolFileTypeSP type_sp = 813 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 814 815 Declaration decl; 816 Variable::RangeList ranges; 817 ModuleSP module = GetObjectFile()->GetModule(); 818 DWARFExpression location = MakeConstantLocationExpression( 819 constant.Type, tpi, constant.Value, module); 820 821 bool external = false; 822 bool artificial = false; 823 bool location_is_constant_data = true; 824 bool static_member = false; 825 VariableSP var_sp = std::make_shared<Variable>( 826 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(), 827 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location, 828 external, artificial, location_is_constant_data, static_member); 829 return var_sp; 830 } 831 832 VariableSP 833 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) { 834 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr); 835 if (emplace_result.second) 836 emplace_result.first->second = CreateGlobalVariable(var_id); 837 838 return emplace_result.first->second; 839 } 840 841 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) { 842 return GetOrCreateType(PdbTypeSymId(ti, false)); 843 } 844 845 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id, 846 CompileUnit &comp_unit) { 847 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr); 848 if (emplace_result.second) 849 emplace_result.first->second = CreateFunction(func_id, comp_unit); 850 851 return emplace_result.first->second; 852 } 853 854 CompUnitSP 855 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) { 856 857 auto emplace_result = 858 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr); 859 if (emplace_result.second) 860 emplace_result.first->second = CreateCompileUnit(cci); 861 862 lldbassert(emplace_result.first->second); 863 return emplace_result.first->second; 864 } 865 866 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) { 867 auto iter = m_blocks.find(toOpaqueUid(block_id)); 868 if (iter != m_blocks.end()) 869 return *iter->second; 870 871 return CreateBlock(block_id); 872 } 873 874 void SymbolFileNativePDB::ParseDeclsForContext( 875 lldb_private::CompilerDeclContext decl_ctx) { 876 clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx); 877 if (!context) 878 return; 879 m_ast->ParseDeclsForContext(*context); 880 } 881 882 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) { 883 if (index >= GetNumCompileUnits()) 884 return CompUnitSP(); 885 lldbassert(index < UINT16_MAX); 886 if (index >= UINT16_MAX) 887 return nullptr; 888 889 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index); 890 891 return GetOrCreateCompileUnit(item); 892 } 893 894 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) { 895 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 896 PdbSymUid uid(comp_unit.GetID()); 897 lldbassert(uid.kind() == PdbSymUidKind::Compiland); 898 899 CompilandIndexItem *item = 900 m_index->compilands().GetCompiland(uid.asCompiland().modi); 901 lldbassert(item); 902 if (!item->m_compile_opts) 903 return lldb::eLanguageTypeUnknown; 904 905 return TranslateLanguage(item->m_compile_opts->getLanguage()); 906 } 907 908 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) { return; } 909 910 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) { 911 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 912 PdbSymUid uid{comp_unit.GetID()}; 913 lldbassert(uid.kind() == PdbSymUidKind::Compiland); 914 uint16_t modi = uid.asCompiland().modi; 915 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi); 916 917 size_t count = comp_unit.GetNumFunctions(); 918 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray(); 919 for (auto iter = syms.begin(); iter != syms.end(); ++iter) { 920 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) 921 continue; 922 923 PdbCompilandSymId sym_id{modi, iter.offset()}; 924 925 FunctionSP func = GetOrCreateFunction(sym_id, comp_unit); 926 } 927 928 size_t new_count = comp_unit.GetNumFunctions(); 929 lldbassert(new_count >= count); 930 return new_count - count; 931 } 932 933 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) { 934 // If any of these flags are set, we need to resolve the compile unit. 935 uint32_t flags = eSymbolContextCompUnit; 936 flags |= eSymbolContextVariable; 937 flags |= eSymbolContextFunction; 938 flags |= eSymbolContextBlock; 939 flags |= eSymbolContextLineEntry; 940 return (resolve_scope & flags) != 0; 941 } 942 943 uint32_t SymbolFileNativePDB::ResolveSymbolContext( 944 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) { 945 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 946 uint32_t resolved_flags = 0; 947 lldb::addr_t file_addr = addr.GetFileAddress(); 948 949 if (NeedsResolvedCompileUnit(resolve_scope)) { 950 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr); 951 if (!modi) 952 return 0; 953 CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi); 954 if (!cci) 955 return 0; 956 957 sc.comp_unit = GetOrCreateCompileUnit(*cci).get(); 958 resolved_flags |= eSymbolContextCompUnit; 959 } 960 961 if (resolve_scope & eSymbolContextFunction || 962 resolve_scope & eSymbolContextBlock) { 963 lldbassert(sc.comp_unit); 964 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr); 965 // Search the matches in reverse. This way if there are multiple matches 966 // (for example we are 3 levels deep in a nested scope) it will find the 967 // innermost one first. 968 for (const auto &match : llvm::reverse(matches)) { 969 if (match.uid.kind() != PdbSymUidKind::CompilandSym) 970 continue; 971 972 PdbCompilandSymId csid = match.uid.asCompilandSym(); 973 CVSymbol cvs = m_index->ReadSymbolRecord(csid); 974 PDB_SymType type = CVSymToPDBSym(cvs.kind()); 975 if (type != PDB_SymType::Function && type != PDB_SymType::Block) 976 continue; 977 if (type == PDB_SymType::Function) { 978 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get(); 979 sc.block = sc.GetFunctionBlock(); 980 } 981 982 if (type == PDB_SymType::Block) { 983 sc.block = &GetOrCreateBlock(csid); 984 sc.function = sc.block->CalculateSymbolContextFunction(); 985 } 986 resolved_flags |= eSymbolContextFunction; 987 resolved_flags |= eSymbolContextBlock; 988 break; 989 } 990 } 991 992 if (resolve_scope & eSymbolContextLineEntry) { 993 lldbassert(sc.comp_unit); 994 if (auto *line_table = sc.comp_unit->GetLineTable()) { 995 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 996 resolved_flags |= eSymbolContextLineEntry; 997 } 998 } 999 1000 return resolved_flags; 1001 } 1002 1003 uint32_t SymbolFileNativePDB::ResolveSymbolContext( 1004 const FileSpec &file_spec, uint32_t line, bool check_inlines, 1005 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) { 1006 return 0; 1007 } 1008 1009 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence, 1010 const CompilandIndexItem &cci, 1011 lldb::addr_t base_addr, 1012 uint32_t file_number, 1013 const LineFragmentHeader &block, 1014 const LineNumberEntry &cur) { 1015 LineInfo cur_info(cur.Flags); 1016 1017 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto()) 1018 return; 1019 1020 uint64_t addr = base_addr + cur.Offset; 1021 1022 bool is_statement = cur_info.isStatement(); 1023 bool is_prologue = IsFunctionPrologue(cci, addr); 1024 bool is_epilogue = IsFunctionEpilogue(cci, addr); 1025 1026 uint32_t lno = cur_info.getStartLine(); 1027 1028 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number, 1029 is_statement, false, is_prologue, is_epilogue, 1030 false); 1031 } 1032 1033 static void TerminateLineSequence(LineTable &table, 1034 const LineFragmentHeader &block, 1035 lldb::addr_t base_addr, uint32_t file_number, 1036 uint32_t last_line, 1037 std::unique_ptr<LineSequence> seq) { 1038 // The end is always a terminal entry, so insert it regardless. 1039 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize, 1040 last_line, 0, file_number, false, false, 1041 false, false, true); 1042 table.InsertSequence(seq.release()); 1043 } 1044 1045 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) { 1046 // Unfortunately LLDB is set up to parse the entire compile unit line table 1047 // all at once, even if all it really needs is line info for a specific 1048 // function. In the future it would be nice if it could set the sc.m_function 1049 // member, and we could only get the line info for the function in question. 1050 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1051 PdbSymUid cu_id(comp_unit.GetID()); 1052 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1053 CompilandIndexItem *cci = 1054 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1055 lldbassert(cci); 1056 auto line_table = std::make_unique<LineTable>(&comp_unit); 1057 1058 // This is basically a copy of the .debug$S subsections from all original COFF 1059 // object files merged together with address relocations applied. We are 1060 // looking for all DEBUG_S_LINES subsections. 1061 for (const DebugSubsectionRecord &dssr : 1062 cci->m_debug_stream.getSubsectionsArray()) { 1063 if (dssr.kind() != DebugSubsectionKind::Lines) 1064 continue; 1065 1066 DebugLinesSubsectionRef lines; 1067 llvm::BinaryStreamReader reader(dssr.getRecordData()); 1068 if (auto EC = lines.initialize(reader)) { 1069 llvm::consumeError(std::move(EC)); 1070 return false; 1071 } 1072 1073 const LineFragmentHeader *lfh = lines.header(); 1074 uint64_t virtual_addr = 1075 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset); 1076 1077 const auto &checksums = cci->m_strings.checksums().getArray(); 1078 const auto &strings = cci->m_strings.strings(); 1079 for (const LineColumnEntry &group : lines) { 1080 // Indices in this structure are actually offsets of records in the 1081 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index 1082 // into the global PDB string table. 1083 auto iter = checksums.at(group.NameIndex); 1084 if (iter == checksums.end()) 1085 continue; 1086 1087 llvm::Expected<llvm::StringRef> efn = 1088 strings.getString(iter->FileNameOffset); 1089 if (!efn) { 1090 llvm::consumeError(efn.takeError()); 1091 continue; 1092 } 1093 1094 // LLDB wants the index of the file in the list of support files. 1095 auto fn_iter = llvm::find(cci->m_file_list, *efn); 1096 lldbassert(fn_iter != cci->m_file_list.end()); 1097 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter); 1098 1099 std::unique_ptr<LineSequence> sequence( 1100 line_table->CreateLineSequenceContainer()); 1101 lldbassert(!group.LineNumbers.empty()); 1102 1103 for (const LineNumberEntry &entry : group.LineNumbers) { 1104 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr, 1105 file_index, *lfh, entry); 1106 } 1107 LineInfo last_line(group.LineNumbers.back().Flags); 1108 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index, 1109 last_line.getEndLine(), std::move(sequence)); 1110 } 1111 } 1112 1113 if (line_table->GetSize() == 0) 1114 return false; 1115 1116 comp_unit.SetLineTable(line_table.release()); 1117 return true; 1118 } 1119 1120 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) { 1121 // PDB doesn't contain information about macros 1122 return false; 1123 } 1124 1125 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit, 1126 FileSpecList &support_files) { 1127 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1128 PdbSymUid cu_id(comp_unit.GetID()); 1129 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1130 CompilandIndexItem *cci = 1131 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1132 lldbassert(cci); 1133 1134 for (llvm::StringRef f : cci->m_file_list) { 1135 FileSpec::Style style = 1136 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows; 1137 FileSpec spec(f, style); 1138 support_files.Append(spec); 1139 } 1140 return true; 1141 } 1142 1143 bool SymbolFileNativePDB::ParseImportedModules( 1144 const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { 1145 // PDB does not yet support module debug info 1146 return false; 1147 } 1148 1149 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) { 1150 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1151 GetOrCreateBlock(PdbSymUid(func.GetID()).asCompilandSym()); 1152 // FIXME: Parse child blocks 1153 return 1; 1154 } 1155 1156 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); } 1157 1158 void SymbolFileNativePDB::FindGlobalVariables( 1159 ConstString name, const CompilerDeclContext &parent_decl_ctx, 1160 uint32_t max_matches, VariableList &variables) { 1161 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1162 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1163 1164 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName( 1165 name.GetStringRef(), m_index->symrecords()); 1166 for (const SymbolAndOffset &result : results) { 1167 VariableSP var; 1168 switch (result.second.kind()) { 1169 case SymbolKind::S_GDATA32: 1170 case SymbolKind::S_LDATA32: 1171 case SymbolKind::S_GTHREAD32: 1172 case SymbolKind::S_LTHREAD32: 1173 case SymbolKind::S_CONSTANT: { 1174 PdbGlobalSymId global(result.first, false); 1175 var = GetOrCreateGlobalVariable(global); 1176 variables.AddVariable(var); 1177 break; 1178 } 1179 default: 1180 continue; 1181 } 1182 } 1183 } 1184 1185 void SymbolFileNativePDB::FindFunctions( 1186 ConstString name, const CompilerDeclContext &parent_decl_ctx, 1187 FunctionNameType name_type_mask, bool include_inlines, 1188 SymbolContextList &sc_list) { 1189 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1190 // For now we only support lookup by method name. 1191 if (!(name_type_mask & eFunctionNameTypeMethod)) 1192 return; 1193 1194 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1195 1196 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName( 1197 name.GetStringRef(), m_index->symrecords()); 1198 for (const SymbolAndOffset &match : matches) { 1199 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF) 1200 continue; 1201 ProcRefSym proc(match.second.kind()); 1202 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc)); 1203 1204 if (!IsValidRecord(proc)) 1205 continue; 1206 1207 CompilandIndexItem &cci = 1208 m_index->compilands().GetOrCreateCompiland(proc.modi()); 1209 SymbolContext sc; 1210 1211 sc.comp_unit = GetOrCreateCompileUnit(cci).get(); 1212 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset); 1213 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get(); 1214 1215 sc_list.Append(sc); 1216 } 1217 } 1218 1219 void SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex, 1220 bool include_inlines, 1221 SymbolContextList &sc_list) {} 1222 1223 void SymbolFileNativePDB::FindTypes( 1224 ConstString name, const CompilerDeclContext &parent_decl_ctx, 1225 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, 1226 TypeMap &types) { 1227 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1228 if (!name) 1229 return; 1230 1231 searched_symbol_files.clear(); 1232 searched_symbol_files.insert(this); 1233 1234 // There is an assumption 'name' is not a regex 1235 FindTypesByName(name.GetStringRef(), max_matches, types); 1236 } 1237 1238 void SymbolFileNativePDB::FindTypes( 1239 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, 1240 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {} 1241 1242 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name, 1243 uint32_t max_matches, 1244 TypeMap &types) { 1245 1246 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name); 1247 if (max_matches > 0 && max_matches < matches.size()) 1248 matches.resize(max_matches); 1249 1250 for (TypeIndex ti : matches) { 1251 TypeSP type = GetOrCreateType(ti); 1252 if (!type) 1253 continue; 1254 1255 types.Insert(type); 1256 } 1257 } 1258 1259 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) { 1260 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1261 // Only do the full type scan the first time. 1262 if (m_done_full_type_scan) 1263 return 0; 1264 1265 const size_t old_count = GetTypeList().GetSize(); 1266 LazyRandomTypeCollection &types = m_index->tpi().typeCollection(); 1267 1268 // First process the entire TPI stream. 1269 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { 1270 TypeSP type = GetOrCreateType(*ti); 1271 if (type) 1272 (void)type->GetFullCompilerType(); 1273 } 1274 1275 // Next look for S_UDT records in the globals stream. 1276 for (const uint32_t gid : m_index->globals().getGlobalsTable()) { 1277 PdbGlobalSymId global{gid, false}; 1278 CVSymbol sym = m_index->ReadSymbolRecord(global); 1279 if (sym.kind() != S_UDT) 1280 continue; 1281 1282 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 1283 bool is_typedef = true; 1284 if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) { 1285 CVType cvt = m_index->tpi().getType(udt.Type); 1286 llvm::StringRef name = CVTagRecord::create(cvt).name(); 1287 if (name == udt.Name) 1288 is_typedef = false; 1289 } 1290 1291 if (is_typedef) 1292 GetOrCreateTypedef(global); 1293 } 1294 1295 const size_t new_count = GetTypeList().GetSize(); 1296 1297 m_done_full_type_scan = true; 1298 1299 return new_count - old_count; 1300 } 1301 1302 size_t 1303 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit, 1304 VariableList &variables) { 1305 PdbSymUid sym_uid(comp_unit.GetID()); 1306 lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland); 1307 return 0; 1308 } 1309 1310 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id, 1311 PdbCompilandSymId var_id, 1312 bool is_param) { 1313 ModuleSP module = GetObjectFile()->GetModule(); 1314 Block &block = GetOrCreateBlock(scope_id); 1315 VariableInfo var_info = 1316 GetVariableLocationInfo(*m_index, var_id, block, module); 1317 if (!var_info.location || !var_info.ranges) 1318 return nullptr; 1319 1320 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi); 1321 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii); 1322 TypeSP type_sp = GetOrCreateType(var_info.type); 1323 std::string name = var_info.name.str(); 1324 Declaration decl; 1325 SymbolFileTypeSP sftype = 1326 std::make_shared<SymbolFileType>(*this, type_sp->GetID()); 1327 1328 ValueType var_scope = 1329 is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal; 1330 bool external = false; 1331 bool artificial = false; 1332 bool location_is_constant_data = false; 1333 bool static_member = false; 1334 VariableSP var_sp = std::make_shared<Variable>( 1335 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope, 1336 comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, external, 1337 artificial, location_is_constant_data, static_member); 1338 1339 if (!is_param) 1340 m_ast->GetOrCreateVariableDecl(scope_id, var_id); 1341 1342 m_local_variables[toOpaqueUid(var_id)] = var_sp; 1343 return var_sp; 1344 } 1345 1346 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable( 1347 PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) { 1348 auto iter = m_local_variables.find(toOpaqueUid(var_id)); 1349 if (iter != m_local_variables.end()) 1350 return iter->second; 1351 1352 return CreateLocalVariable(scope_id, var_id, is_param); 1353 } 1354 1355 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) { 1356 CVSymbol sym = m_index->ReadSymbolRecord(id); 1357 lldbassert(sym.kind() == SymbolKind::S_UDT); 1358 1359 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 1360 1361 TypeSP target_type = GetOrCreateType(udt.Type); 1362 1363 (void)m_ast->GetOrCreateTypedefDecl(id); 1364 1365 Declaration decl; 1366 return std::make_shared<lldb_private::Type>( 1367 toOpaqueUid(id), this, ConstString(udt.Name), 1368 target_type->GetByteSize(nullptr), nullptr, target_type->GetID(), 1369 lldb_private::Type::eEncodingIsTypedefUID, decl, 1370 target_type->GetForwardCompilerType(), 1371 lldb_private::Type::ResolveState::Forward); 1372 } 1373 1374 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) { 1375 auto iter = m_types.find(toOpaqueUid(id)); 1376 if (iter != m_types.end()) 1377 return iter->second; 1378 1379 return CreateTypedef(id); 1380 } 1381 1382 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) { 1383 Block &block = GetOrCreateBlock(block_id); 1384 1385 size_t count = 0; 1386 1387 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi); 1388 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset); 1389 uint32_t params_remaining = 0; 1390 switch (sym.kind()) { 1391 case S_GPROC32: 1392 case S_LPROC32: { 1393 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind())); 1394 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc)); 1395 CVType signature = m_index->tpi().getType(proc.FunctionType); 1396 ProcedureRecord sig; 1397 cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig)); 1398 params_remaining = sig.getParameterCount(); 1399 break; 1400 } 1401 case S_BLOCK32: 1402 break; 1403 default: 1404 lldbassert(false && "Symbol is not a block!"); 1405 return 0; 1406 } 1407 1408 VariableListSP variables = block.GetBlockVariableList(false); 1409 if (!variables) { 1410 variables = std::make_shared<VariableList>(); 1411 block.SetVariableList(variables); 1412 } 1413 1414 CVSymbolArray syms = limitSymbolArrayToScope( 1415 cii->m_debug_stream.getSymbolArray(), block_id.offset); 1416 1417 // Skip the first record since it's a PROC32 or BLOCK32, and there's 1418 // no point examining it since we know it's not a local variable. 1419 syms.drop_front(); 1420 auto iter = syms.begin(); 1421 auto end = syms.end(); 1422 1423 while (iter != end) { 1424 uint32_t record_offset = iter.offset(); 1425 CVSymbol variable_cvs = *iter; 1426 PdbCompilandSymId child_sym_id(block_id.modi, record_offset); 1427 ++iter; 1428 1429 // If this is a block, recurse into its children and then skip it. 1430 if (variable_cvs.kind() == S_BLOCK32) { 1431 uint32_t block_end = getScopeEndOffset(variable_cvs); 1432 count += ParseVariablesForBlock(child_sym_id); 1433 iter = syms.at(block_end); 1434 continue; 1435 } 1436 1437 bool is_param = params_remaining > 0; 1438 VariableSP variable; 1439 switch (variable_cvs.kind()) { 1440 case S_REGREL32: 1441 case S_REGISTER: 1442 case S_LOCAL: 1443 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param); 1444 if (is_param) 1445 --params_remaining; 1446 if (variable) 1447 variables->AddVariableIfUnique(variable); 1448 break; 1449 default: 1450 break; 1451 } 1452 } 1453 1454 // Pass false for set_children, since we call this recursively so that the 1455 // children will call this for themselves. 1456 block.SetDidParseVariables(true, false); 1457 1458 return count; 1459 } 1460 1461 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) { 1462 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1463 lldbassert(sc.function || sc.comp_unit); 1464 1465 VariableListSP variables; 1466 if (sc.block) { 1467 PdbSymUid block_id(sc.block->GetID()); 1468 1469 size_t count = ParseVariablesForBlock(block_id.asCompilandSym()); 1470 return count; 1471 } 1472 1473 if (sc.function) { 1474 PdbSymUid block_id(sc.function->GetID()); 1475 1476 size_t count = ParseVariablesForBlock(block_id.asCompilandSym()); 1477 return count; 1478 } 1479 1480 if (sc.comp_unit) { 1481 variables = sc.comp_unit->GetVariableList(false); 1482 if (!variables) { 1483 variables = std::make_shared<VariableList>(); 1484 sc.comp_unit->SetVariableList(variables); 1485 } 1486 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables); 1487 } 1488 1489 llvm_unreachable("Unreachable!"); 1490 } 1491 1492 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) { 1493 if (auto decl = m_ast->GetOrCreateDeclForUid(uid)) 1494 return decl.getValue(); 1495 else 1496 return CompilerDecl(); 1497 } 1498 1499 CompilerDeclContext 1500 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) { 1501 clang::DeclContext *context = 1502 m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid)); 1503 if (!context) 1504 return {}; 1505 1506 return m_ast->ToCompilerDeclContext(*context); 1507 } 1508 1509 CompilerDeclContext 1510 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) { 1511 clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid)); 1512 return m_ast->ToCompilerDeclContext(*context); 1513 } 1514 1515 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 1516 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1517 auto iter = m_types.find(type_uid); 1518 // lldb should not be passing us non-sensical type uids. the only way it 1519 // could have a type uid in the first place is if we handed it out, in which 1520 // case we should know about the type. However, that doesn't mean we've 1521 // instantiated it yet. We can vend out a UID for a future type. So if the 1522 // type doesn't exist, let's instantiate it now. 1523 if (iter != m_types.end()) 1524 return &*iter->second; 1525 1526 PdbSymUid uid(type_uid); 1527 lldbassert(uid.kind() == PdbSymUidKind::Type); 1528 PdbTypeSymId type_id = uid.asTypeSym(); 1529 if (type_id.index.isNoneType()) 1530 return nullptr; 1531 1532 TypeSP type_sp = CreateAndCacheType(type_id); 1533 return &*type_sp; 1534 } 1535 1536 llvm::Optional<SymbolFile::ArrayInfo> 1537 SymbolFileNativePDB::GetDynamicArrayInfoForUID( 1538 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 1539 return llvm::None; 1540 } 1541 1542 1543 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) { 1544 clang::QualType qt = 1545 clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType()); 1546 1547 return m_ast->CompleteType(qt); 1548 } 1549 1550 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1551 TypeClass type_mask, 1552 lldb_private::TypeList &type_list) {} 1553 1554 CompilerDeclContext 1555 SymbolFileNativePDB::FindNamespace(ConstString name, 1556 const CompilerDeclContext &parent_decl_ctx) { 1557 return {}; 1558 } 1559 1560 llvm::Expected<TypeSystem &> 1561 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1562 auto type_system_or_err = 1563 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); 1564 if (type_system_or_err) { 1565 type_system_or_err->SetSymbolFile(this); 1566 } 1567 return type_system_or_err; 1568 } 1569 1570 ConstString SymbolFileNativePDB::GetPluginName() { 1571 static ConstString g_name("pdb"); 1572 return g_name; 1573 } 1574 1575 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; } 1576