LLDB mainline
SymbolFileNativePDB.cpp
Go to the documentation of this file.
1//===-- SymbolFileNativePDB.cpp -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
16#include "lldb/Core/Module.h"
27#include "lldb/Utility/Log.h"
28
29#include "clang/Basic/ABI.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/DebugInfo/CodeView/CVRecord.h"
34#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
35#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
36#include "llvm/DebugInfo/CodeView/Formatters.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/NativeSession.h"
47#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
48#include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
49#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
50#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
51#include "llvm/DebugInfo/PDB/PDB.h"
52#include "llvm/DebugInfo/PDB/PDBTypes.h"
53#include "llvm/Demangle/MicrosoftDemangle.h"
54#include "llvm/Object/COFF.h"
55#include "llvm/Support/Allocator.h"
56#include "llvm/Support/BinaryStreamReader.h"
57#include "llvm/Support/Error.h"
58#include "llvm/Support/ErrorExtras.h"
59#include "llvm/Support/ErrorOr.h"
60#include "llvm/Support/MemoryBuffer.h"
61
63#include "PdbSymUid.h"
64#include "PdbUtil.h"
65#include "UdtRecordCompleter.h"
66#include <optional>
67#include <string_view>
68
69using namespace lldb;
70using namespace lldb_private;
71using namespace npdb;
72using namespace llvm::codeview;
73using namespace llvm::pdb;
74
76
78 switch (lang) {
79 case PDB_Lang::Cpp:
81 case PDB_Lang::C:
83 case PDB_Lang::Swift:
85 case PDB_Lang::Rust:
87 case PDB_Lang::ObjC:
89 case PDB_Lang::ObjCpp:
91 default:
93 }
94}
95
96static std::optional<std::string>
97findMatchingPDBFilePath(llvm::StringRef original_pdb_path,
98 llvm::StringRef exe_path) {
99 const FileSystem &fs = FileSystem::Instance();
100
101 if (fs.Exists(original_pdb_path))
102 return std::string(original_pdb_path);
103
104 const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent();
105 // While the exe_path uses the native style, the exe might be compiled on a
106 // different OS, so try to guess the style used.
107 const FileSpec original_pdb_spec(original_pdb_path,
108 FileSpec::GuessPathStyle(original_pdb_path)
109 .value_or(FileSpec::Style::native));
110 const llvm::StringRef pdb_filename = original_pdb_spec.GetFilename();
111
112 // If the file doesn't exist, perhaps the path specified at build time
113 // doesn't match the PDB's current location, so check the location of the
114 // executable.
115 const FileSpec local_pdb = exe_dir.CopyByAppendingPathComponent(pdb_filename);
116 if (fs.Exists(local_pdb))
117 return local_pdb.GetPath();
118
119 // Otherwise, search for one in target.debug-file-search-paths
121 for (const FileSpec &search_dir : search_paths) {
122 FileSpec pdb_path = search_dir.CopyByAppendingPathComponent(pdb_filename);
123 if (fs.Exists(pdb_path))
124 return pdb_path.GetPath();
125 }
126
127 return std::nullopt;
128}
129
130static std::unique_ptr<PDBFile>
131loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
132 // Try to find a matching PDB for an EXE.
133 using namespace llvm::object;
134 auto expected_binary = createBinary(exe_path);
135
136 // If the file isn't a PE/COFF executable, fail.
137 if (!expected_binary) {
138 llvm::consumeError(expected_binary.takeError());
139 return nullptr;
140 }
141 OwningBinary<Binary> binary = std::move(*expected_binary);
142
143 // TODO: Avoid opening the PE/COFF binary twice by reading this information
144 // directly from the lldb_private::ObjectFile.
145 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
146 if (!obj)
147 return nullptr;
148 const llvm::codeview::DebugInfo *pdb_info = nullptr;
149
150 // If it doesn't have a debug directory, fail.
151 llvm::StringRef pdb_file;
152 if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) {
153 consumeError(std::move(e));
154 return nullptr;
155 }
156
157 std::optional<std::string> resolved_pdb_path =
158 findMatchingPDBFilePath(pdb_file, exe_path);
159 if (!resolved_pdb_path)
160 return nullptr;
161
162 // If the file is not a PDB or if it doesn't have a matching GUID, fail.
163 auto pdb =
164 ObjectFilePDB::loadPDBFile(*std::move(resolved_pdb_path), allocator);
165 if (!pdb)
166 return nullptr;
167
168 auto expected_info = pdb->getPDBInfoStream();
169 if (!expected_info) {
170 llvm::consumeError(expected_info.takeError());
171 return nullptr;
172 }
173 llvm::codeview::GUID guid;
174 memcpy(&guid, pdb_info->PDB70.Signature, 16);
175
176 if (expected_info->getGuid() != guid)
177 return nullptr;
178
179 return pdb;
180}
181
183 lldb::addr_t addr) {
184 // FIXME: Implement this.
185 return false;
186}
187
189 lldb::addr_t addr) {
190 // FIXME: Implement this.
191 return false;
192}
193
194// See llvm::codeview::TypeIndex::simpleTypeName as well as strForPrimitiveTi
195// from the original pdbdump:
196// https://github.com/microsoft/microsoft-pdb/blob/805655a28bd8198004be2ac27e6e0290121a5e89/pdbdump/pdbdump.cpp#L1896-L1974
197//
198// For 64bit integers we use "long long" like DIA instead of "__int64".
199static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
200 switch (kind) {
201 case SimpleTypeKind::Boolean128:
202 return "__bool128";
203 case SimpleTypeKind::Boolean64:
204 return "__bool64";
205 case SimpleTypeKind::Boolean32:
206 return "__bool32";
207 case SimpleTypeKind::Boolean16:
208 return "__bool16";
209 case SimpleTypeKind::Boolean8:
210 return "bool";
211
212 case SimpleTypeKind::Byte:
213 case SimpleTypeKind::UnsignedCharacter:
214 return "unsigned char";
215 case SimpleTypeKind::NarrowCharacter:
216 return "char";
217 case SimpleTypeKind::SignedCharacter:
218 case SimpleTypeKind::SByte:
219 return "signed char";
220 case SimpleTypeKind::Character32:
221 return "char32_t";
222 case SimpleTypeKind::Character16:
223 return "char16_t";
224 case SimpleTypeKind::Character8:
225 return "char8_t";
226
227 case SimpleTypeKind::Complex128:
228 return "_Complex __float128";
229 case SimpleTypeKind::Complex80:
230 return "_Complex long double";
231 case SimpleTypeKind::Complex64:
232 return "_Complex double";
233 case SimpleTypeKind::Complex48:
234 return "_Complex __float48";
235 case SimpleTypeKind::Complex32:
236 case SimpleTypeKind::Complex32PartialPrecision:
237 return "_Complex float";
238 case SimpleTypeKind::Complex16:
239 return "_Complex _Float16";
240
241 case SimpleTypeKind::Float128:
242 return "__float128";
243 case SimpleTypeKind::Float80:
244 return "long double";
245 case SimpleTypeKind::Float64:
246 return "double";
247 case SimpleTypeKind::Float48:
248 return "__float48";
249 case SimpleTypeKind::Float32:
250 case SimpleTypeKind::Float32PartialPrecision:
251 return "float";
252 case SimpleTypeKind::Float16:
253 return "_Float16";
254
255 case SimpleTypeKind::Int128Oct:
256 case SimpleTypeKind::Int128:
257 return "__int128";
258 case SimpleTypeKind::Int64:
259 case SimpleTypeKind::Int64Quad:
260 return "long long";
261 case SimpleTypeKind::Int32Long:
262 return "long";
263 case SimpleTypeKind::Int32:
264 return "int";
265 case SimpleTypeKind::Int16:
266 case SimpleTypeKind::Int16Short:
267 return "short";
268
269 case SimpleTypeKind::UInt128Oct:
270 case SimpleTypeKind::UInt128:
271 return "unsigned __int128";
272 case SimpleTypeKind::UInt64:
273 case SimpleTypeKind::UInt64Quad:
274 return "unsigned long long";
275 case SimpleTypeKind::UInt32:
276 return "unsigned";
277 case SimpleTypeKind::UInt16:
278 case SimpleTypeKind::UInt16Short:
279 return "unsigned short";
280 case SimpleTypeKind::UInt32Long:
281 return "unsigned long";
282
283 case SimpleTypeKind::HResult:
284 return "HRESULT";
285 case SimpleTypeKind::Void:
286 return "void";
287 case SimpleTypeKind::WideCharacter:
288 return "wchar_t";
289
290 case SimpleTypeKind::None:
291 case SimpleTypeKind::NotTranslated:
292 return "";
293 }
294 return "";
295}
296
297static bool IsClassRecord(TypeLeafKind kind) {
298 switch (kind) {
299 case LF_STRUCTURE:
300 case LF_CLASS:
301 case LF_INTERFACE:
302 return true;
303 default:
304 return false;
305 }
306}
307
308static std::optional<CVTagRecord>
309GetNestedTagDefinition(const NestedTypeRecord &Record,
310 const CVTagRecord &parent, TpiStream &tpi) {
311 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
312 // is also used to indicate the primary definition of a nested class. That is
313 // to say, if you have:
314 // struct A {
315 // struct B {};
316 // using C = B;
317 // };
318 // Then in the debug info, this will appear as:
319 // LF_STRUCTURE `A::B` [type index = N]
320 // LF_STRUCTURE `A`
321 // LF_NESTTYPE [name = `B`, index = N]
322 // LF_NESTTYPE [name = `C`, index = N]
323 // In order to accurately reconstruct the decl context hierarchy, we need to
324 // know which ones are actual definitions and which ones are just aliases.
325
326 // If it's a simple type, then this is something like `using foo = int`.
327 if (Record.Type.isSimple())
328 return std::nullopt;
329
330 CVType cvt = tpi.getType(Record.Type);
331
332 if (!IsTagRecord(cvt))
333 return std::nullopt;
334
335 // If it's an inner definition, then treat whatever name we have here as a
336 // single component of a mangled name. So we can inject it into the parent's
337 // mangled name to see if it matches.
338 CVTagRecord child = CVTagRecord::create(cvt);
339 std::string qname = std::string(parent.asTag().getUniqueName());
340 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
341 return std::nullopt;
342
343 // qname[3] is the tag type identifier (struct, class, union, etc). Since the
344 // inner tag type is not necessarily the same as the outer tag type, re-write
345 // it to match the inner tag type.
346 qname[3] = child.asTag().getUniqueName()[3];
347 std::string piece;
348 if (qname[3] == 'W')
349 piece = "4";
350 piece += Record.Name;
351 piece.push_back('@');
352 qname.insert(4, std::move(piece));
353 if (qname != child.asTag().UniqueName)
354 return std::nullopt;
355
356 return std::move(child);
357}
358
364
368
370
372 return "Microsoft PDB debug symbol cross-platform file reader.";
373}
374
377 return nullptr;
378
379 return new SymbolFileNativePDB(std::move(objfile_sp));
380}
381
384
386
388 uint32_t abilities = 0;
389 if (!m_objfile_sp)
390 return 0;
391
392 if (!m_index) {
393 // Lazily load and match the PDB file, but only do this once.
394 PDBFile *pdb_file;
395 if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) {
396 pdb_file = &pdb->GetPDBFile();
397 } else {
398 m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(),
400 pdb_file = m_file_up.get();
401 }
402
403 if (!pdb_file)
404 return 0;
405
406 LLDB_LOG(
407 GetLog(LLDBLog::Symbols), "Loading {0} for {1}",
408 pdb_file->getFilePath(),
409 m_objfile_sp->GetModule()->GetObjectFile()->GetFileSpec().GetPath());
410
411 auto expected_index = PdbIndex::create(pdb_file);
412 if (!expected_index) {
413 llvm::consumeError(expected_index.takeError());
414 return 0;
415 }
416 m_index = std::move(*expected_index);
417 }
418 if (!m_index)
419 return 0;
420
421 // We don't especially have to be precise here. We only distinguish between
422 // stripped and not stripped.
423 abilities = kAllAbilities;
424
425 if (m_index->dbi().isStripped())
426 abilities &= ~(Blocks | LocalVariables);
427 return abilities;
428}
429
431 m_obj_load_address = m_objfile_sp->GetModule()
432 ->GetObjectFile()
433 ->GetBaseAddress()
434 .GetFileAddress();
435 m_index->SetLoadAddress(m_obj_load_address);
436 m_index->ParseSectionContribs();
437
438 auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
440 if (auto err = ts_or_err.takeError()) {
441 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
442 "Failed to initialize: {0}");
443 } else {
444 if (auto ts = *ts_or_err)
445 ts->SetSymbolFile(this);
446 }
447}
448
450 const DbiModuleList &modules = m_index->dbi().modules();
451 uint32_t count = modules.getModuleCount();
452 if (count == 0)
453 return count;
454
455 // The linker can inject an additional "dummy" compilation unit into the
456 // PDB. Ignore this special compile unit for our purposes, if it is there.
457 // It is always the last one.
458 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
459 if (last.getModuleName() == "* Linker *")
460 --count;
461 return count;
462}
463
465 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
466 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
467 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
468 lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
469 auto ts_or_err = GetTypeSystemForLanguage(comp_unit->GetLanguage());
470 if (auto err = ts_or_err.takeError())
471 return nullptr;
472 auto ts = *ts_or_err;
473 if (!ts)
474 return nullptr;
475 PdbAstBuilder* ast_builder = ts->GetNativePDBParser();
476
477 switch (sym.kind()) {
478 case S_GPROC32:
479 case S_LPROC32:
480 // This is a function. It must be global. Creating the Function entry
481 // for it automatically creates a block for it.
482 if (FunctionSP func = GetOrCreateFunction(block_id, *comp_unit))
483 return &func->GetBlock(false);
484 break;
485 case S_BLOCK32: {
486 // This is a block. Its parent is either a function or another block. In
487 // either case, its parent can be viewed as a block (e.g. a function
488 // contains 1 big block. So just get the parent block and add this block
489 // to it.
490 BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
491 if (auto err = SymbolDeserializer::deserializeAs<BlockSym>(sym, block)) {
492 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
493 "Failed to deserialize BlockSym record: {0}");
494 return nullptr;
495 }
496 if (block.Parent == 0) {
497 LLDB_LOG(GetLog(LLDBLog::Symbols), "BlockSym record ({0}) with parent=0",
498 block_id);
499 return nullptr;
500 }
501 PdbCompilandSymId parent_id(block_id.modi, block.Parent);
502 Block *parent_block = GetOrCreateBlock(parent_id);
503 if (!parent_block)
504 return nullptr;
505 Function *func = parent_block->CalculateSymbolContextFunction();
506 if (!func) {
507 LLDB_LOG(GetLog(LLDBLog::Symbols), "parent of {0} is not a function",
508 parent_id);
509 return nullptr;
510 }
511 lldb::addr_t block_base =
512 m_index->MakeVirtualAddress(block.Segment, block.CodeOffset);
513 lldb::addr_t func_base = func->GetAddress().GetFileAddress();
514 BlockSP child_block = parent_block->CreateChild(opaque_block_uid);
515 if (block_base >= func_base)
516 child_block->AddRange(Block::Range(block_base - func_base, block.CodeSize));
517 else {
518 GetObjectFile()->GetModule()->ReportError(
519 "S_BLOCK32 at modi: {0:d} offset: {1:d}: adding range "
520 "[{2:x16}-{3:x16}) which has a base that is less than the "
521 "function's "
522 "low PC 0x%" PRIx64 ". Please file a bug and attach the file at the "
523 "start of this error message",
524 block_id.modi, block_id.offset, block_base,
525 block_base + block.CodeSize, func_base);
526 }
527 if (ast_builder)
528 ast_builder->EnsureBlock(block_id);
529 m_blocks.insert({opaque_block_uid, child_block});
530 break;
531 }
532 case S_INLINESITE: {
533 // This ensures line table is parsed first so we have inline sites info.
534 comp_unit->GetLineTable();
535
536 std::shared_ptr<InlineSite> inline_site = m_inline_sites[opaque_block_uid];
537 Block *parent_block = GetOrCreateBlock(inline_site->parent_id);
538 if (!parent_block)
539 return nullptr;
540 BlockSP child_block = parent_block->CreateChild(opaque_block_uid);
541 if (ast_builder)
542 ast_builder->EnsureInlinedFunction(block_id);
543 // Copy ranges from InlineSite to Block.
544 for (size_t i = 0; i < inline_site->ranges.GetSize(); ++i) {
545 auto *entry = inline_site->ranges.GetEntryAtIndex(i);
546 child_block->AddRange(
547 Block::Range(entry->GetRangeBase(), entry->GetByteSize()));
548 }
549 child_block->FinalizeRanges();
550
551 // Get the inlined function callsite info.
552 Declaration &decl = inline_site->inline_function_info->GetDeclaration();
553 Declaration &callsite = inline_site->inline_function_info->GetCallSite();
554 child_block->SetInlinedFunctionInfo(
555 inline_site->inline_function_info->GetName().GetCString(), nullptr,
556 &decl, &callsite);
557 m_blocks.insert({opaque_block_uid, child_block});
558 break;
559 }
560 default:
561 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a block", block_id);
562 return nullptr;
563 }
564
565 return nullptr;
566}
567
569 CompileUnit &comp_unit) {
570 const CompilandIndexItem *cci =
571 m_index->compilands().GetCompiland(func_id.modi);
572 if (!cci) {
573 LLDB_LOG(GetLog(LLDBLog::Symbols), "missing compiland {0}", func_id.modi);
574 return nullptr;
575 }
576
577 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
578 if (sym_record.kind() != S_LPROC32 && sym_record.kind() != S_GPROC32) {
579 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a function", func_id);
580 return nullptr;
581 }
582
584
585 auto file_vm_addr =
586 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
587 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
588 return nullptr;
589
590 Address func_addr(file_vm_addr, comp_unit.GetModule()->GetSectionList());
591 if (!func_addr.IsValid())
592 return nullptr;
593
594 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
595 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)) {
596 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
597 "Failed to deserialize ProcSym record: {0}");
598 return nullptr;
599 }
600 if (proc.FunctionType == TypeIndex::None())
601 return nullptr;
602 TypeSP func_type = GetOrCreateType(proc.FunctionType);
603 if (!func_type)
604 return nullptr;
605
606 PdbTypeSymId sig_id(proc.FunctionType, false);
607
608 std::optional<llvm::StringRef> mangled_opt = FindMangledSymbol(
609 SegmentOffset(proc.Segment, proc.CodeOffset), proc.FunctionType);
610 Mangled mangled(mangled_opt.value_or(proc.Name));
611
612 FunctionSP func_sp = std::make_shared<Function>(
613 &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
614 func_type.get(), func_addr,
615 AddressRanges{AddressRange(func_addr, sol.length)});
616
617 comp_unit.AddFunction(func_sp);
618
619 auto ts_or_err = GetTypeSystemForLanguage(comp_unit.GetLanguage());
620 if (auto err = ts_or_err.takeError())
621 return func_sp;
622 auto ts = *ts_or_err;
623 if (ts) {
624 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
625 ast_builder->EnsureFunction(func_id);
626 }
627
628 return func_sp;
629}
630
633 lldb::LanguageType lang =
634 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
636
637 LazyBool optimized = eLazyBoolNo;
638 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
639 optimized = eLazyBoolYes;
640
641 llvm::SmallString<64> source_file_name;
642 if (auto main_file_or_err = m_index->compilands().GetMainSourceFile(cci)) {
643 source_file_name = std::move(*main_file_or_err);
644 } else {
645 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), main_file_or_err.takeError(),
646 "Failed to determine main source file: {0}");
647 }
648 FileSpec fs(llvm::sys::path::convert_to_slash(
649 source_file_name, llvm::sys::path::Style::windows_backslash));
650
651 CompUnitSP cu_sp = std::make_shared<CompileUnit>(
652 m_objfile_sp->GetModule(), nullptr, std::make_shared<SupportFile>(fs),
653 toOpaqueUid(cci.m_id), lang, optimized);
654
655 SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
656 return cu_sp;
657}
658
660 const ModifierRecord &mr,
661 CompilerType ct) {
662 TpiStream &stream = m_index->tpi();
663
664 std::string name;
665
666 if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
667 name += "const ";
668 if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
669 name += "volatile ";
670 if ((mr.Modifiers & ModifierOptions::Unaligned) != ModifierOptions::None)
671 name += "__unaligned ";
672
673 if (mr.ModifiedType.isSimple())
674 name += GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
675 else
676 name += computeTypeName(stream.typeCollection(), mr.ModifiedType);
677 Declaration decl;
678 lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
679
680 return MakeType(toOpaqueUid(type_id), ConstString(name),
681 llvm::expectedToOptional(modified_type->GetByteSize(nullptr)),
682 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
684}
685
688 const llvm::codeview::PointerRecord &pr,
689 CompilerType ct) {
690 TypeSP pointee = GetOrCreateType(pr.ReferentType);
691 if (!pointee)
692 return nullptr;
693
694 if (pr.isPointerToMember()) {
695 MemberPointerInfo mpi = pr.getMemberInfo();
696 GetOrCreateType(mpi.ContainingType);
697 }
698
699 Declaration decl;
700 return MakeType(toOpaqueUid(type_id), ConstString(), pr.getSize(), nullptr,
703}
704
706 CompilerType ct) {
707 uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
708 if (ti == TypeIndex::NullptrT()) {
709 Declaration decl;
710 return MakeType(uid, ConstString("decltype(nullptr)"), std::nullopt,
711 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
713 }
714
715 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
716 TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
717 uint32_t pointer_size = 0;
718 switch (ti.getSimpleMode()) {
719 case SimpleTypeMode::FarPointer32:
720 case SimpleTypeMode::NearPointer32:
721 pointer_size = 4;
722 break;
723 case SimpleTypeMode::NearPointer64:
724 pointer_size = 8;
725 break;
726 default:
727 // 128-bit and 16-bit pointers unsupported.
728 return nullptr;
729 }
730 Declaration decl;
731 return MakeType(uid, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
733 }
734
735 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
736 return nullptr;
737
738 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
739 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
740
741 Declaration decl;
742 return MakeType(uid, ConstString(type_name), size, nullptr, LLDB_INVALID_UID,
744}
745
746static std::string GetUnqualifiedTypeName(const TagRecord &record) {
747 if (!record.hasUniqueName())
748 return std::string(MSVCUndecoratedNameParser::DropScope(record.Name));
749
750 llvm::ms_demangle::Demangler demangler;
751 std::string_view sv(record.UniqueName.begin(), record.UniqueName.size());
752 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
753 if (demangler.Error)
754 return std::string(MSVCUndecoratedNameParser::DropScope(record.Name));
755
756 llvm::ms_demangle::IdentifierNode *idn =
757 ttn->QualifiedName->getUnqualifiedIdentifier();
758 return idn->toString();
759}
760
763 const TagRecord &record,
764 size_t size, CompilerType ct) {
765
766 std::string uname = GetUnqualifiedTypeName(record);
767
768 llvm::Expected<Declaration> maybeDecl = ResolveUdtDeclaration(type_id);
769 Declaration decl;
770 if (maybeDecl)
771 decl = std::move(*maybeDecl);
772 else
773 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), maybeDecl.takeError(),
774 "Failed to resolve declaration for '{1}': {0}", uname);
775
776 return MakeType(toOpaqueUid(type_id), ConstString(uname), size, nullptr,
779}
780
782 const ClassRecord &cr,
783 CompilerType ct) {
784 return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
785}
786
788 const UnionRecord &ur,
789 CompilerType ct) {
790 return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
791}
792
794 const EnumRecord &er,
795 CompilerType ct) {
796 std::string uname = GetUnqualifiedTypeName(er);
797
798 llvm::Expected<Declaration> maybeDecl = ResolveUdtDeclaration(type_id);
799 Declaration decl;
800 if (maybeDecl)
801 decl = std::move(*maybeDecl);
802 else
803 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), maybeDecl.takeError(),
804 "Failed to resolve declaration for '{1}': {0}", uname);
805
806 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
807
808 return MakeType(
809 toOpaqueUid(type_id), ConstString(uname),
810 llvm::expectedToOptional(underlying_type->GetByteSize(nullptr)), nullptr,
813}
814
816 const ArrayRecord &ar,
817 CompilerType ct) {
818 TypeSP element_type = GetOrCreateType(ar.ElementType);
819
820 Declaration decl;
821 TypeSP array_sp =
822 MakeType(toOpaqueUid(type_id), ConstString(), ar.Size, nullptr,
825 array_sp->SetEncodingType(element_type.get());
826 return array_sp;
827}
828
830 const MemberFunctionRecord &mfr,
831 CompilerType ct) {
832 if (mfr.ReturnType.isSimple())
833 GetOrCreateType(mfr.ReturnType);
834 CreateSimpleArgumentListTypes(mfr.ArgumentList);
835
836 Declaration decl;
837 return MakeType(toOpaqueUid(type_id), ConstString(), 0, nullptr,
840}
841
843 const ProcedureRecord &pr,
844 CompilerType ct) {
845 if (pr.ReturnType.isSimple())
846 GetOrCreateType(pr.ReturnType);
847 CreateSimpleArgumentListTypes(pr.ArgumentList);
848
849 Declaration decl;
850 return MakeType(toOpaqueUid(type_id), ConstString(), 0, nullptr,
853}
854
856 llvm::codeview::TypeIndex arglist_ti) {
857 if (arglist_ti.isNoneType())
858 return;
859
860 CVType arglist_cvt = m_index->tpi().getType(arglist_ti);
861 if (arglist_cvt.kind() != LF_ARGLIST)
862 return; // invalid debug info
863
864 ArgListRecord alr;
865 if (auto err =
866 TypeDeserializer::deserializeAs<ArgListRecord>(arglist_cvt, alr)) {
867 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
868 "Failed to deserialize ArgListRecord record ({1}): {0}",
869 arglist_ti);
870 return;
871 }
872 for (TypeIndex id : alr.getIndices())
873 if (!id.isNoneType() && id.isSimple())
874 GetOrCreateType(id);
875}
876
878 if (type_id.index.isSimple())
879 return CreateSimpleType(type_id.index, ct);
880
881 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
882 CVType cvt = stream.getType(type_id.index);
883
884 if (cvt.kind() == LF_MODIFIER) {
885 ModifierRecord modifier;
886 if (auto err =
887 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)) {
888 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
889 "Failed to deserialize ModifierRecord record ({1}): {0}",
890 type_id.index);
891 return nullptr;
892 }
893 return CreateModifierType(type_id, modifier, ct);
894 }
895
896 if (cvt.kind() == LF_POINTER) {
897 PointerRecord pointer;
898 if (auto err =
899 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)) {
900 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
901 "Failed to deserialize PointerRecord record ({1}): {0}",
902 type_id.index);
903 return nullptr;
904 }
905 return CreatePointerType(type_id, pointer, ct);
906 }
907
908 if (IsClassRecord(cvt.kind())) {
909 ClassRecord cr;
910 if (auto err = TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr)) {
911 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
912 "Failed to deserialize ClassRecord record ({1}): {0}",
913 type_id.index);
914 return nullptr;
915 }
916 return CreateTagType(type_id, cr, ct);
917 }
918
919 if (cvt.kind() == LF_ENUM) {
920 EnumRecord er;
921 if (auto err = TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)) {
922 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
923 "Failed to deserialize EnumRecord record ({1}): {0}",
924 type_id.index);
925 return nullptr;
926 }
927 return CreateTagType(type_id, er, ct);
928 }
929
930 if (cvt.kind() == LF_UNION) {
931 UnionRecord ur;
932 if (auto err = TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur)) {
933 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
934 "Failed to deserialize UnionRecord record ({1}): {0}",
935 type_id.index);
936 return nullptr;
937 }
938 return CreateTagType(type_id, ur, ct);
939 }
940
941 if (cvt.kind() == LF_ARRAY) {
942 ArrayRecord ar;
943 if (auto err = TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)) {
944 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
945 "Failed to deserialize ArrayRecord record ({1}): {0}",
946 type_id.index);
947 return nullptr;
948 }
949 return CreateArrayType(type_id, ar, ct);
950 }
951
952 if (cvt.kind() == LF_PROCEDURE) {
953 ProcedureRecord pr;
954 if (auto err = TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)) {
955 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
956 "Failed to deserialize ProcedureRecord record ({1}): {0}",
957 type_id.index);
958 return nullptr;
959 }
960 return CreateProcedureType(type_id, pr, ct);
961 }
962 if (cvt.kind() == LF_MFUNCTION) {
963 MemberFunctionRecord mfr;
964 if (auto err =
965 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)) {
967 GetLog(LLDBLog::Symbols), std::move(err),
968 "Failed to deserialize MemberFunctionRecord record ({1}): {0}",
969 type_id.index);
970 return nullptr;
971 }
972 return CreateFunctionType(type_id, mfr, ct);
973 }
974
975 return nullptr;
976}
977
979 // If they search for a UDT which is a forward ref, try and resolve the full
980 // decl and just map the forward ref uid to the full decl record.
981 std::optional<PdbTypeSymId> full_decl_uid;
982 if (IsForwardRefUdt(type_id, m_index->tpi())) {
983 auto expected_full_ti =
984 m_index->tpi().findFullDeclForForwardRef(type_id.index);
985 if (!expected_full_ti)
986 llvm::consumeError(expected_full_ti.takeError());
987 else if (*expected_full_ti != type_id.index) {
988 full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
989
990 // It's possible that a lookup would occur for the full decl causing it
991 // to be cached, then a second lookup would occur for the forward decl.
992 // We don't want to create a second full decl, so make sure the full
993 // decl hasn't already been cached.
994 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
995 if (full_iter != m_types.end()) {
996 TypeSP result = full_iter->second;
997 // Map the forward decl to the TypeSP for the full decl so we can take
998 // the fast path next time.
999 m_types[toOpaqueUid(type_id)] = result;
1000 return result;
1001 }
1002 }
1003 }
1004
1005 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
1007 if (auto err = ts_or_err.takeError())
1008 return nullptr;
1009 auto ts = *ts_or_err;
1010 if (!ts)
1011 return nullptr;
1012 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
1013 if (!ast_builder)
1014 return nullptr;
1015 CompilerType ct = ast_builder->GetOrCreateType(best_decl_id);
1016 if (!ct)
1017 return nullptr;
1018
1019 TypeSP result = CreateType(best_decl_id, ct);
1020 if (!result)
1021 return nullptr;
1022
1023 uint64_t best_uid = toOpaqueUid(best_decl_id);
1024 m_types[best_uid] = result;
1025 // If we had both a forward decl and a full decl, make both point to the new
1026 // type.
1027 if (full_decl_uid)
1028 m_types[toOpaqueUid(type_id)] = result;
1029
1030 return result;
1031}
1032
1034 // We can't use try_emplace / overwrite here because the process of creating
1035 // a type could create nested types, which could invalidate iterators. So
1036 // we have to do a 2-phase lookup / insert.
1037 auto iter = m_types.find(toOpaqueUid(type_id));
1038 if (iter != m_types.end())
1039 return iter->second;
1040
1041 TypeSP type = CreateAndCacheType(type_id);
1042 if (type)
1043 GetTypeList().Insert(type);
1044 return type;
1045}
1046
1048 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
1049 if (sym.kind() == S_CONSTANT)
1050 return CreateConstantSymbol(var_id, sym);
1051
1052 ModuleSP module_sp = GetObjectFile()->GetModule();
1054 TypeIndex ti;
1055 llvm::StringRef name;
1056 lldb::addr_t addr = 0;
1057 bool is_external = false;
1058 DWARFExpression location_expr;
1059 switch (sym.kind()) {
1060 case S_GDATA32:
1061 is_external = true;
1062 [[fallthrough]];
1063 case S_LDATA32: {
1064 DataSym ds(sym.kind());
1065 if (auto err = SymbolDeserializer::deserializeAs<DataSym>(sym, ds)) {
1066 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1067 "Failed to deserialize DataSym record: {0}");
1068 return nullptr;
1069 }
1070 ti = ds.Type;
1071 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
1073 name = ds.Name;
1074 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
1075 if (addr == LLDB_INVALID_ADDRESS)
1076 return nullptr;
1077 location_expr =
1078 MakeGlobalLocationExpression(ds.Segment, ds.DataOffset, module_sp);
1079 break;
1080 }
1081 case S_GTHREAD32:
1082 is_external = true;
1083 [[fallthrough]];
1084 case S_LTHREAD32: {
1085 ThreadLocalDataSym tlds(sym.kind());
1086 if (auto err =
1087 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)) {
1088 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1089 "Failed to deserialize ThreadLocalDataSym record: {0}");
1090 return nullptr;
1091 }
1092 ti = tlds.Type;
1093 name = tlds.Name;
1094 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
1096 if (addr == LLDB_INVALID_ADDRESS)
1097 return nullptr;
1098 location_expr =
1099 MakeGlobalThreadLocalLocationExpression(tlds.DataOffset, module_sp);
1100 break;
1101 }
1102 default:
1103 llvm_unreachable("unreachable!");
1104 }
1105
1106 CompUnitSP comp_unit;
1107 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
1108 // Some globals has modi points to the linker module, ignore them.
1109 if (!modi || modi >= GetNumCompileUnits())
1110 return nullptr;
1111
1112 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
1113 comp_unit = GetOrCreateCompileUnit(cci);
1114
1115 Declaration decl;
1116 PdbTypeSymId tid(ti, false);
1117 SymbolFileTypeSP type_sp =
1118 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1119 Variable::RangeList ranges;
1120 auto ts_or_err = GetTypeSystemForLanguage(comp_unit->GetLanguage());
1121 if (auto err = ts_or_err.takeError())
1122 return nullptr;
1123 auto ts = *ts_or_err;
1124 if (ts) {
1125 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
1126 ast_builder->EnsureVariable(var_id);
1127 }
1128
1129 DWARFExpressionList location(module_sp, location_expr, nullptr);
1130
1131 std::string global_name("::");
1132 global_name += name;
1133 bool artificial = false;
1134 bool location_is_constant_data = false;
1135 bool static_member = false;
1136 VariableSP var_sp = std::make_shared<Variable>(
1137 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
1138 scope, comp_unit.get(), ranges, &decl, location, is_external, artificial,
1139 location_is_constant_data, static_member);
1140
1141 return var_sp;
1142}
1143
1146 const CVSymbol &cvs) {
1147 TpiStream &tpi = m_index->tpi();
1148 ConstantSym constant(cvs.kind());
1149
1150 if (cvs.kind() != S_CONSTANT)
1151 return nullptr;
1152
1153 if (auto err =
1154 SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)) {
1155 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1156 "Failed to deserialize ConstantSym record: {0}");
1157 return nullptr;
1158 }
1159 std::string global_name("::");
1160 global_name += constant.Name;
1161 PdbTypeSymId tid(constant.Type, false);
1162 SymbolFileTypeSP type_sp =
1163 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1164
1165 Declaration decl;
1166 Variable::RangeList ranges;
1167 ModuleSP module = GetObjectFile()->GetModule();
1168 auto location_or_err = MakeConstantLocationExpression(constant.Type, tpi,
1169 constant.Value, module);
1170 if (!location_or_err) {
1171 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
1172 "Failed to make constant location expression for {1}: {0}",
1173 constant.Name);
1174 return nullptr;
1175 }
1176 DWARFExpressionList location(module, std::move(*location_or_err), nullptr);
1177
1178 bool external = false;
1179 bool artificial = false;
1180 bool location_is_constant_data = true;
1181 bool static_member = false;
1182 VariableSP var_sp = std::make_shared<Variable>(
1183 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
1184 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
1185 external, artificial, location_is_constant_data, static_member);
1186 return var_sp;
1187}
1188
1191 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
1192 if (emplace_result.second) {
1193 if (VariableSP var_sp = CreateGlobalVariable(var_id))
1194 emplace_result.first->second = var_sp;
1195 else
1196 return nullptr;
1197 }
1198
1199 return emplace_result.first->second;
1200}
1201
1203 return GetOrCreateType(PdbTypeSymId(ti, false));
1204}
1205
1207 CompileUnit &comp_unit) {
1208 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
1209 if (emplace_result.second)
1210 emplace_result.first->second = CreateFunction(func_id, comp_unit);
1211
1212 return emplace_result.first->second;
1213}
1214
1217
1218 auto emplace_result =
1219 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
1220 if (emplace_result.second) {
1221 emplace_result.first->second = CreateCompileUnit(cci);
1222 LLDB_LOG(GetLog(LLDBLog::Symbols), "failed to create compile unit for {0}",
1223 cci.m_id.modi);
1224 }
1225
1226 return emplace_result.first->second;
1227}
1228
1230 auto iter = m_blocks.find(toOpaqueUid(block_id));
1231 if (iter != m_blocks.end())
1232 return iter->second.get();
1233
1234 return CreateBlock(block_id);
1235}
1236
1239 TypeSystem *ts = decl_ctx.GetTypeSystem();
1240 if (!ts)
1241 return;
1242 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
1243 if (!ast_builder)
1244 return;
1245 ast_builder->ParseDeclsForContext(decl_ctx);
1246}
1247
1249 if (index >= GetNumCompileUnits())
1250 return CompUnitSP();
1251 assert(index < UINT16_MAX && "Invalid compile unit index");
1252 if (index >= UINT16_MAX)
1253 return nullptr;
1254
1255 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1256
1257 return GetOrCreateCompileUnit(item);
1258}
1259
1261 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1262 PdbSymUid uid(comp_unit.GetID());
1263 if (uid.kind() != PdbSymUidKind::Compiland) {
1264 assert(false && "uid of compile unit not a compiland");
1266 }
1267
1268 CompilandIndexItem *item =
1269 m_index->compilands().GetCompiland(uid.asCompiland().modi);
1270 assert(item);
1271 if (!item || !item->m_compile_opts)
1273
1274 return TranslateLanguage(item->m_compile_opts->getLanguage());
1275}
1276
1278 auto *section_list =
1279 m_objfile_sp->GetModule()->GetObjectFile()->GetSectionList();
1280 if (!section_list)
1281 return;
1282
1283 llvm::DenseMap<lldb::addr_t, llvm::SmallVector<uint32_t, 1>> symbols_by_addr;
1284 for (uint32_t i = 0, n = symtab.GetNumSymbols(); i < n; ++i) {
1285 Symbol *sym = symtab.SymbolAtIndex(i);
1286 if (sym && sym->ValueIsAddress())
1287 symbols_by_addr[sym->GetAddressRef().GetFileAddress()].push_back(i);
1288 }
1289
1290 PublicSym32 last_sym;
1291 size_t last_sym_idx = 0;
1292 lldb::SectionSP section_sp;
1293
1294 // To estimate the size of a symbol, we use the difference to the next symbol.
1295 // If there's no next symbol or the section/segment changed, the symbol will
1296 // take the remaining space. The estimate can be too high in case there's
1297 // padding between symbols. This similar to the algorithm used by the DIA
1298 // SDK.
1299 auto finish_last_symbol = [&](const PublicSym32 *next) {
1300 if (!section_sp)
1301 return;
1302 Symbol *last = symtab.SymbolAtIndex(last_sym_idx);
1303 if (!last)
1304 return;
1305
1306 if (next && last_sym.Segment == next->Segment) {
1307 if (next->Offset < last_sym.Offset) {
1309 "Ignoring size estimate for '{0}': segment {1} offset {2} is "
1310 "greater than the following offset {3}",
1311 last_sym.Name, last_sym.Segment, last_sym.Offset,
1312 next->Offset);
1313 return;
1314 }
1315 last->SetByteSize(next->Offset - last_sym.Offset);
1316 } else {
1317 // the last symbol was the last in its section
1318 if (section_sp->GetByteSize() < last_sym.Offset) {
1320 "Ignoring size estimate for '{0}': segment {1} offset {2} is "
1321 "past the end of section '{3}' (size {4})",
1322 last_sym.Name, last_sym.Segment, last_sym.Offset,
1323 section_sp->GetName(), section_sp->GetByteSize());
1324 return;
1325 }
1326 last->SetByteSize(section_sp->GetByteSize() - last_sym.Offset);
1327 }
1328 };
1329
1330 // The address map is sorted by the address of a symbol.
1331 for (auto pid : m_index->publics().getAddressMap()) {
1332 PdbGlobalSymId global{pid, true};
1333 CVSymbol sym = m_index->ReadSymbolRecord(global);
1334 auto kind = sym.kind();
1335 if (kind != S_PUB32)
1336 continue;
1337 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
1338 if (!pub_or_err) {
1339 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
1340 "Failed to deserialize PublicSym32 record: {0}");
1341 continue;
1342 }
1343 PublicSym32 pub = std::move(*pub_or_err);
1344 finish_last_symbol(&pub);
1345
1346 if (!section_sp || last_sym.Segment != pub.Segment)
1347 section_sp = section_list->FindSectionByID(pub.Segment);
1348
1349 if (!section_sp)
1350 continue;
1351
1353 if ((pub.Flags & PublicSymFlags::Function) != PublicSymFlags::None ||
1354 (pub.Flags & PublicSymFlags::Code) != PublicSymFlags::None)
1355 type = eSymbolTypeCode;
1356
1357 Symbol pub_symbol(/*symID=*/pid,
1358 /*name=*/pub.Name,
1359 /*type=*/type,
1360 /*external=*/true,
1361 /*is_debug=*/true,
1362 /*is_trampoline=*/false,
1363 /*is_artificial=*/false,
1364 /*section_sp=*/section_sp,
1365 /*value=*/pub.Offset,
1366 /*size=*/0,
1367 /*size_is_valid=*/false,
1368 /*contains_linker_annotations=*/false,
1369 /*flags=*/0);
1370
1371 auto it = symbols_by_addr.find(pub_symbol.GetAddressRef().GetFileAddress());
1372 if (it != symbols_by_addr.end() &&
1373 llvm::any_of(it->second, [&](uint32_t idx) {
1374 Symbol *sym = symtab.SymbolAtIndex(idx);
1375 return sym && sym->GetMangled() == pub_symbol.GetMangled();
1376 }))
1378
1379 last_sym_idx = symtab.AddSymbol(pub_symbol);
1380 last_sym = pub;
1381 }
1382
1383 finish_last_symbol(nullptr);
1384}
1385
1387 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1388 PdbSymUid uid{comp_unit.GetID()};
1389 if (uid.kind() != PdbSymUidKind::Compiland) {
1390 assert(false && "uid of compile unit not a compiland");
1391 return 0;
1392 }
1393 uint16_t modi = uid.asCompiland().modi;
1394 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
1395
1396 size_t count = comp_unit.GetNumFunctions();
1397 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
1398 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1399 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
1400 continue;
1401
1402 PdbCompilandSymId sym_id{modi, iter.offset()};
1403
1404 FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
1405 }
1406
1407 size_t new_count = comp_unit.GetNumFunctions();
1408 if (new_count < count) {
1409 assert(false && "less functions after parsing than before");
1410 return 0;
1411 }
1412 return new_count - count;
1413}
1414
1415static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1416 // If any of these flags are set, we need to resolve the compile unit.
1417 uint32_t flags = eSymbolContextCompUnit;
1418 flags |= eSymbolContextVariable;
1419 flags |= eSymbolContextFunction;
1420 flags |= eSymbolContextBlock;
1421 flags |= eSymbolContextLineEntry;
1422 return (resolve_scope & flags) != 0;
1423}
1424
1426 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1427 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1428 uint32_t resolved_flags = 0;
1429 lldb::addr_t file_addr = addr.GetFileAddress();
1430
1431 if (NeedsResolvedCompileUnit(resolve_scope)) {
1432 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1433 if (!modi)
1434 return 0;
1435 CompUnitSP cu_sp = GetCompileUnitAtIndex(*modi);
1436 if (!cu_sp)
1437 return 0;
1438
1439 sc.comp_unit = cu_sp.get();
1440 resolved_flags |= eSymbolContextCompUnit;
1441 }
1442
1443 if (resolve_scope & eSymbolContextFunction ||
1444 resolve_scope & eSymbolContextBlock) {
1445 if (!sc.comp_unit) {
1447 "missing compile unit for symbol at address {0:x}", file_addr);
1448 return 0;
1449 }
1450 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1451 // Search the matches in reverse. This way if there are multiple matches
1452 // (for example we are 3 levels deep in a nested scope) it will find the
1453 // innermost one first.
1454 for (const auto &match : llvm::reverse(matches)) {
1455 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1456 continue;
1457
1458 PdbCompilandSymId csid = match.uid.asCompilandSym();
1459 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1460 PDB_SymType type = CVSymToPDBSym(cvs.kind());
1461 if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1462 continue;
1463 if (type == PDB_SymType::Function) {
1464 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1465 if (sc.function) {
1466 Block &block = sc.function->GetBlock(true);
1467 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1468 addr_t offset = file_addr - func_base;
1469 sc.block = block.FindInnermostBlockByOffset(offset);
1470 }
1471 }
1472
1473 if (type == PDB_SymType::Block) {
1474 Block *block = GetOrCreateBlock(csid);
1475 if (!block)
1476 continue;
1478 if (sc.function) {
1479 sc.function->GetBlock(true);
1480 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1481 addr_t offset = file_addr - func_base;
1482 sc.block = block->FindInnermostBlockByOffset(offset);
1483 }
1484 }
1485 if (sc.function)
1486 resolved_flags |= eSymbolContextFunction;
1487 if (sc.block)
1488 resolved_flags |= eSymbolContextBlock;
1489 break;
1490 }
1491 }
1492
1493 if (resolve_scope & eSymbolContextLineEntry) {
1494 if (!sc.comp_unit) {
1496 "missing compile unit for symbol at address {0:x}", file_addr);
1497 return 0;
1498 }
1499 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1500 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1501 resolved_flags |= eSymbolContextLineEntry;
1502 }
1503 }
1504
1505 return resolved_flags;
1506}
1507
1509 const SourceLocationSpec &src_location_spec,
1510 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1511 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1512 const uint32_t prev_size = sc_list.GetSize();
1513 if (resolve_scope & eSymbolContextCompUnit) {
1514 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1515 ++cu_idx) {
1516 CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1517 if (!cu)
1518 continue;
1519
1520 bool file_spec_matches_cu_file_spec = FileSpec::Match(
1521 src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1522 if (file_spec_matches_cu_file_spec) {
1523 cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1524 break;
1525 }
1526 }
1527 }
1528 return sc_list.GetSize() - prev_size;
1529}
1530
1532 // Unfortunately LLDB is set up to parse the entire compile unit line table
1533 // all at once, even if all it really needs is line info for a specific
1534 // function. In the future it would be nice if it could set the sc.m_function
1535 // member, and we could only get the line info for the function in question.
1536 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1537 PdbSymUid cu_id(comp_unit.GetID());
1538 if (cu_id.kind() != PdbSymUidKind::Compiland) {
1539 assert(false && "uid of compile unit not a compiland");
1540 return false;
1541 }
1542 uint16_t modi = cu_id.asCompiland().modi;
1543 CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1544 if (!cii) {
1545 LLDB_LOG(GetLog(LLDBLog::Symbols), "missing compiland for modi={0}", modi);
1546 return false;
1547 }
1548
1549 // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1550 // in this CU. Add line entries into the set first so that if there are line
1551 // entries with same addres, the later is always more accurate than the
1552 // former.
1553 std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1554
1555 // This is basically a copy of the .debug$S subsections from all original COFF
1556 // object files merged together with address relocations applied. We are
1557 // looking for all DEBUG_S_LINES subsections.
1558 for (const DebugSubsectionRecord &dssr :
1559 cii->m_debug_stream.getSubsectionsArray()) {
1560 if (dssr.kind() != DebugSubsectionKind::Lines)
1561 continue;
1562
1563 DebugLinesSubsectionRef lines;
1564 llvm::BinaryStreamReader reader(dssr.getRecordData());
1565 if (auto EC = lines.initialize(reader)) {
1566 llvm::consumeError(std::move(EC));
1567 return false;
1568 }
1569
1570 const LineFragmentHeader *lfh = lines.header();
1571 uint64_t virtual_addr =
1572 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1573 if (virtual_addr == LLDB_INVALID_ADDRESS)
1574 continue;
1575
1576 for (const LineColumnEntry &group : lines) {
1577 llvm::Expected<uint32_t> file_index_or_err =
1578 GetFileIndex(*cii, group.NameIndex);
1579 if (!file_index_or_err) {
1580 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1581 "failed to get file index for line entry: {0}");
1582 continue;
1583 }
1584 uint32_t file_index = file_index_or_err.get();
1585 if (group.LineNumbers.empty()) {
1587 "no line numbers for {0} in modi={1}", group.NameIndex, modi);
1588 continue;
1589 }
1592 for (const LineNumberEntry &entry : group.LineNumbers) {
1593 LineInfo cur_info(entry.Flags);
1594
1595 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1596 continue;
1597
1598 uint64_t addr = virtual_addr + entry.Offset;
1599
1600 bool is_statement = cur_info.isStatement();
1601 bool is_prologue = IsFunctionPrologue(*cii, addr);
1602 bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1603
1604 uint32_t lno = cur_info.getStartLine();
1605
1606 LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1607 is_prologue, is_epilogue, false);
1608 // Terminal entry has lower precedence than new entry.
1609 auto iter = line_set.find(new_entry);
1610 if (iter != line_set.end() && iter->is_terminal_entry)
1611 line_set.erase(iter);
1612 line_set.insert(new_entry);
1613
1614 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1615 line_entry.SetRangeEnd(addr);
1616 cii->m_global_line_table.Append(line_entry);
1617 }
1618 line_entry.SetRangeBase(addr);
1619 line_entry.data = {file_index, lno};
1620 }
1621 LineInfo last_line(group.LineNumbers.back().Flags);
1622 line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1623 file_index, false, false, false, false, true);
1624
1625 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1626 line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1627 cii->m_global_line_table.Append(line_entry);
1628 }
1629 }
1630 }
1631
1633
1634 // Parse all S_INLINESITE in this CU.
1635 const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1636 for (auto iter = syms.begin(); iter != syms.end();) {
1637 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1638 ++iter;
1639 continue;
1640 }
1641
1642 uint32_t record_offset = iter.offset();
1643 CVSymbol func_record =
1644 cii->m_debug_stream.readSymbolAtOffset(record_offset);
1646 addr_t file_vm_addr =
1647 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
1648 if (file_vm_addr == LLDB_INVALID_ADDRESS)
1649 continue;
1650
1651 Address func_base(file_vm_addr, comp_unit.GetModule()->GetSectionList());
1652 PdbCompilandSymId func_id{modi, record_offset};
1653
1654 // Iterate all S_INLINESITEs in the function.
1655 auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1656 if (kind != S_INLINESITE)
1657 return false;
1658
1659 ParseInlineSite(id, func_base);
1660
1661 for (const auto &line_entry :
1662 m_inline_sites[toOpaqueUid(id)]->line_entries) {
1663 // If line_entry is not terminal entry, remove previous line entry at
1664 // the same address and insert new one. Terminal entry inside an inline
1665 // site might not be terminal entry for its parent.
1666 if (!line_entry.is_terminal_entry)
1667 line_set.erase(line_entry);
1668 line_set.insert(line_entry);
1669 }
1670 // No longer useful after adding to line_set.
1671 m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1672 return true;
1673 };
1674 ParseSymbolArrayInScope(func_id, parse_inline_sites);
1675 // Jump to the end of the function record.
1676 iter = syms.at(getScopeEndOffset(func_record));
1677 }
1678
1680
1681 // Add line entries in line_set to line_table.
1682 std::vector<LineTable::Sequence> sequence(1);
1683 for (const auto &line_entry : line_set) {
1685 sequence.back(), line_entry.file_addr, line_entry.line,
1686 line_entry.column, line_entry.file_idx,
1687 line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1688 line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1689 line_entry.is_terminal_entry);
1690 }
1691 auto line_table =
1692 std::make_unique<LineTable>(&comp_unit, std::move(sequence));
1693
1694 if (line_table->GetSize() == 0)
1695 return false;
1696
1697 comp_unit.SetLineTable(line_table.release());
1698 return true;
1699}
1700
1702 // PDB doesn't contain information about macros
1703 return false;
1704}
1705
1706llvm::Expected<uint32_t>
1708 uint32_t file_id) {
1709 if (!cii.m_strings.hasChecksums() || !cii.m_strings.hasStrings())
1710 return llvm::make_error<RawError>(raw_error_code::no_entry);
1711
1712 const auto &checksums = cii.m_strings.checksums().getArray();
1713 const auto &strings = cii.m_strings.strings();
1714 // Indices in this structure are actually offsets of records in the
1715 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1716 // into the global PDB string table.
1717 auto iter = checksums.at(file_id);
1718 if (iter == checksums.end())
1719 return llvm::make_error<RawError>(raw_error_code::no_entry);
1720
1721 llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1722 if (!efn) {
1723 return efn.takeError();
1724 }
1725
1726 // LLDB wants the index of the file in the list of support files.
1727 auto fn_iter = llvm::find(cii.m_file_list, *efn);
1728 if (fn_iter != cii.m_file_list.end())
1729 return std::distance(cii.m_file_list.begin(), fn_iter);
1730 return llvm::make_error<RawError>(raw_error_code::no_entry);
1731}
1732
1734 SupportFileList &support_files) {
1735 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1736 PdbSymUid cu_id(comp_unit.GetID());
1737 if (cu_id.kind() != PdbSymUidKind::Compiland) {
1738 assert(false && "uid of compile unit not a compiland");
1739 return false;
1740 }
1741 CompilandIndexItem *cci =
1742 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1743 if (!cci) {
1744 LLDB_LOG(GetLog(LLDBLog::Symbols), "missing compiland for modi={0}",
1745 cu_id.asCompiland().modi);
1746 return false;
1747 }
1748
1749 for (llvm::StringRef f : cci->m_file_list) {
1750 FileSpec::Style style =
1751 f.starts_with("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1752 FileSpec spec(f, style);
1753 support_files.Append(spec);
1754 }
1755 return true;
1756}
1757
1759 const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1760 // PDB does not yet support module debug info
1761 return false;
1762}
1763
1765 Address func_addr) {
1766 lldb::user_id_t opaque_uid = toOpaqueUid(id);
1767 if (m_inline_sites.contains(opaque_uid))
1768 return;
1769
1770 addr_t func_base = func_addr.GetFileAddress();
1771 CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1772 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1773 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1774 if (sym.kind() != S_INLINESITE)
1775 return;
1776
1777 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1778 if (auto err =
1779 SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site)) {
1780 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1781 "Failed to deserialize InlineSiteSym record: {0}");
1782 return;
1783 }
1784 PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1785
1786 std::shared_ptr<InlineSite> inline_site_sp =
1787 std::make_shared<InlineSite>(parent_id);
1788
1789 // Get the inlined function declaration info.
1790 auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1791 if (iter == cii->m_inline_map.end())
1792 return;
1793 InlineeSourceLine inlinee_line = iter->second;
1794
1795 const SupportFileList &files = comp_unit->GetSupportFiles();
1796 FileSpec decl_file;
1797 llvm::Expected<uint32_t> file_index_or_err =
1798 GetFileIndex(*cii, inlinee_line.Header->FileID);
1799 if (!file_index_or_err) {
1800 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1801 "failed to get file index for inline site: {0}");
1802 return;
1803 }
1804 uint32_t file_offset = file_index_or_err.get();
1805 decl_file = files.GetFileSpecAtIndex(file_offset);
1806 uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1807 std::unique_ptr<Declaration> decl_up =
1808 std::make_unique<Declaration>(decl_file, decl_line);
1809
1810 // Parse range and line info.
1811 uint32_t code_offset = 0;
1812 int32_t line_offset = 0;
1813 std::optional<uint32_t> code_offset_base;
1814 std::optional<uint32_t> code_offset_end;
1815 std::optional<int32_t> cur_line_offset;
1816 std::optional<int32_t> next_line_offset;
1817 std::optional<uint32_t> next_file_offset;
1818
1819 bool is_terminal_entry = false;
1820 bool is_start_of_statement = true;
1821 // The first instruction is the prologue end.
1822 bool is_prologue_end = true;
1823
1824 auto update_code_offset = [&](uint32_t code_delta) {
1825 if (!code_offset_base)
1826 code_offset_base = code_offset;
1827 else if (!code_offset_end)
1828 code_offset_end = *code_offset_base + code_delta;
1829 };
1830 auto update_line_offset = [&](int32_t line_delta) {
1831 line_offset += line_delta;
1832 if (!code_offset_base || !cur_line_offset)
1833 cur_line_offset = line_offset;
1834 else
1835 next_line_offset = line_offset;
1836 ;
1837 };
1838 auto update_file_offset = [&](uint32_t offset) {
1839 if (!code_offset_base)
1840 file_offset = offset;
1841 else
1842 next_file_offset = offset;
1843 };
1844
1845 for (auto &annot : inline_site.annotations()) {
1846 switch (annot.OpCode) {
1847 case BinaryAnnotationsOpCode::CodeOffset:
1848 case BinaryAnnotationsOpCode::ChangeCodeOffset:
1849 case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1850 code_offset += annot.U1;
1851 update_code_offset(annot.U1);
1852 break;
1853 case BinaryAnnotationsOpCode::ChangeLineOffset:
1854 update_line_offset(annot.S1);
1855 break;
1856 case BinaryAnnotationsOpCode::ChangeCodeLength:
1857 update_code_offset(annot.U1);
1858 code_offset += annot.U1;
1859 is_terminal_entry = true;
1860 break;
1861 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1862 code_offset += annot.U1;
1863 update_code_offset(annot.U1);
1864 update_line_offset(annot.S1);
1865 break;
1866 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1867 code_offset += annot.U2;
1868 update_code_offset(annot.U2);
1869 update_code_offset(annot.U1);
1870 code_offset += annot.U1;
1871 is_terminal_entry = true;
1872 break;
1873 case BinaryAnnotationsOpCode::ChangeFile:
1874 update_file_offset(annot.U1);
1875 break;
1876 default:
1877 break;
1878 }
1879
1880 // Add range if current range is finished.
1881 if (code_offset_base && code_offset_end && cur_line_offset) {
1882 inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1883 *code_offset_base, *code_offset_end - *code_offset_base,
1884 decl_line + *cur_line_offset));
1885 // Set base, end, file offset and line offset for next range.
1886 if (next_file_offset)
1887 file_offset = *next_file_offset;
1888 if (next_line_offset) {
1889 cur_line_offset = next_line_offset;
1890 next_line_offset = std::nullopt;
1891 }
1892 code_offset_base = is_terminal_entry ? std::nullopt : code_offset_end;
1893 code_offset_end = next_file_offset = std::nullopt;
1894 }
1895 if (code_offset_base && cur_line_offset) {
1896 if (is_terminal_entry) {
1897 LineTable::Entry line_entry(
1898 func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1899 file_offset, false, false, false, false, true);
1900 inline_site_sp->line_entries.push_back(line_entry);
1901 } else {
1902 LineTable::Entry line_entry(func_base + *code_offset_base,
1903 decl_line + *cur_line_offset, 0,
1904 file_offset, is_start_of_statement, false,
1905 is_prologue_end, false, false);
1906 inline_site_sp->line_entries.push_back(line_entry);
1907 is_prologue_end = false;
1908 is_start_of_statement = false;
1909 }
1910 }
1911 if (is_terminal_entry)
1912 is_start_of_statement = true;
1913 is_terminal_entry = false;
1914 }
1915
1916 inline_site_sp->ranges.Sort();
1917
1918 // Get the inlined function callsite info.
1919 std::unique_ptr<Declaration> callsite_up;
1920 if (!inline_site_sp->ranges.IsEmpty()) {
1921 auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1922 addr_t base_offset = entry->GetRangeBase();
1923 if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1924 S_INLINESITE) {
1925 // Its parent is another inline site, lookup parent site's range vector
1926 // for callsite line.
1927 ParseInlineSite(parent_id, Address(func_base));
1928 std::shared_ptr<InlineSite> parent_site =
1929 m_inline_sites[toOpaqueUid(parent_id)];
1930 FileSpec &parent_decl_file =
1931 parent_site->inline_function_info->GetDeclaration().GetFile();
1932 if (auto *parent_entry =
1933 parent_site->ranges.FindEntryThatContains(base_offset)) {
1934 callsite_up =
1935 std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1936 }
1937 } else {
1938 // Its parent is a function, lookup global line table for callsite.
1939 if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1940 func_base + base_offset)) {
1941 const FileSpec &callsite_file =
1942 files.GetFileSpecAtIndex(entry->data.first);
1943 callsite_up =
1944 std::make_unique<Declaration>(callsite_file, entry->data.second);
1945 }
1946 }
1947 }
1948
1949 // Get the inlined function name.
1950 std::string inlinee_name;
1951 llvm::Expected<CVType> inlinee_cvt =
1952 m_index->ipi().typeCollection().getTypeOrError(inline_site.Inlinee);
1953 if (!inlinee_cvt) {
1954 inlinee_name = "[error reading function name: " +
1955 llvm::toString(inlinee_cvt.takeError()) + "]";
1956 } else if (inlinee_cvt->kind() == LF_MFUNC_ID) {
1957 MemberFuncIdRecord mfr;
1958 if (auto err = TypeDeserializer::deserializeAs<MemberFuncIdRecord>(
1959 *inlinee_cvt, mfr)) {
1960 inlinee_name =
1961 "[error reading function name: " + llvm::toString(std::move(err)) +
1962 "]";
1963 } else {
1964 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1965 inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1966 inlinee_name.append("::");
1967 inlinee_name.append(mfr.getName().str());
1968 }
1969 } else if (inlinee_cvt->kind() == LF_FUNC_ID) {
1970 FuncIdRecord fir;
1971 if (auto err =
1972 TypeDeserializer::deserializeAs<FuncIdRecord>(*inlinee_cvt, fir)) {
1973 inlinee_name =
1974 "[error reading function name: " + llvm::toString(std::move(err)) +
1975 "]";
1976 } else {
1977 TypeIndex parent_idx = fir.getParentScope();
1978 if (!parent_idx.isNoneType()) {
1979 LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1980 inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1981 inlinee_name.append("::");
1982 }
1983 inlinee_name.append(fir.getName().str());
1984 }
1985 }
1986 inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1987 inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1988 callsite_up.get());
1989
1990 m_inline_sites[opaque_uid] = inline_site_sp;
1991}
1992
1994 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1995 PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1996 // After we iterate through inline sites inside the function, we already get
1997 // all the info needed, removing from the map to save memory.
1998 std::set<uint64_t> remove_uids;
1999 auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
2000 if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
2001 kind == S_INLINESITE) {
2002 GetOrCreateBlock(id);
2003 if (kind == S_INLINESITE)
2004 remove_uids.insert(toOpaqueUid(id));
2005 return true;
2006 }
2007 return false;
2008 };
2009 size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
2010 for (uint64_t uid : remove_uids) {
2011 m_inline_sites.erase(uid);
2012 }
2013
2014 func.GetBlock(false).SetBlockInfoHasBeenParsed(true, true);
2015 return count;
2016}
2017
2019 PdbCompilandSymId parent_id,
2020 llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
2021 CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
2022 CVSymbolArray syms =
2023 cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
2024
2025 size_t count = 1;
2026 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
2027 PdbCompilandSymId child_id(parent_id.modi, iter.offset());
2028 if (fn(iter->kind(), child_id))
2029 ++count;
2030 }
2031
2032 return count;
2033}
2034
2035void SymbolFileNativePDB::DumpClangAST(Stream &s, llvm::StringRef filter,
2036 bool show_color) {
2038 if (!ts_or_err) {
2039 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ts_or_err.takeError(),
2040 "failed to get C++ type system: {0}");
2041 return;
2042 }
2043 auto ts = *ts_or_err;
2044 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
2045 if (!clang)
2046 return;
2047 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
2048 if (!ast_builder)
2049 return;
2050 ast_builder->Dump(s, filter, show_color);
2051}
2052
2054 if (!m_func_full_names.IsEmpty() || !m_global_variable_base_names.IsEmpty())
2055 return;
2056
2057 // (segment, code offset) -> gid
2058 std::map<std::pair<uint16_t, uint32_t>, uint32_t> func_addr_ids;
2059
2060 // First, look through all items in the globals table.
2061 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2062 CVSymbol sym = m_index->symrecords().readRecord(gid);
2063 auto kind = sym.kind();
2064
2065 // If this is a global variable, we only need to look at the name
2066 llvm::StringRef name;
2067 switch (kind) {
2068 case SymbolKind::S_GDATA32:
2069 case SymbolKind::S_LDATA32: {
2070 auto data_or_err = SymbolDeserializer::deserializeAs<DataSym>(sym);
2071 if (!data_or_err) {
2072 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2073 "Failed to deserialize DataSym record: {0}");
2074 continue;
2075 }
2076 name = data_or_err->Name;
2077 break;
2078 }
2079 case SymbolKind::S_GTHREAD32:
2080 case SymbolKind::S_LTHREAD32: {
2081 auto data_or_err =
2082 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym);
2083 if (!data_or_err) {
2084 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2085 "Failed to deserialize ThreadLocalDataSym record: {0}");
2086 continue;
2087 }
2088 name = data_or_err->Name;
2089 break;
2090 }
2091 case SymbolKind::S_CONSTANT: {
2092 auto data_or_err = SymbolDeserializer::deserializeAs<ConstantSym>(sym);
2093 if (!data_or_err) {
2094 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2095 "Failed to deserialize ConstantSym record: {0}");
2096 continue;
2097 }
2098 name = data_or_err->Name;
2099 break;
2100 }
2101 default:
2102 break;
2103 }
2104
2105 if (!name.empty()) {
2106 llvm::StringRef base = MSVCUndecoratedNameParser::DropScope(name);
2107 if (base.empty())
2108 base = name;
2109
2110 m_global_variable_base_names.Append(ConstString(base), gid);
2111 continue;
2112 }
2113
2114 if (kind != S_PROCREF && kind != S_LPROCREF)
2115 continue;
2116
2117 // For functions, we need to follow the reference to the procedure and look
2118 // at the type
2119
2120 auto ref_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2121 if (!ref_or_err) {
2122 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ref_or_err.takeError(),
2123 "Failed to deserialize ProcRefSym record: {0}");
2124 continue;
2125 }
2126 ProcRefSym ref = std::move(*ref_or_err);
2127 if (ref.Name.empty())
2128 continue;
2129
2130 // Find the function this is referencing.
2131 CompilandIndexItem &cci =
2132 m_index->compilands().GetOrCreateCompiland(ref.modi());
2133 auto iter = cci.m_debug_stream.getSymbolArray().at(ref.SymOffset);
2134 if (iter == cci.m_debug_stream.getSymbolArray().end())
2135 continue;
2136 kind = iter->kind();
2137 if (kind != S_GPROC32 && kind != S_LPROC32)
2138 continue;
2139
2140 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcSym>(*iter);
2141 if (!proc_or_err) {
2142 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2143 "Failed to deserialize ProcSym record: {0}");
2144 continue;
2145 }
2146 ProcSym proc = std::move(*proc_or_err);
2147 if ((proc.Flags & ProcSymFlags::IsUnreachable) != ProcSymFlags::None)
2148 continue;
2149 if (proc.Name.empty() || proc.FunctionType.isSimple())
2150 continue;
2151
2152 // The function/procedure symbol only contains the demangled name.
2153 // The mangled names are in the publics table. Save the address of this
2154 // function to lookup the mangled name later.
2155 func_addr_ids.emplace(std::make_pair(proc.Segment, proc.CodeOffset), gid);
2156
2157 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(proc.Name);
2158 if (basename.empty())
2159 basename = proc.Name;
2160
2161 m_func_base_names.Append(ConstString(basename), gid);
2162 m_func_full_names.Append(ConstString(proc.Name), gid);
2163
2164 // To see if this is a member function, check the type.
2165 auto type = m_index->tpi().getType(proc.FunctionType);
2166 if (type.kind() == LF_MFUNCTION) {
2167 MemberFunctionRecord mfr;
2168 if (auto err = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2169 type, mfr)) {
2171 GetLog(LLDBLog::Symbols), std::move(err),
2172 "Failed to deserialize MemberFunctionRecord record ({1}): {0}",
2173 proc.FunctionType);
2174 } else if (!mfr.getThisType().isNoneType())
2175 m_func_method_names.Append(ConstString(basename), gid);
2176 }
2177 }
2178
2179 // The publics stream contains all mangled function names and their address.
2180 for (auto pid : m_index->publics().getPublicsTable()) {
2181 PdbGlobalSymId global{pid, true};
2182 CVSymbol sym = m_index->ReadSymbolRecord(global);
2183 auto kind = sym.kind();
2184 if (kind != S_PUB32)
2185 continue;
2186 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
2187 if (!pub_or_err) {
2188 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
2189 "Failed to deserialize PublicSym32 record: {0}");
2190 continue;
2191 }
2192 PublicSym32 pub = std::move(*pub_or_err);
2193 // We only care about mangled names - if the name isn't mangled, it's
2194 // already in the full name map.
2195 if (!Mangled::IsMangledName(pub.Name))
2196 continue;
2197
2198 // Check if this symbol is for one of our functions.
2199 auto it = func_addr_ids.find({pub.Segment, pub.Offset});
2200 if (it != func_addr_ids.end())
2201 m_func_full_names.Append(ConstString(pub.Name), it->second);
2202 }
2203
2204 // Sort them before value searching is working properly.
2205 m_func_full_names.Sort(std::less<uint32_t>());
2206 m_func_full_names.SizeToFit();
2207 m_func_method_names.Sort(std::less<uint32_t>());
2208 m_func_method_names.SizeToFit();
2209 m_func_base_names.Sort(std::less<uint32_t>());
2210 m_func_base_names.SizeToFit();
2211 m_global_variable_base_names.Sort(std::less<uint32_t>());
2212 m_global_variable_base_names.SizeToFit();
2213}
2214
2216 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2217 uint32_t max_matches, VariableList &variables) {
2218 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2219
2221
2222 std::vector<uint32_t> results;
2223 m_global_variable_base_names.GetValues(name, results);
2224
2225 size_t n_matches = 0;
2226 for (uint32_t gid : results) {
2227 PdbGlobalSymId global(gid, false);
2228
2229 if (parent_decl_ctx.IsValid() &&
2230 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2231 continue;
2232
2234 if (!var)
2235 continue;
2236 variables.AddVariable(var);
2237
2238 if (++n_matches >= max_matches)
2239 break;
2240 }
2241}
2242
2244 const Module::LookupInfo &lookup_info,
2245 const CompilerDeclContext &parent_decl_ctx, bool include_inlines,
2246 SymbolContextList &sc_list) {
2247 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2248 ConstString name = lookup_info.GetLookupName();
2249 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2250 if (name_type_mask & eFunctionNameTypeFull)
2251 name = lookup_info.GetName();
2252
2253 if (!(name_type_mask & eFunctionNameTypeFull ||
2254 name_type_mask & eFunctionNameTypeBase ||
2255 name_type_mask & eFunctionNameTypeMethod))
2256 return;
2258
2259 std::set<uint32_t> resolved_ids; // avoid duplicate lookups
2260 auto resolve_from = [&](UniqueCStringMap<uint32_t> &Names) {
2261 std::vector<uint32_t> ids;
2262 if (!Names.GetValues(name, ids))
2263 return;
2264
2265 for (uint32_t id : ids) {
2266 if (!resolved_ids.insert(id).second)
2267 continue;
2268
2269 PdbGlobalSymId global{id, false};
2270 if (parent_decl_ctx.IsValid() &&
2271 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2272 continue;
2273
2274 CVSymbol sym = m_index->ReadSymbolRecord(global);
2275 auto kind = sym.kind();
2276 if (kind != S_PROCREF && kind != S_LPROCREF) {
2277 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a proc reference",
2278 global);
2279 continue;
2280 }
2281
2282 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2283 if (!proc_or_err) {
2284 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2285 "Failed to deserialize ProcRefSym record: {0}");
2286 continue;
2287 }
2288 ProcRefSym proc = std::move(*proc_or_err);
2289
2290 if (!IsValidRecord(proc))
2291 continue;
2292
2293 CompilandIndexItem &cci =
2294 m_index->compilands().GetOrCreateCompiland(proc.modi());
2295 SymbolContext sc;
2296
2297 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
2298 if (!sc.comp_unit)
2299 continue;
2300
2301 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
2302 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
2303 if (!sc.function)
2304 continue;
2305
2306 sc_list.Append(sc);
2307 }
2308 };
2309
2310 if (name_type_mask & eFunctionNameTypeFull)
2311 resolve_from(m_func_full_names);
2312 if (name_type_mask & eFunctionNameTypeBase)
2313 resolve_from(m_func_base_names);
2314 if (name_type_mask & eFunctionNameTypeMethod)
2315 resolve_from(m_func_method_names);
2316}
2317
2319 bool include_inlines,
2320 SymbolContextList &sc_list) {}
2321
2323 lldb_private::TypeResults &results) {
2324
2325 // Make sure we haven't already searched this SymbolFile before.
2326 if (results.AlreadySearched(this))
2327 return;
2328
2329 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2330
2332
2333 // We can't query for the full name because the type might reside
2334 // in an anonymous namespace. Search for the basename in our map and check the
2335 // matching types afterwards.
2336 std::vector<uint32_t> matches;
2337 m_type_base_names.GetValues(query.GetTypeBasename(), matches);
2338
2339 for (uint32_t match_idx : matches) {
2340 std::vector context = GetContextForType(TypeIndex(match_idx));
2341 if (context.empty())
2342 continue;
2343
2344 if (query.ContextMatches(context)) {
2345 TypeSP type_sp = GetOrCreateType(TypeIndex(match_idx));
2346 if (!type_sp)
2347 continue;
2348
2349 results.InsertUnique(type_sp);
2350 if (results.Done(query))
2351 return;
2352 }
2353 }
2354}
2355
2357 uint32_t max_matches,
2358 TypeMap &types) {
2359
2360 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
2361 if (max_matches > 0 && max_matches < matches.size())
2362 matches.resize(max_matches);
2363
2364 for (TypeIndex ti : matches) {
2365 TypeSP type = GetOrCreateType(ti);
2366 if (!type)
2367 continue;
2368
2369 types.Insert(type);
2370 }
2371}
2372
2374 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2375 // Only do the full type scan the first time.
2377 return 0;
2378
2379 const size_t old_count = GetTypeList().GetSize();
2380 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2381
2382 // First process the entire TPI stream.
2383 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2384 TypeSP type = GetOrCreateType(*ti);
2385 if (type)
2386 (void)type->GetFullCompilerType();
2387 }
2388
2389 // Next look for S_UDT records in the globals stream.
2390 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2391 PdbGlobalSymId global{gid, false};
2392 CVSymbol sym = m_index->ReadSymbolRecord(global);
2393 if (sym.kind() != S_UDT)
2394 continue;
2395
2396 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2397 if (!udt_or_err) {
2398 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2399 "Failed to deserialize UDTSym record: {0}");
2400 continue;
2401 }
2402 UDTSym udt = std::move(*udt_or_err);
2403 bool is_typedef = true;
2404 if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
2405 CVType cvt = m_index->tpi().getType(udt.Type);
2406 llvm::StringRef name = CVTagRecord::create(cvt).name();
2407 if (name == udt.Name)
2408 is_typedef = false;
2409 }
2410
2411 if (is_typedef)
2412 GetOrCreateTypedef(global);
2413 }
2414
2415 const size_t new_count = GetTypeList().GetSize();
2416
2417 m_done_full_type_scan = true;
2418
2419 return new_count - old_count;
2420}
2421
2422size_t
2424 VariableList &variables) {
2425 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2426 PdbGlobalSymId global{gid, false};
2427 CVSymbol sym = m_index->ReadSymbolRecord(global);
2428 // TODO: S_CONSTANT is not handled here to prevent a possible crash in
2429 // lldb_private::npdb::MakeConstantLocationExpression when it's a record
2430 // type (e.g. std::strong_ordering::equal). That function needs to be
2431 // updated to handle this case when we add S_CONSTANT case here.
2432 switch (sym.kind()) {
2433 case SymbolKind::S_GDATA32:
2434 case SymbolKind::S_LDATA32:
2435 case SymbolKind::S_GTHREAD32:
2436 case SymbolKind::S_LTHREAD32: {
2437 if (VariableSP var = GetOrCreateGlobalVariable(global))
2438 variables.AddVariable(var);
2439 break;
2440 }
2441 default:
2442 break;
2443 }
2444 }
2445 return variables.GetSize();
2446}
2447
2449 PdbCompilandSymId var_id,
2450 bool is_param,
2451 bool is_constant) {
2452 ModuleSP module = GetObjectFile()->GetModule();
2453 Block *block = GetOrCreateBlock(scope_id);
2454 if (!block)
2455 return nullptr;
2456
2457 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
2458 if (!cii)
2459 return nullptr;
2460 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
2461
2462 VariableInfo var_info;
2463 bool location_is_constant_data = is_constant;
2464
2465 if (is_constant) {
2466 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(var_id.offset);
2467 if (sym.kind() != S_CONSTANT)
2468 return nullptr;
2469 ConstantSym constant(sym.kind());
2470 if (auto err =
2471 SymbolDeserializer::deserializeAs<ConstantSym>(sym, constant)) {
2472 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2473 "Failed to deserialize ConstantSym record: {0}");
2474 return nullptr;
2475 }
2476
2477 var_info.name = constant.Name;
2478 var_info.type = constant.Type;
2479 auto location_or_err = MakeConstantLocationExpression(
2480 constant.Type, m_index->tpi(), constant.Value, module);
2481 if (!location_or_err) {
2482 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
2483 "Failed to make constant location expression for {1}: {0}",
2484 constant.Name);
2485 return nullptr;
2486 }
2487 var_info.location =
2488 DWARFExpressionList(module, std::move(*location_or_err), nullptr);
2489 } else {
2490 // Get function block.
2491 Block *func_block = block;
2492 while (func_block->GetParent())
2493 func_block = func_block->GetParent();
2494
2495 Address addr;
2496 func_block->GetStartAddress(addr);
2497 var_info = GetVariableLocationInfo(*m_index, var_id, *func_block, module);
2498 Function *func = func_block->CalculateSymbolContextFunction();
2499 if (!func)
2500 return nullptr;
2501 // Use empty dwarf expr if optimized away so that it won't be filtered out
2502 // when lookuping local variables in this scope.
2503 if (!var_info.location.IsValid())
2504 var_info.location =
2505 DWARFExpressionList(module, DWARFExpression(), nullptr);
2507 }
2508
2509 TypeSP type_sp = GetOrCreateType(var_info.type);
2510 if (!type_sp)
2511 return nullptr;
2512 std::string name = var_info.name.str();
2513 Declaration decl;
2514 SymbolFileTypeSP sftype =
2515 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
2516
2517 is_param |= var_info.is_param;
2518 ValueType var_scope =
2520 bool external = false;
2521 bool artificial = false;
2522 bool static_member = false;
2523 Variable::RangeList scope_ranges;
2524 VariableSP var_sp = std::make_shared<Variable>(
2525 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope, block,
2526 scope_ranges, &decl, var_info.location, external, artificial,
2527 location_is_constant_data, static_member);
2528 if (!is_param) {
2529 auto ts_or_err = GetTypeSystemForLanguage(comp_unit_sp->GetLanguage());
2530 if (auto err = ts_or_err.takeError())
2531 return nullptr;
2532 auto ts = *ts_or_err;
2533 if (ts) {
2534 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
2535 ast_builder->EnsureVariable(scope_id, var_id);
2536 }
2537 }
2538 m_local_variables[toOpaqueUid(var_id)] = var_sp;
2539 return var_sp;
2540}
2541
2544 PdbCompilandSymId var_id,
2545 bool is_param, bool is_constant) {
2546 auto iter = m_local_variables.find(toOpaqueUid(var_id));
2547 if (iter != m_local_variables.end())
2548 return iter->second;
2549
2550 return CreateLocalVariable(scope_id, var_id, is_param, is_constant);
2551}
2552
2554 CVSymbol sym = m_index->ReadSymbolRecord(id);
2555 if (sym.kind() != S_UDT) {
2556 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not an S_UDT", id);
2557 return nullptr;
2558 }
2559
2560 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2561 if (!udt_or_err) {
2562 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2563 "Failed to deserialize UDTSym record: {0}");
2564 return nullptr;
2565 }
2566 UDTSym udt = std::move(*udt_or_err);
2567
2568 TypeSP target_type = GetOrCreateType(udt.Type);
2569
2571 if (auto err = ts_or_err.takeError())
2572 return nullptr;
2573 auto ts = *ts_or_err;
2574 if (!ts)
2575 return nullptr;
2576 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2577 if (!ast_builder)
2578 return nullptr;
2579 CompilerType ct = ast_builder->GetOrCreateTypedefType(id);
2580 if (!ct)
2581 ct = target_type->GetForwardCompilerType();
2582
2583 Declaration decl;
2584 return MakeType(toOpaqueUid(id), ConstString(udt.Name),
2585 llvm::expectedToOptional(target_type->GetByteSize(nullptr)),
2586 nullptr, target_type->GetID(),
2589}
2590
2592 auto iter = m_types.find(toOpaqueUid(id));
2593 if (iter != m_types.end())
2594 return iter->second;
2595
2596 return CreateTypedef(id);
2597}
2598
2600 Block *block = GetOrCreateBlock(block_id);
2601 if (!block)
2602 return 0;
2603
2604 size_t count = 0;
2605
2606 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
2607 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
2608 uint32_t params_remaining = 0;
2609 switch (sym.kind()) {
2610 case S_GPROC32:
2611 case S_LPROC32: {
2612 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
2613 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym, proc)) {
2614 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2615 "Failed to deserialize ProcSym record: {0}");
2616 return 0;
2617 }
2618 CVType signature = m_index->tpi().getType(proc.FunctionType);
2619 if (signature.kind() == LF_PROCEDURE) {
2620 ProcedureRecord sig;
2621 if (llvm::Error e = TypeDeserializer::deserializeAs<ProcedureRecord>(
2622 signature, sig)) {
2623 llvm::consumeError(std::move(e));
2624 return 0;
2625 }
2626 params_remaining = sig.getParameterCount();
2627 } else if (signature.kind() == LF_MFUNCTION) {
2628 MemberFunctionRecord sig;
2629 if (llvm::Error e = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2630 signature, sig)) {
2631 llvm::consumeError(std::move(e));
2632 return 0;
2633 }
2634 params_remaining = sig.getParameterCount();
2635 } else
2636 return 0;
2637 break;
2638 }
2639 case S_BLOCK32:
2640 break;
2641 case S_INLINESITE:
2642 break;
2643 default:
2644 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a block", block_id);
2645 return 0;
2646 }
2647
2648 VariableListSP variables = block->GetBlockVariableList(false);
2649 if (!variables) {
2650 variables = std::make_shared<VariableList>();
2651 block->SetVariableList(variables);
2652 }
2653
2654 CVSymbolArray syms = limitSymbolArrayToScope(
2655 cii->m_debug_stream.getSymbolArray(), block_id.offset);
2656
2657 // Skip the first record since it's a PROC32 or BLOCK32, and there's
2658 // no point examining it since we know it's not a local variable.
2659 syms.drop_front();
2660 auto iter = syms.begin();
2661 auto end = syms.end();
2662
2663 while (iter != end) {
2664 uint32_t record_offset = iter.offset();
2665 CVSymbol variable_cvs = *iter;
2666 PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
2667 ++iter;
2668
2669 // If this is a block or inline site, recurse into its children and then
2670 // skip it.
2671 if (variable_cvs.kind() == S_BLOCK32 ||
2672 variable_cvs.kind() == S_INLINESITE) {
2673 uint32_t block_end = getScopeEndOffset(variable_cvs);
2674 count += ParseVariablesForBlock(child_sym_id);
2675 iter = syms.at(block_end);
2676 continue;
2677 }
2678
2679 bool is_param = params_remaining > 0;
2680 VariableSP variable;
2681 switch (variable_cvs.kind()) {
2682 case S_REGREL32:
2683 case S_REGREL32_INDIR:
2684 case S_REGISTER:
2685 case S_LOCAL:
2686 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
2687 if (is_param)
2688 --params_remaining;
2689 if (variable)
2690 variables->AddVariableIfUnique(variable);
2691 break;
2692 case S_CONSTANT:
2693 variable = GetOrCreateLocalVariable(block_id, child_sym_id,
2694 /*is_param=*/false,
2695 /*is_constant=*/true);
2696 if (variable)
2697 variables->AddVariableIfUnique(variable);
2698 break;
2699 default:
2700 break;
2701 }
2702 }
2703
2704 // Pass false for set_children, since we call this recursively so that the
2705 // children will call this for themselves.
2706 block->SetDidParseVariables(true, false);
2707
2708 return count;
2709}
2710
2712 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2713
2714 if (sc.block) {
2715 PdbSymUid block_id(sc.block->GetID());
2716
2717 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2718 return count;
2719 }
2720
2721 if (sc.function) {
2722 PdbSymUid block_id(sc.function->GetID());
2723
2724 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2725 return count;
2726 }
2727
2728 if (sc.comp_unit) {
2729 VariableListSP variables = sc.comp_unit->GetVariableList(false);
2730 if (!variables) {
2731 variables = std::make_shared<VariableList>();
2732 sc.comp_unit->SetVariableList(variables);
2733 }
2734 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
2735 }
2736
2738 "missing missing block, function, or module for symbol context");
2739 return 0;
2740}
2741
2744 if (auto err = ts_or_err.takeError())
2745 return CompilerDecl();
2746 auto ts = *ts_or_err;
2747 if (!ts)
2748 return {};
2749 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2750 if (!ast_builder)
2751 return {};
2752 return ast_builder->GetOrCreateDeclForUid(uid);
2753}
2754
2758 if (auto err = ts_or_err.takeError())
2759 return {};
2760 auto ts = *ts_or_err;
2761 if (!ts)
2762 return {};
2763 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2764 if (!ast_builder)
2765 return {};
2766 return ast_builder->GetOrCreateDeclContextForUid(PdbSymUid(uid));
2767}
2768
2772 if (auto err = ts_or_err.takeError())
2773 return CompilerDeclContext();
2774 auto ts = *ts_or_err;
2775 if (!ts)
2776 return {};
2777 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2778 if (!ast_builder)
2779 return {};
2780 return ast_builder->GetParentDeclContext(PdbSymUid(uid));
2781}
2782
2784 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2785 auto iter = m_types.find(type_uid);
2786 // lldb should not be passing us non-sensical type uids. the only way it
2787 // could have a type uid in the first place is if we handed it out, in which
2788 // case we should know about the type. However, that doesn't mean we've
2789 // instantiated it yet. We can vend out a UID for a future type. So if the
2790 // type doesn't exist, let's instantiate it now.
2791 if (iter != m_types.end())
2792 return &*iter->second;
2793
2794 PdbSymUid uid(type_uid);
2795 if (uid.kind() != PdbSymUidKind::Type) {
2796 assert(false && "uid is not a type index");
2797 return nullptr;
2798 }
2799 PdbTypeSymId type_id = uid.asTypeSym();
2800 if (type_id.index.isNoneType())
2801 return nullptr;
2802
2803 TypeSP type_sp = CreateAndCacheType(type_id);
2804 if (!type_sp)
2805 return nullptr;
2806 return &*type_sp;
2807}
2808
2809std::optional<SymbolFile::ArrayInfo>
2811 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
2812 return std::nullopt;
2813}
2814
2816 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2817 auto ts = compiler_type.GetTypeSystem();
2818 if (!ts)
2819 return false;
2820
2821 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2822 if (!ast_builder)
2823 return false;
2824 return ast_builder->CompleteType(compiler_type);
2825}
2826
2828 TypeClass type_mask,
2829 lldb_private::TypeList &type_list) {}
2830
2833 const CompilerDeclContext &parent_decl_ctx,
2834 bool /* only_root_namespaces */) {
2835 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2837 if (auto err = ts_or_err.takeError())
2838 return {};
2839 auto ts = *ts_or_err;
2840 if (!ts)
2841 return {};
2842 auto *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
2843 if (!clang)
2844 return {};
2845
2846 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
2847 if (!ast_builder)
2848 return {};
2849
2850 return ast_builder->FindNamespaceDecl(parent_decl_ctx, name.GetStringRef());
2851}
2852
2853llvm::Expected<lldb::TypeSystemSP>
2855 auto type_system_or_err =
2856 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
2857 if (type_system_or_err)
2858 if (auto ts = *type_system_or_err)
2859 ts->SetSymbolFile(this);
2860 return type_system_or_err;
2861}
2862
2863uint64_t SymbolFileNativePDB::GetDebugInfoSize(bool load_all_debug_info) {
2864 // PDB files are a separate file that contains all debug info.
2865 return m_index->pdb().getFileSize();
2866}
2867
2870 return;
2871 m_parent_map_built = true;
2872
2873 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2874
2875 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
2876 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
2877
2878 struct RecordIndices {
2879 TypeIndex forward;
2880 TypeIndex full;
2881 };
2882
2883 llvm::StringMap<RecordIndices> record_indices;
2884
2885 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2886 CVType type = types.getType(*ti);
2887 if (!IsTagRecord(type))
2888 continue;
2889
2890 CVTagRecord tag = CVTagRecord::create(type);
2891
2892 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
2893 if (tag.asTag().isForwardRef()) {
2894 indices.forward = *ti;
2895 } else {
2896 indices.full = *ti;
2897
2898 auto base_name = MSVCUndecoratedNameParser::DropScope(tag.name());
2899 m_type_base_names.Append(ConstString(base_name), ti->getIndex());
2900 }
2901
2902 if (indices.full != TypeIndex::None() &&
2903 indices.forward != TypeIndex::None()) {
2904 forward_to_full[indices.forward] = indices.full;
2905 full_to_forward[indices.full] = indices.forward;
2906 }
2907
2908 // We're looking for LF_NESTTYPE records in the field list, so ignore
2909 // forward references (no field list), and anything without a nested class
2910 // (since there won't be any LF_NESTTYPE records).
2911 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
2912 continue;
2913
2914 struct ProcessTpiStream : public TypeVisitorCallbacks {
2915 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
2916 const CVTagRecord &parent_cvt,
2917 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
2918 : index(index), parents(parents), parent(parent),
2919 parent_cvt(parent_cvt) {}
2920
2921 PdbIndex &index;
2922 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
2923
2924 unsigned unnamed_type_index = 1;
2925 TypeIndex parent;
2926 const CVTagRecord &parent_cvt;
2927
2928 llvm::Error visitKnownMember(CVMemberRecord &CVR,
2929 NestedTypeRecord &Record) override {
2930 std::string unnamed_type_name;
2931 if (Record.Name.empty()) {
2932 unnamed_type_name =
2933 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
2934 Record.Name = unnamed_type_name;
2935 ++unnamed_type_index;
2936 }
2937 std::optional<CVTagRecord> tag =
2938 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
2939 if (!tag)
2940 return llvm::ErrorSuccess();
2941
2942 parents[Record.Type] = parent;
2943 return llvm::ErrorSuccess();
2944 }
2945 };
2946
2947 CVType field_list_cvt = m_index->tpi().getType(tag.asTag().FieldList);
2948 if (field_list_cvt.kind() != LF_FIELDLIST)
2949 continue; // Invalid reference to a field list.
2950
2951 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
2952 FieldListRecord field_list;
2953 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
2954 field_list_cvt, field_list))
2955 llvm::consumeError(std::move(error));
2956 if (llvm::Error error = visitMemberRecordStream(field_list.Data, process))
2957 llvm::consumeError(std::move(error));
2958 }
2959
2960 // After calling Append(), the type-name map needs to be sorted again to be
2961 // able to look up a type by its name.
2962 m_type_base_names.Sort(std::less<uint32_t>());
2963
2964 // Now that we know the forward -> full mapping of all type indices, we can
2965 // re-write all the indices. At the end of this process, we want a mapping
2966 // consisting of fwd -> full and full -> full for all child -> parent indices.
2967 // We can re-write the values in place, but for the keys, we must save them
2968 // off so that we don't modify the map in place while also iterating it.
2969 std::vector<TypeIndex> full_keys;
2970 std::vector<TypeIndex> fwd_keys;
2971 for (auto &entry : m_parent_types) {
2972 TypeIndex key = entry.first;
2973 TypeIndex value = entry.second;
2974
2975 auto iter = forward_to_full.find(value);
2976 if (iter != forward_to_full.end())
2977 entry.second = iter->second;
2978
2979 iter = forward_to_full.find(key);
2980 if (iter != forward_to_full.end())
2981 fwd_keys.push_back(key);
2982 else
2983 full_keys.push_back(key);
2984 }
2985 for (TypeIndex fwd : fwd_keys) {
2986 TypeIndex full = forward_to_full[fwd];
2987 TypeIndex parent_idx = m_parent_types[fwd];
2988 m_parent_types[full] = parent_idx;
2989 }
2990 for (TypeIndex full : full_keys) {
2991 TypeIndex fwd = full_to_forward[full];
2992 m_parent_types[fwd] = m_parent_types[full];
2993 }
2994}
2995
2996std::optional<PdbCompilandSymId>
2998 CVSymbol sym = m_index->ReadSymbolRecord(id);
2999 if (symbolOpensScope(sym.kind())) {
3000 // If this exact symbol opens a scope, we can just directly access its
3001 // parent.
3002 id.offset = getScopeParentOffset(sym);
3003 // Global symbols have parent offset of 0. Return std::nullopt to indicate
3004 // this.
3005 if (id.offset == 0)
3006 return std::nullopt;
3007 return id;
3008 }
3009
3010 // Otherwise we need to start at the beginning and iterate forward until we
3011 // reach (or pass) this particular symbol
3012 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(id.modi);
3013 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
3014
3015 auto begin = syms.begin();
3016 auto end = syms.at(id.offset);
3017 std::vector<PdbCompilandSymId> scope_stack;
3018
3019 while (begin != end) {
3020 if (begin.offset() > id.offset) {
3021 // We passed it. We couldn't even find this symbol record.
3022 LLDB_LOG(GetLog(LLDBLog::Symbols), "invalid compiland symbol id: {0}",
3023 id);
3024 return std::nullopt;
3025 }
3026
3027 // We haven't found the symbol yet. Check if we need to open or close the
3028 // scope stack.
3029 if (symbolOpensScope(begin->kind())) {
3030 // We can use the end offset of the scope to determine whether or not
3031 // we can just outright skip this entire scope.
3032 uint32_t scope_end = getScopeEndOffset(*begin);
3033 if (scope_end < id.offset) {
3034 begin = syms.at(scope_end);
3035 } else {
3036 // The symbol we're looking for is somewhere in this scope.
3037 scope_stack.emplace_back(id.modi, begin.offset());
3038 }
3039 } else if (symbolEndsScope(begin->kind())) {
3040 scope_stack.pop_back();
3041 }
3042 ++begin;
3043 }
3044 if (scope_stack.empty())
3045 return std::nullopt;
3046 // We have a match! Return the top of the stack
3047 return scope_stack.back();
3048}
3049
3050std::optional<llvm::codeview::TypeIndex>
3051SymbolFileNativePDB::GetParentType(llvm::codeview::TypeIndex ti) {
3053 auto parent_iter = m_parent_types.find(ti);
3054 if (parent_iter == m_parent_types.end())
3055 return std::nullopt;
3056 return parent_iter->second;
3057}
3058
3059std::vector<CompilerContext>
3061 CVType type = m_index->tpi().getType(ti);
3062 if (!IsTagRecord(type))
3063 return {};
3064
3065 CVTagRecord tag = CVTagRecord::create(type);
3066
3067 std::optional<Type::ParsedName> parsed_name =
3069 if (!parsed_name)
3070 return {{tag.contextKind(), ConstString(tag.name())}};
3071
3072 std::vector<CompilerContext> ctx;
3073 // assume everything is a namespace at first
3074 for (llvm::StringRef scope : parsed_name->scope) {
3075 ctx.emplace_back(CompilerContextKind::Namespace, ConstString(scope));
3076 }
3077 // we know the kind of our own type
3078 ctx.emplace_back(tag.contextKind(), ConstString(parsed_name->basename));
3079
3080 // try to find the kind of parents
3081 for (auto &el : llvm::reverse(llvm::drop_end(ctx))) {
3082 std::optional<TypeIndex> parent = GetParentType(ti);
3083 if (!parent)
3084 break;
3085
3086 ti = *parent;
3087 type = m_index->tpi().getType(ti);
3088 switch (type.kind()) {
3089 case LF_CLASS:
3090 case LF_STRUCTURE:
3091 case LF_INTERFACE:
3093 continue;
3094 case LF_UNION:
3096 continue;
3097 case LF_ENUM:
3098 el.kind = CompilerContextKind::Enum;
3099 continue;
3100 default:
3101 break;
3102 }
3103 break;
3104 }
3105 return ctx;
3106}
3107
3108std::optional<llvm::StringRef>
3110 TypeIndex function_type) {
3111 auto symbol = m_index->publics().findByAddress(m_index->symrecords(),
3112 so.segment, so.offset);
3113 if (!symbol)
3114 return std::nullopt;
3115
3116 llvm::StringRef name = symbol->first.Name;
3117 // For functions, we might need to strip the mangled name. See
3118 // StripMangledFunctionName for more info.
3119 if (!function_type.isNoneType() &&
3120 (symbol->first.Flags & PublicSymFlags::Function) != PublicSymFlags::None)
3121 name = StripMangledFunctionName(name, function_type);
3122
3123 return name;
3124}
3125
3126llvm::StringRef
3128 PdbTypeSymId func_ty) {
3129 // "In non-64 bit environments" (on x86 in pactice), __cdecl functions get
3130 // prefixed with an underscore. For compilers using LLVM, this happens in LLVM
3131 // (as opposed to the compiler frontend). Because of this, DWARF doesn't
3132 // contain the "full" mangled name in DW_AT_linkage_name for these functions.
3133 // We strip the mangling here for compatibility with DWARF. See
3134 // llvm.org/pr161676 and
3135 // https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names#FormatC
3136
3137 if (!mangled.starts_with('_') ||
3138 m_index->dbi().getMachineType() != PDB_Machine::x86)
3139 return mangled;
3140
3141 CVType cvt = m_index->tpi().getType(func_ty.index);
3142 PDB_CallingConv cc = PDB_CallingConv::NearC;
3143 if (cvt.kind() == LF_PROCEDURE) {
3144 ProcedureRecord proc;
3145 if (llvm::Error error =
3146 TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, proc))
3147 llvm::consumeError(std::move(error));
3148 cc = proc.CallConv;
3149 } else if (cvt.kind() == LF_MFUNCTION) {
3150 MemberFunctionRecord mfunc;
3151 if (llvm::Error error =
3152 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfunc))
3153 llvm::consumeError(std::move(error));
3154 cc = mfunc.CallConv;
3155 } else {
3156 LLDB_LOG(GetLog(LLDBLog::Symbols), "Unexpected function type, got {0}",
3157 cvt.kind());
3158 return mangled;
3159 }
3160
3161 if (cc == PDB_CallingConv::NearC || cc == PDB_CallingConv::FarC)
3162 return mangled.drop_front();
3163
3164 return mangled;
3165}
3166
3167std::string
3169 llvm::StringRef lookup_name) {
3170 if (lookup_name.empty())
3171 return {};
3172
3173 lldb::ModuleSP module_sp = m_objfile_sp->GetModule();
3174 if (!module_sp)
3175 return {};
3176
3177 // Note, discriminator is added by Clang during mangling.
3178 return FunctionCallLabel{/*discriminator=*/{},
3179 /*module_id=*/module_sp->GetID(),
3180 /*symbol_id=*/uid.toOpaqueId(),
3181 /*lookup_name=*/lookup_name}
3182 .toString();
3183}
3184
3186 const CompilandIndexItem *cci = m_index->compilands().GetCompiland(id.modi);
3187 if (!cci)
3188 return {};
3189
3190 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(id.offset);
3191 if (sym_record.kind() != S_LPROC32 && sym_record.kind() != S_GPROC32)
3192 return {};
3193
3194 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
3195 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)) {
3196 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3197 "Failed to deserialize ProcSym record: {0}");
3198 return {};
3199 }
3200
3201 // Functions with internal linkage have no public symbol, so fall back to the
3202 // name in the procedure record.
3203 llvm::StringRef lookup_name =
3204 FindMangledSymbol(SegmentOffset(proc.Segment, proc.CodeOffset),
3205 proc.FunctionType)
3206 .value_or(proc.Name);
3207 return MakeFunctionCallLabel(id, lookup_name);
3208}
3209
3210std::string
3212 llvm::StringRef qualified_name) {
3213 if (std::optional<PdbCompilandSymId> func_id =
3214 FindMethodDefinition(qualified_name, method_type))
3215 return GetFunctionCallLabel(*func_id);
3216 return {};
3217}
3218
3219std::optional<PdbCompilandSymId>
3220SymbolFileNativePDB::FindMethodDefinition(llvm::StringRef qualified_name,
3221 TypeIndex method_type) {
3222 // GSIHashTable leaves its bucket map uninitialized when the table has no
3223 // records, so findRecordsByName cannot be called on it.
3224 if (m_index->globals().getGlobalsTable().HashRecords.empty())
3225 return std::nullopt;
3226
3227 Log *log = GetLog(LLDBLog::Symbols);
3228 for (const auto &[offset, sym] : m_index->globals().findRecordsByName(
3229 qualified_name, m_index->symrecords())) {
3230 if (sym.kind() != S_PROCREF && sym.kind() != S_LPROCREF)
3231 continue;
3232 auto ref_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
3233 if (!ref_or_err) {
3234 LLDB_LOG_ERROR(log, ref_or_err.takeError(),
3235 "Failed to deserialize ProcRefSym record: {0}");
3236 continue;
3237 }
3238
3239 // Nothing else may have loaded the compiland of the definition yet.
3240 CompilandIndexItem &cci =
3241 m_index->compilands().GetOrCreateCompiland(ref_or_err->modi());
3242 auto iter = cci.m_debug_stream.getSymbolArray().at(ref_or_err->SymOffset);
3243 if (iter == cci.m_debug_stream.getSymbolArray().end())
3244 continue;
3245 if (iter->kind() != S_GPROC32 && iter->kind() != S_LPROC32)
3246 continue;
3247 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcSym>(*iter);
3248 if (!proc_or_err) {
3249 LLDB_LOG_ERROR(log, proc_or_err.takeError(),
3250 "Failed to deserialize ProcSym record: {0}");
3251 continue;
3252 }
3253
3254 // Overloads share the name, so only the type identifies the definition.
3255 if (proc_or_err->FunctionType == method_type)
3256 return PdbCompilandSymId(ref_or_err->modi(), ref_or_err->SymOffset);
3257 }
3258 return std::nullopt;
3259}
3260
3261llvm::Expected<SymbolContext>
3263 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3264
3265 // Only complete and base object structors have a procedure record. Closures
3266 // and deleting destructors have no debug info.
3267 if (llvm::StringRef discriminator = label.discriminator;
3268 !discriminator.empty()) {
3269 const bool is_ctor = discriminator.consume_front("C");
3270 uint64_t kind;
3271 bool is_defined = false;
3272 if ((is_ctor || discriminator.consume_front("D")) &&
3273 llvm::to_integer(discriminator, kind))
3274 is_defined = is_ctor ? kind == clang::CXXCtorType::Ctor_Complete ||
3275 kind == clang::CXXCtorType::Ctor_Base
3276 : kind == clang::CXXDtorType::Dtor_Complete ||
3277 kind == clang::CXXDtorType::Dtor_Base;
3278 if (!is_defined)
3279 return llvm::createStringErrorV(
3280 "{0} refers to a structor variant without debug info", label);
3281 }
3282
3283 PdbSymUid uid(label.symbol_id);
3284 if (uid.kind() != PdbSymUidKind::CompilandSym)
3285 return llvm::createStringErrorV("invalid function ID in {0}", label);
3286 PdbCompilandSymId func_id = uid.asCompilandSym();
3287
3288 CompilandIndexItem *cci = m_index->compilands().GetCompiland(func_id.modi);
3289 if (!cci)
3290 return llvm::createStringErrorV("invalid compiland in {0}", label);
3291
3292 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cci);
3293 if (!comp_unit)
3294 return llvm::createStringErrorV("failed to create compile unit for {0}",
3295 label);
3296
3297 FunctionSP func = GetOrCreateFunction(func_id, *comp_unit);
3298 if (!func)
3299 return llvm::createStringErrorV("failed to create function for {0}", label);
3300
3301 SymbolContext sc;
3302 func->CalculateSymbolContext(&sc);
3303 return sc;
3304}
3305
3307 for (CVType cvt : m_index->ipi().typeArray()) {
3308 switch (cvt.kind()) {
3309 case LF_UDT_SRC_LINE: {
3310 UdtSourceLineRecord udt_src;
3311 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_src)) {
3312 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3313 "Failed to deserialize UdtSourceLineRecord record: {0}");
3314 continue;
3315 }
3316 m_udt_declarations.try_emplace(
3317 udt_src.UDT, UdtDeclaration{/*FileNameIndex=*/udt_src.SourceFile,
3318 /*IsIpiIndex=*/true,
3319 /*Line=*/udt_src.LineNumber});
3320 } break;
3321 case LF_UDT_MOD_SRC_LINE: {
3322 UdtModSourceLineRecord udt_mod_src;
3323 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_mod_src)) {
3325 GetLog(LLDBLog::Symbols), std::move(err),
3326 "Failed to deserialize UdtModSourceLineRecord record: {0}");
3327 continue;
3328 }
3329 // Some types might be contributed by multiple modules. We assume that
3330 // they all point to the same file and line because we can only provide
3331 // one location.
3332 m_udt_declarations.try_emplace(
3333 udt_mod_src.UDT,
3334 UdtDeclaration{/*FileNameIndex=*/udt_mod_src.SourceFile,
3335 /*IsIpiIndex=*/false,
3336 /*Line=*/udt_mod_src.LineNumber});
3337 } break;
3338 default:
3339 break;
3340 }
3341 }
3342}
3343
3344llvm::Expected<Declaration>
3346 std::call_once(m_cached_udt_declarations, [this] { CacheUdtDeclarations(); });
3347
3348 auto it = m_udt_declarations.find(type_id.index);
3349 if (it == m_udt_declarations.end())
3350 return llvm::createStringError("no UDT declaration found");
3351
3352 llvm::StringRef file_name;
3353 if (it->second.IsIpiIndex) {
3354 CVType cvt = m_index->ipi().getType(it->second.FileNameIndex);
3355 if (cvt.kind() != LF_STRING_ID)
3356 return llvm::createStringError("file name was not a LF_STRING_ID");
3357
3358 StringIdRecord sid;
3359 if (auto err = TypeDeserializer::deserializeAs(cvt, sid))
3360 return std::move(err);
3361 file_name = sid.String;
3362 } else {
3363 // The file name index is an index into the string table
3364 auto string_table = m_index->pdb().getStringTable();
3365 if (!string_table)
3366 return string_table.takeError();
3367
3368 llvm::Expected<llvm::StringRef> string =
3369 string_table->getStringTable().getString(
3370 it->second.FileNameIndex.getIndex());
3371 if (!string)
3372 return string.takeError();
3373 file_name = *string;
3374 }
3375
3376 // rustc sets the filename to "<unknown>" for some files
3377 if (file_name == "\\<unknown>")
3378 return Declaration();
3379
3380 return Declaration(FileSpec(file_name), it->second.Line);
3381}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static std::unique_ptr< PDBFile > loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator)
static std::optional< CVTagRecord > GetNestedTagDefinition(const NestedTypeRecord &Record, const CVTagRecord &parent, TpiStream &tpi)
static lldb::LanguageType TranslateLanguage(PDB_Lang lang)
static std::string GetUnqualifiedTypeName(const TagRecord &record)
static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind)
static bool IsClassRecord(TypeLeafKind kind)
static bool IsFunctionEpilogue(const CompilandIndexItem &cci, lldb::addr_t addr)
static bool NeedsResolvedCompileUnit(uint32_t resolve_scope)
static std::optional< std::string > findMatchingPDBFilePath(llvm::StringRef original_pdb_path, llvm::StringRef exe_path)
static bool IsFunctionPrologue(const CompilandIndexItem &cci, lldb::addr_t addr)
static llvm::StringRef DropScope(llvm::StringRef name)
static bool UseNativePDB()
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
A class that describes a single lexical block.
Definition Block.h:41
RangeList::Entry Range
Definition Block.h:44
lldb::VariableListSP GetBlockVariableList(bool can_create)
Get the variable list for this block only.
Definition Block.cpp:382
Block * FindInnermostBlockByOffset(const lldb::addr_t offset)
Definition Block.cpp:127
void SetBlockInfoHasBeenParsed(bool b, bool set_children)
Definition Block.cpp:469
lldb::BlockSP CreateChild(lldb::user_id_t uid)
Creates a block with the specified UID uid.
Definition Block.cpp:370
Function * CalculateSymbolContextFunction() override
Definition Block.cpp:150
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
Definition Block.h:310
Block * GetParent() const
Get the parent block.
Definition Block.cpp:202
bool GetStartAddress(Address &addr)
Definition Block.cpp:317
void SetDidParseVariables(bool b, bool set_children)
Definition Block.cpp:479
A class that describes a compilation unit.
Definition CompileUnit.h:43
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
lldb::VariableListSP GetVariableList(bool can_create)
Get the variable list for a compile unit.
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
void ResolveSymbolContext(const SourceLocationSpec &src_location_spec, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list, RealpathPrefixes *realpath_prefixes=nullptr)
Resolve symbol contexts by file and line.
void SetLineTable(LineTable *line_table)
Set the line table for the compile unit.
void AddFunction(lldb::FunctionSP &function_sp)
Add a function to this compile unit.
size_t GetNumFunctions() const
Returns the number of functions in this compile unit.
lldb::LanguageType GetLanguage()
LineTable * GetLineTable()
Get the line table for the compile unit.
Represents a generic declaration context in a program.
Represents a generic declaration such as a function declaration.
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
"lldb/Expression/DWARFExpressionList.h" Encapsulates a range map from file address range to a single ...
bool IsValid() const
Return true if the location expression contains data.
void SetFuncFileAddress(lldb::addr_t func_file_addr)
"lldb/Expression/DWARFExpression.h" Encapsulates a DWARF location expression and interprets it.
A class to manage flag bits.
Definition Debugger.h:101
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file collection class.
A file utility class.
Definition FileSpec.h:56
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:326
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:317
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:431
llvm::sys::path::Style Style
Definition FileSpec.h:58
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
A class that describes a function.
Definition Function.h:386
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:439
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition Function.cpp:401
static void AppendLineEntryToSequence(Sequence &sequence, lldb::addr_t file_addr, uint32_t line, uint16_t column, uint16_t file_idx, bool is_start_of_statement, bool is_start_of_basic_block, bool is_prologue_end, bool is_epilogue_begin, bool is_terminal_entry)
Definition LineTable.cpp:59
A class that handles mangled names.
Definition Mangled.h:34
static bool IsMangledName(llvm::StringRef name)
Definition Mangled.cpp:39
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
A class that encapsulates name lookup information.
Definition Module.h:935
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:976
ConstString GetLookupName() const
Definition Module.h:974
ConstString GetName() const
Definition Module.h:972
static std::unique_ptr< llvm::pdb::PDBFile > loadPDBFile(std::string PdbPath, llvm::BumpPtrAllocator &Allocator)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
RangeData< lldb::addr_t, uint32_t, std::pair< uint32_t, uint32_t > > Entry
Definition RangeMap.h:462
void Append(const Entry &entry)
Definition RangeMap.h:474
Entry * FindEntryThatContains(B addr)
Definition RangeMap.h:583
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
A stream class that can stream formatted output to a file.
Definition Stream.h:28
A list of support files for a CompileUnit.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
void Append(const FileSpec &file)
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * block
The Block for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override
ObjectFile * GetObjectFile() override
Definition SymbolFile.h:590
virtual TypeList & GetTypeList()
Definition SymbolFile.h:663
lldb::ObjectFileSP m_objfile_sp
Definition SymbolFile.h:666
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
Definition SymbolFile.h:575
uint32_t GetNumCompileUnits() override
lldb::TypeSP MakeType(lldb::user_id_t uid, ConstString name, std::optional< uint64_t > byte_size, SymbolContextScope *context, lldb::user_id_t encoding_uid, Type::EncodingDataType encoding_uid_type, const Declaration &decl, const CompilerType &compiler_qual_type, Type::ResolveState compiler_type_resolve_state, uint32_t opaque_payload=0) override
This function is used to create types that belong to a SymbolFile.
Definition SymbolFile.h:634
virtual std::recursive_mutex & GetModuleMutex() const
Symbols file subclasses should override this to return the Module that owns the TypeSystem that this ...
bool ValueIsAddress() const
Definition Symbol.cpp:191
void SetType(lldb::SymbolType type)
Definition Symbol.h:199
Address & GetAddressRef()
Definition Symbol.h:78
void SetByteSize(lldb::addr_t size)
Definition Symbol.h:241
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:225
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:61
size_t GetNumSymbols() const
Definition Symtab.cpp:74
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2924
uint32_t GetSize() const
Definition TypeList.cpp:36
void Insert(const lldb::TypeSP &type)
Definition TypeList.cpp:27
void Insert(const lldb::TypeSP &type)
Definition TypeMap.cpp:27
A class that contains all state required for type lookups.
Definition Type.h:104
ConstString GetTypeBasename() const
Get the type basename to use when searching the type indexes in each SymbolFile object.
Definition Type.cpp:114
bool ContextMatches(llvm::ArrayRef< lldb_private::CompilerContext > context) const
Check of a CompilerContext array from matching type from a symbol file matches the m_context.
Definition Type.cpp:130
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
bool InsertUnique(const lldb::TypeSP &type_sp)
When types that match a TypeQuery are found, this API is used to insert the matching types.
Definition Type.cpp:195
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
Definition Type.cpp:201
bool AlreadySearched(lldb_private::SymbolFile *sym_file)
Check if a SymbolFile object has already been searched by this type match object.
Definition Type.cpp:191
A TypeSystem implementation based on Clang.
Interface for representing a type system.
Definition TypeSystem.h:72
virtual npdb::PdbAstBuilder * GetNativePDBParser()
Definition TypeSystem.h:94
@ eEncodingIsTypedefUID
This type is alias to a type whose UID is m_encoding_uid.
Definition Type.h:434
@ eEncodingIsUID
This type is the type whose UID is m_encoding_uid.
Definition Type.h:423
static std::optional< ParsedName > GetTypeScopeAndBasename(llvm::StringRef name)
Definition Type.cpp:801
void AddVariable(const lldb::VariableSP &var_sp)
RangeVector< lldb::addr_t, lldb::addr_t > RangeList
Definition Variable.h:27
virtual CompilerType GetOrCreateTypedefType(PdbGlobalSymId id)=0
virtual void Dump(Stream &stream, llvm::StringRef filter, bool show_color)=0
virtual CompilerDeclContext FindNamespaceDecl(CompilerDeclContext parent_ctx, llvm::StringRef name)=0
virtual bool CompleteType(CompilerType ct)=0
virtual void EnsureBlock(PdbCompilandSymId block_id)=0
virtual CompilerDeclContext GetParentDeclContext(PdbSymUid uid)=0
virtual CompilerType GetOrCreateType(PdbTypeSymId type)=0
virtual CompilerDecl GetOrCreateDeclForUid(PdbSymUid uid)=0
virtual void EnsureInlinedFunction(PdbCompilandSymId inlinesite_id)=0
virtual void ParseDeclsForContext(CompilerDeclContext context)=0
virtual CompilerDeclContext GetOrCreateDeclContextForUid(PdbSymUid uid)=0
PdbIndex - Lazy access to the important parts of a PDB file.
Definition PdbIndex.h:47
static llvm::Expected< std::unique_ptr< PdbIndex > > create(llvm::pdb::PDBFile *)
Definition PdbIndex.cpp:42
llvm::pdb::TpiStream & tpi()
Definition PdbIndex.h:124
PdbCompilandId asCompiland() const
PdbCompilandSymId asCompilandSym() const
PdbTypeSymId asTypeSym() const
uint64_t toOpaqueId() const
Definition PdbSymUid.h:100
PdbSymUidKind kind() const
void CreateSimpleArgumentListTypes(llvm::codeview::TypeIndex arglist_ti)
lldb::VariableSP GetOrCreateGlobalVariable(PdbGlobalSymId var_id)
bool ParseLineTable(lldb_private::CompileUnit &comp_unit) override
lldb::TypeSP CreateArrayType(PdbTypeSymId type_id, const llvm::codeview::ArrayRecord &ar, CompilerType ct)
std::optional< ArrayInfo > GetDynamicArrayInfoForUID(lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) override
If type_uid points to an array type, return its characteristics.
void CacheGlobalBaseNames()
Caches the basenames of symbols found in the globals stream.
llvm::Expected< Declaration > ResolveUdtDeclaration(PdbTypeSymId type_id)
lldb::VariableSP CreateGlobalVariable(PdbGlobalSymId var_id)
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language) override
void InitializeObject() override
Initialize the SymbolFile object.
lldb_private::UniqueCStringMap< uint32_t > m_func_base_names
basename -> Global ID(s)
static SymbolFile * CreateInstance(lldb::ObjectFileSP objfile_sp)
llvm::DenseMap< lldb::user_id_t, lldb::TypeSP > m_types
bool CompleteType(CompilerType &compiler_type) override
lldb::LanguageType ParseLanguage(lldb_private::CompileUnit &comp_unit) override
CompilerDeclContext GetDeclContextForUID(lldb::user_id_t uid) override
void DumpClangAST(Stream &s, llvm::StringRef filter, bool show_color) override
size_t ParseVariablesForContext(const SymbolContext &sc) override
size_t ParseFunctions(lldb_private::CompileUnit &comp_unit) override
lldb::TypeSP CreatePointerType(PdbTypeSymId type_id, const llvm::codeview::PointerRecord &pr, CompilerType ct)
lldb::FunctionSP CreateFunction(PdbCompilandSymId func_id, CompileUnit &comp_unit)
llvm::DenseMap< lldb::user_id_t, lldb::BlockSP > m_blocks
bool ParseSupportFiles(lldb_private::CompileUnit &comp_unit, SupportFileList &support_files) override
CompilerDecl GetDeclForUID(lldb::user_id_t uid) override
SymbolFileNativePDB(lldb::ObjectFileSP objfile_sp)
lldb::TypeSP GetOrCreateTypedef(PdbGlobalSymId id)
void FindTypesByName(llvm::StringRef name, uint32_t max_matches, TypeMap &types)
lldb::TypeSP CreateTagType(PdbTypeSymId type_id, const llvm::codeview::ClassRecord &cr, CompilerType ct)
lldb::TypeSP GetOrCreateType(PdbTypeSymId type_id)
void GetTypes(SymbolContextScope *sc_scope, lldb::TypeClass type_mask, TypeList &type_list) override
std::string GetFunctionCallLabel(PdbCompilandSymId id)
Build the asm label for the declaration of a function so that calls to it are routed through ResolveF...
llvm::DenseMap< lldb::user_id_t, lldb::VariableSP > m_local_variables
llvm::Expected< SymbolContext > ResolveFunctionCallLabel(FunctionCallLabel &label) override
Resolves the function corresponding to the specified LLDB function call label.
lldb::VariableSP CreateConstantSymbol(PdbGlobalSymId var_id, const llvm::codeview::CVSymbol &cvs)
lldb::TypeSP CreateType(PdbTypeSymId type_id, CompilerType ct)
lldb_private::UniqueCStringMap< uint32_t > m_func_method_names
method basename -> Global ID(s)
std::optional< llvm::codeview::TypeIndex > GetParentType(llvm::codeview::TypeIndex ti)
lldb_private::UniqueCStringMap< uint32_t > m_global_variable_base_names
global variable basename -> Global ID(s)
void FindFunctions(const Module::LookupInfo &lookup_info, const CompilerDeclContext &parent_decl_ctx, bool include_inlines, SymbolContextList &sc_list) override
std::unique_ptr< llvm::pdb::PDBFile > m_file_up
lldb::TypeSP CreateProcedureType(PdbTypeSymId type_id, const llvm::codeview::ProcedureRecord &pr, CompilerType ct)
lldb::TypeSP CreateModifierType(PdbTypeSymId type_id, const llvm::codeview::ModifierRecord &mr, CompilerType ct)
uint64_t GetDebugInfoSize(bool load_all_debug_info=false) override
Metrics gathering functions.
std::optional< llvm::StringRef > FindMangledSymbol(SegmentOffset so, llvm::codeview::TypeIndex function_type=llvm::codeview::TypeIndex())
Find a symbol name at a specific address (so).
size_t ParseTypes(lldb_private::CompileUnit &comp_unit) override
Block * GetOrCreateBlock(PdbCompilandSymId block_id)
lldb::VariableSP GetOrCreateLocalVariable(PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param, bool is_constant=false)
size_t ParseBlocksRecursive(Function &func) override
std::optional< PdbCompilandSymId > FindMethodDefinition(llvm::StringRef qualified_name, llvm::codeview::TypeIndex method_type)
Find the S_GPROC32/S_LPROC32 record named qualified_name whose type is method_type.
lldb::CompUnitSP CreateCompileUnit(const CompilandIndexItem &cci)
std::optional< PdbCompilandSymId > FindSymbolScope(PdbCompilandSymId id)
size_t ParseSymbolArrayInScope(PdbCompilandSymId parent, llvm::function_ref< bool(llvm::codeview::SymbolKind, PdbCompilandSymId)> fn)
size_t ParseVariablesForCompileUnit(CompileUnit &comp_unit, VariableList &variables)
llvm::DenseMap< lldb::user_id_t, lldb::CompUnitSP > m_compilands
Block * CreateBlock(PdbCompilandSymId block_id)
std::vector< CompilerContext > GetContextForType(llvm::codeview::TypeIndex ti)
llvm::Expected< uint32_t > GetFileIndex(const CompilandIndexItem &cii, uint32_t file_id)
lldb::CompUnitSP GetOrCreateCompileUnit(const CompilandIndexItem &cci)
Type * ResolveTypeUID(lldb::user_id_t type_uid) override
llvm::DenseMap< lldb::user_id_t, lldb::FunctionSP > m_functions
bool ParseImportedModules(const SymbolContext &sc, std::vector< lldb_private::SourceModule > &imported_modules) override
llvm::StringRef StripMangledFunctionName(llvm::StringRef mangled, PdbTypeSymId func_ty)
static void DebuggerInitialize(Debugger &debugger)
lldb::VariableSP CreateLocalVariable(PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param, bool is_constant=false)
llvm::DenseMap< lldb::user_id_t, std::shared_ptr< InlineSite > > m_inline_sites
void ParseInlineSite(PdbCompilandSymId inline_site_id, Address func_addr)
std::string MakeFunctionCallLabel(PdbSymUid uid, llvm::StringRef lookup_name)
lldb::TypeSP CreateClassStructUnion(PdbTypeSymId type_id, const llvm::codeview::TagRecord &record, size_t size, CompilerType ct)
void FindGlobalVariables(ConstString name, const CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, VariableList &variables) override
size_t ParseVariablesForBlock(PdbCompilandSymId block_id)
void ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx) override
lldb::FunctionSP GetOrCreateFunction(PdbCompilandSymId func_id, CompileUnit &comp_unit)
llvm::DenseMap< llvm::codeview::TypeIndex, llvm::codeview::TypeIndex > m_parent_types
lldb_private::UniqueCStringMap< uint32_t > m_func_full_names
mangled name/full function name -> Global ID(s)
lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override
lldb::TypeSP CreateFunctionType(PdbTypeSymId type_id, const llvm::codeview::MemberFunctionRecord &pr, CompilerType ct)
lldb_private::UniqueCStringMap< uint32_t > m_type_base_names
lldb::TypeSP CreateAndCacheType(PdbTypeSymId type_id)
CompilerDeclContext FindNamespace(ConstString name, const CompilerDeclContext &parent_decl_ctx, bool only_root_namespaces) override
Finds a namespace of name name and whose parent context is parent_decl_ctx.
CompilerDeclContext GetDeclContextContainingUID(lldb::user_id_t uid) override
bool ParseDebugMacros(lldb_private::CompileUnit &comp_unit) override
lldb::TypeSP CreateTypedef(PdbGlobalSymId id)
llvm::DenseMap< llvm::codeview::TypeIndex, UdtDeclaration > m_udt_declarations
void FindTypes(const lldb_private::TypeQuery &match, lldb_private::TypeResults &results) override
Find types using a type-matching object that contains all search parameters.
std::string GetMethodCallLabel(llvm::codeview::TypeIndex method_type, llvm::StringRef qualified_name)
Build the asm label for a method that was declared in the field list of its class.
uint32_t ResolveSymbolContext(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc) override
llvm::DenseMap< lldb::user_id_t, lldb::VariableSP > m_global_vars
lldb::TypeSP CreateSimpleType(llvm::codeview::TypeIndex ti, CompilerType ct)
#define LLDB_INVALID_UID
#define LLDB_INVALID_ADDRESS
uint64_t toOpaqueUid(const T &cid)
Definition PdbSymUid.h:111
size_t GetTypeSizeForSimpleKind(llvm::codeview::SimpleTypeKind kind)
SegmentOffsetLength GetSegmentOffsetAndLength(const llvm::codeview::CVSymbol &sym)
bool IsTagRecord(llvm::codeview::CVType cvt)
Definition PdbUtil.cpp:517
bool IsValidRecord(const RecordT &sym)
Definition PdbUtil.h:129
llvm::Expected< DWARFExpression > MakeConstantLocationExpression(llvm::codeview::TypeIndex underlying_ti, llvm::pdb::TpiStream &tpi, const llvm::APSInt &constant, lldb::ModuleSP module)
DWARFExpression MakeGlobalLocationExpression(uint16_t section, uint32_t offset, lldb::ModuleSP module)
VariableInfo GetVariableLocationInfo(PdbIndex &index, PdbCompilandSymId var_id, Block &func_block, lldb::ModuleSP module)
Definition PdbUtil.cpp:746
bool IsForwardRefUdt(llvm::codeview::CVType cvt)
llvm::pdb::PDB_SymType CVSymToPDBSym(llvm::codeview::SymbolKind kind)
DWARFExpression MakeGlobalThreadLocalLocationExpression(uint32_t offset, const lldb::ModuleSP &module)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::Function > FunctionSP
std::shared_ptr< lldb_private::Block > BlockSP
std::shared_ptr< lldb_private::ObjectFile > ObjectFileSP
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeRust
Rust.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeSwift
Swift.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::Type > TypeSP
SymbolType
Symbol types.
@ eSymbolTypeAdditional
When symbols take more than one entry, the extra entries get this type.
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::SymbolFileType > SymbolFileTypeSP
std::shared_ptr< lldb_private::Variable > VariableSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
Holds parsed information about a function call label that LLDB attaches as an AsmLabel to function AS...
Definition Expression.h:110
lldb::user_id_t symbol_id
Unique identifier of the function symbol on which to perform the function call.
Definition Expression.h:122
std::string toString() const
Encode this FunctionCallLabel into its string representation.
llvm::StringRef discriminator
Arbitrary string which language plugins can interpret for their own needs.
Definition Expression.h:113
BaseType GetRangeBase() const
Definition RangeMap.h:45
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47
CompilerContextKind contextKind() const
Definition PdbUtil.h:75
static CVTagRecord create(llvm::codeview::CVType type)
Definition PdbUtil.cpp:197
const llvm::codeview::TagRecord & asTag() const
Definition PdbUtil.h:44
llvm::StringRef name() const
Definition PdbUtil.h:67
Represents a single compile unit.
std::map< llvm::codeview::TypeIndex, llvm::codeview::InlineeSourceLine > m_inline_map
std::optional< llvm::codeview::Compile3Sym > m_compile_opts
llvm::pdb::ModuleDebugStreamRef m_debug_stream
llvm::codeview::StringsAndChecksumsRef m_strings
std::vector< llvm::StringRef > m_file_list
llvm::codeview::TypeIndex index
Definition PdbSymUid.h:73
DWARFExpressionList location
Definition PdbUtil.h:115
llvm::codeview::TypeIndex type
Definition PdbUtil.h:114