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