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