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