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->GetBaseAddress().GetFileAddress();
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<SourceModule> &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 || scope == eValueTypeVariableArgument) {
937     if (sc.function) {
938       Block &function_block = sc.function->GetBlock(true);
939       Block *block =
940           function_block.FindBlockByID(pdb_data.getLexicalParentId());
941       if (!block)
942         block = &function_block;
943 
944       context_scope = block;
945 
946       for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges;
947            ++i) {
948         AddressRange range;
949         if (!block->GetRangeAtIndex(i, range))
950           continue;
951 
952         ranges.Append(range.GetBaseAddress().GetFileAddress(),
953                       range.GetByteSize());
954       }
955     }
956   }
957 
958   SymbolFileTypeSP type_sp =
959       std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
960 
961   auto var_name = pdb_data.getName();
962   auto mangled = GetMangledForPDBData(pdb_data);
963   auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
964 
965   bool is_constant;
966   DWARFExpression location = ConvertPDBLocationToDWARFExpression(
967       GetObjectFile()->GetModule(), pdb_data, ranges, is_constant);
968 
969   var_sp = std::make_shared<Variable>(
970       var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
971       ranges, &decl, location, is_external, is_artificial, is_static_member);
972   var_sp->SetLocationIsConstantValueData(is_constant);
973 
974   m_variables.insert(std::make_pair(var_uid, var_sp));
975   return var_sp;
976 }
977 
978 size_t
979 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
980                               const llvm::pdb::PDBSymbol &pdb_symbol,
981                               lldb_private::VariableList *variable_list) {
982   size_t num_added = 0;
983 
984   if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
985     VariableListSP local_variable_list_sp;
986 
987     auto result = m_variables.find(pdb_data->getSymIndexId());
988     if (result != m_variables.end()) {
989       if (variable_list)
990         variable_list->AddVariableIfUnique(result->second);
991     } else {
992       // Prepare right VariableList for this variable.
993       if (auto lexical_parent = pdb_data->getLexicalParent()) {
994         switch (lexical_parent->getSymTag()) {
995         case PDB_SymType::Exe:
996           assert(sc.comp_unit);
997           LLVM_FALLTHROUGH;
998         case PDB_SymType::Compiland: {
999           if (sc.comp_unit) {
1000             local_variable_list_sp = sc.comp_unit->GetVariableList(false);
1001             if (!local_variable_list_sp) {
1002               local_variable_list_sp = std::make_shared<VariableList>();
1003               sc.comp_unit->SetVariableList(local_variable_list_sp);
1004             }
1005           }
1006         } break;
1007         case PDB_SymType::Block:
1008         case PDB_SymType::Function: {
1009           if (sc.function) {
1010             Block *block = sc.function->GetBlock(true).FindBlockByID(
1011                 lexical_parent->getSymIndexId());
1012             if (block) {
1013               local_variable_list_sp = block->GetBlockVariableList(false);
1014               if (!local_variable_list_sp) {
1015                 local_variable_list_sp = std::make_shared<VariableList>();
1016                 block->SetVariableList(local_variable_list_sp);
1017               }
1018             }
1019           }
1020         } break;
1021         default:
1022           break;
1023         }
1024       }
1025 
1026       if (local_variable_list_sp) {
1027         if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1028           local_variable_list_sp->AddVariableIfUnique(var_sp);
1029           if (variable_list)
1030             variable_list->AddVariableIfUnique(var_sp);
1031           ++num_added;
1032           PDBASTParser *ast = GetPDBAstParser();
1033           if (ast)
1034             ast->GetDeclForSymbol(*pdb_data);
1035         }
1036       }
1037     }
1038   }
1039 
1040   if (auto results = pdb_symbol.findAllChildren()) {
1041     while (auto result = results->getNext())
1042       num_added += ParseVariables(sc, *result, variable_list);
1043   }
1044 
1045   return num_added;
1046 }
1047 
1048 uint32_t SymbolFilePDB::FindGlobalVariables(
1049     lldb_private::ConstString name,
1050     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1051     uint32_t max_matches, lldb_private::VariableList &variables) {
1052   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1053     return 0;
1054   if (name.IsEmpty())
1055     return 0;
1056 
1057   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1058   if (!results)
1059     return 0;
1060 
1061   uint32_t matches = 0;
1062   size_t old_size = variables.GetSize();
1063   while (auto result = results->getNext()) {
1064     auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1065     if (max_matches > 0 && matches >= max_matches)
1066       break;
1067 
1068     SymbolContext sc;
1069     sc.module_sp = m_obj_file->GetModule();
1070     lldbassert(sc.module_sp.get());
1071 
1072     if (!name.GetStringRef().equals(
1073             MSVCUndecoratedNameParser::DropScope(pdb_data->getName())))
1074       continue;
1075 
1076     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1077     // FIXME: We are not able to determine the compile unit.
1078     if (sc.comp_unit == nullptr)
1079       continue;
1080 
1081     if (parent_decl_ctx && GetDeclContextContainingUID(
1082                                result->getSymIndexId()) != *parent_decl_ctx)
1083       continue;
1084 
1085     ParseVariables(sc, *pdb_data, &variables);
1086     matches = variables.GetSize() - old_size;
1087   }
1088 
1089   return matches;
1090 }
1091 
1092 uint32_t
1093 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression &regex,
1094                                    uint32_t max_matches,
1095                                    lldb_private::VariableList &variables) {
1096   if (!regex.IsValid())
1097     return 0;
1098   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1099   if (!results)
1100     return 0;
1101 
1102   uint32_t matches = 0;
1103   size_t old_size = variables.GetSize();
1104   while (auto pdb_data = results->getNext()) {
1105     if (max_matches > 0 && matches >= max_matches)
1106       break;
1107 
1108     auto var_name = pdb_data->getName();
1109     if (var_name.empty())
1110       continue;
1111     if (!regex.Execute(var_name))
1112       continue;
1113     SymbolContext sc;
1114     sc.module_sp = m_obj_file->GetModule();
1115     lldbassert(sc.module_sp.get());
1116 
1117     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1118     // FIXME: We are not able to determine the compile unit.
1119     if (sc.comp_unit == nullptr)
1120       continue;
1121 
1122     ParseVariables(sc, *pdb_data, &variables);
1123     matches = variables.GetSize() - old_size;
1124   }
1125 
1126   return matches;
1127 }
1128 
1129 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1130                                     bool include_inlines,
1131                                     lldb_private::SymbolContextList &sc_list) {
1132   lldb_private::SymbolContext sc;
1133   sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1134   if (!sc.comp_unit)
1135     return false;
1136   sc.module_sp = sc.comp_unit->GetModule();
1137   sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit);
1138   if (!sc.function)
1139     return false;
1140 
1141   sc_list.Append(sc);
1142   return true;
1143 }
1144 
1145 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1146                                     lldb_private::SymbolContextList &sc_list) {
1147   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1148   if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1149     return false;
1150   return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1151 }
1152 
1153 void SymbolFilePDB::CacheFunctionNames() {
1154   if (!m_func_full_names.IsEmpty())
1155     return;
1156 
1157   std::map<uint64_t, uint32_t> addr_ids;
1158 
1159   if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1160     while (auto pdb_func_up = results_up->getNext()) {
1161       if (pdb_func_up->isCompilerGenerated())
1162         continue;
1163 
1164       auto name = pdb_func_up->getName();
1165       auto demangled_name = pdb_func_up->getUndecoratedName();
1166       if (name.empty() && demangled_name.empty())
1167         continue;
1168 
1169       auto uid = pdb_func_up->getSymIndexId();
1170       if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1171         addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1172 
1173       if (auto parent = pdb_func_up->getClassParent()) {
1174 
1175         // PDB have symbols for class/struct methods or static methods in Enum
1176         // Class. We won't bother to check if the parent is UDT or Enum here.
1177         m_func_method_names.Append(ConstString(name), uid);
1178 
1179         // To search a method name, like NS::Class:MemberFunc, LLDB searches
1180         // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1181         // not have inforamtion of this, we extract base names and cache them
1182         // by our own effort.
1183         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1184         if (!basename.empty())
1185           m_func_base_names.Append(ConstString(basename), uid);
1186         else {
1187           m_func_base_names.Append(ConstString(name), uid);
1188         }
1189 
1190         if (!demangled_name.empty())
1191           m_func_full_names.Append(ConstString(demangled_name), uid);
1192 
1193       } else {
1194         // Handle not-method symbols.
1195 
1196         // The function name might contain namespace, or its lexical scope.
1197         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1198         if (!basename.empty())
1199           m_func_base_names.Append(ConstString(basename), uid);
1200         else
1201           m_func_base_names.Append(ConstString(name), uid);
1202 
1203         if (name == "main") {
1204           m_func_full_names.Append(ConstString(name), uid);
1205 
1206           if (!demangled_name.empty() && name != demangled_name) {
1207             m_func_full_names.Append(ConstString(demangled_name), uid);
1208             m_func_base_names.Append(ConstString(demangled_name), uid);
1209           }
1210         } else if (!demangled_name.empty()) {
1211           m_func_full_names.Append(ConstString(demangled_name), uid);
1212         } else {
1213           m_func_full_names.Append(ConstString(name), uid);
1214         }
1215       }
1216     }
1217   }
1218 
1219   if (auto results_up =
1220           m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1221     while (auto pub_sym_up = results_up->getNext()) {
1222       if (!pub_sym_up->isFunction())
1223         continue;
1224       auto name = pub_sym_up->getName();
1225       if (name.empty())
1226         continue;
1227 
1228       if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1229         auto vm_addr = pub_sym_up->getVirtualAddress();
1230 
1231         // PDB public symbol has mangled name for its associated function.
1232         if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1233           // Cache mangled name.
1234           m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1235         }
1236       }
1237     }
1238   }
1239   // Sort them before value searching is working properly
1240   m_func_full_names.Sort();
1241   m_func_full_names.SizeToFit();
1242   m_func_method_names.Sort();
1243   m_func_method_names.SizeToFit();
1244   m_func_base_names.Sort();
1245   m_func_base_names.SizeToFit();
1246 }
1247 
1248 uint32_t SymbolFilePDB::FindFunctions(
1249     lldb_private::ConstString name,
1250     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1251     FunctionNameType name_type_mask, bool include_inlines, bool append,
1252     lldb_private::SymbolContextList &sc_list) {
1253   if (!append)
1254     sc_list.Clear();
1255   lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1256 
1257   if (name_type_mask == eFunctionNameTypeNone)
1258     return 0;
1259   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1260     return 0;
1261   if (name.IsEmpty())
1262     return 0;
1263 
1264   auto old_size = sc_list.GetSize();
1265   if (name_type_mask & eFunctionNameTypeFull ||
1266       name_type_mask & eFunctionNameTypeBase ||
1267       name_type_mask & eFunctionNameTypeMethod) {
1268     CacheFunctionNames();
1269 
1270     std::set<uint32_t> resolved_ids;
1271     auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,
1272                       &resolved_ids](UniqueCStringMap<uint32_t> &Names) {
1273       std::vector<uint32_t> ids;
1274       if (!Names.GetValues(name, ids))
1275         return;
1276 
1277       for (uint32_t id : ids) {
1278         if (resolved_ids.find(id) != resolved_ids.end())
1279           continue;
1280 
1281         if (parent_decl_ctx &&
1282             GetDeclContextContainingUID(id) != *parent_decl_ctx)
1283           continue;
1284 
1285         if (ResolveFunction(id, include_inlines, sc_list))
1286           resolved_ids.insert(id);
1287       }
1288     };
1289     if (name_type_mask & eFunctionNameTypeFull) {
1290       ResolveFn(m_func_full_names);
1291       ResolveFn(m_func_base_names);
1292       ResolveFn(m_func_method_names);
1293     }
1294     if (name_type_mask & eFunctionNameTypeBase) {
1295       ResolveFn(m_func_base_names);
1296     }
1297     if (name_type_mask & eFunctionNameTypeMethod) {
1298       ResolveFn(m_func_method_names);
1299     }
1300   }
1301   return sc_list.GetSize() - old_size;
1302 }
1303 
1304 uint32_t
1305 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
1306                              bool include_inlines, bool append,
1307                              lldb_private::SymbolContextList &sc_list) {
1308   if (!append)
1309     sc_list.Clear();
1310   if (!regex.IsValid())
1311     return 0;
1312 
1313   auto old_size = sc_list.GetSize();
1314   CacheFunctionNames();
1315 
1316   std::set<uint32_t> resolved_ids;
1317   auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1318                     this](UniqueCStringMap<uint32_t> &Names) {
1319     std::vector<uint32_t> ids;
1320     if (Names.GetValues(regex, ids)) {
1321       for (auto id : ids) {
1322         if (resolved_ids.find(id) == resolved_ids.end())
1323           if (ResolveFunction(id, include_inlines, sc_list))
1324             resolved_ids.insert(id);
1325       }
1326     }
1327   };
1328   ResolveFn(m_func_full_names);
1329   ResolveFn(m_func_base_names);
1330 
1331   return sc_list.GetSize() - old_size;
1332 }
1333 
1334 void SymbolFilePDB::GetMangledNamesForFunction(
1335     const std::string &scope_qualified_name,
1336     std::vector<lldb_private::ConstString> &mangled_names) {}
1337 
1338 void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) {
1339   std::set<lldb::addr_t> sym_addresses;
1340   for (size_t i = 0; i < symtab.GetNumSymbols(); i++)
1341     sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());
1342 
1343   auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();
1344   if (!results)
1345     return;
1346 
1347   auto section_list = m_obj_file->GetSectionList();
1348   if (!section_list)
1349     return;
1350 
1351   while (auto pub_symbol = results->getNext()) {
1352     auto section_id = pub_symbol->getAddressSection();
1353 
1354     auto section = section_list->FindSectionByID(section_id);
1355     if (!section)
1356       continue;
1357 
1358     auto offset = pub_symbol->getAddressOffset();
1359 
1360     auto file_addr = section->GetFileAddress() + offset;
1361     if (sym_addresses.find(file_addr) != sym_addresses.end())
1362       continue;
1363     sym_addresses.insert(file_addr);
1364 
1365     auto size = pub_symbol->getLength();
1366     symtab.AddSymbol(
1367         Symbol(pub_symbol->getSymIndexId(),   // symID
1368                pub_symbol->getName().c_str(), // name
1369                true,                          // name_is_mangled
1370                pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type
1371                true,      // external
1372                false,     // is_debug
1373                false,     // is_trampoline
1374                false,     // is_artificial
1375                section,   // section_sp
1376                offset,    // value
1377                size,      // size
1378                size != 0, // size_is_valid
1379                false,     // contains_linker_annotations
1380                0          // flags
1381                ));
1382   }
1383 
1384   symtab.CalculateSymbolSizes();
1385   symtab.Finalize();
1386 }
1387 
1388 uint32_t SymbolFilePDB::FindTypes(
1389     lldb_private::ConstString name,
1390     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1391     uint32_t max_matches,
1392     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1393     lldb_private::TypeMap &types) {
1394   if (!append)
1395     types.Clear();
1396   if (!name)
1397     return 0;
1398   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1399     return 0;
1400 
1401   searched_symbol_files.clear();
1402   searched_symbol_files.insert(this);
1403 
1404   // There is an assumption 'name' is not a regex
1405   FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1406 
1407   return types.GetSize();
1408 }
1409 
1410 void SymbolFilePDB::DumpClangAST(Stream &s) {
1411   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1412   auto clang = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1413   if (!clang)
1414     return;
1415   clang->Dump(s);
1416 }
1417 
1418 void SymbolFilePDB::FindTypesByRegex(
1419     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1420     lldb_private::TypeMap &types) {
1421   // When searching by regex, we need to go out of our way to limit the search
1422   // space as much as possible since this searches EVERYTHING in the PDB,
1423   // manually doing regex comparisons.  PDB library isn't optimized for regex
1424   // searches or searches across multiple symbol types at the same time, so the
1425   // best we can do is to search enums, then typedefs, then classes one by one,
1426   // and do a regex comparison against each of them.
1427   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1428                                   PDB_SymType::UDT};
1429   std::unique_ptr<IPDBEnumSymbols> results;
1430 
1431   uint32_t matches = 0;
1432 
1433   for (auto tag : tags_to_search) {
1434     results = m_global_scope_up->findAllChildren(tag);
1435     if (!results)
1436       continue;
1437 
1438     while (auto result = results->getNext()) {
1439       if (max_matches > 0 && matches >= max_matches)
1440         break;
1441 
1442       std::string type_name;
1443       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1444         type_name = enum_type->getName();
1445       else if (auto typedef_type =
1446                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1447         type_name = typedef_type->getName();
1448       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1449         type_name = class_type->getName();
1450       else {
1451         // We're looking only for types that have names.  Skip symbols, as well
1452         // as unnamed types such as arrays, pointers, etc.
1453         continue;
1454       }
1455 
1456       if (!regex.Execute(type_name))
1457         continue;
1458 
1459       // This should cause the type to get cached and stored in the `m_types`
1460       // lookup.
1461       if (!ResolveTypeUID(result->getSymIndexId()))
1462         continue;
1463 
1464       auto iter = m_types.find(result->getSymIndexId());
1465       if (iter == m_types.end())
1466         continue;
1467       types.Insert(iter->second);
1468       ++matches;
1469     }
1470   }
1471 }
1472 
1473 void SymbolFilePDB::FindTypesByName(
1474     llvm::StringRef name,
1475     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1476     uint32_t max_matches, lldb_private::TypeMap &types) {
1477   std::unique_ptr<IPDBEnumSymbols> results;
1478   if (name.empty())
1479     return;
1480   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1481   if (!results)
1482     return;
1483 
1484   uint32_t matches = 0;
1485 
1486   while (auto result = results->getNext()) {
1487     if (max_matches > 0 && matches >= max_matches)
1488       break;
1489 
1490     if (MSVCUndecoratedNameParser::DropScope(
1491             result->getRawSymbol().getName()) != name)
1492       continue;
1493 
1494     switch (result->getSymTag()) {
1495     case PDB_SymType::Enum:
1496     case PDB_SymType::UDT:
1497     case PDB_SymType::Typedef:
1498       break;
1499     default:
1500       // We're looking only for types that have names.  Skip symbols, as well
1501       // as unnamed types such as arrays, pointers, etc.
1502       continue;
1503     }
1504 
1505     // This should cause the type to get cached and stored in the `m_types`
1506     // lookup.
1507     if (!ResolveTypeUID(result->getSymIndexId()))
1508       continue;
1509 
1510     if (parent_decl_ctx && GetDeclContextContainingUID(
1511                                result->getSymIndexId()) != *parent_decl_ctx)
1512       continue;
1513 
1514     auto iter = m_types.find(result->getSymIndexId());
1515     if (iter == m_types.end())
1516       continue;
1517     types.Insert(iter->second);
1518     ++matches;
1519   }
1520 }
1521 
1522 size_t SymbolFilePDB::FindTypes(
1523     const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1524     lldb_private::TypeMap &types) {
1525   return 0;
1526 }
1527 
1528 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1529   return m_obj_file->GetModule()->GetTypeList();
1530 }
1531 
1532 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1533                                          uint32_t type_mask,
1534                                          TypeCollection &type_collection) {
1535   bool can_parse = false;
1536   switch (pdb_symbol.getSymTag()) {
1537   case PDB_SymType::ArrayType:
1538     can_parse = ((type_mask & eTypeClassArray) != 0);
1539     break;
1540   case PDB_SymType::BuiltinType:
1541     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1542     break;
1543   case PDB_SymType::Enum:
1544     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1545     break;
1546   case PDB_SymType::Function:
1547   case PDB_SymType::FunctionSig:
1548     can_parse = ((type_mask & eTypeClassFunction) != 0);
1549     break;
1550   case PDB_SymType::PointerType:
1551     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1552                                eTypeClassMemberPointer)) != 0);
1553     break;
1554   case PDB_SymType::Typedef:
1555     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1556     break;
1557   case PDB_SymType::UDT: {
1558     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1559     assert(udt);
1560     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1561                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1562                                 eTypeClassUnion)) != 0));
1563   } break;
1564   default:
1565     break;
1566   }
1567 
1568   if (can_parse) {
1569     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1570       auto result =
1571           std::find(type_collection.begin(), type_collection.end(), type);
1572       if (result == type_collection.end())
1573         type_collection.push_back(type);
1574     }
1575   }
1576 
1577   auto results_up = pdb_symbol.findAllChildren();
1578   while (auto symbol_up = results_up->getNext())
1579     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1580 }
1581 
1582 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1583                                TypeClass type_mask,
1584                                lldb_private::TypeList &type_list) {
1585   TypeCollection type_collection;
1586   uint32_t old_size = type_list.GetSize();
1587   CompileUnit *cu =
1588       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1589   if (cu) {
1590     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1591     if (!compiland_up)
1592       return 0;
1593     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1594   } else {
1595     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1596       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1597       if (cu_sp) {
1598         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1599           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1600       }
1601     }
1602   }
1603 
1604   for (auto type : type_collection) {
1605     type->GetForwardCompilerType();
1606     type_list.Insert(type->shared_from_this());
1607   }
1608   return type_list.GetSize() - old_size;
1609 }
1610 
1611 lldb_private::TypeSystem *
1612 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1613   auto type_system =
1614       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1615   if (type_system)
1616     type_system->SetSymbolFile(this);
1617   return type_system;
1618 }
1619 
1620 PDBASTParser *SymbolFilePDB::GetPDBAstParser() {
1621   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1622   auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1623   if (!clang_type_system)
1624     return nullptr;
1625 
1626   return clang_type_system->GetPDBParser();
1627 }
1628 
1629 
1630 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1631     lldb_private::ConstString name,
1632     const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1633   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1634   auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1635   if (!clang_type_system)
1636     return CompilerDeclContext();
1637 
1638   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1639   if (!pdb)
1640     return CompilerDeclContext();
1641 
1642   clang::DeclContext *decl_context = nullptr;
1643   if (parent_decl_ctx)
1644     decl_context = static_cast<clang::DeclContext *>(
1645         parent_decl_ctx->GetOpaqueDeclContext());
1646 
1647   auto namespace_decl =
1648       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1649   if (!namespace_decl)
1650     return CompilerDeclContext();
1651 
1652   return CompilerDeclContext(type_system,
1653                              static_cast<clang::DeclContext *>(namespace_decl));
1654 }
1655 
1656 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1657   static ConstString g_name("pdb");
1658   return g_name;
1659 }
1660 
1661 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1662 
1663 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1664 
1665 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1666   return *m_session_up;
1667 }
1668 
1669 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1670                                                        uint32_t index) {
1671   auto found_cu = m_comp_units.find(id);
1672   if (found_cu != m_comp_units.end())
1673     return found_cu->second;
1674 
1675   auto compiland_up = GetPDBCompilandByUID(id);
1676   if (!compiland_up)
1677     return CompUnitSP();
1678 
1679   lldb::LanguageType lang;
1680   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1681   if (!details)
1682     lang = lldb::eLanguageTypeC_plus_plus;
1683   else
1684     lang = TranslateLanguage(details->getLanguage());
1685 
1686   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1687     return CompUnitSP();
1688 
1689   std::string path = compiland_up->getSourceFileFullPath();
1690   if (path.empty())
1691     return CompUnitSP();
1692 
1693   // Don't support optimized code for now, DebugInfoPDB does not return this
1694   // information.
1695   LazyBool optimized = eLazyBoolNo;
1696   auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1697                                              path.c_str(), id, lang, optimized);
1698 
1699   if (!cu_sp)
1700     return CompUnitSP();
1701 
1702   m_comp_units.insert(std::make_pair(id, cu_sp));
1703   if (index == UINT32_MAX)
1704     GetCompileUnitIndex(*compiland_up, index);
1705   lldbassert(index != UINT32_MAX);
1706   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1707                                                                     cu_sp);
1708   return cu_sp;
1709 }
1710 
1711 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,
1712                                               uint32_t match_line) {
1713   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1714   if (!compiland_up)
1715     return false;
1716 
1717   // LineEntry needs the *index* of the file into the list of support files
1718   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1719   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1720   // to do a mapping so that we can hand out indices.
1721   llvm::DenseMap<uint32_t, uint32_t> index_map;
1722   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1723   auto line_table = llvm::make_unique<LineTable>(&comp_unit);
1724 
1725   // Find contributions to `compiland` from all source and header files.
1726   std::string path = comp_unit.GetPath();
1727   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1728   if (!files)
1729     return false;
1730 
1731   // For each source and header file, create a LineSequence for contributions
1732   // to the compiland from that file, and add the sequence.
1733   while (auto file = files->getNext()) {
1734     std::unique_ptr<LineSequence> sequence(
1735         line_table->CreateLineSequenceContainer());
1736     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1737     if (!lines)
1738       continue;
1739     int entry_count = lines->getChildCount();
1740 
1741     uint64_t prev_addr;
1742     uint32_t prev_length;
1743     uint32_t prev_line;
1744     uint32_t prev_source_idx;
1745 
1746     for (int i = 0; i < entry_count; ++i) {
1747       auto line = lines->getChildAtIndex(i);
1748 
1749       uint64_t lno = line->getLineNumber();
1750       uint64_t addr = line->getVirtualAddress();
1751       uint32_t length = line->getLength();
1752       uint32_t source_id = line->getSourceFileId();
1753       uint32_t col = line->getColumnNumber();
1754       uint32_t source_idx = index_map[source_id];
1755 
1756       // There was a gap between the current entry and the previous entry if
1757       // the addresses don't perfectly line up.
1758       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1759 
1760       // Before inserting the current entry, insert a terminal entry at the end
1761       // of the previous entry's address range if the current entry resulted in
1762       // a gap from the previous entry.
1763       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1764         line_table->AppendLineEntryToSequence(
1765             sequence.get(), prev_addr + prev_length, prev_line, 0,
1766             prev_source_idx, false, false, false, false, true);
1767 
1768         line_table->InsertSequence(sequence.release());
1769         sequence.reset(line_table->CreateLineSequenceContainer());
1770       }
1771 
1772       if (ShouldAddLine(match_line, lno, length)) {
1773         bool is_statement = line->isStatement();
1774         bool is_prologue = false;
1775         bool is_epilogue = false;
1776         auto func =
1777             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1778         if (func) {
1779           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1780           if (prologue)
1781             is_prologue = (addr == prologue->getVirtualAddress());
1782 
1783           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1784           if (epilogue)
1785             is_epilogue = (addr == epilogue->getVirtualAddress());
1786         }
1787 
1788         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1789                                               source_idx, is_statement, false,
1790                                               is_prologue, is_epilogue, false);
1791       }
1792 
1793       prev_addr = addr;
1794       prev_length = length;
1795       prev_line = lno;
1796       prev_source_idx = source_idx;
1797     }
1798 
1799     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1800       // The end is always a terminal entry, so insert it regardless.
1801       line_table->AppendLineEntryToSequence(
1802           sequence.get(), prev_addr + prev_length, prev_line, 0,
1803           prev_source_idx, false, false, false, false, true);
1804     }
1805 
1806     line_table->InsertSequence(sequence.release());
1807   }
1808 
1809   if (line_table->GetSize()) {
1810     comp_unit.SetLineTable(line_table.release());
1811     return true;
1812   }
1813   return false;
1814 }
1815 
1816 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1817     const PDBSymbolCompiland &compiland,
1818     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1819   // This is a hack, but we need to convert the source id into an index into
1820   // the support files array.  We don't want to do path comparisons to avoid
1821   // basename / full path issues that may or may not even be a problem, so we
1822   // use the globally unique source file identifiers.  Ideally we could use the
1823   // global identifiers everywhere, but LineEntry currently assumes indices.
1824   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1825   if (!source_files)
1826     return;
1827 
1828   // LLDB uses the DWARF-like file numeration (one based)
1829   int index = 1;
1830 
1831   while (auto file = source_files->getNext()) {
1832     uint32_t source_id = file->getUniqueId();
1833     index_map[source_id] = index++;
1834   }
1835 }
1836 
1837 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1838     const lldb_private::Address &so_addr) {
1839   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1840   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1841     return nullptr;
1842 
1843   // If it is a PDB function's vm addr, this is the first sure bet.
1844   if (auto lines =
1845           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1846     if (auto first_line = lines->getNext())
1847       return ParseCompileUnitForUID(first_line->getCompilandId());
1848   }
1849 
1850   // Otherwise we resort to section contributions.
1851   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1852     while (auto section = sec_contribs->getNext()) {
1853       auto va = section->getVirtualAddress();
1854       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1855         return ParseCompileUnitForUID(section->getCompilandId());
1856     }
1857   }
1858   return nullptr;
1859 }
1860 
1861 Mangled
1862 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1863   Mangled mangled;
1864   auto func_name = pdb_func.getName();
1865   auto func_undecorated_name = pdb_func.getUndecoratedName();
1866   std::string func_decorated_name;
1867 
1868   // Seek from public symbols for non-static function's decorated name if any.
1869   // For static functions, they don't have undecorated names and aren't exposed
1870   // in Public Symbols either.
1871   if (!func_undecorated_name.empty()) {
1872     auto result_up = m_global_scope_up->findChildren(
1873         PDB_SymType::PublicSymbol, func_undecorated_name,
1874         PDB_NameSearchFlags::NS_UndecoratedName);
1875     if (result_up) {
1876       while (auto symbol_up = result_up->getNext()) {
1877         // For a public symbol, it is unique.
1878         lldbassert(result_up->getChildCount() == 1);
1879         if (auto *pdb_public_sym =
1880                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1881                     symbol_up.get())) {
1882           if (pdb_public_sym->isFunction()) {
1883             func_decorated_name = pdb_public_sym->getName();
1884             break;
1885           }
1886         }
1887       }
1888     }
1889   }
1890   if (!func_decorated_name.empty()) {
1891     mangled.SetMangledName(ConstString(func_decorated_name));
1892 
1893     // For MSVC, format of C funciton's decorated name depends on calling
1894     // conventon. Unfortunately none of the format is recognized by current
1895     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1896     // `__purecall` is retrieved as both its decorated and undecorated name
1897     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1898     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1899     // Mangled::GetDemangledName method will fail internally and caches an
1900     // empty string as its undecorated name. So we will face a contradition
1901     // here for the same symbol:
1902     //   non-empty undecorated name from PDB
1903     //   empty undecorated name from LLDB
1904     if (!func_undecorated_name.empty() &&
1905         mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1906       mangled.SetDemangledName(ConstString(func_undecorated_name));
1907 
1908     // LLDB uses several flags to control how a C++ decorated name is
1909     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1910     // yielded name could be different from what we retrieve from
1911     // PDB source unless we also apply same flags in getting undecorated
1912     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1913     if (!func_undecorated_name.empty() &&
1914         mangled.GetDemangledName(mangled.GuessLanguage()) !=
1915             ConstString(func_undecorated_name))
1916       mangled.SetDemangledName(ConstString(func_undecorated_name));
1917   } else if (!func_undecorated_name.empty()) {
1918     mangled.SetDemangledName(ConstString(func_undecorated_name));
1919   } else if (!func_name.empty())
1920     mangled.SetValue(ConstString(func_name), false);
1921 
1922   return mangled;
1923 }
1924 
1925 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1926     const lldb_private::CompilerDeclContext *decl_ctx) {
1927   if (decl_ctx == nullptr || !decl_ctx->IsValid())
1928     return true;
1929 
1930   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1931   if (!decl_ctx_type_system)
1932     return false;
1933   TypeSystem *type_system = GetTypeSystemForLanguage(
1934       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1935   if (decl_ctx_type_system == type_system)
1936     return true; // The type systems match, return true
1937 
1938   return false;
1939 }
1940 
1941 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1942   static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1943     return lhs < rhs.Offset;
1944   };
1945 
1946   // Cache section contributions
1947   if (m_sec_contribs.empty()) {
1948     if (auto SecContribs = m_session_up->getSectionContribs()) {
1949       while (auto SectionContrib = SecContribs->getNext()) {
1950         auto comp_id = SectionContrib->getCompilandId();
1951         if (!comp_id)
1952           continue;
1953 
1954         auto sec = SectionContrib->getAddressSection();
1955         auto &sec_cs = m_sec_contribs[sec];
1956 
1957         auto offset = SectionContrib->getAddressOffset();
1958         auto it =
1959             std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
1960 
1961         auto size = SectionContrib->getLength();
1962         sec_cs.insert(it, {offset, size, comp_id});
1963       }
1964     }
1965   }
1966 
1967   // Check by line number
1968   if (auto Lines = data.getLineNumbers()) {
1969     if (auto FirstLine = Lines->getNext())
1970       return FirstLine->getCompilandId();
1971   }
1972 
1973   // Retrieve section + offset
1974   uint32_t DataSection = data.getAddressSection();
1975   uint32_t DataOffset = data.getAddressOffset();
1976   if (DataSection == 0) {
1977     if (auto RVA = data.getRelativeVirtualAddress())
1978       m_session_up->addressForRVA(RVA, DataSection, DataOffset);
1979   }
1980 
1981   if (DataSection) {
1982     // Search by section contributions
1983     auto &sec_cs = m_sec_contribs[DataSection];
1984     auto it =
1985         std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
1986     if (it != sec_cs.begin()) {
1987       --it;
1988       if (DataOffset < it->Offset + it->Size)
1989         return it->CompilandId;
1990     }
1991   } else {
1992     // Search in lexical tree
1993     auto LexParentId = data.getLexicalParentId();
1994     while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
1995       if (LexParent->getSymTag() == PDB_SymType::Exe)
1996         break;
1997       if (LexParent->getSymTag() == PDB_SymType::Compiland)
1998         return LexParentId;
1999       LexParentId = LexParent->getRawSymbol().getLexicalParentId();
2000     }
2001   }
2002 
2003   return 0;
2004 }
2005