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   ModifierRecord mr;
395   llvm::cantFail(TypeDeserializer::deserializeAs<ModifierRecord>(cvt, mr));
396   return GetPdbSymType(tpi, mr.ModifiedType);
397 }
398 
399 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
400   switch (cr.Kind) {
401   case TypeRecordKind::Class:
402     return clang::TTK_Class;
403   case TypeRecordKind::Struct:
404     return clang::TTK_Struct;
405   case TypeRecordKind::Union:
406     return clang::TTK_Union;
407   case TypeRecordKind::Interface:
408     return clang::TTK_Interface;
409   case TypeRecordKind::Enum:
410     return clang::TTK_Enum;
411   default:
412     lldbassert(false && "Invalid tag record kind!");
413     return clang::TTK_Struct;
414   }
415 }
416 
417 void SymbolFileNativePDB::Initialize() {
418   PluginManager::RegisterPlugin(GetPluginNameStatic(),
419                                 GetPluginDescriptionStatic(), CreateInstance,
420                                 DebuggerInitialize);
421 }
422 
423 void SymbolFileNativePDB::Terminate() {
424   PluginManager::UnregisterPlugin(CreateInstance);
425 }
426 
427 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
428 
429 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
430   static ConstString g_name("native-pdb");
431   return g_name;
432 }
433 
434 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
435   return "Microsoft PDB debug symbol cross-platform file reader.";
436 }
437 
438 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
439   return new SymbolFileNativePDB(obj_file);
440 }
441 
442 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
443     : SymbolFile(object_file) {}
444 
445 SymbolFileNativePDB::~SymbolFileNativePDB() {}
446 
447 uint32_t SymbolFileNativePDB::CalculateAbilities() {
448   uint32_t abilities = 0;
449   if (!m_obj_file)
450     return 0;
451 
452   if (!m_index) {
453     // Lazily load and match the PDB file, but only do this once.
454     std::unique_ptr<PDBFile> file_up =
455         loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
456 
457     if (!file_up) {
458       auto module_sp = m_obj_file->GetModule();
459       if (!module_sp)
460         return 0;
461       // See if any symbol file is specified through `--symfile` option.
462       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
463       if (!symfile)
464         return 0;
465       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
466     }
467 
468     if (!file_up)
469       return 0;
470 
471     auto expected_index = PdbIndex::create(std::move(file_up));
472     if (!expected_index) {
473       llvm::consumeError(expected_index.takeError());
474       return 0;
475     }
476     m_index = std::move(*expected_index);
477   }
478   if (!m_index)
479     return 0;
480 
481   // We don't especially have to be precise here.  We only distinguish between
482   // stripped and not stripped.
483   abilities = kAllAbilities;
484 
485   if (m_index->dbi().isStripped())
486     abilities &= ~(Blocks | LocalVariables);
487   return abilities;
488 }
489 
490 void SymbolFileNativePDB::InitializeObject() {
491   m_obj_load_address = m_obj_file->GetFileOffset();
492   m_index->SetLoadAddress(m_obj_load_address);
493   m_index->ParseSectionContribs();
494 
495   TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
496   m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
497   m_importer = llvm::make_unique<ClangASTImporter>();
498   lldbassert(m_clang);
499 }
500 
501 uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
502   const DbiModuleList &modules = m_index->dbi().modules();
503   uint32_t count = modules.getModuleCount();
504   if (count == 0)
505     return count;
506 
507   // The linker can inject an additional "dummy" compilation unit into the
508   // PDB. Ignore this special compile unit for our purposes, if it is there.
509   // It is always the last one.
510   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
511   if (last.getModuleName() == "* Linker *")
512     --count;
513   return count;
514 }
515 
516 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbSymUid func_uid,
517                                                      const SymbolContext &sc) {
518   lldbassert(func_uid.tag() == PDB_SymType::Function);
519 
520   PdbSymUid cuid = PdbSymUid::makeCompilandId(func_uid.asCuSym().modi);
521 
522   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
523   lldbassert(cci);
524   CVSymbol sym_record =
525       cci->m_debug_stream.readSymbolAtOffset(func_uid.asCuSym().offset);
526 
527   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
528   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
529 
530   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
531   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
532     return nullptr;
533 
534   AddressRange func_range(file_vm_addr, sol.length,
535                           sc.module_sp->GetSectionList());
536   if (!func_range.GetBaseAddress().IsValid())
537     return nullptr;
538 
539   Type *func_type = nullptr;
540 
541   // FIXME: Resolve types and mangled names.
542   PdbSymUid sig_uid =
543       PdbSymUid::makeTypeSymId(PDB_SymType::FunctionSig, TypeIndex{0}, false);
544   Mangled mangled(getSymbolName(sym_record));
545 
546   FunctionSP func_sp = std::make_shared<Function>(
547       sc.comp_unit, func_uid.toOpaqueId(), sig_uid.toOpaqueId(), mangled,
548       func_type, func_range);
549 
550   sc.comp_unit->AddFunction(func_sp);
551   return func_sp;
552 }
553 
554 CompUnitSP
555 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
556   lldb::LanguageType lang =
557       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
558                          : lldb::eLanguageTypeUnknown;
559 
560   LazyBool optimized = eLazyBoolNo;
561   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
562     optimized = eLazyBoolYes;
563 
564   llvm::StringRef source_file_name =
565       m_index->compilands().GetMainSourceFile(cci);
566   FileSpec fs(source_file_name, false);
567 
568   CompUnitSP cu_sp =
569       std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
570                                     cci.m_uid.toOpaqueId(), lang, optimized);
571 
572   const PdbCompilandId &cuid = cci.m_uid.asCompiland();
573   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cuid.modi,
574                                                                     cu_sp);
575   return cu_sp;
576 }
577 
578 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbSymUid type_uid,
579                                                      const ModifierRecord &mr) {
580   TpiStream &stream = m_index->tpi();
581 
582   TypeSP t = GetOrCreateType(mr.ModifiedType);
583   CompilerType ct = t->GetForwardCompilerType();
584   if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
585     ct = ct.AddConstModifier();
586   if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
587     ct = ct.AddVolatileModifier();
588   std::string name;
589   if (mr.ModifiedType.isSimple())
590     name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
591   else
592     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
593   Declaration decl;
594   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
595                                 ConstString(name), t->GetByteSize(), nullptr,
596                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
597                                 ct, Type::eResolveStateFull);
598 }
599 
600 lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
601     PdbSymUid type_uid, const llvm::codeview::PointerRecord &pr) {
602   TypeSP pointee = GetOrCreateType(pr.ReferentType);
603   CompilerType pointee_ct = pointee->GetForwardCompilerType();
604   lldbassert(pointee_ct);
605   Declaration decl;
606 
607   if (pr.isPointerToMember()) {
608     MemberPointerInfo mpi = pr.getMemberInfo();
609     TypeSP class_type = GetOrCreateType(mpi.ContainingType);
610 
611     CompilerType ct = ClangASTContext::CreateMemberPointerType(
612         class_type->GetLayoutCompilerType(), pointee_ct);
613 
614     return std::make_shared<Type>(
615         type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(),
616         pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
617         Type::eResolveStateFull);
618   }
619 
620   CompilerType pointer_ct = pointee_ct;
621   if (pr.getMode() == PointerMode::LValueReference)
622     pointer_ct = pointer_ct.GetLValueReferenceType();
623   else if (pr.getMode() == PointerMode::RValueReference)
624     pointer_ct = pointer_ct.GetRValueReferenceType();
625   else
626     pointer_ct = pointer_ct.GetPointerType();
627 
628   if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
629     pointer_ct = pointer_ct.AddConstModifier();
630 
631   if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
632     pointer_ct = pointer_ct.AddVolatileModifier();
633 
634   if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
635     pointer_ct = pointer_ct.AddRestrictModifier();
636 
637   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
638                                 ConstString(), pr.getSize(), nullptr,
639                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
640                                 pointer_ct, Type::eResolveStateFull);
641 }
642 
643 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
644   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
645     PdbSymUid uid =
646         PdbSymUid::makeTypeSymId(PDB_SymType::PointerType, ti, false);
647     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
648     CompilerType ct = direct_sp->GetFullCompilerType();
649     ct = ct.GetPointerType();
650     uint32_t pointer_size = 0;
651     switch (ti.getSimpleMode()) {
652     case SimpleTypeMode::FarPointer32:
653     case SimpleTypeMode::NearPointer32:
654       pointer_size = 4;
655       break;
656     case SimpleTypeMode::NearPointer64:
657       pointer_size = 8;
658       break;
659     default:
660       // 128-bit and 16-bit pointers unsupported.
661       return nullptr;
662     }
663     Declaration decl;
664     return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
665                                   ConstString(), pointer_size, nullptr,
666                                   LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
667                                   ct, Type::eResolveStateFull);
668   }
669 
670   PdbSymUid uid = PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false);
671   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
672     return nullptr;
673 
674   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
675   lldbassert(bt != lldb::eBasicTypeInvalid);
676   CompilerType ct = m_clang->GetBasicType(bt);
677   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
678 
679   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
680 
681   Declaration decl;
682   return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
683                                 ConstString(type_name), size, nullptr,
684                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
685                                 ct, Type::eResolveStateFull);
686 }
687 
688 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
689     PdbSymUid type_uid, llvm::StringRef name, size_t size,
690     clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
691 
692   // Some UDT with trival ctor has zero length. Just ignore.
693   if (size == 0)
694     return nullptr;
695 
696   // Ignore unnamed-tag UDTs.
697   name = DropNameScope(name);
698   if (name.empty())
699     return nullptr;
700 
701   clang::DeclContext *decl_context = m_clang->GetTranslationUnitDecl();
702 
703   lldb::AccessType access =
704       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
705 
706   ClangASTMetadata metadata;
707   metadata.SetUserID(type_uid.toOpaqueId());
708   metadata.SetIsDynamicCXXType(false);
709 
710   CompilerType ct =
711       m_clang->CreateRecordType(decl_context, access, name.str().c_str(), ttk,
712                                 lldb::eLanguageTypeC_plus_plus, &metadata);
713   lldbassert(ct.IsValid());
714 
715   clang::CXXRecordDecl *record_decl =
716       m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
717   lldbassert(record_decl);
718 
719   clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
720       *m_clang->getASTContext(), inheritance);
721   record_decl->addAttr(attr);
722 
723   ClangASTContext::StartTagDeclarationDefinition(ct);
724 
725   // Even if it's possible, don't complete it at this point. Just mark it
726   // forward resolved, and if/when LLDB needs the full definition, it can
727   // ask us.
728   ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
729 
730   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
731   Declaration decl;
732   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
733                                 ConstString(name), size, nullptr,
734                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
735                                 ct, Type::eResolveStateForward);
736 }
737 
738 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
739                                                 const ClassRecord &cr) {
740   clang::TagTypeKind ttk = TranslateUdtKind(cr);
741 
742   clang::MSInheritanceAttr::Spelling inheritance =
743       GetMSInheritance(m_index->tpi().typeCollection(), cr);
744   return CreateClassStructUnion(type_uid, cr.getName(), cr.getSize(), ttk,
745                                 inheritance);
746 }
747 
748 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
749                                                 const UnionRecord &ur) {
750   return CreateClassStructUnion(
751       type_uid, ur.getName(), ur.getSize(), clang::TTK_Union,
752       clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
753 }
754 
755 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
756                                                 const EnumRecord &er) {
757   llvm::StringRef name = DropNameScope(er.getName());
758 
759   clang::DeclContext *decl_context = m_clang->GetTranslationUnitDecl();
760 
761   Declaration decl;
762   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
763   CompilerType enum_ct = m_clang->CreateEnumerationType(
764       name.str().c_str(), decl_context, decl,
765       underlying_type->GetFullCompilerType(), er.isScoped());
766 
767   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
768 
769   // We're just going to forward resolve this for now.  We'll complete
770   // it only if the user requests.
771   return std::make_shared<lldb_private::Type>(
772       type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(name),
773       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
774       lldb_private::Type::eEncodingIsUID, decl, enum_ct,
775       lldb_private::Type::eResolveStateForward);
776 }
777 
778 TypeSP SymbolFileNativePDB::CreateType(PdbSymUid type_uid) {
779   const PdbTypeSymId &tsid = type_uid.asTypeSym();
780   TypeIndex index(tsid.index);
781 
782   if (index.getIndex() < TypeIndex::FirstNonSimpleIndex)
783     return CreateSimpleType(index);
784 
785   TpiStream &stream = tsid.is_ipi ? m_index->ipi() : m_index->tpi();
786   CVType cvt = stream.getType(index);
787 
788   if (cvt.kind() == LF_MODIFIER) {
789     ModifierRecord modifier;
790     llvm::cantFail(
791         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
792     return CreateModifierType(type_uid, modifier);
793   }
794 
795   if (cvt.kind() == LF_POINTER) {
796     PointerRecord pointer;
797     llvm::cantFail(
798         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
799     return CreatePointerType(type_uid, pointer);
800   }
801 
802   if (IsClassRecord(cvt.kind())) {
803     ClassRecord cr;
804     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
805     return CreateTagType(type_uid, cr);
806   }
807 
808   if (cvt.kind() == LF_ENUM) {
809     EnumRecord er;
810     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
811     return CreateTagType(type_uid, er);
812   }
813 
814   if (cvt.kind() == LF_UNION) {
815     UnionRecord ur;
816     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
817     return CreateTagType(type_uid, ur);
818   }
819 
820   return nullptr;
821 }
822 
823 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbSymUid type_uid) {
824   // If they search for a UDT which is a forward ref, try and resolve the full
825   // decl and just map the forward ref uid to the full decl record.
826   llvm::Optional<PdbSymUid> full_decl_uid;
827   if (type_uid.tag() == PDB_SymType::UDT ||
828       type_uid.tag() == PDB_SymType::Enum) {
829     const PdbTypeSymId &type_id = type_uid.asTypeSym();
830     TypeIndex ti(type_id.index);
831     lldbassert(!ti.isSimple());
832     CVType cvt = m_index->tpi().getType(ti);
833 
834     if (IsForwardRefUdt(cvt)) {
835       auto expected_full_ti = m_index->tpi().findFullDeclForForwardRef(ti);
836       if (!expected_full_ti)
837         llvm::consumeError(expected_full_ti.takeError());
838       else {
839         full_decl_uid = PdbSymUid::makeTypeSymId(
840             type_uid.tag(), *expected_full_ti, type_id.is_ipi);
841 
842         // It's possible that a lookup would occur for the full decl causing it
843         // to be cached, then a second lookup would occur for the forward decl.
844         // We don't want to create a second full decl, so make sure the full
845         // decl hasn't already been cached.
846         auto full_iter = m_types.find(full_decl_uid->toOpaqueId());
847         if (full_iter != m_types.end()) {
848           TypeSP result = full_iter->second;
849           // Map the forward decl to the TypeSP for the full decl so we can take
850           // the fast path next time.
851           m_types[type_uid.toOpaqueId()] = result;
852           return result;
853         }
854       }
855     }
856   }
857 
858   PdbSymUid best_uid = full_decl_uid ? *full_decl_uid : type_uid;
859   TypeSP result = CreateType(best_uid);
860   m_types[best_uid.toOpaqueId()] = result;
861   // If we had both a forward decl and a full decl, make both point to the new
862   // type.
863   if (full_decl_uid)
864     m_types[type_uid.toOpaqueId()] = result;
865 
866   const PdbTypeSymId &type_id = best_uid.asTypeSym();
867   if (best_uid.tag() == PDB_SymType::UDT ||
868       best_uid.tag() == PDB_SymType::Enum) {
869     clang::TagDecl *record_decl =
870         m_clang->GetAsTagDecl(result->GetForwardCompilerType());
871     lldbassert(record_decl);
872 
873     TypeIndex ti(type_id.index);
874     m_uid_to_decl[best_uid.toOpaqueId()] = record_decl;
875     m_decl_to_status[record_decl] =
876         DeclStatus(best_uid.toOpaqueId(), Type::eResolveStateForward);
877   }
878   return result;
879 }
880 
881 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbSymUid type_uid) {
882   lldbassert(PdbSymUid::isTypeSym(type_uid.tag()));
883   // We can't use try_emplace / overwrite here because the process of creating
884   // a type could create nested types, which could invalidate iterators.  So
885   // we have to do a 2-phase lookup / insert.
886   auto iter = m_types.find(type_uid.toOpaqueId());
887   if (iter != m_types.end())
888     return iter->second;
889 
890   return CreateAndCacheType(type_uid);
891 }
892 
893 static DWARFExpression MakeGlobalLocationExpression(uint16_t section,
894                                                     uint32_t offset,
895                                                     ModuleSP module) {
896   assert(section > 0);
897   assert(module);
898 
899   const ArchSpec &architecture = module->GetArchitecture();
900   ByteOrder byte_order = architecture.GetByteOrder();
901   uint32_t address_size = architecture.GetAddressByteSize();
902   uint32_t byte_size = architecture.GetDataByteSize();
903   assert(byte_order != eByteOrderInvalid && address_size != 0);
904 
905   RegisterKind register_kind = eRegisterKindDWARF;
906   StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order);
907   stream.PutHex8(DW_OP_addr);
908 
909   SectionList *section_list = module->GetSectionList();
910   assert(section_list);
911 
912   // Section indices in PDB are 1-based, but in DWARF they are 0-based, so we
913   // need to subtract 1.
914   uint32_t section_idx = section - 1;
915   if (section_idx >= section_list->GetSize())
916     return DWARFExpression(nullptr);
917 
918   auto section_ptr = section_list->GetSectionAtIndex(section_idx);
919   if (!section_ptr)
920     return DWARFExpression(nullptr);
921 
922   stream.PutMaxHex64(section_ptr->GetFileAddress() + offset, address_size,
923                      byte_order);
924   DataBufferSP buffer =
925       std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize());
926   DataExtractor extractor(buffer, byte_order, address_size, byte_size);
927   DWARFExpression result(module, extractor, nullptr, 0, buffer->GetByteSize());
928   result.SetRegisterKind(register_kind);
929   return result;
930 }
931 
932 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbSymUid var_uid) {
933   const PdbCuSymId &cu_sym = var_uid.asCuSym();
934   lldbassert(cu_sym.global);
935   CVSymbol sym = m_index->symrecords().readRecord(cu_sym.offset);
936   lldb::ValueType scope = eValueTypeInvalid;
937   TypeIndex ti;
938   llvm::StringRef name;
939   lldb::addr_t addr = 0;
940   uint16_t section = 0;
941   uint32_t offset = 0;
942   bool is_external = false;
943   switch (sym.kind()) {
944   case S_GDATA32:
945     is_external = true;
946     LLVM_FALLTHROUGH;
947   case S_LDATA32: {
948     DataSym ds(sym.kind());
949     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
950     ti = ds.Type;
951     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
952                                       : eValueTypeVariableStatic;
953     name = ds.Name;
954     section = ds.Segment;
955     offset = ds.DataOffset;
956     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
957     break;
958   }
959   case S_GTHREAD32:
960     is_external = true;
961     LLVM_FALLTHROUGH;
962   case S_LTHREAD32: {
963     ThreadLocalDataSym tlds(sym.kind());
964     llvm::cantFail(
965         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
966     ti = tlds.Type;
967     name = tlds.Name;
968     section = tlds.Segment;
969     offset = tlds.DataOffset;
970     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
971     scope = eValueTypeVariableThreadLocal;
972     break;
973   }
974   default:
975     llvm_unreachable("unreachable!");
976   }
977 
978   CompUnitSP comp_unit;
979   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
980   if (modi) {
981     PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi);
982     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid);
983     comp_unit = GetOrCreateCompileUnit(cci);
984   }
985 
986   Declaration decl;
987   PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti);
988   PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false);
989   SymbolFileTypeSP type_sp =
990       std::make_shared<SymbolFileType>(*this, tuid.toOpaqueId());
991   Variable::RangeList ranges;
992 
993   DWARFExpression location = MakeGlobalLocationExpression(
994       section, offset, GetObjectFile()->GetModule());
995 
996   std::string global_name("::");
997   global_name += name;
998   VariableSP var_sp = std::make_shared<Variable>(
999       var_uid.toOpaqueId(), name.str().c_str(), global_name.c_str(), type_sp,
1000       scope, comp_unit.get(), ranges, &decl, location, is_external, false,
1001       false);
1002   var_sp->SetLocationIsConstantValueData(false);
1003 
1004   return var_sp;
1005 }
1006 
1007 VariableSP SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbSymUid var_uid) {
1008   lldbassert(var_uid.isGlobalVariable());
1009 
1010   auto emplace_result =
1011       m_global_vars.try_emplace(var_uid.toOpaqueId(), nullptr);
1012   if (emplace_result.second)
1013     emplace_result.first->second = CreateGlobalVariable(var_uid);
1014 
1015   return emplace_result.first->second;
1016 }
1017 
1018 lldb::TypeSP
1019 SymbolFileNativePDB::GetOrCreateType(llvm::codeview::TypeIndex ti) {
1020   PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti);
1021   PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false);
1022   return GetOrCreateType(tuid);
1023 }
1024 
1025 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbSymUid func_uid,
1026                                                     const SymbolContext &sc) {
1027   lldbassert(func_uid.tag() == PDB_SymType::Function);
1028   auto emplace_result = m_functions.try_emplace(func_uid.toOpaqueId(), nullptr);
1029   if (emplace_result.second)
1030     emplace_result.first->second = CreateFunction(func_uid, sc);
1031 
1032   lldbassert(emplace_result.first->second);
1033   return emplace_result.first->second;
1034 }
1035 
1036 CompUnitSP
1037 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
1038   auto emplace_result =
1039       m_compilands.try_emplace(cci.m_uid.toOpaqueId(), nullptr);
1040   if (emplace_result.second)
1041     emplace_result.first->second = CreateCompileUnit(cci);
1042 
1043   lldbassert(emplace_result.first->second);
1044   return emplace_result.first->second;
1045 }
1046 
1047 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1048   if (index >= GetNumCompileUnits())
1049     return CompUnitSP();
1050   lldbassert(index < UINT16_MAX);
1051   if (index >= UINT16_MAX)
1052     return nullptr;
1053 
1054   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1055 
1056   return GetOrCreateCompileUnit(item);
1057 }
1058 
1059 lldb::LanguageType
1060 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
1061   // What fields should I expect to be filled out on the SymbolContext?  Is it
1062   // safe to assume that `sc.comp_unit` is valid?
1063   if (!sc.comp_unit)
1064     return lldb::eLanguageTypeUnknown;
1065   PdbSymUid uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1066   lldbassert(uid.tag() == PDB_SymType::Compiland);
1067 
1068   CompilandIndexItem *item = m_index->compilands().GetCompiland(uid);
1069   lldbassert(item);
1070   if (!item->m_compile_opts)
1071     return lldb::eLanguageTypeUnknown;
1072 
1073   return TranslateLanguage(item->m_compile_opts->getLanguage());
1074 }
1075 
1076 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
1077   lldbassert(sc.comp_unit);
1078   return false;
1079 }
1080 
1081 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1082   // If any of these flags are set, we need to resolve the compile unit.
1083   uint32_t flags = eSymbolContextCompUnit;
1084   flags |= eSymbolContextVariable;
1085   flags |= eSymbolContextFunction;
1086   flags |= eSymbolContextBlock;
1087   flags |= eSymbolContextLineEntry;
1088   return (resolve_scope & flags) != 0;
1089 }
1090 
1091 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1092     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1093   uint32_t resolved_flags = 0;
1094   lldb::addr_t file_addr = addr.GetFileAddress();
1095 
1096   if (NeedsResolvedCompileUnit(resolve_scope)) {
1097     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1098     if (!modi)
1099       return 0;
1100     PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi);
1101     CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
1102     if (!cci)
1103       return 0;
1104 
1105     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
1106     resolved_flags |= eSymbolContextCompUnit;
1107   }
1108 
1109   if (resolve_scope & eSymbolContextFunction) {
1110     lldbassert(sc.comp_unit);
1111     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1112     for (const auto &match : matches) {
1113       if (match.uid.tag() != PDB_SymType::Function)
1114         continue;
1115       sc.function = GetOrCreateFunction(match.uid, sc).get();
1116     }
1117     resolved_flags |= eSymbolContextFunction;
1118   }
1119 
1120   if (resolve_scope & eSymbolContextLineEntry) {
1121     lldbassert(sc.comp_unit);
1122     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1123       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1124         resolved_flags |= eSymbolContextLineEntry;
1125     }
1126   }
1127 
1128   return resolved_flags;
1129 }
1130 
1131 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1132                                       const CompilandIndexItem &cci,
1133                                       lldb::addr_t base_addr,
1134                                       uint32_t file_number,
1135                                       const LineFragmentHeader &block,
1136                                       const LineNumberEntry &cur) {
1137   LineInfo cur_info(cur.Flags);
1138 
1139   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1140     return;
1141 
1142   uint64_t addr = base_addr + cur.Offset;
1143 
1144   bool is_statement = cur_info.isStatement();
1145   bool is_prologue = IsFunctionPrologue(cci, addr);
1146   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1147 
1148   uint32_t lno = cur_info.getStartLine();
1149 
1150   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1151                                   is_statement, false, is_prologue, is_epilogue,
1152                                   false);
1153 }
1154 
1155 static void TerminateLineSequence(LineTable &table,
1156                                   const LineFragmentHeader &block,
1157                                   lldb::addr_t base_addr, uint32_t file_number,
1158                                   uint32_t last_line,
1159                                   std::unique_ptr<LineSequence> seq) {
1160   // The end is always a terminal entry, so insert it regardless.
1161   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1162                                   last_line, 0, file_number, false, false,
1163                                   false, false, true);
1164   table.InsertSequence(seq.release());
1165 }
1166 
1167 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
1168   // Unfortunately LLDB is set up to parse the entire compile unit line table
1169   // all at once, even if all it really needs is line info for a specific
1170   // function.  In the future it would be nice if it could set the sc.m_function
1171   // member, and we could only get the line info for the function in question.
1172   lldbassert(sc.comp_unit);
1173   PdbSymUid cu_id = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1174   lldbassert(cu_id.isCompiland());
1175   CompilandIndexItem *cci = m_index->compilands().GetCompiland(cu_id);
1176   lldbassert(cci);
1177   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1178 
1179   // This is basically a copy of the .debug$S subsections from all original COFF
1180   // object files merged together with address relocations applied.  We are
1181   // looking for all DEBUG_S_LINES subsections.
1182   for (const DebugSubsectionRecord &dssr :
1183        cci->m_debug_stream.getSubsectionsArray()) {
1184     if (dssr.kind() != DebugSubsectionKind::Lines)
1185       continue;
1186 
1187     DebugLinesSubsectionRef lines;
1188     llvm::BinaryStreamReader reader(dssr.getRecordData());
1189     if (auto EC = lines.initialize(reader)) {
1190       llvm::consumeError(std::move(EC));
1191       return false;
1192     }
1193 
1194     const LineFragmentHeader *lfh = lines.header();
1195     uint64_t virtual_addr =
1196         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1197 
1198     const auto &checksums = cci->m_strings.checksums().getArray();
1199     const auto &strings = cci->m_strings.strings();
1200     for (const LineColumnEntry &group : lines) {
1201       // Indices in this structure are actually offsets of records in the
1202       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1203       // into the global PDB string table.
1204       auto iter = checksums.at(group.NameIndex);
1205       if (iter == checksums.end())
1206         continue;
1207 
1208       llvm::Expected<llvm::StringRef> efn =
1209           strings.getString(iter->FileNameOffset);
1210       if (!efn) {
1211         llvm::consumeError(efn.takeError());
1212         continue;
1213       }
1214 
1215       // LLDB wants the index of the file in the list of support files.
1216       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1217       lldbassert(fn_iter != cci->m_file_list.end());
1218       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1219 
1220       std::unique_ptr<LineSequence> sequence(
1221           line_table->CreateLineSequenceContainer());
1222       lldbassert(!group.LineNumbers.empty());
1223 
1224       for (const LineNumberEntry &entry : group.LineNumbers) {
1225         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1226                                   file_index, *lfh, entry);
1227       }
1228       LineInfo last_line(group.LineNumbers.back().Flags);
1229       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1230                             last_line.getEndLine(), std::move(sequence));
1231     }
1232   }
1233 
1234   if (line_table->GetSize() == 0)
1235     return false;
1236 
1237   sc.comp_unit->SetLineTable(line_table.release());
1238   return true;
1239 }
1240 
1241 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
1242   // PDB doesn't contain information about macros
1243   return false;
1244 }
1245 
1246 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
1247     const SymbolContext &sc, FileSpecList &support_files) {
1248   lldbassert(sc.comp_unit);
1249 
1250   PdbSymUid comp_uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1251   lldbassert(comp_uid.tag() == PDB_SymType::Compiland);
1252 
1253   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(comp_uid);
1254   lldbassert(cci);
1255 
1256   for (llvm::StringRef f : cci->m_file_list) {
1257     FileSpec::Style style =
1258         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1259     FileSpec spec(f, false, style);
1260     support_files.Append(spec);
1261   }
1262 
1263   return true;
1264 }
1265 
1266 bool SymbolFileNativePDB::ParseImportedModules(
1267     const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
1268   // PDB does not yet support module debug info
1269   return false;
1270 }
1271 
1272 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
1273   lldbassert(sc.comp_unit && sc.function);
1274   return 0;
1275 }
1276 
1277 uint32_t SymbolFileNativePDB::FindGlobalVariables(
1278     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1279     uint32_t max_matches, VariableList &variables) {
1280   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1281 
1282   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1283       name.GetStringRef(), m_index->symrecords());
1284   for (const SymbolAndOffset &result : results) {
1285     VariableSP var;
1286     switch (result.second.kind()) {
1287     case SymbolKind::S_GDATA32:
1288     case SymbolKind::S_LDATA32:
1289     case SymbolKind::S_GTHREAD32:
1290     case SymbolKind::S_LTHREAD32: {
1291       PdbSymUid uid = PdbSymUid::makeGlobalVariableUid(result.first);
1292       var = GetOrCreateGlobalVariable(uid);
1293       variables.AddVariable(var);
1294       break;
1295     }
1296     default:
1297       continue;
1298     }
1299   }
1300   return variables.GetSize();
1301 }
1302 
1303 uint32_t SymbolFileNativePDB::FindFunctions(
1304     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1305     FunctionNameType name_type_mask, bool include_inlines, bool append,
1306     SymbolContextList &sc_list) {
1307   // For now we only support lookup by method name.
1308   if (!(name_type_mask & eFunctionNameTypeMethod))
1309     return 0;
1310 
1311   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1312 
1313   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1314       name.GetStringRef(), m_index->symrecords());
1315   for (const SymbolAndOffset &match : matches) {
1316     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1317       continue;
1318     ProcRefSym proc(match.second.kind());
1319     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1320 
1321     if (!IsValidRecord(proc))
1322       continue;
1323 
1324     PdbSymUid cuid = PdbSymUid::makeCompilandId(proc);
1325     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid);
1326     SymbolContext sc;
1327 
1328     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1329     sc.module_sp = sc.comp_unit->GetModule();
1330     PdbSymUid func_uid = PdbSymUid::makeCuSymId(proc);
1331     sc.function = GetOrCreateFunction(func_uid, sc).get();
1332 
1333     sc_list.Append(sc);
1334   }
1335 
1336   return sc_list.GetSize();
1337 }
1338 
1339 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1340                                             bool include_inlines, bool append,
1341                                             SymbolContextList &sc_list) {
1342   return 0;
1343 }
1344 
1345 uint32_t SymbolFileNativePDB::FindTypes(
1346     const SymbolContext &sc, const ConstString &name,
1347     const CompilerDeclContext *parent_decl_ctx, bool append,
1348     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1349     TypeMap &types) {
1350   if (!append)
1351     types.Clear();
1352   if (!name)
1353     return 0;
1354 
1355   searched_symbol_files.clear();
1356   searched_symbol_files.insert(this);
1357 
1358   // There is an assumption 'name' is not a regex
1359   size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1360 
1361   return match_count;
1362 }
1363 
1364 size_t
1365 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1366                                bool append, TypeMap &types) {
1367   return 0;
1368 }
1369 
1370 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1371                                             uint32_t max_matches,
1372                                             TypeMap &types) {
1373 
1374   size_t match_count = 0;
1375   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1376   if (max_matches > 0 && max_matches < matches.size())
1377     matches.resize(max_matches);
1378 
1379   for (TypeIndex ti : matches) {
1380     TypeSP type = GetOrCreateType(ti);
1381     if (!type)
1382       continue;
1383 
1384     types.Insert(type);
1385     ++match_count;
1386   }
1387   return match_count;
1388 }
1389 
1390 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1391 
1392 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1393   auto iter = m_types.find(type_uid);
1394   // lldb should not be passing us non-sensical type uids.  the only way it
1395   // could have a type uid in the first place is if we handed it out, in which
1396   // case we should know about the type.  However, that doesn't mean we've
1397   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1398   // type doesn't exist, let's instantiate it now.
1399   if (iter != m_types.end())
1400     return &*iter->second;
1401 
1402   PdbSymUid uid = PdbSymUid::fromOpaqueId(type_uid);
1403   lldbassert(uid.isTypeSym(uid.tag()));
1404   const PdbTypeSymId &type_id = uid.asTypeSym();
1405   TypeIndex ti(type_id.index);
1406   if (ti.isNoneType())
1407     return nullptr;
1408 
1409   TypeSP type_sp = CreateAndCacheType(uid);
1410   return &*type_sp;
1411 }
1412 
1413 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1414   // If this is not in our map, it's an error.
1415   clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1416   lldbassert(tag_decl);
1417   auto status_iter = m_decl_to_status.find(tag_decl);
1418   lldbassert(status_iter != m_decl_to_status.end());
1419 
1420   // If it's already complete, just return.
1421   DeclStatus &status = status_iter->second;
1422   if (status.status == Type::eResolveStateFull)
1423     return true;
1424 
1425   PdbSymUid uid = PdbSymUid::fromOpaqueId(status.uid);
1426   lldbassert(uid.tag() == PDB_SymType::UDT || uid.tag() == PDB_SymType::Enum);
1427 
1428   const PdbTypeSymId &type_id = uid.asTypeSym();
1429 
1430   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
1431                                          false);
1432 
1433   // In CreateAndCacheType, we already go out of our way to resolve forward
1434   // ref UDTs to full decls, and the uids we vend out always refer to full
1435   // decls if a full decl exists in the debug info.  So if we don't have a full
1436   // decl here, it means one doesn't exist in the debug info, and we can't
1437   // complete the type.
1438   CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
1439   if (IsForwardRefUdt(cvt))
1440     return false;
1441 
1442   auto types_iter = m_types.find(uid.toOpaqueId());
1443   lldbassert(types_iter != m_types.end());
1444 
1445   TypeIndex field_list_ti = GetFieldListIndex(cvt);
1446   CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
1447   if (field_list_cvt.kind() != LF_FIELDLIST)
1448     return false;
1449 
1450   // Visit all members of this class, then perform any finalization necessary
1451   // to complete the class.
1452   UdtRecordCompleter completer(uid, compiler_type, *tag_decl, *this);
1453   auto error =
1454       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
1455   completer.complete();
1456 
1457   status.status = Type::eResolveStateFull;
1458   if (!error)
1459     return true;
1460 
1461   llvm::consumeError(std::move(error));
1462   return false;
1463 }
1464 
1465 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1466                                      TypeClass type_mask,
1467                                      lldb_private::TypeList &type_list) {
1468   return 0;
1469 }
1470 
1471 CompilerDeclContext
1472 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
1473                                    const ConstString &name,
1474                                    const CompilerDeclContext *parent_decl_ctx) {
1475   return {};
1476 }
1477 
1478 TypeSystem *
1479 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1480   auto type_system =
1481       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1482   if (type_system)
1483     type_system->SetSymbolFile(this);
1484   return type_system;
1485 }
1486 
1487 ConstString SymbolFileNativePDB::GetPluginName() {
1488   static ConstString g_name("pdb");
1489   return g_name;
1490 }
1491 
1492 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1493