Coverage Report

Created: 2022-01-22 13:19

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