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