blob: 898b43073bb8f34e64619d7b9f817cedfd54002a [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
69static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
70 switch (lang) {
71 case PDB_Lang::Cpp:
72 return lldb::LanguageType::eLanguageTypeC_plus_plus;
73 case PDB_Lang::C:
74 return lldb::LanguageType::eLanguageTypeC;
75 default:
76 return lldb::LanguageType::eLanguageTypeUnknown;
77 }
78}
79
80static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
81 llvm::BumpPtrAllocator &Allocator) {
82 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
83 llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
84 /*RequiresNullTerminator=*/false);
85 if (!ErrorOrBuffer)
86 return nullptr;
87 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
88
89 llvm::StringRef Path = Buffer->getBufferIdentifier();
90 auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>(
91 std::move(Buffer), llvm::support::little);
92
93 auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
Zachary Turner8040eea2018-10-12 22:57:40 +000094 if (auto EC = File->parseFileHeaders()) {
95 llvm::consumeError(std::move(EC));
Zachary Turner307f5ae2018-10-12 19:47:13 +000096 return nullptr;
Zachary Turner8040eea2018-10-12 22:57:40 +000097 }
98 if (auto EC = File->parseStreamData()) {
99 llvm::consumeError(std::move(EC));
Zachary Turner307f5ae2018-10-12 19:47:13 +0000100 return nullptr;
Zachary Turner8040eea2018-10-12 22:57:40 +0000101 }
Zachary Turner307f5ae2018-10-12 19:47:13 +0000102
103 return File;
104}
105
106static std::unique_ptr<PDBFile>
107loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
108 // Try to find a matching PDB for an EXE.
109 using namespace llvm::object;
110 auto expected_binary = createBinary(exe_path);
111
112 // If the file isn't a PE/COFF executable, fail.
113 if (!expected_binary) {
114 llvm::consumeError(expected_binary.takeError());
115 return nullptr;
116 }
117 OwningBinary<Binary> binary = std::move(*expected_binary);
118
119 auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
120 if (!obj)
121 return nullptr;
122 const llvm::codeview::DebugInfo *pdb_info = nullptr;
123
124 // If it doesn't have a debug directory, fail.
125 llvm::StringRef pdb_file;
126 auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
127 if (ec)
128 return nullptr;
129
130 // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
131 // fail.
132 llvm::file_magic magic;
133 ec = llvm::identify_magic(pdb_file, magic);
134 if (ec || magic != llvm::file_magic::pdb)
135 return nullptr;
136 std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator);
Zachary Turner8040eea2018-10-12 22:57:40 +0000137 if (!pdb)
138 return nullptr;
139
Zachary Turner307f5ae2018-10-12 19:47:13 +0000140 auto expected_info = pdb->getPDBInfoStream();
141 if (!expected_info) {
142 llvm::consumeError(expected_info.takeError());
143 return nullptr;
144 }
145 llvm::codeview::GUID guid;
146 memcpy(&guid, pdb_info->PDB70.Signature, 16);
147
148 if (expected_info->getGuid() != guid)
149 return nullptr;
150 return pdb;
151}
152
153static bool IsFunctionPrologue(const CompilandIndexItem &cci,
154 lldb::addr_t addr) {
155 // FIXME: Implement this.
156 return false;
157}
158
159static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
160 lldb::addr_t addr) {
161 // FIXME: Implement this.
162 return false;
163}
164
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000165static clang::MSInheritanceAttr::Spelling
166GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) {
167 if (record.DerivationList == TypeIndex::None())
168 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
169
170 CVType bases = tpi.getType(record.DerivationList);
171 ArgListRecord base_list;
172 cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list));
173 if (base_list.ArgIndices.empty())
174 return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
175
176 int base_count = 0;
177 for (TypeIndex ti : base_list.ArgIndices) {
178 CVType base = tpi.getType(ti);
179 if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS)
180 return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
181 ++base_count;
182 }
183
184 if (base_count > 1)
185 return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
186 return clang::MSInheritanceAttr::Keyword_single_inheritance;
187}
188
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000189static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
190 switch (kind) {
191 case SimpleTypeKind::Boolean128:
192 case SimpleTypeKind::Boolean16:
193 case SimpleTypeKind::Boolean32:
194 case SimpleTypeKind::Boolean64:
195 case SimpleTypeKind::Boolean8:
196 return "bool";
197 case SimpleTypeKind::Byte:
198 case SimpleTypeKind::UnsignedCharacter:
199 return "unsigned char";
200 case SimpleTypeKind::NarrowCharacter:
201 return "char";
202 case SimpleTypeKind::SignedCharacter:
203 case SimpleTypeKind::SByte:
Zachary Turner71ebb722018-10-23 22:15:05 +0000204 return "signed char";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000205 case SimpleTypeKind::Character16:
206 return "char16_t";
207 case SimpleTypeKind::Character32:
208 return "char32_t";
209 case SimpleTypeKind::Complex80:
210 case SimpleTypeKind::Complex64:
211 case SimpleTypeKind::Complex32:
212 return "complex";
213 case SimpleTypeKind::Float128:
214 case SimpleTypeKind::Float80:
215 return "long double";
216 case SimpleTypeKind::Float64:
217 return "double";
218 case SimpleTypeKind::Float32:
219 return "float";
220 case SimpleTypeKind::Float16:
221 return "single";
222 case SimpleTypeKind::Int128:
223 return "__int128";
224 case SimpleTypeKind::Int64:
225 case SimpleTypeKind::Int64Quad:
Zachary Turner71ebb722018-10-23 22:15:05 +0000226 return "int64_t";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000227 case SimpleTypeKind::Int32:
228 return "int";
229 case SimpleTypeKind::Int16:
230 return "short";
231 case SimpleTypeKind::UInt128:
232 return "unsigned __int128";
233 case SimpleTypeKind::UInt64:
234 case SimpleTypeKind::UInt64Quad:
Zachary Turner71ebb722018-10-23 22:15:05 +0000235 return "uint64_t";
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000236 case SimpleTypeKind::HResult:
237 return "HRESULT";
238 case SimpleTypeKind::UInt32:
239 return "unsigned";
240 case SimpleTypeKind::UInt16:
241 case SimpleTypeKind::UInt16Short:
242 return "unsigned short";
243 case SimpleTypeKind::Int32Long:
244 return "long";
245 case SimpleTypeKind::UInt32Long:
246 return "unsigned long";
247 case SimpleTypeKind::Void:
248 return "void";
249 case SimpleTypeKind::WideCharacter:
250 return "wchar_t";
251 default:
252 return "";
253 }
254}
255
256static bool IsClassRecord(TypeLeafKind kind) {
257 switch (kind) {
258 case LF_STRUCTURE:
259 case LF_CLASS:
260 case LF_INTERFACE:
261 return true;
262 default:
263 return false;
264 }
265}
266
Zachary Turner544a66d82018-11-01 16:37:29 +0000267static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
268 if (args.empty())
269 return false;
270 return args.back() == TypeIndex::None();
271}
272
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000273static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
274 switch (cr.Kind) {
275 case TypeRecordKind::Class:
276 return clang::TTK_Class;
277 case TypeRecordKind::Struct:
278 return clang::TTK_Struct;
279 case TypeRecordKind::Union:
280 return clang::TTK_Union;
281 case TypeRecordKind::Interface:
282 return clang::TTK_Interface;
283 case TypeRecordKind::Enum:
284 return clang::TTK_Enum;
285 default:
286 lldbassert(false && "Invalid tag record kind!");
287 return clang::TTK_Struct;
288 }
289}
290
Zachary Turner544a66d82018-11-01 16:37:29 +0000291static llvm::Optional<clang::CallingConv>
292TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
293 using CC = llvm::codeview::CallingConvention;
294 switch (conv) {
295
296 case CC::NearC:
297 case CC::FarC:
298 return clang::CallingConv::CC_C;
299 case CC::NearPascal:
300 case CC::FarPascal:
301 return clang::CallingConv::CC_X86Pascal;
302 case CC::NearFast:
303 case CC::FarFast:
304 return clang::CallingConv::CC_X86FastCall;
305 case CC::NearStdCall:
306 case CC::FarStdCall:
307 return clang::CallingConv::CC_X86StdCall;
308 case CC::ThisCall:
309 return clang::CallingConv::CC_X86ThisCall;
310 case CC::NearVector:
311 return clang::CallingConv::CC_X86VectorCall;
312 default:
313 return llvm::None;
314 }
315}
316
Zachary Turner307f5ae2018-10-12 19:47:13 +0000317void SymbolFileNativePDB::Initialize() {
318 PluginManager::RegisterPlugin(GetPluginNameStatic(),
319 GetPluginDescriptionStatic(), CreateInstance,
320 DebuggerInitialize);
321}
322
323void SymbolFileNativePDB::Terminate() {
324 PluginManager::UnregisterPlugin(CreateInstance);
325}
326
Zachary Turnerb96181c2018-10-22 16:19:07 +0000327void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
Zachary Turner307f5ae2018-10-12 19:47:13 +0000328
Zachary Turnerb96181c2018-10-22 16:19:07 +0000329ConstString SymbolFileNativePDB::GetPluginNameStatic() {
Zachary Turner307f5ae2018-10-12 19:47:13 +0000330 static ConstString g_name("native-pdb");
331 return g_name;
332}
333
334const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
335 return "Microsoft PDB debug symbol cross-platform file reader.";
336}
337
Zachary Turnerb96181c2018-10-22 16:19:07 +0000338SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
Zachary Turner307f5ae2018-10-12 19:47:13 +0000339 return new SymbolFileNativePDB(obj_file);
340}
341
Zachary Turnerb96181c2018-10-22 16:19:07 +0000342SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
Zachary Turner307f5ae2018-10-12 19:47:13 +0000343 : SymbolFile(object_file) {}
344
345SymbolFileNativePDB::~SymbolFileNativePDB() {}
346
347uint32_t SymbolFileNativePDB::CalculateAbilities() {
348 uint32_t abilities = 0;
349 if (!m_obj_file)
350 return 0;
351
352 if (!m_index) {
353 // Lazily load and match the PDB file, but only do this once.
354 std::unique_ptr<PDBFile> file_up =
355 loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
356
357 if (!file_up) {
358 auto module_sp = m_obj_file->GetModule();
359 if (!module_sp)
360 return 0;
361 // See if any symbol file is specified through `--symfile` option.
362 FileSpec symfile = module_sp->GetSymbolFileFileSpec();
363 if (!symfile)
364 return 0;
365 file_up = loadPDBFile(symfile.GetPath(), m_allocator);
366 }
367
368 if (!file_up)
369 return 0;
370
371 auto expected_index = PdbIndex::create(std::move(file_up));
372 if (!expected_index) {
373 llvm::consumeError(expected_index.takeError());
374 return 0;
375 }
376 m_index = std::move(*expected_index);
377 }
378 if (!m_index)
379 return 0;
380
381 // We don't especially have to be precise here. We only distinguish between
382 // stripped and not stripped.
383 abilities = kAllAbilities;
384
385 if (m_index->dbi().isStripped())
386 abilities &= ~(Blocks | LocalVariables);
387 return abilities;
388}
389
390void SymbolFileNativePDB::InitializeObject() {
391 m_obj_load_address = m_obj_file->GetFileOffset();
392 m_index->SetLoadAddress(m_obj_load_address);
393 m_index->ParseSectionContribs();
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000394
395 TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
396 m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
397 m_importer = llvm::make_unique<ClangASTImporter>();
Zachary Turner056e4ab2018-11-08 18:50:11 +0000398
399 PreprocessTpiStream();
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000400 lldbassert(m_clang);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000401}
402
Zachary Turner03a24052018-11-13 20:07:32 +0000403static llvm::Optional<CVTagRecord>
404GetNestedTagRecord(const NestedTypeRecord &Record, const CVTagRecord &parent,
405 TpiStream &tpi) {
406 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
407 // is also used to indicate the primary definition of a nested class. That is
408 // to say, if you have:
409 // struct A {
410 // struct B {};
411 // using C = B;
412 // };
413 // Then in the debug info, this will appear as:
414 // LF_STRUCTURE `A::B` [type index = N]
415 // LF_STRUCTURE `A`
416 // LF_NESTTYPE [name = `B`, index = N]
417 // LF_NESTTYPE [name = `C`, index = N]
418 // In order to accurately reconstruct the decl context hierarchy, we need to
419 // know which ones are actual definitions and which ones are just aliases.
420
421 // If it's a simple type, then this is something like `using foo = int`.
422 if (Record.Type.isSimple())
423 return llvm::None;
424
Zachary Turner2af34162018-11-13 20:07:57 +0000425 CVType cvt = tpi.getType(Record.Type);
426
427 if (!IsTagRecord(cvt))
428 return llvm::None;
429
Zachary Turner03a24052018-11-13 20:07:32 +0000430 // If it's an inner definition, then treat whatever name we have here as a
431 // single component of a mangled name. So we can inject it into the parent's
432 // mangled name to see if it matches.
Zachary Turner2af34162018-11-13 20:07:57 +0000433 CVTagRecord child = CVTagRecord::create(cvt);
Zachary Turner03a24052018-11-13 20:07:32 +0000434 std::string qname = parent.asTag().getUniqueName();
435 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
436 return llvm::None;
437
438 // qname[3] is the tag type identifier (struct, class, union, etc). Since the
439 // inner tag type is not necessarily the same as the outer tag type, re-write
440 // it to match the inner tag type.
441 qname[3] = child.asTag().getUniqueName()[3];
442 std::string piece = Record.Name;
443 piece.push_back('@');
444 qname.insert(4, std::move(piece));
445 if (qname != child.asTag().UniqueName)
446 return llvm::None;
447
448 return std::move(child);
449}
450
Zachary Turner056e4ab2018-11-08 18:50:11 +0000451void SymbolFileNativePDB::PreprocessTpiStream() {
452 LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
453
454 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
455 CVType type = types.getType(*ti);
456 if (!IsTagRecord(type))
457 continue;
458
459 CVTagRecord tag = CVTagRecord::create(type);
460 // We're looking for LF_NESTTYPE records in the field list, so ignore
461 // forward references (no field list), and anything without a nested class
462 // (since there won't be any LF_NESTTYPE records).
463 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
464 continue;
465
466 struct ProcessTpiStream : public TypeVisitorCallbacks {
467 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
Zachary Turner03a24052018-11-13 20:07:32 +0000468 const CVTagRecord &parent_cvt,
Zachary Turner056e4ab2018-11-08 18:50:11 +0000469 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
Zachary Turner03a24052018-11-13 20:07:32 +0000470 : index(index), parents(parents), parent(parent),
471 parent_cvt(parent_cvt) {}
Zachary Turner056e4ab2018-11-08 18:50:11 +0000472
473 PdbIndex &index;
474 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
475 TypeIndex parent;
Zachary Turner03a24052018-11-13 20:07:32 +0000476 const CVTagRecord &parent_cvt;
Zachary Turner056e4ab2018-11-08 18:50:11 +0000477
478 llvm::Error visitKnownMember(CVMemberRecord &CVR,
479 NestedTypeRecord &Record) override {
Zachary Turner03a24052018-11-13 20:07:32 +0000480 llvm::Optional<CVTagRecord> tag =
481 GetNestedTagRecord(Record, parent_cvt, index.tpi());
482 if (!tag)
Zachary Turner056e4ab2018-11-08 18:50:11 +0000483 return llvm::ErrorSuccess();
Zachary Turner03a24052018-11-13 20:07:32 +0000484
485 parents[Record.Type] = parent;
486 if (!tag->asTag().isForwardRef())
487 return llvm::ErrorSuccess();
488
Zachary Turner056e4ab2018-11-08 18:50:11 +0000489 llvm::Expected<TypeIndex> full_decl =
490 index.tpi().findFullDeclForForwardRef(Record.Type);
491 if (!full_decl) {
492 llvm::consumeError(full_decl.takeError());
493 return llvm::ErrorSuccess();
494 }
495 parents[*full_decl] = parent;
496 return llvm::ErrorSuccess();
497 }
498 };
499
500 CVType field_list = m_index->tpi().getType(tag.asTag().FieldList);
Zachary Turner03a24052018-11-13 20:07:32 +0000501 ProcessTpiStream process(*m_index, *ti, tag, m_parent_types);
Zachary Turner056e4ab2018-11-08 18:50:11 +0000502 llvm::Error error = visitMemberRecordStream(field_list.data(), process);
503 if (error)
504 llvm::consumeError(std::move(error));
505 }
506}
507
Zachary Turner307f5ae2018-10-12 19:47:13 +0000508uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
509 const DbiModuleList &modules = m_index->dbi().modules();
510 uint32_t count = modules.getModuleCount();
511 if (count == 0)
512 return count;
513
514 // The linker can inject an additional "dummy" compilation unit into the
515 // PDB. Ignore this special compile unit for our purposes, if it is there.
516 // It is always the last one.
517 DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
518 if (last.getModuleName() == "* Linker *")
519 --count;
520 return count;
521}
522
Zachary Turner6284aee2018-11-16 02:42:32 +0000523lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
Zachary Turner307f5ae2018-10-12 19:47:13 +0000524 const SymbolContext &sc) {
Zachary Turner6284aee2018-11-16 02:42:32 +0000525 const CompilandIndexItem *cci =
526 m_index->compilands().GetCompiland(func_id.modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000527 lldbassert(cci);
Zachary Turner6284aee2018-11-16 02:42:32 +0000528 CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000529
530 lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
531 SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
532
533 auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
534 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
535 return nullptr;
536
537 AddressRange func_range(file_vm_addr, sol.length,
538 sc.module_sp->GetSectionList());
539 if (!func_range.GetBaseAddress().IsValid())
540 return nullptr;
541
Zachary Turnera42bbe32018-12-07 19:34:02 +0000542 ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
543 cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
544 TypeSP func_type = GetOrCreateType(proc.FunctionType);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000545
Zachary Turnera42bbe32018-12-07 19:34:02 +0000546 PdbTypeSymId sig_id(proc.FunctionType, false);
547 Mangled mangled(proc.Name);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000548 FunctionSP func_sp = std::make_shared<Function>(
Zachary Turner6284aee2018-11-16 02:42:32 +0000549 sc.comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
Zachary Turnera42bbe32018-12-07 19:34:02 +0000550 func_type.get(), func_range);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000551
552 sc.comp_unit->AddFunction(func_sp);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000553
554 clang::StorageClass storage = clang::SC_None;
555 if (sym_record.kind() == S_LPROC32)
556 storage = clang::SC_Static;
557
558 // There are two ways we could retrieve the parameter list. The first is by
559 // iterating the arguments on the function signature type, however that would
560 // only tell us the types of the arguments and not the names. The second is
561 // to iterate the CVSymbol records that follow the S_GPROC32 / S_LPROC32 until
562 // we have the correct number of arguments as stated by the function
563 // signature. The latter has more potential to go wrong in the face of
564 // improper debug info simply because we're assuming more about the layout of
565 // the records, but it is the only way to get argument names.
566 CVType sig_cvt;
567 CVType arg_list_cvt;
568 ProcedureRecord sig_record;
569 ArgListRecord arg_list_record;
570
571 sig_cvt = m_index->tpi().getType(proc.FunctionType);
572 if (sig_cvt.kind() != LF_PROCEDURE)
573 return func_sp;
574 cantFail(
575 TypeDeserializer::deserializeAs<ProcedureRecord>(sig_cvt, sig_record));
576
577 CompilerDeclContext context =
578 GetDeclContextContainingUID(toOpaqueUid(func_id));
579
580 clang::DeclContext *decl_context =
581 static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
582 clang::FunctionDecl *function_decl = m_clang->CreateFunctionDeclaration(
583 decl_context, proc.Name.str().c_str(),
584 func_type->GetForwardCompilerType(), storage, false);
585
586 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
587 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
588 CVSymbolArray scope = limitSymbolArrayToScope(
589 cci->m_debug_stream.getSymbolArray(), func_id.offset);
590
591 uint32_t params_remaining = sig_record.getParameterCount();
592 auto begin = scope.begin();
593 auto end = scope.end();
594 std::vector<clang::ParmVarDecl *> params;
595 while (begin != end && params_remaining > 0) {
596 uint32_t record_offset = begin.offset();
597 CVSymbol sym = *begin++;
598
599 TypeIndex param_type;
600 llvm::StringRef param_name;
601 switch (sym.kind()) {
602 case S_REGREL32: {
603 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
604 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
605 param_type = reg.Type;
606 param_name = reg.Name;
607 break;
608 }
609 case S_REGISTER: {
610 RegisterSym reg(SymbolRecordKind::RegisterSym);
611 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
612 param_type = reg.Index;
613 param_name = reg.Name;
614 break;
615 }
616 case S_LOCAL: {
617 LocalSym local(SymbolRecordKind::LocalSym);
618 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
619 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
620 continue;
621 param_type = local.Type;
622 param_name = local.Name;
623 break;
624 }
625 case S_BLOCK32:
626 // All parameters should come before the first block. If that isn't the
627 // case, then perhaps this is bad debug info that doesn't contain
628 // information about all parameters.
629 params_remaining = 0;
630 continue;
631 default:
632 continue;
633 }
634
635 PdbCompilandSymId param_uid(func_id.modi, record_offset);
636 TypeSP type_sp = GetOrCreateType(param_type);
637 clang::ParmVarDecl *param = m_clang->CreateParameterDeclaration(
Zachary Turner6753d2d2018-12-12 17:17:53 +0000638 function_decl, param_name.str().c_str(),
639 type_sp->GetForwardCompilerType(), clang::SC_None);
Zachary Turnera42bbe32018-12-07 19:34:02 +0000640 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
641
642 m_uid_to_decl[toOpaqueUid(param_uid)] = param;
643 params.push_back(param);
644 --params_remaining;
645 }
646
647 if (!params.empty())
648 m_clang->SetFunctionParameters(function_decl, params.data(), params.size());
649
Zachary Turner307f5ae2018-10-12 19:47:13 +0000650 return func_sp;
651}
652
653CompUnitSP
654SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
655 lldb::LanguageType lang =
656 cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
657 : lldb::eLanguageTypeUnknown;
658
659 LazyBool optimized = eLazyBoolNo;
660 if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
661 optimized = eLazyBoolYes;
662
663 llvm::StringRef source_file_name =
664 m_index->compilands().GetMainSourceFile(cci);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000665 FileSpec fs(source_file_name);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000666
667 CompUnitSP cu_sp =
668 std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
Zachary Turner6284aee2018-11-16 02:42:32 +0000669 toOpaqueUid(cci.m_id), lang, optimized);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000670
Zachary Turner6284aee2018-11-16 02:42:32 +0000671 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
672 cci.m_id.modi, cu_sp);
Zachary Turner307f5ae2018-10-12 19:47:13 +0000673 return cu_sp;
674}
675
Zachary Turner6284aee2018-11-16 02:42:32 +0000676lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000677 const ModifierRecord &mr) {
678 TpiStream &stream = m_index->tpi();
679
680 TypeSP t = GetOrCreateType(mr.ModifiedType);
681 CompilerType ct = t->GetForwardCompilerType();
682 if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
683 ct = ct.AddConstModifier();
684 if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
685 ct = ct.AddVolatileModifier();
686 std::string name;
687 if (mr.ModifiedType.isSimple())
688 name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
689 else
690 name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
691 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000692 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000693 ConstString(name), t->GetByteSize(), nullptr,
694 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
695 ct, Type::eResolveStateFull);
696}
697
698lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
Zachary Turner6284aee2018-11-16 02:42:32 +0000699 PdbTypeSymId type_id, const llvm::codeview::PointerRecord &pr) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000700 TypeSP pointee = GetOrCreateType(pr.ReferentType);
Zachary Turner544a66d82018-11-01 16:37:29 +0000701 if (!pointee)
702 return nullptr;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000703 CompilerType pointee_ct = pointee->GetForwardCompilerType();
704 lldbassert(pointee_ct);
705 Declaration decl;
706
707 if (pr.isPointerToMember()) {
708 MemberPointerInfo mpi = pr.getMemberInfo();
709 TypeSP class_type = GetOrCreateType(mpi.ContainingType);
710
711 CompilerType ct = ClangASTContext::CreateMemberPointerType(
712 class_type->GetLayoutCompilerType(), pointee_ct);
713
714 return std::make_shared<Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +0000715 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000716 pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
717 Type::eResolveStateFull);
718 }
719
720 CompilerType pointer_ct = pointee_ct;
721 if (pr.getMode() == PointerMode::LValueReference)
722 pointer_ct = pointer_ct.GetLValueReferenceType();
723 else if (pr.getMode() == PointerMode::RValueReference)
724 pointer_ct = pointer_ct.GetRValueReferenceType();
725 else
726 pointer_ct = pointer_ct.GetPointerType();
727
728 if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
729 pointer_ct = pointer_ct.AddConstModifier();
730
731 if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
732 pointer_ct = pointer_ct.AddVolatileModifier();
733
734 if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
735 pointer_ct = pointer_ct.AddRestrictModifier();
736
Zachary Turner6284aee2018-11-16 02:42:32 +0000737 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000738 ConstString(), pr.getSize(), nullptr,
739 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
740 pointer_ct, Type::eResolveStateFull);
741}
742
743lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
Zachary Turner9fbf9352018-11-16 03:16:27 +0000744 uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
Zachary Turner544a66d82018-11-01 16:37:29 +0000745 if (ti == TypeIndex::NullptrT()) {
Zachary Turner544a66d82018-11-01 16:37:29 +0000746 CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr);
747 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000748 return std::make_shared<Type>(
749 uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
750 Type::eEncodingIsUID, decl, ct, Type::eResolveStateFull);
Zachary Turner544a66d82018-11-01 16:37:29 +0000751 }
752
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000753 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000754 TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
755 CompilerType ct = direct_sp->GetFullCompilerType();
756 ct = ct.GetPointerType();
Zachary Turner71ebb722018-10-23 22:15:05 +0000757 uint32_t pointer_size = 0;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000758 switch (ti.getSimpleMode()) {
759 case SimpleTypeMode::FarPointer32:
760 case SimpleTypeMode::NearPointer32:
761 pointer_size = 4;
762 break;
763 case SimpleTypeMode::NearPointer64:
764 pointer_size = 8;
765 break;
766 default:
767 // 128-bit and 16-bit pointers unsupported.
768 return nullptr;
769 }
770 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000771 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(), ConstString(),
772 pointer_size, nullptr, LLDB_INVALID_UID,
773 Type::eEncodingIsUID, decl, ct,
774 Type::eResolveStateFull);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000775 }
776
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000777 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
778 return nullptr;
779
780 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
Zachary Turner544a66d82018-11-01 16:37:29 +0000781 if (bt == lldb::eBasicTypeInvalid)
782 return nullptr;
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000783 CompilerType ct = m_clang->GetBasicType(bt);
784 size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
785
786 llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
787
788 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000789 return std::make_shared<Type>(uid, m_clang->GetSymbolFile(),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000790 ConstString(type_name), size, nullptr,
791 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
792 ct, Type::eResolveStateFull);
793}
794
Zachary Turner056e4ab2018-11-08 18:50:11 +0000795static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) {
796 OutputStream OS;
797 initializeOutputStream(nullptr, nullptr, OS, 1024);
798 n->output(OS, llvm::ms_demangle::OF_Default);
799 OS << '\0';
800 return {OS.getBuffer()};
801}
802
Zachary Turner03a24052018-11-13 20:07:32 +0000803static bool
804AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
805 for (llvm::ms_demangle::Node *n : scopes) {
806 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
807 if (idn->TemplateParams)
808 return true;
809 }
810 return false;
811}
812
Zachary Turner056e4ab2018-11-08 18:50:11 +0000813std::pair<clang::DeclContext *, std::string>
814SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record,
815 TypeIndex ti) {
Zachary Turnera42bbe32018-12-07 19:34:02 +0000816 // FIXME: Move this to GetDeclContextContainingUID.
817
Zachary Turner056e4ab2018-11-08 18:50:11 +0000818 llvm::ms_demangle::Demangler demangler;
819 StringView sv(record.UniqueName.begin(), record.UniqueName.size());
820 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
821 llvm::ms_demangle::IdentifierNode *idn =
822 ttn->QualifiedName->getUnqualifiedIdentifier();
823 std::string uname = RenderDemanglerNode(idn);
824
825 llvm::ms_demangle::NodeArrayNode *name_components =
826 ttn->QualifiedName->Components;
827 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
828 name_components->Count - 1);
829
830 clang::DeclContext *context = m_clang->GetTranslationUnitDecl();
831
832 // If this type doesn't have a parent type in the debug info, then the best we
833 // can do is to say that it's either a series of namespaces (if the scope is
834 // non-empty), or the translation unit (if the scope is empty).
835 auto parent_iter = m_parent_types.find(ti);
836 if (parent_iter == m_parent_types.end()) {
837 if (scopes.empty())
838 return {context, uname};
839
Zachary Turner03a24052018-11-13 20:07:32 +0000840 // If there is no parent in the debug info, but some of the scopes have
841 // template params, then this is a case of bad debug info. See, for
842 // example, llvm.org/pr39607. We don't want to create an ambiguity between
843 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
844 // global scope with the fully qualified name.
845 if (AnyScopesHaveTemplateParams(scopes))
846 return {context, record.Name};
847
Zachary Turner056e4ab2018-11-08 18:50:11 +0000848 for (llvm::ms_demangle::Node *scope : scopes) {
849 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
850 std::string str = RenderDemanglerNode(nii);
851 context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context);
852 }
853 return {context, uname};
854 }
855
856 // Otherwise, all we need to do is get the parent type of this type and
857 // recurse into our lazy type creation / AST reconstruction logic to get an
858 // LLDB TypeSP for the parent. This will cause the AST to automatically get
859 // the right DeclContext created for any parent.
860 TypeSP parent = GetOrCreateType(parent_iter->second);
861 if (!parent)
862 return {context, uname};
863 CompilerType parent_ct = parent->GetForwardCompilerType();
864 clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct);
865 context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl());
866 return {context, uname};
867}
868
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000869lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
Zachary Turner6284aee2018-11-16 02:42:32 +0000870 PdbTypeSymId type_id, const llvm::codeview::TagRecord &record, size_t size,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000871 clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
872
Zachary Turner056e4ab2018-11-08 18:50:11 +0000873 clang::DeclContext *decl_context = nullptr;
874 std::string uname;
Zachary Turner6284aee2018-11-16 02:42:32 +0000875 std::tie(decl_context, uname) = CreateDeclInfoForType(record, type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000876
877 lldb::AccessType access =
878 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
879
880 ClangASTMetadata metadata;
Zachary Turner6284aee2018-11-16 02:42:32 +0000881 metadata.SetUserID(toOpaqueUid(type_id));
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000882 metadata.SetIsDynamicCXXType(false);
883
884 CompilerType ct =
Zachary Turner056e4ab2018-11-08 18:50:11 +0000885 m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000886 lldb::eLanguageTypeC_plus_plus, &metadata);
Zachary Turner056e4ab2018-11-08 18:50:11 +0000887
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000888 lldbassert(ct.IsValid());
889
890 clang::CXXRecordDecl *record_decl =
891 m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
892 lldbassert(record_decl);
893
894 clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
895 *m_clang->getASTContext(), inheritance);
896 record_decl->addAttr(attr);
897
898 ClangASTContext::StartTagDeclarationDefinition(ct);
899
900 // Even if it's possible, don't complete it at this point. Just mark it
901 // forward resolved, and if/when LLDB needs the full definition, it can
902 // ask us.
903 ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
904
905 // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
906 Declaration decl;
Zachary Turner6284aee2018-11-16 02:42:32 +0000907 return std::make_shared<Type>(toOpaqueUid(type_id), m_clang->GetSymbolFile(),
Zachary Turner056e4ab2018-11-08 18:50:11 +0000908 ConstString(uname), size, nullptr,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000909 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
910 ct, Type::eResolveStateForward);
911}
912
Zachary Turner6284aee2018-11-16 02:42:32 +0000913lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000914 const ClassRecord &cr) {
915 clang::TagTypeKind ttk = TranslateUdtKind(cr);
916
917 clang::MSInheritanceAttr::Spelling inheritance =
918 GetMSInheritance(m_index->tpi().typeCollection(), cr);
Zachary Turner6284aee2018-11-16 02:42:32 +0000919 return CreateClassStructUnion(type_id, cr, cr.getSize(), ttk, inheritance);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000920}
921
Zachary Turner6284aee2018-11-16 02:42:32 +0000922lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000923 const UnionRecord &ur) {
924 return CreateClassStructUnion(
Zachary Turner6284aee2018-11-16 02:42:32 +0000925 type_id, ur, ur.getSize(), clang::TTK_Union,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000926 clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
927}
928
Zachary Turner6284aee2018-11-16 02:42:32 +0000929lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000930 const EnumRecord &er) {
Zachary Turner2af34162018-11-13 20:07:57 +0000931 clang::DeclContext *decl_context = nullptr;
932 std::string uname;
Zachary Turner6284aee2018-11-16 02:42:32 +0000933 std::tie(decl_context, uname) = CreateDeclInfoForType(er, type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000934
935 Declaration decl;
936 TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
937 CompilerType enum_ct = m_clang->CreateEnumerationType(
Zachary Turner2af34162018-11-13 20:07:57 +0000938 uname.c_str(), decl_context, decl, underlying_type->GetFullCompilerType(),
939 er.isScoped());
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000940
941 ClangASTContext::StartTagDeclarationDefinition(enum_ct);
Zachary Turner12abab52018-11-09 17:08:26 +0000942 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000943
944 // We're just going to forward resolve this for now. We'll complete
945 // it only if the user requests.
946 return std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +0000947 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(uname),
Zachary Turner2f7efbc2018-10-23 16:37:53 +0000948 underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
949 lldb_private::Type::eEncodingIsUID, decl, enum_ct,
950 lldb_private::Type::eResolveStateForward);
951}
952
Zachary Turner6284aee2018-11-16 02:42:32 +0000953TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
Zachary Turner511bff22018-10-30 18:57:08 +0000954 const ArrayRecord &ar) {
955 TypeSP element_type = GetOrCreateType(ar.ElementType);
956 uint64_t element_count = ar.Size / element_type->GetByteSize();
957
958 CompilerType element_ct = element_type->GetFullCompilerType();
959
960 CompilerType array_ct =
961 m_clang->CreateArrayType(element_ct, element_count, false);
962
963 Declaration decl;
964 TypeSP array_sp = std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +0000965 toOpaqueUid(type_id), m_clang->GetSymbolFile(), ConstString(), ar.Size,
Zachary Turner511bff22018-10-30 18:57:08 +0000966 nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
967 array_ct, lldb_private::Type::eResolveStateFull);
968 array_sp->SetEncodingType(element_type.get());
969 return array_sp;
970}
971
Zachary Turner6284aee2018-11-16 02:42:32 +0000972TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
Zachary Turner544a66d82018-11-01 16:37:29 +0000973 const ProcedureRecord &pr) {
974 TpiStream &stream = m_index->tpi();
975 CVType args_cvt = stream.getType(pr.ArgumentList);
976 ArgListRecord args;
977 llvm::cantFail(
978 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
979
980 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
981 bool is_variadic = IsCVarArgsFunction(arg_indices);
982 if (is_variadic)
983 arg_indices = arg_indices.drop_back();
984
985 std::vector<CompilerType> arg_list;
986 arg_list.reserve(arg_list.size());
987
988 for (TypeIndex arg_index : arg_indices) {
989 TypeSP arg_sp = GetOrCreateType(arg_index);
990 if (!arg_sp)
991 return nullptr;
992 arg_list.push_back(arg_sp->GetFullCompilerType());
993 }
994
995 TypeSP return_type_sp = GetOrCreateType(pr.ReturnType);
996 if (!return_type_sp)
997 return nullptr;
998
999 llvm::Optional<clang::CallingConv> cc =
1000 TranslateCallingConvention(pr.CallConv);
1001 if (!cc)
1002 return nullptr;
1003
1004 CompilerType return_ct = return_type_sp->GetFullCompilerType();
1005 CompilerType func_sig_ast_type = m_clang->CreateFunctionType(
1006 return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc);
1007
1008 Declaration decl;
1009 return std::make_shared<lldb_private::Type>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001010 toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
Zachary Turner544a66d82018-11-01 16:37:29 +00001011 lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type,
1012 lldb_private::Type::eResolveStateFull);
1013}
1014
Zachary Turner6284aee2018-11-16 02:42:32 +00001015TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id) {
1016 if (type_id.index.isSimple())
1017 return CreateSimpleType(type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001018
Zachary Turner6284aee2018-11-16 02:42:32 +00001019 TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
1020 CVType cvt = stream.getType(type_id.index);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001021
1022 if (cvt.kind() == LF_MODIFIER) {
1023 ModifierRecord modifier;
1024 llvm::cantFail(
1025 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
Zachary Turner6284aee2018-11-16 02:42:32 +00001026 return CreateModifierType(type_id, modifier);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001027 }
1028
1029 if (cvt.kind() == LF_POINTER) {
1030 PointerRecord pointer;
1031 llvm::cantFail(
1032 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
Zachary Turner6284aee2018-11-16 02:42:32 +00001033 return CreatePointerType(type_id, pointer);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001034 }
1035
1036 if (IsClassRecord(cvt.kind())) {
1037 ClassRecord cr;
1038 llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
Zachary Turner6284aee2018-11-16 02:42:32 +00001039 return CreateTagType(type_id, cr);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001040 }
1041
1042 if (cvt.kind() == LF_ENUM) {
1043 EnumRecord er;
1044 llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
Zachary Turner6284aee2018-11-16 02:42:32 +00001045 return CreateTagType(type_id, er);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001046 }
1047
1048 if (cvt.kind() == LF_UNION) {
1049 UnionRecord ur;
1050 llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
Zachary Turner6284aee2018-11-16 02:42:32 +00001051 return CreateTagType(type_id, ur);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001052 }
1053
Zachary Turner511bff22018-10-30 18:57:08 +00001054 if (cvt.kind() == LF_ARRAY) {
1055 ArrayRecord ar;
1056 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
Zachary Turner6284aee2018-11-16 02:42:32 +00001057 return CreateArrayType(type_id, ar);
Zachary Turner511bff22018-10-30 18:57:08 +00001058 }
1059
Zachary Turner544a66d82018-11-01 16:37:29 +00001060 if (cvt.kind() == LF_PROCEDURE) {
1061 ProcedureRecord pr;
1062 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
Zachary Turner6284aee2018-11-16 02:42:32 +00001063 return CreateProcedureType(type_id, pr);
Zachary Turner544a66d82018-11-01 16:37:29 +00001064 }
1065
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001066 return nullptr;
1067}
1068
Zachary Turner6284aee2018-11-16 02:42:32 +00001069TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001070 // If they search for a UDT which is a forward ref, try and resolve the full
1071 // decl and just map the forward ref uid to the full decl record.
Zachary Turner6284aee2018-11-16 02:42:32 +00001072 llvm::Optional<PdbTypeSymId> full_decl_uid;
1073 if (IsForwardRefUdt(type_id, m_index->tpi())) {
1074 auto expected_full_ti =
1075 m_index->tpi().findFullDeclForForwardRef(type_id.index);
1076 if (!expected_full_ti)
1077 llvm::consumeError(expected_full_ti.takeError());
1078 else if (*expected_full_ti != type_id.index) {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001079 full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001080
Zachary Turner6284aee2018-11-16 02:42:32 +00001081 // It's possible that a lookup would occur for the full decl causing it
1082 // to be cached, then a second lookup would occur for the forward decl.
1083 // We don't want to create a second full decl, so make sure the full
1084 // decl hasn't already been cached.
1085 auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
1086 if (full_iter != m_types.end()) {
1087 TypeSP result = full_iter->second;
1088 // Map the forward decl to the TypeSP for the full decl so we can take
1089 // the fast path next time.
1090 m_types[toOpaqueUid(type_id)] = result;
1091 return result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001092 }
1093 }
1094 }
1095
Zachary Turner6284aee2018-11-16 02:42:32 +00001096 PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
1097 TypeSP result = CreateType(best_decl_id);
Zachary Turner544a66d82018-11-01 16:37:29 +00001098 if (!result)
1099 return nullptr;
Zachary Turner6284aee2018-11-16 02:42:32 +00001100
1101 uint64_t best_uid = toOpaqueUid(best_decl_id);
1102 m_types[best_uid] = result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001103 // If we had both a forward decl and a full decl, make both point to the new
1104 // type.
1105 if (full_decl_uid)
Zachary Turner6284aee2018-11-16 02:42:32 +00001106 m_types[toOpaqueUid(type_id)] = result;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001107
Zachary Turner6284aee2018-11-16 02:42:32 +00001108 if (IsTagRecord(best_decl_id, m_index->tpi())) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001109 clang::TagDecl *record_decl =
1110 m_clang->GetAsTagDecl(result->GetForwardCompilerType());
1111 lldbassert(record_decl);
1112
Zachary Turner6284aee2018-11-16 02:42:32 +00001113 m_uid_to_decl[best_uid] = record_decl;
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001114 m_decl_to_status[record_decl] =
Zachary Turner6284aee2018-11-16 02:42:32 +00001115 DeclStatus(best_uid, Type::eResolveStateForward);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001116 }
1117 return result;
1118}
1119
Zachary Turner6284aee2018-11-16 02:42:32 +00001120TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001121 // We can't use try_emplace / overwrite here because the process of creating
1122 // a type could create nested types, which could invalidate iterators. So
1123 // we have to do a 2-phase lookup / insert.
Zachary Turner6284aee2018-11-16 02:42:32 +00001124 auto iter = m_types.find(toOpaqueUid(type_id));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001125 if (iter != m_types.end())
1126 return iter->second;
1127
Zachary Turner6284aee2018-11-16 02:42:32 +00001128 return CreateAndCacheType(type_id);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001129}
1130
Zachary Turner6284aee2018-11-16 02:42:32 +00001131VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
1132 CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
Zachary Turner2af34162018-11-13 20:07:57 +00001133 if (sym.kind() == S_CONSTANT)
Zachary Turner6284aee2018-11-16 02:42:32 +00001134 return CreateConstantSymbol(var_id, sym);
Zachary Turner2af34162018-11-13 20:07:57 +00001135
Zachary Turner9f727952018-10-26 09:06:38 +00001136 lldb::ValueType scope = eValueTypeInvalid;
1137 TypeIndex ti;
1138 llvm::StringRef name;
1139 lldb::addr_t addr = 0;
1140 uint16_t section = 0;
1141 uint32_t offset = 0;
1142 bool is_external = false;
1143 switch (sym.kind()) {
1144 case S_GDATA32:
1145 is_external = true;
1146 LLVM_FALLTHROUGH;
1147 case S_LDATA32: {
1148 DataSym ds(sym.kind());
1149 llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
1150 ti = ds.Type;
1151 scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
1152 : eValueTypeVariableStatic;
1153 name = ds.Name;
1154 section = ds.Segment;
1155 offset = ds.DataOffset;
1156 addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
1157 break;
1158 }
1159 case S_GTHREAD32:
1160 is_external = true;
1161 LLVM_FALLTHROUGH;
1162 case S_LTHREAD32: {
1163 ThreadLocalDataSym tlds(sym.kind());
1164 llvm::cantFail(
1165 SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
1166 ti = tlds.Type;
1167 name = tlds.Name;
1168 section = tlds.Segment;
1169 offset = tlds.DataOffset;
1170 addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
1171 scope = eValueTypeVariableThreadLocal;
1172 break;
1173 }
1174 default:
1175 llvm_unreachable("unreachable!");
1176 }
1177
1178 CompUnitSP comp_unit;
1179 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
1180 if (modi) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001181 CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
Zachary Turner9f727952018-10-26 09:06:38 +00001182 comp_unit = GetOrCreateCompileUnit(cci);
1183 }
1184
1185 Declaration decl;
Zachary Turner9fbf9352018-11-16 03:16:27 +00001186 PdbTypeSymId tid(ti, false);
Zachary Turner9f727952018-10-26 09:06:38 +00001187 SymbolFileTypeSP type_sp =
Zachary Turner6284aee2018-11-16 02:42:32 +00001188 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
Zachary Turner9f727952018-10-26 09:06:38 +00001189 Variable::RangeList ranges;
1190
1191 DWARFExpression location = MakeGlobalLocationExpression(
1192 section, offset, GetObjectFile()->GetModule());
1193
1194 std::string global_name("::");
1195 global_name += name;
1196 VariableSP var_sp = std::make_shared<Variable>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001197 toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
Zachary Turner9f727952018-10-26 09:06:38 +00001198 scope, comp_unit.get(), ranges, &decl, location, is_external, false,
1199 false);
1200 var_sp->SetLocationIsConstantValueData(false);
1201
1202 return var_sp;
1203}
1204
Zachary Turner2af34162018-11-13 20:07:57 +00001205lldb::VariableSP
Zachary Turner6284aee2018-11-16 02:42:32 +00001206SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
Zachary Turner2af34162018-11-13 20:07:57 +00001207 const CVSymbol &cvs) {
1208 TpiStream &tpi = m_index->tpi();
1209 ConstantSym constant(cvs.kind());
1210
1211 llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
1212 std::string global_name("::");
1213 global_name += constant.Name;
Zachary Turner9fbf9352018-11-16 03:16:27 +00001214 PdbTypeSymId tid(constant.Type, false);
Zachary Turner2af34162018-11-13 20:07:57 +00001215 SymbolFileTypeSP type_sp =
Zachary Turner6284aee2018-11-16 02:42:32 +00001216 std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
Zachary Turner2af34162018-11-13 20:07:57 +00001217
1218 Declaration decl;
1219 Variable::RangeList ranges;
1220 ModuleSP module = GetObjectFile()->GetModule();
Zachary Turnera93458b2018-12-06 17:49:15 +00001221 DWARFExpression location = MakeConstantLocationExpression(
1222 constant.Type, tpi, constant.Value, module);
Zachary Turner2af34162018-11-13 20:07:57 +00001223
1224 VariableSP var_sp = std::make_shared<Variable>(
Zachary Turner6284aee2018-11-16 02:42:32 +00001225 toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
Zachary Turner2af34162018-11-13 20:07:57 +00001226 type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
1227 false, false, false);
1228 var_sp->SetLocationIsConstantValueData(true);
1229 return var_sp;
1230}
1231
Zachary Turner6284aee2018-11-16 02:42:32 +00001232VariableSP
1233SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
1234 auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
Zachary Turner9f727952018-10-26 09:06:38 +00001235 if (emplace_result.second)
Zachary Turner6284aee2018-11-16 02:42:32 +00001236 emplace_result.first->second = CreateGlobalVariable(var_id);
Zachary Turner9f727952018-10-26 09:06:38 +00001237
1238 return emplace_result.first->second;
1239}
1240
Zachary Turner6284aee2018-11-16 02:42:32 +00001241lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001242 return GetOrCreateType(PdbTypeSymId(ti, false));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001243}
1244
Zachary Turner6284aee2018-11-16 02:42:32 +00001245FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
Zachary Turner307f5ae2018-10-12 19:47:13 +00001246 const SymbolContext &sc) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001247 auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001248 if (emplace_result.second)
Zachary Turner6284aee2018-11-16 02:42:32 +00001249 emplace_result.first->second = CreateFunction(func_id, sc);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001250
1251 lldbassert(emplace_result.first->second);
1252 return emplace_result.first->second;
1253}
1254
1255CompUnitSP
1256SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001257
Zachary Turner307f5ae2018-10-12 19:47:13 +00001258 auto emplace_result =
Zachary Turner6284aee2018-11-16 02:42:32 +00001259 m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001260 if (emplace_result.second)
1261 emplace_result.first->second = CreateCompileUnit(cci);
1262
1263 lldbassert(emplace_result.first->second);
1264 return emplace_result.first->second;
1265}
1266
1267lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1268 if (index >= GetNumCompileUnits())
1269 return CompUnitSP();
1270 lldbassert(index < UINT16_MAX);
1271 if (index >= UINT16_MAX)
1272 return nullptr;
1273
1274 CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1275
1276 return GetOrCreateCompileUnit(item);
1277}
1278
Zachary Turnerb96181c2018-10-22 16:19:07 +00001279lldb::LanguageType
1280SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001281 // What fields should I expect to be filled out on the SymbolContext? Is it
1282 // safe to assume that `sc.comp_unit` is valid?
1283 if (!sc.comp_unit)
1284 return lldb::eLanguageTypeUnknown;
Zachary Turner6284aee2018-11-16 02:42:32 +00001285 PdbSymUid uid(sc.comp_unit->GetID());
1286 lldbassert(uid.kind() == PdbSymUidKind::Compiland);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001287
Zachary Turner6284aee2018-11-16 02:42:32 +00001288 CompilandIndexItem *item =
1289 m_index->compilands().GetCompiland(uid.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001290 lldbassert(item);
1291 if (!item->m_compile_opts)
1292 return lldb::eLanguageTypeUnknown;
1293
1294 return TranslateLanguage(item->m_compile_opts->getLanguage());
1295}
1296
Zachary Turnerb96181c2018-10-22 16:19:07 +00001297size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001298 lldbassert(sc.comp_unit);
1299 return false;
1300}
1301
1302static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1303 // If any of these flags are set, we need to resolve the compile unit.
1304 uint32_t flags = eSymbolContextCompUnit;
1305 flags |= eSymbolContextVariable;
1306 flags |= eSymbolContextFunction;
1307 flags |= eSymbolContextBlock;
1308 flags |= eSymbolContextLineEntry;
1309 return (resolve_scope & flags) != 0;
1310}
1311
Zachary Turner991e4452018-10-25 20:45:19 +00001312uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1313 const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001314 uint32_t resolved_flags = 0;
1315 lldb::addr_t file_addr = addr.GetFileAddress();
1316
1317 if (NeedsResolvedCompileUnit(resolve_scope)) {
1318 llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1319 if (!modi)
1320 return 0;
Zachary Turner6284aee2018-11-16 02:42:32 +00001321 CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001322 if (!cci)
1323 return 0;
1324
1325 sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
1326 resolved_flags |= eSymbolContextCompUnit;
1327 }
1328
1329 if (resolve_scope & eSymbolContextFunction) {
1330 lldbassert(sc.comp_unit);
1331 std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1332 for (const auto &match : matches) {
Zachary Turner6284aee2018-11-16 02:42:32 +00001333 if (match.uid.kind() != PdbSymUidKind::CompilandSym)
Zachary Turner307f5ae2018-10-12 19:47:13 +00001334 continue;
Zachary Turner6284aee2018-11-16 02:42:32 +00001335 PdbCompilandSymId csid = match.uid.asCompilandSym();
1336 CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1337 if (CVSymToPDBSym(cvs.kind()) != PDB_SymType::Function)
1338 continue;
1339 sc.function = GetOrCreateFunction(csid, sc).get();
Zachary Turner307f5ae2018-10-12 19:47:13 +00001340 }
1341 resolved_flags |= eSymbolContextFunction;
1342 }
1343
1344 if (resolve_scope & eSymbolContextLineEntry) {
1345 lldbassert(sc.comp_unit);
1346 if (auto *line_table = sc.comp_unit->GetLineTable()) {
1347 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1348 resolved_flags |= eSymbolContextLineEntry;
1349 }
1350 }
1351
1352 return resolved_flags;
1353}
1354
1355static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1356 const CompilandIndexItem &cci,
1357 lldb::addr_t base_addr,
1358 uint32_t file_number,
1359 const LineFragmentHeader &block,
1360 const LineNumberEntry &cur) {
1361 LineInfo cur_info(cur.Flags);
1362
1363 if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1364 return;
1365
1366 uint64_t addr = base_addr + cur.Offset;
1367
1368 bool is_statement = cur_info.isStatement();
1369 bool is_prologue = IsFunctionPrologue(cci, addr);
1370 bool is_epilogue = IsFunctionEpilogue(cci, addr);
1371
1372 uint32_t lno = cur_info.getStartLine();
1373
1374 table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1375 is_statement, false, is_prologue, is_epilogue,
1376 false);
1377}
1378
1379static void TerminateLineSequence(LineTable &table,
1380 const LineFragmentHeader &block,
1381 lldb::addr_t base_addr, uint32_t file_number,
1382 uint32_t last_line,
1383 std::unique_ptr<LineSequence> seq) {
1384 // The end is always a terminal entry, so insert it regardless.
1385 table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1386 last_line, 0, file_number, false, false,
1387 false, false, true);
1388 table.InsertSequence(seq.release());
1389}
1390
Zachary Turnerb96181c2018-10-22 16:19:07 +00001391bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001392 // Unfortunately LLDB is set up to parse the entire compile unit line table
1393 // all at once, even if all it really needs is line info for a specific
1394 // function. In the future it would be nice if it could set the sc.m_function
1395 // member, and we could only get the line info for the function in question.
1396 lldbassert(sc.comp_unit);
Zachary Turner6284aee2018-11-16 02:42:32 +00001397 PdbSymUid cu_id(sc.comp_unit->GetID());
1398 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1399 CompilandIndexItem *cci =
1400 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001401 lldbassert(cci);
1402 auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1403
1404 // This is basically a copy of the .debug$S subsections from all original COFF
1405 // object files merged together with address relocations applied. We are
1406 // looking for all DEBUG_S_LINES subsections.
1407 for (const DebugSubsectionRecord &dssr :
1408 cci->m_debug_stream.getSubsectionsArray()) {
1409 if (dssr.kind() != DebugSubsectionKind::Lines)
1410 continue;
1411
1412 DebugLinesSubsectionRef lines;
1413 llvm::BinaryStreamReader reader(dssr.getRecordData());
1414 if (auto EC = lines.initialize(reader)) {
1415 llvm::consumeError(std::move(EC));
1416 return false;
1417 }
1418
1419 const LineFragmentHeader *lfh = lines.header();
1420 uint64_t virtual_addr =
1421 m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1422
1423 const auto &checksums = cci->m_strings.checksums().getArray();
1424 const auto &strings = cci->m_strings.strings();
1425 for (const LineColumnEntry &group : lines) {
1426 // Indices in this structure are actually offsets of records in the
1427 // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index
1428 // into the global PDB string table.
1429 auto iter = checksums.at(group.NameIndex);
1430 if (iter == checksums.end())
1431 continue;
1432
1433 llvm::Expected<llvm::StringRef> efn =
1434 strings.getString(iter->FileNameOffset);
1435 if (!efn) {
1436 llvm::consumeError(efn.takeError());
1437 continue;
1438 }
1439
1440 // LLDB wants the index of the file in the list of support files.
1441 auto fn_iter = llvm::find(cci->m_file_list, *efn);
1442 lldbassert(fn_iter != cci->m_file_list.end());
1443 uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1444
1445 std::unique_ptr<LineSequence> sequence(
1446 line_table->CreateLineSequenceContainer());
1447 lldbassert(!group.LineNumbers.empty());
1448
1449 for (const LineNumberEntry &entry : group.LineNumbers) {
1450 AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1451 file_index, *lfh, entry);
1452 }
1453 LineInfo last_line(group.LineNumbers.back().Flags);
1454 TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1455 last_line.getEndLine(), std::move(sequence));
1456 }
1457 }
1458
1459 if (line_table->GetSize() == 0)
1460 return false;
1461
1462 sc.comp_unit->SetLineTable(line_table.release());
1463 return true;
1464}
1465
Zachary Turnerb96181c2018-10-22 16:19:07 +00001466bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001467 // PDB doesn't contain information about macros
1468 return false;
1469}
1470
1471bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001472 const SymbolContext &sc, FileSpecList &support_files) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001473 lldbassert(sc.comp_unit);
1474
Zachary Turner6284aee2018-11-16 02:42:32 +00001475 PdbSymUid cu_id(sc.comp_unit->GetID());
1476 lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1477 CompilandIndexItem *cci =
1478 m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001479 lldbassert(cci);
1480
1481 for (llvm::StringRef f : cci->m_file_list) {
1482 FileSpec::Style style =
1483 f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001484 FileSpec spec(f, style);
Zachary Turner307f5ae2018-10-12 19:47:13 +00001485 support_files.Append(spec);
1486 }
1487
1488 return true;
1489}
1490
1491bool SymbolFileNativePDB::ParseImportedModules(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001492 const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001493 // PDB does not yet support module debug info
1494 return false;
1495}
1496
Zachary Turnerb96181c2018-10-22 16:19:07 +00001497size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001498 lldbassert(sc.comp_unit && sc.function);
1499 return 0;
1500}
1501
Zachary Turner49110232018-11-05 17:40:28 +00001502void SymbolFileNativePDB::DumpClangAST(Stream &s) {
1503 if (!m_clang)
1504 return;
1505 m_clang->Dump(s);
1506}
1507
Zachary Turner9f727952018-10-26 09:06:38 +00001508uint32_t SymbolFileNativePDB::FindGlobalVariables(
1509 const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1510 uint32_t max_matches, VariableList &variables) {
1511 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1512
1513 std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1514 name.GetStringRef(), m_index->symrecords());
1515 for (const SymbolAndOffset &result : results) {
1516 VariableSP var;
1517 switch (result.second.kind()) {
1518 case SymbolKind::S_GDATA32:
1519 case SymbolKind::S_LDATA32:
1520 case SymbolKind::S_GTHREAD32:
Zachary Turner2af34162018-11-13 20:07:57 +00001521 case SymbolKind::S_LTHREAD32:
1522 case SymbolKind::S_CONSTANT: {
Zachary Turner9fbf9352018-11-16 03:16:27 +00001523 PdbGlobalSymId global(result.first, false);
Zachary Turner6284aee2018-11-16 02:42:32 +00001524 var = GetOrCreateGlobalVariable(global);
Zachary Turner9f727952018-10-26 09:06:38 +00001525 variables.AddVariable(var);
1526 break;
1527 }
1528 default:
1529 continue;
1530 }
1531 }
1532 return variables.GetSize();
1533}
1534
Zachary Turner307f5ae2018-10-12 19:47:13 +00001535uint32_t SymbolFileNativePDB::FindFunctions(
Zachary Turnerb96181c2018-10-22 16:19:07 +00001536 const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
Zachary Turner117b1fa2018-10-25 20:45:40 +00001537 FunctionNameType name_type_mask, bool include_inlines, bool append,
Zachary Turnerb96181c2018-10-22 16:19:07 +00001538 SymbolContextList &sc_list) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001539 // For now we only support lookup by method name.
1540 if (!(name_type_mask & eFunctionNameTypeMethod))
1541 return 0;
1542
1543 using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1544
1545 std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1546 name.GetStringRef(), m_index->symrecords());
1547 for (const SymbolAndOffset &match : matches) {
1548 if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1549 continue;
1550 ProcRefSym proc(match.second.kind());
1551 cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1552
1553 if (!IsValidRecord(proc))
1554 continue;
1555
Zachary Turner6284aee2018-11-16 02:42:32 +00001556 CompilandIndexItem &cci =
1557 m_index->compilands().GetOrCreateCompiland(proc.modi());
Zachary Turnerb96181c2018-10-22 16:19:07 +00001558 SymbolContext sc;
Zachary Turner307f5ae2018-10-12 19:47:13 +00001559
1560 sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1561 sc.module_sp = sc.comp_unit->GetModule();
Zachary Turner9fbf9352018-11-16 03:16:27 +00001562 PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
Zachary Turner6284aee2018-11-16 02:42:32 +00001563 sc.function = GetOrCreateFunction(func_id, sc).get();
Zachary Turner307f5ae2018-10-12 19:47:13 +00001564
1565 sc_list.Append(sc);
1566 }
1567
1568 return sc_list.GetSize();
1569}
1570
Zachary Turnerb96181c2018-10-22 16:19:07 +00001571uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1572 bool include_inlines, bool append,
1573 SymbolContextList &sc_list) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001574 return 0;
1575}
1576
Zachary Turnerb96181c2018-10-22 16:19:07 +00001577uint32_t SymbolFileNativePDB::FindTypes(
1578 const SymbolContext &sc, const ConstString &name,
1579 const CompilerDeclContext *parent_decl_ctx, bool append,
1580 uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1581 TypeMap &types) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001582 if (!append)
1583 types.Clear();
1584 if (!name)
1585 return 0;
1586
1587 searched_symbol_files.clear();
1588 searched_symbol_files.insert(this);
1589
1590 // There is an assumption 'name' is not a regex
1591 size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1592
1593 return match_count;
Zachary Turnerb96181c2018-10-22 16:19:07 +00001594}
1595
1596size_t
1597SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1598 bool append, TypeMap &types) {
1599 return 0;
1600}
1601
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001602size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1603 uint32_t max_matches,
1604 TypeMap &types) {
1605
1606 size_t match_count = 0;
1607 std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1608 if (max_matches > 0 && max_matches < matches.size())
1609 matches.resize(max_matches);
1610
1611 for (TypeIndex ti : matches) {
1612 TypeSP type = GetOrCreateType(ti);
1613 if (!type)
1614 continue;
1615
1616 types.Insert(type);
1617 ++match_count;
1618 }
1619 return match_count;
1620}
1621
Zachary Turnerb96181c2018-10-22 16:19:07 +00001622size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1623
Zachary Turnera42bbe32018-12-07 19:34:02 +00001624CompilerDeclContext
1625SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1626 // FIXME: This should look up the uid, decide if it's a symbol or a type, and
1627 // depending which it is, find the appropriate DeclContext. Possibilities:
1628 // For classes and typedefs:
1629 // * Function
1630 // * Namespace
1631 // * Global
1632 // * Block
1633 // * Class
1634 // For field list members:
1635 // * Class
1636 // For variables:
1637 // * Function
1638 // * Namespace
1639 // * Global
1640 // * Block
1641 // For functions:
1642 // * Namespace
1643 // * Global
1644 // * Class
1645 //
1646 // It is an error to call this function with a uid for any other symbol type.
1647 return {m_clang, m_clang->GetTranslationUnitDecl()};
1648}
1649
Zachary Turnerb96181c2018-10-22 16:19:07 +00001650Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001651 auto iter = m_types.find(type_uid);
1652 // lldb should not be passing us non-sensical type uids. the only way it
1653 // could have a type uid in the first place is if we handed it out, in which
Zachary Turner9f727952018-10-26 09:06:38 +00001654 // case we should know about the type. However, that doesn't mean we've
1655 // instantiated it yet. We can vend out a UID for a future type. So if the
1656 // type doesn't exist, let's instantiate it now.
1657 if (iter != m_types.end())
1658 return &*iter->second;
1659
Zachary Turner6284aee2018-11-16 02:42:32 +00001660 PdbSymUid uid(type_uid);
1661 lldbassert(uid.kind() == PdbSymUidKind::Type);
1662 PdbTypeSymId type_id = uid.asTypeSym();
1663 if (type_id.index.isNoneType())
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001664 return nullptr;
Zachary Turner9f727952018-10-26 09:06:38 +00001665
Zachary Turner6284aee2018-11-16 02:42:32 +00001666 TypeSP type_sp = CreateAndCacheType(type_id);
Zachary Turner9f727952018-10-26 09:06:38 +00001667 return &*type_sp;
Zachary Turnerb96181c2018-10-22 16:19:07 +00001668}
1669
Adrian Prantleca07c52018-11-05 20:49:07 +00001670llvm::Optional<SymbolFile::ArrayInfo>
1671SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1672 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1673 return llvm::None;
1674}
1675
1676
Zachary Turnerb96181c2018-10-22 16:19:07 +00001677bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001678 // If this is not in our map, it's an error.
1679 clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1680 lldbassert(tag_decl);
1681 auto status_iter = m_decl_to_status.find(tag_decl);
1682 lldbassert(status_iter != m_decl_to_status.end());
1683
1684 // If it's already complete, just return.
1685 DeclStatus &status = status_iter->second;
1686 if (status.status == Type::eResolveStateFull)
1687 return true;
1688
Zachary Turner6284aee2018-11-16 02:42:32 +00001689 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001690
Zachary Turner6284aee2018-11-16 02:42:32 +00001691 lldbassert(IsTagRecord(type_id, m_index->tpi()));
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001692
1693 ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
1694 false);
1695
1696 // In CreateAndCacheType, we already go out of our way to resolve forward
1697 // ref UDTs to full decls, and the uids we vend out always refer to full
1698 // decls if a full decl exists in the debug info. So if we don't have a full
1699 // decl here, it means one doesn't exist in the debug info, and we can't
1700 // complete the type.
1701 CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
1702 if (IsForwardRefUdt(cvt))
1703 return false;
1704
Zachary Turner6284aee2018-11-16 02:42:32 +00001705 auto types_iter = m_types.find(status.uid);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001706 lldbassert(types_iter != m_types.end());
1707
Zachary Turner511bff22018-10-30 18:57:08 +00001708 if (cvt.kind() == LF_MODIFIER) {
1709 TypeIndex unmodified_type = LookThroughModifierRecord(cvt);
1710 cvt = m_index->tpi().getType(unmodified_type);
1711 // LF_MODIFIERS usually point to forward decls, so this is the one case
1712 // where we won't have been able to resolve a forward decl to a full decl
1713 // earlier on. So we need to do that now.
1714 if (IsForwardRefUdt(cvt)) {
1715 llvm::Expected<TypeIndex> expected_full_ti =
1716 m_index->tpi().findFullDeclForForwardRef(unmodified_type);
1717 if (!expected_full_ti) {
1718 llvm::consumeError(expected_full_ti.takeError());
1719 return false;
1720 }
1721 cvt = m_index->tpi().getType(*expected_full_ti);
1722 lldbassert(!IsForwardRefUdt(cvt));
1723 unmodified_type = *expected_full_ti;
1724 }
Zachary Turner9fbf9352018-11-16 03:16:27 +00001725 type_id = PdbTypeSymId(unmodified_type, false);
Zachary Turner511bff22018-10-30 18:57:08 +00001726 }
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001727 TypeIndex field_list_ti = GetFieldListIndex(cvt);
1728 CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
1729 if (field_list_cvt.kind() != LF_FIELDLIST)
1730 return false;
1731
1732 // Visit all members of this class, then perform any finalization necessary
1733 // to complete the class.
Zachary Turner6284aee2018-11-16 02:42:32 +00001734 UdtRecordCompleter completer(type_id, compiler_type, *tag_decl, *this);
Zachary Turner2f7efbc2018-10-23 16:37:53 +00001735 auto error =
1736 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
1737 completer.complete();
1738
1739 status.status = Type::eResolveStateFull;
1740 if (!error)
1741 return true;
1742
1743 llvm::consumeError(std::move(error));
Zachary Turnerb96181c2018-10-22 16:19:07 +00001744 return false;
1745}
1746
1747size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
Zachary Turner117b1fa2018-10-25 20:45:40 +00001748 TypeClass type_mask,
Zachary Turnerb96181c2018-10-22 16:19:07 +00001749 lldb_private::TypeList &type_list) {
1750 return 0;
1751}
1752
1753CompilerDeclContext
1754SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
1755 const ConstString &name,
1756 const CompilerDeclContext *parent_decl_ctx) {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001757 return {};
1758}
1759
Zachary Turnerb96181c2018-10-22 16:19:07 +00001760TypeSystem *
Zachary Turner307f5ae2018-10-12 19:47:13 +00001761SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1762 auto type_system =
1763 m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1764 if (type_system)
1765 type_system->SetSymbolFile(this);
1766 return type_system;
1767}
1768
Zachary Turnerb96181c2018-10-22 16:19:07 +00001769ConstString SymbolFileNativePDB::GetPluginName() {
Zachary Turner307f5ae2018-10-12 19:47:13 +00001770 static ConstString g_name("pdb");
1771 return g_name;
1772}
1773
1774uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }