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
9 #include "SymbolFileNativePDB.h"
10
11 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
12 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
13 #include "Plugins/ObjectFile/PDB/ObjectFilePDB.h"
14 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/StreamBuffer.h"
18 #include "lldb/Core/StreamFile.h"
19 #include "lldb/Symbol/CompileUnit.h"
20 #include "lldb/Symbol/LineTable.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/SymbolVendor.h"
24 #include "lldb/Symbol/Variable.h"
25 #include "lldb/Symbol/VariableList.h"
26 #include "lldb/Utility/LLDBLog.h"
27 #include "lldb/Utility/Log.h"
28
29 #include "llvm/DebugInfo/CodeView/CVRecord.h"
30 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
31 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
32 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
33 #include "llvm/DebugInfo/CodeView/RecordName.h"
34 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
35 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
36 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
37 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
38 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
39 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
40 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
41 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
43 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
44 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45 #include "llvm/DebugInfo/PDB/PDB.h"
46 #include "llvm/DebugInfo/PDB/PDBTypes.h"
47 #include "llvm/Demangle/MicrosoftDemangle.h"
48 #include "llvm/Object/COFF.h"
49 #include "llvm/Support/Allocator.h"
50 #include "llvm/Support/BinaryStreamReader.h"
51 #include "llvm/Support/Error.h"
52 #include "llvm/Support/ErrorOr.h"
53 #include "llvm/Support/MemoryBuffer.h"
54
55 #include "DWARFLocationExpression.h"
56 #include "PdbSymUid.h"
57 #include "PdbUtil.h"
58 #include "UdtRecordCompleter.h"
59 #include <optional>
60
61 using namespace lldb;
62 using namespace lldb_private;
63 using namespace npdb;
64 using namespace llvm::codeview;
65 using namespace llvm::pdb;
66
67 char SymbolFileNativePDB::ID;
68
TranslateLanguage(PDB_Lang lang)69 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
70 switch (lang) {
71 case PDB_Lang::Cpp:
72 return lldb::LanguageType::eLanguageTypeC_plus_plus;
73 case PDB_Lang::C:
74 return lldb::LanguageType::eLanguageTypeC;
75 case PDB_Lang::Swift:
76 return lldb::LanguageType::eLanguageTypeSwift;
77 case PDB_Lang::Rust:
78 return lldb::LanguageType::eLanguageTypeRust;
79 default:
80 return lldb::LanguageType::eLanguageTypeUnknown;
81 }
82 }
83
84 static std::unique_ptr<PDBFile>
loadMatchingPDBFile(std::string exe_path,llvm::BumpPtrAllocator & allocator)85 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
86 // Try to find a matching PDB for an EXE.
87 using namespace llvm::object;
88 auto expected_binary = createBinary(exe_path);
89
90 // If the file isn't a PE/COFF executable, fail.
91 if (!expected_binary) {
92 llvm::consumeError(expected_binary.takeError());
93 return nullptr;
94 }
95 OwningBinary<Binary> binary = std::move(*expected_binary);
96
97 // TODO: Avoid opening the PE/COFF binary twice by reading this information
98 // directly from the lldb_private::ObjectFile.
99 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
100 if (!obj)
101 return nullptr;
102 const llvm::codeview::DebugInfo *pdb_info = nullptr;
103
104 // If it doesn't have a debug directory, fail.
105 llvm::StringRef pdb_file;
106 if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) {
107 consumeError(std::move(e));
108 return nullptr;
109 }
110
111 // If the file doesn't exist, perhaps the path specified at build time
112 // doesn't match the PDB's current location, so check the location of the
113 // executable.
114 if (!FileSystem::Instance().Exists(pdb_file)) {
115 const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent();
116 const auto pdb_name = FileSpec(pdb_file).GetFilename().GetCString();
117 pdb_file = exe_dir.CopyByAppendingPathComponent(pdb_name).GetPathAsConstString().GetStringRef();
118 }
119
120 // If the file is not a PDB or if it doesn't have a matching GUID, fail.
121 auto pdb = ObjectFilePDB::loadPDBFile(std::string(pdb_file), allocator);
122 if (!pdb)
123 return nullptr;
124
125 auto expected_info = pdb->getPDBInfoStream();
126 if (!expected_info) {
127 llvm::consumeError(expected_info.takeError());
128 return nullptr;
129 }
130 llvm::codeview::GUID guid;
131 memcpy(&guid, pdb_info->PDB70.Signature, 16);
132
133 if (expected_info->getGuid() != guid)
134 return nullptr;
135 return pdb;
136 }
137
IsFunctionPrologue(const CompilandIndexItem & cci,lldb::addr_t addr)138 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
139 lldb::addr_t addr) {
140 // FIXME: Implement this.
141 return false;
142 }
143
IsFunctionEpilogue(const CompilandIndexItem & cci,lldb::addr_t addr)144 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
145 lldb::addr_t addr) {
146 // FIXME: Implement this.
147 return false;
148 }
149
GetSimpleTypeName(SimpleTypeKind kind)150 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
151 switch (kind) {
152 case SimpleTypeKind::Boolean128:
153 case SimpleTypeKind::Boolean16:
154 case SimpleTypeKind::Boolean32:
155 case SimpleTypeKind::Boolean64:
156 case SimpleTypeKind::Boolean8:
157 return "bool";
158 case SimpleTypeKind::Byte:
159 case SimpleTypeKind::UnsignedCharacter:
160 return "unsigned char";
161 case SimpleTypeKind::NarrowCharacter:
162 return "char";
163 case SimpleTypeKind::SignedCharacter:
164 case SimpleTypeKind::SByte:
165 return "signed char";
166 case SimpleTypeKind::Character16:
167 return "char16_t";
168 case SimpleTypeKind::Character32:
169 return "char32_t";
170 case SimpleTypeKind::Character8:
171 return "char8_t";
172 case SimpleTypeKind::Complex80:
173 case SimpleTypeKind::Complex64:
174 case SimpleTypeKind::Complex32:
175 return "complex";
176 case SimpleTypeKind::Float128:
177 case SimpleTypeKind::Float80:
178 return "long double";
179 case SimpleTypeKind::Float64:
180 return "double";
181 case SimpleTypeKind::Float32:
182 return "float";
183 case SimpleTypeKind::Float16:
184 return "single";
185 case SimpleTypeKind::Int128:
186 return "__int128";
187 case SimpleTypeKind::Int64:
188 case SimpleTypeKind::Int64Quad:
189 return "int64_t";
190 case SimpleTypeKind::Int32:
191 return "int";
192 case SimpleTypeKind::Int16:
193 return "short";
194 case SimpleTypeKind::UInt128:
195 return "unsigned __int128";
196 case SimpleTypeKind::UInt64:
197 case SimpleTypeKind::UInt64Quad:
198 return "uint64_t";
199 case SimpleTypeKind::HResult:
200 return "HRESULT";
201 case SimpleTypeKind::UInt32:
202 return "unsigned";
203 case SimpleTypeKind::UInt16:
204 case SimpleTypeKind::UInt16Short:
205 return "unsigned short";
206 case SimpleTypeKind::Int32Long:
207 return "long";
208 case SimpleTypeKind::UInt32Long:
209 return "unsigned long";
210 case SimpleTypeKind::Void:
211 return "void";
212 case SimpleTypeKind::WideCharacter:
213 return "wchar_t";
214 default:
215 return "";
216 }
217 }
218
IsClassRecord(TypeLeafKind kind)219 static bool IsClassRecord(TypeLeafKind kind) {
220 switch (kind) {
221 case LF_STRUCTURE:
222 case LF_CLASS:
223 case LF_INTERFACE:
224 return true;
225 default:
226 return false;
227 }
228 }
229
230 static std::optional<CVTagRecord>
GetNestedTagDefinition(const NestedTypeRecord & Record,const CVTagRecord & parent,TpiStream & tpi)231 GetNestedTagDefinition(const NestedTypeRecord &Record,
232 const CVTagRecord &parent, TpiStream &tpi) {
233 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
234 // is also used to indicate the primary definition of a nested class. That is
235 // to say, if you have:
236 // struct A {
237 // struct B {};
238 // using C = B;
239 // };
240 // Then in the debug info, this will appear as:
241 // LF_STRUCTURE `A::B` [type index = N]
242 // LF_STRUCTURE `A`
243 // LF_NESTTYPE [name = `B`, index = N]
244 // LF_NESTTYPE [name = `C`, index = N]
245 // In order to accurately reconstruct the decl context hierarchy, we need to
246 // know which ones are actual definitions and which ones are just aliases.
247
248 // If it's a simple type, then this is something like `using foo = int`.
249 if (Record.Type.isSimple())
250 return std::nullopt;
251
252 CVType cvt = tpi.getType(Record.Type);
253
254 if (!IsTagRecord(cvt))
255 return std::nullopt;
256
257 // If it's an inner definition, then treat whatever name we have here as a
258 // single component of a mangled name. So we can inject it into the parent's
259 // mangled name to see if it matches.
260 CVTagRecord child = CVTagRecord::create(cvt);
261 std::string qname = std::string(parent.asTag().getUniqueName());
262 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
263 return std::nullopt;
264
265 // qname[3] is the tag type identifier (struct, class, union, etc). Since the
266 // inner tag type is not necessarily the same as the outer tag type, re-write
267 // it to match the inner tag type.
268 qname[3] = child.asTag().getUniqueName()[3];
269 std::string piece;
270 if (qname[3] == 'W')
271 piece = "4";
272 piece += Record.Name;
273 piece.push_back('@');
274 qname.insert(4, std::move(piece));
275 if (qname != child.asTag().UniqueName)
276 return std::nullopt;
277
278 return std::move(child);
279 }
280
Initialize()281 void SymbolFileNativePDB::Initialize() {
282 PluginManager::RegisterPlugin(GetPluginNameStatic(),
283 GetPluginDescriptionStatic(), CreateInstance,
284 DebuggerInitialize);
285 }
286
Terminate()287 void SymbolFileNativePDB::Terminate() {
288 PluginManager::UnregisterPlugin(CreateInstance);
289 }
290
DebuggerInitialize(Debugger & debugger)291 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
292
GetPluginDescriptionStatic()293 llvm::StringRef SymbolFileNativePDB::GetPluginDescriptionStatic() {
294 return "Microsoft PDB debug symbol cross-platform file reader.";
295 }
296
CreateInstance(ObjectFileSP objfile_sp)297 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) {
298 return new SymbolFileNativePDB(std::move(objfile_sp));
299 }
300
SymbolFileNativePDB(ObjectFileSP objfile_sp)301 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp)
302 : SymbolFileCommon(std::move(objfile_sp)) {}
303
304 SymbolFileNativePDB::~SymbolFileNativePDB() = default;
305
CalculateAbilities()306 uint32_t SymbolFileNativePDB::CalculateAbilities() {
307 uint32_t abilities = 0;
308 if (!m_objfile_sp)
309 return 0;
310
311 if (!m_index) {
312 // Lazily load and match the PDB file, but only do this once.
313 PDBFile *pdb_file;
314 if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) {
315 pdb_file = &pdb->GetPDBFile();
316 } else {
317 m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(),
318 m_allocator);
319 pdb_file = m_file_up.get();
320 }
321
322 if (!pdb_file)
323 return 0;
324
325 auto expected_index = PdbIndex::create(pdb_file);
326 if (!expected_index) {
327 llvm::consumeError(expected_index.takeError());
328 return 0;
329 }
330 m_index = std::move(*expected_index);
331 }
332 if (!m_index)
333 return 0;
334
335 // We don't especially have to be precise here. We only distinguish between
336 // stripped and not stripped.
337 abilities = kAllAbilities;
338
339 if (m_index->dbi().isStripped())
340 abilities &= ~(Blocks | LocalVariables);
341 return abilities;
342 }
343
InitializeObject()344 void SymbolFileNativePDB::InitializeObject() {
345 m_obj_load_address = m_objfile_sp->GetModule()
346 ->GetObjectFile()
347 ->GetBaseAddress()
348 .GetFileAddress();
349 m_index->SetLoadAddress(m_obj_load_address);
350 m_index->ParseSectionContribs();
351
352 auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
353 lldb::eLanguageTypeC_plus_plus);
354 if (auto err = ts_or_err.takeError()) {
355 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
356 "Failed to initialize");
357 } else {
358 if (auto ts = *ts_or_err)
359 ts->SetSymbolFile(this);
360 BuildParentMap();
361 }
362 }
363
CalculateNumCompileUnits()364 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() {
365 const DbiModuleList &modules = m_index->dbi().modules();
366 uint32_t count = modules.getModuleCount();
367 if (count == 0)
368 return count;
369
370 // The linker can inject an additional "dummy" compilation unit into the
371 // PDB. Ignore this special compile unit for our purposes, if it is there.
372 // It is always the last one.
373 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
374 if (last.getModuleName() == "* Linker *")
375 --count;
376 return count;
377 }
378
CreateBlock(PdbCompilandSymId block_id)379 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
380 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
381 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
382 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
383 lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
384 BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
385 auto ts_or_err = GetTypeSystemForLanguage(comp_unit->GetLanguage());
386 if (auto err = ts_or_err.takeError())
387 return *child_block;
388 auto ts = *ts_or_err;
389 if (!ts)
390 return *child_block;
391 PdbAstBuilder* ast_builder = ts->GetNativePDBParser();
392
393 switch (sym.kind()) {
394 case S_GPROC32:
395 case S_LPROC32: {
396 // This is a function. It must be global. Creating the Function entry
397 // for it automatically creates a block for it.
398 FunctionSP func = GetOrCreateFunction(block_id, *comp_unit);
399 if (func) {
400 Block &block = func->GetBlock(false);
401 if (block.GetNumRanges() == 0)
402 block.AddRange(Block::Range(0, func->GetAddressRange().GetByteSize()));
403 return block;
404 }
405 break;
406 }
407 case S_BLOCK32: {
408 // This is a block. Its parent is either a function or another block. In
409 // either case, its parent can be viewed as a block (e.g. a function
410 // contains 1 big block. So just get the parent block and add this block
411 // to it.
412 BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
413 cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
414 lldbassert(block.Parent != 0);
415 PdbCompilandSymId parent_id(block_id.modi, block.Parent);
416 Block &parent_block = GetOrCreateBlock(parent_id);
417 Function *func = parent_block.CalculateSymbolContextFunction();
418 lldbassert(func);
419 lldb::addr_t block_base =
420 m_index->MakeVirtualAddress(block.Segment, block.CodeOffset);
421 lldb::addr_t func_base =
422 func->GetAddressRange().GetBaseAddress().GetFileAddress();
423 if (block_base >= func_base)
424 child_block->AddRange(Block::Range(block_base - func_base, block.CodeSize));
425 else {
426 GetObjectFile()->GetModule()->ReportError(
427 "S_BLOCK32 at modi: {0:d} offset: {1:d}: adding range "
428 "[{2:x16}-{3:x16}) which has a base that is less than the "
429 "function's "
430 "low PC 0x%" PRIx64 ". Please file a bug and attach the file at the "
431 "start of this error message",
432 block_id.modi, block_id.offset, block_base,
433 block_base + block.CodeSize, func_base);
434 }
435 parent_block.AddChild(child_block);
436 ast_builder->GetOrCreateBlockDecl(block_id);
437 m_blocks.insert({opaque_block_uid, child_block});
438 break;
439 }
440 case S_INLINESITE: {
441 // This ensures line table is parsed first so we have inline sites info.
442 comp_unit->GetLineTable();
443
444 std::shared_ptr<InlineSite> inline_site = m_inline_sites[opaque_block_uid];
445 Block &parent_block = GetOrCreateBlock(inline_site->parent_id);
446 parent_block.AddChild(child_block);
447 ast_builder->GetOrCreateInlinedFunctionDecl(block_id);
448 // Copy ranges from InlineSite to Block.
449 for (size_t i = 0; i < inline_site->ranges.GetSize(); ++i) {
450 auto *entry = inline_site->ranges.GetEntryAtIndex(i);
451 child_block->AddRange(
452 Block::Range(entry->GetRangeBase(), entry->GetByteSize()));
453 }
454 child_block->FinalizeRanges();
455
456 // Get the inlined function callsite info.
457 Declaration &decl = inline_site->inline_function_info->GetDeclaration();
458 Declaration &callsite = inline_site->inline_function_info->GetCallSite();
459 child_block->SetInlinedFunctionInfo(
460 inline_site->inline_function_info->GetName().GetCString(), nullptr,
461 &decl, &callsite);
462 m_blocks.insert({opaque_block_uid, child_block});
463 break;
464 }
465 default:
466 lldbassert(false && "Symbol is not a block!");
467 }
468
469 return *child_block;
470 }
471
CreateFunction(PdbCompilandSymId func_id,CompileUnit & comp_unit)472 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
473 CompileUnit &comp_unit) {
474 const CompilandIndexItem *cci =
475 m_index->compilands().GetCompiland(func_id.modi);
476 lldbassert(cci);
477 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
478
479 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
480 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
481
482 auto file_vm_addr =
483 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
484 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
485 return nullptr;
486
487 AddressRange func_range(file_vm_addr, sol.length,
488 comp_unit.GetModule()->GetSectionList());
489 if (!func_range.GetBaseAddress().IsValid())
490 return nullptr;
491
492 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
493 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
494 if (proc.FunctionType == TypeIndex::None())
495 return nullptr;
496 TypeSP func_type = GetOrCreateType(proc.FunctionType);
497 if (!func_type)
498 return nullptr;
499
500 PdbTypeSymId sig_id(proc.FunctionType, false);
501 Mangled mangled(proc.Name);
502 FunctionSP func_sp = std::make_shared<Function>(
503 &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
504 func_type.get(), func_range);
505
506 comp_unit.AddFunction(func_sp);
507
508 auto ts_or_err = GetTypeSystemForLanguage(comp_unit.GetLanguage());
509 if (auto err = ts_or_err.takeError())
510 return func_sp;
511 auto ts = *ts_or_err;
512 if (!ts)
513 return func_sp;
514 ts->GetNativePDBParser()->GetOrCreateFunctionDecl(func_id);
515
516 return func_sp;
517 }
518
519 CompUnitSP
CreateCompileUnit(const CompilandIndexItem & cci)520 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
521 lldb::LanguageType lang =
522 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
523 : lldb::eLanguageTypeUnknown;
524
525 LazyBool optimized = eLazyBoolNo;
526 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
527 optimized = eLazyBoolYes;
528
529 llvm::SmallString<64> source_file_name =
530 m_index->compilands().GetMainSourceFile(cci);
531 FileSpec fs(llvm::sys::path::convert_to_slash(
532 source_file_name, llvm::sys::path::Style::windows_backslash));
533
534 CompUnitSP cu_sp =
535 std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs,
536 toOpaqueUid(cci.m_id), lang, optimized);
537
538 SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
539 return cu_sp;
540 }
541
CreateModifierType(PdbTypeSymId type_id,const ModifierRecord & mr,CompilerType ct)542 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
543 const ModifierRecord &mr,
544 CompilerType ct) {
545 TpiStream &stream = m_index->tpi();
546
547 std::string name;
548 if (mr.ModifiedType.isSimple())
549 name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind()));
550 else
551 name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
552 Declaration decl;
553 lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
554
555 return MakeType(toOpaqueUid(type_id), ConstString(name),
556 modified_type->GetByteSize(nullptr), nullptr,
557 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
558 Type::ResolveState::Full);
559 }
560
561 lldb::TypeSP
CreatePointerType(PdbTypeSymId type_id,const llvm::codeview::PointerRecord & pr,CompilerType ct)562 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id,
563 const llvm::codeview::PointerRecord &pr,
564 CompilerType ct) {
565 TypeSP pointee = GetOrCreateType(pr.ReferentType);
566 if (!pointee)
567 return nullptr;
568
569 if (pr.isPointerToMember()) {
570 MemberPointerInfo mpi = pr.getMemberInfo();
571 GetOrCreateType(mpi.ContainingType);
572 }
573
574 Declaration decl;
575 return MakeType(toOpaqueUid(type_id), ConstString(), pr.getSize(), nullptr,
576 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
577 Type::ResolveState::Full);
578 }
579
CreateSimpleType(TypeIndex ti,CompilerType ct)580 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti,
581 CompilerType ct) {
582 uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
583 if (ti == TypeIndex::NullptrT()) {
584 Declaration decl;
585 return MakeType(uid, ConstString("std::nullptr_t"), 0, nullptr,
586 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
587 Type::ResolveState::Full);
588 }
589
590 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
591 TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
592 uint32_t pointer_size = 0;
593 switch (ti.getSimpleMode()) {
594 case SimpleTypeMode::FarPointer32:
595 case SimpleTypeMode::NearPointer32:
596 pointer_size = 4;
597 break;
598 case SimpleTypeMode::NearPointer64:
599 pointer_size = 8;
600 break;
601 default:
602 // 128-bit and 16-bit pointers unsupported.
603 return nullptr;
604 }
605 Declaration decl;
606 return MakeType(uid, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
607 Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
608 }
609
610 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
611 return nullptr;
612
613 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
614 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
615
616 Declaration decl;
617 return MakeType(uid, ConstString(type_name), size, nullptr, LLDB_INVALID_UID,
618 Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
619 }
620
GetUnqualifiedTypeName(const TagRecord & record)621 static std::string GetUnqualifiedTypeName(const TagRecord &record) {
622 if (!record.hasUniqueName()) {
623 MSVCUndecoratedNameParser parser(record.Name);
624 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
625
626 return std::string(specs.back().GetBaseName());
627 }
628
629 llvm::ms_demangle::Demangler demangler;
630 StringView sv(record.UniqueName.begin(), record.UniqueName.size());
631 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
632 if (demangler.Error)
633 return std::string(record.Name);
634
635 llvm::ms_demangle::IdentifierNode *idn =
636 ttn->QualifiedName->getUnqualifiedIdentifier();
637 return idn->toString();
638 }
639
640 lldb::TypeSP
CreateClassStructUnion(PdbTypeSymId type_id,const TagRecord & record,size_t size,CompilerType ct)641 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id,
642 const TagRecord &record,
643 size_t size, CompilerType ct) {
644
645 std::string uname = GetUnqualifiedTypeName(record);
646
647 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
648 Declaration decl;
649 return MakeType(toOpaqueUid(type_id), ConstString(uname), size, nullptr,
650 LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
651 Type::ResolveState::Forward);
652 }
653
CreateTagType(PdbTypeSymId type_id,const ClassRecord & cr,CompilerType ct)654 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
655 const ClassRecord &cr,
656 CompilerType ct) {
657 return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
658 }
659
CreateTagType(PdbTypeSymId type_id,const UnionRecord & ur,CompilerType ct)660 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
661 const UnionRecord &ur,
662 CompilerType ct) {
663 return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
664 }
665
CreateTagType(PdbTypeSymId type_id,const EnumRecord & er,CompilerType ct)666 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
667 const EnumRecord &er,
668 CompilerType ct) {
669 std::string uname = GetUnqualifiedTypeName(er);
670
671 Declaration decl;
672 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
673
674 return MakeType(toOpaqueUid(type_id), ConstString(uname),
675 underlying_type->GetByteSize(nullptr), nullptr,
676 LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
677 ct, lldb_private::Type::ResolveState::Forward);
678 }
679
CreateArrayType(PdbTypeSymId type_id,const ArrayRecord & ar,CompilerType ct)680 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
681 const ArrayRecord &ar,
682 CompilerType ct) {
683 TypeSP element_type = GetOrCreateType(ar.ElementType);
684
685 Declaration decl;
686 TypeSP array_sp =
687 MakeType(toOpaqueUid(type_id), ConstString(), ar.Size, nullptr,
688 LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct,
689 lldb_private::Type::ResolveState::Full);
690 array_sp->SetEncodingType(element_type.get());
691 return array_sp;
692 }
693
CreateFunctionType(PdbTypeSymId type_id,const MemberFunctionRecord & mfr,CompilerType ct)694 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id,
695 const MemberFunctionRecord &mfr,
696 CompilerType ct) {
697 Declaration decl;
698 return MakeType(toOpaqueUid(type_id), ConstString(), 0, nullptr,
699 LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
700 ct, lldb_private::Type::ResolveState::Full);
701 }
702
CreateProcedureType(PdbTypeSymId type_id,const ProcedureRecord & pr,CompilerType ct)703 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
704 const ProcedureRecord &pr,
705 CompilerType ct) {
706 Declaration decl;
707 return MakeType(toOpaqueUid(type_id), ConstString(), 0, nullptr,
708 LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
709 ct, lldb_private::Type::ResolveState::Full);
710 }
711
CreateType(PdbTypeSymId type_id,CompilerType ct)712 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) {
713 if (type_id.index.isSimple())
714 return CreateSimpleType(type_id.index, ct);
715
716 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
717 CVType cvt = stream.getType(type_id.index);
718
719 if (cvt.kind() == LF_MODIFIER) {
720 ModifierRecord modifier;
721 llvm::cantFail(
722 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
723 return CreateModifierType(type_id, modifier, ct);
724 }
725
726 if (cvt.kind() == LF_POINTER) {
727 PointerRecord pointer;
728 llvm::cantFail(
729 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
730 return CreatePointerType(type_id, pointer, ct);
731 }
732
733 if (IsClassRecord(cvt.kind())) {
734 ClassRecord cr;
735 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
736 return CreateTagType(type_id, cr, ct);
737 }
738
739 if (cvt.kind() == LF_ENUM) {
740 EnumRecord er;
741 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
742 return CreateTagType(type_id, er, ct);
743 }
744
745 if (cvt.kind() == LF_UNION) {
746 UnionRecord ur;
747 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
748 return CreateTagType(type_id, ur, ct);
749 }
750
751 if (cvt.kind() == LF_ARRAY) {
752 ArrayRecord ar;
753 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
754 return CreateArrayType(type_id, ar, ct);
755 }
756
757 if (cvt.kind() == LF_PROCEDURE) {
758 ProcedureRecord pr;
759 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
760 return CreateProcedureType(type_id, pr, ct);
761 }
762 if (cvt.kind() == LF_MFUNCTION) {
763 MemberFunctionRecord mfr;
764 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
765 return CreateFunctionType(type_id, mfr, ct);
766 }
767
768 return nullptr;
769 }
770
CreateAndCacheType(PdbTypeSymId type_id)771 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
772 // If they search for a UDT which is a forward ref, try and resolve the full
773 // decl and just map the forward ref uid to the full decl record.
774 std::optional<PdbTypeSymId> full_decl_uid;
775 if (IsForwardRefUdt(type_id, m_index->tpi())) {
776 auto expected_full_ti =
777 m_index->tpi().findFullDeclForForwardRef(type_id.index);
778 if (!expected_full_ti)
779 llvm::consumeError(expected_full_ti.takeError());
780 else if (*expected_full_ti != type_id.index) {
781 full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
782
783 // It's possible that a lookup would occur for the full decl causing it
784 // to be cached, then a second lookup would occur for the forward decl.
785 // We don't want to create a second full decl, so make sure the full
786 // decl hasn't already been cached.
787 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
788 if (full_iter != m_types.end()) {
789 TypeSP result = full_iter->second;
790 // Map the forward decl to the TypeSP for the full decl so we can take
791 // the fast path next time.
792 m_types[toOpaqueUid(type_id)] = result;
793 return result;
794 }
795 }
796 }
797
798 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
799 auto ts_or_err = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
800 if (auto err = ts_or_err.takeError())
801 return nullptr;
802 auto ts = *ts_or_err;
803 if (!ts)
804 return nullptr;
805
806 PdbAstBuilder* ast_builder = ts->GetNativePDBParser();
807 clang::QualType qt = ast_builder->GetOrCreateType(best_decl_id);
808 if (qt.isNull())
809 return nullptr;
810
811 TypeSP result = CreateType(best_decl_id, ast_builder->ToCompilerType(qt));
812 if (!result)
813 return nullptr;
814
815 uint64_t best_uid = toOpaqueUid(best_decl_id);
816 m_types[best_uid] = result;
817 // If we had both a forward decl and a full decl, make both point to the new
818 // type.
819 if (full_decl_uid)
820 m_types[toOpaqueUid(type_id)] = result;
821
822 return result;
823 }
824
GetOrCreateType(PdbTypeSymId type_id)825 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
826 // We can't use try_emplace / overwrite here because the process of creating
827 // a type could create nested types, which could invalidate iterators. So
828 // we have to do a 2-phase lookup / insert.
829 auto iter = m_types.find(toOpaqueUid(type_id));
830 if (iter != m_types.end())
831 return iter->second;
832
833 TypeSP type = CreateAndCacheType(type_id);
834 if (type)
835 GetTypeList().Insert(type);
836 return type;
837 }
838
CreateGlobalVariable(PdbGlobalSymId var_id)839 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
840 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
841 if (sym.kind() == S_CONSTANT)
842 return CreateConstantSymbol(var_id, sym);
843
844 lldb::ValueType scope = eValueTypeInvalid;
845 TypeIndex ti;
846 llvm::StringRef name;
847 lldb::addr_t addr = 0;
848 uint16_t section = 0;
849 uint32_t offset = 0;
850 bool is_external = false;
851 switch (sym.kind()) {
852 case S_GDATA32:
853 is_external = true;
854 [[fallthrough]];
855 case S_LDATA32: {
856 DataSym ds(sym.kind());
857 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
858 ti = ds.Type;
859 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
860 : eValueTypeVariableStatic;
861 name = ds.Name;
862 section = ds.Segment;
863 offset = ds.DataOffset;
864 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
865 break;
866 }
867 case S_GTHREAD32:
868 is_external = true;
869 [[fallthrough]];
870 case S_LTHREAD32: {
871 ThreadLocalDataSym tlds(sym.kind());
872 llvm::cantFail(
873 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
874 ti = tlds.Type;
875 name = tlds.Name;
876 section = tlds.Segment;
877 offset = tlds.DataOffset;
878 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
879 scope = eValueTypeVariableThreadLocal;
880 break;
881 }
882 default:
883 llvm_unreachable("unreachable!");
884 }
885
886 CompUnitSP comp_unit;
887 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
888 if (!modi) {
889 return nullptr;
890 }
891
892 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
893 comp_unit = GetOrCreateCompileUnit(cci);
894
895 Declaration decl;
896 PdbTypeSymId tid(ti, false);
897 SymbolFileTypeSP type_sp =
898 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
899 Variable::RangeList ranges;
900 auto ts_or_err = GetTypeSystemForLanguage(comp_unit->GetLanguage());
901 if (auto err = ts_or_err.takeError())
902 return nullptr;
903 auto ts = *ts_or_err;
904 if (!ts)
905 return nullptr;
906
907 ts->GetNativePDBParser()->GetOrCreateVariableDecl(var_id);
908
909 ModuleSP module_sp = GetObjectFile()->GetModule();
910 DWARFExpressionList location(
911 module_sp, MakeGlobalLocationExpression(section, offset, module_sp),
912 nullptr);
913
914 std::string global_name("::");
915 global_name += name;
916 bool artificial = false;
917 bool location_is_constant_data = false;
918 bool static_member = false;
919 VariableSP var_sp = std::make_shared<Variable>(
920 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
921 scope, comp_unit.get(), ranges, &decl, location, is_external, artificial,
922 location_is_constant_data, static_member);
923
924 return var_sp;
925 }
926
927 lldb::VariableSP
CreateConstantSymbol(PdbGlobalSymId var_id,const CVSymbol & cvs)928 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
929 const CVSymbol &cvs) {
930 TpiStream &tpi = m_index->tpi();
931 ConstantSym constant(cvs.kind());
932
933 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
934 std::string global_name("::");
935 global_name += constant.Name;
936 PdbTypeSymId tid(constant.Type, false);
937 SymbolFileTypeSP type_sp =
938 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
939
940 Declaration decl;
941 Variable::RangeList ranges;
942 ModuleSP module = GetObjectFile()->GetModule();
943 DWARFExpressionList location(module,
944 MakeConstantLocationExpression(
945 constant.Type, tpi, constant.Value, module),
946 nullptr);
947
948 bool external = false;
949 bool artificial = false;
950 bool location_is_constant_data = true;
951 bool static_member = false;
952 VariableSP var_sp = std::make_shared<Variable>(
953 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
954 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
955 external, artificial, location_is_constant_data, static_member);
956 return var_sp;
957 }
958
959 VariableSP
GetOrCreateGlobalVariable(PdbGlobalSymId var_id)960 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
961 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
962 if (emplace_result.second) {
963 if (VariableSP var_sp = CreateGlobalVariable(var_id))
964 emplace_result.first->second = var_sp;
965 else
966 return nullptr;
967 }
968
969 return emplace_result.first->second;
970 }
971
GetOrCreateType(TypeIndex ti)972 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
973 return GetOrCreateType(PdbTypeSymId(ti, false));
974 }
975
GetOrCreateFunction(PdbCompilandSymId func_id,CompileUnit & comp_unit)976 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
977 CompileUnit &comp_unit) {
978 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
979 if (emplace_result.second)
980 emplace_result.first->second = CreateFunction(func_id, comp_unit);
981
982 return emplace_result.first->second;
983 }
984
985 CompUnitSP
GetOrCreateCompileUnit(const CompilandIndexItem & cci)986 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
987
988 auto emplace_result =
989 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
990 if (emplace_result.second)
991 emplace_result.first->second = CreateCompileUnit(cci);
992
993 lldbassert(emplace_result.first->second);
994 return emplace_result.first->second;
995 }
996
GetOrCreateBlock(PdbCompilandSymId block_id)997 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
998 auto iter = m_blocks.find(toOpaqueUid(block_id));
999 if (iter != m_blocks.end())
1000 return *iter->second;
1001
1002 return CreateBlock(block_id);
1003 }
1004
ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx)1005 void SymbolFileNativePDB::ParseDeclsForContext(
1006 lldb_private::CompilerDeclContext decl_ctx) {
1007 TypeSystem* ts_or_err = decl_ctx.GetTypeSystem();
1008 if (!ts_or_err)
1009 return;
1010 PdbAstBuilder* ast_builder = ts_or_err->GetNativePDBParser();
1011 clang::DeclContext *context = ast_builder->FromCompilerDeclContext(decl_ctx);
1012 if (!context)
1013 return;
1014 ast_builder->ParseDeclsForContext(*context);
1015 }
1016
ParseCompileUnitAtIndex(uint32_t index)1017 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1018 if (index >= GetNumCompileUnits())
1019 return CompUnitSP();
1020 lldbassert(index < UINT16_MAX);
1021 if (index >= UINT16_MAX)
1022 return nullptr;
1023
1024 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1025
1026 return GetOrCreateCompileUnit(item);
1027 }
1028
ParseLanguage(CompileUnit & comp_unit)1029 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
1030 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1031 PdbSymUid uid(comp_unit.GetID());
1032 lldbassert(uid.kind() == PdbSymUidKind::Compiland);
1033
1034 CompilandIndexItem *item =
1035 m_index->compilands().GetCompiland(uid.asCompiland().modi);
1036 lldbassert(item);
1037 if (!item->m_compile_opts)
1038 return lldb::eLanguageTypeUnknown;
1039
1040 return TranslateLanguage(item->m_compile_opts->getLanguage());
1041 }
1042
AddSymbols(Symtab & symtab)1043 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) {}
1044
ParseFunctions(CompileUnit & comp_unit)1045 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
1046 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1047 PdbSymUid uid{comp_unit.GetID()};
1048 lldbassert(uid.kind() == PdbSymUidKind::Compiland);
1049 uint16_t modi = uid.asCompiland().modi;
1050 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
1051
1052 size_t count = comp_unit.GetNumFunctions();
1053 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
1054 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1055 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
1056 continue;
1057
1058 PdbCompilandSymId sym_id{modi, iter.offset()};
1059
1060 FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
1061 }
1062
1063 size_t new_count = comp_unit.GetNumFunctions();
1064 lldbassert(new_count >= count);
1065 return new_count - count;
1066 }
1067
NeedsResolvedCompileUnit(uint32_t resolve_scope)1068 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1069 // If any of these flags are set, we need to resolve the compile unit.
1070 uint32_t flags = eSymbolContextCompUnit;
1071 flags |= eSymbolContextVariable;
1072 flags |= eSymbolContextFunction;
1073 flags |= eSymbolContextBlock;
1074 flags |= eSymbolContextLineEntry;
1075 return (resolve_scope & flags) != 0;
1076 }
1077
ResolveSymbolContext(const Address & addr,SymbolContextItem resolve_scope,SymbolContext & sc)1078 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1079 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1080 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1081 uint32_t resolved_flags = 0;
1082 lldb::addr_t file_addr = addr.GetFileAddress();
1083
1084 if (NeedsResolvedCompileUnit(resolve_scope)) {
1085 std::optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1086 if (!modi)
1087 return 0;
1088 CompUnitSP cu_sp = GetCompileUnitAtIndex(*modi);
1089 if (!cu_sp)
1090 return 0;
1091
1092 sc.comp_unit = cu_sp.get();
1093 resolved_flags |= eSymbolContextCompUnit;
1094 }
1095
1096 if (resolve_scope & eSymbolContextFunction ||
1097 resolve_scope & eSymbolContextBlock) {
1098 lldbassert(sc.comp_unit);
1099 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1100 // Search the matches in reverse. This way if there are multiple matches
1101 // (for example we are 3 levels deep in a nested scope) it will find the
1102 // innermost one first.
1103 for (const auto &match : llvm::reverse(matches)) {
1104 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1105 continue;
1106
1107 PdbCompilandSymId csid = match.uid.asCompilandSym();
1108 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1109 PDB_SymType type = CVSymToPDBSym(cvs.kind());
1110 if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1111 continue;
1112 if (type == PDB_SymType::Function) {
1113 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1114 if (sc.function) {
1115 Block &block = sc.function->GetBlock(true);
1116 addr_t func_base =
1117 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
1118 addr_t offset = file_addr - func_base;
1119 sc.block = block.FindInnermostBlockByOffset(offset);
1120 }
1121 }
1122
1123 if (type == PDB_SymType::Block) {
1124 Block &block = GetOrCreateBlock(csid);
1125 sc.function = block.CalculateSymbolContextFunction();
1126 if (sc.function) {
1127 sc.function->GetBlock(true);
1128 addr_t func_base =
1129 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
1130 addr_t offset = file_addr - func_base;
1131 sc.block = block.FindInnermostBlockByOffset(offset);
1132 }
1133 }
1134 if (sc.function)
1135 resolved_flags |= eSymbolContextFunction;
1136 if (sc.block)
1137 resolved_flags |= eSymbolContextBlock;
1138 break;
1139 }
1140 }
1141
1142 if (resolve_scope & eSymbolContextLineEntry) {
1143 lldbassert(sc.comp_unit);
1144 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1145 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1146 resolved_flags |= eSymbolContextLineEntry;
1147 }
1148 }
1149
1150 return resolved_flags;
1151 }
1152
ResolveSymbolContext(const SourceLocationSpec & src_location_spec,lldb::SymbolContextItem resolve_scope,SymbolContextList & sc_list)1153 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1154 const SourceLocationSpec &src_location_spec,
1155 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1156 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1157 const uint32_t prev_size = sc_list.GetSize();
1158 if (resolve_scope & eSymbolContextCompUnit) {
1159 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1160 ++cu_idx) {
1161 CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1162 if (!cu)
1163 continue;
1164
1165 bool file_spec_matches_cu_file_spec = FileSpec::Match(
1166 src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1167 if (file_spec_matches_cu_file_spec) {
1168 cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1169 break;
1170 }
1171 }
1172 }
1173 return sc_list.GetSize() - prev_size;
1174 }
1175
ParseLineTable(CompileUnit & comp_unit)1176 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1177 // Unfortunately LLDB is set up to parse the entire compile unit line table
1178 // all at once, even if all it really needs is line info for a specific
1179 // function. In the future it would be nice if it could set the sc.m_function
1180 // member, and we could only get the line info for the function in question.
1181 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1182 PdbSymUid cu_id(comp_unit.GetID());
1183 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1184 uint16_t modi = cu_id.asCompiland().modi;
1185 CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1186 lldbassert(cii);
1187
1188 // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1189 // in this CU. Add line entries into the set first so that if there are line
1190 // entries with same addres, the later is always more accurate than the
1191 // former.
1192 std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1193
1194 // This is basically a copy of the .debug$S subsections from all original COFF
1195 // object files merged together with address relocations applied. We are
1196 // looking for all DEBUG_S_LINES subsections.
1197 for (const DebugSubsectionRecord &dssr :
1198 cii->m_debug_stream.getSubsectionsArray()) {
1199 if (dssr.kind() != DebugSubsectionKind::Lines)
1200 continue;
1201
1202 DebugLinesSubsectionRef lines;
1203 llvm::BinaryStreamReader reader(dssr.getRecordData());
1204 if (auto EC = lines.initialize(reader)) {
1205 llvm::consumeError(std::move(EC));
1206 return false;
1207 }
1208
1209 const LineFragmentHeader *lfh = lines.header();
1210 uint64_t virtual_addr =
1211 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1212 if (virtual_addr == LLDB_INVALID_ADDRESS)
1213 continue;
1214
1215 for (const LineColumnEntry &group : lines) {
1216 llvm::Expected<uint32_t> file_index_or_err =
1217 GetFileIndex(*cii, group.NameIndex);
1218 if (!file_index_or_err)
1219 continue;
1220 uint32_t file_index = file_index_or_err.get();
1221 lldbassert(!group.LineNumbers.empty());
1222 CompilandIndexItem::GlobalLineTable::Entry line_entry(
1223 LLDB_INVALID_ADDRESS, 0);
1224 for (const LineNumberEntry &entry : group.LineNumbers) {
1225 LineInfo cur_info(entry.Flags);
1226
1227 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1228 continue;
1229
1230 uint64_t addr = virtual_addr + entry.Offset;
1231
1232 bool is_statement = cur_info.isStatement();
1233 bool is_prologue = IsFunctionPrologue(*cii, addr);
1234 bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1235
1236 uint32_t lno = cur_info.getStartLine();
1237
1238 LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1239 is_prologue, is_epilogue, false);
1240 // Terminal entry has lower precedence than new entry.
1241 auto iter = line_set.find(new_entry);
1242 if (iter != line_set.end() && iter->is_terminal_entry)
1243 line_set.erase(iter);
1244 line_set.insert(new_entry);
1245
1246 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1247 line_entry.SetRangeEnd(addr);
1248 cii->m_global_line_table.Append(line_entry);
1249 }
1250 line_entry.SetRangeBase(addr);
1251 line_entry.data = {file_index, lno};
1252 }
1253 LineInfo last_line(group.LineNumbers.back().Flags);
1254 line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1255 file_index, false, false, false, false, true);
1256
1257 if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1258 line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1259 cii->m_global_line_table.Append(line_entry);
1260 }
1261 }
1262 }
1263
1264 cii->m_global_line_table.Sort();
1265
1266 // Parse all S_INLINESITE in this CU.
1267 const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1268 for (auto iter = syms.begin(); iter != syms.end();) {
1269 if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1270 ++iter;
1271 continue;
1272 }
1273
1274 uint32_t record_offset = iter.offset();
1275 CVSymbol func_record =
1276 cii->m_debug_stream.readSymbolAtOffset(record_offset);
1277 SegmentOffsetLength sol = GetSegmentOffsetAndLength(func_record);
1278 addr_t file_vm_addr =
1279 m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
1280 if (file_vm_addr == LLDB_INVALID_ADDRESS)
1281 continue;
1282
1283 AddressRange func_range(file_vm_addr, sol.length,
1284 comp_unit.GetModule()->GetSectionList());
1285 Address func_base = func_range.GetBaseAddress();
1286 PdbCompilandSymId func_id{modi, record_offset};
1287
1288 // Iterate all S_INLINESITEs in the function.
1289 auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1290 if (kind != S_INLINESITE)
1291 return false;
1292
1293 ParseInlineSite(id, func_base);
1294
1295 for (const auto &line_entry :
1296 m_inline_sites[toOpaqueUid(id)]->line_entries) {
1297 // If line_entry is not terminal entry, remove previous line entry at
1298 // the same address and insert new one. Terminal entry inside an inline
1299 // site might not be terminal entry for its parent.
1300 if (!line_entry.is_terminal_entry)
1301 line_set.erase(line_entry);
1302 line_set.insert(line_entry);
1303 }
1304 // No longer useful after adding to line_set.
1305 m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1306 return true;
1307 };
1308 ParseSymbolArrayInScope(func_id, parse_inline_sites);
1309 // Jump to the end of the function record.
1310 iter = syms.at(getScopeEndOffset(func_record));
1311 }
1312
1313 cii->m_global_line_table.Clear();
1314
1315 // Add line entries in line_set to line_table.
1316 auto line_table = std::make_unique<LineTable>(&comp_unit);
1317 std::unique_ptr<LineSequence> sequence(
1318 line_table->CreateLineSequenceContainer());
1319 for (const auto &line_entry : line_set) {
1320 line_table->AppendLineEntryToSequence(
1321 sequence.get(), line_entry.file_addr, line_entry.line,
1322 line_entry.column, line_entry.file_idx,
1323 line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1324 line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1325 line_entry.is_terminal_entry);
1326 }
1327 line_table->InsertSequence(sequence.get());
1328
1329 if (line_table->GetSize() == 0)
1330 return false;
1331
1332 comp_unit.SetLineTable(line_table.release());
1333 return true;
1334 }
1335
ParseDebugMacros(CompileUnit & comp_unit)1336 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1337 // PDB doesn't contain information about macros
1338 return false;
1339 }
1340
1341 llvm::Expected<uint32_t>
GetFileIndex(const CompilandIndexItem & cii,uint32_t file_id)1342 SymbolFileNativePDB::GetFileIndex(const CompilandIndexItem &cii,
1343 uint32_t file_id) {
1344 const auto &checksums = cii.m_strings.checksums().getArray();
1345 const auto &strings = cii.m_strings.strings();
1346 // Indices in this structure are actually offsets of records in the
1347 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1348 // into the global PDB string table.
1349 auto iter = checksums.at(file_id);
1350 if (iter == checksums.end())
1351 return llvm::make_error<RawError>(raw_error_code::no_entry);
1352
1353 llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1354 if (!efn) {
1355 return efn.takeError();
1356 }
1357
1358 // LLDB wants the index of the file in the list of support files.
1359 auto fn_iter = llvm::find(cii.m_file_list, *efn);
1360 if (fn_iter != cii.m_file_list.end())
1361 return std::distance(cii.m_file_list.begin(), fn_iter);
1362 return llvm::make_error<RawError>(raw_error_code::no_entry);
1363 }
1364
ParseSupportFiles(CompileUnit & comp_unit,FileSpecList & support_files)1365 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1366 FileSpecList &support_files) {
1367 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1368 PdbSymUid cu_id(comp_unit.GetID());
1369 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1370 CompilandIndexItem *cci =
1371 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1372 lldbassert(cci);
1373
1374 for (llvm::StringRef f : cci->m_file_list) {
1375 FileSpec::Style style =
1376 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1377 FileSpec spec(f, style);
1378 support_files.Append(spec);
1379 }
1380 return true;
1381 }
1382
ParseImportedModules(const SymbolContext & sc,std::vector<SourceModule> & imported_modules)1383 bool SymbolFileNativePDB::ParseImportedModules(
1384 const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1385 // PDB does not yet support module debug info
1386 return false;
1387 }
1388
ParseInlineSite(PdbCompilandSymId id,Address func_addr)1389 void SymbolFileNativePDB::ParseInlineSite(PdbCompilandSymId id,
1390 Address func_addr) {
1391 lldb::user_id_t opaque_uid = toOpaqueUid(id);
1392 if (m_inline_sites.find(opaque_uid) != m_inline_sites.end())
1393 return;
1394
1395 addr_t func_base = func_addr.GetFileAddress();
1396 CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1397 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1398 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1399
1400 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1401 cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site));
1402 PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1403
1404 std::shared_ptr<InlineSite> inline_site_sp =
1405 std::make_shared<InlineSite>(parent_id);
1406
1407 // Get the inlined function declaration info.
1408 auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1409 if (iter == cii->m_inline_map.end())
1410 return;
1411 InlineeSourceLine inlinee_line = iter->second;
1412
1413 const FileSpecList &files = comp_unit->GetSupportFiles();
1414 FileSpec decl_file;
1415 llvm::Expected<uint32_t> file_index_or_err =
1416 GetFileIndex(*cii, inlinee_line.Header->FileID);
1417 if (!file_index_or_err)
1418 return;
1419 uint32_t file_offset = file_index_or_err.get();
1420 decl_file = files.GetFileSpecAtIndex(file_offset);
1421 uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1422 std::unique_ptr<Declaration> decl_up =
1423 std::make_unique<Declaration>(decl_file, decl_line);
1424
1425 // Parse range and line info.
1426 uint32_t code_offset = 0;
1427 int32_t line_offset = 0;
1428 std::optional<uint32_t> code_offset_base;
1429 std::optional<uint32_t> code_offset_end;
1430 std::optional<int32_t> cur_line_offset;
1431 std::optional<int32_t> next_line_offset;
1432 std::optional<uint32_t> next_file_offset;
1433
1434 bool is_terminal_entry = false;
1435 bool is_start_of_statement = true;
1436 // The first instruction is the prologue end.
1437 bool is_prologue_end = true;
1438
1439 auto update_code_offset = [&](uint32_t code_delta) {
1440 if (!code_offset_base)
1441 code_offset_base = code_offset;
1442 else if (!code_offset_end)
1443 code_offset_end = *code_offset_base + code_delta;
1444 };
1445 auto update_line_offset = [&](int32_t line_delta) {
1446 line_offset += line_delta;
1447 if (!code_offset_base || !cur_line_offset)
1448 cur_line_offset = line_offset;
1449 else
1450 next_line_offset = line_offset;
1451 ;
1452 };
1453 auto update_file_offset = [&](uint32_t offset) {
1454 if (!code_offset_base)
1455 file_offset = offset;
1456 else
1457 next_file_offset = offset;
1458 };
1459
1460 for (auto &annot : inline_site.annotations()) {
1461 switch (annot.OpCode) {
1462 case BinaryAnnotationsOpCode::CodeOffset:
1463 case BinaryAnnotationsOpCode::ChangeCodeOffset:
1464 case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1465 code_offset += annot.U1;
1466 update_code_offset(annot.U1);
1467 break;
1468 case BinaryAnnotationsOpCode::ChangeLineOffset:
1469 update_line_offset(annot.S1);
1470 break;
1471 case BinaryAnnotationsOpCode::ChangeCodeLength:
1472 update_code_offset(annot.U1);
1473 code_offset += annot.U1;
1474 is_terminal_entry = true;
1475 break;
1476 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1477 code_offset += annot.U1;
1478 update_code_offset(annot.U1);
1479 update_line_offset(annot.S1);
1480 break;
1481 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1482 code_offset += annot.U2;
1483 update_code_offset(annot.U2);
1484 update_code_offset(annot.U1);
1485 code_offset += annot.U1;
1486 is_terminal_entry = true;
1487 break;
1488 case BinaryAnnotationsOpCode::ChangeFile:
1489 update_file_offset(annot.U1);
1490 break;
1491 default:
1492 break;
1493 }
1494
1495 // Add range if current range is finished.
1496 if (code_offset_base && code_offset_end && cur_line_offset) {
1497 inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1498 *code_offset_base, *code_offset_end - *code_offset_base,
1499 decl_line + *cur_line_offset));
1500 // Set base, end, file offset and line offset for next range.
1501 if (next_file_offset)
1502 file_offset = *next_file_offset;
1503 if (next_line_offset) {
1504 cur_line_offset = next_line_offset;
1505 next_line_offset = std::nullopt;
1506 }
1507 code_offset_base = is_terminal_entry ? std::nullopt : code_offset_end;
1508 code_offset_end = next_file_offset = std::nullopt;
1509 }
1510 if (code_offset_base && cur_line_offset) {
1511 if (is_terminal_entry) {
1512 LineTable::Entry line_entry(
1513 func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1514 file_offset, false, false, false, false, true);
1515 inline_site_sp->line_entries.push_back(line_entry);
1516 } else {
1517 LineTable::Entry line_entry(func_base + *code_offset_base,
1518 decl_line + *cur_line_offset, 0,
1519 file_offset, is_start_of_statement, false,
1520 is_prologue_end, false, false);
1521 inline_site_sp->line_entries.push_back(line_entry);
1522 is_prologue_end = false;
1523 is_start_of_statement = false;
1524 }
1525 }
1526 if (is_terminal_entry)
1527 is_start_of_statement = true;
1528 is_terminal_entry = false;
1529 }
1530
1531 inline_site_sp->ranges.Sort();
1532
1533 // Get the inlined function callsite info.
1534 std::unique_ptr<Declaration> callsite_up;
1535 if (!inline_site_sp->ranges.IsEmpty()) {
1536 auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1537 addr_t base_offset = entry->GetRangeBase();
1538 if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1539 S_INLINESITE) {
1540 // Its parent is another inline site, lookup parent site's range vector
1541 // for callsite line.
1542 ParseInlineSite(parent_id, func_base);
1543 std::shared_ptr<InlineSite> parent_site =
1544 m_inline_sites[toOpaqueUid(parent_id)];
1545 FileSpec &parent_decl_file =
1546 parent_site->inline_function_info->GetDeclaration().GetFile();
1547 if (auto *parent_entry =
1548 parent_site->ranges.FindEntryThatContains(base_offset)) {
1549 callsite_up =
1550 std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1551 }
1552 } else {
1553 // Its parent is a function, lookup global line table for callsite.
1554 if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1555 func_base + base_offset)) {
1556 const FileSpec &callsite_file =
1557 files.GetFileSpecAtIndex(entry->data.first);
1558 callsite_up =
1559 std::make_unique<Declaration>(callsite_file, entry->data.second);
1560 }
1561 }
1562 }
1563
1564 // Get the inlined function name.
1565 CVType inlinee_cvt = m_index->ipi().getType(inline_site.Inlinee);
1566 std::string inlinee_name;
1567 if (inlinee_cvt.kind() == LF_MFUNC_ID) {
1568 MemberFuncIdRecord mfr;
1569 cantFail(
1570 TypeDeserializer::deserializeAs<MemberFuncIdRecord>(inlinee_cvt, mfr));
1571 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1572 inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1573 inlinee_name.append("::");
1574 inlinee_name.append(mfr.getName().str());
1575 } else if (inlinee_cvt.kind() == LF_FUNC_ID) {
1576 FuncIdRecord fir;
1577 cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(inlinee_cvt, fir));
1578 TypeIndex parent_idx = fir.getParentScope();
1579 if (!parent_idx.isNoneType()) {
1580 LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1581 inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1582 inlinee_name.append("::");
1583 }
1584 inlinee_name.append(fir.getName().str());
1585 }
1586 inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1587 inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1588 callsite_up.get());
1589
1590 m_inline_sites[opaque_uid] = inline_site_sp;
1591 }
1592
ParseBlocksRecursive(Function & func)1593 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1594 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1595 PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1596 // After we iterate through inline sites inside the function, we already get
1597 // all the info needed, removing from the map to save memory.
1598 std::set<uint64_t> remove_uids;
1599 auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
1600 if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
1601 kind == S_INLINESITE) {
1602 GetOrCreateBlock(id);
1603 if (kind == S_INLINESITE)
1604 remove_uids.insert(toOpaqueUid(id));
1605 return true;
1606 }
1607 return false;
1608 };
1609 size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
1610 for (uint64_t uid : remove_uids) {
1611 m_inline_sites.erase(uid);
1612 }
1613 return count;
1614 }
1615
ParseSymbolArrayInScope(PdbCompilandSymId parent_id,llvm::function_ref<bool (SymbolKind,PdbCompilandSymId)> fn)1616 size_t SymbolFileNativePDB::ParseSymbolArrayInScope(
1617 PdbCompilandSymId parent_id,
1618 llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
1619 CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
1620 CVSymbolArray syms =
1621 cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
1622
1623 size_t count = 1;
1624 for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1625 PdbCompilandSymId child_id(parent_id.modi, iter.offset());
1626 if (fn(iter->kind(), child_id))
1627 ++count;
1628 }
1629
1630 return count;
1631 }
1632
DumpClangAST(Stream & s)1633 void SymbolFileNativePDB::DumpClangAST(Stream &s) {
1634 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
1635 if (!ts_or_err)
1636 return;
1637 auto ts = *ts_or_err;
1638 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
1639 if (!clang)
1640 return;
1641 clang->GetNativePDBParser()->Dump(s);
1642 }
1643
FindGlobalVariables(ConstString name,const CompilerDeclContext & parent_decl_ctx,uint32_t max_matches,VariableList & variables)1644 void SymbolFileNativePDB::FindGlobalVariables(
1645 ConstString name, const CompilerDeclContext &parent_decl_ctx,
1646 uint32_t max_matches, VariableList &variables) {
1647 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1648 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1649
1650 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1651 name.GetStringRef(), m_index->symrecords());
1652 for (const SymbolAndOffset &result : results) {
1653 switch (result.second.kind()) {
1654 case SymbolKind::S_GDATA32:
1655 case SymbolKind::S_LDATA32:
1656 case SymbolKind::S_GTHREAD32:
1657 case SymbolKind::S_LTHREAD32:
1658 case SymbolKind::S_CONSTANT: {
1659 PdbGlobalSymId global(result.first, false);
1660 if (VariableSP var = GetOrCreateGlobalVariable(global))
1661 variables.AddVariable(var);
1662 break;
1663 }
1664 default:
1665 continue;
1666 }
1667 }
1668 }
1669
FindFunctions(const Module::LookupInfo & lookup_info,const CompilerDeclContext & parent_decl_ctx,bool include_inlines,SymbolContextList & sc_list)1670 void SymbolFileNativePDB::FindFunctions(
1671 const Module::LookupInfo &lookup_info,
1672 const CompilerDeclContext &parent_decl_ctx, bool include_inlines,
1673 SymbolContextList &sc_list) {
1674 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1675 ConstString name = lookup_info.GetLookupName();
1676 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
1677 if (name_type_mask & eFunctionNameTypeFull)
1678 name = lookup_info.GetName();
1679
1680 // For now we only support lookup by method name or full name.
1681 if (!(name_type_mask & eFunctionNameTypeFull ||
1682 name_type_mask & eFunctionNameTypeMethod))
1683 return;
1684
1685 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1686
1687 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1688 name.GetStringRef(), m_index->symrecords());
1689 for (const SymbolAndOffset &match : matches) {
1690 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1691 continue;
1692 ProcRefSym proc(match.second.kind());
1693 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1694
1695 if (!IsValidRecord(proc))
1696 continue;
1697
1698 CompilandIndexItem &cci =
1699 m_index->compilands().GetOrCreateCompiland(proc.modi());
1700 SymbolContext sc;
1701
1702 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1703 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1704 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1705
1706 sc_list.Append(sc);
1707 }
1708 }
1709
FindFunctions(const RegularExpression & regex,bool include_inlines,SymbolContextList & sc_list)1710 void SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex,
1711 bool include_inlines,
1712 SymbolContextList &sc_list) {}
1713
FindTypes(ConstString name,const CompilerDeclContext & parent_decl_ctx,uint32_t max_matches,llvm::DenseSet<SymbolFile * > & searched_symbol_files,TypeMap & types)1714 void SymbolFileNativePDB::FindTypes(
1715 ConstString name, const CompilerDeclContext &parent_decl_ctx,
1716 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1717 TypeMap &types) {
1718 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1719 if (!name)
1720 return;
1721
1722 searched_symbol_files.clear();
1723 searched_symbol_files.insert(this);
1724
1725 // There is an assumption 'name' is not a regex
1726 FindTypesByName(name.GetStringRef(), max_matches, types);
1727 }
1728
FindTypes(llvm::ArrayRef<CompilerContext> pattern,LanguageSet languages,llvm::DenseSet<SymbolFile * > & searched_symbol_files,TypeMap & types)1729 void SymbolFileNativePDB::FindTypes(
1730 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1731 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1732
FindTypesByName(llvm::StringRef name,uint32_t max_matches,TypeMap & types)1733 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1734 uint32_t max_matches,
1735 TypeMap &types) {
1736
1737 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1738 if (max_matches > 0 && max_matches < matches.size())
1739 matches.resize(max_matches);
1740
1741 for (TypeIndex ti : matches) {
1742 TypeSP type = GetOrCreateType(ti);
1743 if (!type)
1744 continue;
1745
1746 types.Insert(type);
1747 }
1748 }
1749
ParseTypes(CompileUnit & comp_unit)1750 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1751 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1752 // Only do the full type scan the first time.
1753 if (m_done_full_type_scan)
1754 return 0;
1755
1756 const size_t old_count = GetTypeList().GetSize();
1757 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1758
1759 // First process the entire TPI stream.
1760 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1761 TypeSP type = GetOrCreateType(*ti);
1762 if (type)
1763 (void)type->GetFullCompilerType();
1764 }
1765
1766 // Next look for S_UDT records in the globals stream.
1767 for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1768 PdbGlobalSymId global{gid, false};
1769 CVSymbol sym = m_index->ReadSymbolRecord(global);
1770 if (sym.kind() != S_UDT)
1771 continue;
1772
1773 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1774 bool is_typedef = true;
1775 if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1776 CVType cvt = m_index->tpi().getType(udt.Type);
1777 llvm::StringRef name = CVTagRecord::create(cvt).name();
1778 if (name == udt.Name)
1779 is_typedef = false;
1780 }
1781
1782 if (is_typedef)
1783 GetOrCreateTypedef(global);
1784 }
1785
1786 const size_t new_count = GetTypeList().GetSize();
1787
1788 m_done_full_type_scan = true;
1789
1790 return new_count - old_count;
1791 }
1792
1793 size_t
ParseVariablesForCompileUnit(CompileUnit & comp_unit,VariableList & variables)1794 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1795 VariableList &variables) {
1796 PdbSymUid sym_uid(comp_unit.GetID());
1797 lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1798 return 0;
1799 }
1800
CreateLocalVariable(PdbCompilandSymId scope_id,PdbCompilandSymId var_id,bool is_param)1801 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1802 PdbCompilandSymId var_id,
1803 bool is_param) {
1804 ModuleSP module = GetObjectFile()->GetModule();
1805 Block &block = GetOrCreateBlock(scope_id);
1806 // Get function block.
1807 Block *func_block = █
1808 while (func_block->GetParent()) {
1809 func_block = func_block->GetParent();
1810 }
1811 Address addr;
1812 func_block->GetStartAddress(addr);
1813 VariableInfo var_info =
1814 GetVariableLocationInfo(*m_index, var_id, *func_block, module);
1815 Function *func = func_block->CalculateSymbolContextFunction();
1816 if (!func)
1817 return nullptr;
1818 // Use empty dwarf expr if optimized away so that it won't be filtered out
1819 // when lookuping local variables in this scope.
1820 if (!var_info.location.IsValid())
1821 var_info.location = DWARFExpressionList(module, DWARFExpression(), nullptr);
1822 var_info.location.SetFuncFileAddress(
1823 func->GetAddressRange().GetBaseAddress().GetFileAddress());
1824 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1825 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1826 TypeSP type_sp = GetOrCreateType(var_info.type);
1827 if (!type_sp)
1828 return nullptr;
1829 std::string name = var_info.name.str();
1830 Declaration decl;
1831 SymbolFileTypeSP sftype =
1832 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1833
1834 is_param |= var_info.is_param;
1835 ValueType var_scope =
1836 is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1837 bool external = false;
1838 bool artificial = false;
1839 bool location_is_constant_data = false;
1840 bool static_member = false;
1841 Variable::RangeList scope_ranges;
1842 VariableSP var_sp = std::make_shared<Variable>(
1843 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1844 &block, scope_ranges, &decl, var_info.location, external, artificial,
1845 location_is_constant_data, static_member);
1846 if (!is_param) {
1847 auto ts_or_err = GetTypeSystemForLanguage(comp_unit_sp->GetLanguage());
1848 if (auto err = ts_or_err.takeError())
1849 return nullptr;
1850 auto ts = *ts_or_err;
1851 if (!ts)
1852 return nullptr;
1853
1854 ts->GetNativePDBParser()->GetOrCreateVariableDecl(scope_id, var_id);
1855 }
1856 m_local_variables[toOpaqueUid(var_id)] = var_sp;
1857 return var_sp;
1858 }
1859
GetOrCreateLocalVariable(PdbCompilandSymId scope_id,PdbCompilandSymId var_id,bool is_param)1860 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1861 PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1862 auto iter = m_local_variables.find(toOpaqueUid(var_id));
1863 if (iter != m_local_variables.end())
1864 return iter->second;
1865
1866 return CreateLocalVariable(scope_id, var_id, is_param);
1867 }
1868
CreateTypedef(PdbGlobalSymId id)1869 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1870 CVSymbol sym = m_index->ReadSymbolRecord(id);
1871 lldbassert(sym.kind() == SymbolKind::S_UDT);
1872
1873 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1874
1875 TypeSP target_type = GetOrCreateType(udt.Type);
1876
1877 auto ts_or_err = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1878 if (auto err = ts_or_err.takeError())
1879 return nullptr;
1880 auto ts = *ts_or_err;
1881 if (!ts)
1882 return nullptr;
1883
1884 ts->GetNativePDBParser()->GetOrCreateTypedefDecl(id);
1885
1886 Declaration decl;
1887 return MakeType(
1888 toOpaqueUid(id), ConstString(udt.Name), target_type->GetByteSize(nullptr),
1889 nullptr, target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID,
1890 decl, target_type->GetForwardCompilerType(),
1891 lldb_private::Type::ResolveState::Forward);
1892 }
1893
GetOrCreateTypedef(PdbGlobalSymId id)1894 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1895 auto iter = m_types.find(toOpaqueUid(id));
1896 if (iter != m_types.end())
1897 return iter->second;
1898
1899 return CreateTypedef(id);
1900 }
1901
ParseVariablesForBlock(PdbCompilandSymId block_id)1902 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1903 Block &block = GetOrCreateBlock(block_id);
1904
1905 size_t count = 0;
1906
1907 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1908 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1909 uint32_t params_remaining = 0;
1910 switch (sym.kind()) {
1911 case S_GPROC32:
1912 case S_LPROC32: {
1913 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1914 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1915 CVType signature = m_index->tpi().getType(proc.FunctionType);
1916 if (signature.kind() == LF_PROCEDURE) {
1917 ProcedureRecord sig;
1918 if (llvm::Error e = TypeDeserializer::deserializeAs<ProcedureRecord>(
1919 signature, sig)) {
1920 llvm::consumeError(std::move(e));
1921 return 0;
1922 }
1923 params_remaining = sig.getParameterCount();
1924 } else if (signature.kind() == LF_MFUNCTION) {
1925 MemberFunctionRecord sig;
1926 if (llvm::Error e = TypeDeserializer::deserializeAs<MemberFunctionRecord>(
1927 signature, sig)) {
1928 llvm::consumeError(std::move(e));
1929 return 0;
1930 }
1931 params_remaining = sig.getParameterCount();
1932 } else
1933 return 0;
1934 break;
1935 }
1936 case S_BLOCK32:
1937 break;
1938 case S_INLINESITE:
1939 break;
1940 default:
1941 lldbassert(false && "Symbol is not a block!");
1942 return 0;
1943 }
1944
1945 VariableListSP variables = block.GetBlockVariableList(false);
1946 if (!variables) {
1947 variables = std::make_shared<VariableList>();
1948 block.SetVariableList(variables);
1949 }
1950
1951 CVSymbolArray syms = limitSymbolArrayToScope(
1952 cii->m_debug_stream.getSymbolArray(), block_id.offset);
1953
1954 // Skip the first record since it's a PROC32 or BLOCK32, and there's
1955 // no point examining it since we know it's not a local variable.
1956 syms.drop_front();
1957 auto iter = syms.begin();
1958 auto end = syms.end();
1959
1960 while (iter != end) {
1961 uint32_t record_offset = iter.offset();
1962 CVSymbol variable_cvs = *iter;
1963 PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1964 ++iter;
1965
1966 // If this is a block or inline site, recurse into its children and then
1967 // skip it.
1968 if (variable_cvs.kind() == S_BLOCK32 ||
1969 variable_cvs.kind() == S_INLINESITE) {
1970 uint32_t block_end = getScopeEndOffset(variable_cvs);
1971 count += ParseVariablesForBlock(child_sym_id);
1972 iter = syms.at(block_end);
1973 continue;
1974 }
1975
1976 bool is_param = params_remaining > 0;
1977 VariableSP variable;
1978 switch (variable_cvs.kind()) {
1979 case S_REGREL32:
1980 case S_REGISTER:
1981 case S_LOCAL:
1982 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1983 if (is_param)
1984 --params_remaining;
1985 if (variable)
1986 variables->AddVariableIfUnique(variable);
1987 break;
1988 default:
1989 break;
1990 }
1991 }
1992
1993 // Pass false for set_children, since we call this recursively so that the
1994 // children will call this for themselves.
1995 block.SetDidParseVariables(true, false);
1996
1997 return count;
1998 }
1999
ParseVariablesForContext(const SymbolContext & sc)2000 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
2001 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2002 lldbassert(sc.function || sc.comp_unit);
2003
2004 VariableListSP variables;
2005 if (sc.block) {
2006 PdbSymUid block_id(sc.block->GetID());
2007
2008 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2009 return count;
2010 }
2011
2012 if (sc.function) {
2013 PdbSymUid block_id(sc.function->GetID());
2014
2015 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
2016 return count;
2017 }
2018
2019 if (sc.comp_unit) {
2020 variables = sc.comp_unit->GetVariableList(false);
2021 if (!variables) {
2022 variables = std::make_shared<VariableList>();
2023 sc.comp_unit->SetVariableList(variables);
2024 }
2025 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
2026 }
2027
2028 llvm_unreachable("Unreachable!");
2029 }
2030
GetDeclForUID(lldb::user_id_t uid)2031 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
2032 auto ts_or_err = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
2033 if (auto err = ts_or_err.takeError())
2034 return CompilerDecl();
2035 auto ts = *ts_or_err;
2036 if (!ts)
2037 return {};
2038
2039 if (auto decl = ts->GetNativePDBParser()->GetOrCreateDeclForUid(uid))
2040 return *decl;
2041 return CompilerDecl();
2042 }
2043
2044 CompilerDeclContext
GetDeclContextForUID(lldb::user_id_t uid)2045 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
2046 auto ts_or_err = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
2047 if (auto err = ts_or_err.takeError())
2048 return {};
2049 auto ts = *ts_or_err;
2050 if (!ts)
2051 return {};
2052
2053 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2054 clang::DeclContext *context =
2055 ast_builder->GetOrCreateDeclContextForUid(PdbSymUid(uid));
2056 if (!context)
2057 return {};
2058
2059 return ast_builder->ToCompilerDeclContext(*context);
2060 }
2061
2062 CompilerDeclContext
GetDeclContextContainingUID(lldb::user_id_t uid)2063 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
2064 auto ts_or_err = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
2065 if (auto err = ts_or_err.takeError())
2066 return CompilerDeclContext();
2067 auto ts = *ts_or_err;
2068 if (!ts)
2069 return {};
2070
2071 PdbAstBuilder *ast_builder = ts->GetNativePDBParser();
2072 clang::DeclContext *context = ast_builder->GetParentDeclContext(PdbSymUid(uid));
2073 if (!context)
2074 return CompilerDeclContext();
2075 return ast_builder->ToCompilerDeclContext(*context);
2076 }
2077
ResolveTypeUID(lldb::user_id_t type_uid)2078 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
2079 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2080 auto iter = m_types.find(type_uid);
2081 // lldb should not be passing us non-sensical type uids. the only way it
2082 // could have a type uid in the first place is if we handed it out, in which
2083 // case we should know about the type. However, that doesn't mean we've
2084 // instantiated it yet. We can vend out a UID for a future type. So if the
2085 // type doesn't exist, let's instantiate it now.
2086 if (iter != m_types.end())
2087 return &*iter->second;
2088
2089 PdbSymUid uid(type_uid);
2090 lldbassert(uid.kind() == PdbSymUidKind::Type);
2091 PdbTypeSymId type_id = uid.asTypeSym();
2092 if (type_id.index.isNoneType())
2093 return nullptr;
2094
2095 TypeSP type_sp = CreateAndCacheType(type_id);
2096 if (!type_sp)
2097 return nullptr;
2098 return &*type_sp;
2099 }
2100
2101 std::optional<SymbolFile::ArrayInfo>
GetDynamicArrayInfoForUID(lldb::user_id_t type_uid,const lldb_private::ExecutionContext * exe_ctx)2102 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
2103 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
2104 return std::nullopt;
2105 }
2106
CompleteType(CompilerType & compiler_type)2107 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
2108 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2109 auto ts = compiler_type.GetTypeSystem();
2110 auto clang_type_system = ts.dyn_cast_or_null<TypeSystemClang>();
2111 if (!clang_type_system)
2112 return false;
2113
2114 PdbAstBuilder *ast_builder =
2115 static_cast<PdbAstBuilder *>(clang_type_system->GetNativePDBParser());
2116 if (ast_builder &&
2117 ast_builder->GetClangASTImporter().CanImport(compiler_type))
2118 return ast_builder->GetClangASTImporter().CompleteType(compiler_type);
2119 clang::QualType qt =
2120 clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
2121
2122 return ast_builder->CompleteType(qt);
2123 }
2124
GetTypes(lldb_private::SymbolContextScope * sc_scope,TypeClass type_mask,lldb_private::TypeList & type_list)2125 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
2126 TypeClass type_mask,
2127 lldb_private::TypeList &type_list) {}
2128
2129 CompilerDeclContext
FindNamespace(ConstString name,const CompilerDeclContext & parent_decl_ctx)2130 SymbolFileNativePDB::FindNamespace(ConstString name,
2131 const CompilerDeclContext &parent_decl_ctx) {
2132 return {};
2133 }
2134
2135 llvm::Expected<lldb::TypeSystemSP>
GetTypeSystemForLanguage(lldb::LanguageType language)2136 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
2137 auto type_system_or_err =
2138 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
2139 if (type_system_or_err)
2140 if (auto ts = *type_system_or_err)
2141 ts->SetSymbolFile(this);
2142 return type_system_or_err;
2143 }
2144
GetDebugInfoSize()2145 uint64_t SymbolFileNativePDB::GetDebugInfoSize() {
2146 // PDB files are a separate file that contains all debug info.
2147 return m_index->pdb().getFileSize();
2148 }
2149
BuildParentMap()2150 void SymbolFileNativePDB::BuildParentMap() {
2151 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
2152
2153 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
2154 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
2155
2156 struct RecordIndices {
2157 TypeIndex forward;
2158 TypeIndex full;
2159 };
2160
2161 llvm::StringMap<RecordIndices> record_indices;
2162
2163 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
2164 CVType type = types.getType(*ti);
2165 if (!IsTagRecord(type))
2166 continue;
2167
2168 CVTagRecord tag = CVTagRecord::create(type);
2169
2170 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
2171 if (tag.asTag().isForwardRef())
2172 indices.forward = *ti;
2173 else
2174 indices.full = *ti;
2175
2176 if (indices.full != TypeIndex::None() &&
2177 indices.forward != TypeIndex::None()) {
2178 forward_to_full[indices.forward] = indices.full;
2179 full_to_forward[indices.full] = indices.forward;
2180 }
2181
2182 // We're looking for LF_NESTTYPE records in the field list, so ignore
2183 // forward references (no field list), and anything without a nested class
2184 // (since there won't be any LF_NESTTYPE records).
2185 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
2186 continue;
2187
2188 struct ProcessTpiStream : public TypeVisitorCallbacks {
2189 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
2190 const CVTagRecord &parent_cvt,
2191 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
2192 : index(index), parents(parents), parent(parent),
2193 parent_cvt(parent_cvt) {}
2194
2195 PdbIndex &index;
2196 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
2197
2198 unsigned unnamed_type_index = 1;
2199 TypeIndex parent;
2200 const CVTagRecord &parent_cvt;
2201
2202 llvm::Error visitKnownMember(CVMemberRecord &CVR,
2203 NestedTypeRecord &Record) override {
2204 std::string unnamed_type_name;
2205 if (Record.Name.empty()) {
2206 unnamed_type_name =
2207 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
2208 Record.Name = unnamed_type_name;
2209 ++unnamed_type_index;
2210 }
2211 std::optional<CVTagRecord> tag =
2212 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
2213 if (!tag)
2214 return llvm::ErrorSuccess();
2215
2216 parents[Record.Type] = parent;
2217 return llvm::ErrorSuccess();
2218 }
2219 };
2220
2221 CVType field_list_cvt = m_index->tpi().getType(tag.asTag().FieldList);
2222 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
2223 FieldListRecord field_list;
2224 if (llvm::Error error = TypeDeserializer::deserializeAs<FieldListRecord>(
2225 field_list_cvt, field_list))
2226 llvm::consumeError(std::move(error));
2227 if (llvm::Error error = visitMemberRecordStream(field_list.Data, process))
2228 llvm::consumeError(std::move(error));
2229 }
2230
2231 // Now that we know the forward -> full mapping of all type indices, we can
2232 // re-write all the indices. At the end of this process, we want a mapping
2233 // consisting of fwd -> full and full -> full for all child -> parent indices.
2234 // We can re-write the values in place, but for the keys, we must save them
2235 // off so that we don't modify the map in place while also iterating it.
2236 std::vector<TypeIndex> full_keys;
2237 std::vector<TypeIndex> fwd_keys;
2238 for (auto &entry : m_parent_types) {
2239 TypeIndex key = entry.first;
2240 TypeIndex value = entry.second;
2241
2242 auto iter = forward_to_full.find(value);
2243 if (iter != forward_to_full.end())
2244 entry.second = iter->second;
2245
2246 iter = forward_to_full.find(key);
2247 if (iter != forward_to_full.end())
2248 fwd_keys.push_back(key);
2249 else
2250 full_keys.push_back(key);
2251 }
2252 for (TypeIndex fwd : fwd_keys) {
2253 TypeIndex full = forward_to_full[fwd];
2254 m_parent_types[full] = m_parent_types[fwd];
2255 }
2256 for (TypeIndex full : full_keys) {
2257 TypeIndex fwd = full_to_forward[full];
2258 m_parent_types[fwd] = m_parent_types[full];
2259 }
2260 }
2261
2262 std::optional<PdbCompilandSymId>
FindSymbolScope(PdbCompilandSymId id)2263 SymbolFileNativePDB::FindSymbolScope(PdbCompilandSymId id) {
2264 CVSymbol sym = m_index->ReadSymbolRecord(id);
2265 if (symbolOpensScope(sym.kind())) {
2266 // If this exact symbol opens a scope, we can just directly access its
2267 // parent.
2268 id.offset = getScopeParentOffset(sym);
2269 // Global symbols have parent offset of 0. Return std::nullopt to indicate
2270 // this.
2271 if (id.offset == 0)
2272 return std::nullopt;
2273 return id;
2274 }
2275
2276 // Otherwise we need to start at the beginning and iterate forward until we
2277 // reach (or pass) this particular symbol
2278 CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(id.modi);
2279 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
2280
2281 auto begin = syms.begin();
2282 auto end = syms.at(id.offset);
2283 std::vector<PdbCompilandSymId> scope_stack;
2284
2285 while (begin != end) {
2286 if (begin.offset() > id.offset) {
2287 // We passed it. We couldn't even find this symbol record.
2288 lldbassert(false && "Invalid compiland symbol id!");
2289 return std::nullopt;
2290 }
2291
2292 // We haven't found the symbol yet. Check if we need to open or close the
2293 // scope stack.
2294 if (symbolOpensScope(begin->kind())) {
2295 // We can use the end offset of the scope to determine whether or not
2296 // we can just outright skip this entire scope.
2297 uint32_t scope_end = getScopeEndOffset(*begin);
2298 if (scope_end < id.offset) {
2299 begin = syms.at(scope_end);
2300 } else {
2301 // The symbol we're looking for is somewhere in this scope.
2302 scope_stack.emplace_back(id.modi, begin.offset());
2303 }
2304 } else if (symbolEndsScope(begin->kind())) {
2305 scope_stack.pop_back();
2306 }
2307 ++begin;
2308 }
2309 if (scope_stack.empty())
2310 return std::nullopt;
2311 // We have a match! Return the top of the stack
2312 return scope_stack.back();
2313 }
2314
2315 std::optional<llvm::codeview::TypeIndex>
GetParentType(llvm::codeview::TypeIndex ti)2316 SymbolFileNativePDB::GetParentType(llvm::codeview::TypeIndex ti) {
2317 auto parent_iter = m_parent_types.find(ti);
2318 if (parent_iter == m_parent_types.end())
2319 return std::nullopt;
2320 return parent_iter->second;
2321 }
2322