blob: 5db4c00c5bc2e6988998ea11f1339f02255f7420 [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 Turnera42bbe32018-12-07 19:34:02 +000040#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
Zachary Turner2f7efbc2018-10-23 16:37:53 +000041#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000042#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
43#include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
44#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
45#include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
46#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
47#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
Zachary Turner2f7efbc2018-10-23 16:37:53 +000048#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000049#include "llvm/DebugInfo/PDB/PDBTypes.h"
Zachary Turner056e4ab2018-11-08 18:50:11 +000050#include "llvm/Demangle/MicrosoftDemangle.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000051#include "llvm/Object/COFF.h"
52#include "llvm/Support/Allocator.h"
53#include "llvm/Support/BinaryStreamReader.h"
Zachary Turner056e4ab2018-11-08 18:50:11 +000054#include "llvm/Support/Error.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000055#include "llvm/Support/ErrorOr.h"
56#include "llvm/Support/MemoryBuffer.h"
57
Zachary Turnera93458b2018-12-06 17:49:15 +000058#include "DWARFLocationExpression.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000059#include "PdbSymUid.h"
60#include "PdbUtil.h"
Zachary Turner2f7efbc2018-10-23 16:37:53 +000061#include "UdtRecordCompleter.h"
Zachary Turner307f5ae2018-10-12 19:47:13 +000062
63using namespace lldb;
64using namespace lldb_private;
Zachary Turner2f7efbc2018-10-23 16:37:53 +000065using namespace npdb;
Zachary Turner307f5ae2018-10-12 19:47:13 +000066using namespace llvm::codeview;
67using namespace llvm::pdb;
68
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +000069namespace {
70struct VariableInfo {
71 llvm::StringRef name;
72 TypeIndex type;
73 llvm::Optional<DWARFExpression> location;
74 llvm::Optional<Variable::RangeList> ranges;
75};
76} // namespace
77
Zachary Turner307f5ae2018-10-12 19:47:13 +000078static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
79 switch (lang) {
80 case PDB_Lang::Cpp:
81 return lldb::LanguageType::eLanguageTypeC_plus_plus;
82 case PDB_Lang::C:
83 return lldb::LanguageType::eLanguageTypeC;
84 default:
85 return lldb::LanguageType::eLanguageTypeUnknown;
86 }
87}
88
89static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
90 llvm::BumpPtrAllocator &Allocator) {
91 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
92 llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
93 /*RequiresNullTerminator=*/false);
94 if (!ErrorOrBuffer)
95 return nullptr;
96 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
97
98 llvm::StringRef Path = Buffer->getBufferIdentifier();
99 auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>(
100 std::move(Buffer), llvm::support::little);
101
102 auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
Zachary Turner8040eea2018-10-12 22:57:40 +0000103 if (auto EC = File->parseFileHeaders()) {
104 llvm::consumeError(std::move(EC));
Zachary Turner307f5ae2018-10-12 19:47:13 +0000105 return nullptr;
Zachary Turner8040eea2018-10-12 22:57:40 +0000106 }
107 if (auto EC = File->parseStreamData()) {
108 llvm::consumeError(std::move(EC));
Zachary Turner307f5ae2018-10-12 19:47:13 +0000109 return nullptr;
Zachary Turner8040eea2018-10-12 22:57:40 +0000110 }
Zachary Turner307f5ae2018-10-12 19:47:13 +0000111
112 return File;
113}
114
115static std::unique_ptr<PDBFile>
116loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
117 // Try to find a matching PDB for an EXE.
118 using namespace llvm::object;
119 auto expected_binary = createBinary(exe_path);
120
121 // If the file isn't a PE/COFF executable, fail.
122 if (!expected_binary) {
123 llvm::consumeError(expected_binary.takeError());
124 return nullptr;
125 }
126 OwningBinary<Binary> binary = std::move(*expected_binary);
127
128 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
129 if (!obj)
130 return nullptr;
131 const llvm::codeview::DebugInfo *pdb_info = nullptr;
132
133 // If it doesn't have a debug directory, fail.
134 llvm::StringRef pdb_file;
135 auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
136 if (ec)
137 return nullptr;
138
139 // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
140 // fail.
141 llvm::file_magic magic;
142 ec = llvm::identify_magic(pdb_file, magic);
143 if (ec || magic != llvm::file_magic::pdb)
144 return nullptr;
145 std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator);
Zachary Turner8040eea2018-10-12 22:57:40 +0000146 if (!pdb)
147 return nullptr;
148
Zachary Turner307f5ae2018-10-12 19:47:13 +0000149 auto expected_info = pdb->getPDBInfoStream();
150 if (!expected_info) {
151 llvm::consumeError(expected_info.takeError());
152 return nullptr;
153 }
154 llvm::codeview::GUID guid;
155 memcpy(&guid, pdb_info->PDB70.Signature, 16);
156
157 if (expected_info->getGuid() != guid)
158 return nullptr;
159 return pdb;
160}
161
162static bool IsFunctionPrologue(const CompilandIndexItem &cci,
163 lldb::addr_t addr) {
164 // FIXME: Implement this.
165 return false;
166}
167
168static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
169 lldb::addr_t addr) {
170 // FIXME: Implement this.
171 return false;
172}
173
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000174static clang::MSInheritanceAttr::Spelling
175GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) {
176 if (record.DerivationList == TypeIndex::None())
177 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
178
179 CVType bases = tpi.getType(record.DerivationList);
180 ArgListRecord base_list;
181 cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list));
182 if (base_list.ArgIndices.empty())
183 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
184
185 int base_count = 0;
186 for (TypeIndex ti : base_list.ArgIndices) {
187 CVType base = tpi.getType(ti);
188 if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS)
189 return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
190 ++base_count;
191 }
192
193 if (base_count > 1)
194 return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
195 return clang::MSInheritanceAttr::Keyword_single_inheritance;
196}
197
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000198static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
199 switch (kind) {
200 case SimpleTypeKind::Boolean128:
201 case SimpleTypeKind::Boolean16:
202 case SimpleTypeKind::Boolean32:
203 case SimpleTypeKind::Boolean64:
204 case SimpleTypeKind::Boolean8:
205 return "bool";
206 case SimpleTypeKind::Byte:
207 case SimpleTypeKind::UnsignedCharacter:
208 return "unsigned char";
209 case SimpleTypeKind::NarrowCharacter:
210 return "char";
211 case SimpleTypeKind::SignedCharacter:
212 case SimpleTypeKind::SByte:
Zachary Turner71ebb722018-10-23 22:15:05 +0000213 return "signed char";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000214 case SimpleTypeKind::Character16:
215 return "char16_t";
216 case SimpleTypeKind::Character32:
217 return "char32_t";
218 case SimpleTypeKind::Complex80:
219 case SimpleTypeKind::Complex64:
220 case SimpleTypeKind::Complex32:
221 return "complex";
222 case SimpleTypeKind::Float128:
223 case SimpleTypeKind::Float80:
224 return "long double";
225 case SimpleTypeKind::Float64:
226 return "double";
227 case SimpleTypeKind::Float32:
228 return "float";
229 case SimpleTypeKind::Float16:
230 return "single";
231 case SimpleTypeKind::Int128:
232 return "__int128";
233 case SimpleTypeKind::Int64:
234 case SimpleTypeKind::Int64Quad:
Zachary Turner71ebb722018-10-23 22:15:05 +0000235 return "int64_t";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000236 case SimpleTypeKind::Int32:
237 return "int";
238 case SimpleTypeKind::Int16:
239 return "short";
240 case SimpleTypeKind::UInt128:
241 return "unsigned __int128";
242 case SimpleTypeKind::UInt64:
243 case SimpleTypeKind::UInt64Quad:
Zachary Turner71ebb722018-10-23 22:15:05 +0000244 return "uint64_t";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000245 case SimpleTypeKind::HResult:
246 return "HRESULT";
247 case SimpleTypeKind::UInt32:
248 return "unsigned";
249 case SimpleTypeKind::UInt16:
250 case SimpleTypeKind::UInt16Short:
251 return "unsigned short";
252 case SimpleTypeKind::Int32Long:
253 return "long";
254 case SimpleTypeKind::UInt32Long:
255 return "unsigned long";
256 case SimpleTypeKind::Void:
257 return "void";
258 case SimpleTypeKind::WideCharacter:
259 return "wchar_t";
260 default:
261 return "";
262 }
263}
264
265static bool IsClassRecord(TypeLeafKind kind) {
266 switch (kind) {
267 case LF_STRUCTURE:
268 case LF_CLASS:
269 case LF_INTERFACE:
270 return true;
271 default:
272 return false;
273 }
274}
275
Zachary Turner544a66d82018-11-01 16:37:29 +0000276static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
277 if (args.empty())
278 return false;
279 return args.back() == TypeIndex::None();
280}
281
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000282static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
283 switch (cr.Kind) {
284 case TypeRecordKind::Class:
285 return clang::TTK_Class;
286 case TypeRecordKind::Struct:
287 return clang::TTK_Struct;
288 case TypeRecordKind::Union:
289 return clang::TTK_Union;
290 case TypeRecordKind::Interface:
291 return clang::TTK_Interface;
292 case TypeRecordKind::Enum:
293 return clang::TTK_Enum;
294 default:
295 lldbassert(false && "Invalid tag record kind!");
296 return clang::TTK_Struct;
297 }
298}
299
Zachary Turner544a66d82018-11-01 16:37:29 +0000300static llvm::Optional<clang::CallingConv>
301TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
302 using CC = llvm::codeview::CallingConvention;
303 switch (conv) {
304
305 case CC::NearC:
306 case CC::FarC:
307 return clang::CallingConv::CC_C;
308 case CC::NearPascal:
309 case CC::FarPascal:
310 return clang::CallingConv::CC_X86Pascal;
311 case CC::NearFast:
312 case CC::FarFast:
313 return clang::CallingConv::CC_X86FastCall;
314 case CC::NearStdCall:
315 case CC::FarStdCall:
316 return clang::CallingConv::CC_X86StdCall;
317 case CC::ThisCall:
318 return clang::CallingConv::CC_X86ThisCall;
319 case CC::NearVector:
320 return clang::CallingConv::CC_X86VectorCall;
321 default:
322 return llvm::None;
323 }
324}
325
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000326static Variable::RangeList
327MakeRangeList(const PdbIndex &index, const LocalVariableAddrRange &range,
328 llvm::ArrayRef<LocalVariableAddrGap> gaps) {
329 lldb::addr_t start =
330 index.MakeVirtualAddress(range.ISectStart, range.OffsetStart);
331 lldb::addr_t end = start + range.Range;
332
333 Variable::RangeList result;
334 while (!gaps.empty()) {
335 const LocalVariableAddrGap &gap = gaps.front();
336
337 lldb::addr_t size = gap.GapStartOffset - start;
338 result.Append(start, size);
339 start += gap.Range;
340 gaps = gaps.drop_front();
341 }
342
343 result.Append(start, end);
344 return result;
345}
346
347static VariableInfo GetVariableInformation(PdbIndex &index,
348 PdbCompilandSymId var_id,
349 ModuleSP module,
350 bool get_location_info) {
351 VariableInfo result;
352 CVSymbol sym = index.ReadSymbolRecord(var_id);
353
354 if (sym.kind() == S_REGREL32) {
355 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
356 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
357 result.type = reg.Type;
358 result.name = reg.Name;
359 if (get_location_info) {
360 result.location =
361 MakeRegRelLocationExpression(reg.Register, reg.Offset, module);
362 result.ranges.emplace();
363 }
364 return result;
365 }
366
367 if (sym.kind() == S_REGISTER) {
368 RegisterSym reg(SymbolRecordKind::RegisterSym);
369 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
370 result.type = reg.Index;
371 result.name = reg.Name;
372 if (get_location_info) {
373 result.location =
374 MakeEnregisteredLocationExpression(reg.Register, module);
375 result.ranges.emplace();
376 }
377 return result;
378 }
379
380 if (sym.kind() == S_LOCAL) {
381 LocalSym local(SymbolRecordKind::LocalSym);
382 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
383 result.type = local.Type;
384 result.name = local.Name;
385
386 if (!get_location_info)
387 return result;
388
389 PdbCompilandSymId loc_specifier_id(var_id.modi,
390 var_id.offset + sym.RecordData.size());
391 CVSymbol loc_specifier_cvs = index.ReadSymbolRecord(loc_specifier_id);
392 if (loc_specifier_cvs.kind() == S_DEFRANGE_FRAMEPOINTER_REL) {
393 DefRangeFramePointerRelSym loc(
394 SymbolRecordKind::DefRangeFramePointerRelSym);
395 cantFail(SymbolDeserializer::deserializeAs<DefRangeFramePointerRelSym>(
396 loc_specifier_cvs, loc));
397 // FIXME: The register needs to come from the S_FRAMEPROC symbol.
398 result.location =
399 MakeRegRelLocationExpression(RegisterId::RSP, loc.Offset, module);
400 result.ranges = MakeRangeList(index, loc.Range, loc.Gaps);
401 } else {
402 // FIXME: Handle other kinds
403 llvm::APSInt value;
404 value = 42;
405 result.location = MakeConstantLocationExpression(
406 TypeIndex::Int32(), index.tpi(), value, module);
407 }
408 return result;
409 }
410 llvm_unreachable("Symbol is not a local variable!");
411 return result;
412}
413
Zachary Turner307f5ae2018-10-12 19:47:13 +0000414void SymbolFileNativePDB::Initialize() {
415 PluginManager::RegisterPlugin(GetPluginNameStatic(),
416 GetPluginDescriptionStatic(), CreateInstance,
417 DebuggerInitialize);
418}
419
420void SymbolFileNativePDB::Terminate() {
421 PluginManager::UnregisterPlugin(CreateInstance);
422}
423
Zachary Turnerb96181c2018-10-22 16:19:07 +0000424void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
Zachary Turner307f5ae2018-10-12 19:47:13 +0000425
Zachary Turnerb96181c2018-10-22 16:19:07 +0000426ConstString SymbolFileNativePDB::GetPluginNameStatic() {
Zachary Turner307f5ae2018-10-12 19:47:13 +0000427 static ConstString g_name("native-pdb");
428 return g_name;
429}
430
431const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
432 return "Microsoft PDB debug symbol cross-platform file reader.";
433}
434
Zachary Turnerb96181c2018-10-22 16:19:07 +0000435SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
Zachary Turner307f5ae2018-10-12 19:47:13 +0000436 return new SymbolFileNativePDB(obj_file);
437}
438
Zachary Turnerb96181c2018-10-22 16:19:07 +0000439SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
Zachary Turner307f5ae2018-10-12 19:47:13 +0000440 : SymbolFile(object_file) {}
441
442SymbolFileNativePDB::~SymbolFileNativePDB() {}
443
444uint32_t SymbolFileNativePDB::CalculateAbilities() {
445 uint32_t abilities = 0;
446 if (!m_obj_file)
447 return 0;
448
449 if (!m_index) {
450 // Lazily load and match the PDB file, but only do this once.
451 std::unique_ptr<PDBFile> file_up =
452 loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
453
454 if (!file_up) {
455 auto module_sp = m_obj_file->GetModule();
456 if (!module_sp)
457 return 0;
458 // See if any symbol file is specified through `--symfile` option.
459 FileSpec symfile = module_sp->GetSymbolFileFileSpec();
460 if (!symfile)
461 return 0;
462 file_up = loadPDBFile(symfile.GetPath(), m_allocator);
463 }
464
465 if (!file_up)
466 return 0;
467
468 auto expected_index = PdbIndex::create(std::move(file_up));
469 if (!expected_index) {
470 llvm::consumeError(expected_index.takeError());
471 return 0;
472 }
473 m_index = std::move(*expected_index);
474 }
475 if (!m_index)
476 return 0;
477
478 // We don't especially have to be precise here. We only distinguish between
479 // stripped and not stripped.
480 abilities = kAllAbilities;
481
482 if (m_index->dbi().isStripped())
483 abilities &= ~(Blocks | LocalVariables);
484 return abilities;
485}
486
487void SymbolFileNativePDB::InitializeObject() {
488 m_obj_load_address = m_obj_file->GetFileOffset();
489 m_index->SetLoadAddress(m_obj_load_address);
490 m_index->ParseSectionContribs();
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000491
492 TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
493 m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
494 m_importer = llvm::make_unique<ClangASTImporter>();
Zachary Turner056e4ab2018-11-08 18:50:11 +0000495
496 PreprocessTpiStream();
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000497 lldbassert(m_clang);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000498}
499
Zachary Turner03a24052018-11-13 20:07:32 +0000500static llvm::Optional<CVTagRecord>
501GetNestedTagRecord(const NestedTypeRecord &Record, const CVTagRecord &parent,
502 TpiStream &tpi) {
503 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
504 // is also used to indicate the primary definition of a nested class. That is
505 // to say, if you have:
506 // struct A {
507 // struct B {};
508 // using C = B;
509 // };
510 // Then in the debug info, this will appear as:
511 // LF_STRUCTURE `A::B` [type index = N]
512 // LF_STRUCTURE `A`
513 // LF_NESTTYPE [name = `B`, index = N]
514 // LF_NESTTYPE [name = `C`, index = N]
515 // In order to accurately reconstruct the decl context hierarchy, we need to
516 // know which ones are actual definitions and which ones are just aliases.
517
518 // If it's a simple type, then this is something like `using foo = int`.
519 if (Record.Type.isSimple())
520 return llvm::None;
521
Zachary Turner2af34162018-11-13 20:07:57 +0000522 CVType cvt = tpi.getType(Record.Type);
523
524 if (!IsTagRecord(cvt))
525 return llvm::None;
526
Zachary Turner03a24052018-11-13 20:07:32 +0000527 // If it's an inner definition, then treat whatever name we have here as a
528 // single component of a mangled name. So we can inject it into the parent's
529 // mangled name to see if it matches.
Zachary Turner2af34162018-11-13 20:07:57 +0000530 CVTagRecord child = CVTagRecord::create(cvt);
Zachary Turner03a24052018-11-13 20:07:32 +0000531 std::string qname = parent.asTag().getUniqueName();
532 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
533 return llvm::None;
534
535 // qname[3] is the tag type identifier (struct, class, union, etc). Since the
536 // inner tag type is not necessarily the same as the outer tag type, re-write
537 // it to match the inner tag type.
538 qname[3] = child.asTag().getUniqueName()[3];
539 std::string piece = Record.Name;
540 piece.push_back('@');
541 qname.insert(4, std::move(piece));
542 if (qname != child.asTag().UniqueName)
543 return llvm::None;
544
545 return std::move(child);
546}
547
Zachary Turner056e4ab2018-11-08 18:50:11 +0000548void SymbolFileNativePDB::PreprocessTpiStream() {
549 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
550
551 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
552 CVType type = types.getType(*ti);
553 if (!IsTagRecord(type))
554 continue;
555
556 CVTagRecord tag = CVTagRecord::create(type);
557 // We're looking for LF_NESTTYPE records in the field list, so ignore
558 // forward references (no field list), and anything without a nested class
559 // (since there won't be any LF_NESTTYPE records).
560 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
561 continue;
562
563 struct ProcessTpiStream : public TypeVisitorCallbacks {
564 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
Zachary Turner03a24052018-11-13 20:07:32 +0000565 const CVTagRecord &parent_cvt,
Zachary Turner056e4ab2018-11-08 18:50:11 +0000566 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
Zachary Turner03a24052018-11-13 20:07:32 +0000567 : index(index), parents(parents), parent(parent),
568 parent_cvt(parent_cvt) {}
Zachary Turner056e4ab2018-11-08 18:50:11 +0000569
570 PdbIndex &index;
571 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
572 TypeIndex parent;
Zachary Turner03a24052018-11-13 20:07:32 +0000573 const CVTagRecord &parent_cvt;
Zachary Turner056e4ab2018-11-08 18:50:11 +0000574
575 llvm::Error visitKnownMember(CVMemberRecord &CVR,
576 NestedTypeRecord &Record) override {
Zachary Turner03a24052018-11-13 20:07:32 +0000577 llvm::Optional<CVTagRecord> tag =
578 GetNestedTagRecord(Record, parent_cvt, index.tpi());
579 if (!tag)
Zachary Turner056e4ab2018-11-08 18:50:11 +0000580 return llvm::ErrorSuccess();
Zachary Turner03a24052018-11-13 20:07:32 +0000581
582 parents[Record.Type] = parent;
583 if (!tag->asTag().isForwardRef())
584 return llvm::ErrorSuccess();
585
Zachary Turner056e4ab2018-11-08 18:50:11 +0000586 llvm::Expected<TypeIndex> full_decl =
587 index.tpi().findFullDeclForForwardRef(Record.Type);
588 if (!full_decl) {
589 llvm::consumeError(full_decl.takeError());
590 return llvm::ErrorSuccess();
591 }
592 parents[*full_decl] = parent;
593 return llvm::ErrorSuccess();
594 }
595 };
596
597 CVType field_list = m_index->tpi().getType(tag.asTag().FieldList);
Zachary Turner03a24052018-11-13 20:07:32 +0000598 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
Zachary Turner056e4ab2018-11-08 18:50:11 +0000599 llvm::Error error = visitMemberRecordStream(field_list.data(), process);
600 if (error)
601 llvm::consumeError(std::move(error));
602 }
603}
604
Zachary Turner307f5ae2018-10-12 19:47:13 +0000605uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
606 const DbiModuleList &modules = m_index->dbi().modules();
607 uint32_t count = modules.getModuleCount();
608 if (count == 0)
609 return count;
610
611 // The linker can inject an additional "dummy" compilation unit into the
612 // PDB. Ignore this special compile unit for our purposes, if it is there.
613 // It is always the last one.
614 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
615 if (last.getModuleName() == "* Linker *")
616 --count;
617 return count;
618}
619
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000620Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
621 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
622 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
623 clang::DeclContext *parent_decl_ctx = m_clang->GetTranslationUnitDecl();
624
625 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) {
626 // This is a function. It must be global. Creating the Function entry for
627 // it automatically creates a block for it.
628 CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
629 return GetOrCreateFunction(block_id, *comp_unit)->GetBlock(false);
630 }
631
632 lldbassert(sym.kind() == S_BLOCK32);
633
634 // This is a block. Its parent is either a function or another block. In
635 // either case, its parent can be viewed as a block (e.g. a function contains
636 // 1 big block. So just get the parent block and add this block to it.
637 BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
638 cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
639 lldbassert(block.Parent != 0);
640 PdbCompilandSymId parent_id(block_id.modi, block.Parent);
641 Block &parent_block = GetOrCreateBlock(parent_id);
642
643 lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
644 BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
645 parent_block.AddChild(child_block);
646 CompilerDeclContext cdc = GetDeclContextForUID(parent_block.GetID());
647 parent_decl_ctx =
648 static_cast<clang::DeclContext *>(cdc.GetOpaqueDeclContext());
649 clang::BlockDecl *block_decl =
650 m_clang->CreateBlockDeclaration(parent_decl_ctx);
651
652 m_blocks.insert({opaque_block_uid, child_block});
653 m_uid_to_decl.insert({opaque_block_uid, block_decl});
654 return *child_block;
655}
656
Zachary Turner6284aee2018-11-16 02:42:32 +0000657lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000658 CompileUnit &comp_unit) {
Zachary Turner6284aee2018-11-16 02:42:32 +0000659 const CompilandIndexItem *cci =
660 m_index->compilands().GetCompiland(func_id.modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000661 lldbassert(cci);
Zachary Turner6284aee2018-11-16 02:42:32 +0000662 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000663
664 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
665 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
666
667 auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
668 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
669 return nullptr;
670
671 AddressRange func_range(file_vm_addr, sol.length,
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000672 comp_unit.GetModule()->GetSectionList());
Zachary Turner307f5ae2018-10-12 19:47:13 +0000673 if (!func_range.GetBaseAddress().IsValid())
674 return nullptr;
675
Zachary Turnera42bbe32018-12-07 19:34:02 +0000676 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
677 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
678 TypeSP func_type = GetOrCreateType(proc.FunctionType);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000679
Zachary Turnera42bbe32018-12-07 19:34:02 +0000680 PdbTypeSymId sig_id(proc.FunctionType, false);
681 Mangled mangled(proc.Name);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000682 FunctionSP func_sp = std::make_shared<Function>(
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000683 &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
Zachary Turnera42bbe32018-12-07 19:34:02 +0000684 func_type.get(), func_range);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000685
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000686 comp_unit.AddFunction(func_sp);
687
688 user_id_t opaque_func_uid = toOpaqueUid(func_id);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000689
690 clang::StorageClass storage = clang::SC_None;
691 if (sym_record.kind() == S_LPROC32)
692 storage = clang::SC_Static;
693
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000694 // The function signature only tells us the number of types of arguments, but
695 // not the names. So we need to iterate the symbol stream looking for the
696 // corresponding symbol records to properly construct the AST.
Zachary Turnera42bbe32018-12-07 19:34:02 +0000697 CVType sig_cvt;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000698 ProcedureRecord sig_record;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000699
700 sig_cvt = m_index->tpi().getType(proc.FunctionType);
701 if (sig_cvt.kind() != LF_PROCEDURE)
702 return func_sp;
703 cantFail(
704 TypeDeserializer::deserializeAs<ProcedureRecord>(sig_cvt, sig_record));
705
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000706 CompilerDeclContext context = GetDeclContextContainingUID(opaque_func_uid);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000707
708 clang::DeclContext *decl_context =
709 static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
710 clang::FunctionDecl *function_decl = m_clang->CreateFunctionDeclaration(
711 decl_context, proc.Name.str().c_str(),
712 func_type->GetForwardCompilerType(), storage, false);
713
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000714 lldbassert(m_uid_to_decl.count(opaque_func_uid) == 0);
715 m_uid_to_decl[opaque_func_uid] = function_decl;
716
Zachary Turnera42bbe32018-12-07 19:34:02 +0000717 CVSymbolArray scope = limitSymbolArrayToScope(
718 cci->m_debug_stream.getSymbolArray(), func_id.offset);
719
720 uint32_t params_remaining = sig_record.getParameterCount();
721 auto begin = scope.begin();
722 auto end = scope.end();
723 std::vector<clang::ParmVarDecl *> params;
724 while (begin != end && params_remaining > 0) {
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000725 CVSymbol sym = *begin;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000726 switch (sym.kind()) {
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000727 case S_REGREL32:
728 case S_REGISTER:
729 case S_LOCAL:
Zachary Turnera42bbe32018-12-07 19:34:02 +0000730 break;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000731 case S_BLOCK32:
Zachary Turnera42bbe32018-12-07 19:34:02 +0000732 params_remaining = 0;
733 continue;
734 default:
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000735 ++begin;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000736 continue;
737 }
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000738 PdbCompilandSymId param_uid(func_id.modi, begin.offset());
739 VariableInfo var_info = GetVariableInformation(
740 *m_index, param_uid, GetObjectFile()->GetModule(), false);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000741
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000742 TypeSP type_sp = GetOrCreateType(var_info.type);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000743 clang::ParmVarDecl *param = m_clang->CreateParameterDeclaration(
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000744 function_decl, var_info.name.str().c_str(),
Zachary Turner6753d2d2018-12-12 17:17:53 +0000745 type_sp->GetForwardCompilerType(), clang::SC_None);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000746 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
747
748 m_uid_to_decl[toOpaqueUid(param_uid)] = param;
749 params.push_back(param);
750 --params_remaining;
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +0000751 ++begin;
Zachary Turnera42bbe32018-12-07 19:34:02 +0000752 }
Zachary Turnera42bbe32018-12-07 19:34:02 +0000753 if (!params.empty())
754 m_clang->SetFunctionParameters(function_decl, params.data(), params.size());
755
Zachary Turner307f5ae2018-10-12 19:47:13 +0000756 return func_sp;
757}
758
759CompUnitSP
760SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
761 lldb::LanguageType lang =
762 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
763 : lldb::eLanguageTypeUnknown;
764
765 LazyBool optimized = eLazyBoolNo;
766 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
767 optimized = eLazyBoolYes;
768
769 llvm::StringRef source_file_name =
770 m_index->compilands().GetMainSourceFile(cci);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000771 FileSpec fs(source_file_name);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000772
773 CompUnitSP cu_sp =
774 std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
Zachary Turner6284aee2018-11-16 02:42:32 +0000775 toOpaqueUid(cci.m_id), lang, optimized);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000776
Zachary Turner6284aee2018-11-16 02:42:32 +0000777 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
778 cci.m_id.modi, cu_sp);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000779 return cu_sp;
780}
781
Zachary Turner6284aee2018-11-16 02:42:32 +0000782lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000783 const ModifierRecord &mr) {
784 TpiStream &stream = m_index->tpi();
785
786 TypeSP t = GetOrCreateType(mr.ModifiedType);
787 CompilerType ct = t->GetForwardCompilerType();
788 if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
789 ct = ct.AddConstModifier();
790 if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
791 ct = ct.AddVolatileModifier();
792 std::string name;
793 if (mr.ModifiedType.isSimple())
794 name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
795 else
796 name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
797 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000798 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000799 ConstString(name), t->GetByteSize(), nullptr,
800 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
801 ct, Type::eResolveStateFull);
802}
803
804lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
Zachary Turner6284aee2018-11-16 02:42:32 +0000805 PdbTypeSymId type_id, const llvm::codeview::PointerRecord &pr) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000806 TypeSP pointee = GetOrCreateType(pr.ReferentType);
Zachary Turner544a66d82018-11-01 16:37:29 +0000807 if (!pointee)
808 return nullptr;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000809 CompilerType pointee_ct = pointee->GetForwardCompilerType();
810 lldbassert(pointee_ct);
811 Declaration decl;
812
813 if (pr.isPointerToMember()) {
814 MemberPointerInfo mpi = pr.getMemberInfo();
815 TypeSP class_type = GetOrCreateType(mpi.ContainingType);
816
817 CompilerType ct = ClangASTContext::CreateMemberPointerType(
818 class_type->GetLayoutCompilerType(), pointee_ct);
819
820 return std::make_shared<Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +0000821 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000822 pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
823 Type::eResolveStateFull);
824 }
825
826 CompilerType pointer_ct = pointee_ct;
827 if (pr.getMode() == PointerMode::LValueReference)
828 pointer_ct = pointer_ct.GetLValueReferenceType();
829 else if (pr.getMode() == PointerMode::RValueReference)
830 pointer_ct = pointer_ct.GetRValueReferenceType();
831 else
832 pointer_ct = pointer_ct.GetPointerType();
833
834 if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
835 pointer_ct = pointer_ct.AddConstModifier();
836
837 if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
838 pointer_ct = pointer_ct.AddVolatileModifier();
839
840 if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
841 pointer_ct = pointer_ct.AddRestrictModifier();
842
Zachary Turner6284aee2018-11-16 02:42:32 +0000843 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000844 ConstString(), pr.getSize(), nullptr,
845 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
846 pointer_ct, Type::eResolveStateFull);
847}
848
849lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
Zachary Turner9fbf9352018-11-16 03:16:27 +0000850 uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
Zachary Turner544a66d82018-11-01 16:37:29 +0000851 if (ti == TypeIndex::NullptrT()) {
Zachary Turner544a66d82018-11-01 16:37:29 +0000852 CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr);
853 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000854 return std::make_shared<Type>(
855 uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
856 Type::eEncodingIsUID, decl, ct, Type::eResolveStateFull);
Zachary Turner544a66d82018-11-01 16:37:29 +0000857 }
858
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000859 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000860 TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
861 CompilerType ct = direct_sp->GetFullCompilerType();
862 ct = ct.GetPointerType();
Zachary Turner71ebb722018-10-23 22:15:05 +0000863 uint32_t pointer_size = 0;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000864 switch (ti.getSimpleMode()) {
865 case SimpleTypeMode::FarPointer32:
866 case SimpleTypeMode::NearPointer32:
867 pointer_size = 4;
868 break;
869 case SimpleTypeMode::NearPointer64:
870 pointer_size = 8;
871 break;
872 default:
873 // 128-bit and 16-bit pointers unsupported.
874 return nullptr;
875 }
876 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000877 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(), ConstString(),
878 pointer_size, nullptr, LLDB_INVALID_UID,
879 Type::eEncodingIsUID, decl, ct,
880 Type::eResolveStateFull);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000881 }
882
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000883 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
884 return nullptr;
885
886 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
Zachary Turner544a66d82018-11-01 16:37:29 +0000887 if (bt == lldb::eBasicTypeInvalid)
888 return nullptr;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000889 CompilerType ct = m_clang->GetBasicType(bt);
890 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
891
892 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
893
894 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000895 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000896 ConstString(type_name), size, nullptr,
897 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
898 ct, Type::eResolveStateFull);
899}
900
Zachary Turner056e4ab2018-11-08 18:50:11 +0000901static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) {
902 OutputStream OS;
903 initializeOutputStream(nullptr, nullptr, OS, 1024);
904 n->output(OS, llvm::ms_demangle::OF_Default);
905 OS << '\0';
906 return {OS.getBuffer()};
907}
908
Zachary Turner03a24052018-11-13 20:07:32 +0000909static bool
910AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
911 for (llvm::ms_demangle::Node *n : scopes) {
912 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
913 if (idn->TemplateParams)
914 return true;
915 }
916 return false;
917}
918
Zachary Turner056e4ab2018-11-08 18:50:11 +0000919std::pair<clang::DeclContext *, std::string>
920SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record,
921 TypeIndex ti) {
Zachary Turnera42bbe32018-12-07 19:34:02 +0000922 // FIXME: Move this to GetDeclContextContainingUID.
923
Zachary Turner056e4ab2018-11-08 18:50:11 +0000924 llvm::ms_demangle::Demangler demangler;
925 StringView sv(record.UniqueName.begin(), record.UniqueName.size());
926 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
927 llvm::ms_demangle::IdentifierNode *idn =
928 ttn->QualifiedName->getUnqualifiedIdentifier();
929 std::string uname = RenderDemanglerNode(idn);
930
931 llvm::ms_demangle::NodeArrayNode *name_components =
932 ttn->QualifiedName->Components;
933 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
934 name_components->Count - 1);
935
936 clang::DeclContext *context = m_clang->GetTranslationUnitDecl();
937
938 // If this type doesn't have a parent type in the debug info, then the best we
939 // can do is to say that it's either a series of namespaces (if the scope is
940 // non-empty), or the translation unit (if the scope is empty).
941 auto parent_iter = m_parent_types.find(ti);
942 if (parent_iter == m_parent_types.end()) {
943 if (scopes.empty())
944 return {context, uname};
945
Zachary Turner03a24052018-11-13 20:07:32 +0000946 // If there is no parent in the debug info, but some of the scopes have
947 // template params, then this is a case of bad debug info. See, for
948 // example, llvm.org/pr39607. We don't want to create an ambiguity between
949 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
950 // global scope with the fully qualified name.
951 if (AnyScopesHaveTemplateParams(scopes))
952 return {context, record.Name};
953
Zachary Turner056e4ab2018-11-08 18:50:11 +0000954 for (llvm::ms_demangle::Node *scope : scopes) {
955 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
956 std::string str = RenderDemanglerNode(nii);
957 context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context);
958 }
959 return {context, uname};
960 }
961
962 // Otherwise, all we need to do is get the parent type of this type and
963 // recurse into our lazy type creation / AST reconstruction logic to get an
964 // LLDB TypeSP for the parent. This will cause the AST to automatically get
965 // the right DeclContext created for any parent.
966 TypeSP parent = GetOrCreateType(parent_iter->second);
967 if (!parent)
968 return {context, uname};
969 CompilerType parent_ct = parent->GetForwardCompilerType();
970 clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct);
971 context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl());
972 return {context, uname};
973}
974
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000975lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
Zachary Turner6284aee2018-11-16 02:42:32 +0000976 PdbTypeSymId type_id, const llvm::codeview::TagRecord &record, size_t size,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000977 clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
978
Zachary Turner056e4ab2018-11-08 18:50:11 +0000979 clang::DeclContext *decl_context = nullptr;
980 std::string uname;
Zachary Turner6284aee2018-11-16 02:42:32 +0000981 std::tie(decl_context, uname) = CreateDeclInfoForType(record, type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000982
983 lldb::AccessType access =
984 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
985
986 ClangASTMetadata metadata;
Zachary Turner6284aee2018-11-16 02:42:32 +0000987 metadata.SetUserID(toOpaqueUid(type_id));
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000988 metadata.SetIsDynamicCXXType(false);
989
990 CompilerType ct =
Zachary Turner056e4ab2018-11-08 18:50:11 +0000991 m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000992 lldb::eLanguageTypeC_plus_plus, &metadata);
Zachary Turner056e4ab2018-11-08 18:50:11 +0000993
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000994 lldbassert(ct.IsValid());
995
996 clang::CXXRecordDecl *record_decl =
997 m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
998 lldbassert(record_decl);
999
1000 clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
1001 *m_clang->getASTContext(), inheritance);
1002 record_decl->addAttr(attr);
1003
1004 ClangASTContext::StartTagDeclarationDefinition(ct);
1005
1006 // Even if it's possible, don't complete it at this point. Just mark it
1007 // forward resolved, and if/when LLDB needs the full definition, it can
1008 // ask us.
1009 ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
1010
1011 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
1012 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +00001013 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner056e4ab2018-11-08 18:50:11 +00001014 ConstString(uname), size, nullptr,
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001015 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
1016 ct, Type::eResolveStateForward);
1017}
1018
Zachary Turner6284aee2018-11-16 02:42:32 +00001019lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001020 const ClassRecord &cr) {
1021 clang::TagTypeKind ttk = TranslateUdtKind(cr);
1022
1023 clang::MSInheritanceAttr::Spelling inheritance =
1024 GetMSInheritance(m_index->tpi().typeCollection(), cr);
Zachary Turner6284aee2018-11-16 02:42:32 +00001025 return CreateClassStructUnion(type_id, cr, cr.getSize(), ttk, inheritance);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001026}
1027
Zachary Turner6284aee2018-11-16 02:42:32 +00001028lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001029 const UnionRecord &ur) {
1030 return CreateClassStructUnion(
Zachary Turner6284aee2018-11-16 02:42:32 +00001031 type_id, ur, ur.getSize(), clang::TTK_Union,
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001032 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
1033}
1034
Zachary Turner6284aee2018-11-16 02:42:32 +00001035lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001036 const EnumRecord &er) {
Zachary Turner2af34162018-11-13 20:07:57 +00001037 clang::DeclContext *decl_context = nullptr;
1038 std::string uname;
Zachary Turner6284aee2018-11-16 02:42:32 +00001039 std::tie(decl_context, uname) = CreateDeclInfoForType(er, type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001040
1041 Declaration decl;
1042 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
1043 CompilerType enum_ct = m_clang->CreateEnumerationType(
Zachary Turner2af34162018-11-13 20:07:57 +00001044 uname.c_str(), decl_context, decl, underlying_type->GetFullCompilerType(),
1045 er.isScoped());
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001046
1047 ClangASTContext::StartTagDeclarationDefinition(enum_ct);
Zachary Turner12abab52018-11-09 17:08:26 +00001048 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001049
1050 // We're just going to forward resolve this for now. We'll complete
1051 // it only if the user requests.
1052 return std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001053 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(uname),
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001054 underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
1055 lldb_private::Type::eEncodingIsUID, decl, enum_ct,
1056 lldb_private::Type::eResolveStateForward);
1057}
1058
Zachary Turner6284aee2018-11-16 02:42:32 +00001059TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
Zachary Turner511bff22018-10-30 18:57:08 +00001060 const ArrayRecord &ar) {
1061 TypeSP element_type = GetOrCreateType(ar.ElementType);
1062 uint64_t element_count = ar.Size / element_type->GetByteSize();
1063
1064 CompilerType element_ct = element_type->GetFullCompilerType();
1065
1066 CompilerType array_ct =
1067 m_clang->CreateArrayType(element_ct, element_count, false);
1068
1069 Declaration decl;
1070 TypeSP array_sp = std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001071 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(), ar.Size,
Zachary Turner511bff22018-10-30 18:57:08 +00001072 nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
1073 array_ct, lldb_private::Type::eResolveStateFull);
1074 array_sp->SetEncodingType(element_type.get());
1075 return array_sp;
1076}
1077
Zachary Turner6284aee2018-11-16 02:42:32 +00001078TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
Zachary Turner544a66d82018-11-01 16:37:29 +00001079 const ProcedureRecord &pr) {
1080 TpiStream &stream = m_index->tpi();
1081 CVType args_cvt = stream.getType(pr.ArgumentList);
1082 ArgListRecord args;
1083 llvm::cantFail(
1084 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1085
1086 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
1087 bool is_variadic = IsCVarArgsFunction(arg_indices);
1088 if (is_variadic)
1089 arg_indices = arg_indices.drop_back();
1090
1091 std::vector<CompilerType> arg_list;
1092 arg_list.reserve(arg_list.size());
1093
1094 for (TypeIndex arg_index : arg_indices) {
1095 TypeSP arg_sp = GetOrCreateType(arg_index);
1096 if (!arg_sp)
1097 return nullptr;
1098 arg_list.push_back(arg_sp->GetFullCompilerType());
1099 }
1100
1101 TypeSP return_type_sp = GetOrCreateType(pr.ReturnType);
1102 if (!return_type_sp)
1103 return nullptr;
1104
1105 llvm::Optional<clang::CallingConv> cc =
1106 TranslateCallingConvention(pr.CallConv);
1107 if (!cc)
1108 return nullptr;
1109
1110 CompilerType return_ct = return_type_sp->GetFullCompilerType();
1111 CompilerType func_sig_ast_type = m_clang->CreateFunctionType(
1112 return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc);
1113
1114 Declaration decl;
1115 return std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001116 toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
Zachary Turner544a66d82018-11-01 16:37:29 +00001117 lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type,
1118 lldb_private::Type::eResolveStateFull);
1119}
1120
Zachary Turner6284aee2018-11-16 02:42:32 +00001121TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id) {
1122 if (type_id.index.isSimple())
1123 return CreateSimpleType(type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001124
Zachary Turner6284aee2018-11-16 02:42:32 +00001125 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
1126 CVType cvt = stream.getType(type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001127
1128 if (cvt.kind() == LF_MODIFIER) {
1129 ModifierRecord modifier;
1130 llvm::cantFail(
1131 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
Zachary Turner6284aee2018-11-16 02:42:32 +00001132 return CreateModifierType(type_id, modifier);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001133 }
1134
1135 if (cvt.kind() == LF_POINTER) {
1136 PointerRecord pointer;
1137 llvm::cantFail(
1138 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
Zachary Turner6284aee2018-11-16 02:42:32 +00001139 return CreatePointerType(type_id, pointer);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001140 }
1141
1142 if (IsClassRecord(cvt.kind())) {
1143 ClassRecord cr;
1144 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
Zachary Turner6284aee2018-11-16 02:42:32 +00001145 return CreateTagType(type_id, cr);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001146 }
1147
1148 if (cvt.kind() == LF_ENUM) {
1149 EnumRecord er;
1150 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
Zachary Turner6284aee2018-11-16 02:42:32 +00001151 return CreateTagType(type_id, er);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001152 }
1153
1154 if (cvt.kind() == LF_UNION) {
1155 UnionRecord ur;
1156 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
Zachary Turner6284aee2018-11-16 02:42:32 +00001157 return CreateTagType(type_id, ur);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001158 }
1159
Zachary Turner511bff22018-10-30 18:57:08 +00001160 if (cvt.kind() == LF_ARRAY) {
1161 ArrayRecord ar;
1162 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
Zachary Turner6284aee2018-11-16 02:42:32 +00001163 return CreateArrayType(type_id, ar);
Zachary Turner511bff22018-10-30 18:57:08 +00001164 }
1165
Zachary Turner544a66d82018-11-01 16:37:29 +00001166 if (cvt.kind() == LF_PROCEDURE) {
1167 ProcedureRecord pr;
1168 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
Zachary Turner6284aee2018-11-16 02:42:32 +00001169 return CreateProcedureType(type_id, pr);
Zachary Turner544a66d82018-11-01 16:37:29 +00001170 }
1171
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001172 return nullptr;
1173}
1174
Zachary Turner6284aee2018-11-16 02:42:32 +00001175TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001176 // If they search for a UDT which is a forward ref, try and resolve the full
1177 // decl and just map the forward ref uid to the full decl record.
Zachary Turner6284aee2018-11-16 02:42:32 +00001178 llvm::Optional<PdbTypeSymId> full_decl_uid;
1179 if (IsForwardRefUdt(type_id, m_index->tpi())) {
1180 auto expected_full_ti =
1181 m_index->tpi().findFullDeclForForwardRef(type_id.index);
1182 if (!expected_full_ti)
1183 llvm::consumeError(expected_full_ti.takeError());
1184 else if (*expected_full_ti != type_id.index) {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001185 full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001186
Zachary Turner6284aee2018-11-16 02:42:32 +00001187 // It's possible that a lookup would occur for the full decl causing it
1188 // to be cached, then a second lookup would occur for the forward decl.
1189 // We don't want to create a second full decl, so make sure the full
1190 // decl hasn't already been cached.
1191 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
1192 if (full_iter != m_types.end()) {
1193 TypeSP result = full_iter->second;
1194 // Map the forward decl to the TypeSP for the full decl so we can take
1195 // the fast path next time.
1196 m_types[toOpaqueUid(type_id)] = result;
1197 return result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001198 }
1199 }
1200 }
1201
Zachary Turner6284aee2018-11-16 02:42:32 +00001202 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
1203 TypeSP result = CreateType(best_decl_id);
Zachary Turner544a66d82018-11-01 16:37:29 +00001204 if (!result)
1205 return nullptr;
Zachary Turner6284aee2018-11-16 02:42:32 +00001206
1207 uint64_t best_uid = toOpaqueUid(best_decl_id);
1208 m_types[best_uid] = result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001209 // If we had both a forward decl and a full decl, make both point to the new
1210 // type.
1211 if (full_decl_uid)
Zachary Turner6284aee2018-11-16 02:42:32 +00001212 m_types[toOpaqueUid(type_id)] = result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001213
Zachary Turner6284aee2018-11-16 02:42:32 +00001214 if (IsTagRecord(best_decl_id, m_index->tpi())) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001215 clang::TagDecl *record_decl =
1216 m_clang->GetAsTagDecl(result->GetForwardCompilerType());
1217 lldbassert(record_decl);
1218
Zachary Turner6284aee2018-11-16 02:42:32 +00001219 m_uid_to_decl[best_uid] = record_decl;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001220 m_decl_to_status[record_decl] =
Zachary Turner6284aee2018-11-16 02:42:32 +00001221 DeclStatus(best_uid, Type::eResolveStateForward);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001222 }
1223 return result;
1224}
1225
Zachary Turner6284aee2018-11-16 02:42:32 +00001226TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001227 // We can't use try_emplace / overwrite here because the process of creating
1228 // a type could create nested types, which could invalidate iterators. So
1229 // we have to do a 2-phase lookup / insert.
Zachary Turner6284aee2018-11-16 02:42:32 +00001230 auto iter = m_types.find(toOpaqueUid(type_id));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001231 if (iter != m_types.end())
1232 return iter->second;
1233
Zachary Turner6284aee2018-11-16 02:42:32 +00001234 return CreateAndCacheType(type_id);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001235}
1236
Zachary Turner6284aee2018-11-16 02:42:32 +00001237VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
1238 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
Zachary Turner2af34162018-11-13 20:07:57 +00001239 if (sym.kind() == S_CONSTANT)
Zachary Turner6284aee2018-11-16 02:42:32 +00001240 return CreateConstantSymbol(var_id, sym);
Zachary Turner2af34162018-11-13 20:07:57 +00001241
Zachary Turner9f727952018-10-26 09:06:38 +00001242 lldb::ValueType scope = eValueTypeInvalid;
1243 TypeIndex ti;
1244 llvm::StringRef name;
1245 lldb::addr_t addr = 0;
1246 uint16_t section = 0;
1247 uint32_t offset = 0;
1248 bool is_external = false;
1249 switch (sym.kind()) {
1250 case S_GDATA32:
1251 is_external = true;
1252 LLVM_FALLTHROUGH;
1253 case S_LDATA32: {
1254 DataSym ds(sym.kind());
1255 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
1256 ti = ds.Type;
1257 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
1258 : eValueTypeVariableStatic;
1259 name = ds.Name;
1260 section = ds.Segment;
1261 offset = ds.DataOffset;
1262 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
1263 break;
1264 }
1265 case S_GTHREAD32:
1266 is_external = true;
1267 LLVM_FALLTHROUGH;
1268 case S_LTHREAD32: {
1269 ThreadLocalDataSym tlds(sym.kind());
1270 llvm::cantFail(
1271 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
1272 ti = tlds.Type;
1273 name = tlds.Name;
1274 section = tlds.Segment;
1275 offset = tlds.DataOffset;
1276 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
1277 scope = eValueTypeVariableThreadLocal;
1278 break;
1279 }
1280 default:
1281 llvm_unreachable("unreachable!");
1282 }
1283
1284 CompUnitSP comp_unit;
1285 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
1286 if (modi) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001287 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
Zachary Turner9f727952018-10-26 09:06:38 +00001288 comp_unit = GetOrCreateCompileUnit(cci);
1289 }
1290
1291 Declaration decl;
Zachary Turner9fbf9352018-11-16 03:16:27 +00001292 PdbTypeSymId tid(ti, false);
Zachary Turner9f727952018-10-26 09:06:38 +00001293 SymbolFileTypeSP type_sp =
Zachary Turner6284aee2018-11-16 02:42:32 +00001294 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
Zachary Turner9f727952018-10-26 09:06:38 +00001295 Variable::RangeList ranges;
1296
1297 DWARFExpression location = MakeGlobalLocationExpression(
1298 section, offset, GetObjectFile()->GetModule());
1299
1300 std::string global_name("::");
1301 global_name += name;
1302 VariableSP var_sp = std::make_shared<Variable>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001303 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
Zachary Turner9f727952018-10-26 09:06:38 +00001304 scope, comp_unit.get(), ranges, &decl, location, is_external, false,
1305 false);
1306 var_sp->SetLocationIsConstantValueData(false);
1307
1308 return var_sp;
1309}
1310
Zachary Turner2af34162018-11-13 20:07:57 +00001311lldb::VariableSP
Zachary Turner6284aee2018-11-16 02:42:32 +00001312SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
Zachary Turner2af34162018-11-13 20:07:57 +00001313 const CVSymbol &cvs) {
1314 TpiStream &tpi = m_index->tpi();
1315 ConstantSym constant(cvs.kind());
1316
1317 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
1318 std::string global_name("::");
1319 global_name += constant.Name;
Zachary Turner9fbf9352018-11-16 03:16:27 +00001320 PdbTypeSymId tid(constant.Type, false);
Zachary Turner2af34162018-11-13 20:07:57 +00001321 SymbolFileTypeSP type_sp =
Zachary Turner6284aee2018-11-16 02:42:32 +00001322 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
Zachary Turner2af34162018-11-13 20:07:57 +00001323
1324 Declaration decl;
1325 Variable::RangeList ranges;
1326 ModuleSP module = GetObjectFile()->GetModule();
Zachary Turnera93458b2018-12-06 17:49:15 +00001327 DWARFExpression location = MakeConstantLocationExpression(
1328 constant.Type, tpi, constant.Value, module);
Zachary Turner2af34162018-11-13 20:07:57 +00001329
1330 VariableSP var_sp = std::make_shared<Variable>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001331 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
Zachary Turner2af34162018-11-13 20:07:57 +00001332 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
1333 false, false, false);
1334 var_sp->SetLocationIsConstantValueData(true);
1335 return var_sp;
1336}
1337
Zachary Turner6284aee2018-11-16 02:42:32 +00001338VariableSP
1339SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
1340 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
Zachary Turner9f727952018-10-26 09:06:38 +00001341 if (emplace_result.second)
Zachary Turner6284aee2018-11-16 02:42:32 +00001342 emplace_result.first->second = CreateGlobalVariable(var_id);
Zachary Turner9f727952018-10-26 09:06:38 +00001343
1344 return emplace_result.first->second;
1345}
1346
Zachary Turner6284aee2018-11-16 02:42:32 +00001347lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001348 return GetOrCreateType(PdbTypeSymId(ti, false));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001349}
1350
Zachary Turner6284aee2018-11-16 02:42:32 +00001351FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001352 CompileUnit &comp_unit) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001353 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001354 if (emplace_result.second)
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001355 emplace_result.first->second = CreateFunction(func_id, comp_unit);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001356
1357 lldbassert(emplace_result.first->second);
1358 return emplace_result.first->second;
1359}
1360
1361CompUnitSP
1362SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001363
Zachary Turner307f5ae2018-10-12 19:47:13 +00001364 auto emplace_result =
Zachary Turner6284aee2018-11-16 02:42:32 +00001365 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001366 if (emplace_result.second)
1367 emplace_result.first->second = CreateCompileUnit(cci);
1368
1369 lldbassert(emplace_result.first->second);
1370 return emplace_result.first->second;
1371}
1372
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001373Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
1374 auto iter = m_blocks.find(toOpaqueUid(block_id));
1375 if (iter != m_blocks.end())
1376 return *iter->second;
1377
1378 return CreateBlock(block_id);
1379}
1380
Zachary Turner307f5ae2018-10-12 19:47:13 +00001381lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1382 if (index >= GetNumCompileUnits())
1383 return CompUnitSP();
1384 lldbassert(index < UINT16_MAX);
1385 if (index >= UINT16_MAX)
1386 return nullptr;
1387
1388 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1389
1390 return GetOrCreateCompileUnit(item);
1391}
1392
Zachary Turnerb96181c2018-10-22 16:19:07 +00001393lldb::LanguageType
1394SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001395 // What fields should I expect to be filled out on the SymbolContext? Is it
1396 // safe to assume that `sc.comp_unit` is valid?
1397 if (!sc.comp_unit)
1398 return lldb::eLanguageTypeUnknown;
Zachary Turner6284aee2018-11-16 02:42:32 +00001399 PdbSymUid uid(sc.comp_unit->GetID());
1400 lldbassert(uid.kind() == PdbSymUidKind::Compiland);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001401
Zachary Turner6284aee2018-11-16 02:42:32 +00001402 CompilandIndexItem *item =
1403 m_index->compilands().GetCompiland(uid.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001404 lldbassert(item);
1405 if (!item->m_compile_opts)
1406 return lldb::eLanguageTypeUnknown;
1407
1408 return TranslateLanguage(item->m_compile_opts->getLanguage());
1409}
1410
Zachary Turnerb96181c2018-10-22 16:19:07 +00001411size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001412 lldbassert(sc.comp_unit);
1413 return false;
1414}
1415
1416static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1417 // If any of these flags are set, we need to resolve the compile unit.
1418 uint32_t flags = eSymbolContextCompUnit;
1419 flags |= eSymbolContextVariable;
1420 flags |= eSymbolContextFunction;
1421 flags |= eSymbolContextBlock;
1422 flags |= eSymbolContextLineEntry;
1423 return (resolve_scope & flags) != 0;
1424}
1425
Zachary Turner991e4452018-10-25 20:45:19 +00001426uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1427 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001428 uint32_t resolved_flags = 0;
1429 lldb::addr_t file_addr = addr.GetFileAddress();
1430
1431 if (NeedsResolvedCompileUnit(resolve_scope)) {
1432 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1433 if (!modi)
1434 return 0;
Zachary Turner6284aee2018-11-16 02:42:32 +00001435 CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001436 if (!cci)
1437 return 0;
1438
1439 sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
1440 resolved_flags |= eSymbolContextCompUnit;
1441 }
1442
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001443 if (resolve_scope & eSymbolContextFunction ||
1444 resolve_scope & eSymbolContextBlock) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001445 lldbassert(sc.comp_unit);
1446 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001447 // Search the matches in reverse. This way if there are multiple matches
1448 // (for example we are 3 levels deep in a nested scope) it will find the
1449 // innermost one first.
1450 for (const auto &match : llvm::reverse(matches)) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001451 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
Zachary Turner307f5ae2018-10-12 19:47:13 +00001452 continue;
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001453
Zachary Turner6284aee2018-11-16 02:42:32 +00001454 PdbCompilandSymId csid = match.uid.asCompilandSym();
1455 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001456 PDB_SymType type = CVSymToPDBSym(cvs.kind());
1457 if (type != PDB_SymType::Function && type != PDB_SymType::Block)
Zachary Turner6284aee2018-11-16 02:42:32 +00001458 continue;
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001459 if (type == PDB_SymType::Function) {
1460 sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1461 sc.block = sc.GetFunctionBlock();
1462 }
1463
1464 if (type == PDB_SymType::Block) {
1465 sc.block = &GetOrCreateBlock(csid);
1466 sc.function = sc.block->CalculateSymbolContextFunction();
1467 }
Zachary Turner307f5ae2018-10-12 19:47:13 +00001468 resolved_flags |= eSymbolContextFunction;
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001469 resolved_flags |= eSymbolContextBlock;
1470 break;
1471 }
Zachary Turner307f5ae2018-10-12 19:47:13 +00001472 }
1473
1474 if (resolve_scope & eSymbolContextLineEntry) {
1475 lldbassert(sc.comp_unit);
1476 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1477 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1478 resolved_flags |= eSymbolContextLineEntry;
1479 }
1480 }
1481
1482 return resolved_flags;
1483}
1484
1485static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1486 const CompilandIndexItem &cci,
1487 lldb::addr_t base_addr,
1488 uint32_t file_number,
1489 const LineFragmentHeader &block,
1490 const LineNumberEntry &cur) {
1491 LineInfo cur_info(cur.Flags);
1492
1493 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1494 return;
1495
1496 uint64_t addr = base_addr + cur.Offset;
1497
1498 bool is_statement = cur_info.isStatement();
1499 bool is_prologue = IsFunctionPrologue(cci, addr);
1500 bool is_epilogue = IsFunctionEpilogue(cci, addr);
1501
1502 uint32_t lno = cur_info.getStartLine();
1503
1504 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1505 is_statement, false, is_prologue, is_epilogue,
1506 false);
1507}
1508
1509static void TerminateLineSequence(LineTable &table,
1510 const LineFragmentHeader &block,
1511 lldb::addr_t base_addr, uint32_t file_number,
1512 uint32_t last_line,
1513 std::unique_ptr<LineSequence> seq) {
1514 // The end is always a terminal entry, so insert it regardless.
1515 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1516 last_line, 0, file_number, false, false,
1517 false, false, true);
1518 table.InsertSequence(seq.release());
1519}
1520
Zachary Turnerb96181c2018-10-22 16:19:07 +00001521bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001522 // Unfortunately LLDB is set up to parse the entire compile unit line table
1523 // all at once, even if all it really needs is line info for a specific
1524 // function. In the future it would be nice if it could set the sc.m_function
1525 // member, and we could only get the line info for the function in question.
1526 lldbassert(sc.comp_unit);
Zachary Turner6284aee2018-11-16 02:42:32 +00001527 PdbSymUid cu_id(sc.comp_unit->GetID());
1528 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1529 CompilandIndexItem *cci =
1530 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001531 lldbassert(cci);
1532 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1533
1534 // This is basically a copy of the .debug$S subsections from all original COFF
1535 // object files merged together with address relocations applied. We are
1536 // looking for all DEBUG_S_LINES subsections.
1537 for (const DebugSubsectionRecord &dssr :
1538 cci->m_debug_stream.getSubsectionsArray()) {
1539 if (dssr.kind() != DebugSubsectionKind::Lines)
1540 continue;
1541
1542 DebugLinesSubsectionRef lines;
1543 llvm::BinaryStreamReader reader(dssr.getRecordData());
1544 if (auto EC = lines.initialize(reader)) {
1545 llvm::consumeError(std::move(EC));
1546 return false;
1547 }
1548
1549 const LineFragmentHeader *lfh = lines.header();
1550 uint64_t virtual_addr =
1551 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1552
1553 const auto &checksums = cci->m_strings.checksums().getArray();
1554 const auto &strings = cci->m_strings.strings();
1555 for (const LineColumnEntry &group : lines) {
1556 // Indices in this structure are actually offsets of records in the
1557 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1558 // into the global PDB string table.
1559 auto iter = checksums.at(group.NameIndex);
1560 if (iter == checksums.end())
1561 continue;
1562
1563 llvm::Expected<llvm::StringRef> efn =
1564 strings.getString(iter->FileNameOffset);
1565 if (!efn) {
1566 llvm::consumeError(efn.takeError());
1567 continue;
1568 }
1569
1570 // LLDB wants the index of the file in the list of support files.
1571 auto fn_iter = llvm::find(cci->m_file_list, *efn);
1572 lldbassert(fn_iter != cci->m_file_list.end());
1573 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1574
1575 std::unique_ptr<LineSequence> sequence(
1576 line_table->CreateLineSequenceContainer());
1577 lldbassert(!group.LineNumbers.empty());
1578
1579 for (const LineNumberEntry &entry : group.LineNumbers) {
1580 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1581 file_index, *lfh, entry);
1582 }
1583 LineInfo last_line(group.LineNumbers.back().Flags);
1584 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1585 last_line.getEndLine(), std::move(sequence));
1586 }
1587 }
1588
1589 if (line_table->GetSize() == 0)
1590 return false;
1591
1592 sc.comp_unit->SetLineTable(line_table.release());
1593 return true;
1594}
1595
Zachary Turnerb96181c2018-10-22 16:19:07 +00001596bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001597 // PDB doesn't contain information about macros
1598 return false;
1599}
1600
1601bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001602 const SymbolContext &sc, FileSpecList &support_files) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001603 lldbassert(sc.comp_unit);
1604
Zachary Turner6284aee2018-11-16 02:42:32 +00001605 PdbSymUid cu_id(sc.comp_unit->GetID());
1606 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1607 CompilandIndexItem *cci =
1608 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001609 lldbassert(cci);
1610
1611 for (llvm::StringRef f : cci->m_file_list) {
1612 FileSpec::Style style =
1613 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001614 FileSpec spec(f, style);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001615 support_files.Append(spec);
1616 }
1617
1618 return true;
1619}
1620
1621bool SymbolFileNativePDB::ParseImportedModules(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001622 const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001623 // PDB does not yet support module debug info
1624 return false;
1625}
1626
Zachary Turnerb96181c2018-10-22 16:19:07 +00001627size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001628 lldbassert(sc.comp_unit && sc.function);
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001629 GetOrCreateBlock(PdbSymUid(sc.function->GetID()).asCompilandSym());
1630 // FIXME: Parse child blocks
1631 return 1;
Zachary Turner307f5ae2018-10-12 19:47:13 +00001632}
1633
Zachary Turner49110232018-11-05 17:40:28 +00001634void SymbolFileNativePDB::DumpClangAST(Stream &s) {
1635 if (!m_clang)
1636 return;
1637 m_clang->Dump(s);
1638}
1639
Zachary Turner9f727952018-10-26 09:06:38 +00001640uint32_t SymbolFileNativePDB::FindGlobalVariables(
1641 const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1642 uint32_t max_matches, VariableList &variables) {
1643 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1644
1645 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1646 name.GetStringRef(), m_index->symrecords());
1647 for (const SymbolAndOffset &result : results) {
1648 VariableSP var;
1649 switch (result.second.kind()) {
1650 case SymbolKind::S_GDATA32:
1651 case SymbolKind::S_LDATA32:
1652 case SymbolKind::S_GTHREAD32:
Zachary Turner2af34162018-11-13 20:07:57 +00001653 case SymbolKind::S_LTHREAD32:
1654 case SymbolKind::S_CONSTANT: {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001655 PdbGlobalSymId global(result.first, false);
Zachary Turner6284aee2018-11-16 02:42:32 +00001656 var = GetOrCreateGlobalVariable(global);
Zachary Turner9f727952018-10-26 09:06:38 +00001657 variables.AddVariable(var);
1658 break;
1659 }
1660 default:
1661 continue;
1662 }
1663 }
1664 return variables.GetSize();
1665}
1666
Zachary Turner307f5ae2018-10-12 19:47:13 +00001667uint32_t SymbolFileNativePDB::FindFunctions(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001668 const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
Zachary Turner117b1fa2018-10-25 20:45:40 +00001669 FunctionNameType name_type_mask, bool include_inlines, bool append,
Zachary Turnerb96181c2018-10-22 16:19:07 +00001670 SymbolContextList &sc_list) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001671 // For now we only support lookup by method name.
1672 if (!(name_type_mask & eFunctionNameTypeMethod))
1673 return 0;
1674
1675 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1676
1677 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1678 name.GetStringRef(), m_index->symrecords());
1679 for (const SymbolAndOffset &match : matches) {
1680 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1681 continue;
1682 ProcRefSym proc(match.second.kind());
1683 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1684
1685 if (!IsValidRecord(proc))
1686 continue;
1687
Zachary Turner6284aee2018-11-16 02:42:32 +00001688 CompilandIndexItem &cci =
1689 m_index->compilands().GetOrCreateCompiland(proc.modi());
Zachary Turnerb96181c2018-10-22 16:19:07 +00001690 SymbolContext sc;
Zachary Turner307f5ae2018-10-12 19:47:13 +00001691
1692 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
Zachary Turner9fbf9352018-11-16 03:16:27 +00001693 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001694 sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
Zachary Turner307f5ae2018-10-12 19:47:13 +00001695
1696 sc_list.Append(sc);
1697 }
1698
1699 return sc_list.GetSize();
1700}
1701
Zachary Turnerb96181c2018-10-22 16:19:07 +00001702uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1703 bool include_inlines, bool append,
1704 SymbolContextList &sc_list) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001705 return 0;
1706}
1707
Zachary Turnerb96181c2018-10-22 16:19:07 +00001708uint32_t SymbolFileNativePDB::FindTypes(
1709 const SymbolContext &sc, const ConstString &name,
1710 const CompilerDeclContext *parent_decl_ctx, bool append,
1711 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1712 TypeMap &types) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001713 if (!append)
1714 types.Clear();
1715 if (!name)
1716 return 0;
1717
1718 searched_symbol_files.clear();
1719 searched_symbol_files.insert(this);
1720
1721 // There is an assumption 'name' is not a regex
1722 size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1723
1724 return match_count;
Zachary Turnerb96181c2018-10-22 16:19:07 +00001725}
1726
1727size_t
1728SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1729 bool append, TypeMap &types) {
1730 return 0;
1731}
1732
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001733size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1734 uint32_t max_matches,
1735 TypeMap &types) {
1736
1737 size_t match_count = 0;
1738 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1739 if (max_matches > 0 && max_matches < matches.size())
1740 matches.resize(max_matches);
1741
1742 for (TypeIndex ti : matches) {
1743 TypeSP type = GetOrCreateType(ti);
1744 if (!type)
1745 continue;
1746
1747 types.Insert(type);
1748 ++match_count;
1749 }
1750 return match_count;
1751}
1752
Zachary Turnerb96181c2018-10-22 16:19:07 +00001753size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1754
Zachary Turnerd3d2b9b2018-12-13 18:17:51 +00001755size_t
1756SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1757 VariableList &variables) {
1758 PdbSymUid sym_uid(comp_unit.GetID());
1759 lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1760 return 0;
1761}
1762
1763VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1764 PdbCompilandSymId var_id,
1765 bool is_param) {
1766 ModuleSP module = GetObjectFile()->GetModule();
1767 VariableInfo var_info =
1768 GetVariableInformation(*m_index, var_id, module, true);
1769
1770 CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1771 CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1772 TypeSP type_sp = GetOrCreateType(var_info.type);
1773 std::string name = var_info.name.str();
1774 Declaration decl;
1775 SymbolFileTypeSP sftype =
1776 std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1777
1778 ValueType var_scope =
1779 is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1780 VariableSP var_sp = std::make_shared<Variable>(
1781 toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1782 comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, false,
1783 false, false);
1784
1785 CompilerDeclContext cdc = GetDeclContextForUID(toOpaqueUid(scope_id));
1786 clang::DeclContext *decl_ctx =
1787 static_cast<clang::DeclContext *>(cdc.GetOpaqueDeclContext());
1788
1789 // Parameter info should have already been added to the AST.
1790 if (!is_param) {
1791 clang::QualType qt =
1792 ClangUtil::GetCanonicalQualType(type_sp->GetForwardCompilerType());
1793
1794 clang::VarDecl *var_decl =
1795 m_clang->CreateVariableDeclaration(decl_ctx, name.c_str(), qt);
1796 lldbassert(m_uid_to_decl.count(toOpaqueUid(var_id)) == 0);
1797 m_uid_to_decl[toOpaqueUid(var_id)] = var_decl;
1798 }
1799
1800 m_local_variables[toOpaqueUid(var_id)] = var_sp;
1801 return var_sp;
1802}
1803
1804VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1805 PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1806 auto iter = m_local_variables.find(toOpaqueUid(var_id));
1807 if (iter != m_local_variables.end())
1808 return iter->second;
1809
1810 return CreateLocalVariable(scope_id, var_id, is_param);
1811}
1812
1813size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1814 Block &block = GetOrCreateBlock(block_id);
1815
1816 size_t count = 0;
1817
1818 CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1819 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1820 uint32_t params_remaining = 0;
1821 switch (sym.kind()) {
1822 case S_GPROC32:
1823 case S_LPROC32: {
1824 ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1825 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1826 CVType signature = m_index->tpi().getType(proc.FunctionType);
1827 ProcedureRecord sig;
1828 cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1829 params_remaining = sig.getParameterCount();
1830 break;
1831 }
1832 case S_BLOCK32:
1833 break;
1834 default:
1835 lldbassert(false && "Symbol is not a block!");
1836 return 0;
1837 }
1838
1839 VariableListSP variables = block.GetBlockVariableList(false);
1840 if (!variables) {
1841 variables = std::make_shared<VariableList>();
1842 block.SetVariableList(variables);
1843 }
1844
1845 CVSymbolArray syms = limitSymbolArrayToScope(
1846 cii->m_debug_stream.getSymbolArray(), block_id.offset);
1847
1848 // Skip the first record since it's a PROC32 or BLOCK32, and there's
1849 // no point examining it since we know it's not a local variable.
1850 syms.drop_front();
1851 auto iter = syms.begin();
1852 auto end = syms.end();
1853
1854 while (iter != end) {
1855 uint32_t record_offset = iter.offset();
1856 CVSymbol variable_cvs = *iter;
1857 PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1858 ++iter;
1859
1860 // If this is a block, recurse into its children and then skip it.
1861 if (variable_cvs.kind() == S_BLOCK32) {
1862 uint32_t block_end = getScopeEndOffset(variable_cvs);
1863 count += ParseVariablesForBlock(child_sym_id);
1864 iter = syms.at(block_end);
1865 continue;
1866 }
1867
1868 bool is_param = params_remaining > 0;
1869 VariableSP variable;
1870 switch (variable_cvs.kind()) {
1871 case S_REGREL32:
1872 case S_REGISTER:
1873 case S_LOCAL:
1874 variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1875 if (is_param)
1876 --params_remaining;
1877 variables->AddVariableIfUnique(variable);
1878 break;
1879 default:
1880 break;
1881 }
1882 }
1883
1884 // Pass false for set_children, since we call this recursively so that the
1885 // children will call this for themselves.
1886 block.SetDidParseVariables(true, false);
1887
1888 return count;
1889}
1890
1891size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1892 lldbassert(sc.function || sc.comp_unit);
1893
1894 VariableListSP variables;
1895 PdbSymUid sym_uid;
1896 if (sc.block) {
1897 PdbSymUid block_id(sc.block->GetID());
1898
1899 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1900 return count;
1901 }
1902
1903 if (sc.function) {
1904 PdbSymUid block_id(sc.function->GetID());
1905
1906 size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1907 return count;
1908 }
1909
1910 if (sc.comp_unit) {
1911 variables = sc.comp_unit->GetVariableList(false);
1912 if (!variables) {
1913 variables = std::make_shared<VariableList>();
1914 sc.comp_unit->SetVariableList(variables);
1915 }
1916 return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1917 }
1918
1919 llvm_unreachable("Unreachable!");
1920}
1921
1922CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1923 auto iter = m_uid_to_decl.find(uid);
1924 if (iter == m_uid_to_decl.end())
1925 return CompilerDecl();
1926
1927 return {m_clang, iter->second};
1928}
1929
1930CompilerDeclContext
1931SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1932 CompilerDecl compiler_decl = GetDeclForUID(uid);
1933 clang::Decl *decl = static_cast<clang::Decl *>(compiler_decl.GetOpaqueDecl());
1934 return {m_clang, clang::Decl::castToDeclContext(decl)};
1935}
1936
Zachary Turnera42bbe32018-12-07 19:34:02 +00001937CompilerDeclContext
1938SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1939 // FIXME: This should look up the uid, decide if it's a symbol or a type, and
1940 // depending which it is, find the appropriate DeclContext. Possibilities:
1941 // For classes and typedefs:
1942 // * Function
1943 // * Namespace
1944 // * Global
1945 // * Block
1946 // * Class
1947 // For field list members:
1948 // * Class
1949 // For variables:
1950 // * Function
1951 // * Namespace
1952 // * Global
1953 // * Block
1954 // For functions:
1955 // * Namespace
1956 // * Global
1957 // * Class
1958 //
1959 // It is an error to call this function with a uid for any other symbol type.
1960 return {m_clang, m_clang->GetTranslationUnitDecl()};
1961}
1962
Zachary Turnerb96181c2018-10-22 16:19:07 +00001963Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001964 auto iter = m_types.find(type_uid);
1965 // lldb should not be passing us non-sensical type uids. the only way it
1966 // could have a type uid in the first place is if we handed it out, in which
Zachary Turner9f727952018-10-26 09:06:38 +00001967 // case we should know about the type. However, that doesn't mean we've
1968 // instantiated it yet. We can vend out a UID for a future type. So if the
1969 // type doesn't exist, let's instantiate it now.
1970 if (iter != m_types.end())
1971 return &*iter->second;
1972
Zachary Turner6284aee2018-11-16 02:42:32 +00001973 PdbSymUid uid(type_uid);
1974 lldbassert(uid.kind() == PdbSymUidKind::Type);
1975 PdbTypeSymId type_id = uid.asTypeSym();
1976 if (type_id.index.isNoneType())
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001977 return nullptr;
Zachary Turner9f727952018-10-26 09:06:38 +00001978
Zachary Turner6284aee2018-11-16 02:42:32 +00001979 TypeSP type_sp = CreateAndCacheType(type_id);
Zachary Turner9f727952018-10-26 09:06:38 +00001980 return &*type_sp;
Zachary Turnerb96181c2018-10-22 16:19:07 +00001981}
1982
Adrian Prantleca07c52018-11-05 20:49:07 +00001983llvm::Optional<SymbolFile::ArrayInfo>
1984SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1985 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1986 return llvm::None;
1987}
1988
1989
Zachary Turnerb96181c2018-10-22 16:19:07 +00001990bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001991 // If this is not in our map, it's an error.
1992 clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1993 lldbassert(tag_decl);
1994 auto status_iter = m_decl_to_status.find(tag_decl);
1995 lldbassert(status_iter != m_decl_to_status.end());
1996
1997 // If it's already complete, just return.
1998 DeclStatus &status = status_iter->second;
1999 if (status.status == Type::eResolveStateFull)
2000 return true;
2001
Zachary Turner6284aee2018-11-16 02:42:32 +00002002 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
Zachary Turner2f7efbc2018-10-23 16:37:53 +00002003
Zachary Turner6284aee2018-11-16 02:42:32 +00002004 lldbassert(IsTagRecord(type_id, m_index->tpi()));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00002005
2006 ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
2007 false);
2008
2009 // In CreateAndCacheType, we already go out of our way to resolve forward
2010 // ref UDTs to full decls, and the uids we vend out always refer to full
2011 // decls if a full decl exists in the debug info. So if we don't have a full
2012 // decl here, it means one doesn't exist in the debug info, and we can't
2013 // complete the type.
2014 CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
2015 if (IsForwardRefUdt(cvt))
2016 return false;
2017
Zachary Turner6284aee2018-11-16 02:42:32 +00002018 auto types_iter = m_types.find(status.uid);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00002019 lldbassert(types_iter != m_types.end());
2020
Zachary Turner511bff22018-10-30 18:57:08 +00002021 if (cvt.kind() == LF_MODIFIER) {
2022 TypeIndex unmodified_type = LookThroughModifierRecord(cvt);
2023 cvt = m_index->tpi().getType(unmodified_type);
2024 // LF_MODIFIERS usually point to forward decls, so this is the one case
2025 // where we won't have been able to resolve a forward decl to a full decl
2026 // earlier on. So we need to do that now.
2027 if (IsForwardRefUdt(cvt)) {
2028 llvm::Expected<TypeIndex> expected_full_ti =
2029 m_index->tpi().findFullDeclForForwardRef(unmodified_type);
2030 if (!expected_full_ti) {
2031 llvm::consumeError(expected_full_ti.takeError());
2032 return false;
2033 }
2034 cvt = m_index->tpi().getType(*expected_full_ti);
2035 lldbassert(!IsForwardRefUdt(cvt));
2036 unmodified_type = *expected_full_ti;
2037 }
Zachary Turner9fbf9352018-11-16 03:16:27 +00002038 type_id = PdbTypeSymId(unmodified_type, false);
Zachary Turner511bff22018-10-30 18:57:08 +00002039 }
Zachary Turner2f7efbc2018-10-23 16:37:53 +00002040 TypeIndex field_list_ti = GetFieldListIndex(cvt);
2041 CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
2042 if (field_list_cvt.kind() != LF_FIELDLIST)
2043 return false;
2044
2045 // Visit all members of this class, then perform any finalization necessary
2046 // to complete the class.
Zachary Turner6284aee2018-11-16 02:42:32 +00002047 UdtRecordCompleter completer(type_id, compiler_type, *tag_decl, *this);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00002048 auto error =
2049 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
2050 completer.complete();
2051
2052 status.status = Type::eResolveStateFull;
2053 if (!error)
2054 return true;
2055
2056 llvm::consumeError(std::move(error));
Zachary Turnerb96181c2018-10-22 16:19:07 +00002057 return false;
2058}
2059
2060size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
Zachary Turner117b1fa2018-10-25 20:45:40 +00002061 TypeClass type_mask,
Zachary Turnerb96181c2018-10-22 16:19:07 +00002062 lldb_private::TypeList &type_list) {
2063 return 0;
2064}
2065
2066CompilerDeclContext
2067SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
2068 const ConstString &name,
2069 const CompilerDeclContext *parent_decl_ctx) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00002070 return {};
2071}
2072
Zachary Turnerb96181c2018-10-22 16:19:07 +00002073TypeSystem *
Zachary Turner307f5ae2018-10-12 19:47:13 +00002074SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
2075 auto type_system =
2076 m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
2077 if (type_system)
2078 type_system->SetSymbolFile(this);
2079 return type_system;
2080}
2081
Zachary Turnerb96181c2018-10-22 16:19:07 +00002082ConstString SymbolFileNativePDB::GetPluginName() {
Zachary Turner307f5ae2018-10-12 19:47:13 +00002083 static ConstString g_name("pdb");
2084 return g_name;
2085}
2086
2087uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }