xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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.Finalize();
1425 }
1426 
1427 void SymbolFilePDB::FindTypes(
1428     lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx,
1429     uint32_t max_matches,
1430     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1431     lldb_private::TypeMap &types) {
1432   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1433   if (!name)
1434     return;
1435   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1436     return;
1437 
1438   searched_symbol_files.clear();
1439   searched_symbol_files.insert(this);
1440 
1441   // There is an assumption 'name' is not a regex
1442   FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1443 }
1444 
1445 void SymbolFilePDB::DumpClangAST(Stream &s) {
1446   auto type_system_or_err =
1447       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1448   if (auto err = type_system_or_err.takeError()) {
1449     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
1450                    std::move(err), "Unable to dump ClangAST");
1451     return;
1452   }
1453 
1454   auto *clang_type_system =
1455       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1456   if (!clang_type_system)
1457     return;
1458   clang_type_system->Dump(s.AsRawOstream());
1459 }
1460 
1461 void SymbolFilePDB::FindTypesByRegex(
1462     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1463     lldb_private::TypeMap &types) {
1464   // When searching by regex, we need to go out of our way to limit the search
1465   // space as much as possible since this searches EVERYTHING in the PDB,
1466   // manually doing regex comparisons.  PDB library isn't optimized for regex
1467   // searches or searches across multiple symbol types at the same time, so the
1468   // best we can do is to search enums, then typedefs, then classes one by one,
1469   // and do a regex comparison against each of them.
1470   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1471                                   PDB_SymType::UDT};
1472   std::unique_ptr<IPDBEnumSymbols> results;
1473 
1474   uint32_t matches = 0;
1475 
1476   for (auto tag : tags_to_search) {
1477     results = m_global_scope_up->findAllChildren(tag);
1478     if (!results)
1479       continue;
1480 
1481     while (auto result = results->getNext()) {
1482       if (max_matches > 0 && matches >= max_matches)
1483         break;
1484 
1485       std::string type_name;
1486       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1487         type_name = enum_type->getName();
1488       else if (auto typedef_type =
1489                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1490         type_name = typedef_type->getName();
1491       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1492         type_name = class_type->getName();
1493       else {
1494         // We're looking only for types that have names.  Skip symbols, as well
1495         // as unnamed types such as arrays, pointers, etc.
1496         continue;
1497       }
1498 
1499       if (!regex.Execute(type_name))
1500         continue;
1501 
1502       // This should cause the type to get cached and stored in the `m_types`
1503       // lookup.
1504       if (!ResolveTypeUID(result->getSymIndexId()))
1505         continue;
1506 
1507       auto iter = m_types.find(result->getSymIndexId());
1508       if (iter == m_types.end())
1509         continue;
1510       types.Insert(iter->second);
1511       ++matches;
1512     }
1513   }
1514 }
1515 
1516 void SymbolFilePDB::FindTypesByName(
1517     llvm::StringRef name,
1518     const lldb_private::CompilerDeclContext &parent_decl_ctx,
1519     uint32_t max_matches, lldb_private::TypeMap &types) {
1520   std::unique_ptr<IPDBEnumSymbols> results;
1521   if (name.empty())
1522     return;
1523   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1524   if (!results)
1525     return;
1526 
1527   uint32_t matches = 0;
1528 
1529   while (auto result = results->getNext()) {
1530     if (max_matches > 0 && matches >= max_matches)
1531       break;
1532 
1533     if (MSVCUndecoratedNameParser::DropScope(
1534             result->getRawSymbol().getName()) != name)
1535       continue;
1536 
1537     switch (result->getSymTag()) {
1538     case PDB_SymType::Enum:
1539     case PDB_SymType::UDT:
1540     case PDB_SymType::Typedef:
1541       break;
1542     default:
1543       // We're looking only for types that have names.  Skip symbols, as well
1544       // as unnamed types such as arrays, pointers, etc.
1545       continue;
1546     }
1547 
1548     // This should cause the type to get cached and stored in the `m_types`
1549     // lookup.
1550     if (!ResolveTypeUID(result->getSymIndexId()))
1551       continue;
1552 
1553     if (parent_decl_ctx.IsValid() &&
1554         GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx)
1555       continue;
1556 
1557     auto iter = m_types.find(result->getSymIndexId());
1558     if (iter == m_types.end())
1559       continue;
1560     types.Insert(iter->second);
1561     ++matches;
1562   }
1563 }
1564 
1565 void SymbolFilePDB::FindTypes(
1566     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1567     llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1568     lldb_private::TypeMap &types) {}
1569 
1570 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1571                                          uint32_t type_mask,
1572                                          TypeCollection &type_collection) {
1573   bool can_parse = false;
1574   switch (pdb_symbol.getSymTag()) {
1575   case PDB_SymType::ArrayType:
1576     can_parse = ((type_mask & eTypeClassArray) != 0);
1577     break;
1578   case PDB_SymType::BuiltinType:
1579     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1580     break;
1581   case PDB_SymType::Enum:
1582     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1583     break;
1584   case PDB_SymType::Function:
1585   case PDB_SymType::FunctionSig:
1586     can_parse = ((type_mask & eTypeClassFunction) != 0);
1587     break;
1588   case PDB_SymType::PointerType:
1589     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1590                                eTypeClassMemberPointer)) != 0);
1591     break;
1592   case PDB_SymType::Typedef:
1593     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1594     break;
1595   case PDB_SymType::UDT: {
1596     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1597     assert(udt);
1598     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1599                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1600                                 eTypeClassUnion)) != 0));
1601   } break;
1602   default:
1603     break;
1604   }
1605 
1606   if (can_parse) {
1607     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1608       auto result =
1609           std::find(type_collection.begin(), type_collection.end(), type);
1610       if (result == type_collection.end())
1611         type_collection.push_back(type);
1612     }
1613   }
1614 
1615   auto results_up = pdb_symbol.findAllChildren();
1616   while (auto symbol_up = results_up->getNext())
1617     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1618 }
1619 
1620 void SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1621                              TypeClass type_mask,
1622                              lldb_private::TypeList &type_list) {
1623   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1624   TypeCollection type_collection;
1625   CompileUnit *cu =
1626       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1627   if (cu) {
1628     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1629     if (!compiland_up)
1630       return;
1631     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1632   } else {
1633     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1634       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1635       if (cu_sp) {
1636         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1637           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1638       }
1639     }
1640   }
1641 
1642   for (auto type : type_collection) {
1643     type->GetForwardCompilerType();
1644     type_list.Insert(type->shared_from_this());
1645   }
1646 }
1647 
1648 llvm::Expected<lldb_private::TypeSystem &>
1649 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1650   auto type_system_or_err =
1651       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1652   if (type_system_or_err) {
1653     type_system_or_err->SetSymbolFile(this);
1654   }
1655   return type_system_or_err;
1656 }
1657 
1658 PDBASTParser *SymbolFilePDB::GetPDBAstParser() {
1659   auto type_system_or_err =
1660       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1661   if (auto err = type_system_or_err.takeError()) {
1662     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
1663                    std::move(err), "Unable to get PDB AST parser");
1664     return nullptr;
1665   }
1666 
1667   auto *clang_type_system =
1668       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1669   if (!clang_type_system)
1670     return nullptr;
1671 
1672   return clang_type_system->GetPDBParser();
1673 }
1674 
1675 lldb_private::CompilerDeclContext
1676 SymbolFilePDB::FindNamespace(lldb_private::ConstString name,
1677                              const CompilerDeclContext &parent_decl_ctx) {
1678   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1679   auto type_system_or_err =
1680       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1681   if (auto err = type_system_or_err.takeError()) {
1682     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
1683                    std::move(err), "Unable to find namespace {}",
1684                    name.AsCString());
1685     return CompilerDeclContext();
1686   }
1687 
1688   auto *clang_type_system =
1689       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1690   if (!clang_type_system)
1691     return CompilerDeclContext();
1692 
1693   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1694   if (!pdb)
1695     return CompilerDeclContext();
1696 
1697   clang::DeclContext *decl_context = nullptr;
1698   if (parent_decl_ctx)
1699     decl_context = static_cast<clang::DeclContext *>(
1700         parent_decl_ctx.GetOpaqueDeclContext());
1701 
1702   auto namespace_decl =
1703       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1704   if (!namespace_decl)
1705     return CompilerDeclContext();
1706 
1707   return clang_type_system->CreateDeclContext(namespace_decl);
1708 }
1709 
1710 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1711 
1712 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1713   return *m_session_up;
1714 }
1715 
1716 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1717                                                        uint32_t index) {
1718   auto found_cu = m_comp_units.find(id);
1719   if (found_cu != m_comp_units.end())
1720     return found_cu->second;
1721 
1722   auto compiland_up = GetPDBCompilandByUID(id);
1723   if (!compiland_up)
1724     return CompUnitSP();
1725 
1726   lldb::LanguageType lang;
1727   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1728   if (!details)
1729     lang = lldb::eLanguageTypeC_plus_plus;
1730   else
1731     lang = TranslateLanguage(details->getLanguage());
1732 
1733   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1734     return CompUnitSP();
1735 
1736   std::string path = compiland_up->getSourceFileFullPath();
1737   if (path.empty())
1738     return CompUnitSP();
1739 
1740   // Don't support optimized code for now, DebugInfoPDB does not return this
1741   // information.
1742   LazyBool optimized = eLazyBoolNo;
1743   auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr,
1744                                              path.c_str(), id, lang, optimized);
1745 
1746   if (!cu_sp)
1747     return CompUnitSP();
1748 
1749   m_comp_units.insert(std::make_pair(id, cu_sp));
1750   if (index == UINT32_MAX)
1751     GetCompileUnitIndex(*compiland_up, index);
1752   lldbassert(index != UINT32_MAX);
1753   SetCompileUnitAtIndex(index, cu_sp);
1754   return cu_sp;
1755 }
1756 
1757 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,
1758                                               uint32_t match_line) {
1759   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1760   if (!compiland_up)
1761     return false;
1762 
1763   // LineEntry needs the *index* of the file into the list of support files
1764   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1765   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1766   // to do a mapping so that we can hand out indices.
1767   llvm::DenseMap<uint32_t, uint32_t> index_map;
1768   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1769   auto line_table = std::make_unique<LineTable>(&comp_unit);
1770 
1771   // Find contributions to `compiland` from all source and header files.
1772   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1773   if (!files)
1774     return false;
1775 
1776   // For each source and header file, create a LineSequence for contributions
1777   // to the compiland from that file, and add the sequence.
1778   while (auto file = files->getNext()) {
1779     std::unique_ptr<LineSequence> sequence(
1780         line_table->CreateLineSequenceContainer());
1781     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1782     if (!lines)
1783       continue;
1784     int entry_count = lines->getChildCount();
1785 
1786     uint64_t prev_addr;
1787     uint32_t prev_length;
1788     uint32_t prev_line;
1789     uint32_t prev_source_idx;
1790 
1791     for (int i = 0; i < entry_count; ++i) {
1792       auto line = lines->getChildAtIndex(i);
1793 
1794       uint64_t lno = line->getLineNumber();
1795       uint64_t addr = line->getVirtualAddress();
1796       uint32_t length = line->getLength();
1797       uint32_t source_id = line->getSourceFileId();
1798       uint32_t col = line->getColumnNumber();
1799       uint32_t source_idx = index_map[source_id];
1800 
1801       // There was a gap between the current entry and the previous entry if
1802       // the addresses don't perfectly line up.
1803       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1804 
1805       // Before inserting the current entry, insert a terminal entry at the end
1806       // of the previous entry's address range if the current entry resulted in
1807       // a gap from the previous entry.
1808       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1809         line_table->AppendLineEntryToSequence(
1810             sequence.get(), prev_addr + prev_length, prev_line, 0,
1811             prev_source_idx, false, false, false, false, true);
1812 
1813         line_table->InsertSequence(sequence.get());
1814         sequence = line_table->CreateLineSequenceContainer();
1815       }
1816 
1817       if (ShouldAddLine(match_line, lno, length)) {
1818         bool is_statement = line->isStatement();
1819         bool is_prologue = false;
1820         bool is_epilogue = false;
1821         auto func =
1822             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1823         if (func) {
1824           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1825           if (prologue)
1826             is_prologue = (addr == prologue->getVirtualAddress());
1827 
1828           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1829           if (epilogue)
1830             is_epilogue = (addr == epilogue->getVirtualAddress());
1831         }
1832 
1833         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1834                                               source_idx, is_statement, false,
1835                                               is_prologue, is_epilogue, false);
1836       }
1837 
1838       prev_addr = addr;
1839       prev_length = length;
1840       prev_line = lno;
1841       prev_source_idx = source_idx;
1842     }
1843 
1844     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1845       // The end is always a terminal entry, so insert it regardless.
1846       line_table->AppendLineEntryToSequence(
1847           sequence.get(), prev_addr + prev_length, prev_line, 0,
1848           prev_source_idx, false, false, false, false, true);
1849     }
1850 
1851     line_table->InsertSequence(sequence.get());
1852   }
1853 
1854   if (line_table->GetSize()) {
1855     comp_unit.SetLineTable(line_table.release());
1856     return true;
1857   }
1858   return false;
1859 }
1860 
1861 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1862     const PDBSymbolCompiland &compiland,
1863     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1864   // This is a hack, but we need to convert the source id into an index into
1865   // the support files array.  We don't want to do path comparisons to avoid
1866   // basename / full path issues that may or may not even be a problem, so we
1867   // use the globally unique source file identifiers.  Ideally we could use the
1868   // global identifiers everywhere, but LineEntry currently assumes indices.
1869   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1870   if (!source_files)
1871     return;
1872 
1873   int index = 0;
1874   while (auto file = source_files->getNext()) {
1875     uint32_t source_id = file->getUniqueId();
1876     index_map[source_id] = index++;
1877   }
1878 }
1879 
1880 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1881     const lldb_private::Address &so_addr) {
1882   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1883   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1884     return nullptr;
1885 
1886   // If it is a PDB function's vm addr, this is the first sure bet.
1887   if (auto lines =
1888           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1889     if (auto first_line = lines->getNext())
1890       return ParseCompileUnitForUID(first_line->getCompilandId());
1891   }
1892 
1893   // Otherwise we resort to section contributions.
1894   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1895     while (auto section = sec_contribs->getNext()) {
1896       auto va = section->getVirtualAddress();
1897       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1898         return ParseCompileUnitForUID(section->getCompilandId());
1899     }
1900   }
1901   return nullptr;
1902 }
1903 
1904 Mangled
1905 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1906   Mangled mangled;
1907   auto func_name = pdb_func.getName();
1908   auto func_undecorated_name = pdb_func.getUndecoratedName();
1909   std::string func_decorated_name;
1910 
1911   // Seek from public symbols for non-static function's decorated name if any.
1912   // For static functions, they don't have undecorated names and aren't exposed
1913   // in Public Symbols either.
1914   if (!func_undecorated_name.empty()) {
1915     auto result_up = m_global_scope_up->findChildren(
1916         PDB_SymType::PublicSymbol, func_undecorated_name,
1917         PDB_NameSearchFlags::NS_UndecoratedName);
1918     if (result_up) {
1919       while (auto symbol_up = result_up->getNext()) {
1920         // For a public symbol, it is unique.
1921         lldbassert(result_up->getChildCount() == 1);
1922         if (auto *pdb_public_sym =
1923                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1924                     symbol_up.get())) {
1925           if (pdb_public_sym->isFunction()) {
1926             func_decorated_name = pdb_public_sym->getName();
1927             break;
1928           }
1929         }
1930       }
1931     }
1932   }
1933   if (!func_decorated_name.empty()) {
1934     mangled.SetMangledName(ConstString(func_decorated_name));
1935 
1936     // For MSVC, format of C funciton's decorated name depends on calling
1937     // convention. Unfortunately none of the format is recognized by current
1938     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1939     // `__purecall` is retrieved as both its decorated and undecorated name
1940     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1941     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1942     // Mangled::GetDemangledName method will fail internally and caches an
1943     // empty string as its undecorated name. So we will face a contradiction
1944     // here for the same symbol:
1945     //   non-empty undecorated name from PDB
1946     //   empty undecorated name from LLDB
1947     if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty())
1948       mangled.SetDemangledName(ConstString(func_undecorated_name));
1949 
1950     // LLDB uses several flags to control how a C++ decorated name is
1951     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1952     // yielded name could be different from what we retrieve from
1953     // PDB source unless we also apply same flags in getting undecorated
1954     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1955     if (!func_undecorated_name.empty() &&
1956         mangled.GetDemangledName() != ConstString(func_undecorated_name))
1957       mangled.SetDemangledName(ConstString(func_undecorated_name));
1958   } else if (!func_undecorated_name.empty()) {
1959     mangled.SetDemangledName(ConstString(func_undecorated_name));
1960   } else if (!func_name.empty())
1961     mangled.SetValue(ConstString(func_name), false);
1962 
1963   return mangled;
1964 }
1965 
1966 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1967     const lldb_private::CompilerDeclContext &decl_ctx) {
1968   if (!decl_ctx.IsValid())
1969     return true;
1970 
1971   TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
1972   if (!decl_ctx_type_system)
1973     return false;
1974   auto type_system_or_err = GetTypeSystemForLanguage(
1975       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1976   if (auto err = type_system_or_err.takeError()) {
1977     LLDB_LOG_ERROR(
1978         lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
1979         std::move(err),
1980         "Unable to determine if DeclContext matches this symbol file");
1981     return false;
1982   }
1983 
1984   if (decl_ctx_type_system == &type_system_or_err.get())
1985     return true; // The type systems match, return true
1986 
1987   return false;
1988 }
1989 
1990 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1991   static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1992     return lhs < rhs.Offset;
1993   };
1994 
1995   // Cache section contributions
1996   if (m_sec_contribs.empty()) {
1997     if (auto SecContribs = m_session_up->getSectionContribs()) {
1998       while (auto SectionContrib = SecContribs->getNext()) {
1999         auto comp_id = SectionContrib->getCompilandId();
2000         if (!comp_id)
2001           continue;
2002 
2003         auto sec = SectionContrib->getAddressSection();
2004         auto &sec_cs = m_sec_contribs[sec];
2005 
2006         auto offset = SectionContrib->getAddressOffset();
2007         auto it =
2008             std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
2009 
2010         auto size = SectionContrib->getLength();
2011         sec_cs.insert(it, {offset, size, comp_id});
2012       }
2013     }
2014   }
2015 
2016   // Check by line number
2017   if (auto Lines = data.getLineNumbers()) {
2018     if (auto FirstLine = Lines->getNext())
2019       return FirstLine->getCompilandId();
2020   }
2021 
2022   // Retrieve section + offset
2023   uint32_t DataSection = data.getAddressSection();
2024   uint32_t DataOffset = data.getAddressOffset();
2025   if (DataSection == 0) {
2026     if (auto RVA = data.getRelativeVirtualAddress())
2027       m_session_up->addressForRVA(RVA, DataSection, DataOffset);
2028   }
2029 
2030   if (DataSection) {
2031     // Search by section contributions
2032     auto &sec_cs = m_sec_contribs[DataSection];
2033     auto it =
2034         std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
2035     if (it != sec_cs.begin()) {
2036       --it;
2037       if (DataOffset < it->Offset + it->Size)
2038         return it->CompilandId;
2039     }
2040   } else {
2041     // Search in lexical tree
2042     auto LexParentId = data.getLexicalParentId();
2043     while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
2044       if (LexParent->getSymTag() == PDB_SymType::Exe)
2045         break;
2046       if (LexParent->getSymTag() == PDB_SymType::Compiland)
2047         return LexParentId;
2048       LexParentId = LexParent->getRawSymbol().getLexicalParentId();
2049     }
2050   }
2051 
2052   return 0;
2053 }
2054