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