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(PdbSymUid func_uid, 711 const SymbolContext &sc) { 712 lldbassert(func_uid.tag() == PDB_SymType::Function); 713 714 PdbSymUid cuid = PdbSymUid::makeCompilandId(func_uid.asCuSym().modi); 715 716 const CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid); 717 lldbassert(cci); 718 CVSymbol sym_record = 719 cci->m_debug_stream.readSymbolAtOffset(func_uid.asCuSym().offset); 720 721 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32); 722 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record); 723 724 auto file_vm_addr = m_index->MakeVirtualAddress(sol.so); 725 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0) 726 return nullptr; 727 728 AddressRange func_range(file_vm_addr, sol.length, 729 sc.module_sp->GetSectionList()); 730 if (!func_range.GetBaseAddress().IsValid()) 731 return nullptr; 732 733 Type *func_type = nullptr; 734 735 // FIXME: Resolve types and mangled names. 736 PdbSymUid sig_uid = 737 PdbSymUid::makeTypeSymId(PDB_SymType::FunctionSig, TypeIndex{0}, false); 738 Mangled mangled(getSymbolName(sym_record)); 739 FunctionSP func_sp = std::make_shared<Function>( 740 sc.comp_unit, func_uid.toOpaqueId(), sig_uid.toOpaqueId(), mangled, 741 func_type, func_range); 742 743 sc.comp_unit->AddFunction(func_sp); 744 return func_sp; 745 } 746 747 CompUnitSP 748 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) { 749 lldb::LanguageType lang = 750 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage()) 751 : lldb::eLanguageTypeUnknown; 752 753 LazyBool optimized = eLazyBoolNo; 754 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations()) 755 optimized = eLazyBoolYes; 756 757 llvm::StringRef source_file_name = 758 m_index->compilands().GetMainSourceFile(cci); 759 FileSpec fs(source_file_name); 760 761 CompUnitSP cu_sp = 762 std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs, 763 cci.m_uid.toOpaqueId(), lang, optimized); 764 765 const PdbCompilandId &cuid = cci.m_uid.asCompiland(); 766 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cuid.modi, 767 cu_sp); 768 return cu_sp; 769 } 770 771 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbSymUid type_uid, 772 const ModifierRecord &mr) { 773 TpiStream &stream = m_index->tpi(); 774 775 TypeSP t = GetOrCreateType(mr.ModifiedType); 776 CompilerType ct = t->GetForwardCompilerType(); 777 if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 778 ct = ct.AddConstModifier(); 779 if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 780 ct = ct.AddVolatileModifier(); 781 std::string name; 782 if (mr.ModifiedType.isSimple()) 783 name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind()); 784 else 785 name = computeTypeName(stream.typeCollection(), mr.ModifiedType); 786 Declaration decl; 787 return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(), 788 ConstString(name), t->GetByteSize(), nullptr, 789 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 790 ct, Type::eResolveStateFull); 791 } 792 793 lldb::TypeSP SymbolFileNativePDB::CreatePointerType( 794 PdbSymUid type_uid, const llvm::codeview::PointerRecord &pr) { 795 TypeSP pointee = GetOrCreateType(pr.ReferentType); 796 if (!pointee) 797 return nullptr; 798 CompilerType pointee_ct = pointee->GetForwardCompilerType(); 799 lldbassert(pointee_ct); 800 Declaration decl; 801 802 if (pr.isPointerToMember()) { 803 MemberPointerInfo mpi = pr.getMemberInfo(); 804 TypeSP class_type = GetOrCreateType(mpi.ContainingType); 805 806 CompilerType ct = ClangASTContext::CreateMemberPointerType( 807 class_type->GetLayoutCompilerType(), pointee_ct); 808 809 return std::make_shared<Type>( 810 type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(), 811 pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct, 812 Type::eResolveStateFull); 813 } 814 815 CompilerType pointer_ct = pointee_ct; 816 if (pr.getMode() == PointerMode::LValueReference) 817 pointer_ct = pointer_ct.GetLValueReferenceType(); 818 else if (pr.getMode() == PointerMode::RValueReference) 819 pointer_ct = pointer_ct.GetRValueReferenceType(); 820 else 821 pointer_ct = pointer_ct.GetPointerType(); 822 823 if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None) 824 pointer_ct = pointer_ct.AddConstModifier(); 825 826 if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 827 pointer_ct = pointer_ct.AddVolatileModifier(); 828 829 if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 830 pointer_ct = pointer_ct.AddRestrictModifier(); 831 832 return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(), 833 ConstString(), pr.getSize(), nullptr, 834 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 835 pointer_ct, Type::eResolveStateFull); 836 } 837 838 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) { 839 if (ti == TypeIndex::NullptrT()) { 840 PdbSymUid uid = 841 PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false); 842 CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr); 843 Declaration decl; 844 return std::make_shared<Type>(uid.toOpaqueId(), this, 845 ConstString("std::nullptr_t"), 0, nullptr, 846 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 847 ct, Type::eResolveStateFull); 848 } 849 850 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 851 PdbSymUid uid = 852 PdbSymUid::makeTypeSymId(PDB_SymType::PointerType, ti, false); 853 TypeSP direct_sp = GetOrCreateType(ti.makeDirect()); 854 CompilerType ct = direct_sp->GetFullCompilerType(); 855 ct = ct.GetPointerType(); 856 uint32_t pointer_size = 0; 857 switch (ti.getSimpleMode()) { 858 case SimpleTypeMode::FarPointer32: 859 case SimpleTypeMode::NearPointer32: 860 pointer_size = 4; 861 break; 862 case SimpleTypeMode::NearPointer64: 863 pointer_size = 8; 864 break; 865 default: 866 // 128-bit and 16-bit pointers unsupported. 867 return nullptr; 868 } 869 Declaration decl; 870 return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(), 871 ConstString(), pointer_size, nullptr, 872 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 873 ct, Type::eResolveStateFull); 874 } 875 876 PdbSymUid uid = PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false); 877 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 878 return nullptr; 879 880 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 881 if (bt == lldb::eBasicTypeInvalid) 882 return nullptr; 883 CompilerType ct = m_clang->GetBasicType(bt); 884 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind()); 885 886 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind()); 887 888 Declaration decl; 889 return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(), 890 ConstString(type_name), size, nullptr, 891 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 892 ct, Type::eResolveStateFull); 893 } 894 895 static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) { 896 OutputStream OS; 897 initializeOutputStream(nullptr, nullptr, OS, 1024); 898 n->output(OS, llvm::ms_demangle::OF_Default); 899 OS << '\0'; 900 return {OS.getBuffer()}; 901 } 902 903 static bool 904 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) { 905 for (llvm::ms_demangle::Node *n : scopes) { 906 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n); 907 if (idn->TemplateParams) 908 return true; 909 } 910 return false; 911 } 912 913 std::pair<clang::DeclContext *, std::string> 914 SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record, 915 TypeIndex ti) { 916 llvm::ms_demangle::Demangler demangler; 917 StringView sv(record.UniqueName.begin(), record.UniqueName.size()); 918 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); 919 llvm::ms_demangle::IdentifierNode *idn = 920 ttn->QualifiedName->getUnqualifiedIdentifier(); 921 std::string uname = RenderDemanglerNode(idn); 922 923 llvm::ms_demangle::NodeArrayNode *name_components = 924 ttn->QualifiedName->Components; 925 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes, 926 name_components->Count - 1); 927 928 clang::DeclContext *context = m_clang->GetTranslationUnitDecl(); 929 930 // If this type doesn't have a parent type in the debug info, then the best we 931 // can do is to say that it's either a series of namespaces (if the scope is 932 // non-empty), or the translation unit (if the scope is empty). 933 auto parent_iter = m_parent_types.find(ti); 934 if (parent_iter == m_parent_types.end()) { 935 if (scopes.empty()) 936 return {context, uname}; 937 938 // If there is no parent in the debug info, but some of the scopes have 939 // template params, then this is a case of bad debug info. See, for 940 // example, llvm.org/pr39607. We don't want to create an ambiguity between 941 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at 942 // global scope with the fully qualified name. 943 if (AnyScopesHaveTemplateParams(scopes)) 944 return {context, record.Name}; 945 946 for (llvm::ms_demangle::Node *scope : scopes) { 947 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope); 948 std::string str = RenderDemanglerNode(nii); 949 context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context); 950 } 951 return {context, uname}; 952 } 953 954 // Otherwise, all we need to do is get the parent type of this type and 955 // recurse into our lazy type creation / AST reconstruction logic to get an 956 // LLDB TypeSP for the parent. This will cause the AST to automatically get 957 // the right DeclContext created for any parent. 958 TypeSP parent = GetOrCreateType(parent_iter->second); 959 if (!parent) 960 return {context, uname}; 961 CompilerType parent_ct = parent->GetForwardCompilerType(); 962 clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct); 963 context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl()); 964 return {context, uname}; 965 } 966 967 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion( 968 PdbSymUid type_uid, const llvm::codeview::TagRecord &record, size_t size, 969 clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) { 970 971 const PdbTypeSymId &tid = type_uid.asTypeSym(); 972 TypeIndex ti(tid.index); 973 clang::DeclContext *decl_context = nullptr; 974 std::string uname; 975 std::tie(decl_context, uname) = CreateDeclInfoForType(record, ti); 976 977 lldb::AccessType access = 978 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 979 980 ClangASTMetadata metadata; 981 metadata.SetUserID(type_uid.toOpaqueId()); 982 metadata.SetIsDynamicCXXType(false); 983 984 CompilerType ct = 985 m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk, 986 lldb::eLanguageTypeC_plus_plus, &metadata); 987 988 lldbassert(ct.IsValid()); 989 990 clang::CXXRecordDecl *record_decl = 991 m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType()); 992 lldbassert(record_decl); 993 994 clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit( 995 *m_clang->getASTContext(), inheritance); 996 record_decl->addAttr(attr); 997 998 ClangASTContext::StartTagDeclarationDefinition(ct); 999 1000 // Even if it's possible, don't complete it at this point. Just mark it 1001 // forward resolved, and if/when LLDB needs the full definition, it can 1002 // ask us. 1003 ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true); 1004 1005 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE. 1006 Declaration decl; 1007 return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(), 1008 ConstString(uname), size, nullptr, 1009 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, 1010 ct, Type::eResolveStateForward); 1011 } 1012 1013 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid, 1014 const ClassRecord &cr) { 1015 clang::TagTypeKind ttk = TranslateUdtKind(cr); 1016 1017 clang::MSInheritanceAttr::Spelling inheritance = 1018 GetMSInheritance(m_index->tpi().typeCollection(), cr); 1019 return CreateClassStructUnion(type_uid, cr, cr.getSize(), ttk, inheritance); 1020 } 1021 1022 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid, 1023 const UnionRecord &ur) { 1024 return CreateClassStructUnion( 1025 type_uid, ur, ur.getSize(), clang::TTK_Union, 1026 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance); 1027 } 1028 1029 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid, 1030 const EnumRecord &er) { 1031 const PdbTypeSymId &tid = type_uid.asTypeSym(); 1032 TypeIndex ti(tid.index); 1033 clang::DeclContext *decl_context = nullptr; 1034 std::string uname; 1035 std::tie(decl_context, uname) = CreateDeclInfoForType(er, ti); 1036 1037 Declaration decl; 1038 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType); 1039 CompilerType enum_ct = m_clang->CreateEnumerationType( 1040 uname.c_str(), decl_context, decl, underlying_type->GetFullCompilerType(), 1041 er.isScoped()); 1042 1043 ClangASTContext::StartTagDeclarationDefinition(enum_ct); 1044 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1045 1046 // We're just going to forward resolve this for now. We'll complete 1047 // it only if the user requests. 1048 return std::make_shared<lldb_private::Type>( 1049 type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(uname), 1050 underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID, 1051 lldb_private::Type::eEncodingIsUID, decl, enum_ct, 1052 lldb_private::Type::eResolveStateForward); 1053 } 1054 1055 TypeSP SymbolFileNativePDB::CreateArrayType(PdbSymUid type_uid, 1056 const ArrayRecord &ar) { 1057 TypeSP element_type = GetOrCreateType(ar.ElementType); 1058 uint64_t element_count = ar.Size / element_type->GetByteSize(); 1059 1060 CompilerType element_ct = element_type->GetFullCompilerType(); 1061 1062 CompilerType array_ct = 1063 m_clang->CreateArrayType(element_ct, element_count, false); 1064 1065 Declaration decl; 1066 TypeSP array_sp = std::make_shared<lldb_private::Type>( 1067 type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(), ar.Size, 1068 nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, 1069 array_ct, lldb_private::Type::eResolveStateFull); 1070 array_sp->SetEncodingType(element_type.get()); 1071 return array_sp; 1072 } 1073 1074 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbSymUid type_uid, 1075 const ProcedureRecord &pr) { 1076 TpiStream &stream = m_index->tpi(); 1077 CVType args_cvt = stream.getType(pr.ArgumentList); 1078 ArgListRecord args; 1079 llvm::cantFail( 1080 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1081 1082 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1083 bool is_variadic = IsCVarArgsFunction(arg_indices); 1084 if (is_variadic) 1085 arg_indices = arg_indices.drop_back(); 1086 1087 std::vector<CompilerType> arg_list; 1088 arg_list.reserve(arg_list.size()); 1089 1090 for (TypeIndex arg_index : arg_indices) { 1091 TypeSP arg_sp = GetOrCreateType(arg_index); 1092 if (!arg_sp) 1093 return nullptr; 1094 arg_list.push_back(arg_sp->GetFullCompilerType()); 1095 } 1096 1097 TypeSP return_type_sp = GetOrCreateType(pr.ReturnType); 1098 if (!return_type_sp) 1099 return nullptr; 1100 1101 llvm::Optional<clang::CallingConv> cc = 1102 TranslateCallingConvention(pr.CallConv); 1103 if (!cc) 1104 return nullptr; 1105 1106 CompilerType return_ct = return_type_sp->GetFullCompilerType(); 1107 CompilerType func_sig_ast_type = m_clang->CreateFunctionType( 1108 return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc); 1109 1110 Declaration decl; 1111 return std::make_shared<lldb_private::Type>( 1112 type_uid.toOpaqueId(), this, ConstString(), 0, nullptr, LLDB_INVALID_UID, 1113 lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type, 1114 lldb_private::Type::eResolveStateFull); 1115 } 1116 1117 TypeSP SymbolFileNativePDB::CreateType(PdbSymUid type_uid) { 1118 const PdbTypeSymId &tsid = type_uid.asTypeSym(); 1119 TypeIndex index(tsid.index); 1120 1121 if (index.getIndex() < TypeIndex::FirstNonSimpleIndex) 1122 return CreateSimpleType(index); 1123 1124 TpiStream &stream = tsid.is_ipi ? m_index->ipi() : m_index->tpi(); 1125 CVType cvt = stream.getType(index); 1126 1127 if (cvt.kind() == LF_MODIFIER) { 1128 ModifierRecord modifier; 1129 llvm::cantFail( 1130 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 1131 return CreateModifierType(type_uid, modifier); 1132 } 1133 1134 if (cvt.kind() == LF_POINTER) { 1135 PointerRecord pointer; 1136 llvm::cantFail( 1137 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 1138 return CreatePointerType(type_uid, pointer); 1139 } 1140 1141 if (IsClassRecord(cvt.kind())) { 1142 ClassRecord cr; 1143 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr)); 1144 return CreateTagType(type_uid, cr); 1145 } 1146 1147 if (cvt.kind() == LF_ENUM) { 1148 EnumRecord er; 1149 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)); 1150 return CreateTagType(type_uid, er); 1151 } 1152 1153 if (cvt.kind() == LF_UNION) { 1154 UnionRecord ur; 1155 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur)); 1156 return CreateTagType(type_uid, ur); 1157 } 1158 1159 if (cvt.kind() == LF_ARRAY) { 1160 ArrayRecord ar; 1161 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 1162 return CreateArrayType(type_uid, ar); 1163 } 1164 1165 if (cvt.kind() == LF_PROCEDURE) { 1166 ProcedureRecord pr; 1167 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 1168 return CreateProcedureType(type_uid, pr); 1169 } 1170 1171 return nullptr; 1172 } 1173 1174 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbSymUid type_uid) { 1175 // If they search for a UDT which is a forward ref, try and resolve the full 1176 // decl and just map the forward ref uid to the full decl record. 1177 llvm::Optional<PdbSymUid> full_decl_uid; 1178 if (type_uid.tag() == PDB_SymType::UDT || 1179 type_uid.tag() == PDB_SymType::Enum) { 1180 const PdbTypeSymId &type_id = type_uid.asTypeSym(); 1181 TypeIndex ti(type_id.index); 1182 lldbassert(!ti.isSimple()); 1183 CVType cvt = m_index->tpi().getType(ti); 1184 1185 if (IsForwardRefUdt(cvt)) { 1186 auto expected_full_ti = m_index->tpi().findFullDeclForForwardRef(ti); 1187 if (!expected_full_ti) 1188 llvm::consumeError(expected_full_ti.takeError()); 1189 else if (*expected_full_ti != ti) { 1190 full_decl_uid = PdbSymUid::makeTypeSymId( 1191 type_uid.tag(), *expected_full_ti, type_id.is_ipi); 1192 1193 // It's possible that a lookup would occur for the full decl causing it 1194 // to be cached, then a second lookup would occur for the forward decl. 1195 // We don't want to create a second full decl, so make sure the full 1196 // decl hasn't already been cached. 1197 auto full_iter = m_types.find(full_decl_uid->toOpaqueId()); 1198 if (full_iter != m_types.end()) { 1199 TypeSP result = full_iter->second; 1200 // Map the forward decl to the TypeSP for the full decl so we can take 1201 // the fast path next time. 1202 m_types[type_uid.toOpaqueId()] = result; 1203 return result; 1204 } 1205 } 1206 } 1207 } 1208 1209 PdbSymUid best_uid = full_decl_uid ? *full_decl_uid : type_uid; 1210 TypeSP result = CreateType(best_uid); 1211 if (!result) 1212 return nullptr; 1213 m_types[best_uid.toOpaqueId()] = result; 1214 // If we had both a forward decl and a full decl, make both point to the new 1215 // type. 1216 if (full_decl_uid) 1217 m_types[type_uid.toOpaqueId()] = result; 1218 1219 const PdbTypeSymId &type_id = best_uid.asTypeSym(); 1220 if (best_uid.tag() == PDB_SymType::UDT || 1221 best_uid.tag() == PDB_SymType::Enum) { 1222 clang::TagDecl *record_decl = 1223 m_clang->GetAsTagDecl(result->GetForwardCompilerType()); 1224 lldbassert(record_decl); 1225 1226 TypeIndex ti(type_id.index); 1227 m_uid_to_decl[best_uid.toOpaqueId()] = record_decl; 1228 m_decl_to_status[record_decl] = 1229 DeclStatus(best_uid.toOpaqueId(), Type::eResolveStateForward); 1230 } 1231 return result; 1232 } 1233 1234 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbSymUid type_uid) { 1235 lldbassert(PdbSymUid::isTypeSym(type_uid.tag())); 1236 // We can't use try_emplace / overwrite here because the process of creating 1237 // a type could create nested types, which could invalidate iterators. So 1238 // we have to do a 2-phase lookup / insert. 1239 auto iter = m_types.find(type_uid.toOpaqueId()); 1240 if (iter != m_types.end()) 1241 return iter->second; 1242 1243 return CreateAndCacheType(type_uid); 1244 } 1245 1246 static DWARFExpression 1247 MakeConstantLocationExpression(TypeIndex underlying_ti, TpiStream &tpi, 1248 const ConstantSym &constant, ModuleSP module) { 1249 const ArchSpec &architecture = module->GetArchitecture(); 1250 uint32_t address_size = architecture.GetAddressByteSize(); 1251 1252 size_t size = 0; 1253 bool is_signed = false; 1254 std::tie(size, is_signed) = GetIntegralTypeInfo(underlying_ti, tpi); 1255 1256 union { 1257 llvm::support::little64_t I; 1258 llvm::support::ulittle64_t U; 1259 } Value; 1260 1261 std::shared_ptr<DataBufferHeap> buffer = std::make_shared<DataBufferHeap>(); 1262 buffer->SetByteSize(size); 1263 1264 llvm::ArrayRef<uint8_t> bytes; 1265 if (is_signed) { 1266 Value.I = constant.Value.getSExtValue(); 1267 } else { 1268 Value.U = constant.Value.getZExtValue(); 1269 } 1270 1271 bytes = llvm::makeArrayRef(reinterpret_cast<const uint8_t *>(&Value), 8) 1272 .take_front(size); 1273 buffer->CopyData(bytes.data(), size); 1274 DataExtractor extractor(buffer, lldb::eByteOrderLittle, address_size); 1275 DWARFExpression result(nullptr, extractor, nullptr, 0, size); 1276 return result; 1277 } 1278 1279 static DWARFExpression MakeGlobalLocationExpression(uint16_t section, 1280 uint32_t offset, 1281 ModuleSP module) { 1282 assert(section > 0); 1283 assert(module); 1284 1285 const ArchSpec &architecture = module->GetArchitecture(); 1286 ByteOrder byte_order = architecture.GetByteOrder(); 1287 uint32_t address_size = architecture.GetAddressByteSize(); 1288 uint32_t byte_size = architecture.GetDataByteSize(); 1289 assert(byte_order != eByteOrderInvalid && address_size != 0); 1290 1291 RegisterKind register_kind = eRegisterKindDWARF; 1292 StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order); 1293 stream.PutHex8(DW_OP_addr); 1294 1295 SectionList *section_list = module->GetSectionList(); 1296 assert(section_list); 1297 1298 // Section indices in PDB are 1-based, but in DWARF they are 0-based, so we 1299 // need to subtract 1. 1300 uint32_t section_idx = section - 1; 1301 if (section_idx >= section_list->GetSize()) 1302 return DWARFExpression(nullptr); 1303 1304 auto section_ptr = section_list->GetSectionAtIndex(section_idx); 1305 if (!section_ptr) 1306 return DWARFExpression(nullptr); 1307 1308 stream.PutMaxHex64(section_ptr->GetFileAddress() + offset, address_size, 1309 byte_order); 1310 DataBufferSP buffer = 1311 std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize()); 1312 DataExtractor extractor(buffer, byte_order, address_size, byte_size); 1313 DWARFExpression result(module, extractor, nullptr, 0, buffer->GetByteSize()); 1314 result.SetRegisterKind(register_kind); 1315 return result; 1316 } 1317 1318 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbSymUid var_uid) { 1319 const PdbCuSymId &cu_sym = var_uid.asCuSym(); 1320 lldbassert(cu_sym.global); 1321 CVSymbol sym = m_index->symrecords().readRecord(cu_sym.offset); 1322 if (sym.kind() == S_CONSTANT) 1323 return CreateConstantSymbol(var_uid, sym); 1324 1325 lldb::ValueType scope = eValueTypeInvalid; 1326 TypeIndex ti; 1327 llvm::StringRef name; 1328 lldb::addr_t addr = 0; 1329 uint16_t section = 0; 1330 uint32_t offset = 0; 1331 bool is_external = false; 1332 switch (sym.kind()) { 1333 case S_GDATA32: 1334 is_external = true; 1335 LLVM_FALLTHROUGH; 1336 case S_LDATA32: { 1337 DataSym ds(sym.kind()); 1338 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds)); 1339 ti = ds.Type; 1340 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal 1341 : eValueTypeVariableStatic; 1342 name = ds.Name; 1343 section = ds.Segment; 1344 offset = ds.DataOffset; 1345 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset); 1346 break; 1347 } 1348 case S_GTHREAD32: 1349 is_external = true; 1350 LLVM_FALLTHROUGH; 1351 case S_LTHREAD32: { 1352 ThreadLocalDataSym tlds(sym.kind()); 1353 llvm::cantFail( 1354 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)); 1355 ti = tlds.Type; 1356 name = tlds.Name; 1357 section = tlds.Segment; 1358 offset = tlds.DataOffset; 1359 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset); 1360 scope = eValueTypeVariableThreadLocal; 1361 break; 1362 } 1363 default: 1364 llvm_unreachable("unreachable!"); 1365 } 1366 1367 CompUnitSP comp_unit; 1368 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr); 1369 if (modi) { 1370 PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi); 1371 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid); 1372 comp_unit = GetOrCreateCompileUnit(cci); 1373 } 1374 1375 Declaration decl; 1376 PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti); 1377 PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false); 1378 SymbolFileTypeSP type_sp = 1379 std::make_shared<SymbolFileType>(*this, tuid.toOpaqueId()); 1380 Variable::RangeList ranges; 1381 1382 DWARFExpression location = MakeGlobalLocationExpression( 1383 section, offset, GetObjectFile()->GetModule()); 1384 1385 std::string global_name("::"); 1386 global_name += name; 1387 VariableSP var_sp = std::make_shared<Variable>( 1388 var_uid.toOpaqueId(), name.str().c_str(), global_name.c_str(), type_sp, 1389 scope, comp_unit.get(), ranges, &decl, location, is_external, false, 1390 false); 1391 var_sp->SetLocationIsConstantValueData(false); 1392 1393 return var_sp; 1394 } 1395 1396 lldb::VariableSP 1397 SymbolFileNativePDB::CreateConstantSymbol(PdbSymUid var_uid, 1398 const CVSymbol &cvs) { 1399 TpiStream &tpi = m_index->tpi(); 1400 ConstantSym constant(cvs.kind()); 1401 1402 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)); 1403 std::string global_name("::"); 1404 global_name += constant.Name; 1405 PDB_SymType pdbst = GetPdbSymType(tpi, constant.Type); 1406 PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, constant.Type, false); 1407 SymbolFileTypeSP type_sp = 1408 std::make_shared<SymbolFileType>(*this, tuid.toOpaqueId()); 1409 1410 Declaration decl; 1411 Variable::RangeList ranges; 1412 ModuleSP module = GetObjectFile()->GetModule(); 1413 DWARFExpression location = 1414 MakeConstantLocationExpression(constant.Type, tpi, constant, module); 1415 1416 VariableSP var_sp = std::make_shared<Variable>( 1417 var_uid.toOpaqueId(), constant.Name.str().c_str(), global_name.c_str(), 1418 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location, 1419 false, false, false); 1420 var_sp->SetLocationIsConstantValueData(true); 1421 return var_sp; 1422 } 1423 1424 VariableSP SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbSymUid var_uid) { 1425 lldbassert(var_uid.isGlobalVariable()); 1426 1427 auto emplace_result = 1428 m_global_vars.try_emplace(var_uid.toOpaqueId(), nullptr); 1429 if (emplace_result.second) 1430 emplace_result.first->second = CreateGlobalVariable(var_uid); 1431 1432 return emplace_result.first->second; 1433 } 1434 1435 lldb::TypeSP 1436 SymbolFileNativePDB::GetOrCreateType(llvm::codeview::TypeIndex ti) { 1437 PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti); 1438 PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false); 1439 return GetOrCreateType(tuid); 1440 } 1441 1442 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbSymUid func_uid, 1443 const SymbolContext &sc) { 1444 lldbassert(func_uid.tag() == PDB_SymType::Function); 1445 auto emplace_result = m_functions.try_emplace(func_uid.toOpaqueId(), nullptr); 1446 if (emplace_result.second) 1447 emplace_result.first->second = CreateFunction(func_uid, sc); 1448 1449 lldbassert(emplace_result.first->second); 1450 return emplace_result.first->second; 1451 } 1452 1453 CompUnitSP 1454 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) { 1455 auto emplace_result = 1456 m_compilands.try_emplace(cci.m_uid.toOpaqueId(), nullptr); 1457 if (emplace_result.second) 1458 emplace_result.first->second = CreateCompileUnit(cci); 1459 1460 lldbassert(emplace_result.first->second); 1461 return emplace_result.first->second; 1462 } 1463 1464 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) { 1465 if (index >= GetNumCompileUnits()) 1466 return CompUnitSP(); 1467 lldbassert(index < UINT16_MAX); 1468 if (index >= UINT16_MAX) 1469 return nullptr; 1470 1471 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index); 1472 1473 return GetOrCreateCompileUnit(item); 1474 } 1475 1476 lldb::LanguageType 1477 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) { 1478 // What fields should I expect to be filled out on the SymbolContext? Is it 1479 // safe to assume that `sc.comp_unit` is valid? 1480 if (!sc.comp_unit) 1481 return lldb::eLanguageTypeUnknown; 1482 PdbSymUid uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID()); 1483 lldbassert(uid.tag() == PDB_SymType::Compiland); 1484 1485 CompilandIndexItem *item = m_index->compilands().GetCompiland(uid); 1486 lldbassert(item); 1487 if (!item->m_compile_opts) 1488 return lldb::eLanguageTypeUnknown; 1489 1490 return TranslateLanguage(item->m_compile_opts->getLanguage()); 1491 } 1492 1493 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) { 1494 lldbassert(sc.comp_unit); 1495 return false; 1496 } 1497 1498 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) { 1499 // If any of these flags are set, we need to resolve the compile unit. 1500 uint32_t flags = eSymbolContextCompUnit; 1501 flags |= eSymbolContextVariable; 1502 flags |= eSymbolContextFunction; 1503 flags |= eSymbolContextBlock; 1504 flags |= eSymbolContextLineEntry; 1505 return (resolve_scope & flags) != 0; 1506 } 1507 1508 uint32_t SymbolFileNativePDB::ResolveSymbolContext( 1509 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) { 1510 uint32_t resolved_flags = 0; 1511 lldb::addr_t file_addr = addr.GetFileAddress(); 1512 1513 if (NeedsResolvedCompileUnit(resolve_scope)) { 1514 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr); 1515 if (!modi) 1516 return 0; 1517 PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi); 1518 CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid); 1519 if (!cci) 1520 return 0; 1521 1522 sc.comp_unit = GetOrCreateCompileUnit(*cci).get(); 1523 resolved_flags |= eSymbolContextCompUnit; 1524 } 1525 1526 if (resolve_scope & eSymbolContextFunction) { 1527 lldbassert(sc.comp_unit); 1528 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr); 1529 for (const auto &match : matches) { 1530 if (match.uid.tag() != PDB_SymType::Function) 1531 continue; 1532 sc.function = GetOrCreateFunction(match.uid, sc).get(); 1533 } 1534 resolved_flags |= eSymbolContextFunction; 1535 } 1536 1537 if (resolve_scope & eSymbolContextLineEntry) { 1538 lldbassert(sc.comp_unit); 1539 if (auto *line_table = sc.comp_unit->GetLineTable()) { 1540 if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) 1541 resolved_flags |= eSymbolContextLineEntry; 1542 } 1543 } 1544 1545 return resolved_flags; 1546 } 1547 1548 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence, 1549 const CompilandIndexItem &cci, 1550 lldb::addr_t base_addr, 1551 uint32_t file_number, 1552 const LineFragmentHeader &block, 1553 const LineNumberEntry &cur) { 1554 LineInfo cur_info(cur.Flags); 1555 1556 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto()) 1557 return; 1558 1559 uint64_t addr = base_addr + cur.Offset; 1560 1561 bool is_statement = cur_info.isStatement(); 1562 bool is_prologue = IsFunctionPrologue(cci, addr); 1563 bool is_epilogue = IsFunctionEpilogue(cci, addr); 1564 1565 uint32_t lno = cur_info.getStartLine(); 1566 1567 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number, 1568 is_statement, false, is_prologue, is_epilogue, 1569 false); 1570 } 1571 1572 static void TerminateLineSequence(LineTable &table, 1573 const LineFragmentHeader &block, 1574 lldb::addr_t base_addr, uint32_t file_number, 1575 uint32_t last_line, 1576 std::unique_ptr<LineSequence> seq) { 1577 // The end is always a terminal entry, so insert it regardless. 1578 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize, 1579 last_line, 0, file_number, false, false, 1580 false, false, true); 1581 table.InsertSequence(seq.release()); 1582 } 1583 1584 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) { 1585 // Unfortunately LLDB is set up to parse the entire compile unit line table 1586 // all at once, even if all it really needs is line info for a specific 1587 // function. In the future it would be nice if it could set the sc.m_function 1588 // member, and we could only get the line info for the function in question. 1589 lldbassert(sc.comp_unit); 1590 PdbSymUid cu_id = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID()); 1591 lldbassert(cu_id.isCompiland()); 1592 CompilandIndexItem *cci = m_index->compilands().GetCompiland(cu_id); 1593 lldbassert(cci); 1594 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit); 1595 1596 // This is basically a copy of the .debug$S subsections from all original COFF 1597 // object files merged together with address relocations applied. We are 1598 // looking for all DEBUG_S_LINES subsections. 1599 for (const DebugSubsectionRecord &dssr : 1600 cci->m_debug_stream.getSubsectionsArray()) { 1601 if (dssr.kind() != DebugSubsectionKind::Lines) 1602 continue; 1603 1604 DebugLinesSubsectionRef lines; 1605 llvm::BinaryStreamReader reader(dssr.getRecordData()); 1606 if (auto EC = lines.initialize(reader)) { 1607 llvm::consumeError(std::move(EC)); 1608 return false; 1609 } 1610 1611 const LineFragmentHeader *lfh = lines.header(); 1612 uint64_t virtual_addr = 1613 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset); 1614 1615 const auto &checksums = cci->m_strings.checksums().getArray(); 1616 const auto &strings = cci->m_strings.strings(); 1617 for (const LineColumnEntry &group : lines) { 1618 // Indices in this structure are actually offsets of records in the 1619 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index 1620 // into the global PDB string table. 1621 auto iter = checksums.at(group.NameIndex); 1622 if (iter == checksums.end()) 1623 continue; 1624 1625 llvm::Expected<llvm::StringRef> efn = 1626 strings.getString(iter->FileNameOffset); 1627 if (!efn) { 1628 llvm::consumeError(efn.takeError()); 1629 continue; 1630 } 1631 1632 // LLDB wants the index of the file in the list of support files. 1633 auto fn_iter = llvm::find(cci->m_file_list, *efn); 1634 lldbassert(fn_iter != cci->m_file_list.end()); 1635 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter); 1636 1637 std::unique_ptr<LineSequence> sequence( 1638 line_table->CreateLineSequenceContainer()); 1639 lldbassert(!group.LineNumbers.empty()); 1640 1641 for (const LineNumberEntry &entry : group.LineNumbers) { 1642 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr, 1643 file_index, *lfh, entry); 1644 } 1645 LineInfo last_line(group.LineNumbers.back().Flags); 1646 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index, 1647 last_line.getEndLine(), std::move(sequence)); 1648 } 1649 } 1650 1651 if (line_table->GetSize() == 0) 1652 return false; 1653 1654 sc.comp_unit->SetLineTable(line_table.release()); 1655 return true; 1656 } 1657 1658 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) { 1659 // PDB doesn't contain information about macros 1660 return false; 1661 } 1662 1663 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles( 1664 const SymbolContext &sc, FileSpecList &support_files) { 1665 lldbassert(sc.comp_unit); 1666 1667 PdbSymUid comp_uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID()); 1668 lldbassert(comp_uid.tag() == PDB_SymType::Compiland); 1669 1670 const CompilandIndexItem *cci = m_index->compilands().GetCompiland(comp_uid); 1671 lldbassert(cci); 1672 1673 for (llvm::StringRef f : cci->m_file_list) { 1674 FileSpec::Style style = 1675 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows; 1676 FileSpec spec(f, style); 1677 support_files.Append(spec); 1678 } 1679 1680 return true; 1681 } 1682 1683 bool SymbolFileNativePDB::ParseImportedModules( 1684 const SymbolContext &sc, std::vector<ConstString> &imported_modules) { 1685 // PDB does not yet support module debug info 1686 return false; 1687 } 1688 1689 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) { 1690 lldbassert(sc.comp_unit && sc.function); 1691 return 0; 1692 } 1693 1694 void SymbolFileNativePDB::DumpClangAST(Stream &s) { 1695 if (!m_clang) 1696 return; 1697 m_clang->Dump(s); 1698 } 1699 1700 uint32_t SymbolFileNativePDB::FindGlobalVariables( 1701 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1702 uint32_t max_matches, VariableList &variables) { 1703 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1704 1705 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName( 1706 name.GetStringRef(), m_index->symrecords()); 1707 for (const SymbolAndOffset &result : results) { 1708 VariableSP var; 1709 switch (result.second.kind()) { 1710 case SymbolKind::S_GDATA32: 1711 case SymbolKind::S_LDATA32: 1712 case SymbolKind::S_GTHREAD32: 1713 case SymbolKind::S_LTHREAD32: 1714 case SymbolKind::S_CONSTANT: { 1715 PdbSymUid uid = PdbSymUid::makeGlobalVariableUid(result.first); 1716 var = GetOrCreateGlobalVariable(uid); 1717 variables.AddVariable(var); 1718 break; 1719 } 1720 default: 1721 continue; 1722 } 1723 } 1724 return variables.GetSize(); 1725 } 1726 1727 uint32_t SymbolFileNativePDB::FindFunctions( 1728 const ConstString &name, const CompilerDeclContext *parent_decl_ctx, 1729 FunctionNameType name_type_mask, bool include_inlines, bool append, 1730 SymbolContextList &sc_list) { 1731 // For now we only support lookup by method name. 1732 if (!(name_type_mask & eFunctionNameTypeMethod)) 1733 return 0; 1734 1735 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; 1736 1737 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName( 1738 name.GetStringRef(), m_index->symrecords()); 1739 for (const SymbolAndOffset &match : matches) { 1740 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF) 1741 continue; 1742 ProcRefSym proc(match.second.kind()); 1743 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc)); 1744 1745 if (!IsValidRecord(proc)) 1746 continue; 1747 1748 PdbSymUid cuid = PdbSymUid::makeCompilandId(proc); 1749 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid); 1750 SymbolContext sc; 1751 1752 sc.comp_unit = GetOrCreateCompileUnit(cci).get(); 1753 sc.module_sp = sc.comp_unit->GetModule(); 1754 PdbSymUid func_uid = PdbSymUid::makeCuSymId(proc); 1755 sc.function = GetOrCreateFunction(func_uid, sc).get(); 1756 1757 sc_list.Append(sc); 1758 } 1759 1760 return sc_list.GetSize(); 1761 } 1762 1763 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex, 1764 bool include_inlines, bool append, 1765 SymbolContextList &sc_list) { 1766 return 0; 1767 } 1768 1769 uint32_t SymbolFileNativePDB::FindTypes( 1770 const SymbolContext &sc, const ConstString &name, 1771 const CompilerDeclContext *parent_decl_ctx, bool append, 1772 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, 1773 TypeMap &types) { 1774 if (!append) 1775 types.Clear(); 1776 if (!name) 1777 return 0; 1778 1779 searched_symbol_files.clear(); 1780 searched_symbol_files.insert(this); 1781 1782 // There is an assumption 'name' is not a regex 1783 size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types); 1784 1785 return match_count; 1786 } 1787 1788 size_t 1789 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context, 1790 bool append, TypeMap &types) { 1791 return 0; 1792 } 1793 1794 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name, 1795 uint32_t max_matches, 1796 TypeMap &types) { 1797 1798 size_t match_count = 0; 1799 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name); 1800 if (max_matches > 0 && max_matches < matches.size()) 1801 matches.resize(max_matches); 1802 1803 for (TypeIndex ti : matches) { 1804 TypeSP type = GetOrCreateType(ti); 1805 if (!type) 1806 continue; 1807 1808 types.Insert(type); 1809 ++match_count; 1810 } 1811 return match_count; 1812 } 1813 1814 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; } 1815 1816 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) { 1817 auto iter = m_types.find(type_uid); 1818 // lldb should not be passing us non-sensical type uids. the only way it 1819 // could have a type uid in the first place is if we handed it out, in which 1820 // case we should know about the type. However, that doesn't mean we've 1821 // instantiated it yet. We can vend out a UID for a future type. So if the 1822 // type doesn't exist, let's instantiate it now. 1823 if (iter != m_types.end()) 1824 return &*iter->second; 1825 1826 PdbSymUid uid = PdbSymUid::fromOpaqueId(type_uid); 1827 lldbassert(uid.isTypeSym(uid.tag())); 1828 const PdbTypeSymId &type_id = uid.asTypeSym(); 1829 TypeIndex ti(type_id.index); 1830 if (ti.isNoneType()) 1831 return nullptr; 1832 1833 TypeSP type_sp = CreateAndCacheType(uid); 1834 return &*type_sp; 1835 } 1836 1837 llvm::Optional<SymbolFile::ArrayInfo> 1838 SymbolFileNativePDB::GetDynamicArrayInfoForUID( 1839 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 1840 return llvm::None; 1841 } 1842 1843 1844 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) { 1845 // If this is not in our map, it's an error. 1846 clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type); 1847 lldbassert(tag_decl); 1848 auto status_iter = m_decl_to_status.find(tag_decl); 1849 lldbassert(status_iter != m_decl_to_status.end()); 1850 1851 // If it's already complete, just return. 1852 DeclStatus &status = status_iter->second; 1853 if (status.status == Type::eResolveStateFull) 1854 return true; 1855 1856 PdbSymUid uid = PdbSymUid::fromOpaqueId(status.uid); 1857 lldbassert(uid.tag() == PDB_SymType::UDT || uid.tag() == PDB_SymType::Enum); 1858 1859 const PdbTypeSymId &type_id = uid.asTypeSym(); 1860 1861 ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(), 1862 false); 1863 1864 // In CreateAndCacheType, we already go out of our way to resolve forward 1865 // ref UDTs to full decls, and the uids we vend out always refer to full 1866 // decls if a full decl exists in the debug info. So if we don't have a full 1867 // decl here, it means one doesn't exist in the debug info, and we can't 1868 // complete the type. 1869 CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index)); 1870 if (IsForwardRefUdt(cvt)) 1871 return false; 1872 1873 auto types_iter = m_types.find(uid.toOpaqueId()); 1874 lldbassert(types_iter != m_types.end()); 1875 1876 if (cvt.kind() == LF_MODIFIER) { 1877 TypeIndex unmodified_type = LookThroughModifierRecord(cvt); 1878 cvt = m_index->tpi().getType(unmodified_type); 1879 // LF_MODIFIERS usually point to forward decls, so this is the one case 1880 // where we won't have been able to resolve a forward decl to a full decl 1881 // earlier on. So we need to do that now. 1882 if (IsForwardRefUdt(cvt)) { 1883 llvm::Expected<TypeIndex> expected_full_ti = 1884 m_index->tpi().findFullDeclForForwardRef(unmodified_type); 1885 if (!expected_full_ti) { 1886 llvm::consumeError(expected_full_ti.takeError()); 1887 return false; 1888 } 1889 cvt = m_index->tpi().getType(*expected_full_ti); 1890 lldbassert(!IsForwardRefUdt(cvt)); 1891 unmodified_type = *expected_full_ti; 1892 } 1893 uid = PdbSymUid::makeTypeSymId(uid.tag(), unmodified_type, false); 1894 } 1895 TypeIndex field_list_ti = GetFieldListIndex(cvt); 1896 CVType field_list_cvt = m_index->tpi().getType(field_list_ti); 1897 if (field_list_cvt.kind() != LF_FIELDLIST) 1898 return false; 1899 1900 // Visit all members of this class, then perform any finalization necessary 1901 // to complete the class. 1902 UdtRecordCompleter completer(uid, compiler_type, *tag_decl, *this); 1903 auto error = 1904 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 1905 completer.complete(); 1906 1907 status.status = Type::eResolveStateFull; 1908 if (!error) 1909 return true; 1910 1911 llvm::consumeError(std::move(error)); 1912 return false; 1913 } 1914 1915 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, 1916 TypeClass type_mask, 1917 lldb_private::TypeList &type_list) { 1918 return 0; 1919 } 1920 1921 CompilerDeclContext 1922 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc, 1923 const ConstString &name, 1924 const CompilerDeclContext *parent_decl_ctx) { 1925 return {}; 1926 } 1927 1928 TypeSystem * 1929 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { 1930 auto type_system = 1931 m_obj_file->GetModule()->GetTypeSystemForLanguage(language); 1932 if (type_system) 1933 type_system->SetSymbolFile(this); 1934 return type_system; 1935 } 1936 1937 ConstString SymbolFileNativePDB::GetPluginName() { 1938 static ConstString g_name("pdb"); 1939 return g_name; 1940 } 1941 1942 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; } 1943