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