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