1 //===-- SymbolFilePDB.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 "SymbolFilePDB.h"
11
12 #include "PDBASTParser.h"
13 #include "PDBLocationToDWARFExpression.h"
14
15 #include "clang/Lex/Lexer.h"
16
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/CompileUnit.h"
21 #include "lldb/Symbol/LineTable.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Symbol/SymbolVendor.h"
25 #include "lldb/Symbol/TypeList.h"
26 #include "lldb/Symbol/TypeMap.h"
27 #include "lldb/Symbol/Variable.h"
28 #include "lldb/Utility/RegularExpression.h"
29
30 #include "llvm/DebugInfo/PDB/GenericError.h"
31 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
32 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
33 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
34 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
35 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
36 #include "llvm/DebugInfo/PDB/IPDBTable.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
43 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
44 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
45 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
46 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
47 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
48 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
49 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
50
51 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
52 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
53 #include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h"
54
55 #include <regex>
56
57 using namespace lldb;
58 using namespace lldb_private;
59 using namespace llvm::pdb;
60
61 namespace {
TranslateLanguage(PDB_Lang lang)62 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
63 switch (lang) {
64 case PDB_Lang::Cpp:
65 return lldb::LanguageType::eLanguageTypeC_plus_plus;
66 case PDB_Lang::C:
67 return lldb::LanguageType::eLanguageTypeC;
68 default:
69 return lldb::LanguageType::eLanguageTypeUnknown;
70 }
71 }
72
ShouldAddLine(uint32_t requested_line,uint32_t actual_line,uint32_t addr_length)73 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
74 uint32_t addr_length) {
75 return ((requested_line == 0 || actual_line == requested_line) &&
76 addr_length > 0);
77 }
78 } // namespace
79
ShouldUseNativeReader()80 static bool ShouldUseNativeReader() {
81 #if defined(_WIN32)
82 llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER");
83 return use_native.equals_lower("on") || use_native.equals_lower("yes") ||
84 use_native.equals_lower("1") || use_native.equals_lower("true");
85 #else
86 return true;
87 #endif
88 }
89
Initialize()90 void SymbolFilePDB::Initialize() {
91 if (ShouldUseNativeReader()) {
92 npdb::SymbolFileNativePDB::Initialize();
93 } else {
94 PluginManager::RegisterPlugin(GetPluginNameStatic(),
95 GetPluginDescriptionStatic(), CreateInstance,
96 DebuggerInitialize);
97 }
98 }
99
Terminate()100 void SymbolFilePDB::Terminate() {
101 if (ShouldUseNativeReader()) {
102 npdb::SymbolFileNativePDB::Terminate();
103 } else {
104 PluginManager::UnregisterPlugin(CreateInstance);
105 }
106 }
107
DebuggerInitialize(lldb_private::Debugger & debugger)108 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
109
GetPluginNameStatic()110 lldb_private::ConstString SymbolFilePDB::GetPluginNameStatic() {
111 static ConstString g_name("pdb");
112 return g_name;
113 }
114
GetPluginDescriptionStatic()115 const char *SymbolFilePDB::GetPluginDescriptionStatic() {
116 return "Microsoft PDB debug symbol file reader.";
117 }
118
119 lldb_private::SymbolFile *
CreateInstance(lldb_private::ObjectFile * obj_file)120 SymbolFilePDB::CreateInstance(lldb_private::ObjectFile *obj_file) {
121 return new SymbolFilePDB(obj_file);
122 }
123
SymbolFilePDB(lldb_private::ObjectFile * object_file)124 SymbolFilePDB::SymbolFilePDB(lldb_private::ObjectFile *object_file)
125 : SymbolFile(object_file), m_session_up(), m_global_scope_up(),
126 m_cached_compile_unit_count(0), m_tu_decl_ctx_up() {}
127
~SymbolFilePDB()128 SymbolFilePDB::~SymbolFilePDB() {}
129
CalculateAbilities()130 uint32_t SymbolFilePDB::CalculateAbilities() {
131 uint32_t abilities = 0;
132 if (!m_obj_file)
133 return 0;
134
135 if (!m_session_up) {
136 // Lazily load and match the PDB file, but only do this once.
137 std::string exePath = m_obj_file->GetFileSpec().GetPath();
138 auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
139 m_session_up);
140 if (error) {
141 llvm::consumeError(std::move(error));
142 auto module_sp = m_obj_file->GetModule();
143 if (!module_sp)
144 return 0;
145 // See if any symbol file is specified through `--symfile` option.
146 FileSpec symfile = module_sp->GetSymbolFileFileSpec();
147 if (!symfile)
148 return 0;
149 error = loadDataForPDB(PDB_ReaderType::DIA,
150 llvm::StringRef(symfile.GetPath()), m_session_up);
151 if (error) {
152 llvm::consumeError(std::move(error));
153 return 0;
154 }
155 }
156 }
157 if (!m_session_up)
158 return 0;
159
160 auto enum_tables_up = m_session_up->getEnumTables();
161 if (!enum_tables_up)
162 return 0;
163 while (auto table_up = enum_tables_up->getNext()) {
164 if (table_up->getItemCount() == 0)
165 continue;
166 auto type = table_up->getTableType();
167 switch (type) {
168 case PDB_TableType::Symbols:
169 // This table represents a store of symbols with types listed in
170 // PDBSym_Type
171 abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
172 LocalVariables | VariableTypes);
173 break;
174 case PDB_TableType::LineNumbers:
175 abilities |= LineTables;
176 break;
177 default:
178 break;
179 }
180 }
181 return abilities;
182 }
183
InitializeObject()184 void SymbolFilePDB::InitializeObject() {
185 lldb::addr_t obj_load_address = m_obj_file->GetFileOffset();
186 lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
187 m_session_up->setLoadAddress(obj_load_address);
188 if (!m_global_scope_up)
189 m_global_scope_up = m_session_up->getGlobalScope();
190 lldbassert(m_global_scope_up.get());
191
192 TypeSystem *type_system =
193 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
194 ClangASTContext *clang_type_system =
195 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
196 lldbassert(clang_type_system);
197 m_tu_decl_ctx_up = llvm::make_unique<CompilerDeclContext>(
198 type_system, clang_type_system->GetTranslationUnitDecl());
199 }
200
GetNumCompileUnits()201 uint32_t SymbolFilePDB::GetNumCompileUnits() {
202 if (m_cached_compile_unit_count == 0) {
203 auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
204 if (!compilands)
205 return 0;
206
207 // The linker could link *.dll (compiland language = LINK), or import
208 // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
209 // found as a child of the global scope (PDB executable). Usually, such
210 // compilands contain `thunk` symbols in which we are not interested for
211 // now. However we still count them in the compiland list. If we perform
212 // any compiland related activity, like finding symbols through
213 // llvm::pdb::IPDBSession methods, such compilands will all be searched
214 // automatically no matter whether we include them or not.
215 m_cached_compile_unit_count = compilands->getChildCount();
216
217 // The linker can inject an additional "dummy" compilation unit into the
218 // PDB. Ignore this special compile unit for our purposes, if it is there.
219 // It is always the last one.
220 auto last_compiland_up =
221 compilands->getChildAtIndex(m_cached_compile_unit_count - 1);
222 lldbassert(last_compiland_up.get());
223 std::string name = last_compiland_up->getName();
224 if (name == "* Linker *")
225 --m_cached_compile_unit_count;
226 }
227 return m_cached_compile_unit_count;
228 }
229
GetCompileUnitIndex(const llvm::pdb::PDBSymbolCompiland & pdb_compiland,uint32_t & index)230 void SymbolFilePDB::GetCompileUnitIndex(
231 const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
232 auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
233 if (!results_up)
234 return;
235 auto uid = pdb_compiland.getSymIndexId();
236 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
237 auto compiland_up = results_up->getChildAtIndex(cu_idx);
238 if (!compiland_up)
239 continue;
240 if (compiland_up->getSymIndexId() == uid) {
241 index = cu_idx;
242 return;
243 }
244 }
245 index = UINT32_MAX;
246 return;
247 }
248
249 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
GetPDBCompilandByUID(uint32_t uid)250 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
251 return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
252 }
253
ParseCompileUnitAtIndex(uint32_t index)254 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
255 if (index >= GetNumCompileUnits())
256 return CompUnitSP();
257
258 // Assuming we always retrieve same compilands listed in same order through
259 // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
260 // compile unit makes no sense.
261 auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
262 if (!results)
263 return CompUnitSP();
264 auto compiland_up = results->getChildAtIndex(index);
265 if (!compiland_up)
266 return CompUnitSP();
267 return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
268 }
269
ParseLanguage(CompileUnit & comp_unit)270 lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) {
271 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
272 if (!compiland_up)
273 return lldb::eLanguageTypeUnknown;
274 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
275 if (!details)
276 return lldb::eLanguageTypeUnknown;
277 return TranslateLanguage(details->getLanguage());
278 }
279
280 lldb_private::Function *
ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc & pdb_func,CompileUnit & comp_unit)281 SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func,
282 CompileUnit &comp_unit) {
283 if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId()))
284 return result.get();
285
286 auto file_vm_addr = pdb_func.getVirtualAddress();
287 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
288 return nullptr;
289
290 auto func_length = pdb_func.getLength();
291 AddressRange func_range =
292 AddressRange(file_vm_addr, func_length,
293 GetObjectFile()->GetModule()->GetSectionList());
294 if (!func_range.GetBaseAddress().IsValid())
295 return nullptr;
296
297 lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
298 if (!func_type)
299 return nullptr;
300
301 user_id_t func_type_uid = pdb_func.getSignatureId();
302
303 Mangled mangled = GetMangledForPDBFunc(pdb_func);
304
305 FunctionSP func_sp =
306 std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(),
307 func_type_uid, mangled, func_type, func_range);
308
309 comp_unit.AddFunction(func_sp);
310
311 TypeSystem *type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
312 if (!type_system)
313 return nullptr;
314 ClangASTContext *clang_type_system =
315 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
316 if (!clang_type_system)
317 return nullptr;
318 clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func);
319
320 return func_sp.get();
321 }
322
ParseFunctions(CompileUnit & comp_unit)323 size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) {
324 size_t func_added = 0;
325 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
326 if (!compiland_up)
327 return 0;
328 auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
329 if (!results_up)
330 return 0;
331 while (auto pdb_func_up = results_up->getNext()) {
332 auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId());
333 if (!func_sp) {
334 if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit))
335 ++func_added;
336 }
337 }
338 return func_added;
339 }
340
ParseLineTable(CompileUnit & comp_unit)341 bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) {
342 if (comp_unit.GetLineTable())
343 return true;
344 return ParseCompileUnitLineTable(comp_unit, 0);
345 }
346
ParseDebugMacros(CompileUnit & comp_unit)347 bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) {
348 // PDB doesn't contain information about macros
349 return false;
350 }
351
ParseSupportFiles(CompileUnit & comp_unit,lldb_private::FileSpecList & support_files)352 bool SymbolFilePDB::ParseSupportFiles(
353 CompileUnit &comp_unit, lldb_private::FileSpecList &support_files) {
354
355 // In theory this is unnecessary work for us, because all of this information
356 // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
357 // second time seems like a waste. Unfortunately, there's no good way around
358 // this short of a moderate refactor since SymbolVendor depends on being able
359 // to cache this list.
360 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
361 if (!compiland_up)
362 return false;
363 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
364 if (!files || files->getChildCount() == 0)
365 return false;
366
367 while (auto file = files->getNext()) {
368 FileSpec spec(file->getFileName(), FileSpec::Style::windows);
369 support_files.AppendIfUnique(spec);
370 }
371
372 // LLDB uses the DWARF-like file numeration (one based),
373 // the zeroth file is the compile unit itself
374 support_files.Insert(0, comp_unit);
375
376 return true;
377 }
378
ParseImportedModules(const lldb_private::SymbolContext & sc,std::vector<lldb_private::ConstString> & imported_modules)379 bool SymbolFilePDB::ParseImportedModules(
380 const lldb_private::SymbolContext &sc,
381 std::vector<lldb_private::ConstString> &imported_modules) {
382 // PDB does not yet support module debug info
383 return false;
384 }
385
ParseFunctionBlocksForPDBSymbol(uint64_t func_file_vm_addr,const llvm::pdb::PDBSymbol * pdb_symbol,lldb_private::Block * parent_block,bool is_top_parent)386 static size_t ParseFunctionBlocksForPDBSymbol(
387 uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol,
388 lldb_private::Block *parent_block, bool is_top_parent) {
389 assert(pdb_symbol && parent_block);
390
391 size_t num_added = 0;
392 switch (pdb_symbol->getSymTag()) {
393 case PDB_SymType::Block:
394 case PDB_SymType::Function: {
395 Block *block = nullptr;
396 auto &raw_sym = pdb_symbol->getRawSymbol();
397 if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {
398 if (pdb_func->hasNoInlineAttribute())
399 break;
400 if (is_top_parent)
401 block = parent_block;
402 else
403 break;
404 } else if (llvm::dyn_cast<PDBSymbolBlock>(pdb_symbol)) {
405 auto uid = pdb_symbol->getSymIndexId();
406 if (parent_block->FindBlockByID(uid))
407 break;
408 if (raw_sym.getVirtualAddress() < func_file_vm_addr)
409 break;
410
411 auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());
412 parent_block->AddChild(block_sp);
413 block = block_sp.get();
414 } else
415 llvm_unreachable("Unexpected PDB symbol!");
416
417 block->AddRange(Block::Range(
418 raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
419 block->FinalizeRanges();
420 ++num_added;
421
422 auto results_up = pdb_symbol->findAllChildren();
423 if (!results_up)
424 break;
425 while (auto symbol_up = results_up->getNext()) {
426 num_added += ParseFunctionBlocksForPDBSymbol(
427 func_file_vm_addr, symbol_up.get(), block, false);
428 }
429 } break;
430 default:
431 break;
432 }
433 return num_added;
434 }
435
ParseBlocksRecursive(Function & func)436 size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) {
437 size_t num_added = 0;
438 auto uid = func.GetID();
439 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
440 if (!pdb_func_up)
441 return 0;
442 Block &parent_block = func.GetBlock(false);
443 num_added = ParseFunctionBlocksForPDBSymbol(
444 pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true);
445 return num_added;
446 }
447
ParseTypes(CompileUnit & comp_unit)448 size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) {
449
450 size_t num_added = 0;
451 auto compiland = GetPDBCompilandByUID(comp_unit.GetID());
452 if (!compiland)
453 return 0;
454
455 auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
456 std::unique_ptr<IPDBEnumSymbols> results;
457 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
458 PDB_SymType::UDT};
459 for (auto tag : tags_to_search) {
460 results = raw_sym.findAllChildren(tag);
461 if (!results || results->getChildCount() == 0)
462 continue;
463 while (auto symbol = results->getNext()) {
464 switch (symbol->getSymTag()) {
465 case PDB_SymType::Enum:
466 case PDB_SymType::UDT:
467 case PDB_SymType::Typedef:
468 break;
469 default:
470 continue;
471 }
472
473 // This should cause the type to get cached and stored in the `m_types`
474 // lookup.
475 if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
476 // Resolve the type completely to avoid a completion
477 // (and so a list change, which causes an iterators invalidation)
478 // during a TypeList dumping
479 type->GetFullCompilerType();
480 ++num_added;
481 }
482 }
483 }
484 };
485
486 ParseTypesByTagFn(*compiland);
487
488 // Also parse global types particularly coming from this compiland.
489 // Unfortunately, PDB has no compiland information for each global type. We
490 // have to parse them all. But ensure we only do this once.
491 static bool parse_all_global_types = false;
492 if (!parse_all_global_types) {
493 ParseTypesByTagFn(*m_global_scope_up);
494 parse_all_global_types = true;
495 }
496 return num_added;
497 }
498
499 size_t
ParseVariablesForContext(const lldb_private::SymbolContext & sc)500 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
501 if (!sc.comp_unit)
502 return 0;
503
504 size_t num_added = 0;
505 if (sc.function) {
506 auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
507 sc.function->GetID());
508 if (!pdb_func)
509 return 0;
510
511 num_added += ParseVariables(sc, *pdb_func);
512 sc.function->GetBlock(false).SetDidParseVariables(true, true);
513 } else if (sc.comp_unit) {
514 auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
515 if (!compiland)
516 return 0;
517
518 if (sc.comp_unit->GetVariableList(false))
519 return 0;
520
521 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
522 if (results && results->getChildCount()) {
523 while (auto result = results->getNext()) {
524 auto cu_id = GetCompilandId(*result);
525 // FIXME: We are not able to determine variable's compile unit.
526 if (cu_id == 0)
527 continue;
528
529 if (cu_id == sc.comp_unit->GetID())
530 num_added += ParseVariables(sc, *result);
531 }
532 }
533
534 // FIXME: A `file static` or `global constant` variable appears both in
535 // compiland's children and global scope's children with unexpectedly
536 // different symbol's Id making it ambiguous.
537
538 // FIXME: 'local constant', for example, const char var[] = "abc", declared
539 // in a function scope, can't be found in PDB.
540
541 // Parse variables in this compiland.
542 num_added += ParseVariables(sc, *compiland);
543 }
544
545 return num_added;
546 }
547
ResolveTypeUID(lldb::user_id_t type_uid)548 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
549 auto find_result = m_types.find(type_uid);
550 if (find_result != m_types.end())
551 return find_result->second.get();
552
553 TypeSystem *type_system =
554 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
555 ClangASTContext *clang_type_system =
556 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
557 if (!clang_type_system)
558 return nullptr;
559 PDBASTParser *pdb = clang_type_system->GetPDBParser();
560 if (!pdb)
561 return nullptr;
562
563 auto pdb_type = m_session_up->getSymbolById(type_uid);
564 if (pdb_type == nullptr)
565 return nullptr;
566
567 lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
568 if (result) {
569 m_types.insert(std::make_pair(type_uid, result));
570 auto type_list = GetTypeList();
571 if (type_list)
572 type_list->Insert(result);
573 }
574 return result.get();
575 }
576
GetDynamicArrayInfoForUID(lldb::user_id_t type_uid,const lldb_private::ExecutionContext * exe_ctx)577 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
578 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
579 return llvm::None;
580 }
581
CompleteType(lldb_private::CompilerType & compiler_type)582 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
583 std::lock_guard<std::recursive_mutex> guard(
584 GetObjectFile()->GetModule()->GetMutex());
585
586 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
587 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
588 if (!clang_ast_ctx)
589 return false;
590
591 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
592 if (!pdb)
593 return false;
594
595 return pdb->CompleteTypeFromPDB(compiler_type);
596 }
597
GetDeclForUID(lldb::user_id_t uid)598 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
599 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
600 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
601 if (!clang_ast_ctx)
602 return CompilerDecl();
603
604 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
605 if (!pdb)
606 return CompilerDecl();
607
608 auto symbol = m_session_up->getSymbolById(uid);
609 if (!symbol)
610 return CompilerDecl();
611
612 auto decl = pdb->GetDeclForSymbol(*symbol);
613 if (!decl)
614 return CompilerDecl();
615
616 return CompilerDecl(clang_ast_ctx, decl);
617 }
618
619 lldb_private::CompilerDeclContext
GetDeclContextForUID(lldb::user_id_t uid)620 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
621 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
622 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
623 if (!clang_ast_ctx)
624 return CompilerDeclContext();
625
626 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
627 if (!pdb)
628 return CompilerDeclContext();
629
630 auto symbol = m_session_up->getSymbolById(uid);
631 if (!symbol)
632 return CompilerDeclContext();
633
634 auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
635 if (!decl_context)
636 return GetDeclContextContainingUID(uid);
637
638 return CompilerDeclContext(clang_ast_ctx, decl_context);
639 }
640
641 lldb_private::CompilerDeclContext
GetDeclContextContainingUID(lldb::user_id_t uid)642 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
643 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
644 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
645 if (!clang_ast_ctx)
646 return CompilerDeclContext();
647
648 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
649 if (!pdb)
650 return CompilerDeclContext();
651
652 auto symbol = m_session_up->getSymbolById(uid);
653 if (!symbol)
654 return CompilerDeclContext();
655
656 auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
657 assert(decl_context);
658
659 return CompilerDeclContext(clang_ast_ctx, decl_context);
660 }
661
ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx)662 void SymbolFilePDB::ParseDeclsForContext(
663 lldb_private::CompilerDeclContext decl_ctx) {
664 ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
665 GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
666 if (!clang_ast_ctx)
667 return;
668
669 PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
670 if (!pdb)
671 return;
672
673 pdb->ParseDeclsForDeclContext(
674 static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
675 }
676
677 uint32_t
ResolveSymbolContext(const lldb_private::Address & so_addr,SymbolContextItem resolve_scope,lldb_private::SymbolContext & sc)678 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
679 SymbolContextItem resolve_scope,
680 lldb_private::SymbolContext &sc) {
681 uint32_t resolved_flags = 0;
682 if (resolve_scope & eSymbolContextCompUnit ||
683 resolve_scope & eSymbolContextVariable ||
684 resolve_scope & eSymbolContextFunction ||
685 resolve_scope & eSymbolContextBlock ||
686 resolve_scope & eSymbolContextLineEntry) {
687 auto cu_sp = GetCompileUnitContainsAddress(so_addr);
688 if (!cu_sp) {
689 if (resolved_flags | eSymbolContextVariable) {
690 // TODO: Resolve variables
691 }
692 return 0;
693 }
694 sc.comp_unit = cu_sp.get();
695 resolved_flags |= eSymbolContextCompUnit;
696 lldbassert(sc.module_sp == cu_sp->GetModule());
697 }
698
699 if (resolve_scope & eSymbolContextFunction ||
700 resolve_scope & eSymbolContextBlock) {
701 addr_t file_vm_addr = so_addr.GetFileAddress();
702 auto symbol_up =
703 m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
704 if (symbol_up) {
705 auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
706 assert(pdb_func);
707 auto func_uid = pdb_func->getSymIndexId();
708 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
709 if (sc.function == nullptr)
710 sc.function =
711 ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit);
712 if (sc.function) {
713 resolved_flags |= eSymbolContextFunction;
714 if (resolve_scope & eSymbolContextBlock) {
715 auto block_symbol = m_session_up->findSymbolByAddress(
716 file_vm_addr, PDB_SymType::Block);
717 auto block_id = block_symbol ? block_symbol->getSymIndexId()
718 : sc.function->GetID();
719 sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
720 if (sc.block)
721 resolved_flags |= eSymbolContextBlock;
722 }
723 }
724 }
725 }
726
727 if (resolve_scope & eSymbolContextLineEntry) {
728 if (auto *line_table = sc.comp_unit->GetLineTable()) {
729 Address addr(so_addr);
730 if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
731 resolved_flags |= eSymbolContextLineEntry;
732 }
733 }
734
735 return resolved_flags;
736 }
737
ResolveSymbolContext(const lldb_private::FileSpec & file_spec,uint32_t line,bool check_inlines,SymbolContextItem resolve_scope,lldb_private::SymbolContextList & sc_list)738 uint32_t SymbolFilePDB::ResolveSymbolContext(
739 const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
740 SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
741 const size_t old_size = sc_list.GetSize();
742 if (resolve_scope & lldb::eSymbolContextCompUnit) {
743 // Locate all compilation units with line numbers referencing the specified
744 // file. For example, if `file_spec` is <vector>, then this should return
745 // all source files and header files that reference <vector>, either
746 // directly or indirectly.
747 auto compilands = m_session_up->findCompilandsForSourceFile(
748 file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
749
750 if (!compilands)
751 return 0;
752
753 // For each one, either find its previously parsed data or parse it afresh
754 // and add it to the symbol context list.
755 while (auto compiland = compilands->getNext()) {
756 // If we're not checking inlines, then don't add line information for
757 // this file unless the FileSpec matches. For inline functions, we don't
758 // have to match the FileSpec since they could be defined in headers
759 // other than file specified in FileSpec.
760 if (!check_inlines) {
761 std::string source_file = compiland->getSourceFileFullPath();
762 if (source_file.empty())
763 continue;
764 FileSpec this_spec(source_file, FileSpec::Style::windows);
765 bool need_full_match = !file_spec.GetDirectory().IsEmpty();
766 if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
767 continue;
768 }
769
770 SymbolContext sc;
771 auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
772 if (!cu)
773 continue;
774 sc.comp_unit = cu.get();
775 sc.module_sp = cu->GetModule();
776
777 // If we were asked to resolve line entries, add all entries to the line
778 // table that match the requested line (or all lines if `line` == 0).
779 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
780 eSymbolContextLineEntry)) {
781 bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line);
782
783 if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
784 // The query asks for line entries, but we can't get them for the
785 // compile unit. This is not normal for `line` = 0. So just assert
786 // it.
787 assert(line && "Couldn't get all line entries!\n");
788
789 // Current compiland does not have the requested line. Search next.
790 continue;
791 }
792
793 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
794 if (!has_line_table)
795 continue;
796
797 auto *line_table = sc.comp_unit->GetLineTable();
798 lldbassert(line_table);
799
800 uint32_t num_line_entries = line_table->GetSize();
801 // Skip the terminal line entry.
802 --num_line_entries;
803
804 // If `line `!= 0, see if we can resolve function for each line entry
805 // in the line table.
806 for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
807 ++line_idx) {
808 if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
809 continue;
810
811 auto file_vm_addr =
812 sc.line_entry.range.GetBaseAddress().GetFileAddress();
813 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
814 continue;
815
816 auto symbol_up = m_session_up->findSymbolByAddress(
817 file_vm_addr, PDB_SymType::Function);
818 if (symbol_up) {
819 auto func_uid = symbol_up->getSymIndexId();
820 sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
821 if (sc.function == nullptr) {
822 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
823 assert(pdb_func);
824 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func,
825 *sc.comp_unit);
826 }
827 if (sc.function && (resolve_scope & eSymbolContextBlock)) {
828 Block &block = sc.function->GetBlock(true);
829 sc.block = block.FindBlockByID(sc.function->GetID());
830 }
831 }
832 sc_list.Append(sc);
833 }
834 } else if (has_line_table) {
835 // We can parse line table for the compile unit. But no query to
836 // resolve function or block. We append `sc` to the list anyway.
837 sc_list.Append(sc);
838 }
839 } else {
840 // No query for line entry, function or block. But we have a valid
841 // compile unit, append `sc` to the list.
842 sc_list.Append(sc);
843 }
844 }
845 }
846 return sc_list.GetSize() - old_size;
847 }
848
GetMangledForPDBData(const PDBSymbolData & pdb_data)849 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
850 // Cache public names at first
851 if (m_public_names.empty())
852 if (auto result_up =
853 m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
854 while (auto symbol_up = result_up->getNext())
855 if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
856 m_public_names[addr] = symbol_up->getRawSymbol().getName();
857
858 // Look up the name in the cache
859 return m_public_names.lookup(pdb_data.getVirtualAddress());
860 }
861
ParseVariableForPDBData(const lldb_private::SymbolContext & sc,const llvm::pdb::PDBSymbolData & pdb_data)862 VariableSP SymbolFilePDB::ParseVariableForPDBData(
863 const lldb_private::SymbolContext &sc,
864 const llvm::pdb::PDBSymbolData &pdb_data) {
865 VariableSP var_sp;
866 uint32_t var_uid = pdb_data.getSymIndexId();
867 auto result = m_variables.find(var_uid);
868 if (result != m_variables.end())
869 return result->second;
870
871 ValueType scope = eValueTypeInvalid;
872 bool is_static_member = false;
873 bool is_external = false;
874 bool is_artificial = false;
875
876 switch (pdb_data.getDataKind()) {
877 case PDB_DataKind::Global:
878 scope = eValueTypeVariableGlobal;
879 is_external = true;
880 break;
881 case PDB_DataKind::Local:
882 scope = eValueTypeVariableLocal;
883 break;
884 case PDB_DataKind::FileStatic:
885 scope = eValueTypeVariableStatic;
886 break;
887 case PDB_DataKind::StaticMember:
888 is_static_member = true;
889 scope = eValueTypeVariableStatic;
890 break;
891 case PDB_DataKind::Member:
892 scope = eValueTypeVariableStatic;
893 break;
894 case PDB_DataKind::Param:
895 scope = eValueTypeVariableArgument;
896 break;
897 case PDB_DataKind::Constant:
898 scope = eValueTypeConstResult;
899 break;
900 default:
901 break;
902 }
903
904 switch (pdb_data.getLocationType()) {
905 case PDB_LocType::TLS:
906 scope = eValueTypeVariableThreadLocal;
907 break;
908 case PDB_LocType::RegRel: {
909 // It is a `this` pointer.
910 if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
911 scope = eValueTypeVariableArgument;
912 is_artificial = true;
913 }
914 } break;
915 default:
916 break;
917 }
918
919 Declaration decl;
920 if (!is_artificial && !pdb_data.isCompilerGenerated()) {
921 if (auto lines = pdb_data.getLineNumbers()) {
922 if (auto first_line = lines->getNext()) {
923 uint32_t src_file_id = first_line->getSourceFileId();
924 auto src_file = m_session_up->getSourceFileById(src_file_id);
925 if (src_file) {
926 FileSpec spec(src_file->getFileName());
927 decl.SetFile(spec);
928 decl.SetColumn(first_line->getColumnNumber());
929 decl.SetLine(first_line->getLineNumber());
930 }
931 }
932 }
933 }
934
935 Variable::RangeList ranges;
936 SymbolContextScope *context_scope = sc.comp_unit;
937 if (scope == eValueTypeVariableLocal) {
938 if (sc.function) {
939 context_scope = sc.function->GetBlock(true).FindBlockByID(
940 pdb_data.getLexicalParentId());
941 if (context_scope == nullptr)
942 context_scope = sc.function;
943 }
944 }
945
946 SymbolFileTypeSP type_sp =
947 std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
948
949 auto var_name = pdb_data.getName();
950 auto mangled = GetMangledForPDBData(pdb_data);
951 auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
952
953 bool is_constant;
954 DWARFExpression location = ConvertPDBLocationToDWARFExpression(
955 GetObjectFile()->GetModule(), pdb_data, is_constant);
956
957 var_sp = std::make_shared<Variable>(
958 var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
959 ranges, &decl, location, is_external, is_artificial, is_static_member);
960 var_sp->SetLocationIsConstantValueData(is_constant);
961
962 m_variables.insert(std::make_pair(var_uid, var_sp));
963 return var_sp;
964 }
965
966 size_t
ParseVariables(const lldb_private::SymbolContext & sc,const llvm::pdb::PDBSymbol & pdb_symbol,lldb_private::VariableList * variable_list)967 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
968 const llvm::pdb::PDBSymbol &pdb_symbol,
969 lldb_private::VariableList *variable_list) {
970 size_t num_added = 0;
971
972 if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
973 VariableListSP local_variable_list_sp;
974
975 auto result = m_variables.find(pdb_data->getSymIndexId());
976 if (result != m_variables.end()) {
977 if (variable_list)
978 variable_list->AddVariableIfUnique(result->second);
979 } else {
980 // Prepare right VariableList for this variable.
981 if (auto lexical_parent = pdb_data->getLexicalParent()) {
982 switch (lexical_parent->getSymTag()) {
983 case PDB_SymType::Exe:
984 assert(sc.comp_unit);
985 LLVM_FALLTHROUGH;
986 case PDB_SymType::Compiland: {
987 if (sc.comp_unit) {
988 local_variable_list_sp = sc.comp_unit->GetVariableList(false);
989 if (!local_variable_list_sp) {
990 local_variable_list_sp = std::make_shared<VariableList>();
991 sc.comp_unit->SetVariableList(local_variable_list_sp);
992 }
993 }
994 } break;
995 case PDB_SymType::Block:
996 case PDB_SymType::Function: {
997 if (sc.function) {
998 Block *block = sc.function->GetBlock(true).FindBlockByID(
999 lexical_parent->getSymIndexId());
1000 if (block) {
1001 local_variable_list_sp = block->GetBlockVariableList(false);
1002 if (!local_variable_list_sp) {
1003 local_variable_list_sp = std::make_shared<VariableList>();
1004 block->SetVariableList(local_variable_list_sp);
1005 }
1006 }
1007 }
1008 } break;
1009 default:
1010 break;
1011 }
1012 }
1013
1014 if (local_variable_list_sp) {
1015 if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1016 local_variable_list_sp->AddVariableIfUnique(var_sp);
1017 if (variable_list)
1018 variable_list->AddVariableIfUnique(var_sp);
1019 ++num_added;
1020 PDBASTParser *ast = GetPDBAstParser();
1021 if (ast)
1022 ast->GetDeclForSymbol(*pdb_data);
1023 }
1024 }
1025 }
1026 }
1027
1028 if (auto results = pdb_symbol.findAllChildren()) {
1029 while (auto result = results->getNext())
1030 num_added += ParseVariables(sc, *result, variable_list);
1031 }
1032
1033 return num_added;
1034 }
1035
FindGlobalVariables(const lldb_private::ConstString & name,const lldb_private::CompilerDeclContext * parent_decl_ctx,uint32_t max_matches,lldb_private::VariableList & variables)1036 uint32_t SymbolFilePDB::FindGlobalVariables(
1037 const lldb_private::ConstString &name,
1038 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1039 uint32_t max_matches, lldb_private::VariableList &variables) {
1040 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1041 return 0;
1042 if (name.IsEmpty())
1043 return 0;
1044
1045 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1046 if (!results)
1047 return 0;
1048
1049 uint32_t matches = 0;
1050 size_t old_size = variables.GetSize();
1051 while (auto result = results->getNext()) {
1052 auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1053 if (max_matches > 0 && matches >= max_matches)
1054 break;
1055
1056 SymbolContext sc;
1057 sc.module_sp = m_obj_file->GetModule();
1058 lldbassert(sc.module_sp.get());
1059
1060 if (!name.GetStringRef().equals(
1061 MSVCUndecoratedNameParser::DropScope(pdb_data->getName())))
1062 continue;
1063
1064 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1065 // FIXME: We are not able to determine the compile unit.
1066 if (sc.comp_unit == nullptr)
1067 continue;
1068
1069 if (parent_decl_ctx && GetDeclContextContainingUID(
1070 result->getSymIndexId()) != *parent_decl_ctx)
1071 continue;
1072
1073 ParseVariables(sc, *pdb_data, &variables);
1074 matches = variables.GetSize() - old_size;
1075 }
1076
1077 return matches;
1078 }
1079
1080 uint32_t
FindGlobalVariables(const lldb_private::RegularExpression & regex,uint32_t max_matches,lldb_private::VariableList & variables)1081 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression ®ex,
1082 uint32_t max_matches,
1083 lldb_private::VariableList &variables) {
1084 if (!regex.IsValid())
1085 return 0;
1086 auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1087 if (!results)
1088 return 0;
1089
1090 uint32_t matches = 0;
1091 size_t old_size = variables.GetSize();
1092 while (auto pdb_data = results->getNext()) {
1093 if (max_matches > 0 && matches >= max_matches)
1094 break;
1095
1096 auto var_name = pdb_data->getName();
1097 if (var_name.empty())
1098 continue;
1099 if (!regex.Execute(var_name))
1100 continue;
1101 SymbolContext sc;
1102 sc.module_sp = m_obj_file->GetModule();
1103 lldbassert(sc.module_sp.get());
1104
1105 sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1106 // FIXME: We are not able to determine the compile unit.
1107 if (sc.comp_unit == nullptr)
1108 continue;
1109
1110 ParseVariables(sc, *pdb_data, &variables);
1111 matches = variables.GetSize() - old_size;
1112 }
1113
1114 return matches;
1115 }
1116
ResolveFunction(const llvm::pdb::PDBSymbolFunc & pdb_func,bool include_inlines,lldb_private::SymbolContextList & sc_list)1117 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1118 bool include_inlines,
1119 lldb_private::SymbolContextList &sc_list) {
1120 lldb_private::SymbolContext sc;
1121 sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1122 if (!sc.comp_unit)
1123 return false;
1124 sc.module_sp = sc.comp_unit->GetModule();
1125 sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit);
1126 if (!sc.function)
1127 return false;
1128
1129 sc_list.Append(sc);
1130 return true;
1131 }
1132
ResolveFunction(uint32_t uid,bool include_inlines,lldb_private::SymbolContextList & sc_list)1133 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1134 lldb_private::SymbolContextList &sc_list) {
1135 auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1136 if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1137 return false;
1138 return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1139 }
1140
CacheFunctionNames()1141 void SymbolFilePDB::CacheFunctionNames() {
1142 if (!m_func_full_names.IsEmpty())
1143 return;
1144
1145 std::map<uint64_t, uint32_t> addr_ids;
1146
1147 if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1148 while (auto pdb_func_up = results_up->getNext()) {
1149 if (pdb_func_up->isCompilerGenerated())
1150 continue;
1151
1152 auto name = pdb_func_up->getName();
1153 auto demangled_name = pdb_func_up->getUndecoratedName();
1154 if (name.empty() && demangled_name.empty())
1155 continue;
1156
1157 auto uid = pdb_func_up->getSymIndexId();
1158 if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1159 addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1160
1161 if (auto parent = pdb_func_up->getClassParent()) {
1162
1163 // PDB have symbols for class/struct methods or static methods in Enum
1164 // Class. We won't bother to check if the parent is UDT or Enum here.
1165 m_func_method_names.Append(ConstString(name), uid);
1166
1167 // To search a method name, like NS::Class:MemberFunc, LLDB searches
1168 // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1169 // not have inforamtion of this, we extract base names and cache them
1170 // by our own effort.
1171 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1172 if (!basename.empty())
1173 m_func_base_names.Append(ConstString(basename), uid);
1174 else {
1175 m_func_base_names.Append(ConstString(name), uid);
1176 }
1177
1178 if (!demangled_name.empty())
1179 m_func_full_names.Append(ConstString(demangled_name), uid);
1180
1181 } else {
1182 // Handle not-method symbols.
1183
1184 // The function name might contain namespace, or its lexical scope.
1185 llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1186 if (!basename.empty())
1187 m_func_base_names.Append(ConstString(basename), uid);
1188 else
1189 m_func_base_names.Append(ConstString(name), uid);
1190
1191 if (name == "main") {
1192 m_func_full_names.Append(ConstString(name), uid);
1193
1194 if (!demangled_name.empty() && name != demangled_name) {
1195 m_func_full_names.Append(ConstString(demangled_name), uid);
1196 m_func_base_names.Append(ConstString(demangled_name), uid);
1197 }
1198 } else if (!demangled_name.empty()) {
1199 m_func_full_names.Append(ConstString(demangled_name), uid);
1200 } else {
1201 m_func_full_names.Append(ConstString(name), uid);
1202 }
1203 }
1204 }
1205 }
1206
1207 if (auto results_up =
1208 m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1209 while (auto pub_sym_up = results_up->getNext()) {
1210 if (!pub_sym_up->isFunction())
1211 continue;
1212 auto name = pub_sym_up->getName();
1213 if (name.empty())
1214 continue;
1215
1216 if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1217 auto vm_addr = pub_sym_up->getVirtualAddress();
1218
1219 // PDB public symbol has mangled name for its associated function.
1220 if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1221 // Cache mangled name.
1222 m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1223 }
1224 }
1225 }
1226 }
1227 // Sort them before value searching is working properly
1228 m_func_full_names.Sort();
1229 m_func_full_names.SizeToFit();
1230 m_func_method_names.Sort();
1231 m_func_method_names.SizeToFit();
1232 m_func_base_names.Sort();
1233 m_func_base_names.SizeToFit();
1234 }
1235
FindFunctions(const lldb_private::ConstString & name,const lldb_private::CompilerDeclContext * parent_decl_ctx,FunctionNameType name_type_mask,bool include_inlines,bool append,lldb_private::SymbolContextList & sc_list)1236 uint32_t SymbolFilePDB::FindFunctions(
1237 const lldb_private::ConstString &name,
1238 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1239 FunctionNameType name_type_mask, bool include_inlines, bool append,
1240 lldb_private::SymbolContextList &sc_list) {
1241 if (!append)
1242 sc_list.Clear();
1243 lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1244
1245 if (name_type_mask == eFunctionNameTypeNone)
1246 return 0;
1247 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1248 return 0;
1249 if (name.IsEmpty())
1250 return 0;
1251
1252 auto old_size = sc_list.GetSize();
1253 if (name_type_mask & eFunctionNameTypeFull ||
1254 name_type_mask & eFunctionNameTypeBase ||
1255 name_type_mask & eFunctionNameTypeMethod) {
1256 CacheFunctionNames();
1257
1258 std::set<uint32_t> resolved_ids;
1259 auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,
1260 &resolved_ids](UniqueCStringMap<uint32_t> &Names) {
1261 std::vector<uint32_t> ids;
1262 if (!Names.GetValues(name, ids))
1263 return;
1264
1265 for (uint32_t id : ids) {
1266 if (resolved_ids.find(id) != resolved_ids.end())
1267 continue;
1268
1269 if (parent_decl_ctx &&
1270 GetDeclContextContainingUID(id) != *parent_decl_ctx)
1271 continue;
1272
1273 if (ResolveFunction(id, include_inlines, sc_list))
1274 resolved_ids.insert(id);
1275 }
1276 };
1277 if (name_type_mask & eFunctionNameTypeFull) {
1278 ResolveFn(m_func_full_names);
1279 ResolveFn(m_func_base_names);
1280 ResolveFn(m_func_method_names);
1281 }
1282 if (name_type_mask & eFunctionNameTypeBase) {
1283 ResolveFn(m_func_base_names);
1284 }
1285 if (name_type_mask & eFunctionNameTypeMethod) {
1286 ResolveFn(m_func_method_names);
1287 }
1288 }
1289 return sc_list.GetSize() - old_size;
1290 }
1291
1292 uint32_t
FindFunctions(const lldb_private::RegularExpression & regex,bool include_inlines,bool append,lldb_private::SymbolContextList & sc_list)1293 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression ®ex,
1294 bool include_inlines, bool append,
1295 lldb_private::SymbolContextList &sc_list) {
1296 if (!append)
1297 sc_list.Clear();
1298 if (!regex.IsValid())
1299 return 0;
1300
1301 auto old_size = sc_list.GetSize();
1302 CacheFunctionNames();
1303
1304 std::set<uint32_t> resolved_ids;
1305 auto ResolveFn = [®ex, include_inlines, &sc_list, &resolved_ids,
1306 this](UniqueCStringMap<uint32_t> &Names) {
1307 std::vector<uint32_t> ids;
1308 if (Names.GetValues(regex, ids)) {
1309 for (auto id : ids) {
1310 if (resolved_ids.find(id) == resolved_ids.end())
1311 if (ResolveFunction(id, include_inlines, sc_list))
1312 resolved_ids.insert(id);
1313 }
1314 }
1315 };
1316 ResolveFn(m_func_full_names);
1317 ResolveFn(m_func_base_names);
1318
1319 return sc_list.GetSize() - old_size;
1320 }
1321
GetMangledNamesForFunction(const std::string & scope_qualified_name,std::vector<lldb_private::ConstString> & mangled_names)1322 void SymbolFilePDB::GetMangledNamesForFunction(
1323 const std::string &scope_qualified_name,
1324 std::vector<lldb_private::ConstString> &mangled_names) {}
1325
AddSymbols(lldb_private::Symtab & symtab)1326 void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) {
1327 std::set<lldb::addr_t> sym_addresses;
1328 for (size_t i = 0; i < symtab.GetNumSymbols(); i++)
1329 sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());
1330
1331 auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();
1332 if (!results)
1333 return;
1334
1335 auto section_list = m_obj_file->GetSectionList();
1336 if (!section_list)
1337 return;
1338
1339 while (auto pub_symbol = results->getNext()) {
1340 auto section_idx = pub_symbol->getAddressSection() - 1;
1341 if (section_idx >= section_list->GetSize())
1342 continue;
1343
1344 auto section = section_list->GetSectionAtIndex(section_idx);
1345 if (!section)
1346 continue;
1347
1348 auto offset = pub_symbol->getAddressOffset();
1349
1350 auto file_addr = section->GetFileAddress() + offset;
1351 if (sym_addresses.find(file_addr) != sym_addresses.end())
1352 continue;
1353 sym_addresses.insert(file_addr);
1354
1355 auto size = pub_symbol->getLength();
1356 symtab.AddSymbol(
1357 Symbol(pub_symbol->getSymIndexId(), // symID
1358 pub_symbol->getName().c_str(), // name
1359 true, // name_is_mangled
1360 pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type
1361 true, // external
1362 false, // is_debug
1363 false, // is_trampoline
1364 false, // is_artificial
1365 section, // section_sp
1366 offset, // value
1367 size, // size
1368 size != 0, // size_is_valid
1369 false, // contains_linker_annotations
1370 0 // flags
1371 ));
1372 }
1373
1374 symtab.CalculateSymbolSizes();
1375 symtab.Finalize();
1376 }
1377
FindTypes(const lldb_private::ConstString & name,const lldb_private::CompilerDeclContext * parent_decl_ctx,bool append,uint32_t max_matches,llvm::DenseSet<lldb_private::SymbolFile * > & searched_symbol_files,lldb_private::TypeMap & types)1378 uint32_t SymbolFilePDB::FindTypes(
1379 const lldb_private::ConstString &name,
1380 const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1381 uint32_t max_matches,
1382 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1383 lldb_private::TypeMap &types) {
1384 if (!append)
1385 types.Clear();
1386 if (!name)
1387 return 0;
1388 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1389 return 0;
1390
1391 searched_symbol_files.clear();
1392 searched_symbol_files.insert(this);
1393
1394 // There is an assumption 'name' is not a regex
1395 FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1396
1397 return types.GetSize();
1398 }
1399
DumpClangAST(Stream & s)1400 void SymbolFilePDB::DumpClangAST(Stream &s) {
1401 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1402 auto clang = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1403 if (!clang)
1404 return;
1405 clang->Dump(s);
1406 }
1407
FindTypesByRegex(const lldb_private::RegularExpression & regex,uint32_t max_matches,lldb_private::TypeMap & types)1408 void SymbolFilePDB::FindTypesByRegex(
1409 const lldb_private::RegularExpression ®ex, uint32_t max_matches,
1410 lldb_private::TypeMap &types) {
1411 // When searching by regex, we need to go out of our way to limit the search
1412 // space as much as possible since this searches EVERYTHING in the PDB,
1413 // manually doing regex comparisons. PDB library isn't optimized for regex
1414 // searches or searches across multiple symbol types at the same time, so the
1415 // best we can do is to search enums, then typedefs, then classes one by one,
1416 // and do a regex comparison against each of them.
1417 PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1418 PDB_SymType::UDT};
1419 std::unique_ptr<IPDBEnumSymbols> results;
1420
1421 uint32_t matches = 0;
1422
1423 for (auto tag : tags_to_search) {
1424 results = m_global_scope_up->findAllChildren(tag);
1425 if (!results)
1426 continue;
1427
1428 while (auto result = results->getNext()) {
1429 if (max_matches > 0 && matches >= max_matches)
1430 break;
1431
1432 std::string type_name;
1433 if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1434 type_name = enum_type->getName();
1435 else if (auto typedef_type =
1436 llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1437 type_name = typedef_type->getName();
1438 else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1439 type_name = class_type->getName();
1440 else {
1441 // We're looking only for types that have names. Skip symbols, as well
1442 // as unnamed types such as arrays, pointers, etc.
1443 continue;
1444 }
1445
1446 if (!regex.Execute(type_name))
1447 continue;
1448
1449 // This should cause the type to get cached and stored in the `m_types`
1450 // lookup.
1451 if (!ResolveTypeUID(result->getSymIndexId()))
1452 continue;
1453
1454 auto iter = m_types.find(result->getSymIndexId());
1455 if (iter == m_types.end())
1456 continue;
1457 types.Insert(iter->second);
1458 ++matches;
1459 }
1460 }
1461 }
1462
FindTypesByName(llvm::StringRef name,const lldb_private::CompilerDeclContext * parent_decl_ctx,uint32_t max_matches,lldb_private::TypeMap & types)1463 void SymbolFilePDB::FindTypesByName(
1464 llvm::StringRef name,
1465 const lldb_private::CompilerDeclContext *parent_decl_ctx,
1466 uint32_t max_matches, lldb_private::TypeMap &types) {
1467 std::unique_ptr<IPDBEnumSymbols> results;
1468 if (name.empty())
1469 return;
1470 results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1471 if (!results)
1472 return;
1473
1474 uint32_t matches = 0;
1475
1476 while (auto result = results->getNext()) {
1477 if (max_matches > 0 && matches >= max_matches)
1478 break;
1479
1480 if (MSVCUndecoratedNameParser::DropScope(
1481 result->getRawSymbol().getName()) != name)
1482 continue;
1483
1484 switch (result->getSymTag()) {
1485 case PDB_SymType::Enum:
1486 case PDB_SymType::UDT:
1487 case PDB_SymType::Typedef:
1488 break;
1489 default:
1490 // We're looking only for types that have names. Skip symbols, as well
1491 // as unnamed types such as arrays, pointers, etc.
1492 continue;
1493 }
1494
1495 // This should cause the type to get cached and stored in the `m_types`
1496 // lookup.
1497 if (!ResolveTypeUID(result->getSymIndexId()))
1498 continue;
1499
1500 if (parent_decl_ctx && GetDeclContextContainingUID(
1501 result->getSymIndexId()) != *parent_decl_ctx)
1502 continue;
1503
1504 auto iter = m_types.find(result->getSymIndexId());
1505 if (iter == m_types.end())
1506 continue;
1507 types.Insert(iter->second);
1508 ++matches;
1509 }
1510 }
1511
FindTypes(const std::vector<lldb_private::CompilerContext> & contexts,bool append,lldb_private::TypeMap & types)1512 size_t SymbolFilePDB::FindTypes(
1513 const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1514 lldb_private::TypeMap &types) {
1515 return 0;
1516 }
1517
GetTypeList()1518 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1519 return m_obj_file->GetModule()->GetTypeList();
1520 }
1521
GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol & pdb_symbol,uint32_t type_mask,TypeCollection & type_collection)1522 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1523 uint32_t type_mask,
1524 TypeCollection &type_collection) {
1525 bool can_parse = false;
1526 switch (pdb_symbol.getSymTag()) {
1527 case PDB_SymType::ArrayType:
1528 can_parse = ((type_mask & eTypeClassArray) != 0);
1529 break;
1530 case PDB_SymType::BuiltinType:
1531 can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1532 break;
1533 case PDB_SymType::Enum:
1534 can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1535 break;
1536 case PDB_SymType::Function:
1537 case PDB_SymType::FunctionSig:
1538 can_parse = ((type_mask & eTypeClassFunction) != 0);
1539 break;
1540 case PDB_SymType::PointerType:
1541 can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1542 eTypeClassMemberPointer)) != 0);
1543 break;
1544 case PDB_SymType::Typedef:
1545 can_parse = ((type_mask & eTypeClassTypedef) != 0);
1546 break;
1547 case PDB_SymType::UDT: {
1548 auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1549 assert(udt);
1550 can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1551 ((type_mask & (eTypeClassClass | eTypeClassStruct |
1552 eTypeClassUnion)) != 0));
1553 } break;
1554 default:
1555 break;
1556 }
1557
1558 if (can_parse) {
1559 if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1560 auto result =
1561 std::find(type_collection.begin(), type_collection.end(), type);
1562 if (result == type_collection.end())
1563 type_collection.push_back(type);
1564 }
1565 }
1566
1567 auto results_up = pdb_symbol.findAllChildren();
1568 while (auto symbol_up = results_up->getNext())
1569 GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1570 }
1571
GetTypes(lldb_private::SymbolContextScope * sc_scope,TypeClass type_mask,lldb_private::TypeList & type_list)1572 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1573 TypeClass type_mask,
1574 lldb_private::TypeList &type_list) {
1575 TypeCollection type_collection;
1576 uint32_t old_size = type_list.GetSize();
1577 CompileUnit *cu =
1578 sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1579 if (cu) {
1580 auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1581 if (!compiland_up)
1582 return 0;
1583 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1584 } else {
1585 for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1586 auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1587 if (cu_sp) {
1588 if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1589 GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1590 }
1591 }
1592 }
1593
1594 for (auto type : type_collection) {
1595 type->GetForwardCompilerType();
1596 type_list.Insert(type->shared_from_this());
1597 }
1598 return type_list.GetSize() - old_size;
1599 }
1600
1601 lldb_private::TypeSystem *
GetTypeSystemForLanguage(lldb::LanguageType language)1602 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1603 auto type_system =
1604 m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1605 if (type_system)
1606 type_system->SetSymbolFile(this);
1607 return type_system;
1608 }
1609
GetPDBAstParser()1610 PDBASTParser *SymbolFilePDB::GetPDBAstParser() {
1611 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1612 auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1613 if (!clang_type_system)
1614 return nullptr;
1615
1616 return clang_type_system->GetPDBParser();
1617 }
1618
1619
FindNamespace(const lldb_private::ConstString & name,const lldb_private::CompilerDeclContext * parent_decl_ctx)1620 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1621 const lldb_private::ConstString &name,
1622 const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1623 auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1624 auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1625 if (!clang_type_system)
1626 return CompilerDeclContext();
1627
1628 PDBASTParser *pdb = clang_type_system->GetPDBParser();
1629 if (!pdb)
1630 return CompilerDeclContext();
1631
1632 clang::DeclContext *decl_context = nullptr;
1633 if (parent_decl_ctx)
1634 decl_context = static_cast<clang::DeclContext *>(
1635 parent_decl_ctx->GetOpaqueDeclContext());
1636
1637 auto namespace_decl =
1638 pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1639 if (!namespace_decl)
1640 return CompilerDeclContext();
1641
1642 return CompilerDeclContext(type_system,
1643 static_cast<clang::DeclContext *>(namespace_decl));
1644 }
1645
GetPluginName()1646 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1647 static ConstString g_name("pdb");
1648 return g_name;
1649 }
1650
GetPluginVersion()1651 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1652
GetPDBSession()1653 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1654
GetPDBSession() const1655 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1656 return *m_session_up;
1657 }
1658
ParseCompileUnitForUID(uint32_t id,uint32_t index)1659 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1660 uint32_t index) {
1661 auto found_cu = m_comp_units.find(id);
1662 if (found_cu != m_comp_units.end())
1663 return found_cu->second;
1664
1665 auto compiland_up = GetPDBCompilandByUID(id);
1666 if (!compiland_up)
1667 return CompUnitSP();
1668
1669 lldb::LanguageType lang;
1670 auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1671 if (!details)
1672 lang = lldb::eLanguageTypeC_plus_plus;
1673 else
1674 lang = TranslateLanguage(details->getLanguage());
1675
1676 if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1677 return CompUnitSP();
1678
1679 std::string path = compiland_up->getSourceFileFullPath();
1680 if (path.empty())
1681 return CompUnitSP();
1682
1683 // Don't support optimized code for now, DebugInfoPDB does not return this
1684 // information.
1685 LazyBool optimized = eLazyBoolNo;
1686 auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1687 path.c_str(), id, lang, optimized);
1688
1689 if (!cu_sp)
1690 return CompUnitSP();
1691
1692 m_comp_units.insert(std::make_pair(id, cu_sp));
1693 if (index == UINT32_MAX)
1694 GetCompileUnitIndex(*compiland_up, index);
1695 lldbassert(index != UINT32_MAX);
1696 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1697 cu_sp);
1698 return cu_sp;
1699 }
1700
ParseCompileUnitLineTable(CompileUnit & comp_unit,uint32_t match_line)1701 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,
1702 uint32_t match_line) {
1703 auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1704 if (!compiland_up)
1705 return false;
1706
1707 // LineEntry needs the *index* of the file into the list of support files
1708 // returned by ParseCompileUnitSupportFiles. But the underlying SDK gives us
1709 // a globally unique idenfitifier in the namespace of the PDB. So, we have
1710 // to do a mapping so that we can hand out indices.
1711 llvm::DenseMap<uint32_t, uint32_t> index_map;
1712 BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1713 auto line_table = llvm::make_unique<LineTable>(&comp_unit);
1714
1715 // Find contributions to `compiland` from all source and header files.
1716 std::string path = comp_unit.GetPath();
1717 auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1718 if (!files)
1719 return false;
1720
1721 // For each source and header file, create a LineSequence for contributions
1722 // to the compiland from that file, and add the sequence.
1723 while (auto file = files->getNext()) {
1724 std::unique_ptr<LineSequence> sequence(
1725 line_table->CreateLineSequenceContainer());
1726 auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1727 if (!lines)
1728 continue;
1729 int entry_count = lines->getChildCount();
1730
1731 uint64_t prev_addr;
1732 uint32_t prev_length;
1733 uint32_t prev_line;
1734 uint32_t prev_source_idx;
1735
1736 for (int i = 0; i < entry_count; ++i) {
1737 auto line = lines->getChildAtIndex(i);
1738
1739 uint64_t lno = line->getLineNumber();
1740 uint64_t addr = line->getVirtualAddress();
1741 uint32_t length = line->getLength();
1742 uint32_t source_id = line->getSourceFileId();
1743 uint32_t col = line->getColumnNumber();
1744 uint32_t source_idx = index_map[source_id];
1745
1746 // There was a gap between the current entry and the previous entry if
1747 // the addresses don't perfectly line up.
1748 bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1749
1750 // Before inserting the current entry, insert a terminal entry at the end
1751 // of the previous entry's address range if the current entry resulted in
1752 // a gap from the previous entry.
1753 if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1754 line_table->AppendLineEntryToSequence(
1755 sequence.get(), prev_addr + prev_length, prev_line, 0,
1756 prev_source_idx, false, false, false, false, true);
1757
1758 line_table->InsertSequence(sequence.release());
1759 sequence.reset(line_table->CreateLineSequenceContainer());
1760 }
1761
1762 if (ShouldAddLine(match_line, lno, length)) {
1763 bool is_statement = line->isStatement();
1764 bool is_prologue = false;
1765 bool is_epilogue = false;
1766 auto func =
1767 m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1768 if (func) {
1769 auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1770 if (prologue)
1771 is_prologue = (addr == prologue->getVirtualAddress());
1772
1773 auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1774 if (epilogue)
1775 is_epilogue = (addr == epilogue->getVirtualAddress());
1776 }
1777
1778 line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1779 source_idx, is_statement, false,
1780 is_prologue, is_epilogue, false);
1781 }
1782
1783 prev_addr = addr;
1784 prev_length = length;
1785 prev_line = lno;
1786 prev_source_idx = source_idx;
1787 }
1788
1789 if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1790 // The end is always a terminal entry, so insert it regardless.
1791 line_table->AppendLineEntryToSequence(
1792 sequence.get(), prev_addr + prev_length, prev_line, 0,
1793 prev_source_idx, false, false, false, false, true);
1794 }
1795
1796 line_table->InsertSequence(sequence.release());
1797 }
1798
1799 if (line_table->GetSize()) {
1800 comp_unit.SetLineTable(line_table.release());
1801 return true;
1802 }
1803 return false;
1804 }
1805
BuildSupportFileIdToSupportFileIndexMap(const PDBSymbolCompiland & compiland,llvm::DenseMap<uint32_t,uint32_t> & index_map) const1806 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1807 const PDBSymbolCompiland &compiland,
1808 llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1809 // This is a hack, but we need to convert the source id into an index into
1810 // the support files array. We don't want to do path comparisons to avoid
1811 // basename / full path issues that may or may not even be a problem, so we
1812 // use the globally unique source file identifiers. Ideally we could use the
1813 // global identifiers everywhere, but LineEntry currently assumes indices.
1814 auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1815 if (!source_files)
1816 return;
1817
1818 // LLDB uses the DWARF-like file numeration (one based)
1819 int index = 1;
1820
1821 while (auto file = source_files->getNext()) {
1822 uint32_t source_id = file->getUniqueId();
1823 index_map[source_id] = index++;
1824 }
1825 }
1826
GetCompileUnitContainsAddress(const lldb_private::Address & so_addr)1827 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1828 const lldb_private::Address &so_addr) {
1829 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1830 if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1831 return nullptr;
1832
1833 // If it is a PDB function's vm addr, this is the first sure bet.
1834 if (auto lines =
1835 m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1836 if (auto first_line = lines->getNext())
1837 return ParseCompileUnitForUID(first_line->getCompilandId());
1838 }
1839
1840 // Otherwise we resort to section contributions.
1841 if (auto sec_contribs = m_session_up->getSectionContribs()) {
1842 while (auto section = sec_contribs->getNext()) {
1843 auto va = section->getVirtualAddress();
1844 if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1845 return ParseCompileUnitForUID(section->getCompilandId());
1846 }
1847 }
1848 return nullptr;
1849 }
1850
1851 Mangled
GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc & pdb_func)1852 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1853 Mangled mangled;
1854 auto func_name = pdb_func.getName();
1855 auto func_undecorated_name = pdb_func.getUndecoratedName();
1856 std::string func_decorated_name;
1857
1858 // Seek from public symbols for non-static function's decorated name if any.
1859 // For static functions, they don't have undecorated names and aren't exposed
1860 // in Public Symbols either.
1861 if (!func_undecorated_name.empty()) {
1862 auto result_up = m_global_scope_up->findChildren(
1863 PDB_SymType::PublicSymbol, func_undecorated_name,
1864 PDB_NameSearchFlags::NS_UndecoratedName);
1865 if (result_up) {
1866 while (auto symbol_up = result_up->getNext()) {
1867 // For a public symbol, it is unique.
1868 lldbassert(result_up->getChildCount() == 1);
1869 if (auto *pdb_public_sym =
1870 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1871 symbol_up.get())) {
1872 if (pdb_public_sym->isFunction()) {
1873 func_decorated_name = pdb_public_sym->getName();
1874 break;
1875 }
1876 }
1877 }
1878 }
1879 }
1880 if (!func_decorated_name.empty()) {
1881 mangled.SetMangledName(ConstString(func_decorated_name));
1882
1883 // For MSVC, format of C funciton's decorated name depends on calling
1884 // conventon. Unfortunately none of the format is recognized by current
1885 // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1886 // `__purecall` is retrieved as both its decorated and undecorated name
1887 // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1888 // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1889 // Mangled::GetDemangledName method will fail internally and caches an
1890 // empty string as its undecorated name. So we will face a contradition
1891 // here for the same symbol:
1892 // non-empty undecorated name from PDB
1893 // empty undecorated name from LLDB
1894 if (!func_undecorated_name.empty() &&
1895 mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1896 mangled.SetDemangledName(ConstString(func_undecorated_name));
1897
1898 // LLDB uses several flags to control how a C++ decorated name is
1899 // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1900 // yielded name could be different from what we retrieve from
1901 // PDB source unless we also apply same flags in getting undecorated
1902 // name through PDBSymbolFunc::getUndecoratedNameEx method.
1903 if (!func_undecorated_name.empty() &&
1904 mangled.GetDemangledName(mangled.GuessLanguage()) !=
1905 ConstString(func_undecorated_name))
1906 mangled.SetDemangledName(ConstString(func_undecorated_name));
1907 } else if (!func_undecorated_name.empty()) {
1908 mangled.SetDemangledName(ConstString(func_undecorated_name));
1909 } else if (!func_name.empty())
1910 mangled.SetValue(ConstString(func_name), false);
1911
1912 return mangled;
1913 }
1914
DeclContextMatchesThisSymbolFile(const lldb_private::CompilerDeclContext * decl_ctx)1915 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1916 const lldb_private::CompilerDeclContext *decl_ctx) {
1917 if (decl_ctx == nullptr || !decl_ctx->IsValid())
1918 return true;
1919
1920 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1921 if (!decl_ctx_type_system)
1922 return false;
1923 TypeSystem *type_system = GetTypeSystemForLanguage(
1924 decl_ctx_type_system->GetMinimumLanguage(nullptr));
1925 if (decl_ctx_type_system == type_system)
1926 return true; // The type systems match, return true
1927
1928 return false;
1929 }
1930
GetCompilandId(const llvm::pdb::PDBSymbolData & data)1931 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1932 static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1933 return lhs < rhs.Offset;
1934 };
1935
1936 // Cache section contributions
1937 if (m_sec_contribs.empty()) {
1938 if (auto SecContribs = m_session_up->getSectionContribs()) {
1939 while (auto SectionContrib = SecContribs->getNext()) {
1940 auto comp_id = SectionContrib->getCompilandId();
1941 if (!comp_id)
1942 continue;
1943
1944 auto sec = SectionContrib->getAddressSection();
1945 auto &sec_cs = m_sec_contribs[sec];
1946
1947 auto offset = SectionContrib->getAddressOffset();
1948 auto it =
1949 std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
1950
1951 auto size = SectionContrib->getLength();
1952 sec_cs.insert(it, {offset, size, comp_id});
1953 }
1954 }
1955 }
1956
1957 // Check by line number
1958 if (auto Lines = data.getLineNumbers()) {
1959 if (auto FirstLine = Lines->getNext())
1960 return FirstLine->getCompilandId();
1961 }
1962
1963 // Retrieve section + offset
1964 uint32_t DataSection = data.getAddressSection();
1965 uint32_t DataOffset = data.getAddressOffset();
1966 if (DataSection == 0) {
1967 if (auto RVA = data.getRelativeVirtualAddress())
1968 m_session_up->addressForRVA(RVA, DataSection, DataOffset);
1969 }
1970
1971 if (DataSection) {
1972 // Search by section contributions
1973 auto &sec_cs = m_sec_contribs[DataSection];
1974 auto it =
1975 std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
1976 if (it != sec_cs.begin()) {
1977 --it;
1978 if (DataOffset < it->Offset + it->Size)
1979 return it->CompilandId;
1980 }
1981 } else {
1982 // Search in lexical tree
1983 auto LexParentId = data.getLexicalParentId();
1984 while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
1985 if (LexParent->getSymTag() == PDB_SymType::Exe)
1986 break;
1987 if (LexParent->getSymTag() == PDB_SymType::Compiland)
1988 return LexParentId;
1989 LexParentId = LexParent->getRawSymbol().getLexicalParentId();
1990 }
1991 }
1992
1993 return 0;
1994 }
1995