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