1 //===-- SymbolFilePDB.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFilePDB.h"
11 
12 #include "clang/Lex/Lexer.h"
13 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Symbol/ClangASTContext.h"
17 #include "lldb/Symbol/CompileUnit.h"
18 #include "lldb/Symbol/LineTable.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolContext.h"
21 #include "lldb/Symbol/SymbolVendor.h"
22 #include "lldb/Symbol/TypeList.h"
23 #include "lldb/Symbol/TypeMap.h"
24 #include "lldb/Symbol/Variable.h"
25 #include "lldb/Utility/RegularExpression.h"
26 
27 #include "llvm/DebugInfo/PDB/GenericError.h"
28 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
29 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
30 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
31 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
32 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
33 #include "llvm/DebugInfo/PDB/IPDBTable.h"
34 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
35 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
36 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
43 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
44 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
45 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
46 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
47 
48 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" // For IsCPPMangledName
49 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
50 #include "Plugins/SymbolFile/PDB/PDBLocationToDWARFExpression.h"
51 
52 #include <regex>
53 
54 using namespace lldb;
55 using namespace lldb_private;
56 using namespace llvm::pdb;
57 
58 namespace {
59 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
60   switch (lang) {
61   case PDB_Lang::Cpp:
62     return lldb::LanguageType::eLanguageTypeC_plus_plus;
63   case PDB_Lang::C:
64     return lldb::LanguageType::eLanguageTypeC;
65   default:
66     return lldb::LanguageType::eLanguageTypeUnknown;
67   }
68 }
69 
70 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
71                    uint32_t addr_length) {
72   return ((requested_line == 0 || actual_line == requested_line) &&
73           addr_length > 0);
74 }
75 } // namespace
76 
77 void SymbolFilePDB::Initialize() {
78   PluginManager::RegisterPlugin(GetPluginNameStatic(),
79                                 GetPluginDescriptionStatic(), CreateInstance,
80                                 DebuggerInitialize);
81 }
82 
83 void SymbolFilePDB::Terminate() {
84   PluginManager::UnregisterPlugin(CreateInstance);
85 }
86 
87 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
88 
89 lldb_private::ConstString SymbolFilePDB::GetPluginNameStatic() {
90   static ConstString g_name("pdb");
91   return g_name;
92 }
93 
94 const char *SymbolFilePDB::GetPluginDescriptionStatic() {
95   return "Microsoft PDB debug symbol file reader.";
96 }
97 
98 lldb_private::SymbolFile *
99 SymbolFilePDB::CreateInstance(lldb_private::ObjectFile *obj_file) {
100   return new SymbolFilePDB(obj_file);
101 }
102 
103 SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file)
104     : SymbolFile(object_file), m_session_up(), m_global_scope_up(),
105       m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {}
106 
107 SymbolFilePDB::~SymbolFilePDB() {}
108 
109 uint32_t SymbolFilePDB::CalculateAbilities() {
110   uint32_t abilities = 0;
111   if (!m_obj_file)
112     return 0;
113 
114   if (!m_session_up) {
115     // Lazily load and match the PDB file, but only do this once.
116     std::string exePath = m_obj_file->GetFileSpec().GetPath();
117     auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
118                                 m_session_up);
119     if (error) {
120       llvm::consumeError(std::move(error));
121       auto module_sp = m_obj_file->GetModule();
122       if (!module_sp)
123         return 0;
124       // See if any symbol file is specified through `--symfile` option.
125       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
126       if (!symfile)
127         return 0;
128       error = loadDataForPDB(PDB_ReaderType::DIA,
129                              llvm::StringRef(symfile.GetPath()), m_session_up);
130       if (error) {
131         llvm::consumeError(std::move(error));
132         return 0;
133       }
134     }
135   }
136   if (!m_session_up)
137     return 0;
138 
139   auto enum_tables_up = m_session_up->getEnumTables();
140   if (!enum_tables_up)
141     return 0;
142   while (auto table_up = enum_tables_up->getNext()) {
143     if (table_up->getItemCount() == 0)
144       continue;
145     auto type = table_up->getTableType();
146     switch (type) {
147     case PDB_TableType::Symbols:
148       // This table represents a store of symbols with types listed in
149       // PDBSym_Type
150       abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
151                     LocalVariables | VariableTypes);
152       break;
153     case PDB_TableType::LineNumbers:
154       abilities |= LineTables;
155       break;
156     default:
157       break;
158     }
159   }
160   return abilities;
161 }
162 
163 void SymbolFilePDB::InitializeObject() {
164   lldb::addr_t obj_load_address = m_obj_file->GetFileOffset();
165   lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
166   m_session_up->setLoadAddress(obj_load_address);
167   if (!m_global_scope_up)
168     m_global_scope_up = m_session_up->getGlobalScope();
169   lldbassert(m_global_scope_up.get());
170 
171   TypeSystem *type_system =
172       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
173   ClangASTContext *clang_type_system =
174       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
175   lldbassert(clang_type_system);
176   m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>(
177       type_system, clang_type_system->GetTranslationUnitDecl());
178 }
179 
180 uint32_t SymbolFilePDB::GetNumCompileUnits() {
181   if (m_cached_compile_unit_count == 0) {
182     auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
183     if (!compilands)
184       return 0;
185 
186     // The linker could link *.dll (compiland language = LINK), or import
187     // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
188     // found as a child of the global scope (PDB executable). Usually, such
189     // compilands contain `thunk` symbols in which we are not interested for
190     // now. However we still count them in the compiland list. If we perform
191     // any compiland related activity, like finding symbols through
192     // llvm::pdb::IPDBSession methods, such compilands will all be searched
193     // automatically no matter whether we include them or not.
194     m_cached_compile_unit_count = compilands->getChildCount();
195 
196     // The linker can inject an additional "dummy" compilation unit into the
197     // PDB. Ignore this special compile unit for our purposes, if it is there.
198     // It is always the last one.
199     auto last_compiland_up =
200         compilands->getChildAtIndex(m_cached_compile_unit_count - 1);
201     lldbassert(last_compiland_up.get());
202     std::string name = last_compiland_up->getName();
203     if (name == "* Linker *")
204       --m_cached_compile_unit_count;
205   }
206   return m_cached_compile_unit_count;
207 }
208 
209 void SymbolFilePDB::GetCompileUnitIndex(
210     const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
211   auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
212   if (!results_up)
213     return;
214   auto uid = pdb_compiland.getSymIndexId();
215   for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
216     auto compiland_up = results_up->getChildAtIndex(cu_idx);
217     if (!compiland_up)
218       continue;
219     if (compiland_up->getSymIndexId() == uid) {
220       index = cu_idx;
221       return;
222     }
223   }
224   index = UINT32_MAX;
225   return;
226 }
227 
228 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
229 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
230   return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
231 }
232 
233 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
234   if (index >= GetNumCompileUnits())
235     return CompUnitSP();
236 
237   // Assuming we always retrieve same compilands listed in same order through
238   // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
239   // compile unit makes no sense.
240   auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
241   if (!results)
242     return CompUnitSP();
243   auto compiland_up = results->getChildAtIndex(index);
244   if (!compiland_up)
245     return CompUnitSP();
246   return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
247 }
248 
249 lldb::LanguageType
250 SymbolFilePDB::ParseCompileUnitLanguage(const lldb_private::SymbolContext &sc) {
251   // What fields should I expect to be filled out on the SymbolContext?  Is it
252   // safe to assume that `sc.comp_unit` is valid?
253   if (!sc.comp_unit)
254     return lldb::eLanguageTypeUnknown;
255 
256   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
257   if (!compiland_up)
258     return lldb::eLanguageTypeUnknown;
259   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
260   if (!details)
261     return lldb::eLanguageTypeUnknown;
262   return TranslateLanguage(details->getLanguage());
263 }
264 
265 lldb_private::Function *SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(
266     const PDBSymbolFunc &pdb_func, const lldb_private::SymbolContext &sc) {
267   lldbassert(sc.comp_unit && sc.module_sp.get());
268 
269   auto file_vm_addr = pdb_func.getVirtualAddress();
270   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
271     return nullptr;
272 
273   auto func_length = pdb_func.getLength();
274   AddressRange func_range =
275       AddressRange(file_vm_addr, func_length, sc.module_sp->GetSectionList());
276   if (!func_range.GetBaseAddress().IsValid())
277     return nullptr;
278 
279   lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
280   if (!func_type)
281     return nullptr;
282 
283   user_id_t func_type_uid = pdb_func.getSignatureId();
284 
285   Mangled mangled = GetMangledForPDBFunc(pdb_func);
286 
287   FunctionSP func_sp =
288       std::make_shared<Function>(sc.comp_unit, pdb_func.getSymIndexId(),
289                                  func_type_uid, mangled, func_type, func_range);
290 
291   sc.comp_unit->AddFunction(func_sp);
292   return func_sp.get();
293 }
294 
295 size_t SymbolFilePDB::ParseCompileUnitFunctions(
296     const lldb_private::SymbolContext &sc) {
297   lldbassert(sc.comp_unit);
298   size_t func_added = 0;
299   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
300   if (!compiland_up)
301     return 0;
302   auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
303   if (!results_up)
304     return 0;
305   while (auto pdb_func_up = results_up->getNext()) {
306     auto func_sp =
307         sc.comp_unit->FindFunctionByUID(pdb_func_up->getSymIndexId());
308     if (!func_sp) {
309       if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, sc))
310         ++func_added;
311     }
312   }
313   return func_added;
314 }
315 
316 bool SymbolFilePDB::ParseCompileUnitLineTable(
317     const lldb_private::SymbolContext &sc) {
318   lldbassert(sc.comp_unit);
319   if (sc.comp_unit->GetLineTable())
320     return true;
321   return ParseCompileUnitLineTable(sc, 0);
322 }
323 
324 bool SymbolFilePDB::ParseCompileUnitDebugMacros(
325     const lldb_private::SymbolContext &sc) {
326   // PDB doesn't contain information about macros
327   return false;
328 }
329 
330 bool SymbolFilePDB::ParseCompileUnitSupportFiles(
331     const lldb_private::SymbolContext &sc,
332     lldb_private::FileSpecList &support_files) {
333   lldbassert(sc.comp_unit);
334 
335   // In theory this is unnecessary work for us, because all of this information
336   // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
337   // second time seems like a waste.  Unfortunately, there's no good way around
338   // this short of a moderate refactor since SymbolVendor depends on being able
339   // to cache this list.
340   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
341   if (!compiland_up)
342     return false;
343   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
344   if (!files || files->getChildCount() == 0)
345     return false;
346 
347   while (auto file = files->getNext()) {
348     FileSpec spec(file->getFileName(), false, FileSpec::Style::windows);
349     support_files.AppendIfUnique(spec);
350   }
351 
352   // LLDB uses the DWARF-like file numeration (one based),
353   // the zeroth file is the compile unit itself
354   support_files.Insert(0, *sc.comp_unit);
355 
356   return true;
357 }
358 
359 bool SymbolFilePDB::ParseImportedModules(
360     const lldb_private::SymbolContext &sc,
361     std::vector<lldb_private::ConstString> &imported_modules) {
362   // PDB does not yet support module debug info
363   return false;
364 }
365 
366 static size_t ParseFunctionBlocksForPDBSymbol(
367     const lldb_private::SymbolContext &sc, uint64_t func_file_vm_addr,
368     const llvm::pdb::PDBSymbol *pdb_symbol, lldb_private::Block *parent_block,
369     bool is_top_parent) {
370   assert(pdb_symbol && parent_block);
371 
372   size_t num_added = 0;
373   switch (pdb_symbol->getSymTag()) {
374   case PDB_SymType::Block:
375   case PDB_SymType::Function: {
376     Block *block = nullptr;
377     auto &raw_sym = pdb_symbol->getRawSymbol();
378     if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {
379       if (pdb_func->hasNoInlineAttribute())
380         break;
381       if (is_top_parent)
382         block = parent_block;
383       else
384         break;
385     } else if (llvm::dyn_cast<PDBSymbolBlock>(pdb_symbol)) {
386       auto uid = pdb_symbol->getSymIndexId();
387       if (parent_block->FindBlockByID(uid))
388         break;
389       if (raw_sym.getVirtualAddress() < func_file_vm_addr)
390         break;
391 
392       auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());
393       parent_block->AddChild(block_sp);
394       block = block_sp.get();
395     } else
396       llvm_unreachable("Unexpected PDB symbol!");
397 
398     block->AddRange(Block::Range(
399         raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
400     block->FinalizeRanges();
401     ++num_added;
402 
403     auto results_up = pdb_symbol->findAllChildren();
404     if (!results_up)
405       break;
406     while (auto symbol_up = results_up->getNext()) {
407       num_added += ParseFunctionBlocksForPDBSymbol(
408           sc, func_file_vm_addr, symbol_up.get(), block, false);
409     }
410   } break;
411   default:
412     break;
413   }
414   return num_added;
415 }
416 
417 size_t
418 SymbolFilePDB::ParseFunctionBlocks(const lldb_private::SymbolContext &sc) {
419   lldbassert(sc.comp_unit && sc.function);
420   size_t num_added = 0;
421   auto uid = sc.function->GetID();
422   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
423   if (!pdb_func_up)
424     return 0;
425   Block &parent_block = sc.function->GetBlock(false);
426   num_added =
427       ParseFunctionBlocksForPDBSymbol(sc, pdb_func_up->getVirtualAddress(),
428                                       pdb_func_up.get(), &parent_block, true);
429   return num_added;
430 }
431 
432 size_t SymbolFilePDB::ParseTypes(const lldb_private::SymbolContext &sc) {
433   lldbassert(sc.module_sp.get());
434   if (!sc.comp_unit)
435     return 0;
436 
437   size_t num_added = 0;
438   auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
439   if (!compiland)
440     return 0;
441 
442   auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
443     std::unique_ptr<IPDBEnumSymbols> results;
444     PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
445                                     PDB_SymType::UDT};
446     for (auto tag : tags_to_search) {
447       results = raw_sym.findAllChildren(tag);
448       if (!results || results->getChildCount() == 0)
449         continue;
450       while (auto symbol = results->getNext()) {
451         switch (symbol->getSymTag()) {
452         case PDB_SymType::Enum:
453         case PDB_SymType::UDT:
454         case PDB_SymType::Typedef:
455           break;
456         default:
457           continue;
458         }
459 
460         // This should cause the type to get cached and stored in the `m_types`
461         // lookup.
462         if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
463           // Resolve the type completely to avoid a completion
464           // (and so a list change, which causes an iterators invalidation)
465           // during a TypeList dumping
466           type->GetFullCompilerType();
467           ++num_added;
468         }
469       }
470     }
471   };
472 
473   if (sc.function) {
474     auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
475         sc.function->GetID());
476     if (!pdb_func)
477       return 0;
478     ParseTypesByTagFn(*pdb_func);
479   } else {
480     ParseTypesByTagFn(*compiland);
481 
482     // Also parse global types particularly coming from this compiland.
483     // Unfortunately, PDB has no compiland information for each global type. We
484     // have to parse them all. But ensure we only do this once.
485     static bool parse_all_global_types = false;
486     if (!parse_all_global_types) {
487       ParseTypesByTagFn(*m_global_scope_up);
488       parse_all_global_types = true;
489     }
490   }
491   return num_added;
492 }
493 
494 size_t
495 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
496   if (!sc.comp_unit)
497     return 0;
498 
499   size_t num_added = 0;
500   if (sc.function) {
501     auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
502         sc.function->GetID());
503     if (!pdb_func)
504       return 0;
505 
506     num_added += ParseVariables(sc, *pdb_func);
507     sc.function->GetBlock(false).SetDidParseVariables(true, true);
508   } else if (sc.comp_unit) {
509     auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
510     if (!compiland)
511       return 0;
512 
513     if (sc.comp_unit->GetVariableList(false))
514       return 0;
515 
516     auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
517     if (results && results->getChildCount()) {
518       while (auto result = results->getNext()) {
519         auto cu_id = result->getCompilandId();
520         // FIXME: We are not able to determine variable's compile unit.
521         if (cu_id == 0)
522           continue;
523 
524         if (cu_id == sc.comp_unit->GetID())
525           num_added += ParseVariables(sc, *result);
526       }
527     }
528 
529     // FIXME: A `file static` or `global constant` variable appears both in
530     // compiland's children and global scope's children with unexpectedly
531     // different symbol's Id making it ambiguous.
532 
533     // FIXME: 'local constant', for example, const char var[] = "abc", declared
534     // in a function scope, can't be found in PDB.
535 
536     // Parse variables in this compiland.
537     num_added += ParseVariables(sc, *compiland);
538   }
539 
540   return num_added;
541 }
542 
543 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
544   auto find_result = m_types.find(type_uid);
545   if (find_result != m_types.end())
546     return find_result->second.get();
547 
548   TypeSystem *type_system =
549       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
550   ClangASTContext *clang_type_system =
551       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
552   if (!clang_type_system)
553     return nullptr;
554   PDBASTParser *pdb = clang_type_system->GetPDBParser();
555   if (!pdb)
556     return nullptr;
557 
558   auto pdb_type = m_session_up->getSymbolById(type_uid);
559   if (pdb_type == nullptr)
560     return nullptr;
561 
562   lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
563   if (result) {
564     m_types.insert(std::make_pair(type_uid, result));
565     auto type_list = GetTypeList();
566     if (type_list)
567       type_list->Insert(result);
568   }
569   return result.get();
570 }
571 
572 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
573   std::lock_guard<std::recursive_mutex> guard(
574       GetObjectFile()->GetModule()->GetMutex());
575 
576   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
577       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
578   if (!clang_ast_ctx)
579     return false;
580 
581   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
582   if (!pdb)
583     return false;
584 
585   return pdb->CompleteTypeFromPDB(compiler_type);
586 }
587 
588 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
589   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
590       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
591   if (!clang_ast_ctx)
592     return CompilerDecl();
593 
594   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
595   if (!pdb)
596     return CompilerDecl();
597 
598   auto symbol = m_session_up->getSymbolById(uid);
599   if (!symbol)
600     return CompilerDecl();
601 
602   auto decl = pdb->GetDeclForSymbol(*symbol);
603   if (!decl)
604     return CompilerDecl();
605 
606   return CompilerDecl(clang_ast_ctx, decl);
607 }
608 
609 lldb_private::CompilerDeclContext
610 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
611   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
612       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
613   if (!clang_ast_ctx)
614     return CompilerDeclContext();
615 
616   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
617   if (!pdb)
618     return CompilerDeclContext();
619 
620   auto symbol = m_session_up->getSymbolById(uid);
621   if (!symbol)
622     return CompilerDeclContext();
623 
624   auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
625   if (!decl_context)
626     return GetDeclContextContainingUID(uid);
627 
628   return CompilerDeclContext(clang_ast_ctx, decl_context);
629 }
630 
631 lldb_private::CompilerDeclContext
632 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
633   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
634       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
635   if (!clang_ast_ctx)
636     return CompilerDeclContext();
637 
638   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
639   if (!pdb)
640     return CompilerDeclContext();
641 
642   auto symbol = m_session_up->getSymbolById(uid);
643   if (!symbol)
644     return CompilerDeclContext();
645 
646   auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
647   assert(decl_context);
648 
649   return CompilerDeclContext(clang_ast_ctx, decl_context);
650 }
651 
652 void SymbolFilePDB::ParseDeclsForContext(
653     lldb_private::CompilerDeclContext decl_ctx) {
654   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
655       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
656   if (!clang_ast_ctx)
657     return;
658 
659   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
660   if (!pdb)
661     return;
662 
663   pdb->ParseDeclsForDeclContext(
664       static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
665 }
666 
667 uint32_t
668 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
669                                     uint32_t resolve_scope,
670                                     lldb_private::SymbolContext &sc) {
671   uint32_t resolved_flags = 0;
672   if (resolve_scope & eSymbolContextCompUnit ||
673       resolve_scope & eSymbolContextVariable ||
674       resolve_scope & eSymbolContextFunction ||
675       resolve_scope & eSymbolContextBlock ||
676       resolve_scope & eSymbolContextLineEntry) {
677     auto cu_sp = GetCompileUnitContainsAddress(so_addr);
678     if (!cu_sp) {
679       if (resolved_flags | eSymbolContextVariable) {
680         // TODO: Resolve variables
681       }
682       return 0;
683     }
684     sc.comp_unit = cu_sp.get();
685     resolved_flags |= eSymbolContextCompUnit;
686     lldbassert(sc.module_sp == cu_sp->GetModule());
687   }
688 
689   if (resolve_scope & eSymbolContextFunction ||
690       resolve_scope & eSymbolContextBlock) {
691     addr_t file_vm_addr = so_addr.GetFileAddress();
692     auto symbol_up =
693         m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
694     if (symbol_up) {
695       auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
696       assert(pdb_func);
697       auto func_uid = pdb_func->getSymIndexId();
698       sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
699       if (sc.function == nullptr)
700         sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
701       if (sc.function) {
702         resolved_flags |= eSymbolContextFunction;
703         if (resolve_scope & eSymbolContextBlock) {
704           auto block_symbol = m_session_up->findSymbolByAddress(
705               file_vm_addr, PDB_SymType::Block);
706           auto block_id = block_symbol ? block_symbol->getSymIndexId()
707                                        : sc.function->GetID();
708           sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
709           if (sc.block)
710             resolved_flags |= eSymbolContextBlock;
711         }
712       }
713     }
714   }
715 
716   if (resolve_scope & eSymbolContextLineEntry) {
717     if (auto *line_table = sc.comp_unit->GetLineTable()) {
718       Address addr(so_addr);
719       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
720         resolved_flags |= eSymbolContextLineEntry;
721     }
722   }
723 
724   return resolved_flags;
725 }
726 
727 uint32_t SymbolFilePDB::ResolveSymbolContext(
728     const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
729     uint32_t resolve_scope, lldb_private::SymbolContextList &sc_list) {
730   const size_t old_size = sc_list.GetSize();
731   if (resolve_scope & lldb::eSymbolContextCompUnit) {
732     // Locate all compilation units with line numbers referencing the specified
733     // file.  For example, if `file_spec` is <vector>, then this should return
734     // all source files and header files that reference <vector>, either
735     // directly or indirectly.
736     auto compilands = m_session_up->findCompilandsForSourceFile(
737         file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
738 
739     if (!compilands)
740       return 0;
741 
742     // For each one, either find its previously parsed data or parse it afresh
743     // and add it to the symbol context list.
744     while (auto compiland = compilands->getNext()) {
745       // If we're not checking inlines, then don't add line information for
746       // this file unless the FileSpec matches. For inline functions, we don't
747       // have to match the FileSpec since they could be defined in headers
748       // other than file specified in FileSpec.
749       if (!check_inlines) {
750         std::string source_file = compiland->getSourceFileFullPath();
751         if (source_file.empty())
752           continue;
753         FileSpec this_spec(source_file, false, FileSpec::Style::windows);
754         bool need_full_match = !file_spec.GetDirectory().IsEmpty();
755         if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
756           continue;
757       }
758 
759       SymbolContext sc;
760       auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
761       if (!cu)
762         continue;
763       sc.comp_unit = cu.get();
764       sc.module_sp = cu->GetModule();
765 
766       // If we were asked to resolve line entries, add all entries to the line
767       // table that match the requested line (or all lines if `line` == 0).
768       if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
769                            eSymbolContextLineEntry)) {
770         bool has_line_table = ParseCompileUnitLineTable(sc, line);
771 
772         if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
773           // The query asks for line entries, but we can't get them for the
774           // compile unit. This is not normal for `line` = 0. So just assert
775           // it.
776           assert(line && "Couldn't get all line entries!\n");
777 
778           // Current compiland does not have the requested line. Search next.
779           continue;
780         }
781 
782         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
783           if (!has_line_table)
784             continue;
785 
786           auto *line_table = sc.comp_unit->GetLineTable();
787           lldbassert(line_table);
788 
789           uint32_t num_line_entries = line_table->GetSize();
790           // Skip the terminal line entry.
791           --num_line_entries;
792 
793           // If `line `!= 0, see if we can resolve function for each line entry
794           // in the line table.
795           for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
796                ++line_idx) {
797             if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
798               continue;
799 
800             auto file_vm_addr =
801                 sc.line_entry.range.GetBaseAddress().GetFileAddress();
802             if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
803               continue;
804 
805             auto symbol_up = m_session_up->findSymbolByAddress(
806                 file_vm_addr, PDB_SymType::Function);
807             if (symbol_up) {
808               auto func_uid = symbol_up->getSymIndexId();
809               sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
810               if (sc.function == nullptr) {
811                 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
812                 assert(pdb_func);
813                 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
814               }
815               if (sc.function && (resolve_scope & eSymbolContextBlock)) {
816                 Block &block = sc.function->GetBlock(true);
817                 sc.block = block.FindBlockByID(sc.function->GetID());
818               }
819             }
820             sc_list.Append(sc);
821           }
822         } else if (has_line_table) {
823           // We can parse line table for the compile unit. But no query to
824           // resolve function or block. We append `sc` to the list anyway.
825           sc_list.Append(sc);
826         }
827       } else {
828         // No query for line entry, function or block. But we have a valid
829         // compile unit, append `sc` to the list.
830         sc_list.Append(sc);
831       }
832     }
833   }
834   return sc_list.GetSize() - old_size;
835 }
836 
837 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
838   std::string decorated_name;
839   auto vm_addr = pdb_data.getVirtualAddress();
840   if (vm_addr != LLDB_INVALID_ADDRESS && vm_addr) {
841     auto result_up =
842         m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol);
843     if (result_up) {
844       while (auto symbol_up = result_up->getNext()) {
845         if (symbol_up->getRawSymbol().getVirtualAddress() == vm_addr) {
846           decorated_name = symbol_up->getRawSymbol().getName();
847           break;
848         }
849       }
850     }
851   }
852   if (!decorated_name.empty())
853     return decorated_name;
854 
855   return std::string();
856 }
857 
858 VariableSP SymbolFilePDB::ParseVariableForPDBData(
859     const lldb_private::SymbolContext &sc,
860     const llvm::pdb::PDBSymbolData &pdb_data) {
861   VariableSP var_sp;
862   uint32_t var_uid = pdb_data.getSymIndexId();
863   auto result = m_variables.find(var_uid);
864   if (result != m_variables.end())
865     return result->second;
866 
867   ValueType scope = eValueTypeInvalid;
868   bool is_static_member = false;
869   bool is_external = false;
870   bool is_artificial = false;
871 
872   switch (pdb_data.getDataKind()) {
873   case PDB_DataKind::Global:
874     scope = eValueTypeVariableGlobal;
875     is_external = true;
876     break;
877   case PDB_DataKind::Local:
878     scope = eValueTypeVariableLocal;
879     break;
880   case PDB_DataKind::FileStatic:
881     scope = eValueTypeVariableStatic;
882     break;
883   case PDB_DataKind::StaticMember:
884     is_static_member = true;
885     scope = eValueTypeVariableStatic;
886     break;
887   case PDB_DataKind::Member:
888     scope = eValueTypeVariableStatic;
889     break;
890   case PDB_DataKind::Param:
891     scope = eValueTypeVariableArgument;
892     break;
893   case PDB_DataKind::Constant:
894     scope = eValueTypeConstResult;
895     break;
896   default:
897     break;
898   }
899 
900   switch (pdb_data.getLocationType()) {
901   case PDB_LocType::TLS:
902     scope = eValueTypeVariableThreadLocal;
903     break;
904   case PDB_LocType::RegRel: {
905     // It is a `this` pointer.
906     if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
907       scope = eValueTypeVariableArgument;
908       is_artificial = true;
909     }
910   } break;
911   default:
912     break;
913   }
914 
915   Declaration decl;
916   if (!is_artificial && !pdb_data.isCompilerGenerated()) {
917     if (auto lines = pdb_data.getLineNumbers()) {
918       if (auto first_line = lines->getNext()) {
919         uint32_t src_file_id = first_line->getSourceFileId();
920         auto src_file = m_session_up->getSourceFileById(src_file_id);
921         if (src_file) {
922           FileSpec spec(src_file->getFileName(), /*resolve_path*/ false);
923           decl.SetFile(spec);
924           decl.SetColumn(first_line->getColumnNumber());
925           decl.SetLine(first_line->getLineNumber());
926         }
927       }
928     }
929   }
930 
931   Variable::RangeList ranges;
932   SymbolContextScope *context_scope = sc.comp_unit;
933   if (scope == eValueTypeVariableLocal) {
934     if (sc.function) {
935       context_scope = sc.function->GetBlock(true).FindBlockByID(
936           pdb_data.getLexicalParentId());
937       if (context_scope == nullptr)
938         context_scope = sc.function;
939     }
940   }
941 
942   SymbolFileTypeSP type_sp =
943       std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
944 
945   auto var_name = pdb_data.getName();
946   auto mangled = GetMangledForPDBData(pdb_data);
947   auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
948 
949   bool is_constant;
950   DWARFExpression location = ConvertPDBLocationToDWARFExpression(
951       GetObjectFile()->GetModule(), pdb_data, is_constant);
952 
953   var_sp = std::make_shared<Variable>(
954       var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
955       ranges, &decl, location, is_external, is_artificial, is_static_member);
956   var_sp->SetLocationIsConstantValueData(is_constant);
957 
958   m_variables.insert(std::make_pair(var_uid, var_sp));
959   return var_sp;
960 }
961 
962 size_t
963 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
964                               const llvm::pdb::PDBSymbol &pdb_symbol,
965                               lldb_private::VariableList *variable_list) {
966   size_t num_added = 0;
967 
968   if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
969     VariableListSP local_variable_list_sp;
970 
971     auto result = m_variables.find(pdb_data->getSymIndexId());
972     if (result != m_variables.end()) {
973       if (variable_list)
974         variable_list->AddVariableIfUnique(result->second);
975     } else {
976       // Prepare right VariableList for this variable.
977       if (auto lexical_parent = pdb_data->getLexicalParent()) {
978         switch (lexical_parent->getSymTag()) {
979         case PDB_SymType::Exe:
980           assert(sc.comp_unit);
981           LLVM_FALLTHROUGH;
982         case PDB_SymType::Compiland: {
983           if (sc.comp_unit) {
984             local_variable_list_sp = sc.comp_unit->GetVariableList(false);
985             if (!local_variable_list_sp) {
986               local_variable_list_sp = std::make_shared<VariableList>();
987               sc.comp_unit->SetVariableList(local_variable_list_sp);
988             }
989           }
990         } break;
991         case PDB_SymType::Block:
992         case PDB_SymType::Function: {
993           if (sc.function) {
994             Block *block = sc.function->GetBlock(true).FindBlockByID(
995                 lexical_parent->getSymIndexId());
996             if (block) {
997               local_variable_list_sp = block->GetBlockVariableList(false);
998               if (!local_variable_list_sp) {
999                 local_variable_list_sp = std::make_shared<VariableList>();
1000                 block->SetVariableList(local_variable_list_sp);
1001               }
1002             }
1003           }
1004         } break;
1005         default:
1006           break;
1007         }
1008       }
1009 
1010       if (local_variable_list_sp) {
1011         if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1012           local_variable_list_sp->AddVariableIfUnique(var_sp);
1013           if (variable_list)
1014             variable_list->AddVariableIfUnique(var_sp);
1015           ++num_added;
1016         }
1017       }
1018     }
1019   }
1020 
1021   if (auto results = pdb_symbol.findAllChildren()) {
1022     while (auto result = results->getNext())
1023       num_added += ParseVariables(sc, *result, variable_list);
1024   }
1025 
1026   return num_added;
1027 }
1028 
1029 uint32_t SymbolFilePDB::FindGlobalVariables(
1030     const lldb_private::ConstString &name,
1031     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1032     uint32_t max_matches, lldb_private::VariableList &variables) {
1033   if (!parent_decl_ctx)
1034     parent_decl_ctx = m_tu_decl_ctx_up.get();
1035   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1036     return 0;
1037   if (name.IsEmpty())
1038     return 0;
1039 
1040   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1041   if (!results)
1042     return 0;
1043 
1044   uint32_t matches = 0;
1045   size_t old_size = variables.GetSize();
1046   while (auto result = results->getNext()) {
1047     auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1048     if (max_matches > 0 && matches >= max_matches)
1049       break;
1050 
1051     SymbolContext sc;
1052     sc.module_sp = m_obj_file->GetModule();
1053     lldbassert(sc.module_sp.get());
1054 
1055     sc.comp_unit = ParseCompileUnitForUID(pdb_data->getCompilandId()).get();
1056     // FIXME: We are not able to determine the compile unit.
1057     if (sc.comp_unit == nullptr)
1058       continue;
1059 
1060     if (!name.GetStringRef().equals(
1061             PDBASTParser::PDBNameDropScope(pdb_data->getName())))
1062       continue;
1063 
1064     auto actual_parent_decl_ctx =
1065         GetDeclContextContainingUID(result->getSymIndexId());
1066     if (actual_parent_decl_ctx != *parent_decl_ctx)
1067       continue;
1068 
1069     ParseVariables(sc, *pdb_data, &variables);
1070     matches = variables.GetSize() - old_size;
1071   }
1072 
1073   return matches;
1074 }
1075 
1076 uint32_t
1077 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression &regex,
1078                                    uint32_t max_matches,
1079                                    lldb_private::VariableList &variables) {
1080   if (!regex.IsValid())
1081     return 0;
1082   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1083   if (!results)
1084     return 0;
1085 
1086   uint32_t matches = 0;
1087   size_t old_size = variables.GetSize();
1088   while (auto pdb_data = results->getNext()) {
1089     if (max_matches > 0 && matches >= max_matches)
1090       break;
1091 
1092     auto var_name = pdb_data->getName();
1093     if (var_name.empty())
1094       continue;
1095     if (!regex.Execute(var_name))
1096       continue;
1097     SymbolContext sc;
1098     sc.module_sp = m_obj_file->GetModule();
1099     lldbassert(sc.module_sp.get());
1100 
1101     sc.comp_unit = ParseCompileUnitForUID(pdb_data->getCompilandId()).get();
1102     // FIXME: We are not able to determine the compile unit.
1103     if (sc.comp_unit == nullptr)
1104       continue;
1105 
1106     ParseVariables(sc, *pdb_data, &variables);
1107     matches = variables.GetSize() - old_size;
1108   }
1109 
1110   return matches;
1111 }
1112 
1113 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1114                                     bool include_inlines,
1115                                     lldb_private::SymbolContextList &sc_list) {
1116   lldb_private::SymbolContext sc;
1117   sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1118   if (!sc.comp_unit)
1119     return false;
1120   sc.module_sp = sc.comp_unit->GetModule();
1121   sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, sc);
1122   if (!sc.function)
1123     return false;
1124 
1125   sc_list.Append(sc);
1126   return true;
1127 }
1128 
1129 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1130                                     lldb_private::SymbolContextList &sc_list) {
1131   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1132   if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1133     return false;
1134   return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1135 }
1136 
1137 void SymbolFilePDB::CacheFunctionNames() {
1138   if (!m_func_full_names.IsEmpty())
1139     return;
1140 
1141   std::map<uint64_t, uint32_t> addr_ids;
1142 
1143   if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1144     while (auto pdb_func_up = results_up->getNext()) {
1145       if (pdb_func_up->isCompilerGenerated())
1146         continue;
1147 
1148       auto name = pdb_func_up->getName();
1149       auto demangled_name = pdb_func_up->getUndecoratedName();
1150       if (name.empty() && demangled_name.empty())
1151         continue;
1152 
1153       auto uid = pdb_func_up->getSymIndexId();
1154       if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1155         addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1156 
1157       if (auto parent = pdb_func_up->getClassParent()) {
1158 
1159         // PDB have symbols for class/struct methods or static methods in Enum
1160         // Class. We won't bother to check if the parent is UDT or Enum here.
1161         m_func_method_names.Append(ConstString(name), uid);
1162 
1163         ConstString cstr_name(name);
1164 
1165         // To search a method name, like NS::Class:MemberFunc, LLDB searches
1166         // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1167         // not have inforamtion of this, we extract base names and cache them
1168         // by our own effort.
1169         llvm::StringRef basename;
1170         CPlusPlusLanguage::MethodName cpp_method(cstr_name);
1171         if (cpp_method.IsValid()) {
1172           llvm::StringRef context;
1173           basename = cpp_method.GetBasename();
1174           if (basename.empty())
1175             CPlusPlusLanguage::ExtractContextAndIdentifier(name.c_str(),
1176                                                            context, basename);
1177         }
1178 
1179         if (!basename.empty())
1180           m_func_base_names.Append(ConstString(basename), uid);
1181         else {
1182           m_func_base_names.Append(ConstString(name), uid);
1183         }
1184 
1185         if (!demangled_name.empty())
1186           m_func_full_names.Append(ConstString(demangled_name), uid);
1187 
1188       } else {
1189         // Handle not-method symbols.
1190 
1191         // The function name might contain namespace, or its lexical scope. It
1192         // is not safe to get its base name by applying same scheme as we deal
1193         // with the method names.
1194         // FIXME: Remove namespace if function is static in a scope.
1195         m_func_base_names.Append(ConstString(name), uid);
1196 
1197         if (name == "main") {
1198           m_func_full_names.Append(ConstString(name), uid);
1199 
1200           if (!demangled_name.empty() && name != demangled_name) {
1201             m_func_full_names.Append(ConstString(demangled_name), uid);
1202             m_func_base_names.Append(ConstString(demangled_name), uid);
1203           }
1204         } else if (!demangled_name.empty()) {
1205           m_func_full_names.Append(ConstString(demangled_name), uid);
1206         } else {
1207           m_func_full_names.Append(ConstString(name), uid);
1208         }
1209       }
1210     }
1211   }
1212 
1213   if (auto results_up =
1214           m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1215     while (auto pub_sym_up = results_up->getNext()) {
1216       if (!pub_sym_up->isFunction())
1217         continue;
1218       auto name = pub_sym_up->getName();
1219       if (name.empty())
1220         continue;
1221 
1222       if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1223         auto vm_addr = pub_sym_up->getVirtualAddress();
1224 
1225         // PDB public symbol has mangled name for its associated function.
1226         if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1227           // Cache mangled name.
1228           m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1229         }
1230       }
1231     }
1232   }
1233   // Sort them before value searching is working properly
1234   m_func_full_names.Sort();
1235   m_func_full_names.SizeToFit();
1236   m_func_method_names.Sort();
1237   m_func_method_names.SizeToFit();
1238   m_func_base_names.Sort();
1239   m_func_base_names.SizeToFit();
1240 }
1241 
1242 uint32_t SymbolFilePDB::FindFunctions(
1243     const lldb_private::ConstString &name,
1244     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1245     uint32_t name_type_mask, bool include_inlines, bool append,
1246     lldb_private::SymbolContextList &sc_list) {
1247   if (!append)
1248     sc_list.Clear();
1249   lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1250 
1251   if (name_type_mask == eFunctionNameTypeNone)
1252     return 0;
1253   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1254     return 0;
1255   if (name.IsEmpty())
1256     return 0;
1257 
1258   auto old_size = sc_list.GetSize();
1259   if (name_type_mask & eFunctionNameTypeFull ||
1260       name_type_mask & eFunctionNameTypeBase ||
1261       name_type_mask & eFunctionNameTypeMethod) {
1262     CacheFunctionNames();
1263 
1264     std::set<uint32_t> resolved_ids;
1265     auto ResolveFn = [include_inlines, &name, &sc_list, &resolved_ids,
1266                       this](UniqueCStringMap<uint32_t> &Names) {
1267       std::vector<uint32_t> ids;
1268       if (Names.GetValues(name, ids)) {
1269         for (auto id : ids) {
1270           if (resolved_ids.find(id) == resolved_ids.end()) {
1271             if (ResolveFunction(id, include_inlines, sc_list))
1272               resolved_ids.insert(id);
1273           }
1274         }
1275       }
1276     };
1277     if (name_type_mask & eFunctionNameTypeFull) {
1278       ResolveFn(m_func_full_names);
1279     }
1280     if (name_type_mask & eFunctionNameTypeBase) {
1281       ResolveFn(m_func_base_names);
1282     }
1283     if (name_type_mask & eFunctionNameTypeMethod) {
1284       ResolveFn(m_func_method_names);
1285     }
1286   }
1287   return sc_list.GetSize() - old_size;
1288 }
1289 
1290 uint32_t
1291 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
1292                              bool include_inlines, bool append,
1293                              lldb_private::SymbolContextList &sc_list) {
1294   if (!append)
1295     sc_list.Clear();
1296   if (!regex.IsValid())
1297     return 0;
1298 
1299   auto old_size = sc_list.GetSize();
1300   CacheFunctionNames();
1301 
1302   std::set<uint32_t> resolved_ids;
1303   auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1304                     this](UniqueCStringMap<uint32_t> &Names) {
1305     std::vector<uint32_t> ids;
1306     if (Names.GetValues(regex, ids)) {
1307       for (auto id : ids) {
1308         if (resolved_ids.find(id) == resolved_ids.end())
1309           if (ResolveFunction(id, include_inlines, sc_list))
1310             resolved_ids.insert(id);
1311       }
1312     }
1313   };
1314   ResolveFn(m_func_full_names);
1315   ResolveFn(m_func_base_names);
1316 
1317   return sc_list.GetSize() - old_size;
1318 }
1319 
1320 void SymbolFilePDB::GetMangledNamesForFunction(
1321     const std::string &scope_qualified_name,
1322     std::vector<lldb_private::ConstString> &mangled_names) {}
1323 
1324 uint32_t SymbolFilePDB::FindTypes(
1325     const lldb_private::SymbolContext &sc,
1326     const lldb_private::ConstString &name,
1327     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1328     uint32_t max_matches,
1329     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1330     lldb_private::TypeMap &types) {
1331   if (!append)
1332     types.Clear();
1333   if (!name)
1334     return 0;
1335   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1336     return 0;
1337 
1338   searched_symbol_files.clear();
1339   searched_symbol_files.insert(this);
1340 
1341   std::string name_str = name.AsCString();
1342 
1343   // There is an assumption 'name' is not a regex
1344   FindTypesByName(name_str, parent_decl_ctx, max_matches, types);
1345 
1346   return types.GetSize();
1347 }
1348 
1349 void SymbolFilePDB::FindTypesByRegex(
1350     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1351     lldb_private::TypeMap &types) {
1352   // When searching by regex, we need to go out of our way to limit the search
1353   // space as much as possible since this searches EVERYTHING in the PDB,
1354   // manually doing regex comparisons.  PDB library isn't optimized for regex
1355   // searches or searches across multiple symbol types at the same time, so the
1356   // best we can do is to search enums, then typedefs, then classes one by one,
1357   // and do a regex comparison against each of them.
1358   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1359                                   PDB_SymType::UDT};
1360   std::unique_ptr<IPDBEnumSymbols> results;
1361 
1362   uint32_t matches = 0;
1363 
1364   for (auto tag : tags_to_search) {
1365     results = m_global_scope_up->findAllChildren(tag);
1366     if (!results)
1367       continue;
1368 
1369     while (auto result = results->getNext()) {
1370       if (max_matches > 0 && matches >= max_matches)
1371         break;
1372 
1373       std::string type_name;
1374       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1375         type_name = enum_type->getName();
1376       else if (auto typedef_type =
1377                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1378         type_name = typedef_type->getName();
1379       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1380         type_name = class_type->getName();
1381       else {
1382         // We're looking only for types that have names.  Skip symbols, as well
1383         // as unnamed types such as arrays, pointers, etc.
1384         continue;
1385       }
1386 
1387       if (!regex.Execute(type_name))
1388         continue;
1389 
1390       // This should cause the type to get cached and stored in the `m_types`
1391       // lookup.
1392       if (!ResolveTypeUID(result->getSymIndexId()))
1393         continue;
1394 
1395       auto iter = m_types.find(result->getSymIndexId());
1396       if (iter == m_types.end())
1397         continue;
1398       types.Insert(iter->second);
1399       ++matches;
1400     }
1401   }
1402 }
1403 
1404 void SymbolFilePDB::FindTypesByName(
1405     const std::string &name,
1406     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1407     uint32_t max_matches, lldb_private::TypeMap &types) {
1408   if (!parent_decl_ctx)
1409     parent_decl_ctx = m_tu_decl_ctx_up.get();
1410   std::unique_ptr<IPDBEnumSymbols> results;
1411   if (name.empty())
1412     return;
1413   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1414   if (!results)
1415     return;
1416 
1417   uint32_t matches = 0;
1418 
1419   while (auto result = results->getNext()) {
1420     if (max_matches > 0 && matches >= max_matches)
1421       break;
1422 
1423     if (PDBASTParser::PDBNameDropScope(result->getRawSymbol().getName()) !=
1424         name)
1425       continue;
1426 
1427     switch (result->getSymTag()) {
1428     case PDB_SymType::Enum:
1429     case PDB_SymType::UDT:
1430     case PDB_SymType::Typedef:
1431       break;
1432     default:
1433       // We're looking only for types that have names.  Skip symbols, as well
1434       // as unnamed types such as arrays, pointers, etc.
1435       continue;
1436     }
1437 
1438     // This should cause the type to get cached and stored in the `m_types`
1439     // lookup.
1440     if (!ResolveTypeUID(result->getSymIndexId()))
1441       continue;
1442 
1443     auto actual_parent_decl_ctx =
1444         GetDeclContextContainingUID(result->getSymIndexId());
1445     if (actual_parent_decl_ctx != *parent_decl_ctx)
1446       continue;
1447 
1448     auto iter = m_types.find(result->getSymIndexId());
1449     if (iter == m_types.end())
1450       continue;
1451     types.Insert(iter->second);
1452     ++matches;
1453   }
1454 }
1455 
1456 size_t SymbolFilePDB::FindTypes(
1457     const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1458     lldb_private::TypeMap &types) {
1459   return 0;
1460 }
1461 
1462 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1463   return m_obj_file->GetModule()->GetTypeList();
1464 }
1465 
1466 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1467                                          uint32_t type_mask,
1468                                          TypeCollection &type_collection) {
1469   bool can_parse = false;
1470   switch (pdb_symbol.getSymTag()) {
1471   case PDB_SymType::ArrayType:
1472     can_parse = ((type_mask & eTypeClassArray) != 0);
1473     break;
1474   case PDB_SymType::BuiltinType:
1475     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1476     break;
1477   case PDB_SymType::Enum:
1478     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1479     break;
1480   case PDB_SymType::Function:
1481   case PDB_SymType::FunctionSig:
1482     can_parse = ((type_mask & eTypeClassFunction) != 0);
1483     break;
1484   case PDB_SymType::PointerType:
1485     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1486                                eTypeClassMemberPointer)) != 0);
1487     break;
1488   case PDB_SymType::Typedef:
1489     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1490     break;
1491   case PDB_SymType::UDT: {
1492     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1493     assert(udt);
1494     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1495                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1496                                 eTypeClassUnion)) != 0));
1497   } break;
1498   default:
1499     break;
1500   }
1501 
1502   if (can_parse) {
1503     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1504       auto result =
1505           std::find(type_collection.begin(), type_collection.end(), type);
1506       if (result == type_collection.end())
1507         type_collection.push_back(type);
1508     }
1509   }
1510 
1511   auto results_up = pdb_symbol.findAllChildren();
1512   while (auto symbol_up = results_up->getNext())
1513     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1514 }
1515 
1516 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1517                                uint32_t type_mask,
1518                                lldb_private::TypeList &type_list) {
1519   TypeCollection type_collection;
1520   uint32_t old_size = type_list.GetSize();
1521   CompileUnit *cu =
1522       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1523   if (cu) {
1524     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1525     if (!compiland_up)
1526       return 0;
1527     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1528   } else {
1529     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1530       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1531       if (cu_sp) {
1532         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1533           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1534       }
1535     }
1536   }
1537 
1538   for (auto type : type_collection) {
1539     type->GetForwardCompilerType();
1540     type_list.Insert(type->shared_from_this());
1541   }
1542   return type_list.GetSize() - old_size;
1543 }
1544 
1545 lldb_private::TypeSystem *
1546 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1547   auto type_system =
1548       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1549   if (type_system)
1550     type_system->SetSymbolFile(this);
1551   return type_system;
1552 }
1553 
1554 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1555     const lldb_private::SymbolContext &sc,
1556     const lldb_private::ConstString &name,
1557     const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1558   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1559   auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1560   if (!clang_type_system)
1561     return CompilerDeclContext();
1562 
1563   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1564   if (!pdb)
1565     return CompilerDeclContext();
1566 
1567   clang::DeclContext *decl_context = nullptr;
1568   if (parent_decl_ctx)
1569     decl_context = static_cast<clang::DeclContext *>(
1570         parent_decl_ctx->GetOpaqueDeclContext());
1571 
1572   auto namespace_decl =
1573       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1574   if (!namespace_decl)
1575     return CompilerDeclContext();
1576 
1577   return CompilerDeclContext(type_system,
1578                              static_cast<clang::DeclContext *>(namespace_decl));
1579 }
1580 
1581 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1582   static ConstString g_name("pdb");
1583   return g_name;
1584 }
1585 
1586 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1587 
1588 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1589 
1590 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1591   return *m_session_up;
1592 }
1593 
1594 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1595                                                        uint32_t index) {
1596   auto found_cu = m_comp_units.find(id);
1597   if (found_cu != m_comp_units.end())
1598     return found_cu->second;
1599 
1600   auto compiland_up = GetPDBCompilandByUID(id);
1601   if (!compiland_up)
1602     return CompUnitSP();
1603 
1604   lldb::LanguageType lang;
1605   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1606   if (!details)
1607     lang = lldb::eLanguageTypeC_plus_plus;
1608   else
1609     lang = TranslateLanguage(details->getLanguage());
1610 
1611   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1612     return CompUnitSP();
1613 
1614   std::string path = compiland_up->getSourceFileFullPath();
1615   if (path.empty())
1616     return CompUnitSP();
1617 
1618   // Don't support optimized code for now, DebugInfoPDB does not return this
1619   // information.
1620   LazyBool optimized = eLazyBoolNo;
1621   auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1622                                              path.c_str(), id, lang, optimized);
1623 
1624   if (!cu_sp)
1625     return CompUnitSP();
1626 
1627   m_comp_units.insert(std::make_pair(id, cu_sp));
1628   if (index == UINT32_MAX)
1629     GetCompileUnitIndex(*compiland_up, index);
1630   lldbassert(index != UINT32_MAX);
1631   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1632                                                                     cu_sp);
1633   return cu_sp;
1634 }
1635 
1636 bool SymbolFilePDB::ParseCompileUnitLineTable(
1637     const lldb_private::SymbolContext &sc, uint32_t match_line) {
1638   lldbassert(sc.comp_unit);
1639 
1640   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
1641   if (!compiland_up)
1642     return false;
1643 
1644   // LineEntry needs the *index* of the file into the list of support files
1645   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1646   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1647   // to do a mapping so that we can hand out indices.
1648   llvm::DenseMap<uint32_t, uint32_t> index_map;
1649   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1650   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1651 
1652   // Find contributions to `compiland` from all source and header files.
1653   std::string path = sc.comp_unit->GetPath();
1654   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1655   if (!files)
1656     return false;
1657 
1658   // For each source and header file, create a LineSequence for contributions
1659   // to the compiland from that file, and add the sequence.
1660   while (auto file = files->getNext()) {
1661     std::unique_ptr<LineSequence> sequence(
1662         line_table->CreateLineSequenceContainer());
1663     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1664     if (!lines)
1665       continue;
1666     int entry_count = lines->getChildCount();
1667 
1668     uint64_t prev_addr;
1669     uint32_t prev_length;
1670     uint32_t prev_line;
1671     uint32_t prev_source_idx;
1672 
1673     for (int i = 0; i < entry_count; ++i) {
1674       auto line = lines->getChildAtIndex(i);
1675 
1676       uint64_t lno = line->getLineNumber();
1677       uint64_t addr = line->getVirtualAddress();
1678       uint32_t length = line->getLength();
1679       uint32_t source_id = line->getSourceFileId();
1680       uint32_t col = line->getColumnNumber();
1681       uint32_t source_idx = index_map[source_id];
1682 
1683       // There was a gap between the current entry and the previous entry if
1684       // the addresses don't perfectly line up.
1685       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1686 
1687       // Before inserting the current entry, insert a terminal entry at the end
1688       // of the previous entry's address range if the current entry resulted in
1689       // a gap from the previous entry.
1690       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1691         line_table->AppendLineEntryToSequence(
1692             sequence.get(), prev_addr + prev_length, prev_line, 0,
1693             prev_source_idx, false, false, false, false, true);
1694 
1695         line_table->InsertSequence(sequence.release());
1696         sequence.reset(line_table->CreateLineSequenceContainer());
1697       }
1698 
1699       if (ShouldAddLine(match_line, lno, length)) {
1700         bool is_statement = line->isStatement();
1701         bool is_prologue = false;
1702         bool is_epilogue = false;
1703         auto func =
1704             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1705         if (func) {
1706           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1707           if (prologue)
1708             is_prologue = (addr == prologue->getVirtualAddress());
1709 
1710           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1711           if (epilogue)
1712             is_epilogue = (addr == epilogue->getVirtualAddress());
1713         }
1714 
1715         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1716                                               source_idx, is_statement, false,
1717                                               is_prologue, is_epilogue, false);
1718       }
1719 
1720       prev_addr = addr;
1721       prev_length = length;
1722       prev_line = lno;
1723       prev_source_idx = source_idx;
1724     }
1725 
1726     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1727       // The end is always a terminal entry, so insert it regardless.
1728       line_table->AppendLineEntryToSequence(
1729           sequence.get(), prev_addr + prev_length, prev_line, 0,
1730           prev_source_idx, false, false, false, false, true);
1731     }
1732 
1733     line_table->InsertSequence(sequence.release());
1734   }
1735 
1736   if (line_table->GetSize()) {
1737     sc.comp_unit->SetLineTable(line_table.release());
1738     return true;
1739   }
1740   return false;
1741 }
1742 
1743 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1744     const PDBSymbolCompiland &compiland,
1745     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1746   // This is a hack, but we need to convert the source id into an index into
1747   // the support files array.  We don't want to do path comparisons to avoid
1748   // basename / full path issues that may or may not even be a problem, so we
1749   // use the globally unique source file identifiers.  Ideally we could use the
1750   // global identifiers everywhere, but LineEntry currently assumes indices.
1751   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1752   if (!source_files)
1753     return;
1754 
1755   // LLDB uses the DWARF-like file numeration (one based)
1756   int index = 1;
1757 
1758   while (auto file = source_files->getNext()) {
1759     uint32_t source_id = file->getUniqueId();
1760     index_map[source_id] = index++;
1761   }
1762 }
1763 
1764 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1765     const lldb_private::Address &so_addr) {
1766   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1767   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1768     return nullptr;
1769 
1770   // If it is a PDB function's vm addr, this is the first sure bet.
1771   if (auto lines =
1772           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1773     if (auto first_line = lines->getNext())
1774       return ParseCompileUnitForUID(first_line->getCompilandId());
1775   }
1776 
1777   // Otherwise we resort to section contributions.
1778   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1779     while (auto section = sec_contribs->getNext()) {
1780       auto va = section->getVirtualAddress();
1781       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1782         return ParseCompileUnitForUID(section->getCompilandId());
1783     }
1784   }
1785   return nullptr;
1786 }
1787 
1788 Mangled
1789 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1790   Mangled mangled;
1791   auto func_name = pdb_func.getName();
1792   auto func_undecorated_name = pdb_func.getUndecoratedName();
1793   std::string func_decorated_name;
1794 
1795   // Seek from public symbols for non-static function's decorated name if any.
1796   // For static functions, they don't have undecorated names and aren't exposed
1797   // in Public Symbols either.
1798   if (!func_undecorated_name.empty()) {
1799     auto result_up = m_global_scope_up->findChildren(
1800         PDB_SymType::PublicSymbol, func_undecorated_name,
1801         PDB_NameSearchFlags::NS_UndecoratedName);
1802     if (result_up) {
1803       while (auto symbol_up = result_up->getNext()) {
1804         // For a public symbol, it is unique.
1805         lldbassert(result_up->getChildCount() == 1);
1806         if (auto *pdb_public_sym =
1807                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1808                     symbol_up.get())) {
1809           if (pdb_public_sym->isFunction()) {
1810             func_decorated_name = pdb_public_sym->getName();
1811             break;
1812           }
1813         }
1814       }
1815     }
1816   }
1817   if (!func_decorated_name.empty()) {
1818     mangled.SetMangledName(ConstString(func_decorated_name));
1819 
1820     // For MSVC, format of C funciton's decorated name depends on calling
1821     // conventon. Unfortunately none of the format is recognized by current
1822     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1823     // `__purecall` is retrieved as both its decorated and undecorated name
1824     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1825     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1826     // Mangled::GetDemangledName method will fail internally and caches an
1827     // empty string as its undecorated name. So we will face a contradition
1828     // here for the same symbol:
1829     //   non-empty undecorated name from PDB
1830     //   empty undecorated name from LLDB
1831     if (!func_undecorated_name.empty() &&
1832         mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1833       mangled.SetDemangledName(ConstString(func_undecorated_name));
1834 
1835     // LLDB uses several flags to control how a C++ decorated name is
1836     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1837     // yielded name could be different from what we retrieve from
1838     // PDB source unless we also apply same flags in getting undecorated
1839     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1840     if (!func_undecorated_name.empty() &&
1841         mangled.GetDemangledName(mangled.GuessLanguage()) !=
1842             ConstString(func_undecorated_name))
1843       mangled.SetDemangledName(ConstString(func_undecorated_name));
1844   } else if (!func_undecorated_name.empty()) {
1845     mangled.SetDemangledName(ConstString(func_undecorated_name));
1846   } else if (!func_name.empty())
1847     mangled.SetValue(ConstString(func_name), false);
1848 
1849   return mangled;
1850 }
1851 
1852 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1853     const lldb_private::CompilerDeclContext *decl_ctx) {
1854   if (decl_ctx == nullptr || !decl_ctx->IsValid())
1855     return true;
1856 
1857   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1858   if (!decl_ctx_type_system)
1859     return false;
1860   TypeSystem *type_system = GetTypeSystemForLanguage(
1861       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1862   if (decl_ctx_type_system == type_system)
1863     return true; // The type systems match, return true
1864 
1865   return false;
1866 }
1867