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