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