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