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