[Go to site: main page, start]

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 (cvs.kind() != S_CONSTANT)
1129 return nullptr;
1130
1131 if (auto err =
1132 SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)) {
1133 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1134 "Failed to deserialize ConstantSym record: {0}");
1135 return nullptr;
1136 }
1137 std::string global_name("::");
1138 global_name += constant.Name;
1139 PdbTypeSymId tid(constant.Type, false);
1140 SymbolFileTypeSP type_sp =
1141 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
1142
1143 Declaration decl;
1144 Variable::RangeList ranges;
1145 ModuleSP module = GetObjectFile()->GetModule();
1146 auto location_or_err = MakeConstantLocationExpression(constant.Type, tpi,
1147 constant.Value, module);
1148 if (!location_or_err) {
1149 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
1150 "Failed to make constant location expression for {1}: {0}",
1151 constant.Name);
1152 return nullptr;
1153 }
1154 DWARFExpressionList location(module, std::move(*location_or_err), nullptr);
1155
1156 bool external = false;
1157 bool artificial = false;
1158 bool location_is_constant_data = true;
1159 bool static_member = false;
1160 VariableSP var_sp = std::make_shared<Variable>(
1161 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
1162 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
1163 external, artificial, location_is_constant_data, static_member);
1164 return var_sp;
1165}
1166
1169 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
1170 if (emplace_result.second) {
1171 if (VariableSP var_sp = CreateGlobalVariable(var_id))
1172 emplace_result.first->second = var_sp;
1173 else
1174 return nullptr;
1175 }
1176
1177 return emplace_result.first->second;
1178}
1179
1181 return GetOrCreateType(PdbTypeSymId(ti, false));
1182}
1183
1185 CompileUnit &comp_unit) {
1186 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
1187 if (emplace_result.second)
1188 emplace_result.first->second = CreateFunction(func_id, comp_unit);
1189
1190 return emplace_result.first->second;
1191}
1192
1195
1196 auto emplace_result =
1197 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
1198 if (emplace_result.second)
1199 emplace_result.first->second = CreateCompileUnit(cci);
1200
1201 lldbassert(emplace_result.first->second);
1202 return emplace_result.first->second;
1203}
1204
1206 auto iter = m_blocks.find(toOpaqueUid(block_id));
1207 if (iter != m_blocks.end())
1208 return iter->second.get();
1209
1210 return CreateBlock(block_id);
1211}
1212
1215 TypeSystem *ts = decl_ctx.GetTypeSystem();
1216 if (!ts)
1217 return;
1218 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
1219 if (!ast_builder)
1220 return;
1221 ast_builder->ParseDeclsForContext(decl_ctx);
1222}
1223
1225 if (index >= GetNumCompileUnits())
1226 return CompUnitSP();
1227 lldbassert(index < UINT16_MAX);
1228 if (index >= UINT16_MAX)
1229 return nullptr;
1230
1231 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1232
1233 return GetOrCreateCompileUnit(item);
1234}
1235
1237 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1238 PdbSymUid uid(comp_unit.GetID());
1240
1241 CompilandIndexItem *item =
1242 m_index->compilands().GetCompiland(uid.asCompiland().modi);
1243 lldbassert(item);
1244 if (!item->m_compile_opts)
1246
1247 return TranslateLanguage(item->m_compile_opts->getLanguage());
1248}
1249
1251 auto *section_list =
1252 m_objfile_sp->GetModule()->GetObjectFile()->GetSectionList();
1253 if (!section_list)
1254 return;
1255
1256 PublicSym32 last_sym;
1257 size_t last_sym_idx = 0;
1258 lldb::SectionSP section_sp;
1259
1260 // To estimate the size of a symbol, we use the difference to the next symbol.
1261 // If there's no next symbol or the section/segment changed, the symbol will
1262 // take the remaining space. The estimate can be too high in case there's
1263 // padding between symbols. This similar to the algorithm used by the DIA
1264 // SDK.
1265 auto finish_last_symbol = [&](const PublicSym32 *next) {
1266 if (!section_sp)
1267 return;
1268 Symbol *last = symtab.SymbolAtIndex(last_sym_idx);
1269 if (!last)
1270 return;
1271
1272 if (next && last_sym.Segment == next->Segment) {
1273 assert(last_sym.Offset <= next->Offset);
1274 last->SetByteSize(next->Offset - last_sym.Offset);
1275 } else {
1276 // the last symbol was the last in its section
1277 assert(section_sp->GetByteSize() >= last_sym.Offset);
1278 assert(!next || next->Segment > last_sym.Segment);
1279 last->SetByteSize(section_sp->GetByteSize() - last_sym.Offset);
1280 }
1281 };
1282
1283 // The address map is sorted by the address of a symbol.
1284 for (auto pid : m_index->publics().getAddressMap()) {
1285 PdbGlobalSymId global{pid, true};
1286 CVSymbol sym = m_index->ReadSymbolRecord(global);
1287 auto kind = sym.kind();
1288 if (kind != S_PUB32)
1289 continue;
1290 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
1291 if (!pub_or_err) {
1292 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
1293 "Failed to deserialize PublicSym32 record: {0}");
1294 continue;
1295 }
1296 PublicSym32 pub = std::move(*pub_or_err);
1297 finish_last_symbol(&pub);
1298
1299 if (!section_sp || last_sym.Segment != pub.Segment)
1300 section_sp = section_list->FindSectionByID(pub.Segment);
1301
1302 if (!section_sp)
1303 continue;
1304
1306 if ((pub.Flags & PublicSymFlags::Function) != PublicSymFlags::None ||
1307 (pub.Flags & PublicSymFlags::Code) != PublicSymFlags::None)
1308 type = eSymbolTypeCode;
1309
1310 last_sym_idx =
1311 symtab.AddSymbol(Symbol(/*symID=*/pid,
1312 /*name=*/pub.Name,
1313 /*type=*/type,
1314 /*external=*/true,
1315 /*is_debug=*/true,
1316 /*is_trampoline=*/false,
1317 /*is_artificial=*/false,
1318 /*section_sp=*/section_sp,
1319 /*value=*/pub.Offset,
1320 /*size=*/0,
1321 /*size_is_valid=*/false,
1322 /*contains_linker_annotations=*/false,
1323 /*flags=*/0));
1324 last_sym = pub;
1325 }
1326
1327 finish_last_symbol(nullptr);
1328}
1329
1331 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1332 PdbSymUid uid{comp_unit.GetID()};
1334 uint16_t modi = uid.asCompiland().modi;
1335 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
1336
1337 size_t count = comp_unit.GetNumFunctions();
1338 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
1339 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1340 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
1341 continue;
1342
1343 PdbCompilandSymId sym_id{modi, iter.offset()};
1344
1345 FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
1346 }
1347
1348 size_t new_count = comp_unit.GetNumFunctions();
1349 lldbassert(new_count >= count);
1350 return new_count - count;
1351}
1352
1353static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1354 // If any of these flags are set, we need to resolve the compile unit.
1355 uint32_t flags = eSymbolContextCompUnit;
1356 flags |= eSymbolContextVariable;
1357 flags |= eSymbolContextFunction;
1358 flags |= eSymbolContextBlock;
1359 flags |= eSymbolContextLineEntry;
1360 return (resolve_scope & flags) != 0;
1361}
1362
1364 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1365 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1366 uint32_t resolved_flags = 0;
1367 lldb::addr_t file_addr = addr.GetFileAddress();
1368
1369 if (NeedsResolvedCompileUnit(resolve_scope)) {
1370 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1371 if (!modi)
1372 return 0;
1373 CompUnitSP cu_sp = GetCompileUnitAtIndex(*modi);
1374 if (!cu_sp)
1375 return 0;
1376
1377 sc.comp_unit = cu_sp.get();
1378 resolved_flags |= eSymbolContextCompUnit;
1379 }
1380
1381 if (resolve_scope & eSymbolContextFunction ||
1382 resolve_scope & eSymbolContextBlock) {
1384 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1385 // Search the matches in reverse. This way if there are multiple matches
1386 // (for example we are 3 levels deep in a nested scope) it will find the
1387 // innermost one first.
1388 for (const auto &match : llvm::reverse(matches)) {
1389 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1390 continue;
1391
1392 PdbCompilandSymId csid = match.uid.asCompilandSym();
1393 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1394 PDB_SymType type = CVSymToPDBSym(cvs.kind());
1395 if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1396 continue;
1397 if (type == PDB_SymType::Function) {
1398 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1399 if (sc.function) {
1400 Block &block = sc.function->GetBlock(true);
1401 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1402 addr_t offset = file_addr - func_base;
1403 sc.block = block.FindInnermostBlockByOffset(offset);
1404 }
1405 }
1406
1407 if (type == PDB_SymType::Block) {
1408 Block *block = GetOrCreateBlock(csid);
1409 if (!block)
1410 continue;
1412 if (sc.function) {
1413 sc.function->GetBlock(true);
1414 addr_t func_base = sc.function->GetAddress().GetFileAddress();
1415 addr_t offset = file_addr - func_base;
1416 sc.block = block->FindInnermostBlockByOffset(offset);
1417 }
1418 }
1419 if (sc.function)
1420 resolved_flags |= eSymbolContextFunction;
1421 if (sc.block)
1422 resolved_flags |= eSymbolContextBlock;
1423 break;
1424 }
1425 }
1426
1427 if (resolve_scope & eSymbolContextLineEntry) {
1429 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1430 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1431 resolved_flags |= eSymbolContextLineEntry;
1432 }
1433 }
1434
1435 return resolved_flags;
1436}
1437
1439 const SourceLocationSpec &src_location_spec,
1440 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1441 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1442 const uint32_t prev_size = sc_list.GetSize();
1443 if (resolve_scope & eSymbolContextCompUnit) {
1444 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1445 ++cu_idx) {
1446 CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1447 if (!cu)
1448 continue;
1449
1450 bool file_spec_matches_cu_file_spec = FileSpec::Match(
1451 src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1452 if (file_spec_matches_cu_file_spec) {
1453 cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1454 break;
1455 }
1456 }
1457 }
1458 return sc_list.GetSize() - prev_size;
1459}
1460
1462 // Unfortunately LLDB is set up to parse the entire compile unit line table
1463 // all at once, even if all it really needs is line info for a specific
1464 // function. In the future it would be nice if it could set the sc.m_function
1465 // member, and we could only get the line info for the function in question.
1466 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1467 PdbSymUid cu_id(comp_unit.GetID());
1469 uint16_t modi = cu_id.asCompiland().modi;
1470 CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1471 lldbassert(cii);
1472
1473 // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1474 // in this CU. Add line entries into the set first so that if there are line
1475 // entries with same addres, the later is always more accurate than the
1476 // former.
1477 std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1478
1479 // This is basically a copy of the .debug$S subsections from all original COFF
1480 // object files merged together with address relocations applied. We are
1481 // looking for all DEBUG_S_LINES subsections.
1482 for (const DebugSubsectionRecord &dssr :
1483 cii->m_debug_stream.getSubsectionsArray()) {
1484 if (dssr.kind() != DebugSubsectionKind::Lines)
1485 continue;
1486
1487 DebugLinesSubsectionRef lines;
1488 llvm::BinaryStreamReader reader(dssr.getRecordData());
1489 if (auto EC = lines.initialize(reader)) {
1490 llvm::consumeError(std::move(EC));
1491 return false;
1492 }
1493
1494 const LineFragmentHeader *lfh = lines.header();
1495 uint64_t virtual_addr =
1496 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1497 if (virtual_addr == LLDB_INVALID_ADDRESS)
1498 continue;
1499
1500 for (const LineColumnEntry &group : lines) {
1501 llvm::Expected<uint32_t> file_index_or_err =
1502 GetFileIndex(*cii, group.NameIndex);
1503 if (!file_index_or_err) {
1504 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1505 "failed to get file index for line entry: {0}");
1506 continue;
1507 }
1508 uint32_t file_index = file_index_or_err.get();
1509 lldbassert(!group.LineNumbers.empty());
1512 for (const LineNumberEntry &entry : group.LineNumbers) {
1513 LineInfo cur_info(entry.Flags);
1514
1515 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1516 continue;
1517
1518 uint64_t addr = virtual_addr + entry.Offset;
1519
1520 bool is_statement = cur_info.isStatement();
1521 bool is_prologue = IsFunctionPrologue(*cii, addr);
1522 bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1523
1524 uint32_t lno = cur_info.getStartLine();
1525
1526 LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1527 is_prologue, is_epilogue, false);
1528 // Terminal entry has lower precedence than new entry.
1529 auto iter = line_set.find(new_entry);
1530 if (iter != line_set.end() && iter->is_terminal_entry)
1531 line_set.erase(iter);
1532 line_set.insert(new_entry);
1533
1534 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1535 line_entry.SetRangeEnd(addr);
1536 cii->m_global_line_table.Append(line_entry);
1537 }
1538 line_entry.SetRangeBase(addr);
1539 line_entry.data = {file_index, lno};
1540 }
1541 LineInfo last_line(group.LineNumbers.back().Flags);
1542 line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1543 file_index, false, false, false, false, true);
1544
1545 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1546 line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1547 cii->m_global_line_table.Append(line_entry);
1548 }
1549 }
1550 }
1551
1553
1554 // Parse all S_INLINESITE in this CU.
1555 const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1556 for (auto iter = syms.begin(); iter != syms.end();) {
1557 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1558 ++iter;
1559 continue;
1560 }
1561
1562 uint32_t record_offset = iter.offset();
1563 CVSymbol func_record =
1564 cii->m_debug_stream.readSymbolAtOffset(record_offset);
1566 addr_t file_vm_addr =
1567 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
1568 if (file_vm_addr == LLDB_INVALID_ADDRESS)
1569 continue;
1570
1571 Address func_base(file_vm_addr, comp_unit.GetModule()->GetSectionList());
1572 PdbCompilandSymId func_id{modi, record_offset};
1573
1574 // Iterate all S_INLINESITEs in the function.
1575 auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1576 if (kind != S_INLINESITE)
1577 return false;
1578
1579 ParseInlineSite(id, func_base);
1580
1581 for (const auto &line_entry :
1582 m_inline_sites[toOpaqueUid(id)]->line_entries) {
1583 // If line_entry is not terminal entry, remove previous line entry at
1584 // the same address and insert new one. Terminal entry inside an inline
1585 // site might not be terminal entry for its parent.
1586 if (!line_entry.is_terminal_entry)
1587 line_set.erase(line_entry);
1588 line_set.insert(line_entry);
1589 }
1590 // No longer useful after adding to line_set.
1591 m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1592 return true;
1593 };
1594 ParseSymbolArrayInScope(func_id, parse_inline_sites);
1595 // Jump to the end of the function record.
1596 iter = syms.at(getScopeEndOffset(func_record));
1597 }
1598
1600
1601 // Add line entries in line_set to line_table.
1602 std::vector<LineTable::Sequence> sequence(1);
1603 for (const auto &line_entry : line_set) {
1605 sequence.back(), line_entry.file_addr, line_entry.line,
1606 line_entry.column, line_entry.file_idx,
1607 line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1608 line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1609 line_entry.is_terminal_entry);
1610 }
1611 auto line_table =
1612 std::make_unique<LineTable>(&comp_unit, std::move(sequence));
1613
1614 if (line_table->GetSize() == 0)
1615 return false;
1616
1617 comp_unit.SetLineTable(line_table.release());
1618 return true;
1619}
1620
1622 // PDB doesn't contain information about macros
1623 return false;
1624}
1625
1626llvm::Expected<uint32_t>
1628 uint32_t file_id) {
1629 if (!cii.m_strings.hasChecksums() || !cii.m_strings.hasStrings())
1630 return llvm::make_error<RawError>(raw_error_code::no_entry);
1631
1632 const auto &checksums = cii.m_strings.checksums().getArray();
1633 const auto &strings = cii.m_strings.strings();
1634 // Indices in this structure are actually offsets of records in the
1635 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1636 // into the global PDB string table.
1637 auto iter = checksums.at(file_id);
1638 if (iter == checksums.end())
1639 return llvm::make_error<RawError>(raw_error_code::no_entry);
1640
1641 llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1642 if (!efn) {
1643 return efn.takeError();
1644 }
1645
1646 // LLDB wants the index of the file in the list of support files.
1647 auto fn_iter = llvm::find(cii.m_file_list, *efn);
1648 if (fn_iter != cii.m_file_list.end())
1649 return std::distance(cii.m_file_list.begin(), fn_iter);
1650 return llvm::make_error<RawError>(raw_error_code::no_entry);
1651}
1652
1654 SupportFileList &support_files) {
1655 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1656 PdbSymUid cu_id(comp_unit.GetID());
1658 CompilandIndexItem *cci =
1659 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1660 lldbassert(cci);
1661
1662 for (llvm::StringRef f : cci->m_file_list) {
1663 FileSpec::Style style =
1664 f.starts_with("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1665 FileSpec spec(f, style);
1666 support_files.Append(spec);
1667 }
1668 return true;
1669}
1670
1672 const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1673 // PDB does not yet support module debug info
1674 return false;
1675}
1676
1678 Address func_addr) {
1679 lldb::user_id_t opaque_uid = toOpaqueUid(id);
1680 if (m_inline_sites.contains(opaque_uid))
1681 return;
1682
1683 addr_t func_base = func_addr.GetFileAddress();
1684 CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1685 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1686 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1687 if (sym.kind() != S_INLINESITE)
1688 return;
1689
1690 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1691 if (auto err =
1692 SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site)) {
1693 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1694 "Failed to deserialize InlineSiteSym record: {0}");
1695 return;
1696 }
1697 PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1698
1699 std::shared_ptr<InlineSite> inline_site_sp =
1700 std::make_shared<InlineSite>(parent_id);
1701
1702 // Get the inlined function declaration info.
1703 auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1704 if (iter == cii->m_inline_map.end())
1705 return;
1706 InlineeSourceLine inlinee_line = iter->second;
1707
1708 const SupportFileList &files = comp_unit->GetSupportFiles();
1709 FileSpec decl_file;
1710 llvm::Expected<uint32_t> file_index_or_err =
1711 GetFileIndex(*cii, inlinee_line.Header->FileID);
1712 if (!file_index_or_err) {
1713 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), file_index_or_err.takeError(),
1714 "failed to get file index for inline site: {0}");
1715 return;
1716 }
1717 uint32_t file_offset = file_index_or_err.get();
1718 decl_file = files.GetFileSpecAtIndex(file_offset);
1719 uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1720 std::unique_ptr<Declaration> decl_up =
1721 std::make_unique<Declaration>(decl_file, decl_line);
1722
1723 // Parse range and line info.
1724 uint32_t code_offset = 0;
1725 int32_t line_offset = 0;
1726 std::optional<uint32_t> code_offset_base;
1727 std::optional<uint32_t> code_offset_end;
1728 std::optional<int32_t> cur_line_offset;
1729 std::optional<int32_t> next_line_offset;
1730 std::optional<uint32_t> next_file_offset;
1731
1732 bool is_terminal_entry = false;
1733 bool is_start_of_statement = true;
1734 // The first instruction is the prologue end.
1735 bool is_prologue_end = true;
1736
1737 auto update_code_offset = [&](uint32_t code_delta) {
1738 if (!code_offset_base)
1739 code_offset_base = code_offset;
1740 else if (!code_offset_end)
1741 code_offset_end = *code_offset_base + code_delta;
1742 };
1743 auto update_line_offset = [&](int32_t line_delta) {
1744 line_offset += line_delta;
1745 if (!code_offset_base || !cur_line_offset)
1746 cur_line_offset = line_offset;
1747 else
1748 next_line_offset = line_offset;
1749 ;
1750 };
1751 auto update_file_offset = [&](uint32_t offset) {
1752 if (!code_offset_base)
1753 file_offset = offset;
1754 else
1755 next_file_offset = offset;
1756 };
1757
1758 for (auto &annot : inline_site.annotations()) {
1759 switch (annot.OpCode) {
1760 case BinaryAnnotationsOpCode::CodeOffset:
1761 case BinaryAnnotationsOpCode::ChangeCodeOffset:
1762 case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1763 code_offset += annot.U1;
1764 update_code_offset(annot.U1);
1765 break;
1766 case BinaryAnnotationsOpCode::ChangeLineOffset:
1767 update_line_offset(annot.S1);
1768 break;
1769 case BinaryAnnotationsOpCode::ChangeCodeLength:
1770 update_code_offset(annot.U1);
1771 code_offset += annot.U1;
1772 is_terminal_entry = true;
1773 break;
1774 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1775 code_offset += annot.U1;
1776 update_code_offset(annot.U1);
1777 update_line_offset(annot.S1);
1778 break;
1779 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1780 code_offset += annot.U2;
1781 update_code_offset(annot.U2);
1782 update_code_offset(annot.U1);
1783 code_offset += annot.U1;
1784 is_terminal_entry = true;
1785 break;
1786 case BinaryAnnotationsOpCode::ChangeFile:
1787 update_file_offset(annot.U1);
1788 break;
1789 default:
1790 break;
1791 }
1792
1793 // Add range if current range is finished.
1794 if (code_offset_base && code_offset_end && cur_line_offset) {
1795 inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1796 *code_offset_base, *code_offset_end - *code_offset_base,
1797 decl_line + *cur_line_offset));
1798 // Set base, end, file offset and line offset for next range.
1799 if (next_file_offset)
1800 file_offset = *next_file_offset;
1801 if (next_line_offset) {
1802 cur_line_offset = next_line_offset;
1803 next_line_offset = std::nullopt;
1804 }
1805 code_offset_base = is_terminal_entry ? std::nullopt : code_offset_end;
1806 code_offset_end = next_file_offset = std::nullopt;
1807 }
1808 if (code_offset_base && cur_line_offset) {
1809 if (is_terminal_entry) {
1810 LineTable::Entry line_entry(
1811 func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1812 file_offset, false, false, false, false, true);
1813 inline_site_sp->line_entries.push_back(line_entry);
1814 } else {
1815 LineTable::Entry line_entry(func_base + *code_offset_base,
1816 decl_line + *cur_line_offset, 0,
1817 file_offset, is_start_of_statement, false,
1818 is_prologue_end, false, false);
1819 inline_site_sp->line_entries.push_back(line_entry);
1820 is_prologue_end = false;
1821 is_start_of_statement = false;
1822 }
1823 }
1824 if (is_terminal_entry)
1825 is_start_of_statement = true;
1826 is_terminal_entry = false;
1827 }
1828
1829 inline_site_sp->ranges.Sort();
1830
1831 // Get the inlined function callsite info.
1832 std::unique_ptr<Declaration> callsite_up;
1833 if (!inline_site_sp->ranges.IsEmpty()) {
1834 auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1835 addr_t base_offset = entry->GetRangeBase();
1836 if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1837 S_INLINESITE) {
1838 // Its parent is another inline site, lookup parent site's range vector
1839 // for callsite line.
1840 ParseInlineSite(parent_id, Address(func_base));
1841 std::shared_ptr<InlineSite> parent_site =
1842 m_inline_sites[toOpaqueUid(parent_id)];
1843 FileSpec &parent_decl_file =
1844 parent_site->inline_function_info->GetDeclaration().GetFile();
1845 if (auto *parent_entry =
1846 parent_site->ranges.FindEntryThatContains(base_offset)) {
1847 callsite_up =
1848 std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1849 }
1850 } else {
1851 // Its parent is a function, lookup global line table for callsite.
1852 if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1853 func_base + base_offset)) {
1854 const FileSpec &callsite_file =
1855 files.GetFileSpecAtIndex(entry->data.first);
1856 callsite_up =
1857 std::make_unique<Declaration>(callsite_file, entry->data.second);
1858 }
1859 }
1860 }
1861
1862 // Get the inlined function name.
1863 std::string inlinee_name;
1864 llvm::Expected<CVType> inlinee_cvt =
1865 m_index->ipi().typeCollection().getTypeOrError(inline_site.Inlinee);
1866 if (!inlinee_cvt) {
1867 inlinee_name = "[error reading function name: " +
1868 llvm::toString(inlinee_cvt.takeError()) + "]";
1869 } else if (inlinee_cvt->kind() == LF_MFUNC_ID) {
1870 MemberFuncIdRecord mfr;
1871 if (auto err = TypeDeserializer::deserializeAs<MemberFuncIdRecord>(
1872 *inlinee_cvt, mfr)) {
1873 inlinee_name =
1874 "[error reading function name: " + llvm::toString(std::move(err)) +
1875 "]";
1876 } else {
1877 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1878 inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1879 inlinee_name.append("::");
1880 inlinee_name.append(mfr.getName().str());
1881 }
1882 } else if (inlinee_cvt->kind() == LF_FUNC_ID) {
1883 FuncIdRecord fir;
1884 if (auto err =
1885 TypeDeserializer::deserializeAs<FuncIdRecord>(*inlinee_cvt, fir)) {
1886 inlinee_name =
1887 "[error reading function name: " + llvm::toString(std::move(err)) +
1888 "]";
1889 } else {
1890 TypeIndex parent_idx = fir.getParentScope();
1891 if (!parent_idx.isNoneType()) {
1892 LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1893 inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1894 inlinee_name.append("::");
1895 }
1896 inlinee_name.append(fir.getName().str());
1897 }
1898 }
1899 inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1900 inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1901 callsite_up.get());
1902
1903 m_inline_sites[opaque_uid] = inline_site_sp;
1904}
1905
1907 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1908 PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1909 // After we iterate through inline sites inside the function, we already get
1910 // all the info needed, removing from the map to save memory.
1911 std::set<uint64_t> remove_uids;
1912 auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
1913 if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
1914 kind == S_INLINESITE) {
1915 GetOrCreateBlock(id);
1916 if (kind == S_INLINESITE)
1917 remove_uids.insert(toOpaqueUid(id));
1918 return true;
1919 }
1920 return false;
1921 };
1922 size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
1923 for (uint64_t uid : remove_uids) {
1924 m_inline_sites.erase(uid);
1925 }
1926
1927 func.GetBlock(false).SetBlockInfoHasBeenParsed(true, true);
1928 return count;
1929}
1930
1932 PdbCompilandSymId parent_id,
1933 llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
1934 CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
1935 CVSymbolArray syms =
1936 cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
1937
1938 size_t count = 1;
1939 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1940 PdbCompilandSymId child_id(parent_id.modi, iter.offset());
1941 if (fn(iter->kind(), child_id))
1942 ++count;
1943 }
1944
1945 return count;
1946}
1947
1948void SymbolFileNativePDB::DumpClangAST(Stream &s, llvm::StringRef filter,
1949 bool show_color) {
1951 if (!ts_or_err) {
1952 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ts_or_err.takeError(),
1953 "failed to get C++ type system: {0}");
1954 return;
1955 }
1956 auto ts = *ts_or_err;
1957 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
1958 if (!clang)
1959 return;
1960 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
1961 if (!ast_builder)
1962 return;
1963 ast_builder->Dump(s, filter, show_color);
1964}
1965
1967 if (!m_func_full_names.IsEmpty() || !m_global_variable_base_names.IsEmpty())
1968 return;
1969
1970 // (segment, code offset) -> gid
1971 std::map<std::pair<uint16_t, uint32_t>, uint32_t> func_addr_ids;
1972
1973 // First, look through all items in the globals table.
1974 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1975 CVSymbol sym = m_index->symrecords().readRecord(gid);
1976 auto kind = sym.kind();
1977
1978 // If this is a global variable, we only need to look at the name
1979 llvm::StringRef name;
1980 switch (kind) {
1981 case SymbolKind::S_GDATA32:
1982 case SymbolKind::S_LDATA32: {
1983 auto data_or_err = SymbolDeserializer::deserializeAs<DataSym>(sym);
1984 if (!data_or_err) {
1985 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
1986 "Failed to deserialize DataSym record: {0}");
1987 continue;
1988 }
1989 name = data_or_err->Name;
1990 break;
1991 }
1992 case SymbolKind::S_GTHREAD32:
1993 case SymbolKind::S_LTHREAD32: {
1994 auto data_or_err =
1995 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym);
1996 if (!data_or_err) {
1997 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
1998 "Failed to deserialize ThreadLocalDataSym record: {0}");
1999 continue;
2000 }
2001 name = data_or_err->Name;
2002 break;
2003 }
2004 case SymbolKind::S_CONSTANT: {
2005 auto data_or_err = SymbolDeserializer::deserializeAs<ConstantSym>(sym);
2006 if (!data_or_err) {
2007 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), data_or_err.takeError(),
2008 "Failed to deserialize ConstantSym record: {0}");
2009 continue;
2010 }
2011 name = data_or_err->Name;
2012 break;
2013 }
2014 default:
2015 break;
2016 }
2017
2018 if (!name.empty()) {
2019 llvm::StringRef base = MSVCUndecoratedNameParser::DropScope(name);
2020 if (base.empty())
2021 base = name;
2022
2023 m_global_variable_base_names.Append(ConstString(base), gid);
2024 continue;
2025 }
2026
2027 if (kind != S_PROCREF && kind != S_LPROCREF)
2028 continue;
2029
2030 // For functions, we need to follow the reference to the procedure and look
2031 // at the type
2032
2033 auto ref_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2034 if (!ref_or_err) {
2035 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), ref_or_err.takeError(),
2036 "Failed to deserialize ProcRefSym record: {0}");
2037 continue;
2038 }
2039 ProcRefSym ref = std::move(*ref_or_err);
2040 if (ref.Name.empty())
2041 continue;
2042
2043 // Find the function this is referencing.
2044 CompilandIndexItem &cci =
2045 m_index->compilands().GetOrCreateCompiland(ref.modi());
2046 auto iter = cci.m_debug_stream.getSymbolArray().at(ref.SymOffset);
2047 if (iter == cci.m_debug_stream.getSymbolArray().end())
2048 continue;
2049 kind = iter->kind();
2050 if (kind != S_GPROC32 && kind != S_LPROC32)
2051 continue;
2052
2053 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcSym>(*iter);
2054 if (!proc_or_err) {
2055 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2056 "Failed to deserialize ProcSym record: {0}");
2057 continue;
2058 }
2059 ProcSym proc = std::move(*proc_or_err);
2060 if ((proc.Flags & ProcSymFlags::IsUnreachable) != ProcSymFlags::None)
2061 continue;
2062 if (proc.Name.empty() || proc.FunctionType.isSimple())
2063 continue;
2064
2065 // The function/procedure symbol only contains the demangled name.
2066 // The mangled names are in the publics table. Save the address of this
2067 // function to lookup the mangled name later.
2068 func_addr_ids.emplace(std::make_pair(proc.Segment, proc.CodeOffset), gid);
2069
2070 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(proc.Name);
2071 if (basename.empty())
2072 basename = proc.Name;
2073
2074 m_func_base_names.Append(ConstString(basename), gid);
2075 m_func_full_names.Append(ConstString(proc.Name), gid);
2076
2077 // To see if this is a member function, check the type.
2078 auto type = m_index->tpi().getType(proc.FunctionType);
2079 if (type.kind() == LF_MFUNCTION) {
2080 MemberFunctionRecord mfr;
2081 if (auto err = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2082 type, mfr)) {
2084 GetLog(LLDBLog::Symbols), std::move(err),
2085 "Failed to deserialize MemberFunctionRecord record ({1}): {0}",
2086 proc.FunctionType);
2087 } else if (!mfr.getThisType().isNoneType())
2088 m_func_method_names.Append(ConstString(basename), gid);
2089 }
2090 }
2091
2092 // The publics stream contains all mangled function names and their address.
2093 for (auto pid : m_index->publics().getPublicsTable()) {
2094 PdbGlobalSymId global{pid, true};
2095 CVSymbol sym = m_index->ReadSymbolRecord(global);
2096 auto kind = sym.kind();
2097 if (kind != S_PUB32)
2098 continue;
2099 auto pub_or_err = SymbolDeserializer::deserializeAs<PublicSym32>(sym);
2100 if (!pub_or_err) {
2101 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), pub_or_err.takeError(),
2102 "Failed to deserialize PublicSym32 record: {0}");
2103 continue;
2104 }
2105 PublicSym32 pub = std::move(*pub_or_err);
2106 // We only care about mangled names - if the name isn't mangled, it's
2107 // already in the full name map.
2108 if (!Mangled::IsMangledName(pub.Name))
2109 continue;
2110
2111 // Check if this symbol is for one of our functions.
2112 auto it = func_addr_ids.find({pub.Segment, pub.Offset});
2113 if (it != func_addr_ids.end())
2114 m_func_full_names.Append(ConstString(pub.Name), it->second);
2115 }
2116
2117 // Sort them before value searching is working properly.
2118 m_func_full_names.Sort(std::less<uint32_t>());
2119 m_func_full_names.SizeToFit();
2120 m_func_method_names.Sort(std::less<uint32_t>());
2121 m_func_method_names.SizeToFit();
2122 m_func_base_names.Sort(std::less<uint32_t>());
2123 m_func_base_names.SizeToFit();
2124 m_global_variable_base_names.Sort(std::less<uint32_t>());
2125 m_global_variable_base_names.SizeToFit();
2126}
2127
2129 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2130 uint32_t max_matches, VariableList &variables) {
2131 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2132
2134
2135 std::vector<uint32_t> results;
2136 m_global_variable_base_names.GetValues(name, results);
2137
2138 size_t n_matches = 0;
2139 for (uint32_t gid : results) {
2140 PdbGlobalSymId global(gid, false);
2141
2142 if (parent_decl_ctx.IsValid() &&
2143 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2144 continue;
2145
2147 if (!var)
2148 continue;
2149 variables.AddVariable(var);
2150
2151 if (++n_matches >= max_matches)
2152 break;
2153 }
2154}
2155
2157 const Module::LookupInfo &lookup_info,
2158 const CompilerDeclContext &parent_decl_ctx, bool include_inlines,
2159 SymbolContextList &sc_list) {
2160 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2161 ConstString name = lookup_info.GetLookupName();
2162 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2163 if (name_type_mask & eFunctionNameTypeFull)
2164 name = lookup_info.GetName();
2165
2166 if (!(name_type_mask & eFunctionNameTypeFull ||
2167 name_type_mask & eFunctionNameTypeBase ||
2168 name_type_mask & eFunctionNameTypeMethod))
2169 return;
2171
2172 std::set<uint32_t> resolved_ids; // avoid duplicate lookups
2173 auto resolve_from = [&](UniqueCStringMap<uint32_t> &Names) {
2174 std::vector<uint32_t> ids;
2175 if (!Names.GetValues(name, ids))
2176 return;
2177
2178 for (uint32_t id : ids) {
2179 if (!resolved_ids.insert(id).second)
2180 continue;
2181
2182 PdbGlobalSymId global{id, false};
2183 if (parent_decl_ctx.IsValid() &&
2184 GetDeclContextContainingUID(toOpaqueUid(global)) != parent_decl_ctx)
2185 continue;
2186
2187 CVSymbol sym = m_index->ReadSymbolRecord(global);
2188 auto kind = sym.kind();
2189 lldbassert(kind == S_PROCREF || kind == S_LPROCREF);
2190
2191 auto proc_or_err = SymbolDeserializer::deserializeAs<ProcRefSym>(sym);
2192 if (!proc_or_err) {
2193 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), proc_or_err.takeError(),
2194 "Failed to deserialize ProcRefSym record: {0}");
2195 continue;
2196 }
2197 ProcRefSym proc = std::move(*proc_or_err);
2198
2199 if (!IsValidRecord(proc))
2200 continue;
2201
2202 CompilandIndexItem &cci =
2203 m_index->compilands().GetOrCreateCompiland(proc.modi());
2204 SymbolContext sc;
2205
2206 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
2207 if (!sc.comp_unit)
2208 continue;
2209
2210 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
2211 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
2212 if (!sc.function)
2213 continue;
2214
2215 sc_list.Append(sc);
2216 }
2217 };
2218
2219 if (name_type_mask & eFunctionNameTypeFull)
2220 resolve_from(m_func_full_names);
2221 if (name_type_mask & eFunctionNameTypeBase)
2222 resolve_from(m_func_base_names);
2223 if (name_type_mask & eFunctionNameTypeMethod)
2224 resolve_from(m_func_method_names);
2225}
2226
2228 bool include_inlines,
2229 SymbolContextList &sc_list) {}
2230
2232 lldb_private::TypeResults &results) {
2233
2234 // Make sure we haven't already searched this SymbolFile before.
2235 if (results.AlreadySearched(this))
2236 return;
2237
2238 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2239
2240 // We can't query for the full name because the type might reside
2241 // in an anonymous namespace. Search for the basename in our map and check the
2242 // matching types afterwards.
2243 std::vector<uint32_t> matches;
2244 m_type_base_names.GetValues(query.GetTypeBasename(), matches);
2245
2246 for (uint32_t match_idx : matches) {
2247 std::vector context = GetContextForType(TypeIndex(match_idx));
2248 if (context.empty())
2249 continue;
2250
2251 if (query.ContextMatches(context)) {
2252 TypeSP type_sp = GetOrCreateType(TypeIndex(match_idx));
2253 if (!type_sp)
2254 continue;
2255
2256 results.InsertUnique(type_sp);
2257 if (results.Done(query))
2258 return;
2259 }
2260 }
2261}
2262
2264 uint32_t max_matches,
2265 TypeMap &types) {
2266
2267 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
2268 if (max_matches > 0 && max_matches < matches.size())
2269 matches.resize(max_matches);
2270
2271 for (TypeIndex ti : matches) {
2272 TypeSP type = GetOrCreateType(ti);
2273 if (!type)
2274 continue;
2275
2276 types.Insert(type);
2277 }
2278}
2279
2281 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2282 // Only do the full type scan the first time.
2284 return 0;
2285
2286 const size_t old_count = GetTypeList().GetSize();
2287 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2288
2289 // First process the entire TPI stream.
2290 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2291 TypeSP type = GetOrCreateType(*ti);
2292 if (type)
2293 (void)type->GetFullCompilerType();
2294 }
2295
2296 // Next look for S_UDT records in the globals stream.
2297 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2298 PdbGlobalSymId global{gid, false};
2299 CVSymbol sym = m_index->ReadSymbolRecord(global);
2300 if (sym.kind() != S_UDT)
2301 continue;
2302
2303 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2304 if (!udt_or_err) {
2305 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2306 "Failed to deserialize UDTSym record: {0}");
2307 continue;
2308 }
2309 UDTSym udt = std::move(*udt_or_err);
2310 bool is_typedef = true;
2311 if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
2312 CVType cvt = m_index->tpi().getType(udt.Type);
2313 llvm::StringRef name = CVTagRecord::create(cvt).name();
2314 if (name == udt.Name)
2315 is_typedef = false;
2316 }
2317
2318 if (is_typedef)
2319 GetOrCreateTypedef(global);
2320 }
2321
2322 const size_t new_count = GetTypeList().GetSize();
2323
2324 m_done_full_type_scan = true;
2325
2326 return new_count - old_count;
2327}
2328
2329size_t
2331 VariableList &variables) {
2332 PdbSymUid sym_uid(comp_unit.GetID());
2334 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
2335 PdbGlobalSymId global{gid, false};
2336 CVSymbol sym = m_index->ReadSymbolRecord(global);
2337 // TODO: S_CONSTANT is not handled here to prevent a possible crash in
2338 // lldb_private::npdb::MakeConstantLocationExpression when it's a record
2339 // type (e.g. std::strong_ordering::equal). That function needs to be
2340 // updated to handle this case when we add S_CONSTANT case here.
2341 switch (sym.kind()) {
2342 case SymbolKind::S_GDATA32:
2343 case SymbolKind::S_LDATA32:
2344 case SymbolKind::S_GTHREAD32:
2345 case SymbolKind::S_LTHREAD32: {
2346 if (VariableSP var = GetOrCreateGlobalVariable(global))
2347 variables.AddVariable(var);
2348 break;
2349 }
2350 default:
2351 break;
2352 }
2353 }
2354 return variables.GetSize();
2355}
2356
2358 PdbCompilandSymId var_id,
2359 bool is_param,
2360 bool is_constant) {
2361 ModuleSP module = GetObjectFile()->GetModule();
2362 Block *block = GetOrCreateBlock(scope_id);
2363 if (!block)
2364 return nullptr;
2365
2366 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
2367 if (!cii)
2368 return nullptr;
2369 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
2370
2371 VariableInfo var_info;
2372 bool location_is_constant_data = is_constant;
2373
2374 if (is_constant) {
2375 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(var_id.offset);
2376 if (sym.kind() != S_CONSTANT)
2377 return nullptr;
2378 ConstantSym constant(sym.kind());
2379 if (auto err =
2380 SymbolDeserializer::deserializeAs<ConstantSym>(sym, constant)) {
2381 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2382 "Failed to deserialize ConstantSym record: {0}");
2383 return nullptr;
2384 }
2385
2386 var_info.name = constant.Name;
2387 var_info.type = constant.Type;
2388 auto location_or_err = MakeConstantLocationExpression(
2389 constant.Type, m_index->tpi(), constant.Value, module);
2390 if (!location_or_err) {
2391 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), location_or_err.takeError(),
2392 "Failed to make constant location expression for {1}: {0}",
2393 constant.Name);
2394 return nullptr;
2395 }
2396 var_info.location =
2397 DWARFExpressionList(module, std::move(*location_or_err), nullptr);
2398 } else {
2399 // Get function block.
2400 Block *func_block = block;
2401 while (func_block->GetParent())
2402 func_block = func_block->GetParent();
2403
2404 Address addr;
2405 func_block->GetStartAddress(addr);
2406 var_info = GetVariableLocationInfo(*m_index, var_id, *func_block, module);
2407 Function *func = func_block->CalculateSymbolContextFunction();
2408 if (!func)
2409 return nullptr;
2410 // Use empty dwarf expr if optimized away so that it won't be filtered out
2411 // when lookuping local variables in this scope.
2412 if (!var_info.location.IsValid())
2413 var_info.location =
2414 DWARFExpressionList(module, DWARFExpression(), nullptr);
2416 }
2417
2418 TypeSP type_sp = GetOrCreateType(var_info.type);
2419 if (!type_sp)
2420 return nullptr;
2421 std::string name = var_info.name.str();
2422 Declaration decl;
2423 SymbolFileTypeSP sftype =
2424 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
2425
2426 is_param |= var_info.is_param;
2427 ValueType var_scope =
2429 bool external = false;
2430 bool artificial = false;
2431 bool static_member = false;
2432 Variable::RangeList scope_ranges;
2433 VariableSP var_sp = std::make_shared<Variable>(
2434 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope, block,
2435 scope_ranges, &decl, var_info.location, external, artificial,
2436 location_is_constant_data, static_member);
2437 if (!is_param) {
2438 auto ts_or_err = GetTypeSystemForLanguage(comp_unit_sp->GetLanguage());
2439 if (auto err = ts_or_err.takeError())
2440 return nullptr;
2441 auto ts = *ts_or_err;
2442 if (ts) {
2443 if (PdbAstBuilder *ast_builder = ts->GetNativePDBParser())
2444 ast_builder->EnsureVariable(scope_id, var_id);
2445 }
2446 }
2447 m_local_variables[toOpaqueUid(var_id)] = var_sp;
2448 return var_sp;
2449}
2450
2453 PdbCompilandSymId var_id,
2454 bool is_param, bool is_constant) {
2455 auto iter = m_local_variables.find(toOpaqueUid(var_id));
2456 if (iter != m_local_variables.end())
2457 return iter->second;
2458
2459 return CreateLocalVariable(scope_id, var_id, is_param, is_constant);
2460}
2461
2463 CVSymbol sym = m_index->ReadSymbolRecord(id);
2464 lldbassert(sym.kind() == SymbolKind::S_UDT);
2465
2466 auto udt_or_err = SymbolDeserializer::deserializeAs<UDTSym>(sym);
2467 if (!udt_or_err) {
2468 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), udt_or_err.takeError(),
2469 "Failed to deserialize UDTSym record: {0}");
2470 return nullptr;
2471 }
2472 UDTSym udt = std::move(*udt_or_err);
2473
2474 TypeSP target_type = GetOrCreateType(udt.Type);
2475
2477 if (auto err = ts_or_err.takeError())
2478 return nullptr;
2479 auto ts = *ts_or_err;
2480 if (!ts)
2481 return nullptr;
2482 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2483 if (!ast_builder)
2484 return nullptr;
2485 CompilerType ct = ast_builder->GetOrCreateTypedefType(id);
2486 if (!ct)
2487 ct = target_type->GetForwardCompilerType();
2488
2489 Declaration decl;
2490 return MakeType(toOpaqueUid(id), ConstString(udt.Name),
2491 llvm::expectedToOptional(target_type->GetByteSize(nullptr)),
2492 nullptr, target_type->GetID(),
2495}
2496
2498 auto iter = m_types.find(toOpaqueUid(id));
2499 if (iter != m_types.end())
2500 return iter->second;
2501
2502 return CreateTypedef(id);
2503}
2504
2506 Block *block = GetOrCreateBlock(block_id);
2507 if (!block)
2508 return 0;
2509
2510 size_t count = 0;
2511
2512 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
2513 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
2514 uint32_t params_remaining = 0;
2515 switch (sym.kind()) {
2516 case S_GPROC32:
2517 case S_LPROC32: {
2518 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
2519 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym, proc)) {
2520 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2521 "Failed to deserialize ProcSym record: {0}");
2522 return 0;
2523 }
2524 CVType signature = m_index->tpi().getType(proc.FunctionType);
2525 if (signature.kind() == LF_PROCEDURE) {
2526 ProcedureRecord sig;
2527 if (llvm::Error e = TypeDeserializer::deserializeAs<ProcedureRecord>(
2528 signature, sig)) {
2529 llvm::consumeError(std::move(e));
2530 return 0;
2531 }
2532 params_remaining = sig.getParameterCount();
2533 } else if (signature.kind() == LF_MFUNCTION) {
2534 MemberFunctionRecord sig;
2535 if (llvm::Error e = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
2536 signature, sig)) {
2537 llvm::consumeError(std::move(e));
2538 return 0;
2539 }
2540 params_remaining = sig.getParameterCount();
2541 } else
2542 return 0;
2543 break;
2544 }
2545 case S_BLOCK32:
2546 break;
2547 case S_INLINESITE:
2548 break;
2549 default:
2550 lldbassert(false && "Symbol is not a block!");
2551 return 0;
2552 }
2553
2554 VariableListSP variables = block->GetBlockVariableList(false);
2555 if (!variables) {
2556 variables = std::make_shared<VariableList>();
2557 block->SetVariableList(variables);
2558 }
2559
2560 CVSymbolArray syms = limitSymbolArrayToScope(
2561 cii->m_debug_stream.getSymbolArray(), block_id.offset);
2562
2563 // Skip the first record since it's a PROC32 or BLOCK32, and there's
2564 // no point examining it since we know it's not a local variable.
2565 syms.drop_front();
2566 auto iter = syms.begin();
2567 auto end = syms.end();
2568
2569 while (iter != end) {
2570 uint32_t record_offset = iter.offset();
2571 CVSymbol variable_cvs = *iter;
2572 PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
2573 ++iter;
2574
2575 // If this is a block or inline site, recurse into its children and then
2576 // skip it.
2577 if (variable_cvs.kind() == S_BLOCK32 ||
2578 variable_cvs.kind() == S_INLINESITE) {
2579 uint32_t block_end = getScopeEndOffset(variable_cvs);
2580 count += ParseVariablesForBlock(child_sym_id);
2581 iter = syms.at(block_end);
2582 continue;
2583 }
2584
2585 bool is_param = params_remaining > 0;
2586 VariableSP variable;
2587 switch (variable_cvs.kind()) {
2588 case S_REGREL32:
2589 case S_REGREL32_INDIR:
2590 case S_REGISTER:
2591 case S_LOCAL:
2592 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
2593 if (is_param)
2594 --params_remaining;
2595 if (variable)
2596 variables->AddVariableIfUnique(variable);
2597 break;
2598 case S_CONSTANT:
2599 variable = GetOrCreateLocalVariable(block_id, child_sym_id,
2600 /*is_param=*/false,
2601 /*is_constant=*/true);
2602 if (variable)
2603 variables->AddVariableIfUnique(variable);
2604 break;
2605 default:
2606 break;
2607 }
2608 }
2609
2610 // Pass false for set_children, since we call this recursively so that the
2611 // children will call this for themselves.
2612 block->SetDidParseVariables(true, false);
2613
2614 return count;
2615}
2616
2618 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2619 lldbassert(sc.function || sc.comp_unit);
2620
2621 VariableListSP variables;
2622 if (sc.block) {
2623 PdbSymUid block_id(sc.block->GetID());
2624
2625 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2626 return count;
2627 }
2628
2629 if (sc.function) {
2630 PdbSymUid block_id(sc.function->GetID());
2631
2632 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2633 return count;
2634 }
2635
2636 if (sc.comp_unit) {
2637 variables = sc.comp_unit->GetVariableList(false);
2638 if (!variables) {
2639 variables = std::make_shared<VariableList>();
2640 sc.comp_unit->SetVariableList(variables);
2641 }
2642 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
2643 }
2644
2645 llvm_unreachable("Unreachable!");
2646}
2647
2650 if (auto err = ts_or_err.takeError())
2651 return CompilerDecl();
2652 auto ts = *ts_or_err;
2653 if (!ts)
2654 return {};
2655 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2656 if (!ast_builder)
2657 return {};
2658 return ast_builder->GetOrCreateDeclForUid(uid);
2659}
2660
2664 if (auto err = ts_or_err.takeError())
2665 return {};
2666 auto ts = *ts_or_err;
2667 if (!ts)
2668 return {};
2669 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2670 if (!ast_builder)
2671 return {};
2672 return ast_builder->GetOrCreateDeclContextForUid(PdbSymUid(uid));
2673}
2674
2678 if (auto err = ts_or_err.takeError())
2679 return CompilerDeclContext();
2680 auto ts = *ts_or_err;
2681 if (!ts)
2682 return {};
2683 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2684 if (!ast_builder)
2685 return {};
2686 return ast_builder->GetParentDeclContext(PdbSymUid(uid));
2687}
2688
2690 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2691 auto iter = m_types.find(type_uid);
2692 // lldb should not be passing us non-sensical type uids. the only way it
2693 // could have a type uid in the first place is if we handed it out, in which
2694 // case we should know about the type. However, that doesn't mean we've
2695 // instantiated it yet. We can vend out a UID for a future type. So if the
2696 // type doesn't exist, let's instantiate it now.
2697 if (iter != m_types.end())
2698 return &*iter->second;
2699
2700 PdbSymUid uid(type_uid);
2702 PdbTypeSymId type_id = uid.asTypeSym();
2703 if (type_id.index.isNoneType())
2704 return nullptr;
2705
2706 TypeSP type_sp = CreateAndCacheType(type_id);
2707 if (!type_sp)
2708 return nullptr;
2709 return &*type_sp;
2710}
2711
2712std::optional<SymbolFile::ArrayInfo>
2714 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
2715 return std::nullopt;
2716}
2717
2719 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2720 auto ts = compiler_type.GetTypeSystem();
2721 if (!ts)
2722 return false;
2723
2724 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2725 if (!ast_builder)
2726 return false;
2727 return ast_builder->CompleteType(compiler_type);
2728}
2729
2731 TypeClass type_mask,
2732 lldb_private::TypeList &type_list) {}
2733
2736 const CompilerDeclContext &parent_decl_ctx,
2737 bool /* only_root_namespaces */) {
2738 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2740 if (auto err = ts_or_err.takeError())
2741 return {};
2742 auto ts = *ts_or_err;
2743 if (!ts)
2744 return {};
2745 auto *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
2746 if (!clang)
2747 return {};
2748
2749 PdbAstBuilder *ast_builder = clang->GetNativePDBParser();
2750 if (!ast_builder)
2751 return {};
2752
2753 return ast_builder->FindNamespaceDecl(parent_decl_ctx, name.GetStringRef());
2754}
2755
2756llvm::Expected<lldb::TypeSystemSP>
2758 auto type_system_or_err =
2759 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
2760 if (type_system_or_err)
2761 if (auto ts = *type_system_or_err)
2762 ts->SetSymbolFile(this);
2763 return type_system_or_err;
2764}
2765
2766uint64_t SymbolFileNativePDB::GetDebugInfoSize(bool load_all_debug_info) {
2767 // PDB files are a separate file that contains all debug info.
2768 return m_index->pdb().getFileSize();
2769}
2770
2772 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2773
2774 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
2775 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
2776
2777 struct RecordIndices {
2778 TypeIndex forward;
2779 TypeIndex full;
2780 };
2781
2782 llvm::StringMap<RecordIndices> record_indices;
2783
2784 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2785 CVType type = types.getType(*ti);
2786 if (!IsTagRecord(type))
2787 continue;
2788
2789 CVTagRecord tag = CVTagRecord::create(type);
2790
2791 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
2792 if (tag.asTag().isForwardRef()) {
2793 indices.forward = *ti;
2794 } else {
2795 indices.full = *ti;
2796
2797 auto base_name = MSVCUndecoratedNameParser::DropScope(tag.name());
2798 m_type_base_names.Append(ConstString(base_name), ti->getIndex());
2799 }
2800
2801 if (indices.full != TypeIndex::None() &&
2802 indices.forward != TypeIndex::None()) {
2803 forward_to_full[indices.forward] = indices.full;
2804 full_to_forward[indices.full] = indices.forward;
2805 }
2806
2807 // We're looking for LF_NESTTYPE records in the field list, so ignore
2808 // forward references (no field list), and anything without a nested class
2809 // (since there won't be any LF_NESTTYPE records).
2810 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
2811 continue;
2812
2813 struct ProcessTpiStream : public TypeVisitorCallbacks {
2814 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
2815 const CVTagRecord &parent_cvt,
2816 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
2817 : index(index), parents(parents), parent(parent),
2818 parent_cvt(parent_cvt) {}
2819
2820 PdbIndex &index;
2821 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
2822
2823 unsigned unnamed_type_index = 1;
2824 TypeIndex parent;
2825 const CVTagRecord &parent_cvt;
2826
2827 llvm::Error visitKnownMember(CVMemberRecord &CVR,
2828 NestedTypeRecord &Record) override {
2829 std::string unnamed_type_name;
2830 if (Record.Name.empty()) {
2831 unnamed_type_name =
2832 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
2833 Record.Name = unnamed_type_name;
2834 ++unnamed_type_index;
2835 }
2836 std::optional<CVTagRecord> tag =
2837 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
2838 if (!tag)
2839 return llvm::ErrorSuccess();
2840
2841 parents[Record.Type] = parent;
2842 return llvm::ErrorSuccess();
2843 }
2844 };
2845
2846 CVType field_list_cvt = m_index->tpi().getType(tag.asTag().FieldList);
2847 if (field_list_cvt.kind() != LF_FIELDLIST)
2848 continue; // Invalid reference to a field list.
2849
2850 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
2851 FieldListRecord field_list;
2852 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
2853 field_list_cvt, field_list))
2854 llvm::consumeError(std::move(error));
2855 if (llvm::Error error = visitMemberRecordStream(field_list.Data, process))
2856 llvm::consumeError(std::move(error));
2857 }
2858
2859 // After calling Append(), the type-name map needs to be sorted again to be
2860 // able to look up a type by its name.
2861 m_type_base_names.Sort(std::less<uint32_t>());
2862
2863 // Now that we know the forward -> full mapping of all type indices, we can
2864 // re-write all the indices. At the end of this process, we want a mapping
2865 // consisting of fwd -> full and full -> full for all child -> parent indices.
2866 // We can re-write the values in place, but for the keys, we must save them
2867 // off so that we don't modify the map in place while also iterating it.
2868 std::vector<TypeIndex> full_keys;
2869 std::vector<TypeIndex> fwd_keys;
2870 for (auto &entry : m_parent_types) {
2871 TypeIndex key = entry.first;
2872 TypeIndex value = entry.second;
2873
2874 auto iter = forward_to_full.find(value);
2875 if (iter != forward_to_full.end())
2876 entry.second = iter->second;
2877
2878 iter = forward_to_full.find(key);
2879 if (iter != forward_to_full.end())
2880 fwd_keys.push_back(key);
2881 else
2882 full_keys.push_back(key);
2883 }
2884 for (TypeIndex fwd : fwd_keys) {
2885 TypeIndex full = forward_to_full[fwd];
2886 TypeIndex parent_idx = m_parent_types[fwd];
2887 m_parent_types[full] = parent_idx;
2888 }
2889 for (TypeIndex full : full_keys) {
2890 TypeIndex fwd = full_to_forward[full];
2891 m_parent_types[fwd] = m_parent_types[full];
2892 }
2893}
2894
2895std::optional<PdbCompilandSymId>
2897 CVSymbol sym = m_index->ReadSymbolRecord(id);
2898 if (symbolOpensScope(sym.kind())) {
2899 // If this exact symbol opens a scope, we can just directly access its
2900 // parent.
2901 id.offset = getScopeParentOffset(sym);
2902 // Global symbols have parent offset of 0. Return std::nullopt to indicate
2903 // this.
2904 if (id.offset == 0)
2905 return std::nullopt;
2906 return id;
2907 }
2908
2909 // Otherwise we need to start at the beginning and iterate forward until we
2910 // reach (or pass) this particular symbol
2911 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(id.modi);
2912 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
2913
2914 auto begin = syms.begin();
2915 auto end = syms.at(id.offset);
2916 std::vector<PdbCompilandSymId> scope_stack;
2917
2918 while (begin != end) {
2919 if (begin.offset() > id.offset) {
2920 // We passed it. We couldn't even find this symbol record.
2921 lldbassert(false && "Invalid compiland symbol id!");
2922 return std::nullopt;
2923 }
2924
2925 // We haven't found the symbol yet. Check if we need to open or close the
2926 // scope stack.
2927 if (symbolOpensScope(begin->kind())) {
2928 // We can use the end offset of the scope to determine whether or not
2929 // we can just outright skip this entire scope.
2930 uint32_t scope_end = getScopeEndOffset(*begin);
2931 if (scope_end < id.offset) {
2932 begin = syms.at(scope_end);
2933 } else {
2934 // The symbol we're looking for is somewhere in this scope.
2935 scope_stack.emplace_back(id.modi, begin.offset());
2936 }
2937 } else if (symbolEndsScope(begin->kind())) {
2938 scope_stack.pop_back();
2939 }
2940 ++begin;
2941 }
2942 if (scope_stack.empty())
2943 return std::nullopt;
2944 // We have a match! Return the top of the stack
2945 return scope_stack.back();
2946}
2947
2948std::optional<llvm::codeview::TypeIndex>
2949SymbolFileNativePDB::GetParentType(llvm::codeview::TypeIndex ti) {
2950 auto parent_iter = m_parent_types.find(ti);
2951 if (parent_iter == m_parent_types.end())
2952 return std::nullopt;
2953 return parent_iter->second;
2954}
2955
2956std::vector<CompilerContext>
2958 CVType type = m_index->tpi().getType(ti);
2959 if (!IsTagRecord(type))
2960 return {};
2961
2962 CVTagRecord tag = CVTagRecord::create(type);
2963
2964 std::optional<Type::ParsedName> parsed_name =
2966 if (!parsed_name)
2967 return {{tag.contextKind(), ConstString(tag.name())}};
2968
2969 std::vector<CompilerContext> ctx;
2970 // assume everything is a namespace at first
2971 for (llvm::StringRef scope : parsed_name->scope) {
2972 ctx.emplace_back(CompilerContextKind::Namespace, ConstString(scope));
2973 }
2974 // we know the kind of our own type
2975 ctx.emplace_back(tag.contextKind(), ConstString(parsed_name->basename));
2976
2977 // try to find the kind of parents
2978 for (auto &el : llvm::reverse(llvm::drop_end(ctx))) {
2979 std::optional<TypeIndex> parent = GetParentType(ti);
2980 if (!parent)
2981 break;
2982
2983 ti = *parent;
2984 type = m_index->tpi().getType(ti);
2985 switch (type.kind()) {
2986 case LF_CLASS:
2987 case LF_STRUCTURE:
2988 case LF_INTERFACE:
2990 continue;
2991 case LF_UNION:
2993 continue;
2994 case LF_ENUM:
2995 el.kind = CompilerContextKind::Enum;
2996 continue;
2997 default:
2998 break;
2999 }
3000 break;
3001 }
3002 return ctx;
3003}
3004
3005std::optional<llvm::StringRef>
3007 const CompilandIndexItem *cci =
3008 m_index->compilands().GetCompiland(func_id.modi);
3009 if (!cci)
3010 return std::nullopt;
3011
3012 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
3013 if (sym_record.kind() != S_LPROC32 && sym_record.kind() != S_GPROC32)
3014 return std::nullopt;
3015
3016 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
3017 if (auto err = SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)) {
3018 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3019 "Failed to deserialize ProcSym record: {0}");
3020 return std::nullopt;
3021 }
3022
3023 return FindMangledSymbol(SegmentOffset(proc.Segment, proc.CodeOffset),
3024 proc.FunctionType);
3025}
3026
3027std::optional<llvm::StringRef>
3029 TypeIndex function_type) {
3030 auto symbol = m_index->publics().findByAddress(m_index->symrecords(),
3031 so.segment, so.offset);
3032 if (!symbol)
3033 return std::nullopt;
3034
3035 llvm::StringRef name = symbol->first.Name;
3036 // For functions, we might need to strip the mangled name. See
3037 // StripMangledFunctionName for more info.
3038 if (!function_type.isNoneType() &&
3039 (symbol->first.Flags & PublicSymFlags::Function) != PublicSymFlags::None)
3040 name = StripMangledFunctionName(name, function_type);
3041
3042 return name;
3043}
3044
3045llvm::StringRef
3047 PdbTypeSymId func_ty) {
3048 // "In non-64 bit environments" (on x86 in pactice), __cdecl functions get
3049 // prefixed with an underscore. For compilers using LLVM, this happens in LLVM
3050 // (as opposed to the compiler frontend). Because of this, DWARF doesn't
3051 // contain the "full" mangled name in DW_AT_linkage_name for these functions.
3052 // We strip the mangling here for compatibility with DWARF. See
3053 // llvm.org/pr161676 and
3054 // https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names#FormatC
3055
3056 if (!mangled.starts_with('_') ||
3057 m_index->dbi().getMachineType() != PDB_Machine::x86)
3058 return mangled;
3059
3060 CVType cvt = m_index->tpi().getType(func_ty.index);
3061 PDB_CallingConv cc = PDB_CallingConv::NearC;
3062 if (cvt.kind() == LF_PROCEDURE) {
3063 ProcedureRecord proc;
3064 if (llvm::Error error =
3065 TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, proc))
3066 llvm::consumeError(std::move(error));
3067 cc = proc.CallConv;
3068 } else if (cvt.kind() == LF_MFUNCTION) {
3069 MemberFunctionRecord mfunc;
3070 if (llvm::Error error =
3071 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfunc))
3072 llvm::consumeError(std::move(error));
3073 cc = mfunc.CallConv;
3074 } else {
3075 LLDB_LOG(GetLog(LLDBLog::Symbols), "Unexpected function type, got {0}",
3076 cvt.kind());
3077 return mangled;
3078 }
3079
3080 if (cc == PDB_CallingConv::NearC || cc == PDB_CallingConv::FarC)
3081 return mangled.drop_front();
3082
3083 return mangled;
3084}
3085
3087 for (CVType cvt : m_index->ipi().typeArray()) {
3088 switch (cvt.kind()) {
3089 case LF_UDT_SRC_LINE: {
3090 UdtSourceLineRecord udt_src;
3091 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_src)) {
3092 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3093 "Failed to deserialize UdtSourceLineRecord record: {0}");
3094 continue;
3095 }
3096 m_udt_declarations.try_emplace(
3097 udt_src.UDT, UdtDeclaration{/*FileNameIndex=*/udt_src.SourceFile,
3098 /*IsIpiIndex=*/true,
3099 /*Line=*/udt_src.LineNumber});
3100 } break;
3101 case LF_UDT_MOD_SRC_LINE: {
3102 UdtModSourceLineRecord udt_mod_src;
3103 if (auto err = TypeDeserializer::deserializeAs(cvt, udt_mod_src)) {
3105 GetLog(LLDBLog::Symbols), std::move(err),
3106 "Failed to deserialize UdtModSourceLineRecord record: {0}");
3107 continue;
3108 }
3109 // Some types might be contributed by multiple modules. We assume that
3110 // they all point to the same file and line because we can only provide
3111 // one location.
3112 m_udt_declarations.try_emplace(
3113 udt_mod_src.UDT,
3114 UdtDeclaration{/*FileNameIndex=*/udt_mod_src.SourceFile,
3115 /*IsIpiIndex=*/false,
3116 /*Line=*/udt_mod_src.LineNumber});
3117 } break;
3118 default:
3119 break;
3120 }
3121 }
3122}
3123
3124llvm::Expected<Declaration>
3126 std::call_once(m_cached_udt_declarations, [this] { CacheUdtDeclarations(); });
3127
3128 auto it = m_udt_declarations.find(type_id.index);
3129 if (it == m_udt_declarations.end())
3130 return llvm::createStringError("no UDT declaration found");
3131
3132 llvm::StringRef file_name;
3133 if (it->second.IsIpiIndex) {
3134 CVType cvt = m_index->ipi().getType(it->second.FileNameIndex);
3135 if (cvt.kind() != LF_STRING_ID)
3136 return llvm::createStringError("file name was not a LF_STRING_ID");
3137
3138 StringIdRecord sid;
3139 if (auto err = TypeDeserializer::deserializeAs(cvt, sid))
3140 return std::move(err);
3141 file_name = sid.String;
3142 } else {
3143 // The file name index is an index into the string table
3144 auto string_table = m_index->pdb().getStringTable();
3145 if (!string_table)
3146 return string_table.takeError();
3147
3148 llvm::Expected<llvm::StringRef> string =
3149 string_table->getStringTable().getString(
3150 it->second.FileNameIndex.getIndex());
3151 if (!string)
3152 return string.takeError();
3153 file_name = *string;
3154 }
3155
3156 // rustc sets the filename to "<unknown>" for some files
3157 if (file_name == "\\<unknown>")
3158 return Declaration();
3159
3160 return Declaration(FileSpec(file_name), it->second.Line);
3161}
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:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static std::unique_ptr< PDBFile > loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator)
static std::optional< CVTagRecord > GetNestedTagDefinition(const NestedTypeRecord &Record, const CVTagRecord &parent, TpiStream &tpi)
static lldb::LanguageType TranslateLanguage(PDB_Lang lang)
static std::string GetUnqualifiedTypeName(const TagRecord &record)
static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind)
static bool IsClassRecord(TypeLeafKind kind)
static bool IsFunctionEpilogue(const CompilandIndexItem &cci, lldb::addr_t addr)
static bool NeedsResolvedCompileUnit(uint32_t resolve_scope)
static std::optional< std::string > findMatchingPDBFilePath(llvm::StringRef original_pdb_path, llvm::StringRef exe_path)
static bool IsFunctionPrologue(const CompilandIndexItem &cci, lldb::addr_t addr)
static llvm::StringRef DropScope(llvm::StringRef name)
static bool UseNativePDB()
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp: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:382
Block * FindInnermostBlockByOffset(const lldb::addr_t offset)
Definition Block.cpp:127
void SetBlockInfoHasBeenParsed(bool b, bool set_children)
Definition Block.cpp:469
lldb::BlockSP CreateChild(lldb::user_id_t uid)
Creates a block with the specified UID uid.
Definition Block.cpp:370
Function * CalculateSymbolContextFunction() override
Definition Block.cpp:150
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
Definition Block.h:310
Block * GetParent() const
Get the parent block.
Definition Block.cpp:202
bool GetStartAddress(Address &addr)
Definition Block.cpp:317
void SetDidParseVariables(bool b, bool set_children)
Definition Block.cpp:479
A class that describes a compilation unit.
Definition CompileUnit.h:43
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
lldb::VariableListSP GetVariableList(bool can_create)
Get the variable list for a compile unit.
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
void ResolveSymbolContext(const SourceLocationSpec &src_location_spec, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list, RealpathPrefixes *realpath_prefixes=nullptr)
Resolve symbol contexts by file and line.
void SetLineTable(LineTable *line_table)
Set the line table for the compile unit.
void AddFunction(lldb::FunctionSP &function_sp)
Add a function to this compile unit.
size_t GetNumFunctions() const
Returns the number of functions in this compile unit.
lldb::LanguageType GetLanguage()
LineTable * GetLineTable()
Get the line table for the compile unit.
Represents a generic declaration context in a program.
Represents a generic declaration such as a function declaration.
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
"lldb/Expression/DWARFExpressionList.h" Encapsulates a range map from file address range to a single ...
bool IsValid() const
Return true if the location expression contains data.
void SetFuncFileAddress(lldb::addr_t func_file_addr)
"lldb/Expression/DWARFExpression.h" Encapsulates a DWARF location expression and interprets it.
A class to manage flag bits.
Definition Debugger.h:100
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file collection class.
A file utility class.
Definition FileSpec.h:56
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:326
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:317
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:431
llvm::sys::path::Style Style
Definition FileSpec.h:58
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
A class that describes a function.
Definition Function.h:377
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:430
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition Function.cpp:403
static void AppendLineEntryToSequence(Sequence &sequence, lldb::addr_t file_addr, uint32_t line, uint16_t column, uint16_t file_idx, bool is_start_of_statement, bool is_start_of_basic_block, bool is_prologue_end, bool is_epilogue_begin, bool is_terminal_entry)
Definition LineTable.cpp:59
A class that handles mangled names.
Definition Mangled.h:34
static bool IsMangledName(llvm::StringRef name)
Definition Mangled.cpp:39
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
A class that encapsulates name lookup information.
Definition Module.h:935
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:976
ConstString GetLookupName() const
Definition Module.h:974
ConstString GetName() const
Definition Module.h:972
static std::unique_ptr< llvm::pdb::PDBFile > loadPDBFile(std::string PdbPath, llvm::BumpPtrAllocator &Allocator)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
RangeData< lldb::addr_t, uint32_t, std::pair< uint32_t, uint32_t > > Entry
Definition RangeMap.h:462
void Append(const Entry &entry)
Definition RangeMap.h:474
Entry * FindEntryThatContains(B addr)
Definition RangeMap.h:583
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
A stream class that can stream formatted output to a file.
Definition Stream.h:28
A list of support files for a CompileUnit.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
void Append(const FileSpec &file)
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * block
The Block for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override
ObjectFile * GetObjectFile() override
Definition SymbolFile.h:582
virtual TypeList & GetTypeList()
Definition SymbolFile.h:655
lldb::ObjectFileSP m_objfile_sp
Definition SymbolFile.h:658
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
Definition SymbolFile.h:567
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:626
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:230
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:225
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:61
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2901
uint32_t GetSize() const
Definition TypeList.cpp:36
void Insert(const lldb::TypeSP &type)
Definition TypeList.cpp:27
void Insert(const lldb::TypeSP &type)
Definition TypeMap.cpp:27
A class that contains all state required for type lookups.
Definition Type.h:104
ConstString GetTypeBasename() const
Get the type basename to use when searching the type indexes in each SymbolFile object.
Definition Type.cpp:114
bool ContextMatches(llvm::ArrayRef< lldb_private::CompilerContext > context) const
Check of a CompilerContext array from matching type from a symbol file matches the m_context.
Definition Type.cpp:130
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
bool InsertUnique(const lldb::TypeSP &type_sp)
When types that match a TypeQuery are found, this API is used to insert the matching types.
Definition Type.cpp:195
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
Definition Type.cpp:201
bool AlreadySearched(lldb_private::SymbolFile *sym_file)
Check if a SymbolFile object has already been searched by this type match object.
Definition Type.cpp:191
A TypeSystem implementation based on Clang.
Interface for representing a type system.
Definition TypeSystem.h:72
virtual npdb::PdbAstBuilder * GetNativePDBParser()
Definition TypeSystem.h:94
@ eEncodingIsTypedefUID
This type is alias to a type whose UID is m_encoding_uid.
Definition Type.h:434
@ eEncodingIsUID
This type is the type whose UID is m_encoding_uid.
Definition Type.h:423
static std::optional< ParsedName > GetTypeScopeAndBasename(llvm::StringRef name)
Definition Type.cpp:801
void AddVariable(const lldb::VariableSP &var_sp)
RangeVector< lldb::addr_t, lldb::addr_t > RangeList
Definition Variable.h:27
virtual CompilerType GetOrCreateTypedefType(PdbGlobalSymId id)=0
virtual void Dump(Stream &stream, llvm::StringRef filter, bool show_color)=0
virtual CompilerDeclContext FindNamespaceDecl(CompilerDeclContext parent_ctx, llvm::StringRef name)=0
virtual bool CompleteType(CompilerType ct)=0
virtual void EnsureBlock(PdbCompilandSymId block_id)=0
virtual CompilerDeclContext GetParentDeclContext(PdbSymUid uid)=0
virtual CompilerType GetOrCreateType(PdbTypeSymId type)=0
virtual CompilerDecl GetOrCreateDeclForUid(PdbSymUid uid)=0
virtual void EnsureInlinedFunction(PdbCompilandSymId inlinesite_id)=0
virtual void ParseDeclsForContext(CompilerDeclContext context)=0
virtual CompilerDeclContext GetOrCreateDeclContextForUid(PdbSymUid uid)=0
PdbIndex - Lazy access to the important parts of a PDB file.
Definition PdbIndex.h:47
static llvm::Expected< std::unique_ptr< PdbIndex > > create(llvm::pdb::PDBFile *)
Definition PdbIndex.cpp: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:111
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:338
std::shared_ptr< lldb_private::Function > FunctionSP
std::shared_ptr< lldb_private::Block > BlockSP
std::shared_ptr< lldb_private::ObjectFile > ObjectFileSP
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeRust
Rust.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeSwift
Swift.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::Type > TypeSP
SymbolType
Symbol types.
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::SymbolFileType > SymbolFileTypeSP
std::shared_ptr< lldb_private::Variable > VariableSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
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:73
DWARFExpressionList location
Definition PdbUtil.h:115
llvm::codeview::TypeIndex type
Definition PdbUtil.h:114