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 std::string var_name = name.str();
1129 if (ts) {
1130 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser()) {
1131 ast_builder->EnsureVariable(var_id);
1132 var_name = ast_builder->GetQualifiedName(name);
1133 }
1134 }
1135
1136 DWARFExpressionList location(module_sp, location_expr, nullptr);
1137
1138 llvm::StringRef mangled_name = FindMangledSymbol(so).value_or("");
1139 if (!Mangled::IsMangledName(mangled_name))
1140 mangled_name = {};
1141 bool artificial = false;
1142 bool location_is_constant_data = false;
1143 bool static_member = false;
1144 VariableSP var_sp = std::make_shared<Variable>(
1145 toOpaqueUid(var_id), var_name.c_str(), mangled_name.str().c_str(),
1146 type_sp, scope, comp_unit.get(), ranges, &decl, location, is_external,
1147 artificial, location_is_constant_data, static_member);
1148
1149 return var_sp;
1150}
1151
1154 const CVSymbol &cvs) {
1155 TpiStream &tpi = m_index->tpi();
1156 ConstantSym constant(cvs.kind());
1157
1158 if (cvs.kind() != S_CONSTANT)
1159 return nullptr;
1160
1161 if (auto err =
1162 SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)) {
1163 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1164 "Failed to deserialize ConstantSym record: {0}");
1165 return nullptr;
1166 }
1167 PdbTypeSymId tid(constant.Type, false);
1168 SymbolFileTypeSP type_sp =
1169 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1170
1171 Declaration decl;
1172 Variable::RangeList ranges;
1173 ModuleSP module = GetObjectFile()->GetModule();
1174 auto location_or_err = MakeConstantLocationExpression(constant.Type, tpi,
1175 constant.Value, module);
1176 if (!location_or_err) {
1177 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
1178 "Failed to make constant location expression for {1}: {0}",
1179 constant.Name);
1180 return nullptr;
1181 }
1182 DWARFExpressionList location(module, std::move(*location_or_err), nullptr);
1183
1184 std::string var_name = constant.Name.str();
1186 if (auto err = ts_or_err.takeError()) {
1187 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1188 "Failed to get type system for {1}: {0}", constant.Name);
1189 } else if (auto ts = *ts_or_err) {
1190 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
1191 var_name = ast_builder->GetQualifiedName(constant.Name);
1192 }
1193
1194 bool external = false;
1195 bool artificial = false;
1196 bool location_is_constant_data = true;
1197 bool static_member = false;
1198 VariableSP var_sp = std::make_shared<Variable>(
1199 toOpaqueUid(var_id), var_name.c_str(),
1200 /*mangled=*/nullptr, type_sp, eValueTypeVariableGlobal, module.get(),
1201 ranges, &decl, location, external, artificial, location_is_constant_data,
1202 static_member);
1203 return var_sp;
1204}
1205
1208 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
1209 if (emplace_result.second) {
1210 if (VariableSP var_sp = CreateGlobalVariable(var_id))
1211 emplace_result.first->second = var_sp;
1212 else
1213 return nullptr;
1214 }
1215
1216 return emplace_result.first->second;
1217}
1218
1220 return GetOrCreateType(PdbTypeSymId(ti, false));
1221}
1222
1224 CompileUnit &comp_unit) {
1225 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
1226 if (emplace_result.second)
1227 emplace_result.first->second = CreateFunction(func_id, comp_unit);
1228
1229 return emplace_result.first->second;
1230}
1231
1234
1235 auto emplace_result =
1236 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
1237 if (emplace_result.second) {
1238 emplace_result.first->second = CreateCompileUnit(cci);
1239 LLDB_LOG(GetLog(LLDBLog::Symbols), "failed to create compile unit for {0}",
1240 cci.m_id.modi);
1241 }
1242
1243 return emplace_result.first->second;
1244}
1245
1247 auto iter = m_blocks.find(toOpaqueUid(block_id));
1248 if (iter != m_blocks.end())
1249 return iter->second.get();
1250
1251 return CreateBlock(block_id);
1252}
1253
1256 TypeSystem *ts = decl_ctx.GetTypeSystem();
1257 if (!ts)
1258 return;
1259 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
1260 if (!ast_builder)
1261 return;
1262 ast_builder->ParseDeclsForContext(decl_ctx);
1263}
1264
1266 if (index >= GetNumCompileUnits())
1267 return CompUnitSP();
1268 assert(index < UINT16_MAX && "Invalid compile unit index");
1269 if (index >= UINT16_MAX)
1270 return nullptr;
1271
1272 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1273
1274 return GetOrCreateCompileUnit(item);
1275}
1276
1278 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1279 PdbSymUid uid(comp_unit.GetID());
1280 if (uid.kind() != PdbSymUidKind::Compiland) {
1281 assert(false && "uid of compile unit not a compiland");
1283 }
1284
1285 CompilandIndexItem *item =
1286 m_index->compilands().GetCompiland(uid.asCompiland().modi);
1287 assert(item);
1288 if (!item || !item->m_compile_opts)
1290
1291 return TranslateLanguage(item->m_compile_opts->getLanguage());
1292}
1293
1295 auto *section_list =
1296 m_objfile_sp->GetModule()->GetObjectFile()->GetSectionList();
1297 if (!section_list)
1298 return;
1299
1300 llvm::DenseMap<lldb::addr_t, llvm::SmallVector<uint32_t, 1>> symbols_by_addr;
1301 for (uint32_t i = 0, n = symtab.GetNumSymbols(); i < n; ++i) {
1302 Symbol *sym = symtab.SymbolAtIndex(i);
1303 if (sym && sym->ValueIsAddress())
1304 symbols_by_addr[sym->GetAddressRef().GetFileAddress()].push_back(i);
1305 }
1306
1307 PublicSym32 last_sym;
1308 size_t last_sym_idx = 0;
1309 lldb::SectionSP section_sp;
1310
1311 // To estimate the size of a symbol, we use the difference to the next symbol.
1312 // If there's no next symbol or the section/segment changed, the symbol will
1313 // take the remaining space. The estimate can be too high in case there's
1314 // padding between symbols. This similar to the algorithm used by the DIA
1315 // SDK.
1316 auto finish_last_symbol = [&](const PublicSym32 *next) {
1317 if (!section_sp)
1318 return;
1319 Symbol *last = symtab.SymbolAtIndex(last_sym_idx);
1320 if (!last)
1321 return;
1322
1323 if (next && last_sym.Segment == next->Segment) {
1324 if (next->Offset < last_sym.Offset) {
1326 "Ignoring size estimate for '{0}': segment {1} offset {2} is "
1327 "greater than the following offset {3}",
1328 last_sym.Name, last_sym.Segment, last_sym.Offset,
1329 next->Offset);
1330 return;
1331 }
1332 last->SetByteSize(next->Offset - last_sym.Offset);
1333 } else {
1334 // the last symbol was the last in its section
1335 if (section_sp->GetByteSize() < last_sym.Offset) {
1337 "Ignoring size estimate for '{0}': segment {1} offset {2} is "
1338 "past the end of section '{3}' (size {4})",
1339 last_sym.Name, last_sym.Segment, last_sym.Offset,
1340 section_sp->GetName(), section_sp->GetByteSize());
1341 return;
1342 }
1343 last->SetByteSize(section_sp->GetByteSize() - last_sym.Offset);
1344 }
1345 };
1346
1347 // The address map is sorted by the address of a symbol.
1348 for (auto pid : m_index->publics().getAddressMap()) {
1349 PdbGlobalSymId global{pid, true};
1350 CVSymbol sym = m_index->ReadSymbolRecord(global);
1351 auto kind = sym.kind();
1352 if (kind != S_PUB32)
1353 continue;
1354 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
1355 if (!pub_or_err) {
1356 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
1357 "Failed to deserialize PublicSym32 record: {0}");
1358 continue;
1359 }
1360 PublicSym32 pub = std::move(*pub_or_err);
1361 finish_last_symbol(&pub);
1362
1363 if (!section_sp || last_sym.Segment != pub.Segment)
1364 section_sp = section_list->FindSectionByID(pub.Segment);
1365
1366 if (!section_sp)
1367 continue;
1368
1370 if ((pub.Flags & PublicSymFlags::Function) != PublicSymFlags::None ||
1371 (pub.Flags & PublicSymFlags::Code) != PublicSymFlags::None)
1372 type = eSymbolTypeCode;
1373
1374 Symbol pub_symbol(/*symID=*/pid,
1375 /*name=*/pub.Name,
1376 /*type=*/type,
1377 /*external=*/true,
1378 /*is_debug=*/true,
1379 /*is_trampoline=*/false,
1380 /*is_artificial=*/false,
1381 /*section_sp=*/section_sp,
1382 /*value=*/pub.Offset,
1383 /*size=*/0,
1384 /*size_is_valid=*/false,
1385 /*contains_linker_annotations=*/false,
1386 /*flags=*/0);
1387
1388 auto it = symbols_by_addr.find(pub_symbol.GetAddressRef().GetFileAddress());
1389 if (it != symbols_by_addr.end() &&
1390 llvm::any_of(it->second, [&](uint32_t idx) {
1391 Symbol *sym = symtab.SymbolAtIndex(idx);
1392 return sym && sym->GetMangled() == pub_symbol.GetMangled();
1393 }))
1395
1396 last_sym_idx = symtab.AddSymbol(pub_symbol);
1397 last_sym = pub;
1398 }
1399
1400 finish_last_symbol(nullptr);
1401}
1402
1404 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1405 PdbSymUid uid{comp_unit.GetID()};
1406 if (uid.kind() != PdbSymUidKind::Compiland) {
1407 assert(false && "uid of compile unit not a compiland");
1408 return 0;
1409 }
1410 uint16_t modi = uid.asCompiland().modi;
1411 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
1412
1413 size_t count = comp_unit.GetNumFunctions();
1414 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
1415 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1416 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
1417 continue;
1418
1419 PdbCompilandSymId sym_id{modi, iter.offset()};
1420
1421 FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
1422 }
1423
1424 size_t new_count = comp_unit.GetNumFunctions();
1425 if (new_count < count) {
1426 assert(false && "less functions after parsing than before");
1427 return 0;
1428 }
1429 return new_count - count;
1430}
1431
1432static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1433 // If any of these flags are set, we need to resolve the compile unit.
1434 uint32_t flags = eSymbolContextCompUnit;
1435 flags |= eSymbolContextVariable;
1436 flags |= eSymbolContextFunction;
1437 flags |= eSymbolContextBlock;
1438 flags |= eSymbolContextLineEntry;
1439 return (resolve_scope & flags) != 0;
1440}
1441
1443 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1444 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1445 uint32_t resolved_flags = 0;
1446 lldb::addr_t file_addr = addr.GetFileAddress();
1447
1448 if (NeedsResolvedCompileUnit(resolve_scope)) {
1449 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1450 if (!modi)
1451 return 0;
1452 CompUnitSP cu_sp = GetCompileUnitAtIndex(*modi);
1453 if (!cu_sp)
1454 return 0;
1455
1456 sc.comp_unit = cu_sp.get();
1457 resolved_flags |= eSymbolContextCompUnit;
1458 }
1459
1460 if (resolve_scope & eSymbolContextFunction ||
1461 resolve_scope & eSymbolContextBlock) {
1462 if (!sc.comp_unit) {
1464 "missing compile unit for symbol at address {0:x}", file_addr);
1465 return 0;
1466 }
1467 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1468 // Search the matches in reverse. This way if there are multiple matches
1469 // (for example we are 3 levels deep in a nested scope) it will find the
1470 // innermost one first.
1471 for (const auto &match : llvm::reverse(matches)) {
1472 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1473 continue;
1474
1475 PdbCompilandSymId csid = match.uid.asCompilandSym();
1476 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1477 PDB_SymType type = CVSymToPDBSym(cvs.kind());
1478 if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1479 continue;
1480 if (type == PDB_SymType::Function) {
1481 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1482 if (sc.function) {
1483 Block &block = sc.function->GetBlock(true);
1484 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1485 addr_t offset = file_addr - func_base;
1486 sc.block = block.FindInnermostBlockByOffset(offset);
1487 }
1488 }
1489
1490 if (type == PDB_SymType::Block) {
1491 Block *block = GetOrCreateBlock(csid);
1492 if (!block)
1493 continue;
1495 if (sc.function) {
1496 sc.function->GetBlock(true);
1497 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1498 addr_t offset = file_addr - func_base;
1499 sc.block = block->FindInnermostBlockByOffset(offset);
1500 }
1501 }
1502 if (sc.function)
1503 resolved_flags |= eSymbolContextFunction;
1504 if (sc.block)
1505 resolved_flags |= eSymbolContextBlock;
1506 break;
1507 }
1508 }
1509
1510 if (resolve_scope & eSymbolContextLineEntry) {
1511 if (!sc.comp_unit) {
1513 "missing compile unit for symbol at address {0:x}", file_addr);
1514 return 0;
1515 }
1516 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1517 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1518 resolved_flags |= eSymbolContextLineEntry;
1519 }
1520 }
1521
1522 return resolved_flags;
1523}
1524
1526 const SourceLocationSpec &src_location_spec,
1527 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1528 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1529 const uint32_t prev_size = sc_list.GetSize();
1530 if (resolve_scope & eSymbolContextCompUnit) {
1531 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1532 ++cu_idx) {
1533 CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1534 if (!cu)
1535 continue;
1536
1537 bool file_spec_matches_cu_file_spec = FileSpec::Match(
1538 src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1539 if (file_spec_matches_cu_file_spec) {
1540 cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1541 break;
1542 }
1543 }
1544 }
1545 return sc_list.GetSize() - prev_size;
1546}
1547
1549 // Unfortunately LLDB is set up to parse the entire compile unit line table
1550 // all at once, even if all it really needs is line info for a specific
1551 // function. In the future it would be nice if it could set the sc.m_function
1552 // member, and we could only get the line info for the function in question.
1553 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1554 PdbSymUid cu_id(comp_unit.GetID());
1555 if (cu_id.kind() != PdbSymUidKind::Compiland) {
1556 assert(false && "uid of compile unit not a compiland");
1557 return false;
1558 }
1559 uint16_t modi = cu_id.asCompiland().modi;
1560 CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1561 if (!cii) {
1562 LLDB_LOG(GetLog(LLDBLog::Symbols), "missing compiland for modi={0}", modi);
1563 return false;
1564 }
1565
1566 // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1567 // in this CU. Add line entries into the set first so that if there are line
1568 // entries with same addres, the later is always more accurate than the
1569 // former.
1570 std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1571
1572 // This is basically a copy of the .debug$S subsections from all original COFF
1573 // object files merged together with address relocations applied. We are
1574 // looking for all DEBUG_S_LINES subsections.
1575 for (const DebugSubsectionRecord &dssr :
1576 cii->m_debug_stream.getSubsectionsArray()) {
1577 if (dssr.kind() != DebugSubsectionKind::Lines)
1578 continue;
1579
1580 DebugLinesSubsectionRef lines;
1581 llvm::BinaryStreamReader reader(dssr.getRecordData());
1582 if (auto EC = lines.initialize(reader)) {
1583 llvm::consumeError(std::move(EC));
1584 return false;
1585 }
1586
1587 const LineFragmentHeader *lfh = lines.header();
1588 uint64_t virtual_addr =
1589 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1590 if (virtual_addr == LLDB_INVALID_ADDRESS)
1591 continue;
1592
1593 for (const LineColumnEntry &group : lines) {
1594 llvm::Expected<uint32_t> file_index_or_err =
1595 GetFileIndex(*cii, group.NameIndex);
1596 if (!file_index_or_err) {
1597 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1598 "failed to get file index for line entry: {0}");
1599 continue;
1600 }
1601 uint32_t file_index = file_index_or_err.get();
1602 if (group.LineNumbers.empty()) {
1604 "no line numbers for {0} in modi={1}", group.NameIndex, modi);
1605 continue;
1606 }
1609 for (const LineNumberEntry &entry : group.LineNumbers) {
1610 LineInfo cur_info(entry.Flags);
1611
1612 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1613 continue;
1614
1615 uint64_t addr = virtual_addr + entry.Offset;
1616
1617 bool is_statement = cur_info.isStatement();
1618 bool is_prologue = IsFunctionPrologue(*cii, addr);
1619 bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1620
1621 uint32_t lno = cur_info.getStartLine();
1622
1623 LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1624 is_prologue, is_epilogue, false);
1625 // Terminal entry has lower precedence than new entry.
1626 auto iter = line_set.find(new_entry);
1627 if (iter != line_set.end() && iter->is_terminal_entry)
1628 line_set.erase(iter);
1629 line_set.insert(new_entry);
1630
1631 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1632 line_entry.SetRangeEnd(addr);
1633 cii->m_global_line_table.Append(line_entry);
1634 }
1635 line_entry.SetRangeBase(addr);
1636 line_entry.data = {file_index, lno};
1637 }
1638 LineInfo last_line(group.LineNumbers.back().Flags);
1639 line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1640 file_index, false, false, false, false, true);
1641
1642 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1643 line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1644 cii->m_global_line_table.Append(line_entry);
1645 }
1646 }
1647 }
1648
1650
1651 // Parse all S_INLINESITE in this CU.
1652 const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1653 for (auto iter = syms.begin(); iter != syms.end();) {
1654 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1655 ++iter;
1656 continue;
1657 }
1658
1659 uint32_t record_offset = iter.offset();
1660 CVSymbol func_record =
1661 cii->m_debug_stream.readSymbolAtOffset(record_offset);
1663 addr_t file_vm_addr =
1664 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
1665 if (file_vm_addr == LLDB_INVALID_ADDRESS)
1666 continue;
1667
1668 Address func_base(file_vm_addr, comp_unit.GetModule()->GetSectionList());
1669 PdbCompilandSymId func_id{modi, record_offset};
1670
1671 // Iterate all S_INLINESITEs in the function.
1672 auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1673 if (kind != S_INLINESITE)
1674 return false;
1675
1676 ParseInlineSite(id, func_base);
1677
1678 for (const auto &line_entry :
1679 m_inline_sites[toOpaqueUid(id)]->line_entries) {
1680 // If line_entry is not terminal entry, remove previous line entry at
1681 // the same address and insert new one. Terminal entry inside an inline
1682 // site might not be terminal entry for its parent.
1683 if (!line_entry.is_terminal_entry)
1684 line_set.erase(line_entry);
1685 line_set.insert(line_entry);
1686 }
1687 // No longer useful after adding to line_set.
1688 m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1689 return true;
1690 };
1691 ParseSymbolArrayInScope(func_id, parse_inline_sites);
1692 // Jump to the end of the function record.
1693 iter = syms.at(getScopeEndOffset(func_record));
1694 }
1695
1697
1698 // Add line entries in line_set to line_table.
1699 std::vector<LineTable::Sequence> sequence(1);
1700 for (const auto &line_entry : line_set) {
1702 sequence.back(), line_entry.file_addr, line_entry.line,
1703 line_entry.column, line_entry.file_idx,
1704 line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1705 line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1706 line_entry.is_terminal_entry);
1707 }
1708 auto line_table =
1709 std::make_unique<LineTable>(&comp_unit, std::move(sequence));
1710
1711 if (line_table->GetSize() == 0)
1712 return false;
1713
1714 comp_unit.SetLineTable(line_table.release());
1715 return true;
1716}
1717
1719 // PDB doesn't contain information about macros
1720 return false;
1721}
1722
1723llvm::Expected<uint32_t>
1725 uint32_t file_id) {
1726 if (!cii.m_strings.hasChecksums() || !cii.m_strings.hasStrings())
1727 return llvm::make_error<RawError>(raw_error_code::no_entry);
1728
1729 const auto &checksums = cii.m_strings.checksums().getArray();
1730 const auto &strings = cii.m_strings.strings();
1731 // Indices in this structure are actually offsets of records in the
1732 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1733 // into the global PDB string table.
1734 auto iter = checksums.at(file_id);
1735 if (iter == checksums.end())
1736 return llvm::make_error<RawError>(raw_error_code::no_entry);
1737
1738 llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1739 if (!efn) {
1740 return efn.takeError();
1741 }
1742
1743 // LLDB wants the index of the file in the list of support files.
1744 auto fn_iter = llvm::find(cii.m_file_list, *efn);
1745 if (fn_iter != cii.m_file_list.end())
1746 return std::distance(cii.m_file_list.begin(), fn_iter);
1747 return llvm::make_error<RawError>(raw_error_code::no_entry);
1748}
1749
1751 SupportFileList &support_files) {
1752 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1753 PdbSymUid cu_id(comp_unit.GetID());
1754 if (cu_id.kind() != PdbSymUidKind::Compiland) {
1755 assert(false && "uid of compile unit not a compiland");
1756 return false;
1757 }
1758 CompilandIndexItem *cci =
1759 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1760 if (!cci) {
1761 LLDB_LOG(GetLog(LLDBLog::Symbols), "missing compiland for modi={0}",
1762 cu_id.asCompiland().modi);
1763 return false;
1764 }
1765
1766 for (llvm::StringRef f : cci->m_file_list) {
1767 FileSpec::Style style =
1768 f.starts_with("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1769 FileSpec spec(f, style);
1770 support_files.Append(spec);
1771 }
1772 return true;
1773}
1774
1776 const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1777 // PDB does not yet support module debug info
1778 return false;
1779}
1780
1782 Address func_addr) {
1783 lldb::user_id_t opaque_uid = toOpaqueUid(id);
1784 if (m_inline_sites.contains(opaque_uid))
1785 return;
1786
1787 addr_t func_base = func_addr.GetFileAddress();
1788 CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1789 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1790 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1791 if (sym.kind() != S_INLINESITE)
1792 return;
1793
1794 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1795 if (auto err =
1796 SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site)) {
1797 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1798 "Failed to deserialize InlineSiteSym record: {0}");
1799 return;
1800 }
1801 PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1802
1803 std::shared_ptr<InlineSite> inline_site_sp =
1804 std::make_shared<InlineSite>(parent_id);
1805
1806 // Get the inlined function declaration info.
1807 auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1808 if (iter == cii->m_inline_map.end())
1809 return;
1810 InlineeSourceLine inlinee_line = iter->second;
1811
1812 const SupportFileList &files = comp_unit->GetSupportFiles();
1813 FileSpec decl_file;
1814 llvm::Expected<uint32_t> file_index_or_err =
1815 GetFileIndex(*cii, inlinee_line.Header->FileID);
1816 if (!file_index_or_err) {
1817 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1818 "failed to get file index for inline site: {0}");
1819 return;
1820 }
1821 uint32_t file_offset = file_index_or_err.get();
1822 decl_file = files.GetFileSpecAtIndex(file_offset);
1823 uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1824 std::unique_ptr<Declaration> decl_up =
1825 std::make_unique<Declaration>(decl_file, decl_line);
1826
1827 // Parse range and line info.
1828 uint32_t code_offset = 0;
1829 int32_t line_offset = 0;
1830 std::optional<uint32_t> code_offset_base;
1831 std::optional<uint32_t> code_offset_end;
1832 std::optional<int32_t> cur_line_offset;
1833 std::optional<int32_t> next_line_offset;
1834 std::optional<uint32_t> next_file_offset;
1835
1836 bool is_terminal_entry = false;
1837 bool is_start_of_statement = true;
1838 // The first instruction is the prologue end.
1839 bool is_prologue_end = true;
1840
1841 auto update_code_offset = [&](uint32_t code_delta) {
1842 if (!code_offset_base)
1843 code_offset_base = code_offset;
1844 else if (!code_offset_end)
1845 code_offset_end = *code_offset_base + code_delta;
1846 };
1847 auto update_line_offset = [&](int32_t line_delta) {
1848 line_offset += line_delta;
1849 if (!code_offset_base || !cur_line_offset)
1850 cur_line_offset = line_offset;
1851 else
1852 next_line_offset = line_offset;
1853 ;
1854 };
1855 auto update_file_offset = [&](uint32_t offset) {
1856 if (!code_offset_base)
1857 file_offset = offset;
1858 else
1859 next_file_offset = offset;
1860 };
1861
1862 for (auto &annot : inline_site.annotations()) {
1863 switch (annot.OpCode) {
1864 case BinaryAnnotationsOpCode::CodeOffset:
1865 case BinaryAnnotationsOpCode::ChangeCodeOffset:
1866 case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1867 code_offset += annot.U1;
1868 update_code_offset(annot.U1);
1869 break;
1870 case BinaryAnnotationsOpCode::ChangeLineOffset:
1871 update_line_offset(annot.S1);
1872 break;
1873 case BinaryAnnotationsOpCode::ChangeCodeLength:
1874 update_code_offset(annot.U1);
1875 code_offset += annot.U1;
1876 is_terminal_entry = true;
1877 break;
1878 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1879 code_offset += annot.U1;
1880 update_code_offset(annot.U1);
1881 update_line_offset(annot.S1);
1882 break;
1883 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1884 code_offset += annot.U2;
1885 update_code_offset(annot.U2);
1886 update_code_offset(annot.U1);
1887 code_offset += annot.U1;
1888 is_terminal_entry = true;
1889 break;
1890 case BinaryAnnotationsOpCode::ChangeFile:
1891 update_file_offset(annot.U1);
1892 break;
1893 default:
1894 break;
1895 }
1896
1897 // Add range if current range is finished.
1898 if (code_offset_base && code_offset_end && cur_line_offset) {
1899 inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1900 *code_offset_base, *code_offset_end - *code_offset_base,
1901 decl_line + *cur_line_offset));
1902 // Set base, end, file offset and line offset for next range.
1903 if (next_file_offset)
1904 file_offset = *next_file_offset;
1905 if (next_line_offset) {
1906 cur_line_offset = next_line_offset;
1907 next_line_offset = std::nullopt;
1908 }
1909 code_offset_base = is_terminal_entry ? std::nullopt : code_offset_end;
1910 code_offset_end = next_file_offset = std::nullopt;
1911 }
1912 if (code_offset_base && cur_line_offset) {
1913 if (is_terminal_entry) {
1914 LineTable::Entry line_entry(
1915 func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1916 file_offset, false, false, false, false, true);
1917 inline_site_sp->line_entries.push_back(line_entry);
1918 } else {
1919 LineTable::Entry line_entry(func_base + *code_offset_base,
1920 decl_line + *cur_line_offset, 0,
1921 file_offset, is_start_of_statement, false,
1922 is_prologue_end, false, false);
1923 inline_site_sp->line_entries.push_back(line_entry);
1924 is_prologue_end = false;
1925 is_start_of_statement = false;
1926 }
1927 }
1928 if (is_terminal_entry)
1929 is_start_of_statement = true;
1930 is_terminal_entry = false;
1931 }
1932
1933 inline_site_sp->ranges.Sort();
1934
1935 // Get the inlined function callsite info.
1936 std::unique_ptr<Declaration> callsite_up;
1937 if (!inline_site_sp->ranges.IsEmpty()) {
1938 auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1939 addr_t base_offset = entry->GetRangeBase();
1940 if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1941 S_INLINESITE) {
1942 // Its parent is another inline site, lookup parent site's range vector
1943 // for callsite line.
1944 ParseInlineSite(parent_id, Address(func_base));
1945 std::shared_ptr<InlineSite> parent_site =
1946 m_inline_sites[toOpaqueUid(parent_id)];
1947 FileSpec &parent_decl_file =
1948 parent_site->inline_function_info->GetDeclaration().GetFile();
1949 if (auto *parent_entry =
1950 parent_site->ranges.FindEntryThatContains(base_offset)) {
1951 callsite_up =
1952 std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1953 }
1954 } else {
1955 // Its parent is a function, lookup global line table for callsite.
1956 if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1957 func_base + base_offset)) {
1958 const FileSpec &callsite_file =
1959 files.GetFileSpecAtIndex(entry->data.first);
1960 callsite_up =
1961 std::make_unique<Declaration>(callsite_file, entry->data.second);
1962 }
1963 }
1964 }
1965
1966 // Get the inlined function name.
1967 std::string inlinee_name;
1968 llvm::Expected<CVType> inlinee_cvt =
1969 m_index->ipi().typeCollection().getTypeOrError(inline_site.Inlinee);
1970 if (!inlinee_cvt) {
1971 inlinee_name = "[error reading function name: " +
1972 llvm::toString(inlinee_cvt.takeError()) + "]";
1973 } else if (inlinee_cvt->kind() == LF_MFUNC_ID) {
1974 MemberFuncIdRecord mfr;
1975 if (auto err = TypeDeserializer::deserializeAs<MemberFuncIdRecord>(
1976 *inlinee_cvt, mfr)) {
1977 inlinee_name =
1978 "[error reading function name: " + llvm::toString(std::move(err)) +
1979 "]";
1980 } else {
1981 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1982 inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1983 inlinee_name.append("::");
1984 inlinee_name.append(mfr.getName().str());
1985 }
1986 } else if (inlinee_cvt->kind() == LF_FUNC_ID) {
1987 FuncIdRecord fir;
1988 if (auto err =
1989 TypeDeserializer::deserializeAs<FuncIdRecord>(*inlinee_cvt, fir)) {
1990 inlinee_name =
1991 "[error reading function name: " + llvm::toString(std::move(err)) +
1992 "]";
1993 } else {
1994 TypeIndex parent_idx = fir.getParentScope();
1995 if (!parent_idx.isNoneType()) {
1996 LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1997 inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1998 inlinee_name.append("::");
1999 }
2000 inlinee_name.append(fir.getName().str());
2001 }
2002 }
2003 inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
2004 inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
2005 callsite_up.get());
2006
2007 m_inline_sites[opaque_uid] = inline_site_sp;
2008}
2009
2011 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2012 PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
2013 // After we iterate through inline sites inside the function, we already get
2014 // all the info needed, removing from the map to save memory.
2015 std::set<uint64_t> remove_uids;
2016 auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
2017 if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
2018 kind == S_INLINESITE) {
2019 GetOrCreateBlock(id);
2020 if (kind == S_INLINESITE)
2021 remove_uids.insert(toOpaqueUid(id));
2022 return true;
2023 }
2024 return false;
2025 };
2026 size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
2027 for (uint64_t uid : remove_uids) {
2028 m_inline_sites.erase(uid);
2029 }
2030
2031 func.GetBlock(false).SetBlockInfoHasBeenParsed(true, true);
2032 return count;
2033}
2034
2036 PdbCompilandSymId parent_id,
2037 llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
2038 CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
2039 CVSymbolArray syms =
2040 cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
2041
2042 size_t count = 1;
2043 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
2044 PdbCompilandSymId child_id(parent_id.modi, iter.offset());
2045 if (fn(iter->kind(), child_id))
2046 ++count;
2047 }
2048
2049 return count;
2050}
2051
2052void SymbolFileNativePDB::DumpClangAST(Stream &s, llvm::StringRef filter,
2053 bool show_color) {
2055 if (!ts_or_err) {
2056 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ts_or_err.takeError(),
2057 "failed to get C++ type system: {0}");
2058 return;
2059 }
2060 auto ts = *ts_or_err;
2061 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
2062 if (!clang)
2063 return;
2064 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
2065 if (!ast_builder)
2066 return;
2067 ast_builder->Dump(s, filter, show_color);
2068}
2069
2071 if (!m_func_full_names.IsEmpty() || !m_global_variable_base_names.IsEmpty())
2072 return;
2073
2074 // (segment, code offset) -> gid
2075 std::map<std::pair<uint16_t, uint32_t>, uint32_t> func_addr_ids;
2076
2077 // First, look through all items in the globals table.
2078 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2079 CVSymbol sym = m_index->symrecords().readRecord(gid);
2080 auto kind = sym.kind();
2081
2082 // If this is a global variable, we only need to look at the name
2083 llvm::StringRef name;
2084 switch (kind) {
2085 case SymbolKind::S_GDATA32:
2086 case SymbolKind::S_LDATA32: {
2087 auto data_or_err = SymbolDeserializer::deserializeAs<DataSym>(sym);
2088 if (!data_or_err) {
2089 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2090 "Failed to deserialize DataSym record: {0}");
2091 continue;
2092 }
2093 name = data_or_err->Name;
2094 break;
2095 }
2096 case SymbolKind::S_GTHREAD32:
2097 case SymbolKind::S_LTHREAD32: {
2098 auto data_or_err =
2099 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym);
2100 if (!data_or_err) {
2101 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2102 "Failed to deserialize ThreadLocalDataSym record: {0}");
2103 continue;
2104 }
2105 name = data_or_err->Name;
2106 break;
2107 }
2108 case SymbolKind::S_CONSTANT: {
2109 auto data_or_err = SymbolDeserializer::deserializeAs<ConstantSym>(sym);
2110 if (!data_or_err) {
2111 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2112 "Failed to deserialize ConstantSym record: {0}");
2113 continue;
2114 }
2115 name = data_or_err->Name;
2116 break;
2117 }
2118 default:
2119 break;
2120 }
2121
2122 if (!name.empty()) {
2123 llvm::StringRef base = MSVCUndecoratedNameParser::DropScope(name);
2124 if (base.empty())
2125 base = name;
2126
2127 m_global_variable_base_names.Append(ConstString(base), gid);
2128 continue;
2129 }
2130
2131 if (kind != S_PROCREF && kind != S_LPROCREF)
2132 continue;
2133
2134 // For functions, we need to follow the reference to the procedure and look
2135 // at the type
2136
2137 auto ref_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2138 if (!ref_or_err) {
2139 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ref_or_err.takeError(),
2140 "Failed to deserialize ProcRefSym record: {0}");
2141 continue;
2142 }
2143 ProcRefSym ref = std::move(*ref_or_err);
2144 if (ref.Name.empty())
2145 continue;
2146
2147 // Find the function this is referencing.
2148 CompilandIndexItem &cci =
2149 m_index->compilands().GetOrCreateCompiland(ref.modi());
2150 auto iter = cci.m_debug_stream.getSymbolArray().at(ref.SymOffset);
2151 if (iter == cci.m_debug_stream.getSymbolArray().end())
2152 continue;
2153 kind = iter->kind();
2154 if (kind != S_GPROC32 && kind != S_LPROC32)
2155 continue;
2156
2157 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcSym>(*iter);
2158 if (!proc_or_err) {
2159 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2160 "Failed to deserialize ProcSym record: {0}");
2161 continue;
2162 }
2163 ProcSym proc = std::move(*proc_or_err);
2164 if ((proc.Flags & ProcSymFlags::IsUnreachable) != ProcSymFlags::None)
2165 continue;
2166 if (proc.Name.empty() || proc.FunctionType.isSimple())
2167 continue;
2168
2169 // The function/procedure symbol only contains the demangled name.
2170 // The mangled names are in the publics table. Save the address of this
2171 // function to lookup the mangled name later.
2172 func_addr_ids.emplace(std::make_pair(proc.Segment, proc.CodeOffset), gid);
2173
2174 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(proc.Name);
2175 if (basename.empty())
2176 basename = proc.Name;
2177
2178 m_func_base_names.Append(ConstString(basename), gid);
2179 m_func_full_names.Append(ConstString(proc.Name), gid);
2180
2181 // To see if this is a member function, check the type.
2182 auto type = m_index->tpi().getType(proc.FunctionType);
2183 if (type.kind() == LF_MFUNCTION) {
2184 MemberFunctionRecord mfr;
2185 if (auto err = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2186 type, mfr)) {
2188 GetLog(LLDBLog::Symbols), std::move(err),
2189 "Failed to deserialize MemberFunctionRecord record ({1}): {0}",
2190 proc.FunctionType);
2191 } else if (!mfr.getThisType().isNoneType())
2192 m_func_method_names.Append(ConstString(basename), gid);
2193 }
2194 }
2195
2196 // The publics stream contains all mangled function names and their address.
2197 for (auto pid : m_index->publics().getPublicsTable()) {
2198 PdbGlobalSymId global{pid, true};
2199 CVSymbol sym = m_index->ReadSymbolRecord(global);
2200 auto kind = sym.kind();
2201 if (kind != S_PUB32)
2202 continue;
2203 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
2204 if (!pub_or_err) {
2205 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
2206 "Failed to deserialize PublicSym32 record: {0}");
2207 continue;
2208 }
2209 PublicSym32 pub = std::move(*pub_or_err);
2210 // We only care about mangled names - if the name isn't mangled, it's
2211 // already in the full name map.
2212 if (!Mangled::IsMangledName(pub.Name))
2213 continue;
2214
2215 // Check if this symbol is for one of our functions.
2216 auto it = func_addr_ids.find({pub.Segment, pub.Offset});
2217 if (it != func_addr_ids.end())
2218 m_func_full_names.Append(ConstString(pub.Name), it->second);
2219 }
2220
2221 // Sort them before value searching is working properly.
2222 m_func_full_names.Sort(std::less<uint32_t>());
2223 m_func_full_names.SizeToFit();
2224 m_func_method_names.Sort(std::less<uint32_t>());
2225 m_func_method_names.SizeToFit();
2226 m_func_base_names.Sort(std::less<uint32_t>());
2227 m_func_base_names.SizeToFit();
2228 m_global_variable_base_names.Sort(std::less<uint32_t>());
2229 m_global_variable_base_names.SizeToFit();
2230}
2231
2233 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2234 uint32_t max_matches, VariableList &variables) {
2235 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2236
2238
2239 // A leading "::" requests a variable from the global namespace.
2240 llvm::StringRef lookup_name = name.GetStringRef();
2241 bool is_rooted = lookup_name.consume_front("::");
2242
2243 llvm::StringRef context;
2244 llvm::StringRef basename;
2245 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(lookup_name, context,
2246 basename))
2247 basename = lookup_name;
2248 std::string scoped_suffix = ("::" + lookup_name).str();
2249
2250 std::vector<uint32_t> results;
2251 m_global_variable_base_names.GetValues(ConstString(basename), results);
2252
2253 size_t n_matches = 0;
2254 for (uint32_t gid : results) {
2255 PdbGlobalSymId global(gid, false);
2256
2257 if (parent_decl_ctx.IsValid() &&
2258 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2259 continue;
2260
2262 if (!var)
2263 continue;
2264 if (is_rooted || !context.empty()) {
2265 llvm::StringRef var_name = var->GetName().GetStringRef();
2266 if (var_name != lookup_name &&
2267 (is_rooted || !var_name.ends_with(scoped_suffix)))
2268 continue;
2269 }
2270 variables.AddVariable(var);
2271
2272 if (++n_matches >= max_matches)
2273 break;
2274 }
2275}
2276
2278 const Module::LookupInfo &lookup_info,
2279 const CompilerDeclContext &parent_decl_ctx, bool include_inlines,
2280 SymbolContextList &sc_list) {
2281 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2282 ConstString name = lookup_info.GetLookupName();
2283 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2284 if (name_type_mask & eFunctionNameTypeFull)
2285 name = lookup_info.GetName();
2286
2287 if (!(name_type_mask & eFunctionNameTypeFull ||
2288 name_type_mask & eFunctionNameTypeBase ||
2289 name_type_mask & eFunctionNameTypeMethod))
2290 return;
2292
2293 std::set<uint32_t> resolved_ids; // avoid duplicate lookups
2294 auto resolve_from = [&](UniqueCStringMap<uint32_t> &Names) {
2295 std::vector<uint32_t> ids;
2296 if (!Names.GetValues(name, ids))
2297 return;
2298
2299 for (uint32_t id : ids) {
2300 if (!resolved_ids.insert(id).second)
2301 continue;
2302
2303 PdbGlobalSymId global{id, false};
2304 if (parent_decl_ctx.IsValid() &&
2305 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2306 continue;
2307
2308 AppendFunctionForProcRef(global, sc_list);
2309 }
2310 };
2311
2312 if (name_type_mask & eFunctionNameTypeFull)
2313 resolve_from(m_func_full_names);
2314 if (name_type_mask & eFunctionNameTypeBase)
2315 resolve_from(m_func_base_names);
2316 if (name_type_mask & eFunctionNameTypeMethod)
2317 resolve_from(m_func_method_names);
2318}
2319
2321 bool include_inlines,
2322 SymbolContextList &sc_list) {
2323 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2325
2326 // Like SymbolFileDWARF, match both the basenames and the full names (which
2327 // include the mangled names).
2328 std::vector<uint32_t> ids;
2329 m_func_base_names.GetValues(regex, ids);
2330 m_func_full_names.GetValues(regex, ids);
2331
2332 std::set<uint32_t> resolved_ids;
2333 for (uint32_t id : ids)
2334 if (resolved_ids.insert(id).second)
2335 AppendFunctionForProcRef(PdbGlobalSymId{id, false}, sc_list);
2336}
2337
2339 SymbolContextList &sc_list) {
2340 CVSymbol sym = m_index->ReadSymbolRecord(global);
2341 auto kind = sym.kind();
2342 if (kind != S_PROCREF && kind != S_LPROCREF) {
2343 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a proc reference", global);
2344 return;
2345 }
2346
2347 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2348 if (!proc_or_err) {
2349 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2350 "Failed to deserialize ProcRefSym record: {0}");
2351 return;
2352 }
2353 ProcRefSym proc = std::move(*proc_or_err);
2354
2355 if (!IsValidRecord(proc))
2356 return;
2357
2358 CompilandIndexItem &cci =
2359 m_index->compilands().GetOrCreateCompiland(proc.modi());
2360 SymbolContext sc;
2361
2362 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
2363 if (!sc.comp_unit)
2364 return;
2365
2366 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
2367 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
2368 if (!sc.function)
2369 return;
2370
2371 sc_list.Append(sc);
2372}
2373
2375 lldb_private::TypeResults &results) {
2376
2377 // Make sure we haven't already searched this SymbolFile before.
2378 if (results.AlreadySearched(this))
2379 return;
2380
2381 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2382
2384
2385 // We can't query for the full name because the type might reside
2386 // in an anonymous namespace. Search for the basename in our map and check the
2387 // matching types afterwards.
2388 std::vector<uint32_t> matches;
2389 m_type_base_names.GetValues(query.GetTypeBasename(), matches);
2390
2391 for (uint32_t match_idx : matches) {
2392 std::vector context = GetContextForType(TypeIndex(match_idx));
2393 if (context.empty())
2394 continue;
2395
2396 if (query.ContextMatches(context)) {
2397 TypeSP type_sp = GetOrCreateType(TypeIndex(match_idx));
2398 if (!type_sp)
2399 continue;
2400
2401 results.InsertUnique(type_sp);
2402 if (results.Done(query))
2403 return;
2404 }
2405 }
2406
2407 // Typedefs aren't type records, they only exist as S_UDT symbols.
2408 std::vector<uint32_t> typedef_matches;
2409 m_typedef_base_names.GetValues(query.GetTypeBasename(), typedef_matches);
2410 for (uint32_t gid : typedef_matches) {
2411 PdbGlobalSymId global{gid, false};
2412 if (!query.ContextMatches(GetContextForTypedef(global)))
2413 continue;
2414
2415 TypeSP type_sp = GetOrCreateTypedef(global);
2416 if (!type_sp)
2417 continue;
2418
2419 results.InsertUnique(type_sp);
2420 if (results.Done(query))
2421 return;
2422 }
2423}
2424
2425std::vector<CompilerContext>
2427 CVSymbol sym = m_index->ReadSymbolRecord(id);
2428 if (sym.kind() != S_UDT)
2429 return {};
2430 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2431 if (!udt_or_err) {
2432 llvm::consumeError(udt_or_err.takeError());
2433 return {};
2434 }
2435
2436 std::optional<Type::ParsedName> parsed_name =
2437 Type::GetTypeScopeAndBasename(udt_or_err->Name);
2438 if (!parsed_name)
2439 return {{CompilerContextKind::Typedef, ConstString(udt_or_err->Name)}};
2440
2441 // Typedefs nested in a record are LF_NESTTYPE members of its field list, not
2442 // S_UDT symbols, so every scope of an S_UDT is a namespace.
2443 std::vector<CompilerContext> ctx;
2444 for (llvm::StringRef scope : parsed_name->scope)
2445 ctx.emplace_back(CompilerContextKind::Namespace, ConstString(scope));
2446 ctx.emplace_back(CompilerContextKind::Typedef,
2447 ConstString(parsed_name->basename));
2448 return ctx;
2449}
2450
2452 uint32_t max_matches,
2453 TypeMap &types) {
2454
2455 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
2456 if (max_matches > 0 && max_matches < matches.size())
2457 matches.resize(max_matches);
2458
2459 for (TypeIndex ti : matches) {
2460 TypeSP type = GetOrCreateType(ti);
2461 if (!type)
2462 continue;
2463
2464 types.Insert(type);
2465 }
2466}
2467
2469 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2470 // Only do the full type scan the first time.
2472 return 0;
2473
2474 const size_t old_count = GetTypeList().GetSize();
2475 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2476
2477 // First process the entire TPI stream.
2478 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2479 TypeSP type = GetOrCreateType(*ti);
2480 if (type)
2481 (void)type->GetFullCompilerType();
2482 }
2483
2484 // Next look for S_UDT records in the globals stream.
2485 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2486 PdbGlobalSymId global{gid, false};
2487 CVSymbol sym = m_index->ReadSymbolRecord(global);
2488 if (sym.kind() != S_UDT)
2489 continue;
2490
2491 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2492 if (!udt_or_err) {
2493 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2494 "Failed to deserialize UDTSym record: {0}");
2495 continue;
2496 }
2497 if (IsTypedefUdt(*udt_or_err))
2498 GetOrCreateTypedef(global);
2499 }
2500
2501 const size_t new_count = GetTypeList().GetSize();
2502
2503 m_done_full_type_scan = true;
2504
2505 return new_count - old_count;
2506}
2507
2508size_t
2510 VariableList &variables) {
2511 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2512 PdbGlobalSymId global{gid, false};
2513 CVSymbol sym = m_index->ReadSymbolRecord(global);
2514 // TODO: S_CONSTANT is not handled here to prevent a possible crash in
2515 // lldb_private::npdb::MakeConstantLocationExpression when it's a record
2516 // type (e.g. std::strong_ordering::equal). That function needs to be
2517 // updated to handle this case when we add S_CONSTANT case here.
2518 switch (sym.kind()) {
2519 case SymbolKind::S_GDATA32:
2520 case SymbolKind::S_LDATA32:
2521 case SymbolKind::S_GTHREAD32:
2522 case SymbolKind::S_LTHREAD32: {
2524 if (var && var->GetSymbolContextScope() == &comp_unit)
2525 variables.AddVariable(var);
2526 break;
2527 }
2528 default:
2529 break;
2530 }
2531 }
2532 return variables.GetSize();
2533}
2534
2536 PdbCompilandSymId var_id,
2537 bool is_param,
2538 bool is_constant) {
2539 ModuleSP module = GetObjectFile()->GetModule();
2540 Block *block = GetOrCreateBlock(scope_id);
2541 if (!block)
2542 return nullptr;
2543
2544 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
2545 if (!cii)
2546 return nullptr;
2547 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
2548
2549 VariableInfo var_info;
2550 bool location_is_constant_data = is_constant;
2551
2552 if (is_constant) {
2553 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(var_id.offset);
2554 if (sym.kind() != S_CONSTANT)
2555 return nullptr;
2556 ConstantSym constant(sym.kind());
2557 if (auto err =
2558 SymbolDeserializer::deserializeAs<ConstantSym>(sym, constant)) {
2559 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2560 "Failed to deserialize ConstantSym record: {0}");
2561 return nullptr;
2562 }
2563
2564 var_info.name = constant.Name;
2565 var_info.type = constant.Type;
2566 auto location_or_err = MakeConstantLocationExpression(
2567 constant.Type, m_index->tpi(), constant.Value, module);
2568 if (!location_or_err) {
2569 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
2570 "Failed to make constant location expression for {1}: {0}",
2571 constant.Name);
2572 return nullptr;
2573 }
2574 var_info.location =
2575 DWARFExpressionList(module, std::move(*location_or_err), nullptr);
2576 } else {
2577 // Get function block.
2578 Block *func_block = block;
2579 while (func_block->GetParent())
2580 func_block = func_block->GetParent();
2581
2582 Address addr;
2583 func_block->GetStartAddress(addr);
2584 var_info = GetVariableLocationInfo(*m_index, var_id, *func_block, module);
2585 Function *func = func_block->CalculateSymbolContextFunction();
2586 if (!func)
2587 return nullptr;
2588 // Use empty dwarf expr if optimized away so that it won't be filtered out
2589 // when lookuping local variables in this scope.
2590 if (!var_info.location.IsValid())
2591 var_info.location =
2592 DWARFExpressionList(module, DWARFExpression(), nullptr);
2594 }
2595
2596 TypeSP type_sp = GetOrCreateType(var_info.type);
2597 if (!type_sp)
2598 return nullptr;
2599 std::string name = var_info.name.str();
2600 Declaration decl;
2601 SymbolFileTypeSP sftype =
2602 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
2603
2604 is_param |= var_info.is_param;
2605 ValueType var_scope =
2607 bool external = false;
2608 bool artificial = false;
2609 bool static_member = false;
2610 Variable::RangeList scope_ranges;
2611 VariableSP var_sp = std::make_shared<Variable>(
2612 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope, block,
2613 scope_ranges, &decl, var_info.location, external, artificial,
2614 location_is_constant_data, static_member);
2615 if (!is_param) {
2616 auto ts_or_err = GetTypeSystemForLanguage(comp_unit_sp->GetLanguage());
2617 if (auto err = ts_or_err.takeError())
2618 return nullptr;
2619 auto ts = *ts_or_err;
2620 if (ts) {
2621 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
2622 ast_builder->EnsureVariable(scope_id, var_id);
2623 }
2624 }
2625 m_local_variables[toOpaqueUid(var_id)] = var_sp;
2626 return var_sp;
2627}
2628
2631 PdbCompilandSymId var_id,
2632 bool is_param, bool is_constant) {
2633 auto iter = m_local_variables.find(toOpaqueUid(var_id));
2634 if (iter != m_local_variables.end())
2635 return iter->second;
2636
2637 return CreateLocalVariable(scope_id, var_id, is_param, is_constant);
2638}
2639
2642 PdbCompilandSymId var_id) {
2643 auto iter = m_local_variables.find(toOpaqueUid(var_id));
2644 if (iter != m_local_variables.end())
2645 return iter->second;
2646
2647 Block *block = GetOrCreateBlock(scope_id);
2648 if (!block)
2649 return nullptr;
2650
2651 ModuleSP module_sp = GetObjectFile()->GetModule();
2652 CVSymbol sym = m_index->ReadSymbolRecord(var_id);
2653 TypeIndex ti;
2654 llvm::StringRef name;
2656 DWARFExpression location_expr;
2657 switch (sym.kind()) {
2658 case S_LDATA32: {
2659 DataSym ds(sym.kind());
2660 if (auto err = SymbolDeserializer::deserializeAs<DataSym>(sym, ds)) {
2661 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2662 "Failed to deserialize DataSym record: {0}");
2663 return nullptr;
2664 }
2665 ti = ds.Type;
2666 name = ds.Name;
2667 location_expr =
2668 MakeGlobalLocationExpression(ds.Segment, ds.DataOffset, module_sp);
2669 break;
2670 }
2671 case S_LTHREAD32: {
2672 ThreadLocalDataSym tlds(sym.kind());
2673 if (auto err =
2674 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)) {
2675 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2676 "Failed to deserialize ThreadLocalDataSym record: {0}");
2677 return nullptr;
2678 }
2679 ti = tlds.Type;
2680 name = tlds.Name;
2682 location_expr =
2683 MakeGlobalThreadLocalLocationExpression(tlds.DataOffset, module_sp);
2684 break;
2685 }
2686 default:
2687 return nullptr;
2688 }
2689
2690 TypeSP type_sp = GetOrCreateType(ti);
2691 if (!type_sp)
2692 return nullptr;
2693 SymbolFileTypeSP sftype =
2694 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
2695
2696 DWARFExpressionList location(module_sp, location_expr, nullptr);
2697 Declaration decl;
2698 VariableSP var_sp = std::make_shared<Variable>(
2699 toOpaqueUid(var_id), name.str().c_str(), /*mangled=*/nullptr, sftype,
2700 scope, block, Variable::RangeList(), &decl, location, /*external=*/false,
2701 /*artificial=*/false, /*location_is_constant_data=*/false,
2702 /*static_member=*/false);
2703
2704 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
2705 if (cii) {
2706 auto ts_or_err =
2708 if (auto err = ts_or_err.takeError())
2709 llvm::consumeError(std::move(err));
2710 else if (auto ts = *ts_or_err)
2711 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
2712 ast_builder->EnsureVariable(scope_id, var_id);
2713 }
2714
2715 m_local_variables[toOpaqueUid(var_id)] = var_sp;
2716 return var_sp;
2717}
2718
2720 CVSymbol sym = m_index->ReadSymbolRecord(id);
2721 if (sym.kind() != S_UDT) {
2722 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not an S_UDT", id);
2723 return nullptr;
2724 }
2725
2726 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2727 if (!udt_or_err) {
2728 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2729 "Failed to deserialize UDTSym record: {0}");
2730 return nullptr;
2731 }
2732 UDTSym udt = std::move(*udt_or_err);
2733
2734 TypeSP target_type = GetOrCreateType(udt.Type);
2735
2737 if (auto err = ts_or_err.takeError())
2738 return nullptr;
2739 auto ts = *ts_or_err;
2740 if (!ts)
2741 return nullptr;
2742 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2743 if (!ast_builder)
2744 return nullptr;
2745 CompilerType ct = ast_builder->GetOrCreateTypedefType(id);
2746 if (!ct)
2747 ct = target_type->GetForwardCompilerType();
2748
2749 Declaration decl;
2750 return MakeType(toOpaqueUid(id), ConstString(udt.Name),
2751 llvm::expectedToOptional(target_type->GetByteSize(nullptr)),
2752 nullptr, target_type->GetID(),
2755}
2756
2758 auto iter = m_types.find(toOpaqueUid(id));
2759 if (iter != m_types.end())
2760 return iter->second;
2761
2762 TypeSP type = CreateTypedef(id);
2763 if (type)
2764 m_types[toOpaqueUid(id)] = type;
2765 return type;
2766}
2767
2768bool SymbolFileNativePDB::IsTypedefUdt(const UDTSym &udt) {
2769 // Clang and MSVC also emit an S_UDT for each tag type, named like the tag.
2770 if (!IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi()))
2771 return true;
2772 CVType cvt = m_index->tpi().getType(udt.Type);
2773 return CVTagRecord::create(cvt).name() != udt.Name;
2774}
2775
2777 Block *block = GetOrCreateBlock(block_id);
2778 if (!block)
2779 return 0;
2780
2781 size_t count = 0;
2782
2783 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
2784 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
2785 uint32_t params_remaining = 0;
2786 switch (sym.kind()) {
2787 case S_GPROC32:
2788 case S_LPROC32: {
2789 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
2790 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym, proc)) {
2791 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2792 "Failed to deserialize ProcSym record: {0}");
2793 return 0;
2794 }
2795 CVType signature = m_index->tpi().getType(proc.FunctionType);
2796 if (signature.kind() == LF_PROCEDURE) {
2797 ProcedureRecord sig;
2798 if (llvm::Error e = TypeDeserializer::deserializeAs<ProcedureRecord>(
2799 signature, sig)) {
2800 llvm::consumeError(std::move(e));
2801 return 0;
2802 }
2803 params_remaining = sig.getParameterCount();
2804 } else if (signature.kind() == LF_MFUNCTION) {
2805 MemberFunctionRecord sig;
2806 if (llvm::Error e = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2807 signature, sig)) {
2808 llvm::consumeError(std::move(e));
2809 return 0;
2810 }
2811 params_remaining = sig.getParameterCount();
2812 } else
2813 return 0;
2814 break;
2815 }
2816 case S_BLOCK32:
2817 break;
2818 case S_INLINESITE:
2819 break;
2820 default:
2821 LLDB_LOG(GetLog(LLDBLog::Symbols), "{0} is not a block", block_id);
2822 return 0;
2823 }
2824
2825 VariableListSP variables = block->GetBlockVariableList(false);
2826 if (!variables) {
2827 variables = std::make_shared<VariableList>();
2828 block->SetVariableList(variables);
2829 }
2830
2831 CVSymbolArray syms = limitSymbolArrayToScope(
2832 cii->m_debug_stream.getSymbolArray(), block_id.offset);
2833
2834 // Skip the first record since it's a PROC32 or BLOCK32, and there's
2835 // no point examining it since we know it's not a local variable.
2836 syms.drop_front();
2837 auto iter = syms.begin();
2838 auto end = syms.end();
2839
2840 while (iter != end) {
2841 uint32_t record_offset = iter.offset();
2842 CVSymbol variable_cvs = *iter;
2843 PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
2844 ++iter;
2845
2846 // If this is a block or inline site, recurse into its children and then
2847 // skip it.
2848 if (variable_cvs.kind() == S_BLOCK32 ||
2849 variable_cvs.kind() == S_INLINESITE) {
2850 uint32_t block_end = getScopeEndOffset(variable_cvs);
2851 count += ParseVariablesForBlock(child_sym_id);
2852 iter = syms.at(block_end);
2853 continue;
2854 }
2855
2856 bool is_param = params_remaining > 0;
2857 VariableSP variable;
2858 switch (variable_cvs.kind()) {
2859 case S_REGREL32:
2860 case S_REGREL32_INDIR:
2861 case S_REGISTER:
2862 case S_LOCAL:
2863 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
2864 if (is_param)
2865 --params_remaining;
2866 if (variable)
2867 variables->AddVariableIfUnique(variable);
2868 break;
2869 case S_CONSTANT:
2870 variable = GetOrCreateLocalVariable(block_id, child_sym_id,
2871 /*is_param=*/false,
2872 /*is_constant=*/true);
2873 if (variable)
2874 variables->AddVariableIfUnique(variable);
2875 break;
2876 case S_LDATA32:
2877 case S_LTHREAD32:
2878 variable = GetOrCreateLocalStaticVariable(block_id, child_sym_id);
2879 if (variable)
2880 variables->AddVariableIfUnique(variable);
2881 break;
2882 default:
2883 break;
2884 }
2885 }
2886
2887 // Pass false for set_children, since we call this recursively so that the
2888 // children will call this for themselves.
2889 block->SetDidParseVariables(true, false);
2890
2891 return count;
2892}
2893
2895 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2896
2897 if (sc.block) {
2898 PdbSymUid block_id(sc.block->GetID());
2899
2900 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2901 return count;
2902 }
2903
2904 if (sc.function) {
2905 PdbSymUid block_id(sc.function->GetID());
2906
2907 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2908 return count;
2909 }
2910
2911 if (sc.comp_unit) {
2912 VariableListSP variables = sc.comp_unit->GetVariableList(false);
2913 if (!variables) {
2914 variables = std::make_shared<VariableList>();
2915 sc.comp_unit->SetVariableList(variables);
2916 }
2917 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
2918 }
2919
2921 "missing missing block, function, or module for symbol context");
2922 return 0;
2923}
2924
2927 if (auto err = ts_or_err.takeError())
2928 return CompilerDecl();
2929 auto ts = *ts_or_err;
2930 if (!ts)
2931 return {};
2932 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2933 if (!ast_builder)
2934 return {};
2935 return ast_builder->GetOrCreateDeclForUid(uid);
2936}
2937
2941 if (auto err = ts_or_err.takeError())
2942 return {};
2943 auto ts = *ts_or_err;
2944 if (!ts)
2945 return {};
2946 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2947 if (!ast_builder)
2948 return {};
2949 return ast_builder->GetOrCreateDeclContextForUid(PdbSymUid(uid));
2950}
2951
2955 if (auto err = ts_or_err.takeError())
2956 return CompilerDeclContext();
2957 auto ts = *ts_or_err;
2958 if (!ts)
2959 return {};
2960 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2961 if (!ast_builder)
2962 return {};
2963 return ast_builder->GetParentDeclContext(PdbSymUid(uid));
2964}
2965
2967 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2968 auto iter = m_types.find(type_uid);
2969 // lldb should not be passing us non-sensical type uids. the only way it
2970 // could have a type uid in the first place is if we handed it out, in which
2971 // case we should know about the type. However, that doesn't mean we've
2972 // instantiated it yet. We can vend out a UID for a future type. So if the
2973 // type doesn't exist, let's instantiate it now.
2974 if (iter != m_types.end())
2975 return &*iter->second;
2976
2977 PdbSymUid uid(type_uid);
2978 if (uid.kind() != PdbSymUidKind::Type) {
2979 assert(false && "uid is not a type index");
2980 return nullptr;
2981 }
2982 PdbTypeSymId type_id = uid.asTypeSym();
2983 if (type_id.index.isNoneType())
2984 return nullptr;
2985
2986 TypeSP type_sp = CreateAndCacheType(type_id);
2987 if (!type_sp)
2988 return nullptr;
2989 return &*type_sp;
2990}
2991
2992std::optional<SymbolFile::ArrayInfo>
2994 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
2995 return std::nullopt;
2996}
2997
2999 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3000 auto ts = compiler_type.GetTypeSystem();
3001 if (!ts)
3002 return false;
3003
3004 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
3005 if (!ast_builder)
3006 return false;
3007 return ast_builder->CompleteType(compiler_type);
3008}
3009
3011 TypeClass type_mask,
3012 lldb_private::TypeList &type_list) {}
3013
3016 const CompilerDeclContext &parent_decl_ctx,
3017 bool /* only_root_namespaces */) {
3018 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3020 if (auto err = ts_or_err.takeError())
3021 return {};
3022 auto ts = *ts_or_err;
3023 if (!ts)
3024 return {};
3025 auto *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
3026 if (!clang)
3027 return {};
3028
3029 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
3030 if (!ast_builder)
3031 return {};
3032
3033 return ast_builder->FindNamespaceDecl(parent_decl_ctx, name.GetStringRef());
3034}
3035
3036llvm::Expected<lldb::TypeSystemSP>
3038 auto type_system_or_err =
3039 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
3040 if (type_system_or_err)
3041 if (auto ts = *type_system_or_err)
3042 ts->SetSymbolFile(this);
3043 return type_system_or_err;
3044}
3045
3046uint64_t SymbolFileNativePDB::GetDebugInfoSize(bool load_all_debug_info) {
3047 // PDB files are a separate file that contains all debug info.
3048 return m_index->pdb().getFileSize();
3049}
3050
3053 return;
3054 m_parent_map_built = true;
3055
3056 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
3057
3058 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
3059 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
3060
3061 struct RecordIndices {
3062 TypeIndex forward;
3063 TypeIndex full;
3064 };
3065
3066 llvm::StringMap<RecordIndices> record_indices;
3067
3068 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
3069 CVType type = types.getType(*ti);
3070 if (!IsTagRecord(type))
3071 continue;
3072
3073 CVTagRecord tag = CVTagRecord::create(type);
3074
3075 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
3076 if (tag.asTag().isForwardRef()) {
3077 indices.forward = *ti;
3078 } else {
3079 indices.full = *ti;
3080
3081 auto base_name = MSVCUndecoratedNameParser::DropScope(tag.name());
3082 m_type_base_names.Append(ConstString(base_name), ti->getIndex());
3083 }
3084
3085 if (indices.full != TypeIndex::None() &&
3086 indices.forward != TypeIndex::None()) {
3087 forward_to_full[indices.forward] = indices.full;
3088 full_to_forward[indices.full] = indices.forward;
3089 }
3090
3091 // We're looking for LF_NESTTYPE records in the field list, so ignore
3092 // forward references (no field list), and anything without a nested class
3093 // (since there won't be any LF_NESTTYPE records).
3094 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
3095 continue;
3096
3097 struct ProcessTpiStream : public TypeVisitorCallbacks {
3098 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
3099 const CVTagRecord &parent_cvt,
3100 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
3101 : index(index), parents(parents), parent(parent),
3102 parent_cvt(parent_cvt) {}
3103
3104 PdbIndex &index;
3105 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
3106
3107 unsigned unnamed_type_index = 1;
3108 TypeIndex parent;
3109 const CVTagRecord &parent_cvt;
3110
3111 llvm::Error visitKnownMember(CVMemberRecord &CVR,
3112 NestedTypeRecord &Record) override {
3113 std::string unnamed_type_name;
3114 if (Record.Name.empty()) {
3115 unnamed_type_name =
3116 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
3117 Record.Name = unnamed_type_name;
3118 ++unnamed_type_index;
3119 }
3120 std::optional<CVTagRecord> tag =
3121 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
3122 if (!tag)
3123 return llvm::ErrorSuccess();
3124
3125 parents[Record.Type] = parent;
3126 return llvm::ErrorSuccess();
3127 }
3128 };
3129
3130 CVType field_list_cvt = m_index->tpi().getType(tag.asTag().FieldList);
3131 if (field_list_cvt.kind() != LF_FIELDLIST)
3132 continue; // Invalid reference to a field list.
3133
3134 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
3135 FieldListRecord field_list;
3136 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
3137 field_list_cvt, field_list))
3138 llvm::consumeError(std::move(error));
3139 if (llvm::Error error = visitMemberRecordStream(field_list.Data, process))
3140 llvm::consumeError(std::move(error));
3141 }
3142
3143 // After calling Append(), the type-name map needs to be sorted again to be
3144 // able to look up a type by its name.
3145 m_type_base_names.Sort(std::less<uint32_t>());
3146
3147 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
3148 CVSymbol sym = m_index->symrecords().readRecord(gid);
3149 if (sym.kind() != S_UDT)
3150 continue;
3151 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
3152 if (!udt_or_err) {
3153 llvm::consumeError(udt_or_err.takeError());
3154 continue;
3155 }
3156 if (!IsTypedefUdt(*udt_or_err))
3157 continue;
3158 llvm::StringRef base_name =
3159 MSVCUndecoratedNameParser::DropScope(udt_or_err->Name);
3160 m_typedef_base_names.Append(ConstString(base_name), gid);
3161 }
3162 m_typedef_base_names.Sort(std::less<uint32_t>());
3163
3164 // Now that we know the forward -> full mapping of all type indices, we can
3165 // re-write all the indices. At the end of this process, we want a mapping
3166 // consisting of fwd -> full and full -> full for all child -> parent indices.
3167 // We can re-write the values in place, but for the keys, we must save them
3168 // off so that we don't modify the map in place while also iterating it.
3169 std::vector<TypeIndex> full_keys;
3170 std::vector<TypeIndex> fwd_keys;
3171 for (auto &entry : m_parent_types) {
3172 TypeIndex key = entry.first;
3173 TypeIndex value = entry.second;
3174
3175 auto iter = forward_to_full.find(value);
3176 if (iter != forward_to_full.end())
3177 entry.second = iter->second;
3178
3179 iter = forward_to_full.find(key);
3180 if (iter != forward_to_full.end())
3181 fwd_keys.push_back(key);
3182 else
3183 full_keys.push_back(key);
3184 }
3185 for (TypeIndex fwd : fwd_keys) {
3186 TypeIndex full = forward_to_full[fwd];
3187 TypeIndex parent_idx = m_parent_types[fwd];
3188 m_parent_types[full] = parent_idx;
3189 }
3190 for (TypeIndex full : full_keys) {
3191 TypeIndex fwd = full_to_forward[full];
3192 m_parent_types[fwd] = m_parent_types[full];
3193 }
3194}
3195
3196std::optional<PdbCompilandSymId>
3198 CVSymbol sym = m_index->ReadSymbolRecord(id);
3199 if (symbolOpensScope(sym.kind())) {
3200 // If this exact symbol opens a scope, we can just directly access its
3201 // parent.
3202 id.offset = getScopeParentOffset(sym);
3203 // Global symbols have parent offset of 0. Return std::nullopt to indicate
3204 // this.
3205 if (id.offset == 0)
3206 return std::nullopt;
3207 return id;
3208 }
3209
3210 // Otherwise we need to start at the beginning and iterate forward until we
3211 // reach (or pass) this particular symbol
3212 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(id.modi);
3213 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
3214
3215 auto begin = syms.begin();
3216 auto end = syms.at(id.offset);
3217 std::vector<PdbCompilandSymId> scope_stack;
3218
3219 while (begin != end) {
3220 if (begin.offset() > id.offset) {
3221 // We passed it. We couldn't even find this symbol record.
3222 LLDB_LOG(GetLog(LLDBLog::Symbols), "invalid compiland symbol id: {0}",
3223 id);
3224 return std::nullopt;
3225 }
3226
3227 // We haven't found the symbol yet. Check if we need to open or close the
3228 // scope stack.
3229 if (symbolOpensScope(begin->kind())) {
3230 // We can use the end offset of the scope to determine whether or not
3231 // we can just outright skip this entire scope.
3232 uint32_t scope_end = getScopeEndOffset(*begin);
3233 if (scope_end < id.offset) {
3234 begin = syms.at(scope_end);
3235 } else {
3236 // The symbol we're looking for is somewhere in this scope.
3237 scope_stack.emplace_back(id.modi, begin.offset());
3238 }
3239 } else if (symbolEndsScope(begin->kind())) {
3240 scope_stack.pop_back();
3241 }
3242 ++begin;
3243 }
3244 if (scope_stack.empty())
3245 return std::nullopt;
3246 // We have a match! Return the top of the stack
3247 return scope_stack.back();
3248}
3249
3250std::optional<llvm::codeview::TypeIndex>
3251SymbolFileNativePDB::GetParentType(llvm::codeview::TypeIndex ti) {
3253 auto parent_iter = m_parent_types.find(ti);
3254 if (parent_iter == m_parent_types.end())
3255 return std::nullopt;
3256 return parent_iter->second;
3257}
3258
3259std::vector<CompilerContext>
3261 CVType type = m_index->tpi().getType(ti);
3262 if (!IsTagRecord(type))
3263 return {};
3264
3265 CVTagRecord tag = CVTagRecord::create(type);
3266
3267 std::optional<Type::ParsedName> parsed_name =
3269 if (!parsed_name)
3270 return {{tag.contextKind(), ConstString(tag.name())}};
3271
3272 std::vector<CompilerContext> ctx;
3273 // assume everything is a namespace at first
3274 for (llvm::StringRef scope : parsed_name->scope) {
3275 ctx.emplace_back(CompilerContextKind::Namespace, ConstString(scope));
3276 }
3277 // we know the kind of our own type
3278 ctx.emplace_back(tag.contextKind(), ConstString(parsed_name->basename));
3279
3280 // try to find the kind of parents
3281 for (auto &el : llvm::reverse(llvm::drop_end(ctx))) {
3282 std::optional<TypeIndex> parent = GetParentType(ti);
3283 if (!parent)
3284 break;
3285
3286 ti = *parent;
3287 type = m_index->tpi().getType(ti);
3288 switch (type.kind()) {
3289 case LF_CLASS:
3290 case LF_STRUCTURE:
3291 case LF_INTERFACE:
3293 continue;
3294 case LF_UNION:
3296 continue;
3297 case LF_ENUM:
3298 el.kind = CompilerContextKind::Enum;
3299 continue;
3300 default:
3301 break;
3302 }
3303 break;
3304 }
3305 return ctx;
3306}
3307
3308std::optional<llvm::StringRef>
3310 TypeIndex function_type) {
3311 auto symbol = m_index->publics().findByAddress(m_index->symrecords(),
3312 so.segment, so.offset);
3313 if (!symbol)
3314 return std::nullopt;
3315
3316 llvm::StringRef name = symbol->first.Name;
3317 // For functions, we might need to strip the mangled name. See
3318 // StripMangledFunctionName for more info.
3319 if (!function_type.isNoneType() &&
3320 (symbol->first.Flags & PublicSymFlags::Function) != PublicSymFlags::None)
3321 name = StripMangledFunctionName(name, function_type);
3322
3323 return name;
3324}
3325
3326llvm::StringRef
3328 PdbTypeSymId func_ty) {
3329 // "In non-64 bit environments" (on x86 in pactice), __cdecl functions get
3330 // prefixed with an underscore. For compilers using LLVM, this happens in LLVM
3331 // (as opposed to the compiler frontend). Because of this, DWARF doesn't
3332 // contain the "full" mangled name in DW_AT_linkage_name for these functions.
3333 // We strip the mangling here for compatibility with DWARF. See
3334 // llvm.org/pr161676 and
3335 // https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names#FormatC
3336
3337 if (!mangled.starts_with('_') ||
3338 m_index->dbi().getMachineType() != PDB_Machine::x86)
3339 return mangled;
3340
3341 CVType cvt = m_index->tpi().getType(func_ty.index);
3342 PDB_CallingConv cc = PDB_CallingConv::NearC;
3343 if (cvt.kind() == LF_PROCEDURE) {
3344 ProcedureRecord proc;
3345 if (llvm::Error error =
3346 TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, proc))
3347 llvm::consumeError(std::move(error));
3348 cc = proc.CallConv;
3349 } else if (cvt.kind() == LF_MFUNCTION) {
3350 MemberFunctionRecord mfunc;
3351 if (llvm::Error error =
3352 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfunc))
3353 llvm::consumeError(std::move(error));
3354 cc = mfunc.CallConv;
3355 } else {
3356 LLDB_LOG(GetLog(LLDBLog::Symbols), "Unexpected function type, got {0}",
3357 cvt.kind());
3358 return mangled;
3359 }
3360
3361 if (cc == PDB_CallingConv::NearC || cc == PDB_CallingConv::FarC)
3362 return mangled.drop_front();
3363
3364 return mangled;
3365}
3366
3367std::string
3369 llvm::StringRef lookup_name) {
3370 if (lookup_name.empty())
3371 return {};
3372
3373 lldb::ModuleSP module_sp = m_objfile_sp->GetModule();
3374 if (!module_sp)
3375 return {};
3376
3377 // Note, discriminator is added by Clang during mangling.
3378 return FunctionCallLabel{/*discriminator=*/{},
3379 /*module_id=*/module_sp->GetID(),
3380 /*symbol_id=*/uid.toOpaqueId(),
3381 /*lookup_name=*/lookup_name}
3382 .toString();
3383}
3384
3386 const CompilandIndexItem *cci = m_index->compilands().GetCompiland(id.modi);
3387 if (!cci)
3388 return {};
3389
3390 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(id.offset);
3391 if (sym_record.kind() != S_LPROC32 && sym_record.kind() != S_GPROC32)
3392 return {};
3393
3394 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
3395 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)) {
3396 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3397 "Failed to deserialize ProcSym record: {0}");
3398 return {};
3399 }
3400
3401 // Functions with internal linkage have no public symbol, so fall back to the
3402 // name in the procedure record.
3403 llvm::StringRef lookup_name =
3404 FindMangledSymbol(SegmentOffset(proc.Segment, proc.CodeOffset),
3405 proc.FunctionType)
3406 .value_or(proc.Name);
3407 return MakeFunctionCallLabel(id, lookup_name);
3408}
3409
3410std::string
3412 llvm::StringRef qualified_name) {
3413 if (std::optional<PdbCompilandSymId> func_id =
3414 FindMethodDefinition(qualified_name, method_type))
3415 return GetFunctionCallLabel(*func_id);
3416 return {};
3417}
3418
3419std::optional<PdbCompilandSymId>
3420SymbolFileNativePDB::FindMethodDefinition(llvm::StringRef qualified_name,
3421 TypeIndex method_type) {
3422 // GSIHashTable leaves its bucket map uninitialized when the table has no
3423 // records, so findRecordsByName cannot be called on it.
3424 if (m_index->globals().getGlobalsTable().HashRecords.empty())
3425 return std::nullopt;
3426
3427 Log *log = GetLog(LLDBLog::Symbols);
3428 for (const auto &[offset, sym] : m_index->globals().findRecordsByName(
3429 qualified_name, m_index->symrecords())) {
3430 if (sym.kind() != S_PROCREF && sym.kind() != S_LPROCREF)
3431 continue;
3432 auto ref_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
3433 if (!ref_or_err) {
3434 LLDB_LOG_ERROR(log, ref_or_err.takeError(),
3435 "Failed to deserialize ProcRefSym record: {0}");
3436 continue;
3437 }
3438
3439 // Nothing else may have loaded the compiland of the definition yet.
3440 CompilandIndexItem &cci =
3441 m_index->compilands().GetOrCreateCompiland(ref_or_err->modi());
3442 auto iter = cci.m_debug_stream.getSymbolArray().at(ref_or_err->SymOffset);
3443 if (iter == cci.m_debug_stream.getSymbolArray().end())
3444 continue;
3445 if (iter->kind() != S_GPROC32 && iter->kind() != S_LPROC32)
3446 continue;
3447 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcSym>(*iter);
3448 if (!proc_or_err) {
3449 LLDB_LOG_ERROR(log, proc_or_err.takeError(),
3450 "Failed to deserialize ProcSym record: {0}");
3451 continue;
3452 }
3453
3454 // Overloads share the name, so only the type identifies the definition.
3455 if (proc_or_err->FunctionType == method_type)
3456 return PdbCompilandSymId(ref_or_err->modi(), ref_or_err->SymOffset);
3457 }
3458 return std::nullopt;
3459}
3460
3461llvm::Expected<SymbolContext>
3463 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3464
3465 // Only complete and base object structors have a procedure record. Closures
3466 // and deleting destructors have no debug info.
3467 if (llvm::StringRef discriminator = label.discriminator;
3468 !discriminator.empty()) {
3469 const bool is_ctor = discriminator.consume_front("C");
3470 uint64_t kind;
3471 bool is_defined = false;
3472 if ((is_ctor || discriminator.consume_front("D")) &&
3473 llvm::to_integer(discriminator, kind))
3474 is_defined = is_ctor ? kind == clang::CXXCtorType::Ctor_Complete ||
3475 kind == clang::CXXCtorType::Ctor_Base
3476 : kind == clang::CXXDtorType::Dtor_Complete ||
3477 kind == clang::CXXDtorType::Dtor_Base;
3478 if (!is_defined)
3479 return llvm::createStringErrorV(
3480 "{0} refers to a structor variant without debug info", label);
3481 }
3482
3483 PdbSymUid uid(label.symbol_id);
3484 if (uid.kind() != PdbSymUidKind::CompilandSym)
3485 return llvm::createStringErrorV("invalid function ID in {0}", label);
3486 PdbCompilandSymId func_id = uid.asCompilandSym();
3487
3488 CompilandIndexItem *cci = m_index->compilands().GetCompiland(func_id.modi);
3489 if (!cci)
3490 return llvm::createStringErrorV("invalid compiland in {0}", label);
3491
3492 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cci);
3493 if (!comp_unit)
3494 return llvm::createStringErrorV("failed to create compile unit for {0}",
3495 label);
3496
3497 FunctionSP func = GetOrCreateFunction(func_id, *comp_unit);
3498 if (!func)
3499 return llvm::createStringErrorV("failed to create function for {0}", label);
3500
3501 SymbolContext sc;
3502 func->CalculateSymbolContext(&sc);
3503 return sc;
3504}
3505
3507 for (CVType cvt : m_index->ipi().typeArray()) {
3508 switch (cvt.kind()) {
3509 case LF_UDT_SRC_LINE: {
3510 UdtSourceLineRecord udt_src;
3511 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_src)) {
3512 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3513 "Failed to deserialize UdtSourceLineRecord record: {0}");
3514 continue;
3515 }
3516 m_udt_declarations.try_emplace(
3517 udt_src.UDT, UdtDeclaration{/*FileNameIndex=*/udt_src.SourceFile,
3518 /*IsIpiIndex=*/true,
3519 /*Line=*/udt_src.LineNumber});
3520 } break;
3521 case LF_UDT_MOD_SRC_LINE: {
3522 UdtModSourceLineRecord udt_mod_src;
3523 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_mod_src)) {
3525 GetLog(LLDBLog::Symbols), std::move(err),
3526 "Failed to deserialize UdtModSourceLineRecord record: {0}");
3527 continue;
3528 }
3529 // Some types might be contributed by multiple modules. We assume that
3530 // they all point to the same file and line because we can only provide
3531 // one location.
3532 m_udt_declarations.try_emplace(
3533 udt_mod_src.UDT,
3534 UdtDeclaration{/*FileNameIndex=*/udt_mod_src.SourceFile,
3535 /*IsIpiIndex=*/false,
3536 /*Line=*/udt_mod_src.LineNumber});
3537 } break;
3538 default:
3539 break;
3540 }
3541 }
3542}
3543
3544llvm::Expected<Declaration>
3546 std::call_once(m_cached_udt_declarations, [this] { CacheUdtDeclarations(); });
3547
3548 auto it = m_udt_declarations.find(type_id.index);
3549 if (it == m_udt_declarations.end())
3550 return llvm::createStringError("no UDT declaration found");
3551
3552 llvm::StringRef file_name;
3553 if (it->second.IsIpiIndex) {
3554 CVType cvt = m_index->ipi().getType(it->second.FileNameIndex);
3555 if (cvt.kind() != LF_STRING_ID)
3556 return llvm::createStringError("file name was not a LF_STRING_ID");
3557
3558 StringIdRecord sid;
3559 if (auto err = TypeDeserializer::deserializeAs(cvt, sid))
3560 return std::move(err);
3561 file_name = sid.String;
3562 } else {
3563 // The file name index is an index into the string table
3564 auto string_table = m_index->pdb().getStringTable();
3565 if (!string_table)
3566 return string_table.takeError();
3567
3568 llvm::Expected<llvm::StringRef> string =
3569 string_table->getStringTable().getString(
3570 it->second.FileNameIndex.getIndex());
3571 if (!string)
3572 return string.takeError();
3573 file_name = *string;
3574 }
3575
3576 // rustc sets the filename to "<unknown>" for some files
3577 if (file_name == "\\<unknown>")
3578 return Declaration();
3579
3580 return Declaration(FileSpec(file_name), it->second.Line);
3581}
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:103
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file collection class.
A file utility class.
Definition FileSpec.h:56
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:326
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:317
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:431
llvm::sys::path::Style Style
Definition FileSpec.h:58
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
A class that describes a function.
Definition Function.h:386
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:439
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition Function.cpp:401
static void AppendLineEntryToSequence(Sequence &sequence, lldb::addr_t file_addr, uint32_t line, uint16_t column, uint16_t file_idx, bool is_start_of_statement, bool is_start_of_basic_block, bool is_prologue_end, bool is_epilogue_begin, bool is_terminal_entry)
Definition LineTable.cpp:59
A class that handles mangled names.
Definition Mangled.h:34
static bool IsMangledName(llvm::StringRef name)
Definition Mangled.cpp:39
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
A class that encapsulates name lookup information.
Definition Module.h:935
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:976
ConstString GetLookupName() const
Definition Module.h:974
ConstString GetName() const
Definition Module.h:972
static std::unique_ptr< llvm::pdb::PDBFile > loadPDBFile(std::string PdbPath, llvm::BumpPtrAllocator &Allocator)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
RangeData< lldb::addr_t, uint32_t, std::pair< uint32_t, uint32_t > > Entry
Definition RangeMap.h:462
void Append(const Entry &entry)
Definition RangeMap.h:474
Entry * FindEntryThatContains(B addr)
Definition RangeMap.h:583
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
A stream class that can stream formatted output to a file.
Definition Stream.h:28
A list of support files for a CompileUnit.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
void Append(const FileSpec &file)
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * block
The Block for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override
ObjectFile * GetObjectFile() override
Definition SymbolFile.h:595
virtual TypeList & GetTypeList()
Definition SymbolFile.h:668
lldb::ObjectFileSP m_objfile_sp
Definition SymbolFile.h:671
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
Definition SymbolFile.h:580
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:639
@ kAllAbilities
All detailed debug-information abilities.
Definition SymbolFile.h:80
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:226
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:62
size_t GetNumSymbols() const
Definition Symtab.cpp:75
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2941
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.
ConstString GetTypeBasename() const
Get the type basename to use when searching the type indexes in each SymbolFile object.
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.
This class tracks the state and results of a TypeQuery.
bool InsertUnique(const lldb::TypeSP &type_sp)
When types that match a TypeQuery are found, this API is used to insert the matching types.
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
bool AlreadySearched(lldb_private::SymbolFile *sym_file)
Check if a SymbolFile object has already been searched by this type match object.
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.
@ eEncodingIsUID
This type is the type whose UID is m_encoding_uid.
static std::optional< ParsedName > GetTypeScopeAndBasename(llvm::StringRef name)
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
std::vector< CompilerContext > GetContextForTypedef(PdbGlobalSymId id)
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
void AppendFunctionForProcRef(PdbGlobalSymId global, SymbolContextList &sc_list)
Append the function referenced by the S_PROCREF/S_LPROCREF global.
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)
lldb_private::UniqueCStringMap< uint32_t > m_typedef_base_names
typedef basename -> Global ID(s) of its S_UDT
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
bool IsTypedefUdt(const llvm::codeview::UDTSym &udt)
Returns true if udt is a typedef rather than the S_UDT that is emitted for every tag type.
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
lldb::VariableSP GetOrCreateLocalStaticVariable(PdbCompilandSymId scope_id, PdbCompilandSymId var_id)
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