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