1 //===-- SymbolFileNativePDB.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolFileNativePDB.h"
10 
11 #include "clang/AST/Attr.h"
12 #include "clang/AST/CharUnits.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/Type.h"
16 
17 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
18 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
19 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/StreamBuffer.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/LineTable.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Symbol/SymbolContext.h"
28 #include "lldb/Symbol/SymbolVendor.h"
29 #include "lldb/Symbol/Variable.h"
30 #include "lldb/Symbol/VariableList.h"
31 #include "lldb/Utility/Log.h"
32 
33 #include "llvm/DebugInfo/CodeView/CVRecord.h"
34 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
35 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
36 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
37 #include "llvm/DebugInfo/CodeView/RecordName.h"
38 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
39 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
40 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
41 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
42 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
43 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
44 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
45 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
46 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
47 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
48 #include "llvm/DebugInfo/PDB/PDBTypes.h"
49 #include "llvm/Demangle/MicrosoftDemangle.h"
50 #include "llvm/Object/COFF.h"
51 #include "llvm/Support/Allocator.h"
52 #include "llvm/Support/BinaryStreamReader.h"
53 #include "llvm/Support/Error.h"
54 #include "llvm/Support/ErrorOr.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 
57 #include "DWARFLocationExpression.h"
58 #include "PdbAstBuilder.h"
59 #include "PdbSymUid.h"
60 #include "PdbUtil.h"
61 #include "UdtRecordCompleter.h"
62 
63 using namespace lldb;
64 using namespace lldb_private;
65 using namespace npdb;
66 using namespace llvm::codeview;
67 using namespace llvm::pdb;
68 
69 LLDB_PLUGIN_DEFINE(SymbolFileNativePDB)
70 
71 char SymbolFileNativePDB::ID;
72 
73 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
74   switch (lang) {
75   case PDB_Lang::Cpp:
76     return lldb::LanguageType::eLanguageTypeC_plus_plus;
77   case PDB_Lang::C:
78     return lldb::LanguageType::eLanguageTypeC;
79   case PDB_Lang::Swift:
80     return lldb::LanguageType::eLanguageTypeSwift;
81   default:
82     return lldb::LanguageType::eLanguageTypeUnknown;
83   }
84 }
85 
86 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
87                                             llvm::BumpPtrAllocator &Allocator) {
88   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
89       llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
90                                   /*RequiresNullTerminator=*/false);
91   if (!ErrorOrBuffer)
92     return nullptr;
93   std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
94 
95   llvm::StringRef Path = Buffer->getBufferIdentifier();
96   auto Stream = std::make_unique<llvm::MemoryBufferByteStream>(
97       std::move(Buffer), llvm::support::little);
98 
99   auto File = std::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
100   if (auto EC = File->parseFileHeaders()) {
101     llvm::consumeError(std::move(EC));
102     return nullptr;
103   }
104   if (auto EC = File->parseStreamData()) {
105     llvm::consumeError(std::move(EC));
106     return nullptr;
107   }
108 
109   return File;
110 }
111 
112 static std::unique_ptr<PDBFile>
113 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
114   // Try to find a matching PDB for an EXE.
115   using namespace llvm::object;
116   auto expected_binary = createBinary(exe_path);
117 
118   // If the file isn't a PE/COFF executable, fail.
119   if (!expected_binary) {
120     llvm::consumeError(expected_binary.takeError());
121     return nullptr;
122   }
123   OwningBinary<Binary> binary = std::move(*expected_binary);
124 
125   // TODO: Avoid opening the PE/COFF binary twice by reading this information
126   // directly from the lldb_private::ObjectFile.
127   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
128   if (!obj)
129     return nullptr;
130   const llvm::codeview::DebugInfo *pdb_info = nullptr;
131 
132   // If it doesn't have a debug directory, fail.
133   llvm::StringRef pdb_file;
134   auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
135   if (ec)
136     return nullptr;
137 
138   // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
139   // fail.
140   llvm::file_magic magic;
141   ec = llvm::identify_magic(pdb_file, magic);
142   if (ec || magic != llvm::file_magic::pdb)
143     return nullptr;
144   std::unique_ptr<PDBFile> pdb = loadPDBFile(std::string(pdb_file), allocator);
145   if (!pdb)
146     return nullptr;
147 
148   auto expected_info = pdb->getPDBInfoStream();
149   if (!expected_info) {
150     llvm::consumeError(expected_info.takeError());
151     return nullptr;
152   }
153   llvm::codeview::GUID guid;
154   memcpy(&guid, pdb_info->PDB70.Signature, 16);
155 
156   if (expected_info->getGuid() != guid)
157     return nullptr;
158   return pdb;
159 }
160 
161 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
162                                lldb::addr_t addr) {
163   // FIXME: Implement this.
164   return false;
165 }
166 
167 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
168                                lldb::addr_t addr) {
169   // FIXME: Implement this.
170   return false;
171 }
172 
173 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
174   switch (kind) {
175   case SimpleTypeKind::Boolean128:
176   case SimpleTypeKind::Boolean16:
177   case SimpleTypeKind::Boolean32:
178   case SimpleTypeKind::Boolean64:
179   case SimpleTypeKind::Boolean8:
180     return "bool";
181   case SimpleTypeKind::Byte:
182   case SimpleTypeKind::UnsignedCharacter:
183     return "unsigned char";
184   case SimpleTypeKind::NarrowCharacter:
185     return "char";
186   case SimpleTypeKind::SignedCharacter:
187   case SimpleTypeKind::SByte:
188     return "signed char";
189   case SimpleTypeKind::Character16:
190     return "char16_t";
191   case SimpleTypeKind::Character32:
192     return "char32_t";
193   case SimpleTypeKind::Complex80:
194   case SimpleTypeKind::Complex64:
195   case SimpleTypeKind::Complex32:
196     return "complex";
197   case SimpleTypeKind::Float128:
198   case SimpleTypeKind::Float80:
199     return "long double";
200   case SimpleTypeKind::Float64:
201     return "double";
202   case SimpleTypeKind::Float32:
203     return "float";
204   case SimpleTypeKind::Float16:
205     return "single";
206   case SimpleTypeKind::Int128:
207     return "__int128";
208   case SimpleTypeKind::Int64:
209   case SimpleTypeKind::Int64Quad:
210     return "int64_t";
211   case SimpleTypeKind::Int32:
212     return "int";
213   case SimpleTypeKind::Int16:
214     return "short";
215   case SimpleTypeKind::UInt128:
216     return "unsigned __int128";
217   case SimpleTypeKind::UInt64:
218   case SimpleTypeKind::UInt64Quad:
219     return "uint64_t";
220   case SimpleTypeKind::HResult:
221     return "HRESULT";
222   case SimpleTypeKind::UInt32:
223     return "unsigned";
224   case SimpleTypeKind::UInt16:
225   case SimpleTypeKind::UInt16Short:
226     return "unsigned short";
227   case SimpleTypeKind::Int32Long:
228     return "long";
229   case SimpleTypeKind::UInt32Long:
230     return "unsigned long";
231   case SimpleTypeKind::Void:
232     return "void";
233   case SimpleTypeKind::WideCharacter:
234     return "wchar_t";
235   default:
236     return "";
237   }
238 }
239 
240 static bool IsClassRecord(TypeLeafKind kind) {
241   switch (kind) {
242   case LF_STRUCTURE:
243   case LF_CLASS:
244   case LF_INTERFACE:
245     return true;
246   default:
247     return false;
248   }
249 }
250 
251 void SymbolFileNativePDB::Initialize() {
252   PluginManager::RegisterPlugin(GetPluginNameStatic(),
253                                 GetPluginDescriptionStatic(), CreateInstance,
254                                 DebuggerInitialize);
255 }
256 
257 void SymbolFileNativePDB::Terminate() {
258   PluginManager::UnregisterPlugin(CreateInstance);
259 }
260 
261 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
262 
263 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
264   static ConstString g_name("native-pdb");
265   return g_name;
266 }
267 
268 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
269   return "Microsoft PDB debug symbol cross-platform file reader.";
270 }
271 
272 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) {
273   return new SymbolFileNativePDB(std::move(objfile_sp));
274 }
275 
276 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp)
277     : SymbolFile(std::move(objfile_sp)) {}
278 
279 SymbolFileNativePDB::~SymbolFileNativePDB() {}
280 
281 uint32_t SymbolFileNativePDB::CalculateAbilities() {
282   uint32_t abilities = 0;
283   if (!m_objfile_sp)
284     return 0;
285 
286   if (!m_index) {
287     // Lazily load and match the PDB file, but only do this once.
288     std::unique_ptr<PDBFile> file_up =
289         loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(), m_allocator);
290 
291     if (!file_up) {
292       auto module_sp = m_objfile_sp->GetModule();
293       if (!module_sp)
294         return 0;
295       // See if any symbol file is specified through `--symfile` option.
296       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
297       if (!symfile)
298         return 0;
299       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
300     }
301 
302     if (!file_up)
303       return 0;
304 
305     auto expected_index = PdbIndex::create(std::move(file_up));
306     if (!expected_index) {
307       llvm::consumeError(expected_index.takeError());
308       return 0;
309     }
310     m_index = std::move(*expected_index);
311   }
312   if (!m_index)
313     return 0;
314 
315   // We don't especially have to be precise here.  We only distinguish between
316   // stripped and not stripped.
317   abilities = kAllAbilities;
318 
319   if (m_index->dbi().isStripped())
320     abilities &= ~(Blocks | LocalVariables);
321   return abilities;
322 }
323 
324 void SymbolFileNativePDB::InitializeObject() {
325   m_obj_load_address = m_objfile_sp->GetBaseAddress().GetFileAddress();
326   m_index->SetLoadAddress(m_obj_load_address);
327   m_index->ParseSectionContribs();
328 
329   auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
330       lldb::eLanguageTypeC_plus_plus);
331   if (auto err = ts_or_err.takeError()) {
332     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
333                    std::move(err), "Failed to initialize");
334   } else {
335     ts_or_err->SetSymbolFile(this);
336     auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get());
337     lldbassert(clang);
338     m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang);
339   }
340 }
341 
342 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() {
343   const DbiModuleList &modules = m_index->dbi().modules();
344   uint32_t count = modules.getModuleCount();
345   if (count == 0)
346     return count;
347 
348   // The linker can inject an additional "dummy" compilation unit into the
349   // PDB. Ignore this special compile unit for our purposes, if it is there.
350   // It is always the last one.
351   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
352   if (last.getModuleName() == "* Linker *")
353     --count;
354   return count;
355 }
356 
357 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
358   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
359   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
360 
361   if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) {
362     // This is a function.  It must be global.  Creating the Function entry for
363     // it automatically creates a block for it.
364     CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
365     return GetOrCreateFunction(block_id, *comp_unit)->GetBlock(false);
366   }
367 
368   lldbassert(sym.kind() == S_BLOCK32);
369 
370   // This is a block.  Its parent is either a function or another block.  In
371   // either case, its parent can be viewed as a block (e.g. a function contains
372   // 1 big block.  So just get the parent block and add this block to it.
373   BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
374   cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
375   lldbassert(block.Parent != 0);
376   PdbCompilandSymId parent_id(block_id.modi, block.Parent);
377   Block &parent_block = GetOrCreateBlock(parent_id);
378   lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
379   BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
380   parent_block.AddChild(child_block);
381 
382   m_ast->GetOrCreateBlockDecl(block_id);
383 
384   m_blocks.insert({opaque_block_uid, child_block});
385   return *child_block;
386 }
387 
388 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
389                                                      CompileUnit &comp_unit) {
390   const CompilandIndexItem *cci =
391       m_index->compilands().GetCompiland(func_id.modi);
392   lldbassert(cci);
393   CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
394 
395   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
396   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
397 
398   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
399   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
400     return nullptr;
401 
402   AddressRange func_range(file_vm_addr, sol.length,
403                           comp_unit.GetModule()->GetSectionList());
404   if (!func_range.GetBaseAddress().IsValid())
405     return nullptr;
406 
407   ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
408   cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
409   if (proc.FunctionType == TypeIndex::None())
410     return nullptr;
411   TypeSP func_type = GetOrCreateType(proc.FunctionType);
412   if (!func_type)
413     return nullptr;
414 
415   PdbTypeSymId sig_id(proc.FunctionType, false);
416   Mangled mangled(proc.Name);
417   FunctionSP func_sp = std::make_shared<Function>(
418       &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
419       func_type.get(), func_range);
420 
421   comp_unit.AddFunction(func_sp);
422 
423   m_ast->GetOrCreateFunctionDecl(func_id);
424 
425   return func_sp;
426 }
427 
428 CompUnitSP
429 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
430   lldb::LanguageType lang =
431       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
432                          : lldb::eLanguageTypeUnknown;
433 
434   LazyBool optimized = eLazyBoolNo;
435   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
436     optimized = eLazyBoolYes;
437 
438   llvm::SmallString<64> source_file_name =
439       m_index->compilands().GetMainSourceFile(cci);
440   FileSpec fs(source_file_name);
441 
442   CompUnitSP cu_sp =
443       std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs,
444                                     toOpaqueUid(cci.m_id), lang, optimized);
445 
446   SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
447   return cu_sp;
448 }
449 
450 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
451                                                      const ModifierRecord &mr,
452                                                      CompilerType ct) {
453   TpiStream &stream = m_index->tpi();
454 
455   std::string name;
456   if (mr.ModifiedType.isSimple())
457     name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind()));
458   else
459     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
460   Declaration decl;
461   lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
462 
463   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name),
464                                 modified_type->GetByteSize(), nullptr,
465                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
466                                 ct, Type::ResolveState::Full);
467 }
468 
469 lldb::TypeSP
470 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id,
471                                        const llvm::codeview::PointerRecord &pr,
472                                        CompilerType ct) {
473   TypeSP pointee = GetOrCreateType(pr.ReferentType);
474   if (!pointee)
475     return nullptr;
476 
477   if (pr.isPointerToMember()) {
478     MemberPointerInfo mpi = pr.getMemberInfo();
479     GetOrCreateType(mpi.ContainingType);
480   }
481 
482   Declaration decl;
483   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(),
484                                 pr.getSize(), nullptr, LLDB_INVALID_UID,
485                                 Type::eEncodingIsUID, decl, ct,
486                                 Type::ResolveState::Full);
487 }
488 
489 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti,
490                                                    CompilerType ct) {
491   uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
492   if (ti == TypeIndex::NullptrT()) {
493     Declaration decl;
494     return std::make_shared<Type>(
495         uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
496         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
497   }
498 
499   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
500     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
501     uint32_t pointer_size = 0;
502     switch (ti.getSimpleMode()) {
503     case SimpleTypeMode::FarPointer32:
504     case SimpleTypeMode::NearPointer32:
505       pointer_size = 4;
506       break;
507     case SimpleTypeMode::NearPointer64:
508       pointer_size = 8;
509       break;
510     default:
511       // 128-bit and 16-bit pointers unsupported.
512       return nullptr;
513     }
514     Declaration decl;
515     return std::make_shared<Type>(
516         uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
517         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
518   }
519 
520   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
521     return nullptr;
522 
523   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
524   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
525 
526   Declaration decl;
527   return std::make_shared<Type>(uid, this, ConstString(type_name), size,
528                                 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID,
529                                 decl, ct, Type::ResolveState::Full);
530 }
531 
532 static std::string GetUnqualifiedTypeName(const TagRecord &record) {
533   if (!record.hasUniqueName()) {
534     MSVCUndecoratedNameParser parser(record.Name);
535     llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
536 
537     return std::string(specs.back().GetBaseName());
538   }
539 
540   llvm::ms_demangle::Demangler demangler;
541   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
542   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
543   if (demangler.Error)
544     return std::string(record.Name);
545 
546   llvm::ms_demangle::IdentifierNode *idn =
547       ttn->QualifiedName->getUnqualifiedIdentifier();
548   return idn->toString();
549 }
550 
551 lldb::TypeSP
552 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id,
553                                             const TagRecord &record,
554                                             size_t size, CompilerType ct) {
555 
556   std::string uname = GetUnqualifiedTypeName(record);
557 
558   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
559   Declaration decl;
560   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname),
561                                 size, nullptr, LLDB_INVALID_UID,
562                                 Type::eEncodingIsUID, decl, ct,
563                                 Type::ResolveState::Forward);
564 }
565 
566 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
567                                                 const ClassRecord &cr,
568                                                 CompilerType ct) {
569   return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
570 }
571 
572 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
573                                                 const UnionRecord &ur,
574                                                 CompilerType ct) {
575   return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
576 }
577 
578 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
579                                                 const EnumRecord &er,
580                                                 CompilerType ct) {
581   std::string uname = GetUnqualifiedTypeName(er);
582 
583   Declaration decl;
584   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
585 
586   return std::make_shared<lldb_private::Type>(
587       toOpaqueUid(type_id), this, ConstString(uname),
588       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
589       lldb_private::Type::eEncodingIsUID, decl, ct,
590       lldb_private::Type::ResolveState::Forward);
591 }
592 
593 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
594                                             const ArrayRecord &ar,
595                                             CompilerType ct) {
596   TypeSP element_type = GetOrCreateType(ar.ElementType);
597 
598   Declaration decl;
599   TypeSP array_sp = std::make_shared<lldb_private::Type>(
600       toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr,
601       LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct,
602       lldb_private::Type::ResolveState::Full);
603   array_sp->SetEncodingType(element_type.get());
604   return array_sp;
605 }
606 
607 
608 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id,
609                                                const MemberFunctionRecord &mfr,
610                                                CompilerType ct) {
611   Declaration decl;
612   return std::make_shared<lldb_private::Type>(
613       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
614       lldb_private::Type::eEncodingIsUID, decl, ct,
615       lldb_private::Type::ResolveState::Full);
616 }
617 
618 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
619                                                 const ProcedureRecord &pr,
620                                                 CompilerType ct) {
621   Declaration decl;
622   return std::make_shared<lldb_private::Type>(
623       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
624       lldb_private::Type::eEncodingIsUID, decl, ct,
625       lldb_private::Type::ResolveState::Full);
626 }
627 
628 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) {
629   if (type_id.index.isSimple())
630     return CreateSimpleType(type_id.index, ct);
631 
632   TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
633   CVType cvt = stream.getType(type_id.index);
634 
635   if (cvt.kind() == LF_MODIFIER) {
636     ModifierRecord modifier;
637     llvm::cantFail(
638         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
639     return CreateModifierType(type_id, modifier, ct);
640   }
641 
642   if (cvt.kind() == LF_POINTER) {
643     PointerRecord pointer;
644     llvm::cantFail(
645         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
646     return CreatePointerType(type_id, pointer, ct);
647   }
648 
649   if (IsClassRecord(cvt.kind())) {
650     ClassRecord cr;
651     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
652     return CreateTagType(type_id, cr, ct);
653   }
654 
655   if (cvt.kind() == LF_ENUM) {
656     EnumRecord er;
657     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
658     return CreateTagType(type_id, er, ct);
659   }
660 
661   if (cvt.kind() == LF_UNION) {
662     UnionRecord ur;
663     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
664     return CreateTagType(type_id, ur, ct);
665   }
666 
667   if (cvt.kind() == LF_ARRAY) {
668     ArrayRecord ar;
669     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
670     return CreateArrayType(type_id, ar, ct);
671   }
672 
673   if (cvt.kind() == LF_PROCEDURE) {
674     ProcedureRecord pr;
675     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
676     return CreateProcedureType(type_id, pr, ct);
677   }
678   if (cvt.kind() == LF_MFUNCTION) {
679     MemberFunctionRecord mfr;
680     llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
681     return CreateFunctionType(type_id, mfr, ct);
682   }
683 
684   return nullptr;
685 }
686 
687 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
688   // If they search for a UDT which is a forward ref, try and resolve the full
689   // decl and just map the forward ref uid to the full decl record.
690   llvm::Optional<PdbTypeSymId> full_decl_uid;
691   if (IsForwardRefUdt(type_id, m_index->tpi())) {
692     auto expected_full_ti =
693         m_index->tpi().findFullDeclForForwardRef(type_id.index);
694     if (!expected_full_ti)
695       llvm::consumeError(expected_full_ti.takeError());
696     else if (*expected_full_ti != type_id.index) {
697       full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
698 
699       // It's possible that a lookup would occur for the full decl causing it
700       // to be cached, then a second lookup would occur for the forward decl.
701       // We don't want to create a second full decl, so make sure the full
702       // decl hasn't already been cached.
703       auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
704       if (full_iter != m_types.end()) {
705         TypeSP result = full_iter->second;
706         // Map the forward decl to the TypeSP for the full decl so we can take
707         // the fast path next time.
708         m_types[toOpaqueUid(type_id)] = result;
709         return result;
710       }
711     }
712   }
713 
714   PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
715 
716   clang::QualType qt = m_ast->GetOrCreateType(best_decl_id);
717 
718   TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt));
719   if (!result)
720     return nullptr;
721 
722   uint64_t best_uid = toOpaqueUid(best_decl_id);
723   m_types[best_uid] = result;
724   // If we had both a forward decl and a full decl, make both point to the new
725   // type.
726   if (full_decl_uid)
727     m_types[toOpaqueUid(type_id)] = result;
728 
729   return result;
730 }
731 
732 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
733   // We can't use try_emplace / overwrite here because the process of creating
734   // a type could create nested types, which could invalidate iterators.  So
735   // we have to do a 2-phase lookup / insert.
736   auto iter = m_types.find(toOpaqueUid(type_id));
737   if (iter != m_types.end())
738     return iter->second;
739 
740   TypeSP type = CreateAndCacheType(type_id);
741   if (type)
742     GetTypeList().Insert(type);
743   return type;
744 }
745 
746 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
747   CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
748   if (sym.kind() == S_CONSTANT)
749     return CreateConstantSymbol(var_id, sym);
750 
751   lldb::ValueType scope = eValueTypeInvalid;
752   TypeIndex ti;
753   llvm::StringRef name;
754   lldb::addr_t addr = 0;
755   uint16_t section = 0;
756   uint32_t offset = 0;
757   bool is_external = false;
758   switch (sym.kind()) {
759   case S_GDATA32:
760     is_external = true;
761     LLVM_FALLTHROUGH;
762   case S_LDATA32: {
763     DataSym ds(sym.kind());
764     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
765     ti = ds.Type;
766     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
767                                       : eValueTypeVariableStatic;
768     name = ds.Name;
769     section = ds.Segment;
770     offset = ds.DataOffset;
771     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
772     break;
773   }
774   case S_GTHREAD32:
775     is_external = true;
776     LLVM_FALLTHROUGH;
777   case S_LTHREAD32: {
778     ThreadLocalDataSym tlds(sym.kind());
779     llvm::cantFail(
780         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
781     ti = tlds.Type;
782     name = tlds.Name;
783     section = tlds.Segment;
784     offset = tlds.DataOffset;
785     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
786     scope = eValueTypeVariableThreadLocal;
787     break;
788   }
789   default:
790     llvm_unreachable("unreachable!");
791   }
792 
793   CompUnitSP comp_unit;
794   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
795   if (modi) {
796     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
797     comp_unit = GetOrCreateCompileUnit(cci);
798   }
799 
800   Declaration decl;
801   PdbTypeSymId tid(ti, false);
802   SymbolFileTypeSP type_sp =
803       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
804   Variable::RangeList ranges;
805 
806   m_ast->GetOrCreateVariableDecl(var_id);
807 
808   DWARFExpression location = MakeGlobalLocationExpression(
809       section, offset, GetObjectFile()->GetModule());
810 
811   std::string global_name("::");
812   global_name += name;
813   VariableSP var_sp = std::make_shared<Variable>(
814       toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
815       scope, comp_unit.get(), ranges, &decl, location, is_external, false,
816       false);
817   var_sp->SetLocationIsConstantValueData(false);
818 
819   return var_sp;
820 }
821 
822 lldb::VariableSP
823 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
824                                           const CVSymbol &cvs) {
825   TpiStream &tpi = m_index->tpi();
826   ConstantSym constant(cvs.kind());
827 
828   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
829   std::string global_name("::");
830   global_name += constant.Name;
831   PdbTypeSymId tid(constant.Type, false);
832   SymbolFileTypeSP type_sp =
833       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
834 
835   Declaration decl;
836   Variable::RangeList ranges;
837   ModuleSP module = GetObjectFile()->GetModule();
838   DWARFExpression location = MakeConstantLocationExpression(
839       constant.Type, tpi, constant.Value, module);
840 
841   VariableSP var_sp = std::make_shared<Variable>(
842       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
843       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
844       false, false, false);
845   var_sp->SetLocationIsConstantValueData(true);
846   return var_sp;
847 }
848 
849 VariableSP
850 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
851   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
852   if (emplace_result.second)
853     emplace_result.first->second = CreateGlobalVariable(var_id);
854 
855   return emplace_result.first->second;
856 }
857 
858 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
859   return GetOrCreateType(PdbTypeSymId(ti, false));
860 }
861 
862 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
863                                                     CompileUnit &comp_unit) {
864   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
865   if (emplace_result.second)
866     emplace_result.first->second = CreateFunction(func_id, comp_unit);
867 
868   return emplace_result.first->second;
869 }
870 
871 CompUnitSP
872 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
873 
874   auto emplace_result =
875       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
876   if (emplace_result.second)
877     emplace_result.first->second = CreateCompileUnit(cci);
878 
879   lldbassert(emplace_result.first->second);
880   return emplace_result.first->second;
881 }
882 
883 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
884   auto iter = m_blocks.find(toOpaqueUid(block_id));
885   if (iter != m_blocks.end())
886     return *iter->second;
887 
888   return CreateBlock(block_id);
889 }
890 
891 void SymbolFileNativePDB::ParseDeclsForContext(
892     lldb_private::CompilerDeclContext decl_ctx) {
893   clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx);
894   if (!context)
895     return;
896   m_ast->ParseDeclsForContext(*context);
897 }
898 
899 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
900   if (index >= GetNumCompileUnits())
901     return CompUnitSP();
902   lldbassert(index < UINT16_MAX);
903   if (index >= UINT16_MAX)
904     return nullptr;
905 
906   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
907 
908   return GetOrCreateCompileUnit(item);
909 }
910 
911 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
912   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
913   PdbSymUid uid(comp_unit.GetID());
914   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
915 
916   CompilandIndexItem *item =
917       m_index->compilands().GetCompiland(uid.asCompiland().modi);
918   lldbassert(item);
919   if (!item->m_compile_opts)
920     return lldb::eLanguageTypeUnknown;
921 
922   return TranslateLanguage(item->m_compile_opts->getLanguage());
923 }
924 
925 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) { return; }
926 
927 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
928   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
929   PdbSymUid uid{comp_unit.GetID()};
930   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
931   uint16_t modi = uid.asCompiland().modi;
932   CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
933 
934   size_t count = comp_unit.GetNumFunctions();
935   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
936   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
937     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
938       continue;
939 
940     PdbCompilandSymId sym_id{modi, iter.offset()};
941 
942     FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
943   }
944 
945   size_t new_count = comp_unit.GetNumFunctions();
946   lldbassert(new_count >= count);
947   return new_count - count;
948 }
949 
950 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
951   // If any of these flags are set, we need to resolve the compile unit.
952   uint32_t flags = eSymbolContextCompUnit;
953   flags |= eSymbolContextVariable;
954   flags |= eSymbolContextFunction;
955   flags |= eSymbolContextBlock;
956   flags |= eSymbolContextLineEntry;
957   return (resolve_scope & flags) != 0;
958 }
959 
960 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
961     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
962   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
963   uint32_t resolved_flags = 0;
964   lldb::addr_t file_addr = addr.GetFileAddress();
965 
966   if (NeedsResolvedCompileUnit(resolve_scope)) {
967     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
968     if (!modi)
969       return 0;
970     CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
971     if (!cci)
972       return 0;
973 
974     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
975     resolved_flags |= eSymbolContextCompUnit;
976   }
977 
978   if (resolve_scope & eSymbolContextFunction ||
979       resolve_scope & eSymbolContextBlock) {
980     lldbassert(sc.comp_unit);
981     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
982     // Search the matches in reverse.  This way if there are multiple matches
983     // (for example we are 3 levels deep in a nested scope) it will find the
984     // innermost one first.
985     for (const auto &match : llvm::reverse(matches)) {
986       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
987         continue;
988 
989       PdbCompilandSymId csid = match.uid.asCompilandSym();
990       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
991       PDB_SymType type = CVSymToPDBSym(cvs.kind());
992       if (type != PDB_SymType::Function && type != PDB_SymType::Block)
993         continue;
994       if (type == PDB_SymType::Function) {
995         sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
996         sc.block = sc.GetFunctionBlock();
997       }
998 
999       if (type == PDB_SymType::Block) {
1000         sc.block = &GetOrCreateBlock(csid);
1001         sc.function = sc.block->CalculateSymbolContextFunction();
1002       }
1003     resolved_flags |= eSymbolContextFunction;
1004     resolved_flags |= eSymbolContextBlock;
1005     break;
1006     }
1007   }
1008 
1009   if (resolve_scope & eSymbolContextLineEntry) {
1010     lldbassert(sc.comp_unit);
1011     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1012       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1013         resolved_flags |= eSymbolContextLineEntry;
1014     }
1015   }
1016 
1017   return resolved_flags;
1018 }
1019 
1020 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1021     const FileSpec &file_spec, uint32_t line, bool check_inlines,
1022     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1023   return 0;
1024 }
1025 
1026 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1027                                       const CompilandIndexItem &cci,
1028                                       lldb::addr_t base_addr,
1029                                       uint32_t file_number,
1030                                       const LineFragmentHeader &block,
1031                                       const LineNumberEntry &cur) {
1032   LineInfo cur_info(cur.Flags);
1033 
1034   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1035     return;
1036 
1037   uint64_t addr = base_addr + cur.Offset;
1038 
1039   bool is_statement = cur_info.isStatement();
1040   bool is_prologue = IsFunctionPrologue(cci, addr);
1041   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1042 
1043   uint32_t lno = cur_info.getStartLine();
1044 
1045   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1046                                   is_statement, false, is_prologue, is_epilogue,
1047                                   false);
1048 }
1049 
1050 static void TerminateLineSequence(LineTable &table,
1051                                   const LineFragmentHeader &block,
1052                                   lldb::addr_t base_addr, uint32_t file_number,
1053                                   uint32_t last_line,
1054                                   std::unique_ptr<LineSequence> seq) {
1055   // The end is always a terminal entry, so insert it regardless.
1056   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1057                                   last_line, 0, file_number, false, false,
1058                                   false, false, true);
1059   table.InsertSequence(seq.release());
1060 }
1061 
1062 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1063   // Unfortunately LLDB is set up to parse the entire compile unit line table
1064   // all at once, even if all it really needs is line info for a specific
1065   // function.  In the future it would be nice if it could set the sc.m_function
1066   // member, and we could only get the line info for the function in question.
1067   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1068   PdbSymUid cu_id(comp_unit.GetID());
1069   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1070   CompilandIndexItem *cci =
1071       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1072   lldbassert(cci);
1073   auto line_table = std::make_unique<LineTable>(&comp_unit);
1074 
1075   // This is basically a copy of the .debug$S subsections from all original COFF
1076   // object files merged together with address relocations applied.  We are
1077   // looking for all DEBUG_S_LINES subsections.
1078   for (const DebugSubsectionRecord &dssr :
1079        cci->m_debug_stream.getSubsectionsArray()) {
1080     if (dssr.kind() != DebugSubsectionKind::Lines)
1081       continue;
1082 
1083     DebugLinesSubsectionRef lines;
1084     llvm::BinaryStreamReader reader(dssr.getRecordData());
1085     if (auto EC = lines.initialize(reader)) {
1086       llvm::consumeError(std::move(EC));
1087       return false;
1088     }
1089 
1090     const LineFragmentHeader *lfh = lines.header();
1091     uint64_t virtual_addr =
1092         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1093 
1094     const auto &checksums = cci->m_strings.checksums().getArray();
1095     const auto &strings = cci->m_strings.strings();
1096     for (const LineColumnEntry &group : lines) {
1097       // Indices in this structure are actually offsets of records in the
1098       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1099       // into the global PDB string table.
1100       auto iter = checksums.at(group.NameIndex);
1101       if (iter == checksums.end())
1102         continue;
1103 
1104       llvm::Expected<llvm::StringRef> efn =
1105           strings.getString(iter->FileNameOffset);
1106       if (!efn) {
1107         llvm::consumeError(efn.takeError());
1108         continue;
1109       }
1110 
1111       // LLDB wants the index of the file in the list of support files.
1112       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1113       lldbassert(fn_iter != cci->m_file_list.end());
1114       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1115 
1116       std::unique_ptr<LineSequence> sequence(
1117           line_table->CreateLineSequenceContainer());
1118       lldbassert(!group.LineNumbers.empty());
1119 
1120       for (const LineNumberEntry &entry : group.LineNumbers) {
1121         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1122                                   file_index, *lfh, entry);
1123       }
1124       LineInfo last_line(group.LineNumbers.back().Flags);
1125       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1126                             last_line.getEndLine(), std::move(sequence));
1127     }
1128   }
1129 
1130   if (line_table->GetSize() == 0)
1131     return false;
1132 
1133   comp_unit.SetLineTable(line_table.release());
1134   return true;
1135 }
1136 
1137 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1138   // PDB doesn't contain information about macros
1139   return false;
1140 }
1141 
1142 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1143                                             FileSpecList &support_files) {
1144   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1145   PdbSymUid cu_id(comp_unit.GetID());
1146   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1147   CompilandIndexItem *cci =
1148       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1149   lldbassert(cci);
1150 
1151   for (llvm::StringRef f : cci->m_file_list) {
1152     FileSpec::Style style =
1153         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1154     FileSpec spec(f, style);
1155     support_files.Append(spec);
1156   }
1157   return true;
1158 }
1159 
1160 bool SymbolFileNativePDB::ParseImportedModules(
1161     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1162   // PDB does not yet support module debug info
1163   return false;
1164 }
1165 
1166 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1167   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1168   GetOrCreateBlock(PdbSymUid(func.GetID()).asCompilandSym());
1169   // FIXME: Parse child blocks
1170   return 1;
1171 }
1172 
1173 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1174 
1175 void SymbolFileNativePDB::FindGlobalVariables(
1176     ConstString name, const CompilerDeclContext *parent_decl_ctx,
1177     uint32_t max_matches, VariableList &variables) {
1178   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1179   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1180 
1181   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1182       name.GetStringRef(), m_index->symrecords());
1183   for (const SymbolAndOffset &result : results) {
1184     VariableSP var;
1185     switch (result.second.kind()) {
1186     case SymbolKind::S_GDATA32:
1187     case SymbolKind::S_LDATA32:
1188     case SymbolKind::S_GTHREAD32:
1189     case SymbolKind::S_LTHREAD32:
1190     case SymbolKind::S_CONSTANT: {
1191       PdbGlobalSymId global(result.first, false);
1192       var = GetOrCreateGlobalVariable(global);
1193       variables.AddVariable(var);
1194       break;
1195     }
1196     default:
1197       continue;
1198     }
1199   }
1200 }
1201 
1202 void SymbolFileNativePDB::FindFunctions(
1203     ConstString name, const CompilerDeclContext *parent_decl_ctx,
1204     FunctionNameType name_type_mask, bool include_inlines,
1205     SymbolContextList &sc_list) {
1206   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1207   // For now we only support lookup by method name.
1208   if (!(name_type_mask & eFunctionNameTypeMethod))
1209     return;
1210 
1211   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1212 
1213   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1214       name.GetStringRef(), m_index->symrecords());
1215   for (const SymbolAndOffset &match : matches) {
1216     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1217       continue;
1218     ProcRefSym proc(match.second.kind());
1219     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1220 
1221     if (!IsValidRecord(proc))
1222       continue;
1223 
1224     CompilandIndexItem &cci =
1225         m_index->compilands().GetOrCreateCompiland(proc.modi());
1226     SymbolContext sc;
1227 
1228     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1229     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1230     sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1231 
1232     sc_list.Append(sc);
1233   }
1234 }
1235 
1236 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1237                                         bool include_inlines,
1238                                         SymbolContextList &sc_list) {}
1239 
1240 void SymbolFileNativePDB::FindTypes(
1241     ConstString name, const CompilerDeclContext *parent_decl_ctx,
1242     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1243     TypeMap &types) {
1244   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1245   if (!name)
1246     return;
1247 
1248   searched_symbol_files.clear();
1249   searched_symbol_files.insert(this);
1250 
1251   // There is an assumption 'name' is not a regex
1252   FindTypesByName(name.GetStringRef(), max_matches, types);
1253 }
1254 
1255 void SymbolFileNativePDB::FindTypes(
1256     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1257     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1258 
1259 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1260                                           uint32_t max_matches,
1261                                           TypeMap &types) {
1262 
1263   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1264   if (max_matches > 0 && max_matches < matches.size())
1265     matches.resize(max_matches);
1266 
1267   for (TypeIndex ti : matches) {
1268     TypeSP type = GetOrCreateType(ti);
1269     if (!type)
1270       continue;
1271 
1272     types.Insert(type);
1273   }
1274 }
1275 
1276 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1277   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1278   // Only do the full type scan the first time.
1279   if (m_done_full_type_scan)
1280     return 0;
1281 
1282   const size_t old_count = GetTypeList().GetSize();
1283   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1284 
1285   // First process the entire TPI stream.
1286   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1287     TypeSP type = GetOrCreateType(*ti);
1288     if (type)
1289       (void)type->GetFullCompilerType();
1290   }
1291 
1292   // Next look for S_UDT records in the globals stream.
1293   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1294     PdbGlobalSymId global{gid, false};
1295     CVSymbol sym = m_index->ReadSymbolRecord(global);
1296     if (sym.kind() != S_UDT)
1297       continue;
1298 
1299     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1300     bool is_typedef = true;
1301     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1302       CVType cvt = m_index->tpi().getType(udt.Type);
1303       llvm::StringRef name = CVTagRecord::create(cvt).name();
1304       if (name == udt.Name)
1305         is_typedef = false;
1306     }
1307 
1308     if (is_typedef)
1309       GetOrCreateTypedef(global);
1310   }
1311 
1312   const size_t new_count = GetTypeList().GetSize();
1313 
1314   m_done_full_type_scan = true;
1315 
1316   return new_count - old_count;
1317 }
1318 
1319 size_t
1320 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1321                                                   VariableList &variables) {
1322   PdbSymUid sym_uid(comp_unit.GetID());
1323   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1324   return 0;
1325 }
1326 
1327 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1328                                                     PdbCompilandSymId var_id,
1329                                                     bool is_param) {
1330   ModuleSP module = GetObjectFile()->GetModule();
1331   Block &block = GetOrCreateBlock(scope_id);
1332   VariableInfo var_info =
1333       GetVariableLocationInfo(*m_index, var_id, block, module);
1334   if (!var_info.location || !var_info.ranges)
1335     return nullptr;
1336 
1337   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1338   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1339   TypeSP type_sp = GetOrCreateType(var_info.type);
1340   std::string name = var_info.name.str();
1341   Declaration decl;
1342   SymbolFileTypeSP sftype =
1343       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1344 
1345   ValueType var_scope =
1346       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1347   VariableSP var_sp = std::make_shared<Variable>(
1348       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1349       comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, false,
1350       false, false);
1351 
1352   if (!is_param)
1353     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1354 
1355   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1356   return var_sp;
1357 }
1358 
1359 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1360     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1361   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1362   if (iter != m_local_variables.end())
1363     return iter->second;
1364 
1365   return CreateLocalVariable(scope_id, var_id, is_param);
1366 }
1367 
1368 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1369   CVSymbol sym = m_index->ReadSymbolRecord(id);
1370   lldbassert(sym.kind() == SymbolKind::S_UDT);
1371 
1372   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1373 
1374   TypeSP target_type = GetOrCreateType(udt.Type);
1375 
1376   (void)m_ast->GetOrCreateTypedefDecl(id);
1377 
1378   Declaration decl;
1379   return std::make_shared<lldb_private::Type>(
1380       toOpaqueUid(id), this, ConstString(udt.Name), target_type->GetByteSize(),
1381       nullptr, target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID,
1382       decl, target_type->GetForwardCompilerType(),
1383       lldb_private::Type::ResolveState::Forward);
1384 }
1385 
1386 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1387   auto iter = m_types.find(toOpaqueUid(id));
1388   if (iter != m_types.end())
1389     return iter->second;
1390 
1391   return CreateTypedef(id);
1392 }
1393 
1394 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1395   Block &block = GetOrCreateBlock(block_id);
1396 
1397   size_t count = 0;
1398 
1399   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1400   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1401   uint32_t params_remaining = 0;
1402   switch (sym.kind()) {
1403   case S_GPROC32:
1404   case S_LPROC32: {
1405     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1406     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1407     CVType signature = m_index->tpi().getType(proc.FunctionType);
1408     ProcedureRecord sig;
1409     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1410     params_remaining = sig.getParameterCount();
1411     break;
1412   }
1413   case S_BLOCK32:
1414     break;
1415   default:
1416     lldbassert(false && "Symbol is not a block!");
1417     return 0;
1418   }
1419 
1420   VariableListSP variables = block.GetBlockVariableList(false);
1421   if (!variables) {
1422     variables = std::make_shared<VariableList>();
1423     block.SetVariableList(variables);
1424   }
1425 
1426   CVSymbolArray syms = limitSymbolArrayToScope(
1427       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1428 
1429   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1430   // no point examining it since we know it's not a local variable.
1431   syms.drop_front();
1432   auto iter = syms.begin();
1433   auto end = syms.end();
1434 
1435   while (iter != end) {
1436     uint32_t record_offset = iter.offset();
1437     CVSymbol variable_cvs = *iter;
1438     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1439     ++iter;
1440 
1441     // If this is a block, recurse into its children and then skip it.
1442     if (variable_cvs.kind() == S_BLOCK32) {
1443       uint32_t block_end = getScopeEndOffset(variable_cvs);
1444       count += ParseVariablesForBlock(child_sym_id);
1445       iter = syms.at(block_end);
1446       continue;
1447     }
1448 
1449     bool is_param = params_remaining > 0;
1450     VariableSP variable;
1451     switch (variable_cvs.kind()) {
1452     case S_REGREL32:
1453     case S_REGISTER:
1454     case S_LOCAL:
1455       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1456       if (is_param)
1457         --params_remaining;
1458       if (variable)
1459         variables->AddVariableIfUnique(variable);
1460       break;
1461     default:
1462       break;
1463     }
1464   }
1465 
1466   // Pass false for set_children, since we call this recursively so that the
1467   // children will call this for themselves.
1468   block.SetDidParseVariables(true, false);
1469 
1470   return count;
1471 }
1472 
1473 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1474   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1475   lldbassert(sc.function || sc.comp_unit);
1476 
1477   VariableListSP variables;
1478   if (sc.block) {
1479     PdbSymUid block_id(sc.block->GetID());
1480 
1481     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1482     return count;
1483   }
1484 
1485   if (sc.function) {
1486     PdbSymUid block_id(sc.function->GetID());
1487 
1488     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1489     return count;
1490   }
1491 
1492   if (sc.comp_unit) {
1493     variables = sc.comp_unit->GetVariableList(false);
1494     if (!variables) {
1495       variables = std::make_shared<VariableList>();
1496       sc.comp_unit->SetVariableList(variables);
1497     }
1498     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1499   }
1500 
1501   llvm_unreachable("Unreachable!");
1502 }
1503 
1504 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1505   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1506     return decl.getValue();
1507   else
1508     return CompilerDecl();
1509 }
1510 
1511 CompilerDeclContext
1512 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1513   clang::DeclContext *context =
1514       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1515   if (!context)
1516     return {};
1517 
1518   return m_ast->ToCompilerDeclContext(*context);
1519 }
1520 
1521 CompilerDeclContext
1522 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1523   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1524   return m_ast->ToCompilerDeclContext(*context);
1525 }
1526 
1527 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1528   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1529   auto iter = m_types.find(type_uid);
1530   // lldb should not be passing us non-sensical type uids.  the only way it
1531   // could have a type uid in the first place is if we handed it out, in which
1532   // case we should know about the type.  However, that doesn't mean we've
1533   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1534   // type doesn't exist, let's instantiate it now.
1535   if (iter != m_types.end())
1536     return &*iter->second;
1537 
1538   PdbSymUid uid(type_uid);
1539   lldbassert(uid.kind() == PdbSymUidKind::Type);
1540   PdbTypeSymId type_id = uid.asTypeSym();
1541   if (type_id.index.isNoneType())
1542     return nullptr;
1543 
1544   TypeSP type_sp = CreateAndCacheType(type_id);
1545   return &*type_sp;
1546 }
1547 
1548 llvm::Optional<SymbolFile::ArrayInfo>
1549 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1550     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1551   return llvm::None;
1552 }
1553 
1554 
1555 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1556   clang::QualType qt =
1557       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1558 
1559   return m_ast->CompleteType(qt);
1560 }
1561 
1562 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1563                                    TypeClass type_mask,
1564                                    lldb_private::TypeList &type_list) {}
1565 
1566 CompilerDeclContext
1567 SymbolFileNativePDB::FindNamespace(ConstString name,
1568                                    const CompilerDeclContext *parent_decl_ctx) {
1569   return {};
1570 }
1571 
1572 llvm::Expected<TypeSystem &>
1573 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1574   auto type_system_or_err =
1575       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1576   if (type_system_or_err) {
1577     type_system_or_err->SetSymbolFile(this);
1578   }
1579   return type_system_or_err;
1580 }
1581 
1582 ConstString SymbolFileNativePDB::GetPluginName() {
1583   static ConstString g_name("pdb");
1584   return g_name;
1585 }
1586 
1587 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1588