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