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 "lldb/Core/Module.h" 19 #include "lldb/Core/PluginManager.h" 20 #include "lldb/Core/StreamBuffer.h" 21 #include "lldb/Core/StreamFile.h" 22 #include "lldb/Symbol/ClangASTContext.h" 23 #include "lldb/Symbol/ClangASTImporter.h" 24 #include "lldb/Symbol/ClangExternalASTSourceCommon.h" 25 #include "lldb/Symbol/ClangUtil.h" 26 #include "lldb/Symbol/CompileUnit.h" 27 #include "lldb/Symbol/LineTable.h" 28 #include "lldb/Symbol/ObjectFile.h" 29 #include "lldb/Symbol/SymbolContext.h" 30 #include "lldb/Symbol/SymbolVendor.h" 31 #include "lldb/Symbol/Variable.h" 32 #include "lldb/Symbol/VariableList.h" 33 34 #include "llvm/DebugInfo/CodeView/CVRecord.h" 35 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 36 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h" 37 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" 38 #include "llvm/DebugInfo/CodeView/RecordName.h" 39 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 40 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" 41 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 42 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" 43 #include "llvm/DebugInfo/PDB/Native/InfoStream.h" 44 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h" 45 #include "llvm/DebugInfo/PDB/Native/PDBFile.h" 46 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" 47 #include "llvm/DebugInfo/PDB/Native/TpiStream.h" 48 #include "llvm/DebugInfo/PDB/PDBTypes.h" 49 #include "llvm/Demangle/MicrosoftDemangle.h" 50 #include "llvm/Object/COFF.h" 51 #include "llvm/Support/Allocator.h" 52 #include "llvm/Support/BinaryStreamReader.h" 53 #include "llvm/Support/Error.h" 54 #include "llvm/Support/ErrorOr.h" 55 #include "llvm/Support/MemoryBuffer.h" 56 57 #include "PdbSymUid.h" 58 #include "PdbUtil.h" 59 #include "UdtRecordCompleter.h" 60 61 using namespace lldb; 62 using namespace lldb_private; 63 using namespace npdb; 64 using namespace llvm::codeview; 65 using namespace llvm::pdb; 66 67 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) { 68 switch (lang) { 69 case PDB_Lang::Cpp: 70 return lldb::LanguageType::eLanguageTypeC_plus_plus; 71 case PDB_Lang::C: 72 return lldb::LanguageType::eLanguageTypeC; 73 default: 74 return lldb::LanguageType::eLanguageTypeUnknown; 75 } 76 } 77 78 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath, 79 llvm::BumpPtrAllocator &Allocator) { 80 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer = 81 llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1, 82 /*RequiresNullTerminator=*/false); 83 if (!ErrorOrBuffer) 84 return nullptr; 85 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer); 86 87 llvm::StringRef Path = Buffer->getBufferIdentifier(); 88 auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>( 89 std::move(Buffer), llvm::support::little); 90 91 auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator); 92 if (auto EC = File->parseFileHeaders()) { 93 llvm::consumeError(std::move(EC)); 94 return nullptr; 95 } 96 if (auto EC = File->parseStreamData()) { 97 llvm::consumeError(std::move(EC)); 98 return nullptr; 99 } 100 101 return File; 102 } 103 104 static std::unique_ptr<PDBFile> 105 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) { 106 // Try to find a matching PDB for an EXE. 107 using namespace llvm::object; 108 auto expected_binary = createBinary(exe_path); 109 110 // If the file isn't a PE/COFF executable, fail. 111 if (!expected_binary) { 112 llvm::consumeError(expected_binary.takeError()); 113 return nullptr; 114 } 115 OwningBinary<Binary> binary = std::move(*expected_binary); 116 117 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary()); 118 if (!obj) 119 return nullptr; 120 const llvm::codeview::DebugInfo *pdb_info = nullptr; 121 122 // If it doesn't have a debug directory, fail. 123 llvm::StringRef pdb_file; 124 auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file); 125 if (ec) 126 return nullptr; 127 128 // if the file doesn't exist, is not a pdb, or doesn't have a matching guid, 129 // fail. 130 llvm::file_magic magic; 131 ec = llvm::identify_magic(pdb_file, magic); 132 if (ec || magic != llvm::file_magic::pdb) 133 return nullptr; 134 std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator); 135 if (!pdb) 136 return nullptr; 137 138 auto expected_info = pdb->getPDBInfoStream(); 139 if (!expected_info) { 140 llvm::consumeError(expected_info.takeError()); 141 return nullptr; 142 } 143 llvm::codeview::GUID guid; 144 memcpy(&guid, pdb_info->PDB70.Signature, 16); 145 146 if (expected_info->getGuid() != guid) 147 return nullptr; 148 return pdb; 149 } 150 151 static bool IsFunctionPrologue(const CompilandIndexItem &cci, 152 lldb::addr_t addr) { 153 // FIXME: Implement this. 154 return false; 155 } 156 157 static bool IsFunctionEpilogue(const CompilandIndexItem &cci, 158 lldb::addr_t addr) { 159 // FIXME: Implement this. 160 return false; 161 } 162 163 static clang::MSInheritanceAttr::Spelling 164 GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) { 165 if (record.DerivationList == TypeIndex::None()) 166 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance; 167 168 CVType bases = tpi.getType(record.DerivationList); 169 ArgListRecord base_list; 170 cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list)); 171 if (base_list.ArgIndices.empty()) 172 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance; 173 174 int base_count = 0; 175 for (TypeIndex ti : base_list.ArgIndices) { 176 CVType base = tpi.getType(ti); 177 if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS) 178 return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance; 179 ++base_count; 180 } 181 182 if (base_count > 1) 183 return clang::MSInheritanceAttr::Keyword_multiple_inheritance; 184 return clang::MSInheritanceAttr::Keyword_single_inheritance; 185 } 186 187 static lldb::BasicType GetCompilerTypeForSimpleKind(SimpleTypeKind kind) { 188 switch (kind) { 189 case SimpleTypeKind::Boolean128: 190 case SimpleTypeKind::Boolean16: 191 case SimpleTypeKind::Boolean32: 192 case SimpleTypeKind::Boolean64: 193 case SimpleTypeKind::Boolean8: 194 return lldb::eBasicTypeBool; 195 case SimpleTypeKind::Byte: 196 case SimpleTypeKind::UnsignedCharacter: 197 return lldb::eBasicTypeUnsignedChar; 198 case SimpleTypeKind::NarrowCharacter: 199 return lldb::eBasicTypeChar; 200 case SimpleTypeKind::SignedCharacter: 201 case SimpleTypeKind::SByte: 202 return lldb::eBasicTypeSignedChar; 203 case SimpleTypeKind::Character16: 204 return lldb::eBasicTypeChar16; 205 case SimpleTypeKind::Character32: 206 return lldb::eBasicTypeChar32; 207 case SimpleTypeKind::Complex80: 208 return lldb::eBasicTypeLongDoubleComplex; 209 case SimpleTypeKind::Complex64: 210 return lldb::eBasicTypeDoubleComplex; 211 case SimpleTypeKind::Complex32: 212 return lldb::eBasicTypeFloatComplex; 213 case SimpleTypeKind::Float128: 214 case SimpleTypeKind::Float80: 215 return lldb::eBasicTypeLongDouble; 216 case SimpleTypeKind::Float64: 217 return lldb::eBasicTypeDouble; 218 case SimpleTypeKind::Float32: 219 return lldb::eBasicTypeFloat; 220 case SimpleTypeKind::Float16: 221 return lldb::eBasicTypeHalf; 222 case SimpleTypeKind::Int128: 223 return lldb::eBasicTypeInt128; 224 case SimpleTypeKind::Int64: 225 case SimpleTypeKind::Int64Quad: 226 return lldb::eBasicTypeLongLong; 227 case SimpleTypeKind::Int32: 228 return lldb::eBasicTypeInt; 229 case SimpleTypeKind::Int16: 230 case SimpleTypeKind::Int16Short: 231 return lldb::eBasicTypeShort; 232 case SimpleTypeKind::UInt128: 233 return lldb::eBasicTypeUnsignedInt128; 234 case SimpleTypeKind::UInt64: 235 case SimpleTypeKind::UInt64Quad: 236 return lldb::eBasicTypeUnsignedLongLong; 237 case SimpleTypeKind::HResult: 238 case SimpleTypeKind::UInt32: 239 return lldb::eBasicTypeUnsignedInt; 240 case SimpleTypeKind::UInt16: 241 case SimpleTypeKind::UInt16Short: 242 return lldb::eBasicTypeUnsignedShort; 243 case SimpleTypeKind::Int32Long: 244 return lldb::eBasicTypeLong; 245 case SimpleTypeKind::UInt32Long: 246 return lldb::eBasicTypeUnsignedLong; 247 case SimpleTypeKind::Void: 248 return lldb::eBasicTypeVoid; 249 case SimpleTypeKind::WideCharacter: 250 return lldb::eBasicTypeWChar; 251 default: 252 return lldb::eBasicTypeInvalid; 253 } 254 } 255 256 static bool IsSimpleTypeSignedInteger(SimpleTypeKind kind) { 257 switch (kind) { 258 case SimpleTypeKind::Int128: 259 case SimpleTypeKind::Int64: 260 case SimpleTypeKind::Int64Quad: 261 case SimpleTypeKind::Int32: 262 case SimpleTypeKind::Int32Long: 263 case SimpleTypeKind::Int16: 264 case SimpleTypeKind::Int16Short: 265 case SimpleTypeKind::Float128: 266 case SimpleTypeKind::Float80: 267 case SimpleTypeKind::Float64: 268 case SimpleTypeKind::Float32: 269 case SimpleTypeKind::Float16: 270 case SimpleTypeKind::NarrowCharacter: 271 case SimpleTypeKind::SignedCharacter: 272 case SimpleTypeKind::SByte: 273 return true; 274 default: 275 return false; 276 } 277 } 278 279 static size_t GetTypeSizeForSimpleKind(SimpleTypeKind kind) { 280 switch (kind) { 281 case SimpleTypeKind::Boolean128: 282 case SimpleTypeKind::Int128: 283 case SimpleTypeKind::UInt128: 284 case SimpleTypeKind::Float128: 285 return 16; 286 case SimpleTypeKind::Complex80: 287 case SimpleTypeKind::Float80: 288 return 10; 289 case SimpleTypeKind::Boolean64: 290 case SimpleTypeKind::Complex64: 291 case SimpleTypeKind::UInt64: 292 case SimpleTypeKind::UInt64Quad: 293 case SimpleTypeKind::Float64: 294 case SimpleTypeKind::Int64: 295 case SimpleTypeKind::Int64Quad: 296 return 8; 297 case SimpleTypeKind::Boolean32: 298 case SimpleTypeKind::Character32: 299 case SimpleTypeKind::Complex32: 300 case SimpleTypeKind::Float32: 301 case SimpleTypeKind::Int32: 302 case SimpleTypeKind::Int32Long: 303 case SimpleTypeKind::UInt32Long: 304 case SimpleTypeKind::HResult: 305 case SimpleTypeKind::UInt32: 306 return 4; 307 case SimpleTypeKind::Boolean16: 308 case SimpleTypeKind::Character16: 309 case SimpleTypeKind::Float16: 310 case SimpleTypeKind::Int16: 311 case SimpleTypeKind::Int16Short: 312 case SimpleTypeKind::UInt16: 313 case SimpleTypeKind::UInt16Short: 314 case SimpleTypeKind::WideCharacter: 315 return 2; 316 case SimpleTypeKind::Boolean8: 317 case SimpleTypeKind::Byte: 318 case SimpleTypeKind::UnsignedCharacter: 319 case SimpleTypeKind::NarrowCharacter: 320 case SimpleTypeKind::SignedCharacter: 321 case SimpleTypeKind::SByte: 322 return 1; 323 case SimpleTypeKind::Void: 324 default: 325 return 0; 326 } 327 } 328 329 std::pair<size_t, bool> GetIntegralTypeInfo(TypeIndex ti, TpiStream &tpi) { 330 if (ti.isSimple()) { 331 SimpleTypeKind stk = ti.getSimpleKind(); 332 return {GetTypeSizeForSimpleKind(stk), IsSimpleTypeSignedInteger(stk)}; 333 } 334 335 CVType cvt = tpi.getType(ti); 336 switch (cvt.kind()) { 337 case LF_MODIFIER: { 338 ModifierRecord mfr; 339 llvm::cantFail(TypeDeserializer::deserializeAs<ModifierRecord>(cvt, mfr)); 340 return GetIntegralTypeInfo(mfr.ModifiedType, tpi); 341 } 342 case LF_POINTER: { 343 PointerRecord pr; 344 llvm::cantFail(TypeDeserializer::deserializeAs<PointerRecord>(cvt, pr)); 345 return GetIntegralTypeInfo(pr.ReferentType, tpi); 346 } 347 case LF_ENUM: { 348 EnumRecord er; 349 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)); 350 return GetIntegralTypeInfo(er.UnderlyingType, tpi); 351 } 352 default: 353 assert(false && "Type is not integral!"); 354 return {0, false}; 355 } 356 } 357 358 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) { 359 switch (kind) { 360 case SimpleTypeKind::Boolean128: 361 case SimpleTypeKind::Boolean16: 362 case SimpleTypeKind::Boolean32: 363 case SimpleTypeKind::Boolean64: 364 case SimpleTypeKind::Boolean8: 365 return "bool"; 366 case SimpleTypeKind::Byte: 367 case SimpleTypeKind::UnsignedCharacter: 368 return "unsigned char"; 369 case SimpleTypeKind::NarrowCharacter: 370 return "char"; 371 case SimpleTypeKind::SignedCharacter: 372 case SimpleTypeKind::SByte: 373 return "signed char"; 374 case SimpleTypeKind::Character16: 375 return "char16_t"; 376 case SimpleTypeKind::Character32: 377 return "char32_t"; 378 case SimpleTypeKind::Complex80: 379 case SimpleTypeKind::Complex64: 380 case SimpleTypeKind::Complex32: 381 return "complex"; 382 case SimpleTypeKind::Float128: 383 case SimpleTypeKind::Float80: 384 return "long double"; 385 case SimpleTypeKind::Float64: 386 return "double"; 387 case SimpleTypeKind::Float32: 388 return "float"; 389 case SimpleTypeKind::Float16: 390 return "single"; 391 case SimpleTypeKind::Int128: 392 return "__int128"; 393 case SimpleTypeKind::Int64: 394 case SimpleTypeKind::Int64Quad: 395 return "int64_t"; 396 case SimpleTypeKind::Int32: 397 return "int"; 398 case SimpleTypeKind::Int16: 399 return "short"; 400 case SimpleTypeKind::UInt128: 401 return "unsigned __int128"; 402 case SimpleTypeKind::UInt64: 403 case SimpleTypeKind::UInt64Quad: 404 return "uint64_t"; 405 case SimpleTypeKind::HResult: 406 return "HRESULT"; 407 case SimpleTypeKind::UInt32: 408 return "unsigned"; 409 case SimpleTypeKind::UInt16: 410 case SimpleTypeKind::UInt16Short: 411 return "unsigned short"; 412 case SimpleTypeKind::Int32Long: 413 return "long"; 414 case SimpleTypeKind::UInt32Long: 415 return "unsigned long"; 416 case SimpleTypeKind::Void: 417 return "void"; 418 case SimpleTypeKind::WideCharacter: 419 return "wchar_t"; 420 default: 421 return ""; 422 } 423 } 424 425 static bool IsClassRecord(TypeLeafKind kind) { 426 switch (kind) { 427 case LF_STRUCTURE: 428 case LF_CLASS: 429 case LF_INTERFACE: 430 return true; 431 default: 432 return false; 433 } 434 } 435 436 static PDB_SymType GetPdbSymType(TpiStream &tpi, TypeIndex ti) { 437 if (ti.isSimple()) { 438 if (ti.getSimpleMode() == SimpleTypeMode::Direct) 439 return PDB_SymType::BuiltinType; 440 return PDB_SymType::PointerType; 441 } 442 443 CVType cvt = tpi.getType(ti); 444 TypeLeafKind kind = cvt.kind(); 445 if (kind != LF_MODIFIER) 446 return CVTypeToPDBType(kind); 447 448 // If this is an LF_MODIFIER, look through it to get the kind that it 449 // modifies. Note that it's not possible to have an LF_MODIFIER that 450 // modifies another LF_MODIFIER, although this would handle that anyway. 451 return GetPdbSymType(tpi, LookThroughModifierRecord(cvt)); 452 } 453 454 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) { 455 if (args.empty()) 456 return false; 457 return args.back() == TypeIndex::None(); 458 } 459 460 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) { 461 switch (cr.Kind) { 462 case TypeRecordKind::Class: 463 return clang::TTK_Class; 464 case TypeRecordKind::Struct: 465 return clang::TTK_Struct; 466 case TypeRecordKind::Union: 467 return clang::TTK_Union; 468 case TypeRecordKind::Interface: 469 return clang::TTK_Interface; 470 case TypeRecordKind::Enum: 471 return clang::TTK_Enum; 472 default: 473 lldbassert(false && "Invalid tag record kind!"); 474 return clang::TTK_Struct; 475 } 476 } 477 478 static llvm::Optional<clang::CallingConv> 479 TranslateCallingConvention(llvm::codeview::CallingConvention conv) { 480 using CC = llvm::codeview::CallingConvention; 481 switch (conv) { 482 483 case CC::NearC: 484 case CC::FarC: 485 return clang::CallingConv::CC_C; 486 case CC::NearPascal: 487 case CC::FarPascal: 488 return clang::CallingConv::CC_X86Pascal; 489 case CC::NearFast: 490 case CC::FarFast: 491 return clang::CallingConv::CC_X86FastCall; 492 case CC::NearStdCall: 493 case CC::FarStdCall: 494 return clang::CallingConv::CC_X86StdCall; 495 case CC::ThisCall: 496 return clang::CallingConv::CC_X86ThisCall; 497 case CC::NearVector: 498 return clang::CallingConv::CC_X86VectorCall; 499 default: 500 return llvm::None; 501 } 502 } 503 504 void SymbolFileNativePDB::Initialize() { 505 PluginManager::RegisterPlugin(GetPluginNameStatic(), 506 GetPluginDescriptionStatic(), CreateInstance, 507 DebuggerInitialize); 508 } 509 510 void SymbolFileNativePDB::Terminate() { 511 PluginManager::UnregisterPlugin(CreateInstance); 512 } 513 514 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {} 515 516 ConstString SymbolFileNativePDB::GetPluginNameStatic() { 517 static ConstString g_name("native-pdb"); 518 return g_name; 519 } 520 521 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() { 522 return "Microsoft PDB debug symbol cross-platform file reader."; 523 } 524 525 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) { 526 return new SymbolFileNativePDB(obj_file); 527 } 528 529 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file) 530 : SymbolFile(object_file) {} 531 532 SymbolFileNativePDB::~SymbolFileNativePDB() {} 533 534 uint32_t SymbolFileNativePDB::CalculateAbilities() { 535 uint32_t abilities = 0; 536 if (!m_obj_file) 537 return 0; 538 539 if (!m_index) { 540 // Lazily load and match the PDB file, but only do this once. 541 std::unique_ptr<PDBFile> file_up = 542 loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator); 543 544 if (!file_up) { 545 auto module_sp = m_obj_file->GetModule(); 546 if (!module_sp) 547 return 0; 548 // See if any symbol file is specified through `--symfile` option. 549 FileSpec symfile = module_sp->GetSymbolFileFileSpec(); 550 if (!symfile) 551 return 0; 552 file_up = loadPDBFile(symfile.GetPath(), m_allocator); 553 } 554 555 if (!file_up) 556 return 0; 557 558 auto expected_index = PdbIndex::create(std::move(file_up)); 559 if (!expected_index) { 560 llvm::consumeError(expected_index.takeError()); 561 return 0; 562 } 563 m_index = std::move(*expected_index); 564 } 565 if (!m_index) 566 return 0; 567 568 // We don't especially have to be precise here. We only distinguish between 569 // stripped and not stripped. 570 abilities = kAllAbilities; 571 572 if (m_index->dbi().isStripped()) 573 abilities &= ~(Blocks | LocalVariables); 574 return abilities; 575 } 576 577 void SymbolFileNativePDB::InitializeObject() { 578 m_obj_load_address = m_obj_file->GetFileOffset(); 579 m_index->SetLoadAddress(m_obj_load_address); 580 m_index->ParseSectionContribs(); 581 582 TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus); 583 m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts); 584 m_importer = llvm::make_unique<ClangASTImporter>(); 585 586 PreprocessTpiStream(); 587 lldbassert(m_clang); 588 } 589 590 static llvm::Optional<CVTagRecord> 591 GetNestedTagRecord(const NestedTypeRecord &Record, const CVTagRecord &parent, 592 TpiStream &tpi) { 593 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it 594 // is also used to indicate the primary definition of a nested class. That is 595 // to say, if you have: 596 // struct A { 597 // struct B {}; 598 // using C = B; 599 // }; 600 // Then in the debug info, this will appear as: 601 // LF_STRUCTURE `A::B` [type index = N] 602 // LF_STRUCTURE `A` 603 // LF_NESTTYPE [name = `B`, index = N] 604 // LF_NESTTYPE [name = `C`, index = N] 605 // In order to accurately reconstruct the decl context hierarchy, we need to 606 // know which ones are actual definitions and which ones are just aliases. 607 608 // If it's a simple type, then this is something like `using foo = int`. 609 if (Record.Type.isSimple()) 610 return llvm::None; 611 612 CVType cvt = tpi.getType(Record.Type); 613 614 if (!IsTagRecord(cvt)) 615 return llvm::None; 616 617 // If it's an inner definition, then treat whatever name we have here as a 618 // single component of a mangled name. So we can inject it into the parent's 619 // mangled name to see if it matches. 620 CVTagRecord child = CVTagRecord::create(cvt); 621 std::string qname = parent.asTag().getUniqueName(); 622 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4) 623 return llvm::None; 624 625 // qname[3] is the tag type identifier (struct, class, union, etc). Since the 626 // inner tag type is not necessarily the same as the outer tag type, re-write 627 // it to match the inner tag type. 628 qname[3] = child.asTag().getUniqueName()[3]; 629 std::string piece = Record.Name; 630 piece.push_back('@'); 631 qname.insert(4, std::move(piece)); 632 if (qname != child.asTag().UniqueName) 633 return llvm::None; 634 635 return std::move(child); 636 } 637 638 void SymbolFileNativePDB::PreprocessTpiStream() { 639 LazyRandomTypeCollection &types = m_index->tpi().typeCollection(); 640 641 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { 642 CVType type = types.getType(*ti); 643 if (!IsTagRecord(type)) 644 continue; 645 646 CVTagRecord tag = CVTagRecord::create(type); 647 // We're looking for LF_NESTTYPE records in the field list, so ignore 648 // forward references (no field list), and anything without a nested class 649 // (since there won't be any LF_NESTTYPE records). 650 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass()) 651 continue; 652 653 struct ProcessTpiStream : public TypeVisitorCallbacks { 654 ProcessTpiStream(PdbIndex &index, TypeIndex parent, 655 const CVTagRecord &parent_cvt, 656 llvm::DenseMap<TypeIndex, TypeIndex> &parents) 657 : index(index), parents(parents), parent(parent), 658 parent_cvt(parent_cvt) {} 659 660 PdbIndex &index; 661 llvm::DenseMap<TypeIndex, TypeIndex> &parents; 662 TypeIndex parent; 663 const CVTagRecord &parent_cvt; 664 665 llvm::Error visitKnownMember(CVMemberRecord &CVR, 666 NestedTypeRecord &Record) override { 667 llvm::Optional<CVTagRecord> tag = 668 GetNestedTagRecord(Record, parent_cvt, index.tpi()); 669 if (!tag) 670 return llvm::ErrorSuccess(); 671 672 parents[Record.Type] = parent; 673 if (!tag->asTag().isForwardRef()) 674 return llvm::ErrorSuccess(); 675 676 llvm::Expected<TypeIndex> full_decl = 677 index.tpi().findFullDeclForForwardRef(Record.Type); 678 if (!full_decl) { 679 llvm::consumeError(full_decl.takeError()); 680 return llvm::ErrorSuccess(); 681 } 682 parents[*full_decl] = parent; 683 return llvm::ErrorSuccess(); 684 } 685 }; 686 687 CVType field_list = m_index->tpi().getType(tag.asTag().FieldList); 688 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types); 689 llvm::Error error = visitMemberRecordStream(field_list.data(), process); 690 if (error) 691 llvm::consumeError(std::move(error)); 692 } 693 } 694 695 uint32_t SymbolFileNativePDB::GetNumCompileUnits() { 696 const DbiModuleList &modules = m_index->dbi().modules(); 697 uint32_t count = modules.getModuleCount(); 698 if (count == 0) 699 return count; 700 701 // The linker can inject an additional "dummy" compilation unit into the 702 // PDB. Ignore this special compile unit for our purposes, if it is there. 703 // It is always the last one. 704 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1); 705 if (last.getModuleName() == "* Linker *") 706 --count; 707 return count; 708 } 709 710 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id, 711 const SymbolContext &sc) { 712 const CompilandIndexItem *cci = 713 m_index->compilands().GetCompiland(func_id.modi); 714 lldbassert(cci); 715 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset); 716 717 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32); 718 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record); 719 720 auto file_vm_addr = m_index->MakeVirtualAddress(sol.so); 721 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 722 return nullptr; 723 724 AddressRange func_range(file_vm_addr, sol.length, 725 sc.module_sp->GetSectionList()); 726 if (!func_range.GetBaseAddress().IsValid()) 727 return nullptr; 728 729 Type *func_type = nullptr; 730 731 // FIXME: Resolve types and mangled names. 732 PdbTypeSymId sig_id{TypeIndex::None(), false}; 733 Mangled mangled(getSymbolName(sym_record)); 734 FunctionSP func_sp = std::make_shared<Function>( 735 sc.comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled, 736 func_type, func_range); 737 738 sc.comp_unit->AddFunction(func_sp); 739 return func_sp; 740 } 741 742 CompUnitSP 743 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) { 744 lldb::LanguageType lang = 745 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage()) 746 : lldb::eLanguageTypeUnknown; 747 748 LazyBool optimized = eLazyBoolNo; 749 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations()) 750 optimized = eLazyBoolYes; 751 752 llvm::StringRef source_file_name = 753 m_index->compilands().GetMainSourceFile(cci); 754 FileSpec fs(source_file_name); 755 756 CompUnitSP cu_sp = 757 std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs, 758 toOpaqueUid(cci.m_id), lang, optimized); 759 760 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex( 761 cci.m_id.modi, cu_sp); 762 return cu_sp; 763 } 764 765 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id, 766 const ModifierRecord &mr) { 767 TpiStream &stream = m_index->tpi(); 768 769 TypeSP t = GetOrCreateType(mr.ModifiedType); 770 CompilerType ct = t->GetForwardCompilerType(); 771 if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 772 ct = ct.AddConstModifier(); 773 if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 774 ct = ct.AddVolatileModifier(); 775 std::string name; 776 if (mr.ModifiedType.isSimple()) 777 name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind()); 778 else 779 name = computeTypeName(stream.typeCollection(), mr.ModifiedType); 780 Declaration decl; 781 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(), 782 ConstString(name), t->GetByteSize(), nullptr, 783 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 784 ct, Type::eResolveStateFull); 785 } 786 787 lldb::TypeSP SymbolFileNativePDB::CreatePointerType( 788 PdbTypeSymId type_id, const llvm::codeview::PointerRecord &pr) { 789 TypeSP pointee = GetOrCreateType(pr.ReferentType); 790 if (!pointee) 791 return nullptr; 792 CompilerType pointee_ct = pointee->GetForwardCompilerType(); 793 lldbassert(pointee_ct); 794 Declaration decl; 795 796 if (pr.isPointerToMember()) { 797 MemberPointerInfo mpi = pr.getMemberInfo(); 798 TypeSP class_type = GetOrCreateType(mpi.ContainingType); 799 800 CompilerType ct = ClangASTContext::CreateMemberPointerType( 801 class_type->GetLayoutCompilerType(), pointee_ct); 802 803 return std::make_shared<Type>( 804 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(), 805 pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct, 806 Type::eResolveStateFull); 807 } 808 809 CompilerType pointer_ct = pointee_ct; 810 if (pr.getMode() == PointerMode::LValueReference) 811 pointer_ct = pointer_ct.GetLValueReferenceType(); 812 else if (pr.getMode() == PointerMode::RValueReference) 813 pointer_ct = pointer_ct.GetRValueReferenceType(); 814 else 815 pointer_ct = pointer_ct.GetPointerType(); 816 817 if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None) 818 pointer_ct = pointer_ct.AddConstModifier(); 819 820 if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 821 pointer_ct = pointer_ct.AddVolatileModifier(); 822 823 if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 824 pointer_ct = pointer_ct.AddRestrictModifier(); 825 826 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(), 827 ConstString(), pr.getSize(), nullptr, 828 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 829 pointer_ct, Type::eResolveStateFull); 830 } 831 832 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) { 833 uint64_t uid = toOpaqueUid(PdbTypeSymId{ti, false}); 834 if (ti == TypeIndex::NullptrT()) { 835 CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr); 836 Declaration decl; 837 return std::make_shared<Type>( 838 uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID, 839 Type::eEncodingIsUID, decl, ct, Type::eResolveStateFull); 840 } 841 842 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 843 TypeSP direct_sp = GetOrCreateType(ti.makeDirect()); 844 CompilerType ct = direct_sp->GetFullCompilerType(); 845 ct = ct.GetPointerType(); 846 uint32_t pointer_size = 0; 847 switch (ti.getSimpleMode()) { 848 case SimpleTypeMode::FarPointer32: 849 case SimpleTypeMode::NearPointer32: 850 pointer_size = 4; 851 break; 852 case SimpleTypeMode::NearPointer64: 853 pointer_size = 8; 854 break; 855 default: 856 // 128-bit and 16-bit pointers unsupported. 857 return nullptr; 858 } 859 Declaration decl; 860 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(), ConstString(), 861 pointer_size, nullptr, LLDB_INVALID_UID, 862 Type::eEncodingIsUID, decl, ct, 863 Type::eResolveStateFull); 864 } 865 866 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 867 return nullptr; 868 869 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 870 if (bt == lldb::eBasicTypeInvalid) 871 return nullptr; 872 CompilerType ct = m_clang->GetBasicType(bt); 873 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind()); 874 875 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind()); 876 877 Declaration decl; 878 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(), 879 ConstString(type_name), size, nullptr, 880 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 881 ct, Type::eResolveStateFull); 882 } 883 884 static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) { 885 OutputStream OS; 886 initializeOutputStream(nullptr, nullptr, OS, 1024); 887 n->output(OS, llvm::ms_demangle::OF_Default); 888 OS << '\0'; 889 return {OS.getBuffer()}; 890 } 891 892 static bool 893 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) { 894 for (llvm::ms_demangle::Node *n : scopes) { 895 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n); 896 if (idn->TemplateParams) 897 return true; 898 } 899 return false; 900 } 901 902 std::pair<clang::DeclContext *, std::string> 903 SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record, 904 TypeIndex ti) { 905 llvm::ms_demangle::Demangler demangler; 906 StringView sv(record.UniqueName.begin(), record.UniqueName.size()); 907 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); 908 llvm::ms_demangle::IdentifierNode *idn = 909 ttn->QualifiedName->getUnqualifiedIdentifier(); 910 std::string uname = RenderDemanglerNode(idn); 911 912 llvm::ms_demangle::NodeArrayNode *name_components = 913 ttn->QualifiedName->Components; 914 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes, 915 name_components->Count - 1); 916 917 clang::DeclContext *context = m_clang->GetTranslationUnitDecl(); 918 919 // If this type doesn't have a parent type in the debug info, then the best we 920 // can do is to say that it's either a series of namespaces (if the scope is 921 // non-empty), or the translation unit (if the scope is empty). 922 auto parent_iter = m_parent_types.find(ti); 923 if (parent_iter == m_parent_types.end()) { 924 if (scopes.empty()) 925 return {context, uname}; 926 927 // If there is no parent in the debug info, but some of the scopes have 928 // template params, then this is a case of bad debug info. See, for 929 // example, llvm.org/pr39607. We don't want to create an ambiguity between 930 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at 931 // global scope with the fully qualified name. 932 if (AnyScopesHaveTemplateParams(scopes)) 933 return {context, record.Name}; 934 935 for (llvm::ms_demangle::Node *scope : scopes) { 936 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope); 937 std::string str = RenderDemanglerNode(nii); 938 context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context); 939 } 940 return {context, uname}; 941 } 942 943 // Otherwise, all we need to do is get the parent type of this type and 944 // recurse into our lazy type creation / AST reconstruction logic to get an 945 // LLDB TypeSP for the parent. This will cause the AST to automatically get 946 // the right DeclContext created for any parent. 947 TypeSP parent = GetOrCreateType(parent_iter->second); 948 if (!parent) 949 return {context, uname}; 950 CompilerType parent_ct = parent->GetForwardCompilerType(); 951 clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct); 952 context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl()); 953 return {context, uname}; 954 } 955 956 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion( 957 PdbTypeSymId type_id, const llvm::codeview::TagRecord &record, size_t size, 958 clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) { 959 960 clang::DeclContext *decl_context = nullptr; 961 std::string uname; 962 std::tie(decl_context, uname) = CreateDeclInfoForType(record, type_id.index); 963 964 lldb::AccessType access = 965 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 966 967 ClangASTMetadata metadata; 968 metadata.SetUserID(toOpaqueUid(type_id)); 969 metadata.SetIsDynamicCXXType(false); 970 971 CompilerType ct = 972 m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk, 973 lldb::eLanguageTypeC_plus_plus, &metadata); 974 975 lldbassert(ct.IsValid()); 976 977 clang::CXXRecordDecl *record_decl = 978 m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType()); 979 lldbassert(record_decl); 980 981 clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit( 982 *m_clang->getASTContext(), inheritance); 983 record_decl->addAttr(attr); 984 985 ClangASTContext::StartTagDeclarationDefinition(ct); 986 987 // Even if it's possible, don't complete it at this point. Just mark it 988 // forward resolved, and if/when LLDB needs the full definition, it can 989 // ask us. 990 ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true); 991 992 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE. 993 Declaration decl; 994 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(), 995 ConstString(uname), size, nullptr, 996 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 997 ct, Type::eResolveStateForward); 998 } 999 1000 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 1001 const ClassRecord &cr) { 1002 clang::TagTypeKind ttk = TranslateUdtKind(cr); 1003 1004 clang::MSInheritanceAttr::Spelling inheritance = 1005 GetMSInheritance(m_index->tpi().typeCollection(), cr); 1006 return CreateClassStructUnion(type_id, cr, cr.getSize(), ttk, inheritance); 1007 } 1008 1009 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 1010 const UnionRecord &ur) { 1011 return CreateClassStructUnion( 1012 type_id, ur, ur.getSize(), clang::TTK_Union, 1013 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance); 1014 } 1015 1016 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, 1017 const EnumRecord &er) { 1018 clang::DeclContext *decl_context = nullptr; 1019 std::string uname; 1020 std::tie(decl_context, uname) = CreateDeclInfoForType(er, type_id.index); 1021 1022 Declaration decl; 1023 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType); 1024 CompilerType enum_ct = m_clang->CreateEnumerationType( 1025 uname.c_str(), decl_context, decl, underlying_type->GetFullCompilerType(), 1026 er.isScoped()); 1027 1028 ClangASTContext::StartTagDeclarationDefinition(enum_ct); 1029 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1030 1031 // We're just going to forward resolve this for now. We'll complete 1032 // it only if the user requests. 1033 return std::make_shared<lldb_private::Type>( 1034 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(uname), 1035 underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID, 1036 lldb_private::Type::eEncodingIsUID, decl, enum_ct, 1037 lldb_private::Type::eResolveStateForward); 1038 } 1039 1040 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id, 1041 const ArrayRecord &ar) { 1042 TypeSP element_type = GetOrCreateType(ar.ElementType); 1043 uint64_t element_count = ar.Size / element_type->GetByteSize(); 1044 1045 CompilerType element_ct = element_type->GetFullCompilerType(); 1046 1047 CompilerType array_ct = 1048 m_clang->CreateArrayType(element_ct, element_count, false); 1049 1050 Declaration decl; 1051 TypeSP array_sp = std::make_shared<lldb_private::Type>( 1052 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(), ar.Size, 1053 nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, 1054 array_ct, lldb_private::Type::eResolveStateFull); 1055 array_sp->SetEncodingType(element_type.get()); 1056 return array_sp; 1057 } 1058 1059 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id, 1060 const ProcedureRecord &pr) { 1061 TpiStream &stream = m_index->tpi(); 1062 CVType args_cvt = stream.getType(pr.ArgumentList); 1063 ArgListRecord args; 1064 llvm::cantFail( 1065 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1066 1067 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1068 bool is_variadic = IsCVarArgsFunction(arg_indices); 1069 if (is_variadic) 1070 arg_indices = arg_indices.drop_back(); 1071 1072 std::vector<CompilerType> arg_list; 1073 arg_list.reserve(arg_list.size()); 1074 1075 for (TypeIndex arg_index : arg_indices) { 1076 TypeSP arg_sp = GetOrCreateType(arg_index); 1077 if (!arg_sp) 1078 return nullptr; 1079 arg_list.push_back(arg_sp->GetFullCompilerType()); 1080 } 1081 1082 TypeSP return_type_sp = GetOrCreateType(pr.ReturnType); 1083 if (!return_type_sp) 1084 return nullptr; 1085 1086 llvm::Optional<clang::CallingConv> cc = 1087 TranslateCallingConvention(pr.CallConv); 1088 if (!cc) 1089 return nullptr; 1090 1091 CompilerType return_ct = return_type_sp->GetFullCompilerType(); 1092 CompilerType func_sig_ast_type = m_clang->CreateFunctionType( 1093 return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc); 1094 1095 Declaration decl; 1096 return std::make_shared<lldb_private::Type>( 1097 toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID, 1098 lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type, 1099 lldb_private::Type::eResolveStateFull); 1100 } 1101 1102 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id) { 1103 if (type_id.index.isSimple()) 1104 return CreateSimpleType(type_id.index); 1105 1106 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi(); 1107 CVType cvt = stream.getType(type_id.index); 1108 1109 if (cvt.kind() == LF_MODIFIER) { 1110 ModifierRecord modifier; 1111 llvm::cantFail( 1112 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 1113 return CreateModifierType(type_id, modifier); 1114 } 1115 1116 if (cvt.kind() == LF_POINTER) { 1117 PointerRecord pointer; 1118 llvm::cantFail( 1119 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 1120 return CreatePointerType(type_id, pointer); 1121 } 1122 1123 if (IsClassRecord(cvt.kind())) { 1124 ClassRecord cr; 1125 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr)); 1126 return CreateTagType(type_id, cr); 1127 } 1128 1129 if (cvt.kind() == LF_ENUM) { 1130 EnumRecord er; 1131 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)); 1132 return CreateTagType(type_id, er); 1133 } 1134 1135 if (cvt.kind() == LF_UNION) { 1136 UnionRecord ur; 1137 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur)); 1138 return CreateTagType(type_id, ur); 1139 } 1140 1141 if (cvt.kind() == LF_ARRAY) { 1142 ArrayRecord ar; 1143 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 1144 return CreateArrayType(type_id, ar); 1145 } 1146 1147 if (cvt.kind() == LF_PROCEDURE) { 1148 ProcedureRecord pr; 1149 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 1150 return CreateProcedureType(type_id, pr); 1151 } 1152 1153 return nullptr; 1154 } 1155 1156 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) { 1157 // If they search for a UDT which is a forward ref, try and resolve the full 1158 // decl and just map the forward ref uid to the full decl record. 1159 llvm::Optional<PdbTypeSymId> full_decl_uid; 1160 if (IsForwardRefUdt(type_id, m_index->tpi())) { 1161 auto expected_full_ti = 1162 m_index->tpi().findFullDeclForForwardRef(type_id.index); 1163 if (!expected_full_ti) 1164 llvm::consumeError(expected_full_ti.takeError()); 1165 else if (*expected_full_ti != type_id.index) { 1166 full_decl_uid = PdbTypeSymId{*expected_full_ti, false}; 1167 1168 // It's possible that a lookup would occur for the full decl causing it 1169 // to be cached, then a second lookup would occur for the forward decl. 1170 // We don't want to create a second full decl, so make sure the full 1171 // decl hasn't already been cached. 1172 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid)); 1173 if (full_iter != m_types.end()) { 1174 TypeSP result = full_iter->second; 1175 // Map the forward decl to the TypeSP for the full decl so we can take 1176 // the fast path next time. 1177 m_types[toOpaqueUid(type_id)] = result; 1178 return result; 1179 } 1180 } 1181 } 1182 1183 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id; 1184 TypeSP result = CreateType(best_decl_id); 1185 if (!result) 1186 return nullptr; 1187 1188 uint64_t best_uid = toOpaqueUid(best_decl_id); 1189 m_types[best_uid] = result; 1190 // If we had both a forward decl and a full decl, make both point to the new 1191 // type. 1192 if (full_decl_uid) 1193 m_types[toOpaqueUid(type_id)] = result; 1194 1195 if (IsTagRecord(best_decl_id, m_index->tpi())) { 1196 clang::TagDecl *record_decl = 1197 m_clang->GetAsTagDecl(result->GetForwardCompilerType()); 1198 lldbassert(record_decl); 1199 1200 TypeIndex ti(type_id.index); 1201 m_uid_to_decl[best_uid] = record_decl; 1202 m_decl_to_status[record_decl] = 1203 DeclStatus(best_uid, Type::eResolveStateForward); 1204 } 1205 return result; 1206 } 1207 1208 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) { 1209 // We can't use try_emplace / overwrite here because the process of creating 1210 // a type could create nested types, which could invalidate iterators. So 1211 // we have to do a 2-phase lookup / insert. 1212 auto iter = m_types.find(toOpaqueUid(type_id)); 1213 if (iter != m_types.end()) 1214 return iter->second; 1215 1216 return CreateAndCacheType(type_id); 1217 } 1218 1219 static DWARFExpression 1220 MakeConstantLocationExpression(TypeIndex underlying_ti, TpiStream &tpi, 1221 const ConstantSym &constant, ModuleSP module) { 1222 const ArchSpec &architecture = module->GetArchitecture(); 1223 uint32_t address_size = architecture.GetAddressByteSize(); 1224 1225 size_t size = 0; 1226 bool is_signed = false; 1227 std::tie(size, is_signed) = GetIntegralTypeInfo(underlying_ti, tpi); 1228 1229 union { 1230 llvm::support::little64_t I; 1231 llvm::support::ulittle64_t U; 1232 } Value; 1233 1234 std::shared_ptr<DataBufferHeap> buffer = std::make_shared<DataBufferHeap>(); 1235 buffer->SetByteSize(size); 1236 1237 llvm::ArrayRef<uint8_t> bytes; 1238 if (is_signed) { 1239 Value.I = constant.Value.getSExtValue(); 1240 } else { 1241 Value.U = constant.Value.getZExtValue(); 1242 } 1243 1244 bytes = llvm::makeArrayRef(reinterpret_cast<const uint8_t *>(&Value), 8) 1245 .take_front(size); 1246 buffer->CopyData(bytes.data(), size); 1247 DataExtractor extractor(buffer, lldb::eByteOrderLittle, address_size); 1248 DWARFExpression result(nullptr, extractor, nullptr, 0, size); 1249 return result; 1250 } 1251 1252 static DWARFExpression MakeGlobalLocationExpression(uint16_t section, 1253 uint32_t offset, 1254 ModuleSP module) { 1255 assert(section > 0); 1256 assert(module); 1257 1258 const ArchSpec &architecture = module->GetArchitecture(); 1259 ByteOrder byte_order = architecture.GetByteOrder(); 1260 uint32_t address_size = architecture.GetAddressByteSize(); 1261 uint32_t byte_size = architecture.GetDataByteSize(); 1262 assert(byte_order != eByteOrderInvalid && address_size != 0); 1263 1264 RegisterKind register_kind = eRegisterKindDWARF; 1265 StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); 1266 stream.PutHex8(DW_OP_addr); 1267 1268 SectionList *section_list = module->GetSectionList(); 1269 assert(section_list); 1270 1271 // Section indices in PDB are 1-based, but in DWARF they are 0-based, so we 1272 // need to subtract 1. 1273 uint32_t section_idx = section - 1; 1274 if (section_idx >= section_list->GetSize()) 1275 return DWARFExpression(nullptr); 1276 1277 auto section_ptr = section_list->GetSectionAtIndex(section_idx); 1278 if (!section_ptr) 1279 return DWARFExpression(nullptr); 1280 1281 stream.PutMaxHex64(section_ptr->GetFileAddress() + offset, address_size, 1282 byte_order); 1283 DataBufferSP buffer = 1284 std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize()); 1285 DataExtractor extractor(buffer, byte_order, address_size, byte_size); 1286 DWARFExpression result(module, extractor, nullptr, 0, buffer->GetByteSize()); 1287 result.SetRegisterKind(register_kind); 1288 return result; 1289 } 1290 1291 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) { 1292 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset); 1293 if (sym.kind() == S_CONSTANT) 1294 return CreateConstantSymbol(var_id, sym); 1295 1296 lldb::ValueType scope = eValueTypeInvalid; 1297 TypeIndex ti; 1298 llvm::StringRef name; 1299 lldb::addr_t addr = 0; 1300 uint16_t section = 0; 1301 uint32_t offset = 0; 1302 bool is_external = false; 1303 switch (sym.kind()) { 1304 case S_GDATA32: 1305 is_external = true; 1306 LLVM_FALLTHROUGH; 1307 case S_LDATA32: { 1308 DataSym ds(sym.kind()); 1309 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds)); 1310 ti = ds.Type; 1311 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal 1312 : eValueTypeVariableStatic; 1313 name = ds.Name; 1314 section = ds.Segment; 1315 offset = ds.DataOffset; 1316 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset); 1317 break; 1318 } 1319 case S_GTHREAD32: 1320 is_external = true; 1321 LLVM_FALLTHROUGH; 1322 case S_LTHREAD32: { 1323 ThreadLocalDataSym tlds(sym.kind()); 1324 llvm::cantFail( 1325 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)); 1326 ti = tlds.Type; 1327 name = tlds.Name; 1328 section = tlds.Segment; 1329 offset = tlds.DataOffset; 1330 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset); 1331 scope = eValueTypeVariableThreadLocal; 1332 break; 1333 } 1334 default: 1335 llvm_unreachable("unreachable!"); 1336 } 1337 1338 CompUnitSP comp_unit; 1339 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr); 1340 if (modi) { 1341 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi); 1342 comp_unit = GetOrCreateCompileUnit(cci); 1343 } 1344 1345 Declaration decl; 1346 PdbTypeSymId tid{ti, false}; 1347 SymbolFileTypeSP type_sp = 1348 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 1349 Variable::RangeList ranges; 1350 1351 DWARFExpression location = MakeGlobalLocationExpression( 1352 section, offset, GetObjectFile()->GetModule()); 1353 1354 std::string global_name("::"); 1355 global_name += name; 1356 VariableSP var_sp = std::make_shared<Variable>( 1357 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp, 1358 scope, comp_unit.get(), ranges, &decl, location, is_external, false, 1359 false); 1360 var_sp->SetLocationIsConstantValueData(false); 1361 1362 return var_sp; 1363 } 1364 1365 lldb::VariableSP 1366 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id, 1367 const CVSymbol &cvs) { 1368 TpiStream &tpi = m_index->tpi(); 1369 ConstantSym constant(cvs.kind()); 1370 1371 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)); 1372 std::string global_name("::"); 1373 global_name += constant.Name; 1374 PdbTypeSymId tid{constant.Type, false}; 1375 SymbolFileTypeSP type_sp = 1376 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 1377 1378 Declaration decl; 1379 Variable::RangeList ranges; 1380 ModuleSP module = GetObjectFile()->GetModule(); 1381 DWARFExpression location = 1382 MakeConstantLocationExpression(constant.Type, tpi, constant, module); 1383 1384 VariableSP var_sp = std::make_shared<Variable>( 1385 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(), 1386 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location, 1387 false, false, false); 1388 var_sp->SetLocationIsConstantValueData(true); 1389 return var_sp; 1390 } 1391 1392 VariableSP 1393 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) { 1394 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr); 1395 if (emplace_result.second) 1396 emplace_result.first->second = CreateGlobalVariable(var_id); 1397 1398 return emplace_result.first->second; 1399 } 1400 1401 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) { 1402 return GetOrCreateType(PdbTypeSymId{ti, false}); 1403 } 1404 1405 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id, 1406 const SymbolContext &sc) { 1407 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr); 1408 if (emplace_result.second) 1409 emplace_result.first->second = CreateFunction(func_id, sc); 1410 1411 lldbassert(emplace_result.first->second); 1412 return emplace_result.first->second; 1413 } 1414 1415 CompUnitSP 1416 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) { 1417 1418 auto emplace_result = 1419 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr); 1420 if (emplace_result.second) 1421 emplace_result.first->second = CreateCompileUnit(cci); 1422 1423 lldbassert(emplace_result.first->second); 1424 return emplace_result.first->second; 1425 } 1426 1427 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) { 1428 if (index >= GetNumCompileUnits()) 1429 return CompUnitSP(); 1430 lldbassert(index < UINT16_MAX); 1431 if (index >= UINT16_MAX) 1432 return nullptr; 1433 1434 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index); 1435 1436 return GetOrCreateCompileUnit(item); 1437 } 1438 1439 lldb::LanguageType 1440 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) { 1441 // What fields should I expect to be filled out on the SymbolContext? Is it 1442 // safe to assume that `sc.comp_unit` is valid? 1443 if (!sc.comp_unit) 1444 return lldb::eLanguageTypeUnknown; 1445 PdbSymUid uid(sc.comp_unit->GetID()); 1446 lldbassert(uid.kind() == PdbSymUidKind::Compiland); 1447 1448 CompilandIndexItem *item = 1449 m_index->compilands().GetCompiland(uid.asCompiland().modi); 1450 lldbassert(item); 1451 if (!item->m_compile_opts) 1452 return lldb::eLanguageTypeUnknown; 1453 1454 return TranslateLanguage(item->m_compile_opts->getLanguage()); 1455 } 1456 1457 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) { 1458 lldbassert(sc.comp_unit); 1459 return false; 1460 } 1461 1462 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) { 1463 // If any of these flags are set, we need to resolve the compile unit. 1464 uint32_t flags = eSymbolContextCompUnit; 1465 flags |= eSymbolContextVariable; 1466 flags |= eSymbolContextFunction; 1467 flags |= eSymbolContextBlock; 1468 flags |= eSymbolContextLineEntry; 1469 return (resolve_scope & flags) != 0; 1470 } 1471 1472 uint32_t SymbolFileNativePDB::ResolveSymbolContext( 1473 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) { 1474 uint32_t resolved_flags = 0; 1475 lldb::addr_t file_addr = addr.GetFileAddress(); 1476 1477 if (NeedsResolvedCompileUnit(resolve_scope)) { 1478 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr); 1479 if (!modi) 1480 return 0; 1481 CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi); 1482 if (!cci) 1483 return 0; 1484 1485 sc.comp_unit = GetOrCreateCompileUnit(*cci).get(); 1486 resolved_flags |= eSymbolContextCompUnit; 1487 } 1488 1489 if (resolve_scope & eSymbolContextFunction) { 1490 lldbassert(sc.comp_unit); 1491 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr); 1492 for (const auto &match : matches) { 1493 if (match.uid.kind() != PdbSymUidKind::CompilandSym) 1494 continue; 1495 PdbCompilandSymId csid = match.uid.asCompilandSym(); 1496 CVSymbol cvs = m_index->ReadSymbolRecord(csid); 1497 if (CVSymToPDBSym(cvs.kind()) != PDB_SymType::Function) 1498 continue; 1499 sc.function = GetOrCreateFunction(csid, sc).get(); 1500 } 1501 resolved_flags |= eSymbolContextFunction; 1502 } 1503 1504 if (resolve_scope & eSymbolContextLineEntry) { 1505 lldbassert(sc.comp_unit); 1506 if (auto *line_table = sc.comp_unit->GetLineTable()) { 1507 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 1508 resolved_flags |= eSymbolContextLineEntry; 1509 } 1510 } 1511 1512 return resolved_flags; 1513 } 1514 1515 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence, 1516 const CompilandIndexItem &cci, 1517 lldb::addr_t base_addr, 1518 uint32_t file_number, 1519 const LineFragmentHeader &block, 1520 const LineNumberEntry &cur) { 1521 LineInfo cur_info(cur.Flags); 1522 1523 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto()) 1524 return; 1525 1526 uint64_t addr = base_addr + cur.Offset; 1527 1528 bool is_statement = cur_info.isStatement(); 1529 bool is_prologue = IsFunctionPrologue(cci, addr); 1530 bool is_epilogue = IsFunctionEpilogue(cci, addr); 1531 1532 uint32_t lno = cur_info.getStartLine(); 1533 1534 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number, 1535 is_statement, false, is_prologue, is_epilogue, 1536 false); 1537 } 1538 1539 static void TerminateLineSequence(LineTable &table, 1540 const LineFragmentHeader &block, 1541 lldb::addr_t base_addr, uint32_t file_number, 1542 uint32_t last_line, 1543 std::unique_ptr<LineSequence> seq) { 1544 // The end is always a terminal entry, so insert it regardless. 1545 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize, 1546 last_line, 0, file_number, false, false, 1547 false, false, true); 1548 table.InsertSequence(seq.release()); 1549 } 1550 1551 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) { 1552 // Unfortunately LLDB is set up to parse the entire compile unit line table 1553 // all at once, even if all it really needs is line info for a specific 1554 // function. In the future it would be nice if it could set the sc.m_function 1555 // member, and we could only get the line info for the function in question. 1556 lldbassert(sc.comp_unit); 1557 PdbSymUid cu_id(sc.comp_unit->GetID()); 1558 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1559 CompilandIndexItem *cci = 1560 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1561 lldbassert(cci); 1562 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit); 1563 1564 // This is basically a copy of the .debug$S subsections from all original COFF 1565 // object files merged together with address relocations applied. We are 1566 // looking for all DEBUG_S_LINES subsections. 1567 for (const DebugSubsectionRecord &dssr : 1568 cci->m_debug_stream.getSubsectionsArray()) { 1569 if (dssr.kind() != DebugSubsectionKind::Lines) 1570 continue; 1571 1572 DebugLinesSubsectionRef lines; 1573 llvm::BinaryStreamReader reader(dssr.getRecordData()); 1574 if (auto EC = lines.initialize(reader)) { 1575 llvm::consumeError(std::move(EC)); 1576 return false; 1577 } 1578 1579 const LineFragmentHeader *lfh = lines.header(); 1580 uint64_t virtual_addr = 1581 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset); 1582 1583 const auto &checksums = cci->m_strings.checksums().getArray(); 1584 const auto &strings = cci->m_strings.strings(); 1585 for (const LineColumnEntry &group : lines) { 1586 // Indices in this structure are actually offsets of records in the 1587 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index 1588 // into the global PDB string table. 1589 auto iter = checksums.at(group.NameIndex); 1590 if (iter == checksums.end()) 1591 continue; 1592 1593 llvm::Expected<llvm::StringRef> efn = 1594 strings.getString(iter->FileNameOffset); 1595 if (!efn) { 1596 llvm::consumeError(efn.takeError()); 1597 continue; 1598 } 1599 1600 // LLDB wants the index of the file in the list of support files. 1601 auto fn_iter = llvm::find(cci->m_file_list, *efn); 1602 lldbassert(fn_iter != cci->m_file_list.end()); 1603 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter); 1604 1605 std::unique_ptr<LineSequence> sequence( 1606 line_table->CreateLineSequenceContainer()); 1607 lldbassert(!group.LineNumbers.empty()); 1608 1609 for (const LineNumberEntry &entry : group.LineNumbers) { 1610 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr, 1611 file_index, *lfh, entry); 1612 } 1613 LineInfo last_line(group.LineNumbers.back().Flags); 1614 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index, 1615 last_line.getEndLine(), std::move(sequence)); 1616 } 1617 } 1618 1619 if (line_table->GetSize() == 0) 1620 return false; 1621 1622 sc.comp_unit->SetLineTable(line_table.release()); 1623 return true; 1624 } 1625 1626 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) { 1627 // PDB doesn't contain information about macros 1628 return false; 1629 } 1630 1631 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles( 1632 const SymbolContext &sc, FileSpecList &support_files) { 1633 lldbassert(sc.comp_unit); 1634 1635 PdbSymUid cu_id(sc.comp_unit->GetID()); 1636 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1637 CompilandIndexItem *cci = 1638 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1639 lldbassert(cci); 1640 1641 for (llvm::StringRef f : cci->m_file_list) { 1642 FileSpec::Style style = 1643 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows; 1644 FileSpec spec(f, style); 1645 support_files.Append(spec); 1646 } 1647 1648 return true; 1649 } 1650 1651 bool SymbolFileNativePDB::ParseImportedModules( 1652 const SymbolContext &sc, std::vector<ConstString> &imported_modules) { 1653 // PDB does not yet support module debug info 1654 return false; 1655 } 1656 1657 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) { 1658 lldbassert(sc.comp_unit && sc.function); 1659 return 0; 1660 } 1661 1662 void SymbolFileNativePDB::DumpClangAST(Stream &s) { 1663 if (!m_clang) 1664 return; 1665 m_clang->Dump(s); 1666 } 1667 1668 uint32_t SymbolFileNativePDB::FindGlobalVariables( 1669 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1670 uint32_t max_matches, VariableList &variables) { 1671 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1672 1673 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName( 1674 name.GetStringRef(), m_index->symrecords()); 1675 for (const SymbolAndOffset &result : results) { 1676 VariableSP var; 1677 switch (result.second.kind()) { 1678 case SymbolKind::S_GDATA32: 1679 case SymbolKind::S_LDATA32: 1680 case SymbolKind::S_GTHREAD32: 1681 case SymbolKind::S_LTHREAD32: 1682 case SymbolKind::S_CONSTANT: { 1683 PdbGlobalSymId global{result.first, false}; 1684 var = GetOrCreateGlobalVariable(global); 1685 variables.AddVariable(var); 1686 break; 1687 } 1688 default: 1689 continue; 1690 } 1691 } 1692 return variables.GetSize(); 1693 } 1694 1695 uint32_t SymbolFileNativePDB::FindFunctions( 1696 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1697 FunctionNameType name_type_mask, bool include_inlines, bool append, 1698 SymbolContextList &sc_list) { 1699 // For now we only support lookup by method name. 1700 if (!(name_type_mask & eFunctionNameTypeMethod)) 1701 return 0; 1702 1703 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1704 1705 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName( 1706 name.GetStringRef(), m_index->symrecords()); 1707 for (const SymbolAndOffset &match : matches) { 1708 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF) 1709 continue; 1710 ProcRefSym proc(match.second.kind()); 1711 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc)); 1712 1713 if (!IsValidRecord(proc)) 1714 continue; 1715 1716 CompilandIndexItem &cci = 1717 m_index->compilands().GetOrCreateCompiland(proc.modi()); 1718 SymbolContext sc; 1719 1720 sc.comp_unit = GetOrCreateCompileUnit(cci).get(); 1721 sc.module_sp = sc.comp_unit->GetModule(); 1722 PdbCompilandSymId func_id{proc.modi(), proc.SymOffset}; 1723 sc.function = GetOrCreateFunction(func_id, sc).get(); 1724 1725 sc_list.Append(sc); 1726 } 1727 1728 return sc_list.GetSize(); 1729 } 1730 1731 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex, 1732 bool include_inlines, bool append, 1733 SymbolContextList &sc_list) { 1734 return 0; 1735 } 1736 1737 uint32_t SymbolFileNativePDB::FindTypes( 1738 const SymbolContext &sc, const ConstString &name, 1739 const CompilerDeclContext *parent_decl_ctx, bool append, 1740 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, 1741 TypeMap &types) { 1742 if (!append) 1743 types.Clear(); 1744 if (!name) 1745 return 0; 1746 1747 searched_symbol_files.clear(); 1748 searched_symbol_files.insert(this); 1749 1750 // There is an assumption 'name' is not a regex 1751 size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types); 1752 1753 return match_count; 1754 } 1755 1756 size_t 1757 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context, 1758 bool append, TypeMap &types) { 1759 return 0; 1760 } 1761 1762 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name, 1763 uint32_t max_matches, 1764 TypeMap &types) { 1765 1766 size_t match_count = 0; 1767 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name); 1768 if (max_matches > 0 && max_matches < matches.size()) 1769 matches.resize(max_matches); 1770 1771 for (TypeIndex ti : matches) { 1772 TypeSP type = GetOrCreateType(ti); 1773 if (!type) 1774 continue; 1775 1776 types.Insert(type); 1777 ++match_count; 1778 } 1779 return match_count; 1780 } 1781 1782 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; } 1783 1784 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 1785 auto iter = m_types.find(type_uid); 1786 // lldb should not be passing us non-sensical type uids. the only way it 1787 // could have a type uid in the first place is if we handed it out, in which 1788 // case we should know about the type. However, that doesn't mean we've 1789 // instantiated it yet. We can vend out a UID for a future type. So if the 1790 // type doesn't exist, let's instantiate it now. 1791 if (iter != m_types.end()) 1792 return &*iter->second; 1793 1794 PdbSymUid uid(type_uid); 1795 lldbassert(uid.kind() == PdbSymUidKind::Type); 1796 PdbTypeSymId type_id = uid.asTypeSym(); 1797 if (type_id.index.isNoneType()) 1798 return nullptr; 1799 1800 TypeSP type_sp = CreateAndCacheType(type_id); 1801 return &*type_sp; 1802 } 1803 1804 llvm::Optional<SymbolFile::ArrayInfo> 1805 SymbolFileNativePDB::GetDynamicArrayInfoForUID( 1806 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 1807 return llvm::None; 1808 } 1809 1810 1811 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) { 1812 // If this is not in our map, it's an error. 1813 clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type); 1814 lldbassert(tag_decl); 1815 auto status_iter = m_decl_to_status.find(tag_decl); 1816 lldbassert(status_iter != m_decl_to_status.end()); 1817 1818 // If it's already complete, just return. 1819 DeclStatus &status = status_iter->second; 1820 if (status.status == Type::eResolveStateFull) 1821 return true; 1822 1823 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 1824 1825 lldbassert(IsTagRecord(type_id, m_index->tpi())); 1826 1827 ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(), 1828 false); 1829 1830 // In CreateAndCacheType, we already go out of our way to resolve forward 1831 // ref UDTs to full decls, and the uids we vend out always refer to full 1832 // decls if a full decl exists in the debug info. So if we don't have a full 1833 // decl here, it means one doesn't exist in the debug info, and we can't 1834 // complete the type. 1835 CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index)); 1836 if (IsForwardRefUdt(cvt)) 1837 return false; 1838 1839 auto types_iter = m_types.find(status.uid); 1840 lldbassert(types_iter != m_types.end()); 1841 1842 if (cvt.kind() == LF_MODIFIER) { 1843 TypeIndex unmodified_type = LookThroughModifierRecord(cvt); 1844 cvt = m_index->tpi().getType(unmodified_type); 1845 // LF_MODIFIERS usually point to forward decls, so this is the one case 1846 // where we won't have been able to resolve a forward decl to a full decl 1847 // earlier on. So we need to do that now. 1848 if (IsForwardRefUdt(cvt)) { 1849 llvm::Expected<TypeIndex> expected_full_ti = 1850 m_index->tpi().findFullDeclForForwardRef(unmodified_type); 1851 if (!expected_full_ti) { 1852 llvm::consumeError(expected_full_ti.takeError()); 1853 return false; 1854 } 1855 cvt = m_index->tpi().getType(*expected_full_ti); 1856 lldbassert(!IsForwardRefUdt(cvt)); 1857 unmodified_type = *expected_full_ti; 1858 } 1859 type_id = PdbTypeSymId{unmodified_type, false}; 1860 } 1861 TypeIndex field_list_ti = GetFieldListIndex(cvt); 1862 CVType field_list_cvt = m_index->tpi().getType(field_list_ti); 1863 if (field_list_cvt.kind() != LF_FIELDLIST) 1864 return false; 1865 1866 // Visit all members of this class, then perform any finalization necessary 1867 // to complete the class. 1868 UdtRecordCompleter completer(type_id, compiler_type, *tag_decl, *this); 1869 auto error = 1870 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 1871 completer.complete(); 1872 1873 status.status = Type::eResolveStateFull; 1874 if (!error) 1875 return true; 1876 1877 llvm::consumeError(std::move(error)); 1878 return false; 1879 } 1880 1881 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1882 TypeClass type_mask, 1883 lldb_private::TypeList &type_list) { 1884 return 0; 1885 } 1886 1887 CompilerDeclContext 1888 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc, 1889 const ConstString &name, 1890 const CompilerDeclContext *parent_decl_ctx) { 1891 return {}; 1892 } 1893 1894 TypeSystem * 1895 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1896 auto type_system = 1897 m_obj_file->GetModule()->GetTypeSystemForLanguage(language); 1898 if (type_system) 1899 type_system->SetSymbolFile(this); 1900 return type_system; 1901 } 1902 1903 ConstString SymbolFileNativePDB::GetPluginName() { 1904 static ConstString g_name("pdb"); 1905 return g_name; 1906 } 1907 1908 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; } 1909