LLDB mainline
SymbolFilePDB.cpp
Go to the documentation of this file.
1//===-- SymbolFilePDB.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 "SymbolFilePDB.h"
10
11#include "PDBASTParser.h"
13
14#include "clang/Lex/Lexer.h"
15
17#include "lldb/Core/Debugger.h"
18#include "lldb/Core/Mangled.h"
19#include "lldb/Core/Module.h"
27#include "lldb/Symbol/TypeMap.h"
30#include "lldb/Utility/Log.h"
32
33#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_DIA_SDK
34#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"
35#include "llvm/DebugInfo/PDB/GenericError.h"
36#include "llvm/DebugInfo/PDB/IPDBDataStream.h"
37#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
38#include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
39#include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
40#include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
41#include "llvm/DebugInfo/PDB/IPDBTable.h"
42#include "llvm/DebugInfo/PDB/PDBSymbol.h"
43#include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
44#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
45#include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
46#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
47#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
48#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
49#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
50#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
51#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
52#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
53#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
54#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
55#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
56#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
57
60
61#if defined(_WIN32)
62#include "llvm/Config/llvm-config.h"
63#include <optional>
64#endif
65
66using namespace lldb;
67using namespace lldb_private;
68using namespace llvm::pdb;
69
71
73
74namespace {
75
76enum PDBReader {
77 ePDBReaderDefault,
78 ePDBReaderDIA,
79 ePDBReaderNative,
80};
81
82constexpr OptionEnumValueElement g_pdb_reader_enums[] = {
83 {
84 ePDBReaderDefault,
85 "default",
86 "Use native PDB reader unless LLDB_USE_NATIVE_PDB_READER environment "
87 "is set to 0",
88 },
89 {
90 ePDBReaderDIA,
91 "dia",
92 "Use DIA PDB reader",
93 },
94 {
95 ePDBReaderNative,
96 "native",
97 "Use native PDB reader",
98 },
99};
100
101#define LLDB_PROPERTIES_symbolfilepdb
102#include "SymbolFilePDBProperties.inc"
103
104enum {
105#define LLDB_PROPERTIES_symbolfilepdb
106#include "SymbolFilePDBPropertiesEnum.inc"
107};
108
109static const bool g_should_use_native_reader_by_default = [] {
110 llvm::StringRef env_value = ::getenv("LLDB_USE_NATIVE_PDB_READER");
111
112 return !env_value.equals_insensitive("off") &&
113 !env_value.equals_insensitive("no") &&
114 !env_value.equals_insensitive("0") &&
115 !env_value.equals_insensitive("false");
116}();
117
118class PluginProperties : public Properties {
119public:
120 static llvm::StringRef GetSettingName() {
122 }
123
124 PluginProperties() {
125 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
126 m_collection_sp->Initialize(g_symbolfilepdb_properties_def);
127 }
128
129 bool UseNativeReader() const {
130#if LLVM_ENABLE_DIA_SDK && defined(_WIN32)
131 return IsNativeReaderRequested();
132#else
133 if (!IsNativeReaderRequested()) {
134 static std::once_flag g_warning_shown;
136 "the DIA PDB reader was explicitly requested, but LLDB was built "
137 "without the DIA SDK. The native reader will be used instead",
138 {}, &g_warning_shown);
139 }
140 return true;
141#endif
142 }
143
144private:
145 bool IsNativeReaderRequested() const {
146 auto value =
147 GetPropertyAtIndexAs<PDBReader>(ePropertyReader, ePDBReaderDefault);
148 switch (value) {
149 case ePDBReaderNative:
150 return true;
151 case ePDBReaderDIA:
152 return false;
153 default:
154 return g_should_use_native_reader_by_default;
155 }
156 }
157};
158
159PluginProperties &GetGlobalPluginProperties() {
160 static PluginProperties g_settings;
161 return g_settings;
162}
163
165 switch (lang) {
166 case PDB_Lang::Cpp:
168 case PDB_Lang::C:
170 case PDB_Lang::Swift:
172 case PDB_Lang::Rust:
174 case PDB_Lang::ObjC:
176 case PDB_Lang::ObjCpp:
178 default:
180 }
181}
182
183bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
184 uint32_t addr_length) {
185 return ((requested_line == 0 || actual_line == requested_line) &&
186 addr_length > 0);
187}
188} // namespace
189
191 // Initialize both but check in CreateInstance for the desired plugin
193
197}
198
204
206 return GetGlobalPluginProperties().UseNativeReader();
207}
208
211 debugger, PluginProperties::GetSettingName())) {
213 debugger, GetGlobalPluginProperties().GetValueProperties(),
214 "Properties for the PDB symbol-file plug-in.", true);
215 }
216}
217
219 return "Microsoft PDB debug symbol file reader.";
220}
221
224 if (UseNativePDB())
225 return nullptr;
226
227 return new SymbolFilePDB(std::move(objfile_sp));
228}
229
232
234
236 uint32_t abilities = 0;
237 if (!m_objfile_sp)
238 return 0;
239
240 if (!m_session_up) {
241 // Lazily load and match the PDB file, but only do this once.
242 std::string exePath =
243 m_objfile_sp->GetModule()->GetObjectFile()->GetFileSpec().GetPath();
244 auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
246 if (error) {
247 llvm::consumeError(std::move(error));
248 auto module_sp = m_objfile_sp->GetModule();
249 if (!module_sp)
250 return 0;
251 // See if any symbol file is specified through `--symfile` option.
252 FileSpec symfile = module_sp->GetSymbolFileFileSpec();
253 if (!symfile)
254 return 0;
255 error = loadDataForPDB(PDB_ReaderType::DIA,
256 llvm::StringRef(symfile.GetPath()), m_session_up);
257 if (error) {
258 llvm::consumeError(std::move(error));
259 return 0;
260 }
261 }
262 }
263 if (!m_session_up)
264 return 0;
265
266 auto enum_tables_up = m_session_up->getEnumTables();
267 if (!enum_tables_up)
268 return 0;
269 while (auto table_up = enum_tables_up->getNext()) {
270 if (table_up->getItemCount() == 0)
271 continue;
272 auto type = table_up->getTableType();
273 switch (type) {
274 case PDB_TableType::Symbols:
275 // This table represents a store of symbols with types listed in
276 // PDBSym_Type
277 abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
279 break;
280 case PDB_TableType::LineNumbers:
281 abilities |= LineTables;
282 break;
283 default:
284 break;
285 }
286 }
287 return abilities;
288}
289
291 lldb::addr_t obj_load_address = m_objfile_sp->GetModule()
292 ->GetObjectFile()
293 ->GetBaseAddress()
294 .GetFileAddress();
295 lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
296 m_session_up->setLoadAddress(obj_load_address);
298 m_global_scope_up = m_session_up->getGlobalScope();
300}
301
303 auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
304 if (!compilands)
305 return 0;
306
307 // The linker could link *.dll (compiland language = LINK), or import
308 // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
309 // found as a child of the global scope (PDB executable). Usually, such
310 // compilands contain `thunk` symbols in which we are not interested for
311 // now. However we still count them in the compiland list. If we perform
312 // any compiland related activity, like finding symbols through
313 // llvm::pdb::IPDBSession methods, such compilands will all be searched
314 // automatically no matter whether we include them or not.
315 uint32_t compile_unit_count = compilands->getChildCount();
316
317 // The linker can inject an additional "dummy" compilation unit into the
318 // PDB. Ignore this special compile unit for our purposes, if it is there.
319 // It is always the last one.
320 auto last_compiland_up = compilands->getChildAtIndex(compile_unit_count - 1);
321 lldbassert(last_compiland_up.get());
322 std::string name = last_compiland_up->getName();
323 if (name == "* Linker *")
324 --compile_unit_count;
325 return compile_unit_count;
326}
327
329 const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
330 auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
331 if (!results_up)
332 return;
333 auto uid = pdb_compiland.getSymIndexId();
334 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
335 auto compiland_up = results_up->getChildAtIndex(cu_idx);
336 if (!compiland_up)
337 continue;
338 if (compiland_up->getSymIndexId() == uid) {
339 index = cu_idx;
340 return;
341 }
342 }
343 index = UINT32_MAX;
344}
345
346std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
348 return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
349}
350
352 if (index >= GetNumCompileUnits())
353 return CompUnitSP();
354
355 // Assuming we always retrieve same compilands listed in same order through
356 // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
357 // compile unit makes no sense.
358 auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
359 if (!results)
360 return CompUnitSP();
361 auto compiland_up = results->getChildAtIndex(index);
362 if (!compiland_up)
363 return CompUnitSP();
364 return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
365}
366
368 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
369 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
370 if (!compiland_up)
372 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
373 if (!details)
375 return TranslateLanguage(details->getLanguage());
376}
377
380 CompileUnit &comp_unit) {
381 if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId()))
382 return result.get();
383
384 auto file_vm_addr = pdb_func.getVirtualAddress();
385 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
386 return nullptr;
387
388 auto func_length = pdb_func.getLength();
389 Address func_addr(file_vm_addr,
390 GetObjectFile()->GetModule()->GetSectionList());
391 if (!func_addr.IsValid())
392 return nullptr;
393
394 lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
395 if (!func_type)
396 return nullptr;
397
398 user_id_t func_type_uid = pdb_func.getSignatureId();
399
400 Mangled mangled = GetMangledForPDBFunc(pdb_func);
401
402 FunctionSP func_sp = std::make_shared<Function>(
403 &comp_unit, pdb_func.getSymIndexId(), func_type_uid, mangled, func_type,
404 func_addr, AddressRanges{AddressRange(func_addr, func_length)});
405
406 comp_unit.AddFunction(func_sp);
407
408 LanguageType lang = ParseLanguage(comp_unit);
409 auto type_system_or_err = GetTypeSystemForLanguage(lang);
410 if (auto err = type_system_or_err.takeError()) {
411 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
412 "Unable to parse PDBFunc: {0}");
413 return nullptr;
414 }
415
416 auto ts = *type_system_or_err;
417 TypeSystemClang *clang_type_system =
418 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
419 if (!clang_type_system)
420 return nullptr;
421 clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func);
422
423 return func_sp.get();
424}
425
427 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
428 size_t func_added = 0;
429 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
430 if (!compiland_up)
431 return 0;
432 auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
433 if (!results_up)
434 return 0;
435 while (auto pdb_func_up = results_up->getNext()) {
436 auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId());
437 if (!func_sp) {
438 if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit))
439 ++func_added;
440 }
441 }
442 return func_added;
443}
444
446 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
447 if (comp_unit.GetLineTable())
448 return true;
449 return ParseCompileUnitLineTable(comp_unit, 0);
450}
451
453 // PDB doesn't contain information about macros
454 return false;
455}
456
458 CompileUnit &comp_unit, lldb_private::SupportFileList &support_files) {
459
460 // In theory this is unnecessary work for us, because all of this information
461 // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
462 // second time seems like a waste. Unfortunately, there's no good way around
463 // this short of a moderate refactor since SymbolVendor depends on being able
464 // to cache this list.
465 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
466 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
467 if (!compiland_up)
468 return false;
469 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
470 if (!files || files->getChildCount() == 0)
471 return false;
472
473 while (auto file = files->getNext()) {
474 FileSpec spec(file->getFileName(), FileSpec::Style::windows);
475 support_files.AppendIfUnique(spec);
476 }
477
478 return true;
479}
480
483 std::vector<SourceModule> &imported_modules) {
484 // PDB does not yet support module debug info
485 return false;
486}
487
489 uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol,
490 lldb_private::Block *parent_block, bool is_top_parent) {
491 assert(pdb_symbol && parent_block);
492
493 size_t num_added = 0;
494
495 if (!is_top_parent) {
496 // Ranges for the top block were parsed together with the function.
497 if (pdb_symbol->getSymTag() != PDB_SymType::Block)
498 return num_added;
499
500 auto &raw_sym = pdb_symbol->getRawSymbol();
501 assert(llvm::isa<PDBSymbolBlock>(pdb_symbol));
502 auto uid = pdb_symbol->getSymIndexId();
503 if (parent_block->FindBlockByID(uid))
504 return num_added;
505 if (raw_sym.getVirtualAddress() < func_file_vm_addr)
506 return num_added;
507
508 Block *block = parent_block->CreateChild(pdb_symbol->getSymIndexId()).get();
509 block->AddRange(Block::Range(
510 raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
511 block->FinalizeRanges();
512 }
513 auto results_up = pdb_symbol->findAllChildren();
514 if (!results_up)
515 return num_added;
516
517 while (auto symbol_up = results_up->getNext()) {
519 func_file_vm_addr, symbol_up.get(), parent_block, false);
520 }
521 return num_added;
522}
523
525 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
526 size_t num_added = 0;
527 auto uid = func.GetID();
528 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
529 if (!pdb_func_up)
530 return 0;
531 Block &parent_block = func.GetBlock(false);
533 pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true);
534 return num_added;
535}
536
538 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
539
540 size_t num_added = 0;
541 auto compiland = GetPDBCompilandByUID(comp_unit.GetID());
542 if (!compiland)
543 return 0;
544
545 auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
546 std::unique_ptr<IPDBEnumSymbols> results;
547 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
548 PDB_SymType::UDT};
549 for (auto tag : tags_to_search) {
550 results = raw_sym.findAllChildren(tag);
551 if (!results || results->getChildCount() == 0)
552 continue;
553 while (auto symbol = results->getNext()) {
554 switch (symbol->getSymTag()) {
555 case PDB_SymType::Enum:
556 case PDB_SymType::UDT:
557 case PDB_SymType::Typedef:
558 break;
559 default:
560 continue;
561 }
562
563 // This should cause the type to get cached and stored in the `m_types`
564 // lookup.
565 if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
566 // Resolve the type completely to avoid a completion
567 // (and so a list change, which causes an iterators invalidation)
568 // during a TypeList dumping
569 type->GetFullCompilerType();
570 ++num_added;
571 }
572 }
573 }
574 };
575
576 ParseTypesByTagFn(*compiland);
577
578 // Also parse global types particularly coming from this compiland.
579 // Unfortunately, PDB has no compiland information for each global type. We
580 // have to parse them all. But ensure we only do this once.
581 static bool parse_all_global_types = false;
582 if (!parse_all_global_types) {
583 ParseTypesByTagFn(*m_global_scope_up);
584 parse_all_global_types = true;
585 }
586 return num_added;
587}
588
589size_t
591 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
592 if (!sc.comp_unit)
593 return 0;
594
595 size_t num_added = 0;
596 if (sc.function) {
597 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
598 sc.function->GetID());
599 if (!pdb_func)
600 return 0;
601
602 num_added += ParseVariables(sc, *pdb_func);
603 sc.function->GetBlock(false).SetDidParseVariables(true, true);
604 } else if (sc.comp_unit) {
605 auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
606 if (!compiland)
607 return 0;
608
609 if (sc.comp_unit->GetVariableList(false))
610 return 0;
611
612 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
613 if (results && results->getChildCount()) {
614 while (auto result = results->getNext()) {
615 auto cu_id = GetCompilandId(*result);
616 // FIXME: We are not able to determine variable's compile unit.
617 if (cu_id == 0)
618 continue;
619
620 if (cu_id == sc.comp_unit->GetID())
621 num_added += ParseVariables(sc, *result);
622 }
623 }
624
625 // FIXME: A `file static` or `global constant` variable appears both in
626 // compiland's children and global scope's children with unexpectedly
627 // different symbol's Id making it ambiguous.
628
629 // FIXME: 'local constant', for example, const char var[] = "abc", declared
630 // in a function scope, can't be found in PDB.
631
632 // Parse variables in this compiland.
633 num_added += ParseVariables(sc, *compiland);
634 }
635
636 return num_added;
637}
638
640 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
641 auto find_result = m_types.find(type_uid);
642 if (find_result != m_types.end())
643 return find_result->second.get();
644
645 auto type_system_or_err =
647 if (auto err = type_system_or_err.takeError()) {
648 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
649 "Unable to ResolveTypeUID: {0}");
650 return nullptr;
651 }
652
653 auto ts = *type_system_or_err;
654 TypeSystemClang *clang_type_system =
655 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
656 if (!clang_type_system)
657 return nullptr;
658 PDBASTParser *pdb = clang_type_system->GetPDBParser();
659 if (!pdb)
660 return nullptr;
661
662 auto pdb_type = m_session_up->getSymbolById(type_uid);
663 if (pdb_type == nullptr)
664 return nullptr;
665
666 lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
667 if (result) {
668 m_types.insert(std::make_pair(type_uid, result));
669 }
670 return result.get();
671}
672
673std::optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
674 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
675 return std::nullopt;
676}
677
679 std::lock_guard<std::recursive_mutex> guard(
680 GetObjectFile()->GetModule()->GetMutex());
681
682 auto type_system_or_err =
684 if (auto err = type_system_or_err.takeError()) {
685 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
686 "Unable to get dynamic array info for UID: {0}");
687 return false;
688 }
689 auto ts = *type_system_or_err;
690 TypeSystemClang *clang_ast_ctx =
691 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
692
693 if (!clang_ast_ctx)
694 return false;
695
696 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
697 if (!pdb)
698 return false;
699
700 return pdb->CompleteTypeFromPDB(compiler_type);
701}
702
704 auto type_system_or_err =
706 if (auto err = type_system_or_err.takeError()) {
707 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
708 "Unable to get decl for UID: {0}");
709 return CompilerDecl();
710 }
711 auto ts = *type_system_or_err;
712 TypeSystemClang *clang_ast_ctx =
713 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
714 if (!clang_ast_ctx)
715 return CompilerDecl();
716
717 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
718 if (!pdb)
719 return CompilerDecl();
720
721 auto symbol = m_session_up->getSymbolById(uid);
722 if (!symbol)
723 return CompilerDecl();
724
725 auto decl = pdb->GetDeclForSymbol(*symbol);
726 if (!decl)
727 return CompilerDecl();
728
729 return clang_ast_ctx->GetCompilerDecl(decl);
730}
731
734 auto type_system_or_err =
736 if (auto err = type_system_or_err.takeError()) {
737 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
738 "Unable to get DeclContext for UID: {0}");
739 return CompilerDeclContext();
740 }
741
742 auto ts = *type_system_or_err;
743 TypeSystemClang *clang_ast_ctx =
744 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
745 if (!clang_ast_ctx)
746 return CompilerDeclContext();
747
748 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
749 if (!pdb)
750 return CompilerDeclContext();
751
752 auto symbol = m_session_up->getSymbolById(uid);
753 if (!symbol)
754 return CompilerDeclContext();
755
756 auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
757 if (!decl_context)
758 return GetDeclContextContainingUID(uid);
759
760 return clang_ast_ctx->CreateDeclContext(decl_context);
761}
762
765 auto type_system_or_err =
767 if (auto err = type_system_or_err.takeError()) {
768 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
769 "Unable to get DeclContext containing UID: {0}");
770 return CompilerDeclContext();
771 }
772
773 auto ts = *type_system_or_err;
774 TypeSystemClang *clang_ast_ctx =
775 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
776 if (!clang_ast_ctx)
777 return CompilerDeclContext();
778
779 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
780 if (!pdb)
781 return CompilerDeclContext();
782
783 auto symbol = m_session_up->getSymbolById(uid);
784 if (!symbol)
785 return CompilerDeclContext();
786
787 auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
788 assert(decl_context);
789
790 return clang_ast_ctx->CreateDeclContext(decl_context);
791}
792
795 auto type_system_or_err =
797 if (auto err = type_system_or_err.takeError()) {
798 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
799 "Unable to parse decls for context: {0}");
800 return;
801 }
802
803 auto ts = *type_system_or_err;
804 TypeSystemClang *clang_ast_ctx =
805 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
806 if (!clang_ast_ctx)
807 return;
808
809 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
810 if (!pdb)
811 return;
812
813 pdb->ParseDeclsForDeclContext(
814 static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
815}
816
817uint32_t
819 SymbolContextItem resolve_scope,
821 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
822 uint32_t resolved_flags = 0;
823 if (resolve_scope & eSymbolContextCompUnit ||
824 resolve_scope & eSymbolContextVariable ||
825 resolve_scope & eSymbolContextFunction ||
826 resolve_scope & eSymbolContextBlock ||
827 resolve_scope & eSymbolContextLineEntry) {
828 auto cu_sp = GetCompileUnitContainsAddress(so_addr);
829 if (!cu_sp) {
830 if (resolved_flags & eSymbolContextVariable) {
831 // TODO: Resolve variables
832 }
833 return 0;
834 }
835 sc.comp_unit = cu_sp.get();
836 resolved_flags |= eSymbolContextCompUnit;
837 lldbassert(sc.module_sp == cu_sp->GetModule());
838 }
839
840 if (resolve_scope & eSymbolContextFunction ||
841 resolve_scope & eSymbolContextBlock) {
842 addr_t file_vm_addr = so_addr.GetFileAddress();
843 auto symbol_up =
844 m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
845 if (symbol_up) {
846 auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
847 assert(pdb_func);
848 auto func_uid = pdb_func->getSymIndexId();
849 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
850 if (sc.function == nullptr)
851 sc.function =
853 if (sc.function) {
854 resolved_flags |= eSymbolContextFunction;
855 if (resolve_scope & eSymbolContextBlock) {
856 auto block_symbol = m_session_up->findSymbolByAddress(
857 file_vm_addr, PDB_SymType::Block);
858 auto block_id = block_symbol ? block_symbol->getSymIndexId()
859 : sc.function->GetID();
860 sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
861 if (sc.block)
862 resolved_flags |= eSymbolContextBlock;
863 }
864 }
865 }
866 }
867
868 if (resolve_scope & eSymbolContextLineEntry) {
869 if (auto *line_table = sc.comp_unit->GetLineTable()) {
870 Address addr(so_addr);
871 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
872 resolved_flags |= eSymbolContextLineEntry;
873 }
874 }
875
876 return resolved_flags;
877}
878
880 const lldb_private::SourceLocationSpec &src_location_spec,
881 SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
882 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
883 const size_t old_size = sc_list.GetSize();
884 const FileSpec &file_spec = src_location_spec.GetFileSpec();
885 const uint32_t line = src_location_spec.GetLine().value_or(0);
886 if (resolve_scope & lldb::eSymbolContextCompUnit) {
887 // Locate all compilation units with line numbers referencing the specified
888 // file. For example, if `file_spec` is <vector>, then this should return
889 // all source files and header files that reference <vector>, either
890 // directly or indirectly.
891 auto compilands = m_session_up->findCompilandsForSourceFile(
892 file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
893
894 if (!compilands)
895 return 0;
896
897 // For each one, either find its previously parsed data or parse it afresh
898 // and add it to the symbol context list.
899 while (auto compiland = compilands->getNext()) {
900 // If we're not checking inlines, then don't add line information for
901 // this file unless the FileSpec matches. For inline functions, we don't
902 // have to match the FileSpec since they could be defined in headers
903 // other than file specified in FileSpec.
904 if (!src_location_spec.GetCheckInlines()) {
905 std::string source_file = compiland->getSourceFileFullPath();
906 if (source_file.empty())
907 continue;
908 FileSpec this_spec(source_file, FileSpec::Style::windows);
909 bool need_full_match = !file_spec.GetDirectory().IsEmpty();
910 if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
911 continue;
912 }
913
914 SymbolContext sc;
915 auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
916 if (!cu)
917 continue;
918 sc.comp_unit = cu.get();
919 sc.module_sp = cu->GetModule();
920
921 // If we were asked to resolve line entries, add all entries to the line
922 // table that match the requested line (or all lines if `line` == 0).
923 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
924 eSymbolContextLineEntry)) {
925 bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line);
926
927 if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
928 // The query asks for line entries, but we can't get them for the
929 // compile unit. This is not normal for `line` = 0. So just assert
930 // it.
931 assert(line && "Couldn't get all line entries!\n");
932
933 // Current compiland does not have the requested line. Search next.
934 continue;
935 }
936
937 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
938 if (!has_line_table)
939 continue;
940
941 auto *line_table = sc.comp_unit->GetLineTable();
942 lldbassert(line_table);
943
944 uint32_t num_line_entries = line_table->GetSize();
945 // Skip the terminal line entry.
946 --num_line_entries;
947
948 // If `line `!= 0, see if we can resolve function for each line entry
949 // in the line table.
950 for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
951 ++line_idx) {
952 if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
953 continue;
954
955 auto file_vm_addr =
957 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
958 continue;
959
960 auto symbol_up = m_session_up->findSymbolByAddress(
961 file_vm_addr, PDB_SymType::Function);
962 if (symbol_up) {
963 auto func_uid = symbol_up->getSymIndexId();
964 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
965 if (sc.function == nullptr) {
966 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
967 assert(pdb_func);
969 *sc.comp_unit);
970 }
971 if (sc.function && (resolve_scope & eSymbolContextBlock)) {
972 Block &block = sc.function->GetBlock(true);
973 sc.block = block.FindBlockByID(sc.function->GetID());
974 }
975 }
976 sc_list.Append(sc);
977 }
978 } else if (has_line_table) {
979 // We can parse line table for the compile unit. But no query to
980 // resolve function or block. We append `sc` to the list anyway.
981 sc_list.Append(sc);
982 }
983 } else {
984 // No query for line entry, function or block. But we have a valid
985 // compile unit, append `sc` to the list.
986 sc_list.Append(sc);
987 }
988 }
989 }
990 return sc_list.GetSize() - old_size;
991}
992
993std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
994 // Cache public names at first
995 if (m_public_names.empty())
996 if (auto result_up =
997 m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
998 while (auto symbol_up = result_up->getNext())
999 if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
1000 m_public_names[addr] = symbol_up->getRawSymbol().getName();
1001
1002 // Look up the name in the cache
1003 return m_public_names.lookup(pdb_data.getVirtualAddress());
1004}
1005
1008 const llvm::pdb::PDBSymbolData &pdb_data) {
1009 VariableSP var_sp;
1010 uint32_t var_uid = pdb_data.getSymIndexId();
1011 auto result = m_variables.find(var_uid);
1012 if (result != m_variables.end())
1013 return result->second;
1014
1016 bool is_static_member = false;
1017 bool is_external = false;
1018 bool is_artificial = false;
1019
1020 switch (pdb_data.getDataKind()) {
1021 case PDB_DataKind::Global:
1023 is_external = true;
1024 break;
1025 case PDB_DataKind::Local:
1027 break;
1028 case PDB_DataKind::FileStatic:
1030 break;
1031 case PDB_DataKind::StaticMember:
1032 is_static_member = true;
1034 break;
1035 case PDB_DataKind::Member:
1037 break;
1038 case PDB_DataKind::Param:
1040 break;
1041 case PDB_DataKind::Constant:
1042 scope = eValueTypeConstResult;
1043 break;
1044 default:
1045 break;
1046 }
1047
1048 switch (pdb_data.getLocationType()) {
1049 case PDB_LocType::TLS:
1051 break;
1052 case PDB_LocType::RegRel: {
1053 // It is a `this` pointer.
1054 if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
1056 is_artificial = true;
1057 }
1058 } break;
1059 default:
1060 break;
1061 }
1062
1063 Declaration decl;
1064 if (!is_artificial && !pdb_data.isCompilerGenerated()) {
1065 if (auto lines = pdb_data.getLineNumbers()) {
1066 if (auto first_line = lines->getNext()) {
1067 uint32_t src_file_id = first_line->getSourceFileId();
1068 auto src_file = m_session_up->getSourceFileById(src_file_id);
1069 if (src_file) {
1070 FileSpec spec(src_file->getFileName());
1071 decl.SetFile(spec);
1072 decl.SetColumn(first_line->getColumnNumber());
1073 decl.SetLine(first_line->getLineNumber());
1074 }
1075 }
1076 }
1077 }
1078
1079 Variable::RangeList ranges;
1080 SymbolContextScope *context_scope = sc.comp_unit;
1081 if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) {
1082 if (sc.function) {
1083 Block &function_block = sc.function->GetBlock(true);
1084 Block *block =
1085 function_block.FindBlockByID(pdb_data.getLexicalParentId());
1086 if (!block)
1087 block = &function_block;
1088
1089 context_scope = block;
1090
1091 for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges;
1092 ++i) {
1093 AddressRange range;
1094 if (!block->GetRangeAtIndex(i, range))
1095 continue;
1096
1097 ranges.Append(range.GetBaseAddress().GetFileAddress(),
1098 range.GetByteSize());
1099 }
1100 }
1101 }
1102
1103 SymbolFileTypeSP type_sp =
1104 std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
1105
1106 auto var_name = pdb_data.getName();
1107 auto mangled = GetMangledForPDBData(pdb_data);
1108 auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
1109
1110 bool is_constant;
1111 ModuleSP module_sp = GetObjectFile()->GetModule();
1112 DWARFExpressionList location(module_sp,
1114 module_sp, pdb_data, ranges, is_constant),
1115 nullptr);
1116
1117 var_sp = std::make_shared<Variable>(
1118 var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
1119 ranges, &decl, location, is_external, is_artificial, is_constant,
1120 is_static_member);
1121
1122 m_variables.insert(std::make_pair(var_uid, var_sp));
1123 return var_sp;
1124}
1125
1126size_t
1128 const llvm::pdb::PDBSymbol &pdb_symbol,
1129 lldb_private::VariableList *variable_list) {
1130 size_t num_added = 0;
1131
1132 if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
1133 VariableListSP local_variable_list_sp;
1134
1135 auto result = m_variables.find(pdb_data->getSymIndexId());
1136 if (result != m_variables.end()) {
1137 if (variable_list)
1138 variable_list->AddVariableIfUnique(result->second);
1139 } else {
1140 // Prepare right VariableList for this variable.
1141 if (auto lexical_parent = pdb_data->getLexicalParent()) {
1142 switch (lexical_parent->getSymTag()) {
1143 case PDB_SymType::Exe:
1144 assert(sc.comp_unit);
1145 [[fallthrough]];
1146 case PDB_SymType::Compiland: {
1147 if (sc.comp_unit) {
1148 local_variable_list_sp = sc.comp_unit->GetVariableList(false);
1149 if (!local_variable_list_sp) {
1150 local_variable_list_sp = std::make_shared<VariableList>();
1151 sc.comp_unit->SetVariableList(local_variable_list_sp);
1152 }
1153 }
1154 } break;
1155 case PDB_SymType::Block:
1156 case PDB_SymType::Function: {
1157 if (sc.function) {
1158 Block *block = sc.function->GetBlock(true).FindBlockByID(
1159 lexical_parent->getSymIndexId());
1160 if (block) {
1161 local_variable_list_sp = block->GetBlockVariableList(false);
1162 if (!local_variable_list_sp) {
1163 local_variable_list_sp = std::make_shared<VariableList>();
1164 block->SetVariableList(local_variable_list_sp);
1165 }
1166 }
1167 }
1168 } break;
1169 default:
1170 break;
1171 }
1172 }
1173
1174 if (local_variable_list_sp) {
1175 if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1176 local_variable_list_sp->AddVariableIfUnique(var_sp);
1177 if (variable_list)
1178 variable_list->AddVariableIfUnique(var_sp);
1179 ++num_added;
1181 if (ast)
1182 ast->GetDeclForSymbol(*pdb_data);
1183 }
1184 }
1185 }
1186 }
1187
1188 if (auto results = pdb_symbol.findAllChildren()) {
1189 while (auto result = results->getNext())
1190 num_added += ParseVariables(sc, *result, variable_list);
1191 }
1192
1193 return num_added;
1194}
1195
1197 lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx,
1198 uint32_t max_matches, lldb_private::VariableList &variables) {
1199 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1200 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1201 return;
1202 if (name.IsEmpty())
1203 return;
1204
1205 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1206 if (!results)
1207 return;
1208
1209 uint32_t matches = 0;
1210 size_t old_size = variables.GetSize();
1211 while (auto result = results->getNext()) {
1212 auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1213 if (max_matches > 0 && matches >= max_matches)
1214 break;
1215
1216 SymbolContext sc;
1217 sc.module_sp = m_objfile_sp->GetModule();
1218 lldbassert(sc.module_sp.get());
1219
1220 if (name.GetStringRef() !=
1221 MSVCUndecoratedNameParser::DropScope(pdb_data->getName()))
1222 continue;
1223
1224 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1225 // FIXME: We are not able to determine the compile unit.
1226 if (sc.comp_unit == nullptr)
1227 continue;
1228
1229 if (parent_decl_ctx.IsValid() &&
1230 GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx)
1231 continue;
1232
1233 ParseVariables(sc, *pdb_data, &variables);
1234 matches = variables.GetSize() - old_size;
1235 }
1236}
1237
1239 const lldb_private::RegularExpression &regex, uint32_t max_matches,
1240 lldb_private::VariableList &variables) {
1241 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1242 if (!regex.IsValid())
1243 return;
1244 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1245 if (!results)
1246 return;
1247
1248 uint32_t matches = 0;
1249 size_t old_size = variables.GetSize();
1250 while (auto pdb_data = results->getNext()) {
1251 if (max_matches > 0 && matches >= max_matches)
1252 break;
1253
1254 auto var_name = pdb_data->getName();
1255 if (var_name.empty())
1256 continue;
1257 if (!regex.Execute(var_name))
1258 continue;
1259 SymbolContext sc;
1260 sc.module_sp = m_objfile_sp->GetModule();
1261 lldbassert(sc.module_sp.get());
1262
1263 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1264 // FIXME: We are not able to determine the compile unit.
1265 if (sc.comp_unit == nullptr)
1266 continue;
1267
1268 ParseVariables(sc, *pdb_data, &variables);
1269 matches = variables.GetSize() - old_size;
1270 }
1271}
1272
1273bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1274 bool include_inlines,
1277 sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1278 if (!sc.comp_unit)
1279 return false;
1280 sc.module_sp = sc.comp_unit->GetModule();
1282 if (!sc.function)
1283 return false;
1284
1285 sc_list.Append(sc);
1286 return true;
1287}
1288
1289bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1291 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1292 if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1293 return false;
1294 return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1295}
1296
1298 if (!m_func_full_names.IsEmpty())
1299 return;
1300
1301 std::map<uint64_t, uint32_t> addr_ids;
1302
1303 if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1304 while (auto pdb_func_up = results_up->getNext()) {
1305 if (pdb_func_up->isCompilerGenerated())
1306 continue;
1307
1308 auto name = pdb_func_up->getName();
1309 auto demangled_name = pdb_func_up->getUndecoratedName();
1310 if (name.empty() && demangled_name.empty())
1311 continue;
1312
1313 auto uid = pdb_func_up->getSymIndexId();
1314 if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1315 addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1316
1317 if (auto parent = pdb_func_up->getClassParent()) {
1318
1319 // PDB have symbols for class/struct methods or static methods in Enum
1320 // Class. We won't bother to check if the parent is UDT or Enum here.
1321 m_func_method_names.Append(ConstString(name), uid);
1322
1323 // To search a method name, like NS::Class:MemberFunc, LLDB searches
1324 // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1325 // not have information of this, we extract base names and cache them
1326 // by our own effort.
1327 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1328 if (!basename.empty())
1329 m_func_base_names.Append(ConstString(basename), uid);
1330 else {
1331 m_func_base_names.Append(ConstString(name), uid);
1332 }
1333
1334 if (!demangled_name.empty())
1335 m_func_full_names.Append(ConstString(demangled_name), uid);
1336
1337 } else {
1338 // Handle not-method symbols.
1339
1340 // The function name might contain namespace, or its lexical scope.
1341 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1342 if (!basename.empty())
1343 m_func_base_names.Append(ConstString(basename), uid);
1344 else
1345 m_func_base_names.Append(ConstString(name), uid);
1346
1347 if (name == "main") {
1348 m_func_full_names.Append(ConstString(name), uid);
1349
1350 if (!demangled_name.empty() && name != demangled_name) {
1351 m_func_full_names.Append(ConstString(demangled_name), uid);
1352 m_func_base_names.Append(ConstString(demangled_name), uid);
1353 }
1354 } else if (!demangled_name.empty()) {
1355 m_func_full_names.Append(ConstString(demangled_name), uid);
1356 } else {
1357 m_func_full_names.Append(ConstString(name), uid);
1358 }
1359 }
1360 }
1361 }
1362
1363 if (auto results_up =
1364 m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1365 while (auto pub_sym_up = results_up->getNext()) {
1366 if (!pub_sym_up->isFunction())
1367 continue;
1368 auto name = pub_sym_up->getName();
1369 if (name.empty())
1370 continue;
1371
1372 if (Mangled::IsMangledName(name.c_str())) {
1373 // PDB public symbol has mangled name for its associated function.
1374 if (auto vm_addr = pub_sym_up->getVirtualAddress()) {
1375 if (auto it = addr_ids.find(vm_addr); it != addr_ids.end())
1376 // Cache mangled name.
1377 m_func_full_names.Append(ConstString(name), it->second);
1378 }
1379 }
1380 }
1381 }
1382 // Sort them before value searching is working properly
1383 m_func_full_names.Sort();
1384 m_func_full_names.SizeToFit();
1385 m_func_method_names.Sort();
1386 m_func_method_names.SizeToFit();
1387 m_func_base_names.Sort();
1388 m_func_base_names.SizeToFit();
1389}
1390
1392 const lldb_private::Module::LookupInfo &lookup_info,
1393 const lldb_private::CompilerDeclContext &parent_decl_ctx,
1394 bool include_inlines,
1396 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1397 ConstString name = lookup_info.GetLookupName();
1398 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
1399 lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1400
1401 if (name_type_mask & eFunctionNameTypeFull)
1402 name = lookup_info.GetName();
1403
1404 if (name_type_mask == eFunctionNameTypeNone)
1405 return;
1406 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1407 return;
1408 if (name.IsEmpty())
1409 return;
1410
1411 if (name_type_mask & eFunctionNameTypeFull ||
1412 name_type_mask & eFunctionNameTypeBase ||
1413 name_type_mask & eFunctionNameTypeMethod) {
1415
1416 std::set<uint32_t> resolved_ids;
1417 auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,
1418 &resolved_ids](UniqueCStringMap<uint32_t> &Names) {
1419 std::vector<uint32_t> ids;
1420 if (!Names.GetValues(name, ids))
1421 return;
1422
1423 for (uint32_t id : ids) {
1424 if (resolved_ids.find(id) != resolved_ids.end())
1425 continue;
1426
1427 if (parent_decl_ctx.IsValid() &&
1428 GetDeclContextContainingUID(id) != parent_decl_ctx)
1429 continue;
1430
1431 if (ResolveFunction(id, include_inlines, sc_list))
1432 resolved_ids.insert(id);
1433 }
1434 };
1435 if (name_type_mask & eFunctionNameTypeFull) {
1436 ResolveFn(m_func_full_names);
1437 ResolveFn(m_func_base_names);
1438 ResolveFn(m_func_method_names);
1439 }
1440 if (name_type_mask & eFunctionNameTypeBase)
1441 ResolveFn(m_func_base_names);
1442 if (name_type_mask & eFunctionNameTypeMethod)
1443 ResolveFn(m_func_method_names);
1444 }
1445}
1446
1448 bool include_inlines,
1450 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1451 if (!regex.IsValid())
1452 return;
1453
1455
1456 std::set<uint32_t> resolved_ids;
1457 auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1458 this](UniqueCStringMap<uint32_t> &Names) {
1459 std::vector<uint32_t> ids;
1460 if (Names.GetValues(regex, ids)) {
1461 for (auto id : ids) {
1462 if (resolved_ids.find(id) == resolved_ids.end())
1463 if (ResolveFunction(id, include_inlines, sc_list))
1464 resolved_ids.insert(id);
1465 }
1466 }
1467 };
1468 ResolveFn(m_func_full_names);
1469 ResolveFn(m_func_base_names);
1470}
1471
1473 const std::string &scope_qualified_name,
1474 std::vector<lldb_private::ConstString> &mangled_names) {}
1475
1477 std::set<lldb::addr_t> sym_addresses;
1478 for (size_t i = 0; i < symtab.GetNumSymbols(); i++)
1479 sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());
1480
1481 auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();
1482 if (!results)
1483 return;
1484
1485 auto section_list =
1486 m_objfile_sp->GetModule()->GetObjectFile()->GetSectionList();
1487 if (!section_list)
1488 return;
1489
1490 while (auto pub_symbol = results->getNext()) {
1491 auto section_id = pub_symbol->getAddressSection();
1492
1493 auto section = section_list->FindSectionByID(section_id);
1494 if (!section)
1495 continue;
1496
1497 auto offset = pub_symbol->getAddressOffset();
1498
1499 auto file_addr = section->GetFileAddress() + offset;
1500 if (sym_addresses.find(file_addr) != sym_addresses.end())
1501 continue;
1502 sym_addresses.insert(file_addr);
1503
1504 auto size = pub_symbol->getLength();
1505 symtab.AddSymbol(
1506 Symbol(pub_symbol->getSymIndexId(), // symID
1507 pub_symbol->getName().c_str(), // name
1508 pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type
1509 true, // external
1510 false, // is_debug
1511 false, // is_trampoline
1512 false, // is_artificial
1513 section, // section_sp
1514 offset, // value
1515 size, // size
1516 size != 0, // size_is_valid
1517 false, // contains_linker_annotations
1518 0 // flags
1519 ));
1520 }
1521
1522 symtab.Finalize();
1523}
1524
1525void SymbolFilePDB::DumpClangAST(Stream &s, llvm::StringRef filter,
1526 bool show_color) {
1527 auto type_system_or_err =
1529 if (auto err = type_system_or_err.takeError()) {
1530 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1531 "Unable to dump ClangAST: {0}");
1532 return;
1533 }
1534
1535 auto ts = *type_system_or_err;
1536 TypeSystemClang *clang_type_system =
1537 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
1538 if (!clang_type_system)
1539 return;
1540 clang_type_system->Dump(s.AsRawOstream(), filter, show_color);
1541}
1542
1544 const lldb_private::RegularExpression &regex, uint32_t max_matches,
1545 lldb_private::TypeMap &types) {
1546 // When searching by regex, we need to go out of our way to limit the search
1547 // space as much as possible since this searches EVERYTHING in the PDB,
1548 // manually doing regex comparisons. PDB library isn't optimized for regex
1549 // searches or searches across multiple symbol types at the same time, so the
1550 // best we can do is to search enums, then typedefs, then classes one by one,
1551 // and do a regex comparison against each of them.
1552 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1553 PDB_SymType::UDT};
1554 std::unique_ptr<IPDBEnumSymbols> results;
1555
1556 uint32_t matches = 0;
1557
1558 for (auto tag : tags_to_search) {
1559 results = m_global_scope_up->findAllChildren(tag);
1560 if (!results)
1561 continue;
1562
1563 while (auto result = results->getNext()) {
1564 if (max_matches > 0 && matches >= max_matches)
1565 break;
1566
1567 std::string type_name;
1568 if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1569 type_name = enum_type->getName();
1570 else if (auto typedef_type =
1571 llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1572 type_name = typedef_type->getName();
1573 else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1574 type_name = class_type->getName();
1575 else {
1576 // We're looking only for types that have names. Skip symbols, as well
1577 // as unnamed types such as arrays, pointers, etc.
1578 continue;
1579 }
1580
1581 if (!regex.Execute(type_name))
1582 continue;
1583
1584 // This should cause the type to get cached and stored in the `m_types`
1585 // lookup.
1586 if (!ResolveTypeUID(result->getSymIndexId()))
1587 continue;
1588
1589 auto iter = m_types.find(result->getSymIndexId());
1590 if (iter == m_types.end())
1591 continue;
1592 types.Insert(iter->second);
1593 ++matches;
1594 }
1595 }
1596}
1597
1599 lldb_private::TypeResults &type_results) {
1600
1601 // Make sure we haven't already searched this SymbolFile before.
1602 if (type_results.AlreadySearched(this))
1603 return;
1604
1605 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1606
1607 std::unique_ptr<IPDBEnumSymbols> results;
1608 llvm::StringRef basename = query.GetTypeBasename().GetStringRef();
1609 if (basename.empty())
1610 return;
1611 results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1612 if (!results)
1613 return;
1614
1615 while (auto result = results->getNext()) {
1616
1617 switch (result->getSymTag()) {
1618 case PDB_SymType::Enum:
1619 case PDB_SymType::UDT:
1620 case PDB_SymType::Typedef:
1621 break;
1622 default:
1623 // We're looking only for types that have names. Skip symbols, as well
1624 // as unnamed types such as arrays, pointers, etc.
1625 continue;
1626 }
1627
1629 result->getRawSymbol().getName()) != basename)
1630 continue;
1631
1632 // This should cause the type to get cached and stored in the `m_types`
1633 // lookup.
1634 if (!ResolveTypeUID(result->getSymIndexId()))
1635 continue;
1636
1637 auto iter = m_types.find(result->getSymIndexId());
1638 if (iter == m_types.end())
1639 continue;
1640 // We resolved a type. Get the fully qualified name to ensure it matches.
1641 ConstString name = iter->second->GetQualifiedName();
1642 TypeQuery type_match(name.GetStringRef(), TypeQueryOptions::e_exact_match);
1643 if (query.ContextMatches(type_match.GetContextRef())) {
1644 type_results.InsertUnique(iter->second);
1645 if (type_results.Done(query))
1646 return;
1647 }
1648 }
1649}
1650
1651void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1652 uint32_t type_mask,
1653 TypeCollection &type_collection) {
1654 bool can_parse = false;
1655 switch (pdb_symbol.getSymTag()) {
1656 case PDB_SymType::ArrayType:
1657 can_parse = ((type_mask & eTypeClassArray) != 0);
1658 break;
1659 case PDB_SymType::BuiltinType:
1660 can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1661 break;
1662 case PDB_SymType::Enum:
1663 can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1664 break;
1665 case PDB_SymType::Function:
1666 case PDB_SymType::FunctionSig:
1667 can_parse = ((type_mask & eTypeClassFunction) != 0);
1668 break;
1669 case PDB_SymType::PointerType:
1670 can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1671 eTypeClassMemberPointer)) != 0);
1672 break;
1673 case PDB_SymType::Typedef:
1674 can_parse = ((type_mask & eTypeClassTypedef) != 0);
1675 break;
1676 case PDB_SymType::UDT: {
1677 auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1678 assert(udt);
1679 can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1680 ((type_mask & (eTypeClassClass | eTypeClassStruct |
1681 eTypeClassUnion)) != 0));
1682 } break;
1683 default:
1684 break;
1685 }
1686
1687 if (can_parse) {
1688 if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1689 if (!llvm::is_contained(type_collection, type))
1690 type_collection.push_back(type);
1691 }
1692 }
1693
1694 auto results_up = pdb_symbol.findAllChildren();
1695 while (auto symbol_up = results_up->getNext())
1696 GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1697}
1698
1700 TypeClass type_mask,
1701 lldb_private::TypeList &type_list) {
1702 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1703 TypeCollection type_collection;
1704 CompileUnit *cu =
1705 sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1706 if (cu) {
1707 auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1708 if (!compiland_up)
1709 return;
1710 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1711 } else {
1712 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1713 auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1714 if (cu_sp) {
1715 if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1716 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1717 }
1718 }
1719 }
1720
1721 for (auto type : type_collection) {
1722 type->GetForwardCompilerType();
1723 type_list.Insert(type->shared_from_this());
1724 }
1725}
1726
1727llvm::Expected<lldb::TypeSystemSP>
1729 auto type_system_or_err =
1730 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1731 if (type_system_or_err) {
1732 if (auto ts = *type_system_or_err)
1733 ts->SetSymbolFile(this);
1734 }
1735 return type_system_or_err;
1736}
1737
1739 auto type_system_or_err =
1741 if (auto err = type_system_or_err.takeError()) {
1742 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1743 "Unable to get PDB AST parser: {0}");
1744 return nullptr;
1745 }
1746
1747 auto ts = *type_system_or_err;
1748 auto *clang_type_system =
1749 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
1750 if (!clang_type_system)
1751 return nullptr;
1752
1753 return clang_type_system->GetPDBParser();
1754}
1755
1758 const CompilerDeclContext &parent_decl_ctx, bool) {
1759 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1760 auto type_system_or_err =
1762 if (auto err = type_system_or_err.takeError()) {
1763 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1764 "Unable to find namespace {1}: {0}", name.AsCString());
1765 return CompilerDeclContext();
1766 }
1767 auto ts = *type_system_or_err;
1768 auto *clang_type_system =
1769 llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
1770 if (!clang_type_system)
1771 return CompilerDeclContext();
1772
1773 PDBASTParser *pdb = clang_type_system->GetPDBParser();
1774 if (!pdb)
1775 return CompilerDeclContext();
1776
1777 clang::DeclContext *decl_context = nullptr;
1778 if (parent_decl_ctx)
1779 decl_context = static_cast<clang::DeclContext *>(
1780 parent_decl_ctx.GetOpaqueDeclContext());
1781
1782 auto namespace_decl =
1783 pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1784 if (!namespace_decl)
1785 return CompilerDeclContext();
1786
1787 return clang_type_system->CreateDeclContext(namespace_decl);
1788}
1789
1791
1792const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1793 return *m_session_up;
1794}
1795
1797 uint32_t index) {
1798 auto found_cu = m_comp_units.find(id);
1799 if (found_cu != m_comp_units.end())
1800 return found_cu->second;
1801
1802 auto compiland_up = GetPDBCompilandByUID(id);
1803 if (!compiland_up)
1804 return CompUnitSP();
1805
1806 lldb::LanguageType lang;
1807 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1808 if (!details)
1810 else
1811 lang = TranslateLanguage(details->getLanguage());
1812
1814 return CompUnitSP();
1815
1816 std::string path = compiland_up->getSourceFileFullPath();
1817 if (path.empty())
1818 return CompUnitSP();
1819
1820 // Don't support optimized code for now, DebugInfoPDB does not return this
1821 // information.
1822 LazyBool optimized = eLazyBoolNo;
1823 auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr,
1824 path.c_str(), id, lang, optimized);
1825
1826 if (!cu_sp)
1827 return CompUnitSP();
1828
1829 m_comp_units.insert(std::make_pair(id, cu_sp));
1830 if (index == UINT32_MAX)
1831 GetCompileUnitIndex(*compiland_up, index);
1832 lldbassert(index != UINT32_MAX);
1833 SetCompileUnitAtIndex(index, cu_sp);
1834 return cu_sp;
1835}
1836
1838 uint32_t match_line) {
1839 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1840 if (!compiland_up)
1841 return false;
1842
1843 // LineEntry needs the *index* of the file into the list of support files
1844 // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us
1845 // a globally unique idenfitifier in the namespace of the PDB. So, we have
1846 // to do a mapping so that we can hand out indices.
1847 llvm::DenseMap<uint32_t, uint32_t> index_map;
1848 BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1849 auto line_table = std::make_unique<LineTable>(&comp_unit);
1850
1851 // Find contributions to `compiland` from all source and header files.
1852 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1853 if (!files)
1854 return false;
1855
1856 // For each source and header file, create a LineTable::Sequence for
1857 // contributions to the compiland from that file, and add the sequence.
1858 while (auto file = files->getNext()) {
1859 LineTable::Sequence sequence;
1860 auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1861 if (!lines)
1862 continue;
1863 int entry_count = lines->getChildCount();
1864
1865 uint64_t prev_addr;
1866 uint32_t prev_length;
1867 uint32_t prev_line;
1868 uint32_t prev_source_idx;
1869
1870 for (int i = 0; i < entry_count; ++i) {
1871 auto line = lines->getChildAtIndex(i);
1872
1873 uint64_t lno = line->getLineNumber();
1874 uint64_t addr = line->getVirtualAddress();
1875 uint32_t length = line->getLength();
1876 uint32_t source_id = line->getSourceFileId();
1877 uint32_t col = line->getColumnNumber();
1878 uint32_t source_idx = index_map[source_id];
1879
1880 // There was a gap between the current entry and the previous entry if
1881 // the addresses don't perfectly line up.
1882 bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1883
1884 // Before inserting the current entry, insert a terminal entry at the end
1885 // of the previous entry's address range if the current entry resulted in
1886 // a gap from the previous entry.
1887 if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1888 line_table->AppendLineEntryToSequence(sequence, prev_addr + prev_length,
1889 prev_line, 0, prev_source_idx,
1890 false, false, false, false, true);
1891
1892 line_table->InsertSequence(std::move(sequence));
1893 }
1894
1895 if (ShouldAddLine(match_line, lno, length)) {
1896 bool is_statement = line->isStatement();
1897 bool is_prologue = false;
1898 bool is_epilogue = false;
1899 auto func =
1900 m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1901 if (func) {
1902 auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1903 if (prologue)
1904 is_prologue = (addr == prologue->getVirtualAddress());
1905
1906 auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1907 if (epilogue)
1908 is_epilogue = (addr == epilogue->getVirtualAddress());
1909 }
1910
1911 line_table->AppendLineEntryToSequence(sequence, addr, lno, col,
1912 source_idx, is_statement, false,
1913 is_prologue, is_epilogue, false);
1914 }
1915
1916 prev_addr = addr;
1917 prev_length = length;
1918 prev_line = lno;
1919 prev_source_idx = source_idx;
1920 }
1921
1922 if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1923 // The end is always a terminal entry, so insert it regardless.
1924 line_table->AppendLineEntryToSequence(sequence, prev_addr + prev_length,
1925 prev_line, 0, prev_source_idx,
1926 false, false, false, false, true);
1927 }
1928
1929 line_table->InsertSequence(std::move(sequence));
1930 }
1931
1932 if (line_table->GetSize()) {
1933 comp_unit.SetLineTable(line_table.release());
1934 return true;
1935 }
1936 return false;
1937}
1938
1940 const PDBSymbolCompiland &compiland,
1941 llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1942 // This is a hack, but we need to convert the source id into an index into
1943 // the support files array. We don't want to do path comparisons to avoid
1944 // basename / full path issues that may or may not even be a problem, so we
1945 // use the globally unique source file identifiers. Ideally we could use the
1946 // global identifiers everywhere, but LineEntry currently assumes indices.
1947 auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1948 if (!source_files)
1949 return;
1950
1951 int index = 0;
1952 while (auto file = source_files->getNext()) {
1953 uint32_t source_id = file->getUniqueId();
1954 index_map[source_id] = index++;
1955 }
1956}
1957
1959 const lldb_private::Address &so_addr) {
1960 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1961 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1962 return nullptr;
1963
1964 // If it is a PDB function's vm addr, this is the first sure bet.
1965 if (auto lines =
1966 m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1967 if (auto first_line = lines->getNext())
1968 return ParseCompileUnitForUID(first_line->getCompilandId());
1969 }
1970
1971 // Otherwise we resort to section contributions.
1972 if (auto sec_contribs = m_session_up->getSectionContribs()) {
1973 while (auto section = sec_contribs->getNext()) {
1974 auto va = section->getVirtualAddress();
1975 if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1976 return ParseCompileUnitForUID(section->getCompilandId());
1977 }
1978 }
1979 return nullptr;
1980}
1981
1982Mangled
1983SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1984 Mangled mangled;
1985 auto func_name = pdb_func.getName();
1986 auto func_undecorated_name = pdb_func.getUndecoratedName();
1987 std::string func_decorated_name;
1988
1989 // Seek from public symbols for non-static function's decorated name if any.
1990 // For static functions, they don't have undecorated names and aren't exposed
1991 // in Public Symbols either.
1992 if (!func_undecorated_name.empty()) {
1993 auto result_up = m_global_scope_up->findChildren(
1994 PDB_SymType::PublicSymbol, func_undecorated_name,
1995 PDB_NameSearchFlags::NS_UndecoratedName);
1996 if (result_up) {
1997 while (auto symbol_up = result_up->getNext()) {
1998 // For a public symbol, it is unique.
1999 lldbassert(result_up->getChildCount() == 1);
2000 if (auto *pdb_public_sym =
2001 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
2002 symbol_up.get())) {
2003 if (pdb_public_sym->isFunction()) {
2004 func_decorated_name = pdb_public_sym->getName();
2005 break;
2006 }
2007 }
2008 }
2009 }
2010 }
2011 if (!func_decorated_name.empty()) {
2012 mangled.SetMangledName(ConstString(func_decorated_name));
2013
2014 // For MSVC, format of C function's decorated name depends on calling
2015 // convention. Unfortunately none of the format is recognized by current
2016 // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
2017 // `__purecall` is retrieved as both its decorated and undecorated name
2018 // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
2019 // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
2020 // Mangled::GetDemangledName method will fail internally and caches an
2021 // empty string as its undecorated name. So we will face a contradiction
2022 // here for the same symbol:
2023 // non-empty undecorated name from PDB
2024 // empty undecorated name from LLDB
2025 if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty())
2026 mangled.SetDemangledName(ConstString(func_undecorated_name));
2027
2028 // LLDB uses several flags to control how a C++ decorated name is
2029 // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
2030 // yielded name could be different from what we retrieve from
2031 // PDB source unless we also apply same flags in getting undecorated
2032 // name through PDBSymbolFunc::getUndecoratedNameEx method.
2033 if (!func_undecorated_name.empty() &&
2034 mangled.GetDemangledName() != ConstString(func_undecorated_name))
2035 mangled.SetDemangledName(ConstString(func_undecorated_name));
2036 } else if (!func_undecorated_name.empty()) {
2037 mangled.SetDemangledName(ConstString(func_undecorated_name));
2038 } else if (!func_name.empty())
2039 mangled.SetValue(ConstString(func_name));
2040
2041 return mangled;
2042}
2043
2045 const lldb_private::CompilerDeclContext &decl_ctx) {
2046 if (!decl_ctx.IsValid())
2047 return true;
2048
2049 TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
2050 if (!decl_ctx_type_system)
2051 return false;
2052 auto type_system_or_err = GetTypeSystemForLanguage(
2053 decl_ctx_type_system->GetMinimumLanguage(nullptr));
2054 if (auto err = type_system_or_err.takeError()) {
2056 GetLog(LLDBLog::Symbols), std::move(err),
2057 "Unable to determine if DeclContext matches this symbol file: {0}");
2058 return false;
2059 }
2060
2061 if (decl_ctx_type_system == type_system_or_err->get())
2062 return true; // The type systems match, return true
2063
2064 return false;
2065}
2066
2067uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
2068 static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
2069 return lhs < rhs.Offset;
2070 };
2071
2072 // Cache section contributions
2073 if (m_sec_contribs.empty()) {
2074 if (auto SecContribs = m_session_up->getSectionContribs()) {
2075 while (auto SectionContrib = SecContribs->getNext()) {
2076 auto comp_id = SectionContrib->getCompilandId();
2077 if (!comp_id)
2078 continue;
2079
2080 auto sec = SectionContrib->getAddressSection();
2081 auto &sec_cs = m_sec_contribs[sec];
2082
2083 auto offset = SectionContrib->getAddressOffset();
2084 auto it = llvm::upper_bound(sec_cs, offset, pred_upper);
2085
2086 auto size = SectionContrib->getLength();
2087 sec_cs.insert(it, {offset, size, comp_id});
2088 }
2089 }
2090 }
2091
2092 // Check by line number
2093 if (auto Lines = data.getLineNumbers()) {
2094 if (auto FirstLine = Lines->getNext())
2095 return FirstLine->getCompilandId();
2096 }
2097
2098 // Retrieve section + offset
2099 uint32_t DataSection = data.getAddressSection();
2100 uint32_t DataOffset = data.getAddressOffset();
2101 if (DataSection == 0) {
2102 if (auto RVA = data.getRelativeVirtualAddress())
2103 m_session_up->addressForRVA(RVA, DataSection, DataOffset);
2104 }
2105
2106 if (DataSection) {
2107 // Search by section contributions
2108 auto &sec_cs = m_sec_contribs[DataSection];
2109 auto it = llvm::upper_bound(sec_cs, DataOffset, pred_upper);
2110 if (it != sec_cs.begin()) {
2111 --it;
2112 if (DataOffset < it->Offset + it->Size)
2113 return it->CompilandId;
2114 }
2115 } else {
2116 // Search in lexical tree
2117 auto LexParentId = data.getLexicalParentId();
2118 while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
2119 if (LexParent->getSymTag() == PDB_SymType::Exe)
2120 break;
2121 if (LexParent->getSymTag() == PDB_SymType::Compiland)
2122 return LexParentId;
2123 LexParentId = LexParent->getRawSymbol().getLexicalParentId();
2124 }
2125 }
2126
2127 return 0;
2128}
static llvm::raw_ostream & error(Stream &strm)
static PluginProperties & GetGlobalPluginProperties()
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:399
DWARFExpression ConvertPDBLocationToDWARFExpression(ModuleSP module, const PDBSymbolData &symbol, const Variable::RangeList &ranges, bool &is_constant)
#define LLDB_PLUGIN_DEFINE(PluginName)
static lldb::LanguageType TranslateLanguage(PDB_Lang lang)
static size_t ParseFunctionBlocksForPDBSymbol(uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol, lldb_private::Block *parent_block, bool is_top_parent)
static llvm::StringRef DropScope(llvm::StringRef name)
clang::Decl * GetDeclForSymbol(const llvm::pdb::PDBSymbol &symbol)
lldb_private::CompilerDeclContext GetDeclContextContainingUID(lldb::user_id_t uid) override
std::unique_ptr< llvm::pdb::PDBSymbolCompiland > GetPDBCompilandByUID(uint32_t uid)
static lldb_private::SymbolFile * CreateInstance(lldb::ObjectFileSP objfile_sp)
void DumpClangAST(lldb_private::Stream &s, llvm::StringRef filter, bool show_color) override
std::unique_ptr< llvm::pdb::IPDBSession > m_session_up
lldb::CompUnitSP GetCompileUnitContainsAddress(const lldb_private::Address &so_addr)
void GetMangledNamesForFunction(const std::string &scope_qualified_name, std::vector< lldb_private::ConstString > &mangled_names) override
void GetTypes(lldb_private::SymbolContextScope *sc_scope, lldb::TypeClass type_mask, lldb_private::TypeList &type_list) override
void FindFunctions(const lldb_private::Module::LookupInfo &lookup_info, const lldb_private::CompilerDeclContext &parent_decl_ctx, bool include_inlines, lldb_private::SymbolContextList &sc_list) override
lldb_private::CompilerDeclContext FindNamespace(lldb_private::ConstString name, const lldb_private::CompilerDeclContext &parent_decl_ctx, bool only_root_namespaces) override
Finds a namespace of name name and whose parent context is parent_decl_ctx.
std::unique_ptr< llvm::pdb::PDBSymbolExe > m_global_scope_up
llvm::DenseMap< uint32_t, lldb::CompUnitSP > m_comp_units
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.
size_t ParseTypes(lldb_private::CompileUnit &comp_unit) override
static llvm::StringRef GetPluginNameStatic()
bool ParseCompileUnitLineTable(lldb_private::CompileUnit &comp_unit, uint32_t match_line)
void BuildSupportFileIdToSupportFileIndexMap(const llvm::pdb::PDBSymbolCompiland &pdb_compiland, llvm::DenseMap< uint32_t, uint32_t > &index_map) const
lldb_private::Function * ParseCompileUnitFunctionForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func, lldb_private::CompileUnit &comp_unit)
lldb_private::UniqueCStringMap< uint32_t > m_func_base_names
bool ParseImportedModules(const lldb_private::SymbolContext &sc, std::vector< lldb_private::SourceModule > &imported_modules) override
void FindGlobalVariables(lldb_private::ConstString name, const lldb_private::CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, lldb_private::VariableList &variables) override
size_t ParseVariablesForContext(const lldb_private::SymbolContext &sc) override
static void Initialize()
bool ParseLineTable(lldb_private::CompileUnit &comp_unit) override
void GetCompileUnitIndex(const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index)
llvm::DenseMap< uint32_t, lldb::TypeSP > m_types
void AddSymbols(lldb_private::Symtab &symtab) override
size_t ParseBlocksRecursive(lldb_private::Function &func) override
llvm::DenseMap< uint64_t, std::string > m_public_names
size_t ParseVariables(const lldb_private::SymbolContext &sc, const llvm::pdb::PDBSymbol &pdb_data, lldb_private::VariableList *variable_list=nullptr)
lldb::LanguageType ParseLanguage(lldb_private::CompileUnit &comp_unit) override
bool ParseDebugMacros(lldb_private::CompileUnit &comp_unit) override
void InitializeObject() override
Initialize the SymbolFile object.
static bool UseNativePDB()
uint32_t ResolveSymbolContext(const lldb_private::Address &so_addr, lldb::SymbolContextItem resolve_scope, lldb_private::SymbolContext &sc) override
PDBASTParser * GetPDBAstParser()
uint32_t CalculateNumCompileUnits() override
SymbolFilePDB(lldb::ObjectFileSP objfile_sp)
~SymbolFilePDB() override
uint32_t GetCompilandId(const llvm::pdb::PDBSymbolData &data)
llvm::pdb::IPDBSession & GetPDBSession()
bool ParseSupportFiles(lldb_private::CompileUnit &comp_unit, lldb_private::SupportFileList &support_files) override
static char ID
LLVM RTTI support.
void FindTypesByRegex(const lldb_private::RegularExpression &regex, uint32_t max_matches, lldb_private::TypeMap &types)
size_t ParseFunctions(lldb_private::CompileUnit &comp_unit) override
lldb::CompUnitSP ParseCompileUnitForUID(uint32_t id, uint32_t index=UINT32_MAX)
lldb_private::Mangled GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func)
std::vector< lldb_private::Type * > TypeCollection
void ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx) override
void GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol, uint32_t type_mask, TypeCollection &type_collection)
bool CompleteType(lldb_private::CompilerType &compiler_type) override
static void DebuggerInitialize(lldb_private::Debugger &debugger)
static llvm::StringRef GetPluginDescriptionStatic()
lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override
std::string GetMangledForPDBData(const llvm::pdb::PDBSymbolData &pdb_data)
lldb_private::Type * ResolveTypeUID(lldb::user_id_t type_uid) override
lldb_private::UniqueCStringMap< uint32_t > m_func_full_names
static void Terminate()
lldb_private::UniqueCStringMap< uint32_t > m_func_method_names
bool DeclContextMatchesThisSymbolFile(const lldb_private::CompilerDeclContext &decl_ctx)
lldb_private::CompilerDeclContext GetDeclContextForUID(lldb::user_id_t uid) override
void FindTypes(const lldb_private::TypeQuery &match, lldb_private::TypeResults &results) override
Find types using a type-matching object that contains all search parameters.
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language) override
SecContribsMap m_sec_contribs
lldb::VariableSP ParseVariableForPDBData(const lldb_private::SymbolContext &sc, const llvm::pdb::PDBSymbolData &pdb_data)
bool ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func, bool include_inlines, lldb_private::SymbolContextList &sc_list)
uint32_t CalculateAbilities() override
llvm::DenseMap< uint32_t, lldb::VariableSP > m_variables
lldb_private::CompilerDecl GetDeclForUID(lldb::user_id_t uid) override
A section + offset based address range class.
Address & GetBaseAddress()
Get accessor for the base address of the range.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
A class that describes a single lexical block.
Definition Block.h:41
RangeList::Entry Range
Definition Block.h:44
lldb::VariableListSP GetBlockVariableList(bool can_create)
Get the variable list for this block only.
Definition Block.cpp:392
bool GetRangeAtIndex(uint32_t range_idx, AddressRange &range)
Definition Block.cpp:294
lldb::BlockSP CreateChild(lldb::user_id_t uid)
Creates a block with the specified UID uid.
Definition Block.cpp:380
Block * FindBlockByID(lldb::user_id_t block_id)
Definition Block.cpp:113
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
Definition Block.h:319
size_t GetNumRanges() const
Definition Block.h:331
void SetDidParseVariables(bool b, bool set_children)
Definition Block.cpp:489
void AddRange(const Range &range)
Add a new offset range to this block.
Definition Block.cpp:331
void FinalizeRanges()
Definition Block.cpp:326
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.
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.
lldb::FunctionSP FindFunctionByUID(lldb::user_id_t uid)
Finds a function by user ID.
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.
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
bool IsEmpty() const
Test for empty 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 ...
A class to manage flag bits.
Definition Debugger.h:101
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
void SetLine(uint32_t line)
Set accessor for the declaration line number.
void SetColumn(uint16_t column)
Set accessor for the declaration column number.
void SetFile(const FileSpec &file_spec)
Set accessor for the declaration file specification.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
A class that describes a function.
Definition Function.h:400
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition Function.cpp:383
A class that handles mangled names.
Definition Mangled.h:34
static bool IsMangledName(llvm::StringRef name)
Definition Mangled.cpp:39
void SetDemangledName(ConstString name)
Definition Mangled.h:138
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:284
void SetMangledName(ConstString name)
Definition Mangled.h:143
void SetValue(ConstString name)
Set the string value in this object.
Definition Mangled.cpp:124
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
A class that encapsulates name lookup information.
Definition Module.h:912
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:953
ConstString GetLookupName() const
Definition Module.h:951
ConstString GetName() const
Definition Module.h:949
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool CreateSettingForSymbolFilePlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static lldb::OptionValuePropertiesSP GetSettingForSymbolFilePlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
void Append(const Entry &entry)
Definition RangeMap.h:179
bool IsValid() const
Test if this object contains a valid regular expression.
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
std::optional< uint32_t > GetLine() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:418
A list of support files for a CompileUnit.
bool AppendIfUnique(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...
virtual CompileUnit * CalculateSymbolContextCompileUnit()
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.
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
ObjectFile * GetObjectFile() override
Definition SymbolFile.h:570
lldb::ObjectFileSP m_objfile_sp
Definition SymbolFile.h:646
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
Definition SymbolFile.h:555
uint32_t GetNumCompileUnits() override
Provides public interface for all SymbolFiles.
Definition SymbolFile.h:51
virtual std::recursive_mutex & GetModuleMutex() const
Symbols file subclasses should override this to return the Module that owns the TypeSystem that this ...
lldb::addr_t GetFileAddress() const
Definition Symbol.cpp:497
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:228
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:64
size_t GetNumSymbols() const
Definition Symtab.cpp:77
void Insert(const lldb::TypeSP &type)
Definition TypeList.cpp:27
void Insert(const lldb::TypeSP &type)
Definition TypeMap.cpp:27
A class that contains all state required for type lookups.
Definition Type.h:104
std::vector< lldb_private::CompilerContext > & GetContextRef()
Access the internal compiler context array.
Definition Type.h:322
ConstString GetTypeBasename() const
Get the type basename to use when searching the type indexes in each SymbolFile object.
Definition Type.cpp:113
bool ContextMatches(llvm::ArrayRef< lldb_private::CompilerContext > context) const
Check of a CompilerContext array from matching type from a symbol file matches the m_context.
Definition Type.cpp:129
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
bool InsertUnique(const lldb::TypeSP &type_sp)
When types that match a TypeQuery are found, this API is used to insert the matching types.
Definition Type.cpp:194
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
Definition Type.cpp:200
bool AlreadySearched(lldb_private::SymbolFile *sym_file)
Check if a SymbolFile object has already been searched by this type match object.
Definition Type.cpp:190
A TypeSystem implementation based on Clang.
CompilerDecl GetCompilerDecl(clang::Decl *decl)
Creates a CompilerDecl from the given Decl with the current TypeSystemClang instance as its typesyste...
CompilerDeclContext CreateDeclContext(clang::DeclContext *ctx)
Creates a CompilerDeclContext from the given DeclContext with the current TypeSystemClang instance as...
PDBASTParser * GetPDBParser() override
void Dump(llvm::raw_ostream &output, llvm::StringRef filter, bool show_color) override
Interface for representing a type system.
Definition TypeSystem.h:70
virtual lldb::LanguageType GetMinimumLanguage(lldb::opaque_compiler_type_t type)=0
bool AddVariableIfUnique(const lldb::VariableSP &var_sp)
RangeVector< lldb::addr_t, lldb::addr_t > RangeList
Definition Variable.h:27
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
std::shared_ptr< lldb_private::Function > FunctionSP
std::shared_ptr< lldb_private::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
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::SymbolFileType > SymbolFileTypeSP
std::shared_ptr< lldb_private::Variable > VariableSP
uint64_t user_id_t
Definition lldb-types.h:82
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeConstResult
constant result variables
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
AddressRange range
The section offset address range for this line entry.
Definition LineEntry.h:137
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47