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);
824   var_sp->SetLocationIsConstantValueData(false);
825 
826   return var_sp;
827 }
828 
829 lldb::VariableSP
830 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
831                                           const CVSymbol &cvs) {
832   TpiStream &tpi = m_index->tpi();
833   ConstantSym constant(cvs.kind());
834 
835   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
836   std::string global_name("::");
837   global_name += constant.Name;
838   PdbTypeSymId tid(constant.Type, false);
839   SymbolFileTypeSP type_sp =
840       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
841 
842   Declaration decl;
843   Variable::RangeList ranges;
844   ModuleSP module = GetObjectFile()->GetModule();
845   DWARFExpression location = MakeConstantLocationExpression(
846       constant.Type, tpi, constant.Value, module);
847 
848   VariableSP var_sp = std::make_shared<Variable>(
849       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
850       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
851       false, false, false);
852   var_sp->SetLocationIsConstantValueData(true);
853   return var_sp;
854 }
855 
856 VariableSP
857 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
858   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
859   if (emplace_result.second)
860     emplace_result.first->second = CreateGlobalVariable(var_id);
861 
862   return emplace_result.first->second;
863 }
864 
865 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
866   return GetOrCreateType(PdbTypeSymId(ti, false));
867 }
868 
869 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
870                                                     CompileUnit &comp_unit) {
871   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
872   if (emplace_result.second)
873     emplace_result.first->second = CreateFunction(func_id, comp_unit);
874 
875   return emplace_result.first->second;
876 }
877 
878 CompUnitSP
879 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
880 
881   auto emplace_result =
882       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
883   if (emplace_result.second)
884     emplace_result.first->second = CreateCompileUnit(cci);
885 
886   lldbassert(emplace_result.first->second);
887   return emplace_result.first->second;
888 }
889 
890 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
891   auto iter = m_blocks.find(toOpaqueUid(block_id));
892   if (iter != m_blocks.end())
893     return *iter->second;
894 
895   return CreateBlock(block_id);
896 }
897 
898 void SymbolFileNativePDB::ParseDeclsForContext(
899     lldb_private::CompilerDeclContext decl_ctx) {
900   clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx);
901   if (!context)
902     return;
903   m_ast->ParseDeclsForContext(*context);
904 }
905 
906 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
907   if (index >= GetNumCompileUnits())
908     return CompUnitSP();
909   lldbassert(index < UINT16_MAX);
910   if (index >= UINT16_MAX)
911     return nullptr;
912 
913   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
914 
915   return GetOrCreateCompileUnit(item);
916 }
917 
918 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
919   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
920   PdbSymUid uid(comp_unit.GetID());
921   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
922 
923   CompilandIndexItem *item =
924       m_index->compilands().GetCompiland(uid.asCompiland().modi);
925   lldbassert(item);
926   if (!item->m_compile_opts)
927     return lldb::eLanguageTypeUnknown;
928 
929   return TranslateLanguage(item->m_compile_opts->getLanguage());
930 }
931 
932 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) { return; }
933 
934 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
935   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
936   PdbSymUid uid{comp_unit.GetID()};
937   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
938   uint16_t modi = uid.asCompiland().modi;
939   CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
940 
941   size_t count = comp_unit.GetNumFunctions();
942   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
943   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
944     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
945       continue;
946 
947     PdbCompilandSymId sym_id{modi, iter.offset()};
948 
949     FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
950   }
951 
952   size_t new_count = comp_unit.GetNumFunctions();
953   lldbassert(new_count >= count);
954   return new_count - count;
955 }
956 
957 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
958   // If any of these flags are set, we need to resolve the compile unit.
959   uint32_t flags = eSymbolContextCompUnit;
960   flags |= eSymbolContextVariable;
961   flags |= eSymbolContextFunction;
962   flags |= eSymbolContextBlock;
963   flags |= eSymbolContextLineEntry;
964   return (resolve_scope & flags) != 0;
965 }
966 
967 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
968     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
969   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
970   uint32_t resolved_flags = 0;
971   lldb::addr_t file_addr = addr.GetFileAddress();
972 
973   if (NeedsResolvedCompileUnit(resolve_scope)) {
974     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
975     if (!modi)
976       return 0;
977     CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
978     if (!cci)
979       return 0;
980 
981     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
982     resolved_flags |= eSymbolContextCompUnit;
983   }
984 
985   if (resolve_scope & eSymbolContextFunction ||
986       resolve_scope & eSymbolContextBlock) {
987     lldbassert(sc.comp_unit);
988     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
989     // Search the matches in reverse.  This way if there are multiple matches
990     // (for example we are 3 levels deep in a nested scope) it will find the
991     // innermost one first.
992     for (const auto &match : llvm::reverse(matches)) {
993       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
994         continue;
995 
996       PdbCompilandSymId csid = match.uid.asCompilandSym();
997       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
998       PDB_SymType type = CVSymToPDBSym(cvs.kind());
999       if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1000         continue;
1001       if (type == PDB_SymType::Function) {
1002         sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1003         sc.block = sc.GetFunctionBlock();
1004       }
1005 
1006       if (type == PDB_SymType::Block) {
1007         sc.block = &GetOrCreateBlock(csid);
1008         sc.function = sc.block->CalculateSymbolContextFunction();
1009       }
1010     resolved_flags |= eSymbolContextFunction;
1011     resolved_flags |= eSymbolContextBlock;
1012     break;
1013     }
1014   }
1015 
1016   if (resolve_scope & eSymbolContextLineEntry) {
1017     lldbassert(sc.comp_unit);
1018     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1019       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1020         resolved_flags |= eSymbolContextLineEntry;
1021     }
1022   }
1023 
1024   return resolved_flags;
1025 }
1026 
1027 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1028     const FileSpec &file_spec, uint32_t line, bool check_inlines,
1029     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1030   return 0;
1031 }
1032 
1033 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1034                                       const CompilandIndexItem &cci,
1035                                       lldb::addr_t base_addr,
1036                                       uint32_t file_number,
1037                                       const LineFragmentHeader &block,
1038                                       const LineNumberEntry &cur) {
1039   LineInfo cur_info(cur.Flags);
1040 
1041   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1042     return;
1043 
1044   uint64_t addr = base_addr + cur.Offset;
1045 
1046   bool is_statement = cur_info.isStatement();
1047   bool is_prologue = IsFunctionPrologue(cci, addr);
1048   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1049 
1050   uint32_t lno = cur_info.getStartLine();
1051 
1052   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1053                                   is_statement, false, is_prologue, is_epilogue,
1054                                   false);
1055 }
1056 
1057 static void TerminateLineSequence(LineTable &table,
1058                                   const LineFragmentHeader &block,
1059                                   lldb::addr_t base_addr, uint32_t file_number,
1060                                   uint32_t last_line,
1061                                   std::unique_ptr<LineSequence> seq) {
1062   // The end is always a terminal entry, so insert it regardless.
1063   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1064                                   last_line, 0, file_number, false, false,
1065                                   false, false, true);
1066   table.InsertSequence(seq.release());
1067 }
1068 
1069 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1070   // Unfortunately LLDB is set up to parse the entire compile unit line table
1071   // all at once, even if all it really needs is line info for a specific
1072   // function.  In the future it would be nice if it could set the sc.m_function
1073   // member, and we could only get the line info for the function in question.
1074   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1075   PdbSymUid cu_id(comp_unit.GetID());
1076   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1077   CompilandIndexItem *cci =
1078       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1079   lldbassert(cci);
1080   auto line_table = std::make_unique<LineTable>(&comp_unit);
1081 
1082   // This is basically a copy of the .debug$S subsections from all original COFF
1083   // object files merged together with address relocations applied.  We are
1084   // looking for all DEBUG_S_LINES subsections.
1085   for (const DebugSubsectionRecord &dssr :
1086        cci->m_debug_stream.getSubsectionsArray()) {
1087     if (dssr.kind() != DebugSubsectionKind::Lines)
1088       continue;
1089 
1090     DebugLinesSubsectionRef lines;
1091     llvm::BinaryStreamReader reader(dssr.getRecordData());
1092     if (auto EC = lines.initialize(reader)) {
1093       llvm::consumeError(std::move(EC));
1094       return false;
1095     }
1096 
1097     const LineFragmentHeader *lfh = lines.header();
1098     uint64_t virtual_addr =
1099         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1100 
1101     const auto &checksums = cci->m_strings.checksums().getArray();
1102     const auto &strings = cci->m_strings.strings();
1103     for (const LineColumnEntry &group : lines) {
1104       // Indices in this structure are actually offsets of records in the
1105       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1106       // into the global PDB string table.
1107       auto iter = checksums.at(group.NameIndex);
1108       if (iter == checksums.end())
1109         continue;
1110 
1111       llvm::Expected<llvm::StringRef> efn =
1112           strings.getString(iter->FileNameOffset);
1113       if (!efn) {
1114         llvm::consumeError(efn.takeError());
1115         continue;
1116       }
1117 
1118       // LLDB wants the index of the file in the list of support files.
1119       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1120       lldbassert(fn_iter != cci->m_file_list.end());
1121       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1122 
1123       std::unique_ptr<LineSequence> sequence(
1124           line_table->CreateLineSequenceContainer());
1125       lldbassert(!group.LineNumbers.empty());
1126 
1127       for (const LineNumberEntry &entry : group.LineNumbers) {
1128         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1129                                   file_index, *lfh, entry);
1130       }
1131       LineInfo last_line(group.LineNumbers.back().Flags);
1132       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1133                             last_line.getEndLine(), std::move(sequence));
1134     }
1135   }
1136 
1137   if (line_table->GetSize() == 0)
1138     return false;
1139 
1140   comp_unit.SetLineTable(line_table.release());
1141   return true;
1142 }
1143 
1144 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1145   // PDB doesn't contain information about macros
1146   return false;
1147 }
1148 
1149 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1150                                             FileSpecList &support_files) {
1151   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1152   PdbSymUid cu_id(comp_unit.GetID());
1153   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1154   CompilandIndexItem *cci =
1155       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1156   lldbassert(cci);
1157 
1158   for (llvm::StringRef f : cci->m_file_list) {
1159     FileSpec::Style style =
1160         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1161     FileSpec spec(f, style);
1162     support_files.Append(spec);
1163   }
1164   return true;
1165 }
1166 
1167 bool SymbolFileNativePDB::ParseImportedModules(
1168     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1169   // PDB does not yet support module debug info
1170   return false;
1171 }
1172 
1173 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1174   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1175   GetOrCreateBlock(PdbSymUid(func.GetID()).asCompilandSym());
1176   // FIXME: Parse child blocks
1177   return 1;
1178 }
1179 
1180 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1181 
1182 void SymbolFileNativePDB::FindGlobalVariables(
1183     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1184     uint32_t max_matches, VariableList &variables) {
1185   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1186   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1187 
1188   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1189       name.GetStringRef(), m_index->symrecords());
1190   for (const SymbolAndOffset &result : results) {
1191     VariableSP var;
1192     switch (result.second.kind()) {
1193     case SymbolKind::S_GDATA32:
1194     case SymbolKind::S_LDATA32:
1195     case SymbolKind::S_GTHREAD32:
1196     case SymbolKind::S_LTHREAD32:
1197     case SymbolKind::S_CONSTANT: {
1198       PdbGlobalSymId global(result.first, false);
1199       var = GetOrCreateGlobalVariable(global);
1200       variables.AddVariable(var);
1201       break;
1202     }
1203     default:
1204       continue;
1205     }
1206   }
1207 }
1208 
1209 void SymbolFileNativePDB::FindFunctions(
1210     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1211     FunctionNameType name_type_mask, bool include_inlines,
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;
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 
1243 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1244                                         bool include_inlines,
1245                                         SymbolContextList &sc_list) {}
1246 
1247 void SymbolFileNativePDB::FindTypes(
1248     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1249     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1250     TypeMap &types) {
1251   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1252   if (!name)
1253     return;
1254 
1255   searched_symbol_files.clear();
1256   searched_symbol_files.insert(this);
1257 
1258   // There is an assumption 'name' is not a regex
1259   FindTypesByName(name.GetStringRef(), max_matches, types);
1260 }
1261 
1262 void SymbolFileNativePDB::FindTypes(
1263     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1264     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1265 
1266 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1267                                           uint32_t max_matches,
1268                                           TypeMap &types) {
1269 
1270   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1271   if (max_matches > 0 && max_matches < matches.size())
1272     matches.resize(max_matches);
1273 
1274   for (TypeIndex ti : matches) {
1275     TypeSP type = GetOrCreateType(ti);
1276     if (!type)
1277       continue;
1278 
1279     types.Insert(type);
1280   }
1281 }
1282 
1283 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1284   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1285   // Only do the full type scan the first time.
1286   if (m_done_full_type_scan)
1287     return 0;
1288 
1289   const size_t old_count = GetTypeList().GetSize();
1290   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1291 
1292   // First process the entire TPI stream.
1293   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1294     TypeSP type = GetOrCreateType(*ti);
1295     if (type)
1296       (void)type->GetFullCompilerType();
1297   }
1298 
1299   // Next look for S_UDT records in the globals stream.
1300   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1301     PdbGlobalSymId global{gid, false};
1302     CVSymbol sym = m_index->ReadSymbolRecord(global);
1303     if (sym.kind() != S_UDT)
1304       continue;
1305 
1306     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1307     bool is_typedef = true;
1308     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1309       CVType cvt = m_index->tpi().getType(udt.Type);
1310       llvm::StringRef name = CVTagRecord::create(cvt).name();
1311       if (name == udt.Name)
1312         is_typedef = false;
1313     }
1314 
1315     if (is_typedef)
1316       GetOrCreateTypedef(global);
1317   }
1318 
1319   const size_t new_count = GetTypeList().GetSize();
1320 
1321   m_done_full_type_scan = true;
1322 
1323   return new_count - old_count;
1324 }
1325 
1326 size_t
1327 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1328                                                   VariableList &variables) {
1329   PdbSymUid sym_uid(comp_unit.GetID());
1330   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1331   return 0;
1332 }
1333 
1334 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1335                                                     PdbCompilandSymId var_id,
1336                                                     bool is_param) {
1337   ModuleSP module = GetObjectFile()->GetModule();
1338   Block &block = GetOrCreateBlock(scope_id);
1339   VariableInfo var_info =
1340       GetVariableLocationInfo(*m_index, var_id, block, module);
1341   if (!var_info.location || !var_info.ranges)
1342     return nullptr;
1343 
1344   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1345   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1346   TypeSP type_sp = GetOrCreateType(var_info.type);
1347   std::string name = var_info.name.str();
1348   Declaration decl;
1349   SymbolFileTypeSP sftype =
1350       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1351 
1352   ValueType var_scope =
1353       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1354   VariableSP var_sp = std::make_shared<Variable>(
1355       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1356       comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, false,
1357       false, false);
1358 
1359   if (!is_param)
1360     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1361 
1362   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1363   return var_sp;
1364 }
1365 
1366 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1367     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1368   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1369   if (iter != m_local_variables.end())
1370     return iter->second;
1371 
1372   return CreateLocalVariable(scope_id, var_id, is_param);
1373 }
1374 
1375 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1376   CVSymbol sym = m_index->ReadSymbolRecord(id);
1377   lldbassert(sym.kind() == SymbolKind::S_UDT);
1378 
1379   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1380 
1381   TypeSP target_type = GetOrCreateType(udt.Type);
1382 
1383   (void)m_ast->GetOrCreateTypedefDecl(id);
1384 
1385   Declaration decl;
1386   return std::make_shared<lldb_private::Type>(
1387       toOpaqueUid(id), this, ConstString(udt.Name),
1388       target_type->GetByteSize(nullptr), nullptr, target_type->GetID(),
1389       lldb_private::Type::eEncodingIsTypedefUID, decl,
1390       target_type->GetForwardCompilerType(),
1391       lldb_private::Type::ResolveState::Forward);
1392 }
1393 
1394 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1395   auto iter = m_types.find(toOpaqueUid(id));
1396   if (iter != m_types.end())
1397     return iter->second;
1398 
1399   return CreateTypedef(id);
1400 }
1401 
1402 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1403   Block &block = GetOrCreateBlock(block_id);
1404 
1405   size_t count = 0;
1406 
1407   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1408   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1409   uint32_t params_remaining = 0;
1410   switch (sym.kind()) {
1411   case S_GPROC32:
1412   case S_LPROC32: {
1413     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1414     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1415     CVType signature = m_index->tpi().getType(proc.FunctionType);
1416     ProcedureRecord sig;
1417     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1418     params_remaining = sig.getParameterCount();
1419     break;
1420   }
1421   case S_BLOCK32:
1422     break;
1423   default:
1424     lldbassert(false && "Symbol is not a block!");
1425     return 0;
1426   }
1427 
1428   VariableListSP variables = block.GetBlockVariableList(false);
1429   if (!variables) {
1430     variables = std::make_shared<VariableList>();
1431     block.SetVariableList(variables);
1432   }
1433 
1434   CVSymbolArray syms = limitSymbolArrayToScope(
1435       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1436 
1437   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1438   // no point examining it since we know it's not a local variable.
1439   syms.drop_front();
1440   auto iter = syms.begin();
1441   auto end = syms.end();
1442 
1443   while (iter != end) {
1444     uint32_t record_offset = iter.offset();
1445     CVSymbol variable_cvs = *iter;
1446     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1447     ++iter;
1448 
1449     // If this is a block, recurse into its children and then skip it.
1450     if (variable_cvs.kind() == S_BLOCK32) {
1451       uint32_t block_end = getScopeEndOffset(variable_cvs);
1452       count += ParseVariablesForBlock(child_sym_id);
1453       iter = syms.at(block_end);
1454       continue;
1455     }
1456 
1457     bool is_param = params_remaining > 0;
1458     VariableSP variable;
1459     switch (variable_cvs.kind()) {
1460     case S_REGREL32:
1461     case S_REGISTER:
1462     case S_LOCAL:
1463       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1464       if (is_param)
1465         --params_remaining;
1466       if (variable)
1467         variables->AddVariableIfUnique(variable);
1468       break;
1469     default:
1470       break;
1471     }
1472   }
1473 
1474   // Pass false for set_children, since we call this recursively so that the
1475   // children will call this for themselves.
1476   block.SetDidParseVariables(true, false);
1477 
1478   return count;
1479 }
1480 
1481 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1482   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1483   lldbassert(sc.function || sc.comp_unit);
1484 
1485   VariableListSP variables;
1486   if (sc.block) {
1487     PdbSymUid block_id(sc.block->GetID());
1488 
1489     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1490     return count;
1491   }
1492 
1493   if (sc.function) {
1494     PdbSymUid block_id(sc.function->GetID());
1495 
1496     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1497     return count;
1498   }
1499 
1500   if (sc.comp_unit) {
1501     variables = sc.comp_unit->GetVariableList(false);
1502     if (!variables) {
1503       variables = std::make_shared<VariableList>();
1504       sc.comp_unit->SetVariableList(variables);
1505     }
1506     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1507   }
1508 
1509   llvm_unreachable("Unreachable!");
1510 }
1511 
1512 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1513   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1514     return decl.getValue();
1515   else
1516     return CompilerDecl();
1517 }
1518 
1519 CompilerDeclContext
1520 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1521   clang::DeclContext *context =
1522       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1523   if (!context)
1524     return {};
1525 
1526   return m_ast->ToCompilerDeclContext(*context);
1527 }
1528 
1529 CompilerDeclContext
1530 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1531   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1532   return m_ast->ToCompilerDeclContext(*context);
1533 }
1534 
1535 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1536   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1537   auto iter = m_types.find(type_uid);
1538   // lldb should not be passing us non-sensical type uids.  the only way it
1539   // could have a type uid in the first place is if we handed it out, in which
1540   // case we should know about the type.  However, that doesn't mean we've
1541   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1542   // type doesn't exist, let's instantiate it now.
1543   if (iter != m_types.end())
1544     return &*iter->second;
1545 
1546   PdbSymUid uid(type_uid);
1547   lldbassert(uid.kind() == PdbSymUidKind::Type);
1548   PdbTypeSymId type_id = uid.asTypeSym();
1549   if (type_id.index.isNoneType())
1550     return nullptr;
1551 
1552   TypeSP type_sp = CreateAndCacheType(type_id);
1553   return &*type_sp;
1554 }
1555 
1556 llvm::Optional<SymbolFile::ArrayInfo>
1557 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1558     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1559   return llvm::None;
1560 }
1561 
1562 
1563 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1564   clang::QualType qt =
1565       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1566 
1567   return m_ast->CompleteType(qt);
1568 }
1569 
1570 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1571                                    TypeClass type_mask,
1572                                    lldb_private::TypeList &type_list) {}
1573 
1574 CompilerDeclContext
1575 SymbolFileNativePDB::FindNamespace(ConstString name,
1576                                    const CompilerDeclContext &parent_decl_ctx) {
1577   return {};
1578 }
1579 
1580 llvm::Expected<TypeSystem &>
1581 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1582   auto type_system_or_err =
1583       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1584   if (type_system_or_err) {
1585     type_system_or_err->SetSymbolFile(this);
1586   }
1587   return type_system_or_err;
1588 }
1589 
1590 ConstString SymbolFileNativePDB::GetPluginName() {
1591   static ConstString g_name("pdb");
1592   return g_name;
1593 }
1594 
1595 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1596