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