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