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