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