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