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 "clang/Lex/Lexer.h"
13 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Symbol/ClangASTContext.h"
17 #include "lldb/Symbol/CompileUnit.h"
18 #include "lldb/Symbol/LineTable.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolContext.h"
21 #include "lldb/Symbol/SymbolVendor.h"
22 #include "lldb/Symbol/TypeMap.h"
23 #include "lldb/Symbol/TypeList.h"
24 #include "lldb/Utility/RegularExpression.h"
25 
26 #include "llvm/DebugInfo/PDB/GenericError.h"
27 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
28 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
29 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
30 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
31 #include "llvm/DebugInfo/PDB/IPDBTable.h"
32 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
33 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
34 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
35 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
36 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
43 
44 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
45 
46 #include <regex>
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 using namespace llvm::pdb;
51 
52 namespace {
53 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
54   switch (lang) {
55   case PDB_Lang::Cpp:
56     return lldb::LanguageType::eLanguageTypeC_plus_plus;
57   case PDB_Lang::C:
58     return lldb::LanguageType::eLanguageTypeC;
59   default:
60     return lldb::LanguageType::eLanguageTypeUnknown;
61   }
62 }
63 
64 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
65                    uint32_t addr_length) {
66   return ((requested_line == 0 || actual_line == requested_line) &&
67           addr_length > 0);
68 }
69 }
70 
71 void SymbolFilePDB::Initialize() {
72   PluginManager::RegisterPlugin(GetPluginNameStatic(),
73                                 GetPluginDescriptionStatic(), CreateInstance,
74                                 DebuggerInitialize);
75 }
76 
77 void SymbolFilePDB::Terminate() {
78   PluginManager::UnregisterPlugin(CreateInstance);
79 }
80 
81 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
82 
83 lldb_private::ConstString SymbolFilePDB::GetPluginNameStatic() {
84   static ConstString g_name("pdb");
85   return g_name;
86 }
87 
88 const char *SymbolFilePDB::GetPluginDescriptionStatic() {
89   return "Microsoft PDB debug symbol file reader.";
90 }
91 
92 lldb_private::SymbolFile *
93 SymbolFilePDB::CreateInstance(lldb_private::ObjectFile *obj_file) {
94   return new SymbolFilePDB(obj_file);
95 }
96 
97 SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file)
98     : SymbolFile(object_file), m_session_up(), m_global_scope_up(),
99       m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {}
100 
101 SymbolFilePDB::~SymbolFilePDB() {}
102 
103 uint32_t SymbolFilePDB::CalculateAbilities() {
104   uint32_t abilities = 0;
105   if (!m_obj_file)
106     return 0;
107 
108   if (!m_session_up) {
109     // Lazily load and match the PDB file, but only do this once.
110     std::string exePath = m_obj_file->GetFileSpec().GetPath();
111     auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
112                                 m_session_up);
113     if (error) {
114       llvm::consumeError(std::move(error));
115       auto module_sp = m_obj_file->GetModule();
116       if (!module_sp)
117         return 0;
118       // See if any symbol file is specified through `--symfile` option.
119       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
120       if (!symfile)
121         return 0;
122       error = loadDataForPDB(PDB_ReaderType::DIA,
123                              llvm::StringRef(symfile.GetPath()),
124                              m_session_up);
125       if (error) {
126         llvm::consumeError(std::move(error));
127         return 0;
128       }
129     }
130   }
131   if (!m_session_up.get())
132     return 0;
133 
134   auto enum_tables_up = m_session_up->getEnumTables();
135   if (!enum_tables_up)
136     return 0;
137   while (auto table_up = enum_tables_up->getNext()) {
138     if (table_up->getItemCount() == 0)
139       continue;
140     auto type = table_up->getTableType();
141     switch (type) {
142     case PDB_TableType::Symbols:
143       // This table represents a store of symbols with types listed in
144       // PDBSym_Type
145       abilities |= (CompileUnits | Functions | Blocks |
146                     GlobalVariables | LocalVariables | VariableTypes);
147       break;
148     case PDB_TableType::LineNumbers:
149       abilities |= LineTables;
150       break;
151     default: break;
152     }
153   }
154   return abilities;
155 }
156 
157 void SymbolFilePDB::InitializeObject() {
158   lldb::addr_t obj_load_address = m_obj_file->GetFileOffset();
159   lldbassert(obj_load_address &&
160              obj_load_address != LLDB_INVALID_ADDRESS);
161   m_session_up->setLoadAddress(obj_load_address);
162   if (!m_global_scope_up)
163     m_global_scope_up = m_session_up->getGlobalScope();
164   lldbassert(m_global_scope_up.get());
165 
166   TypeSystem *type_system =
167       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
168   ClangASTContext *clang_type_system =
169       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
170   lldbassert(clang_type_system);
171   m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>(
172       type_system, clang_type_system->GetTranslationUnitDecl());
173 }
174 
175 uint32_t SymbolFilePDB::GetNumCompileUnits() {
176   if (m_cached_compile_unit_count == 0) {
177     auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
178     if (!compilands)
179       return 0;
180 
181     // The linker could link *.dll (compiland language = LINK), or import
182     // *.dll. For example, a compiland with name `Import:KERNEL32.dll`
183     // could be found as a child of the global scope (PDB executable).
184     // Usually, such compilands contain `thunk` symbols in which we are not
185     // interested for now. However we still count them in the compiland list.
186     // If we perform any compiland related activity, like finding symbols
187     // through llvm::pdb::IPDBSession methods, such compilands will all be
188     // searched automatically no matter whether we include them or not.
189     m_cached_compile_unit_count = compilands->getChildCount();
190 
191     // The linker can inject an additional "dummy" compilation unit into the
192     // PDB. Ignore this special compile unit for our purposes, if it is there.
193     // It is always the last one.
194     auto last_compiland_up =
195         compilands->getChildAtIndex(m_cached_compile_unit_count - 1);
196     lldbassert(last_compiland_up.get());
197     std::string name = last_compiland_up->getName();
198     if (name == "* Linker *")
199       --m_cached_compile_unit_count;
200   }
201   return m_cached_compile_unit_count;
202 }
203 
204 void SymbolFilePDB::GetCompileUnitIndex(
205     const llvm::pdb::PDBSymbolCompiland *pdb_compiland,
206     uint32_t &index) {
207   if (!pdb_compiland)
208     return;
209 
210   auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
211   if (!results_up)
212     return;
213   auto uid = pdb_compiland->getSymIndexId();
214   for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
215     auto compiland_up = results_up->getChildAtIndex(cu_idx);
216     if (!compiland_up)
217       continue;
218     if (compiland_up->getSymIndexId() == uid) {
219       index = cu_idx;
220       return;
221     }
222   }
223   index = UINT32_MAX;
224   return;
225 }
226 
227 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
228 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
229   return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
230 }
231 
232 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
233   if (index >= GetNumCompileUnits())
234     return CompUnitSP();
235 
236   // Assuming we always retrieve same compilands listed in same order through
237   // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
238   // compile unit makes no sense.
239   auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
240   if (!results)
241     return CompUnitSP();
242   auto compiland_up = results->getChildAtIndex(index);
243   if (!compiland_up)
244     return CompUnitSP();
245   return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
246 }
247 
248 lldb::LanguageType
249 SymbolFilePDB::ParseCompileUnitLanguage(const lldb_private::SymbolContext &sc) {
250   // What fields should I expect to be filled out on the SymbolContext?  Is it
251   // safe to assume that `sc.comp_unit` is valid?
252   if (!sc.comp_unit)
253     return lldb::eLanguageTypeUnknown;
254 
255   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
256   if (!compiland_up)
257     return lldb::eLanguageTypeUnknown;
258   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
259   if (!details)
260     return lldb::eLanguageTypeUnknown;
261   return TranslateLanguage(details->getLanguage());
262 }
263 
264 size_t SymbolFilePDB::ParseCompileUnitFunctions(
265     const lldb_private::SymbolContext &sc) {
266   // TODO: Implement this
267   return size_t();
268 }
269 
270 bool SymbolFilePDB::ParseCompileUnitLineTable(
271     const lldb_private::SymbolContext &sc) {
272   lldbassert(sc.comp_unit);
273   if (sc.comp_unit->GetLineTable())
274     return true;
275   return ParseCompileUnitLineTable(sc, 0);
276 }
277 
278 bool SymbolFilePDB::ParseCompileUnitDebugMacros(
279     const lldb_private::SymbolContext &sc) {
280   // PDB doesn't contain information about macros
281   return false;
282 }
283 
284 bool SymbolFilePDB::ParseCompileUnitSupportFiles(
285     const lldb_private::SymbolContext &sc,
286     lldb_private::FileSpecList &support_files) {
287   lldbassert(sc.comp_unit);
288 
289   // In theory this is unnecessary work for us, because all of this information
290   // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
291   // second time seems like a waste.  Unfortunately, there's no good way around
292   // this short of a moderate refactor since SymbolVendor depends on being able
293   // to cache this list.
294   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
295   if (!compiland_up)
296     return false;
297   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
298   if (!files || files->getChildCount() == 0)
299     return false;
300 
301   while (auto file = files->getNext()) {
302     FileSpec spec(file->getFileName(), false, FileSpec::ePathSyntaxWindows);
303     support_files.AppendIfUnique(spec);
304   }
305   return true;
306 }
307 
308 bool SymbolFilePDB::ParseImportedModules(
309     const lldb_private::SymbolContext &sc,
310     std::vector<lldb_private::ConstString> &imported_modules) {
311   // PDB does not yet support module debug info
312   return false;
313 }
314 
315 size_t
316 SymbolFilePDB::ParseFunctionBlocks(const lldb_private::SymbolContext &sc) {
317   // TODO: Implement this
318   return size_t();
319 }
320 
321 size_t SymbolFilePDB::ParseTypes(const lldb_private::SymbolContext &sc) {
322   lldbassert(sc.module_sp.get());
323   size_t num_added = 0;
324   auto results_up = m_session_up->getGlobalScope()->findAllChildren();
325   if (!results_up)
326     return 0;
327   while (auto symbol_up = results_up->getNext()) {
328     switch (symbol_up->getSymTag()) {
329     case PDB_SymType::Enum:
330     case PDB_SymType::UDT:
331     case PDB_SymType::Typedef:
332       break;
333     default:
334       continue;
335     }
336 
337     auto type_uid = symbol_up->getSymIndexId();
338     if (m_types.find(type_uid) != m_types.end())
339       continue;
340 
341     // This should cause the type to get cached and stored in the `m_types`
342     // lookup.
343     if (!ResolveTypeUID(symbol_up->getSymIndexId()))
344       continue;
345 
346     ++num_added;
347   }
348   return num_added;
349 }
350 
351 size_t
352 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
353   // TODO: Implement this
354   return size_t();
355 }
356 
357 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
358   auto find_result = m_types.find(type_uid);
359   if (find_result != m_types.end())
360     return find_result->second.get();
361 
362   TypeSystem *type_system =
363       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
364   ClangASTContext *clang_type_system =
365       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
366   if (!clang_type_system)
367     return nullptr;
368   PDBASTParser *pdb =
369       llvm::dyn_cast<PDBASTParser>(clang_type_system->GetPDBParser());
370   if (!pdb)
371     return nullptr;
372 
373   auto pdb_type = m_session_up->getSymbolById(type_uid);
374   if (pdb_type == nullptr)
375     return nullptr;
376 
377   lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
378   if (result.get()) {
379     m_types.insert(std::make_pair(type_uid, result));
380     auto type_list = GetTypeList();
381     type_list->Insert(result);
382   }
383   return result.get();
384 }
385 
386 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
387   // TODO: Implement this
388   return false;
389 }
390 
391 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
392   return lldb_private::CompilerDecl();
393 }
394 
395 lldb_private::CompilerDeclContext
396 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
397   // PDB always uses the translation unit decl context for everything.  We can
398   // improve this later but it's not easy because PDB doesn't provide a high
399   // enough level of type fidelity in this area.
400   return *m_tu_decl_ctx_up;
401 }
402 
403 lldb_private::CompilerDeclContext
404 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
405   return *m_tu_decl_ctx_up;
406 }
407 
408 void SymbolFilePDB::ParseDeclsForContext(
409     lldb_private::CompilerDeclContext decl_ctx) {}
410 
411 uint32_t
412 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
413                                     uint32_t resolve_scope,
414                                     lldb_private::SymbolContext &sc) {
415   return uint32_t();
416 }
417 
418 std::string SymbolFilePDB::GetSourceFileNameForPDBCompiland(
419     const PDBSymbolCompiland *pdb_compiland) {
420   if (!pdb_compiland)
421     return std::string();
422 
423   std::string source_file_name;
424   // `getSourceFileName` returns the basename of the original source file
425   // used to generate this compiland.  It does not return the full path.
426   // Currently the only way to get that is to do a basename lookup to get the
427   // IPDBSourceFile, but this is ambiguous in the case of two source files
428   // with the same name contributing to the same compiland. This is an edge
429   // case that we ignore for now, although we need to a long-term solution.
430   std::string file_name = pdb_compiland->getSourceFileName();
431   if (!file_name.empty()) {
432     auto one_src_file_up =
433       m_session_up->findOneSourceFile(pdb_compiland, file_name,
434                                       PDB_NameSearchFlags::NS_CaseInsensitive);
435     if (one_src_file_up)
436       source_file_name = one_src_file_up->getFileName();
437   }
438   // For some reason, source file name could be empty, so we will walk through
439   // all source files of this compiland, and determine the right source file
440   // if any that is used to generate this compiland based on language
441   // indicated in compilanddetails language field.
442   if (!source_file_name.empty())
443     return source_file_name;
444 
445   auto details_up = pdb_compiland->findOneChild<PDBSymbolCompilandDetails>();
446   PDB_Lang pdb_lang = details_up ? details_up->getLanguage() : PDB_Lang::Cpp;
447   auto src_files_up =
448     m_session_up->getSourceFilesForCompiland(*pdb_compiland);
449   if (src_files_up) {
450     while (auto file_up = src_files_up->getNext()) {
451       FileSpec file_spec(file_up->getFileName(), false,
452                          FileSpec::ePathSyntaxWindows);
453       auto file_extension = file_spec.GetFileNameExtension();
454       if (pdb_lang == PDB_Lang::Cpp || pdb_lang == PDB_Lang::C) {
455         static const char* exts[] = { "cpp", "c", "cc", "cxx" };
456         if (llvm::is_contained(exts, file_extension.GetStringRef().lower()))
457           source_file_name = file_up->getFileName();
458         break;
459       } else if (pdb_lang == PDB_Lang::Masm &&
460                  ConstString::Compare(file_extension, ConstString("ASM"),
461                                       false) == 0) {
462         source_file_name = file_up->getFileName();
463         break;
464       }
465     }
466   }
467   return source_file_name;
468 }
469 
470 uint32_t SymbolFilePDB::ResolveSymbolContext(
471     const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
472     uint32_t resolve_scope, lldb_private::SymbolContextList &sc_list) {
473   const size_t old_size = sc_list.GetSize();
474   if (resolve_scope & lldb::eSymbolContextCompUnit) {
475     // Locate all compilation units with line numbers referencing the specified
476     // file.  For example, if `file_spec` is <vector>, then this should return
477     // all source files and header files that reference <vector>, either
478     // directly or indirectly.
479     auto compilands = m_session_up->findCompilandsForSourceFile(
480         file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
481 
482     if (!compilands)
483       return 0;
484 
485     // For each one, either find its previously parsed data or parse it afresh
486     // and add it to the symbol context list.
487     while (auto compiland = compilands->getNext()) {
488       // If we're not checking inlines, then don't add line information for this
489       // file unless the FileSpec matches.
490       if (!check_inlines) {
491         // `getSourceFileName` returns the basename of the original source file
492         // used to generate this compiland.  It does not return the full path.
493         // Currently the only way to get that is to do a basename lookup to get
494         // the IPDBSourceFile, but this is ambiguous in the case of two source
495         // files with the same name contributing to the same compiland.  This is
496         // a moderately extreme edge case, so we consider this OK for now,
497         // although we need to find a long-term solution.
498         std::string source_file =
499             GetSourceFileNameForPDBCompiland(compiland.get());
500         if (source_file.empty())
501           continue;
502         FileSpec this_spec(source_file, false, FileSpec::ePathSyntaxWindows);
503         bool need_full_match = !file_spec.GetDirectory().IsEmpty();
504         if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
505           continue;
506       }
507 
508       SymbolContext sc;
509       auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
510       if (!cu.get())
511         continue;
512       sc.comp_unit = cu.get();
513       sc.module_sp = cu->GetModule();
514       sc_list.Append(sc);
515 
516       // If we were asked to resolve line entries, add all entries to the line
517       // table that match the requested line (or all lines if `line` == 0).
518       if (resolve_scope & lldb::eSymbolContextLineEntry)
519         ParseCompileUnitLineTable(sc, line);
520     }
521   }
522   return sc_list.GetSize() - old_size;
523 }
524 
525 uint32_t SymbolFilePDB::FindGlobalVariables(
526     const lldb_private::ConstString &name,
527     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
528     uint32_t max_matches, lldb_private::VariableList &variables) {
529   return uint32_t();
530 }
531 
532 uint32_t
533 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression &regex,
534                                    bool append, uint32_t max_matches,
535                                    lldb_private::VariableList &variables) {
536   return uint32_t();
537 }
538 
539 uint32_t SymbolFilePDB::FindFunctions(
540     const lldb_private::ConstString &name,
541     const lldb_private::CompilerDeclContext *parent_decl_ctx,
542     uint32_t name_type_mask, bool include_inlines, bool append,
543     lldb_private::SymbolContextList &sc_list) {
544   return uint32_t();
545 }
546 
547 uint32_t
548 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
549                              bool include_inlines, bool append,
550                              lldb_private::SymbolContextList &sc_list) {
551   return uint32_t();
552 }
553 
554 void SymbolFilePDB::GetMangledNamesForFunction(
555     const std::string &scope_qualified_name,
556     std::vector<lldb_private::ConstString> &mangled_names) {}
557 
558 uint32_t SymbolFilePDB::FindTypes(
559     const lldb_private::SymbolContext &sc,
560     const lldb_private::ConstString &name,
561     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
562     uint32_t max_matches,
563     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
564     lldb_private::TypeMap &types) {
565   if (!append)
566     types.Clear();
567   if (!name)
568     return 0;
569 
570   searched_symbol_files.clear();
571   searched_symbol_files.insert(this);
572 
573   std::string name_str = name.AsCString();
574 
575   // There is an assumption 'name' is not a regex
576   FindTypesByName(name_str, max_matches, types);
577 
578   return types.GetSize();
579 }
580 
581 void
582 SymbolFilePDB::FindTypesByRegex(const lldb_private::RegularExpression &regex,
583                                 uint32_t max_matches,
584                                 lldb_private::TypeMap &types) {
585   // When searching by regex, we need to go out of our way to limit the search
586   // space as much as possible since this searches EVERYTHING in the PDB,
587   // manually doing regex comparisons.  PDB library isn't optimized for regex
588   // searches or searches across multiple symbol types at the same time, so the
589   // best we can do is to search enums, then typedefs, then classes one by one,
590   // and do a regex comparison against each of them.
591   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
592                                   PDB_SymType::UDT};
593   std::unique_ptr<IPDBEnumSymbols> results;
594 
595   uint32_t matches = 0;
596 
597   for (auto tag : tags_to_search) {
598     results = m_global_scope_up->findAllChildren(tag);
599     if (!results)
600       continue;
601 
602     while (auto result = results->getNext()) {
603       if (max_matches > 0 && matches >= max_matches)
604         break;
605 
606       std::string type_name;
607       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
608         type_name = enum_type->getName();
609       else if (auto typedef_type =
610                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
611         type_name = typedef_type->getName();
612       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
613         type_name = class_type->getName();
614       else {
615         // We're looking only for types that have names.  Skip symbols, as well
616         // as unnamed types such as arrays, pointers, etc.
617         continue;
618       }
619 
620       if (!regex.Execute(type_name))
621         continue;
622 
623       // This should cause the type to get cached and stored in the `m_types`
624       // lookup.
625       if (!ResolveTypeUID(result->getSymIndexId()))
626         continue;
627 
628       auto iter = m_types.find(result->getSymIndexId());
629       if (iter == m_types.end())
630         continue;
631       types.Insert(iter->second);
632       ++matches;
633     }
634   }
635 }
636 
637 void SymbolFilePDB::FindTypesByName(const std::string &name,
638                                     uint32_t max_matches,
639                                     lldb_private::TypeMap &types) {
640   std::unique_ptr<IPDBEnumSymbols> results;
641   results = m_global_scope_up->findChildren(PDB_SymType::None, name,
642                                             PDB_NameSearchFlags::NS_Default);
643   if (!results)
644     return;
645 
646   uint32_t matches = 0;
647 
648   while (auto result = results->getNext()) {
649     if (max_matches > 0 && matches >= max_matches)
650       break;
651     switch (result->getSymTag()) {
652     case PDB_SymType::Enum:
653     case PDB_SymType::UDT:
654     case PDB_SymType::Typedef:
655       break;
656     default:
657       // We're looking only for types that have names.  Skip symbols, as well as
658       // unnamed types such as arrays, pointers, etc.
659       continue;
660     }
661 
662     // This should cause the type to get cached and stored in the `m_types`
663     // lookup.
664     if (!ResolveTypeUID(result->getSymIndexId()))
665       continue;
666 
667     auto iter = m_types.find(result->getSymIndexId());
668     if (iter == m_types.end())
669       continue;
670     types.Insert(iter->second);
671     ++matches;
672   }
673 }
674 
675 size_t SymbolFilePDB::FindTypes(
676     const std::vector<lldb_private::CompilerContext> &contexts, bool append,
677     lldb_private::TypeMap &types) {
678   return 0;
679 }
680 
681 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
682   return m_obj_file->GetModule()->GetTypeList();
683 }
684 
685 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
686                                uint32_t type_mask,
687                                lldb_private::TypeList &type_list) {
688   return size_t();
689 }
690 
691 lldb_private::TypeSystem *
692 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
693   auto type_system =
694       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
695   if (type_system)
696     type_system->SetSymbolFile(this);
697   return type_system;
698 }
699 
700 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
701     const lldb_private::SymbolContext &sc,
702     const lldb_private::ConstString &name,
703     const lldb_private::CompilerDeclContext *parent_decl_ctx) {
704   return lldb_private::CompilerDeclContext();
705 }
706 
707 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
708   static ConstString g_name("pdb");
709   return g_name;
710 }
711 
712 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
713 
714 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
715 
716 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
717   return *m_session_up;
718 }
719 
720 lldb::CompUnitSP
721 SymbolFilePDB::ParseCompileUnitForUID(uint32_t id, uint32_t index) {
722   auto found_cu = m_comp_units.find(id);
723   if (found_cu != m_comp_units.end())
724     return found_cu->second;
725 
726   auto compiland_up = GetPDBCompilandByUID(id);
727   if (!compiland_up)
728     return CompUnitSP();
729   std::string path = GetSourceFileNameForPDBCompiland(compiland_up.get());
730   if (path.empty())
731     return CompUnitSP();
732 
733   lldb::LanguageType lang;
734   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
735   if (!details)
736     lang = lldb::eLanguageTypeC_plus_plus;
737   else
738     lang = TranslateLanguage(details->getLanguage());
739 
740   // Don't support optimized code for now, DebugInfoPDB does not return this
741   // information.
742   LazyBool optimized = eLazyBoolNo;
743   auto cu_sp = std::make_shared<CompileUnit>(
744       m_obj_file->GetModule(), nullptr, path.c_str(), id, lang, optimized);
745 
746   if (!cu_sp)
747     return CompUnitSP();
748 
749   m_comp_units.insert(std::make_pair(id, cu_sp));
750   if (index == UINT32_MAX)
751     GetCompileUnitIndex(compiland_up.get(), index);
752   lldbassert(index != UINT32_MAX);
753   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
754       index, cu_sp);
755   return cu_sp;
756 }
757 
758 bool SymbolFilePDB::ParseCompileUnitLineTable(
759     const lldb_private::SymbolContext &sc, uint32_t match_line) {
760   lldbassert(sc.comp_unit);
761 
762   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
763   if (!compiland_up)
764     return false;
765 
766   // LineEntry needs the *index* of the file into the list of support files
767   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
768   // a globally unique idenfitifier in the namespace of the PDB.  So, we have to
769   // do a mapping so that we can hand out indices.
770   llvm::DenseMap<uint32_t, uint32_t> index_map;
771   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
772   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
773 
774   // Find contributions to `compiland` from all source and header files.
775   std::string path = sc.comp_unit->GetPath();
776   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
777   if (!files)
778     return false;
779 
780   // For each source and header file, create a LineSequence for contributions to
781   // the compiland from that file, and add the sequence.
782   while (auto file = files->getNext()) {
783     std::unique_ptr<LineSequence> sequence(
784         line_table->CreateLineSequenceContainer());
785     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
786     if (!lines)
787       continue;
788     int entry_count = lines->getChildCount();
789 
790     uint64_t prev_addr;
791     uint32_t prev_length;
792     uint32_t prev_line;
793     uint32_t prev_source_idx;
794 
795     for (int i = 0; i < entry_count; ++i) {
796       auto line = lines->getChildAtIndex(i);
797 
798       uint64_t lno = line->getLineNumber();
799       uint64_t addr = line->getVirtualAddress();
800       uint32_t length = line->getLength();
801       uint32_t source_id = line->getSourceFileId();
802       uint32_t col = line->getColumnNumber();
803       uint32_t source_idx = index_map[source_id];
804 
805       // There was a gap between the current entry and the previous entry if the
806       // addresses don't perfectly line up.
807       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
808 
809       // Before inserting the current entry, insert a terminal entry at the end
810       // of the previous entry's address range if the current entry resulted in
811       // a gap from the previous entry.
812       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
813         line_table->AppendLineEntryToSequence(
814             sequence.get(), prev_addr + prev_length, prev_line, 0,
815             prev_source_idx, false, false, false, false, true);
816       }
817 
818       if (ShouldAddLine(match_line, lno, length)) {
819         bool is_statement = line->isStatement();
820         bool is_prologue = false;
821         bool is_epilogue = false;
822         auto func =
823             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
824         if (func) {
825           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
826           if (prologue)
827             is_prologue = (addr == prologue->getVirtualAddress());
828 
829           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
830           if (epilogue)
831             is_epilogue = (addr == epilogue->getVirtualAddress());
832         }
833 
834         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
835                                               source_idx, is_statement, false,
836                                               is_prologue, is_epilogue, false);
837       }
838 
839       prev_addr = addr;
840       prev_length = length;
841       prev_line = lno;
842       prev_source_idx = source_idx;
843     }
844 
845     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
846       // The end is always a terminal entry, so insert it regardless.
847       line_table->AppendLineEntryToSequence(
848           sequence.get(), prev_addr + prev_length, prev_line, 0,
849           prev_source_idx, false, false, false, false, true);
850     }
851 
852     line_table->InsertSequence(sequence.release());
853   }
854 
855   if (line_table->GetSize()) {
856     sc.comp_unit->SetLineTable(line_table.release());
857     return true;
858   }
859   return false;
860 }
861 
862 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
863     const PDBSymbolCompiland &compiland,
864     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
865   // This is a hack, but we need to convert the source id into an index into the
866   // support files array.  We don't want to do path comparisons to avoid
867   // basename / full path issues that may or may not even be a problem, so we
868   // use the globally unique source file identifiers.  Ideally we could use the
869   // global identifiers everywhere, but LineEntry currently assumes indices.
870   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
871   if (!source_files)
872     return;
873   int index = 0;
874 
875   while (auto file = source_files->getNext()) {
876     uint32_t source_id = file->getUniqueId();
877     index_map[source_id] = index++;
878   }
879 }
880