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