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