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