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