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