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