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