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