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