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 m_uid_to_decl[best_uid] = record_decl; 1201 m_decl_to_status[record_decl] = 1202 DeclStatus(best_uid, Type::eResolveStateForward); 1203 } 1204 return result; 1205 } 1206 1207 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) { 1208 // We can't use try_emplace / overwrite here because the process of creating 1209 // a type could create nested types, which could invalidate iterators. So 1210 // we have to do a 2-phase lookup / insert. 1211 auto iter = m_types.find(toOpaqueUid(type_id)); 1212 if (iter != m_types.end()) 1213 return iter->second; 1214 1215 return CreateAndCacheType(type_id); 1216 } 1217 1218 static DWARFExpression 1219 MakeConstantLocationExpression(TypeIndex underlying_ti, TpiStream &tpi, 1220 const ConstantSym &constant, ModuleSP module) { 1221 const ArchSpec &architecture = module->GetArchitecture(); 1222 uint32_t address_size = architecture.GetAddressByteSize(); 1223 1224 size_t size = 0; 1225 bool is_signed = false; 1226 std::tie(size, is_signed) = GetIntegralTypeInfo(underlying_ti, tpi); 1227 1228 union { 1229 llvm::support::little64_t I; 1230 llvm::support::ulittle64_t U; 1231 } Value; 1232 1233 std::shared_ptr<DataBufferHeap> buffer = std::make_shared<DataBufferHeap>(); 1234 buffer->SetByteSize(size); 1235 1236 llvm::ArrayRef<uint8_t> bytes; 1237 if (is_signed) { 1238 Value.I = constant.Value.getSExtValue(); 1239 } else { 1240 Value.U = constant.Value.getZExtValue(); 1241 } 1242 1243 bytes = llvm::makeArrayRef(reinterpret_cast<const uint8_t *>(&Value), 8) 1244 .take_front(size); 1245 buffer->CopyData(bytes.data(), size); 1246 DataExtractor extractor(buffer, lldb::eByteOrderLittle, address_size); 1247 DWARFExpression result(nullptr, extractor, nullptr, 0, size); 1248 return result; 1249 } 1250 1251 static DWARFExpression MakeGlobalLocationExpression(uint16_t section, 1252 uint32_t offset, 1253 ModuleSP module) { 1254 assert(section > 0); 1255 assert(module); 1256 1257 const ArchSpec &architecture = module->GetArchitecture(); 1258 ByteOrder byte_order = architecture.GetByteOrder(); 1259 uint32_t address_size = architecture.GetAddressByteSize(); 1260 uint32_t byte_size = architecture.GetDataByteSize(); 1261 assert(byte_order != eByteOrderInvalid && address_size != 0); 1262 1263 RegisterKind register_kind = eRegisterKindDWARF; 1264 StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); 1265 stream.PutHex8(DW_OP_addr); 1266 1267 SectionList *section_list = module->GetSectionList(); 1268 assert(section_list); 1269 1270 // Section indices in PDB are 1-based, but in DWARF they are 0-based, so we 1271 // need to subtract 1. 1272 uint32_t section_idx = section - 1; 1273 if (section_idx >= section_list->GetSize()) 1274 return DWARFExpression(nullptr); 1275 1276 auto section_ptr = section_list->GetSectionAtIndex(section_idx); 1277 if (!section_ptr) 1278 return DWARFExpression(nullptr); 1279 1280 stream.PutMaxHex64(section_ptr->GetFileAddress() + offset, address_size, 1281 byte_order); 1282 DataBufferSP buffer = 1283 std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize()); 1284 DataExtractor extractor(buffer, byte_order, address_size, byte_size); 1285 DWARFExpression result(module, extractor, nullptr, 0, buffer->GetByteSize()); 1286 result.SetRegisterKind(register_kind); 1287 return result; 1288 } 1289 1290 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) { 1291 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset); 1292 if (sym.kind() == S_CONSTANT) 1293 return CreateConstantSymbol(var_id, sym); 1294 1295 lldb::ValueType scope = eValueTypeInvalid; 1296 TypeIndex ti; 1297 llvm::StringRef name; 1298 lldb::addr_t addr = 0; 1299 uint16_t section = 0; 1300 uint32_t offset = 0; 1301 bool is_external = false; 1302 switch (sym.kind()) { 1303 case S_GDATA32: 1304 is_external = true; 1305 LLVM_FALLTHROUGH; 1306 case S_LDATA32: { 1307 DataSym ds(sym.kind()); 1308 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds)); 1309 ti = ds.Type; 1310 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal 1311 : eValueTypeVariableStatic; 1312 name = ds.Name; 1313 section = ds.Segment; 1314 offset = ds.DataOffset; 1315 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset); 1316 break; 1317 } 1318 case S_GTHREAD32: 1319 is_external = true; 1320 LLVM_FALLTHROUGH; 1321 case S_LTHREAD32: { 1322 ThreadLocalDataSym tlds(sym.kind()); 1323 llvm::cantFail( 1324 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)); 1325 ti = tlds.Type; 1326 name = tlds.Name; 1327 section = tlds.Segment; 1328 offset = tlds.DataOffset; 1329 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset); 1330 scope = eValueTypeVariableThreadLocal; 1331 break; 1332 } 1333 default: 1334 llvm_unreachable("unreachable!"); 1335 } 1336 1337 CompUnitSP comp_unit; 1338 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr); 1339 if (modi) { 1340 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi); 1341 comp_unit = GetOrCreateCompileUnit(cci); 1342 } 1343 1344 Declaration decl; 1345 PdbTypeSymId tid(ti, false); 1346 SymbolFileTypeSP type_sp = 1347 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 1348 Variable::RangeList ranges; 1349 1350 DWARFExpression location = MakeGlobalLocationExpression( 1351 section, offset, GetObjectFile()->GetModule()); 1352 1353 std::string global_name("::"); 1354 global_name += name; 1355 VariableSP var_sp = std::make_shared<Variable>( 1356 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp, 1357 scope, comp_unit.get(), ranges, &decl, location, is_external, false, 1358 false); 1359 var_sp->SetLocationIsConstantValueData(false); 1360 1361 return var_sp; 1362 } 1363 1364 lldb::VariableSP 1365 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id, 1366 const CVSymbol &cvs) { 1367 TpiStream &tpi = m_index->tpi(); 1368 ConstantSym constant(cvs.kind()); 1369 1370 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)); 1371 std::string global_name("::"); 1372 global_name += constant.Name; 1373 PdbTypeSymId tid(constant.Type, false); 1374 SymbolFileTypeSP type_sp = 1375 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); 1376 1377 Declaration decl; 1378 Variable::RangeList ranges; 1379 ModuleSP module = GetObjectFile()->GetModule(); 1380 DWARFExpression location = 1381 MakeConstantLocationExpression(constant.Type, tpi, constant, module); 1382 1383 VariableSP var_sp = std::make_shared<Variable>( 1384 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(), 1385 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location, 1386 false, false, false); 1387 var_sp->SetLocationIsConstantValueData(true); 1388 return var_sp; 1389 } 1390 1391 VariableSP 1392 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) { 1393 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr); 1394 if (emplace_result.second) 1395 emplace_result.first->second = CreateGlobalVariable(var_id); 1396 1397 return emplace_result.first->second; 1398 } 1399 1400 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) { 1401 return GetOrCreateType(PdbTypeSymId(ti, false)); 1402 } 1403 1404 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id, 1405 const SymbolContext &sc) { 1406 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr); 1407 if (emplace_result.second) 1408 emplace_result.first->second = CreateFunction(func_id, sc); 1409 1410 lldbassert(emplace_result.first->second); 1411 return emplace_result.first->second; 1412 } 1413 1414 CompUnitSP 1415 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) { 1416 1417 auto emplace_result = 1418 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr); 1419 if (emplace_result.second) 1420 emplace_result.first->second = CreateCompileUnit(cci); 1421 1422 lldbassert(emplace_result.first->second); 1423 return emplace_result.first->second; 1424 } 1425 1426 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) { 1427 if (index >= GetNumCompileUnits()) 1428 return CompUnitSP(); 1429 lldbassert(index < UINT16_MAX); 1430 if (index >= UINT16_MAX) 1431 return nullptr; 1432 1433 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index); 1434 1435 return GetOrCreateCompileUnit(item); 1436 } 1437 1438 lldb::LanguageType 1439 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) { 1440 // What fields should I expect to be filled out on the SymbolContext? Is it 1441 // safe to assume that `sc.comp_unit` is valid? 1442 if (!sc.comp_unit) 1443 return lldb::eLanguageTypeUnknown; 1444 PdbSymUid uid(sc.comp_unit->GetID()); 1445 lldbassert(uid.kind() == PdbSymUidKind::Compiland); 1446 1447 CompilandIndexItem *item = 1448 m_index->compilands().GetCompiland(uid.asCompiland().modi); 1449 lldbassert(item); 1450 if (!item->m_compile_opts) 1451 return lldb::eLanguageTypeUnknown; 1452 1453 return TranslateLanguage(item->m_compile_opts->getLanguage()); 1454 } 1455 1456 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) { 1457 lldbassert(sc.comp_unit); 1458 return false; 1459 } 1460 1461 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) { 1462 // If any of these flags are set, we need to resolve the compile unit. 1463 uint32_t flags = eSymbolContextCompUnit; 1464 flags |= eSymbolContextVariable; 1465 flags |= eSymbolContextFunction; 1466 flags |= eSymbolContextBlock; 1467 flags |= eSymbolContextLineEntry; 1468 return (resolve_scope & flags) != 0; 1469 } 1470 1471 uint32_t SymbolFileNativePDB::ResolveSymbolContext( 1472 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) { 1473 uint32_t resolved_flags = 0; 1474 lldb::addr_t file_addr = addr.GetFileAddress(); 1475 1476 if (NeedsResolvedCompileUnit(resolve_scope)) { 1477 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr); 1478 if (!modi) 1479 return 0; 1480 CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi); 1481 if (!cci) 1482 return 0; 1483 1484 sc.comp_unit = GetOrCreateCompileUnit(*cci).get(); 1485 resolved_flags |= eSymbolContextCompUnit; 1486 } 1487 1488 if (resolve_scope & eSymbolContextFunction) { 1489 lldbassert(sc.comp_unit); 1490 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr); 1491 for (const auto &match : matches) { 1492 if (match.uid.kind() != PdbSymUidKind::CompilandSym) 1493 continue; 1494 PdbCompilandSymId csid = match.uid.asCompilandSym(); 1495 CVSymbol cvs = m_index->ReadSymbolRecord(csid); 1496 if (CVSymToPDBSym(cvs.kind()) != PDB_SymType::Function) 1497 continue; 1498 sc.function = GetOrCreateFunction(csid, sc).get(); 1499 } 1500 resolved_flags |= eSymbolContextFunction; 1501 } 1502 1503 if (resolve_scope & eSymbolContextLineEntry) { 1504 lldbassert(sc.comp_unit); 1505 if (auto *line_table = sc.comp_unit->GetLineTable()) { 1506 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 1507 resolved_flags |= eSymbolContextLineEntry; 1508 } 1509 } 1510 1511 return resolved_flags; 1512 } 1513 1514 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence, 1515 const CompilandIndexItem &cci, 1516 lldb::addr_t base_addr, 1517 uint32_t file_number, 1518 const LineFragmentHeader &block, 1519 const LineNumberEntry &cur) { 1520 LineInfo cur_info(cur.Flags); 1521 1522 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto()) 1523 return; 1524 1525 uint64_t addr = base_addr + cur.Offset; 1526 1527 bool is_statement = cur_info.isStatement(); 1528 bool is_prologue = IsFunctionPrologue(cci, addr); 1529 bool is_epilogue = IsFunctionEpilogue(cci, addr); 1530 1531 uint32_t lno = cur_info.getStartLine(); 1532 1533 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number, 1534 is_statement, false, is_prologue, is_epilogue, 1535 false); 1536 } 1537 1538 static void TerminateLineSequence(LineTable &table, 1539 const LineFragmentHeader &block, 1540 lldb::addr_t base_addr, uint32_t file_number, 1541 uint32_t last_line, 1542 std::unique_ptr<LineSequence> seq) { 1543 // The end is always a terminal entry, so insert it regardless. 1544 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize, 1545 last_line, 0, file_number, false, false, 1546 false, false, true); 1547 table.InsertSequence(seq.release()); 1548 } 1549 1550 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) { 1551 // Unfortunately LLDB is set up to parse the entire compile unit line table 1552 // all at once, even if all it really needs is line info for a specific 1553 // function. In the future it would be nice if it could set the sc.m_function 1554 // member, and we could only get the line info for the function in question. 1555 lldbassert(sc.comp_unit); 1556 PdbSymUid cu_id(sc.comp_unit->GetID()); 1557 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1558 CompilandIndexItem *cci = 1559 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1560 lldbassert(cci); 1561 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit); 1562 1563 // This is basically a copy of the .debug$S subsections from all original COFF 1564 // object files merged together with address relocations applied. We are 1565 // looking for all DEBUG_S_LINES subsections. 1566 for (const DebugSubsectionRecord &dssr : 1567 cci->m_debug_stream.getSubsectionsArray()) { 1568 if (dssr.kind() != DebugSubsectionKind::Lines) 1569 continue; 1570 1571 DebugLinesSubsectionRef lines; 1572 llvm::BinaryStreamReader reader(dssr.getRecordData()); 1573 if (auto EC = lines.initialize(reader)) { 1574 llvm::consumeError(std::move(EC)); 1575 return false; 1576 } 1577 1578 const LineFragmentHeader *lfh = lines.header(); 1579 uint64_t virtual_addr = 1580 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset); 1581 1582 const auto &checksums = cci->m_strings.checksums().getArray(); 1583 const auto &strings = cci->m_strings.strings(); 1584 for (const LineColumnEntry &group : lines) { 1585 // Indices in this structure are actually offsets of records in the 1586 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index 1587 // into the global PDB string table. 1588 auto iter = checksums.at(group.NameIndex); 1589 if (iter == checksums.end()) 1590 continue; 1591 1592 llvm::Expected<llvm::StringRef> efn = 1593 strings.getString(iter->FileNameOffset); 1594 if (!efn) { 1595 llvm::consumeError(efn.takeError()); 1596 continue; 1597 } 1598 1599 // LLDB wants the index of the file in the list of support files. 1600 auto fn_iter = llvm::find(cci->m_file_list, *efn); 1601 lldbassert(fn_iter != cci->m_file_list.end()); 1602 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter); 1603 1604 std::unique_ptr<LineSequence> sequence( 1605 line_table->CreateLineSequenceContainer()); 1606 lldbassert(!group.LineNumbers.empty()); 1607 1608 for (const LineNumberEntry &entry : group.LineNumbers) { 1609 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr, 1610 file_index, *lfh, entry); 1611 } 1612 LineInfo last_line(group.LineNumbers.back().Flags); 1613 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index, 1614 last_line.getEndLine(), std::move(sequence)); 1615 } 1616 } 1617 1618 if (line_table->GetSize() == 0) 1619 return false; 1620 1621 sc.comp_unit->SetLineTable(line_table.release()); 1622 return true; 1623 } 1624 1625 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) { 1626 // PDB doesn't contain information about macros 1627 return false; 1628 } 1629 1630 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles( 1631 const SymbolContext &sc, FileSpecList &support_files) { 1632 lldbassert(sc.comp_unit); 1633 1634 PdbSymUid cu_id(sc.comp_unit->GetID()); 1635 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland); 1636 CompilandIndexItem *cci = 1637 m_index->compilands().GetCompiland(cu_id.asCompiland().modi); 1638 lldbassert(cci); 1639 1640 for (llvm::StringRef f : cci->m_file_list) { 1641 FileSpec::Style style = 1642 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows; 1643 FileSpec spec(f, style); 1644 support_files.Append(spec); 1645 } 1646 1647 return true; 1648 } 1649 1650 bool SymbolFileNativePDB::ParseImportedModules( 1651 const SymbolContext &sc, std::vector<ConstString> &imported_modules) { 1652 // PDB does not yet support module debug info 1653 return false; 1654 } 1655 1656 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) { 1657 lldbassert(sc.comp_unit && sc.function); 1658 return 0; 1659 } 1660 1661 void SymbolFileNativePDB::DumpClangAST(Stream &s) { 1662 if (!m_clang) 1663 return; 1664 m_clang->Dump(s); 1665 } 1666 1667 uint32_t SymbolFileNativePDB::FindGlobalVariables( 1668 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1669 uint32_t max_matches, VariableList &variables) { 1670 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1671 1672 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName( 1673 name.GetStringRef(), m_index->symrecords()); 1674 for (const SymbolAndOffset &result : results) { 1675 VariableSP var; 1676 switch (result.second.kind()) { 1677 case SymbolKind::S_GDATA32: 1678 case SymbolKind::S_LDATA32: 1679 case SymbolKind::S_GTHREAD32: 1680 case SymbolKind::S_LTHREAD32: 1681 case SymbolKind::S_CONSTANT: { 1682 PdbGlobalSymId global(result.first, false); 1683 var = GetOrCreateGlobalVariable(global); 1684 variables.AddVariable(var); 1685 break; 1686 } 1687 default: 1688 continue; 1689 } 1690 } 1691 return variables.GetSize(); 1692 } 1693 1694 uint32_t SymbolFileNativePDB::FindFunctions( 1695 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1696 FunctionNameType name_type_mask, bool include_inlines, bool append, 1697 SymbolContextList &sc_list) { 1698 // For now we only support lookup by method name. 1699 if (!(name_type_mask & eFunctionNameTypeMethod)) 1700 return 0; 1701 1702 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1703 1704 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName( 1705 name.GetStringRef(), m_index->symrecords()); 1706 for (const SymbolAndOffset &match : matches) { 1707 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF) 1708 continue; 1709 ProcRefSym proc(match.second.kind()); 1710 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc)); 1711 1712 if (!IsValidRecord(proc)) 1713 continue; 1714 1715 CompilandIndexItem &cci = 1716 m_index->compilands().GetOrCreateCompiland(proc.modi()); 1717 SymbolContext sc; 1718 1719 sc.comp_unit = GetOrCreateCompileUnit(cci).get(); 1720 sc.module_sp = sc.comp_unit->GetModule(); 1721 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset); 1722 sc.function = GetOrCreateFunction(func_id, sc).get(); 1723 1724 sc_list.Append(sc); 1725 } 1726 1727 return sc_list.GetSize(); 1728 } 1729 1730 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex, 1731 bool include_inlines, bool append, 1732 SymbolContextList &sc_list) { 1733 return 0; 1734 } 1735 1736 uint32_t SymbolFileNativePDB::FindTypes( 1737 const SymbolContext &sc, const ConstString &name, 1738 const CompilerDeclContext *parent_decl_ctx, bool append, 1739 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, 1740 TypeMap &types) { 1741 if (!append) 1742 types.Clear(); 1743 if (!name) 1744 return 0; 1745 1746 searched_symbol_files.clear(); 1747 searched_symbol_files.insert(this); 1748 1749 // There is an assumption 'name' is not a regex 1750 size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types); 1751 1752 return match_count; 1753 } 1754 1755 size_t 1756 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context, 1757 bool append, TypeMap &types) { 1758 return 0; 1759 } 1760 1761 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name, 1762 uint32_t max_matches, 1763 TypeMap &types) { 1764 1765 size_t match_count = 0; 1766 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name); 1767 if (max_matches > 0 && max_matches < matches.size()) 1768 matches.resize(max_matches); 1769 1770 for (TypeIndex ti : matches) { 1771 TypeSP type = GetOrCreateType(ti); 1772 if (!type) 1773 continue; 1774 1775 types.Insert(type); 1776 ++match_count; 1777 } 1778 return match_count; 1779 } 1780 1781 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; } 1782 1783 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 1784 auto iter = m_types.find(type_uid); 1785 // lldb should not be passing us non-sensical type uids. the only way it 1786 // could have a type uid in the first place is if we handed it out, in which 1787 // case we should know about the type. However, that doesn't mean we've 1788 // instantiated it yet. We can vend out a UID for a future type. So if the 1789 // type doesn't exist, let's instantiate it now. 1790 if (iter != m_types.end()) 1791 return &*iter->second; 1792 1793 PdbSymUid uid(type_uid); 1794 lldbassert(uid.kind() == PdbSymUidKind::Type); 1795 PdbTypeSymId type_id = uid.asTypeSym(); 1796 if (type_id.index.isNoneType()) 1797 return nullptr; 1798 1799 TypeSP type_sp = CreateAndCacheType(type_id); 1800 return &*type_sp; 1801 } 1802 1803 llvm::Optional<SymbolFile::ArrayInfo> 1804 SymbolFileNativePDB::GetDynamicArrayInfoForUID( 1805 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 1806 return llvm::None; 1807 } 1808 1809 1810 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) { 1811 // If this is not in our map, it's an error. 1812 clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type); 1813 lldbassert(tag_decl); 1814 auto status_iter = m_decl_to_status.find(tag_decl); 1815 lldbassert(status_iter != m_decl_to_status.end()); 1816 1817 // If it's already complete, just return. 1818 DeclStatus &status = status_iter->second; 1819 if (status.status == Type::eResolveStateFull) 1820 return true; 1821 1822 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 1823 1824 lldbassert(IsTagRecord(type_id, m_index->tpi())); 1825 1826 ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(), 1827 false); 1828 1829 // In CreateAndCacheType, we already go out of our way to resolve forward 1830 // ref UDTs to full decls, and the uids we vend out always refer to full 1831 // decls if a full decl exists in the debug info. So if we don't have a full 1832 // decl here, it means one doesn't exist in the debug info, and we can't 1833 // complete the type. 1834 CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index)); 1835 if (IsForwardRefUdt(cvt)) 1836 return false; 1837 1838 auto types_iter = m_types.find(status.uid); 1839 lldbassert(types_iter != m_types.end()); 1840 1841 if (cvt.kind() == LF_MODIFIER) { 1842 TypeIndex unmodified_type = LookThroughModifierRecord(cvt); 1843 cvt = m_index->tpi().getType(unmodified_type); 1844 // LF_MODIFIERS usually point to forward decls, so this is the one case 1845 // where we won't have been able to resolve a forward decl to a full decl 1846 // earlier on. So we need to do that now. 1847 if (IsForwardRefUdt(cvt)) { 1848 llvm::Expected<TypeIndex> expected_full_ti = 1849 m_index->tpi().findFullDeclForForwardRef(unmodified_type); 1850 if (!expected_full_ti) { 1851 llvm::consumeError(expected_full_ti.takeError()); 1852 return false; 1853 } 1854 cvt = m_index->tpi().getType(*expected_full_ti); 1855 lldbassert(!IsForwardRefUdt(cvt)); 1856 unmodified_type = *expected_full_ti; 1857 } 1858 type_id = PdbTypeSymId(unmodified_type, false); 1859 } 1860 TypeIndex field_list_ti = GetFieldListIndex(cvt); 1861 CVType field_list_cvt = m_index->tpi().getType(field_list_ti); 1862 if (field_list_cvt.kind() != LF_FIELDLIST) 1863 return false; 1864 1865 // Visit all members of this class, then perform any finalization necessary 1866 // to complete the class. 1867 UdtRecordCompleter completer(type_id, compiler_type, *tag_decl, *this); 1868 auto error = 1869 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 1870 completer.complete(); 1871 1872 status.status = Type::eResolveStateFull; 1873 if (!error) 1874 return true; 1875 1876 llvm::consumeError(std::move(error)); 1877 return false; 1878 } 1879 1880 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1881 TypeClass type_mask, 1882 lldb_private::TypeList &type_list) { 1883 return 0; 1884 } 1885 1886 CompilerDeclContext 1887 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc, 1888 const ConstString &name, 1889 const CompilerDeclContext *parent_decl_ctx) { 1890 return {}; 1891 } 1892 1893 TypeSystem * 1894 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1895 auto type_system = 1896 m_obj_file->GetModule()->GetTypeSystemForLanguage(language); 1897 if (type_system) 1898 type_system->SetSymbolFile(this); 1899 return type_system; 1900 } 1901 1902 ConstString SymbolFileNativePDB::GetPluginName() { 1903 static ConstString g_name("pdb"); 1904 return g_name; 1905 } 1906 1907 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; } 1908