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