Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Core/Module.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Module.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 "lldb/Core/Module.h"
10
11
#include "lldb/Core/AddressRange.h"
12
#include "lldb/Core/AddressResolverFileLine.h"
13
#include "lldb/Core/DataFileCache.h"
14
#include "lldb/Core/Debugger.h"
15
#include "lldb/Core/Mangled.h"
16
#include "lldb/Core/ModuleSpec.h"
17
#include "lldb/Core/SearchFilter.h"
18
#include "lldb/Core/Section.h"
19
#include "lldb/Host/FileSystem.h"
20
#include "lldb/Host/Host.h"
21
#include "lldb/Host/HostInfo.h"
22
#include "lldb/Interpreter/CommandInterpreter.h"
23
#include "lldb/Interpreter/ScriptInterpreter.h"
24
#include "lldb/Symbol/CompileUnit.h"
25
#include "lldb/Symbol/Function.h"
26
#include "lldb/Symbol/ObjectFile.h"
27
#include "lldb/Symbol/Symbol.h"
28
#include "lldb/Symbol/SymbolContext.h"
29
#include "lldb/Symbol/SymbolFile.h"
30
#include "lldb/Symbol/SymbolLocator.h"
31
#include "lldb/Symbol/SymbolVendor.h"
32
#include "lldb/Symbol/Symtab.h"
33
#include "lldb/Symbol/Type.h"
34
#include "lldb/Symbol/TypeList.h"
35
#include "lldb/Symbol/TypeMap.h"
36
#include "lldb/Symbol/TypeSystem.h"
37
#include "lldb/Target/Language.h"
38
#include "lldb/Target/Process.h"
39
#include "lldb/Target/Target.h"
40
#include "lldb/Utility/DataBufferHeap.h"
41
#include "lldb/Utility/FileSpecList.h"
42
#include "lldb/Utility/LLDBAssert.h"
43
#include "lldb/Utility/LLDBLog.h"
44
#include "lldb/Utility/Log.h"
45
#include "lldb/Utility/RegularExpression.h"
46
#include "lldb/Utility/Status.h"
47
#include "lldb/Utility/Stream.h"
48
#include "lldb/Utility/StreamString.h"
49
#include "lldb/Utility/Timer.h"
50
51
#if defined(_WIN32)
52
#include "lldb/Host/windows/PosixApi.h"
53
#endif
54
55
#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
56
#include "Plugins/Language/ObjC/ObjCLanguage.h"
57
58
#include "llvm/ADT/STLExtras.h"
59
#include "llvm/Support/Compiler.h"
60
#include "llvm/Support/DJB.h"
61
#include "llvm/Support/FileSystem.h"
62
#include "llvm/Support/FormatVariadic.h"
63
#include "llvm/Support/JSON.h"
64
#include "llvm/Support/Signals.h"
65
#include "llvm/Support/raw_ostream.h"
66
67
#include <cassert>
68
#include <cinttypes>
69
#include <cstdarg>
70
#include <cstdint>
71
#include <cstring>
72
#include <map>
73
#include <optional>
74
#include <type_traits>
75
#include <utility>
76
77
namespace lldb_private {
78
class CompilerDeclContext;
79
}
80
namespace lldb_private {
81
class VariableList;
82
}
83
84
using namespace lldb;
85
using namespace lldb_private;
86
87
// Shared pointers to modules track module lifetimes in targets and in the
88
// global module, but this collection will track all module objects that are
89
// still alive
90
typedef std::vector<Module *> ModuleCollection;
91
92
243k
static ModuleCollection &GetModuleCollection() {
93
  // This module collection needs to live past any module, so we could either
94
  // make it a shared pointer in each module or just leak is.  Since it is only
95
  // an empty vector by the time all the modules have gone away, we just leak
96
  // it for now.  If we decide this is a big problem we can introduce a
97
  // Finalize method that will tear everything down in a predictable order.
98
99
243k
  static ModuleCollection *g_module_collection = nullptr;
100
243k
  if (g_module_collection == nullptr)
101
1.50k
    g_module_collection = new ModuleCollection();
102
103
243k
  return *g_module_collection;
104
243k
}
105
106
243k
std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() {
107
  // NOTE: The mutex below must be leaked since the global module list in
108
  // the ModuleList class will get torn at some point, and we can't know if it
109
  // will tear itself down before the "g_module_collection_mutex" below will.
110
  // So we leak a Mutex object below to safeguard against that
111
112
243k
  static std::recursive_mutex *g_module_collection_mutex = nullptr;
113
243k
  if (g_module_collection_mutex == nullptr)
114
1.50k
    g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
115
243k
  return *g_module_collection_mutex;
116
243k
}
117
118
3.32k
size_t Module::GetNumberAllocatedModules() {
119
3.32k
  std::lock_guard<std::recursive_mutex> guard(
120
3.32k
      GetAllocationModuleCollectionMutex());
121
3.32k
  return GetModuleCollection().size();
122
3.32k
}
123
124
4.89k
Module *Module::GetAllocatedModuleAtIndex(size_t idx) {
125
4.89k
  std::lock_guard<std::recursive_mutex> guard(
126
4.89k
      GetAllocationModuleCollectionMutex());
127
4.89k
  ModuleCollection &modules = GetModuleCollection();
128
4.89k
  if (idx < modules.size())
129
4.89k
    return modules[idx];
130
0
  return nullptr;
131
4.89k
}
132
133
Module::Module(const ModuleSpec &module_spec)
134
114k
    : m_file_has_changed(false), m_first_file_changed_log(false) {
135
  // Scope for locker below...
136
114k
  {
137
114k
    std::lock_guard<std::recursive_mutex> guard(
138
114k
        GetAllocationModuleCollectionMutex());
139
114k
    GetModuleCollection().push_back(this);
140
114k
  }
141
142
114k
  Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
143
114k
  if (log != nullptr)
144
0
    LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
145
114k
              static_cast<void *>(this),
146
114k
              module_spec.GetArchitecture().GetArchitectureName(),
147
114k
              module_spec.GetFileSpec().GetPath().c_str(),
148
114k
              module_spec.GetObjectName().IsEmpty() ? "" : "(",
149
114k
              module_spec.GetObjectName().AsCString(""),
150
114k
              module_spec.GetObjectName().IsEmpty() ? "" : ")");
151
152
114k
  auto data_sp = module_spec.GetData();
153
114k
  lldb::offset_t file_size = 0;
154
114k
  if (data_sp)
155
103k
    file_size = data_sp->GetByteSize();
156
157
  // First extract all module specifications from the file using the local file
158
  // path. If there are no specifications, then don't fill anything in
159
114k
  ModuleSpecList modules_specs;
160
114k
  if (ObjectFile::GetModuleSpecifications(
161
114k
          module_spec.GetFileSpec(), 0, file_size, modules_specs, data_sp) == 0)
162
1.01k
    return;
163
164
  // Now make sure that one of the module specifications matches what we just
165
  // extract. We might have a module specification that specifies a file
166
  // "/usr/lib/dyld" with UUID XXX, but we might have a local version of
167
  // "/usr/lib/dyld" that has
168
  // UUID YYY and we don't want those to match. If they don't match, just don't
169
  // fill any ivars in so we don't accidentally grab the wrong file later since
170
  // they don't match...
171
113k
  ModuleSpec matching_module_spec;
172
113k
  if (!modules_specs.FindMatchingModuleSpec(module_spec,
173
113k
                                            matching_module_spec)) {
174
32
    if (log) {
175
0
      LLDB_LOGF(log, "Found local object file but the specs didn't match");
176
0
    }
177
32
    return;
178
32
  }
179
180
  // Set m_data_sp if it was initially provided in the ModuleSpec. Note that
181
  // we cannot use the data_sp variable here, because it will have been
182
  // modified by GetModuleSpecifications().
183
113k
  if (auto module_spec_data_sp = module_spec.GetData()) {
184
103k
    m_data_sp = module_spec_data_sp;
185
103k
    m_mod_time = {};
186
103k
  } else {
187
9.54k
    if (module_spec.GetFileSpec())
188
9.54k
      m_mod_time =
189
9.54k
          FileSystem::Instance().GetModificationTime(module_spec.GetFileSpec());
190
0
    else if (matching_module_spec.GetFileSpec())
191
0
      m_mod_time = FileSystem::Instance().GetModificationTime(
192
0
          matching_module_spec.GetFileSpec());
193
9.54k
  }
194
195
  // Copy the architecture from the actual spec if we got one back, else use
196
  // the one that was specified
197
113k
  if (matching_module_spec.GetArchitecture().IsValid())
198
113k
    m_arch = matching_module_spec.GetArchitecture();
199
0
  else if (module_spec.GetArchitecture().IsValid())
200
0
    m_arch = module_spec.GetArchitecture();
201
202
  // Copy the file spec over and use the specified one (if there was one) so we
203
  // don't use a path that might have gotten resolved a path in
204
  // 'matching_module_spec'
205
113k
  if (module_spec.GetFileSpec())
206
113k
    m_file = module_spec.GetFileSpec();
207
45
  else if (matching_module_spec.GetFileSpec())
208
0
    m_file = matching_module_spec.GetFileSpec();
209
210
  // Copy the platform file spec over
211
113k
  if (module_spec.GetPlatformFileSpec())
212
28
    m_platform_file = module_spec.GetPlatformFileSpec();
213
113k
  else if (matching_module_spec.GetPlatformFileSpec())
214
0
    m_platform_file = matching_module_spec.GetPlatformFileSpec();
215
216
  // Copy the symbol file spec over
217
113k
  if (module_spec.GetSymbolFileSpec())
218
37
    m_symfile_spec = module_spec.GetSymbolFileSpec();
219
113k
  else if (matching_module_spec.GetSymbolFileSpec())
220
0
    m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
221
222
  // Copy the object name over
223
113k
  if (matching_module_spec.GetObjectName())
224
0
    m_object_name = matching_module_spec.GetObjectName();
225
113k
  else
226
113k
    m_object_name = module_spec.GetObjectName();
227
228
  // Always trust the object offset (file offset) and object modification time
229
  // (for mod time in a BSD static archive) of from the matching module
230
  // specification
231
113k
  m_object_offset = matching_module_spec.GetObjectOffset();
232
113k
  m_object_mod_time = matching_module_spec.GetObjectModificationTime();
233
113k
}
234
235
Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
236
               ConstString object_name, lldb::offset_t object_offset,
237
               const llvm::sys::TimePoint<> &object_mod_time)
238
1.03k
    : m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
239
1.03k
      m_arch(arch), m_file(file_spec), m_object_name(object_name),
240
1.03k
      m_object_offset(object_offset), m_object_mod_time(object_mod_time),
241
1.03k
      m_file_has_changed(false), m_first_file_changed_log(false) {
242
  // Scope for locker below...
243
1.03k
  {
244
1.03k
    std::lock_guard<std::recursive_mutex> guard(
245
1.03k
        GetAllocationModuleCollectionMutex());
246
1.03k
    GetModuleCollection().push_back(this);
247
1.03k
  }
248
249
1.03k
  Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
250
1.03k
  if (log != nullptr)
251
0
    LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
252
1.03k
              static_cast<void *>(this), m_arch.GetArchitectureName(),
253
1.03k
              m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
254
1.03k
              m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
255
1.03k
}
256
257
4.87k
Module::Module() : m_file_has_changed(false), m_first_file_changed_log(false) {
258
4.87k
  std::lock_guard<std::recursive_mutex> guard(
259
4.87k
      GetAllocationModuleCollectionMutex());
260
4.87k
  GetModuleCollection().push_back(this);
261
4.87k
}
262
263
114k
Module::~Module() {
264
  // Lock our module down while we tear everything down to make sure we don't
265
  // get any access to the module while it is being destroyed
266
114k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
267
  // Scope for locker below...
268
114k
  {
269
114k
    std::lock_guard<std::recursive_mutex> guard(
270
114k
        GetAllocationModuleCollectionMutex());
271
114k
    ModuleCollection &modules = GetModuleCollection();
272
114k
    ModuleCollection::iterator end = modules.end();
273
114k
    ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
274
114k
    assert(pos != end);
275
114k
    modules.erase(pos);
276
114k
  }
277
0
  Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
278
114k
  if (log != nullptr)
279
0
    LLDB_LOGF(log, "%p Module::~Module((%s) '%s%s%s%s')",
280
114k
              static_cast<void *>(this), m_arch.GetArchitectureName(),
281
114k
              m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
282
114k
              m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
283
  // Release any auto pointers before we start tearing down our member
284
  // variables since the object file and symbol files might need to make
285
  // function calls back into this module object. The ordering is important
286
  // here because symbol files can require the module object file. So we tear
287
  // down the symbol file first, then the object file.
288
114k
  m_sections_up.reset();
289
114k
  m_symfile_up.reset();
290
114k
  m_objfile_sp.reset();
291
114k
}
292
293
ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
294
                                        lldb::addr_t header_addr, Status &error,
295
32
                                        size_t size_to_read) {
296
32
  if (m_objfile_sp) {
297
0
    error.SetErrorString("object file already exists");
298
32
  } else {
299
32
    std::lock_guard<std::recursive_mutex> guard(m_mutex);
300
32
    if (process_sp) {
301
32
      m_did_load_objfile = true;
302
32
      std::shared_ptr<DataBufferHeap> data_sp =
303
32
          std::make_shared<DataBufferHeap>(size_to_read, 0);
304
32
      Status readmem_error;
305
32
      const size_t bytes_read =
306
32
          process_sp->ReadMemory(header_addr, data_sp->GetBytes(),
307
32
                                 data_sp->GetByteSize(), readmem_error);
308
32
      if (bytes_read < size_to_read)
309
4
        data_sp->SetByteSize(bytes_read);
310
32
      if (data_sp->GetByteSize() > 0) {
311
30
        m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
312
30
                                              header_addr, data_sp);
313
30
        if (m_objfile_sp) {
314
30
          StreamString s;
315
30
          s.Printf("0x%16.16" PRIx64, header_addr);
316
30
          m_object_name.SetString(s.GetString());
317
318
          // Once we get the object file, update our module with the object
319
          // file's architecture since it might differ in vendor/os if some
320
          // parts were unknown.
321
30
          m_arch = m_objfile_sp->GetArchitecture();
322
323
          // Augment the arch with the target's information in case
324
          // we are unable to extract the os/environment from memory.
325
30
          m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture());
326
30
        } else {
327
0
          error.SetErrorString("unable to find suitable object file plug-in");
328
0
        }
329
30
      } else {
330
2
        error.SetErrorStringWithFormat("unable to read header from memory: %s",
331
2
                                       readmem_error.AsCString());
332
2
      }
333
32
    } else {
334
0
      error.SetErrorString("invalid process");
335
0
    }
336
32
  }
337
32
  return m_objfile_sp.get();
338
32
}
339
340
19.0M
const lldb_private::UUID &Module::GetUUID() {
341
19.0M
  if (!m_did_set_uuid.load()) {
342
114k
    std::lock_guard<std::recursive_mutex> guard(m_mutex);
343
114k
    if (!m_did_set_uuid.load()) {
344
114k
      ObjectFile *obj_file = GetObjectFile();
345
346
114k
      if (obj_file != nullptr) {
347
114k
        m_uuid = obj_file->GetUUID();
348
114k
        m_did_set_uuid = true;
349
114k
      }
350
114k
    }
351
114k
  }
352
19.0M
  return m_uuid;
353
19.0M
}
354
355
0
void Module::SetUUID(const lldb_private::UUID &uuid) {
356
0
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
357
0
  if (!m_did_set_uuid) {
358
0
    m_uuid = uuid;
359
0
    m_did_set_uuid = true;
360
0
  } else {
361
0
    lldbassert(0 && "Attempting to overwrite the existing module UUID");
362
0
  }
363
0
}
364
365
llvm::Expected<TypeSystemSP>
366
568k
Module::GetTypeSystemForLanguage(LanguageType language) {
367
568k
  return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
368
568k
}
369
370
void Module::ForEachTypeSystem(
371
957
    llvm::function_ref<bool(lldb::TypeSystemSP)> callback) {
372
957
  m_type_system_map.ForEach(callback);
373
957
}
374
375
20
void Module::ParseAllDebugSymbols() {
376
20
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
377
20
  size_t num_comp_units = GetNumCompileUnits();
378
20
  if (num_comp_units == 0)
379
6
    return;
380
381
14
  SymbolFile *symbols = GetSymbolFile();
382
383
36
  for (size_t cu_idx = 0; cu_idx < num_comp_units; 
cu_idx++22
) {
384
22
    SymbolContext sc;
385
22
    sc.module_sp = shared_from_this();
386
22
    sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
387
22
    if (!sc.comp_unit)
388
0
      continue;
389
390
22
    symbols->ParseVariablesForContext(sc);
391
392
22
    symbols->ParseFunctions(*sc.comp_unit);
393
394
22
    sc.comp_unit->ForeachFunction([&sc, &symbols](const FunctionSP &f) {
395
11
      symbols->ParseBlocksRecursive(*f);
396
397
      // Parse the variables for this function and all its blocks
398
11
      sc.function = f.get();
399
11
      symbols->ParseVariablesForContext(sc);
400
11
      return false;
401
11
    });
402
403
    // Parse all types for this compile unit
404
22
    symbols->ParseTypes(*sc.comp_unit);
405
22
  }
406
14
}
407
408
778k
void Module::CalculateSymbolContext(SymbolContext *sc) {
409
778k
  sc->module_sp = shared_from_this();
410
778k
}
411
412
12
ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
413
414
0
void Module::DumpSymbolContext(Stream *s) {
415
0
  s->Printf(", Module{%p}", static_cast<void *>(this));
416
0
}
417
418
229k
size_t Module::GetNumCompileUnits() {
419
229k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
420
229k
  if (SymbolFile *symbols = GetSymbolFile())
421
228k
    return symbols->GetNumCompileUnits();
422
1.04k
  return 0;
423
229k
}
424
425
9.03k
CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
426
9.03k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
427
9.03k
  size_t num_comp_units = GetNumCompileUnits();
428
9.03k
  CompUnitSP cu_sp;
429
430
9.03k
  if (index < num_comp_units) {
431
9.03k
    if (SymbolFile *symbols = GetSymbolFile())
432
9.03k
      cu_sp = symbols->GetCompileUnitAtIndex(index);
433
9.03k
  }
434
9.03k
  return cu_sp;
435
9.03k
}
436
437
10.1M
bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
438
10.1M
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
439
10.1M
  SectionList *section_list = GetSectionList();
440
10.1M
  if (section_list)
441
10.1M
    return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
442
13
  return false;
443
10.1M
}
444
445
uint32_t Module::ResolveSymbolContextForAddress(
446
    const Address &so_addr, lldb::SymbolContextItem resolve_scope,
447
3.29M
    SymbolContext &sc, bool resolve_tail_call_address) {
448
3.29M
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
449
3.29M
  uint32_t resolved_flags = 0;
450
451
  // Clear the result symbol context in case we don't find anything, but don't
452
  // clear the target
453
3.29M
  sc.Clear(false);
454
455
  // Get the section from the section/offset address.
456
3.29M
  SectionSP section_sp(so_addr.GetSection());
457
458
  // Make sure the section matches this module before we try and match anything
459
3.29M
  if (section_sp && 
section_sp->GetModule().get() == this3.29M
) {
460
    // If the section offset based address resolved itself, then this is the
461
    // right module.
462
3.29M
    sc.module_sp = shared_from_this();
463
3.29M
    resolved_flags |= eSymbolContextModule;
464
465
3.29M
    SymbolFile *symfile = GetSymbolFile();
466
3.29M
    if (!symfile)
467
177
      return resolved_flags;
468
469
    // Resolve the compile unit, function, block, line table or line entry if
470
    // requested.
471
3.29M
    if (resolve_scope & eSymbolContextCompUnit ||
472
3.29M
        
resolve_scope & eSymbolContextFunction2.08M
||
473
3.29M
        
resolve_scope & eSymbolContextBlock205k
||
474
3.29M
        
resolve_scope & eSymbolContextLineEntry27.3k
||
475
3.29M
        
resolve_scope & eSymbolContextVariable18.2k
) {
476
3.27M
      symfile->SetLoadDebugInfoEnabled();
477
3.27M
      resolved_flags |=
478
3.27M
          symfile->ResolveSymbolContext(so_addr, resolve_scope, sc);
479
3.27M
    }
480
481
    // Resolve the symbol if requested, but don't re-look it up if we've
482
    // already found it.
483
3.29M
    if (resolve_scope & eSymbolContextSymbol &&
484
3.29M
        
!(resolved_flags & eSymbolContextSymbol)2.90M
) {
485
394k
      Symtab *symtab = symfile->GetSymtab();
486
394k
      if (symtab && so_addr.IsSectionOffset()) {
487
394k
        Symbol *matching_symbol = nullptr;
488
489
394k
        symtab->ForEachSymbolContainingFileAddress(
490
394k
            so_addr.GetFileAddress(),
491
394k
            [&matching_symbol](Symbol *symbol) -> bool {
492
392k
              if (symbol->GetType() != eSymbolTypeInvalid) {
493
392k
                matching_symbol = symbol;
494
392k
                return false; // Stop iterating
495
392k
              }
496
107
              return true; // Keep iterating
497
392k
            });
498
394k
        sc.symbol = matching_symbol;
499
394k
        if (!sc.symbol && 
resolve_scope & eSymbolContextFunction1.63k
&&
500
394k
            
!(resolved_flags & eSymbolContextFunction)1.60k
) {
501
1.56k
          bool verify_unique = false; // No need to check again since
502
                                      // ResolveSymbolContext failed to find a
503
                                      // symbol at this address.
504
1.56k
          if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
505
1.56k
            sc.symbol =
506
1.56k
                obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
507
1.56k
        }
508
509
394k
        if (sc.symbol) {
510
392k
          if (sc.symbol->IsSynthetic()) {
511
            // We have a synthetic symbol so lets check if the object file from
512
            // the symbol file in the symbol vendor is different than the
513
            // object file for the module, and if so search its symbol table to
514
            // see if we can come up with a better symbol. For example dSYM
515
            // files on MacOSX have an unstripped symbol table inside of them.
516
112
            ObjectFile *symtab_objfile = symtab->GetObjectFile();
517
112
            if (symtab_objfile && symtab_objfile->IsStripped()) {
518
13
              ObjectFile *symfile_objfile = symfile->GetObjectFile();
519
13
              if (symfile_objfile != symtab_objfile) {
520
11
                Symtab *symfile_symtab = symfile_objfile->GetSymtab();
521
11
                if (symfile_symtab) {
522
11
                  Symbol *symbol =
523
11
                      symfile_symtab->FindSymbolContainingFileAddress(
524
11
                          so_addr.GetFileAddress());
525
11
                  if (symbol && !symbol->IsSynthetic()) {
526
11
                    sc.symbol = symbol;
527
11
                  }
528
11
                }
529
11
              }
530
13
            }
531
112
          }
532
392k
          resolved_flags |= eSymbolContextSymbol;
533
392k
        }
534
394k
      }
535
394k
    }
536
537
    // For function symbols, so_addr may be off by one.  This is a convention
538
    // consistent with FDE row indices in eh_frame sections, but requires extra
539
    // logic here to permit symbol lookup for disassembly and unwind.
540
3.29M
    if (resolve_scope & eSymbolContextSymbol &&
541
3.29M
        
!(resolved_flags & eSymbolContextSymbol)2.90M
&&
resolve_tail_call_address1.63k
&&
542
3.29M
        
so_addr.IsSectionOffset()1
) {
543
1
      Address previous_addr = so_addr;
544
1
      previous_addr.Slide(-1);
545
546
1
      bool do_resolve_tail_call_address = false; // prevent recursion
547
1
      const uint32_t flags = ResolveSymbolContextForAddress(
548
1
          previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
549
1
      if (flags & eSymbolContextSymbol) {
550
0
        AddressRange addr_range;
551
0
        if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
552
0
                               false, addr_range)) {
553
0
          if (addr_range.GetBaseAddress().GetSection() ==
554
0
              so_addr.GetSection()) {
555
            // If the requested address is one past the address range of a
556
            // function (i.e. a tail call), or the decremented address is the
557
            // start of a function (i.e. some forms of trampoline), indicate
558
            // that the symbol has been resolved.
559
0
            if (so_addr.GetOffset() ==
560
0
                    addr_range.GetBaseAddress().GetOffset() ||
561
0
                so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() +
562
0
                                           addr_range.GetByteSize()) {
563
0
              resolved_flags |= flags;
564
0
            }
565
0
          } else {
566
0
            sc.symbol =
567
0
                nullptr; // Don't trust the symbol if the sections didn't match.
568
0
          }
569
0
        }
570
0
      }
571
1
    }
572
3.29M
  }
573
3.29M
  return resolved_flags;
574
3.29M
}
575
576
uint32_t Module::ResolveSymbolContextForFilePath(
577
    const char *file_path, uint32_t line, bool check_inlines,
578
0
    lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
579
0
  FileSpec file_spec(file_path);
580
0
  return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
581
0
                                          resolve_scope, sc_list);
582
0
}
583
584
uint32_t Module::ResolveSymbolContextsForFileSpec(
585
    const FileSpec &file_spec, uint32_t line, bool check_inlines,
586
227
    lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
587
227
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
588
227
  LLDB_SCOPED_TIMERF("Module::ResolveSymbolContextForFilePath (%s:%u, "
589
227
                     "check_inlines = %s, resolve_scope = 0x%8.8x)",
590
227
                     file_spec.GetPath().c_str(), line,
591
227
                     check_inlines ? "yes" : "no", resolve_scope);
592
593
227
  const uint32_t initial_count = sc_list.GetSize();
594
595
227
  if (SymbolFile *symbols = GetSymbolFile()) {
596
    // TODO: Handle SourceLocationSpec column information
597
227
    SourceLocationSpec location_spec(file_spec, line, /*column=*/std::nullopt,
598
227
                                     check_inlines, /*exact_match=*/false);
599
600
227
    symbols->ResolveSymbolContext(location_spec, resolve_scope, sc_list);
601
227
  }
602
603
227
  return sc_list.GetSize() - initial_count;
604
227
}
605
606
void Module::FindGlobalVariables(ConstString name,
607
                                 const CompilerDeclContext &parent_decl_ctx,
608
140k
                                 size_t max_matches, VariableList &variables) {
609
140k
  if (SymbolFile *symbols = GetSymbolFile())
610
140k
    symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches, variables);
611
140k
}
612
613
void Module::FindGlobalVariables(const RegularExpression &regex,
614
172
                                 size_t max_matches, VariableList &variables) {
615
172
  SymbolFile *symbols = GetSymbolFile();
616
172
  if (symbols)
617
172
    symbols->FindGlobalVariables(regex, max_matches, variables);
618
172
}
619
620
void Module::FindCompileUnits(const FileSpec &path,
621
756
                              SymbolContextList &sc_list) {
622
756
  const size_t num_compile_units = GetNumCompileUnits();
623
756
  SymbolContext sc;
624
756
  sc.module_sp = shared_from_this();
625
786
  for (size_t i = 0; i < num_compile_units; 
++i30
) {
626
30
    sc.comp_unit = GetCompileUnitAtIndex(i).get();
627
30
    if (sc.comp_unit) {
628
30
      if (FileSpec::Match(path, sc.comp_unit->GetPrimaryFile()))
629
18
        sc_list.Append(sc);
630
30
    }
631
30
  }
632
756
}
633
634
Module::LookupInfo::LookupInfo(ConstString name,
635
                               FunctionNameType name_type_mask,
636
                               LanguageType language)
637
695k
    : m_name(name), m_lookup_name(), m_language(language) {
638
695k
  const char *name_cstr = name.GetCString();
639
695k
  llvm::StringRef basename;
640
695k
  llvm::StringRef context;
641
642
695k
  if (name_type_mask & eFunctionNameTypeAuto) {
643
18.3k
    if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
644
137
      m_name_type_mask = eFunctionNameTypeFull;
645
18.2k
    else if ((language == eLanguageTypeUnknown ||
646
18.2k
              
Language::LanguageIsObjC(language)20
) &&
647
18.2k
             
ObjCLanguage::IsPossibleObjCMethodName(name_cstr)18.2k
)
648
13.5k
      m_name_type_mask = eFunctionNameTypeFull;
649
4.64k
    else if (Language::LanguageIsC(language)) {
650
8
      m_name_type_mask = eFunctionNameTypeFull;
651
4.63k
    } else {
652
4.63k
      if ((language == eLanguageTypeUnknown ||
653
4.63k
           
Language::LanguageIsObjC(language)12
) &&
654
4.63k
          
ObjCLanguage::IsPossibleObjCSelector(name_cstr)4.63k
)
655
3.50k
        m_name_type_mask |= eFunctionNameTypeSelector;
656
657
4.63k
      CPlusPlusLanguage::MethodName cpp_method(name);
658
4.63k
      basename = cpp_method.GetBasename();
659
4.63k
      if (basename.empty()) {
660
4.61k
        if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
661
4.61k
                                                           basename))
662
3.23k
          m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
663
1.37k
        else
664
1.37k
          m_name_type_mask |= eFunctionNameTypeFull;
665
4.61k
      } else {
666
28
        m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
667
28
      }
668
4.63k
    }
669
677k
  } else {
670
677k
    m_name_type_mask = name_type_mask;
671
677k
    if (name_type_mask & eFunctionNameTypeMethod ||
672
677k
        
name_type_mask & eFunctionNameTypeBase677k
) {
673
      // If they've asked for a CPP method or function name and it can't be
674
      // that, we don't even need to search for CPP methods or names.
675
128k
      CPlusPlusLanguage::MethodName cpp_method(name);
676
128k
      if (cpp_method.IsValid()) {
677
0
        basename = cpp_method.GetBasename();
678
679
0
        if (!cpp_method.GetQualifiers().empty()) {
680
          // There is a "const" or other qualifier following the end of the
681
          // function parens, this can't be a eFunctionNameTypeBase
682
0
          m_name_type_mask &= ~(eFunctionNameTypeBase);
683
0
          if (m_name_type_mask == eFunctionNameTypeNone)
684
0
            return;
685
0
        }
686
128k
      } else {
687
        // If the CPP method parser didn't manage to chop this up, try to fill
688
        // in the base name if we can. If a::b::c is passed in, we need to just
689
        // look up "c", and then we'll filter the result later.
690
128k
        CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
691
128k
                                                       basename);
692
128k
      }
693
128k
    }
694
695
677k
    if (name_type_mask & eFunctionNameTypeSelector) {
696
9.46k
      if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
697
0
        m_name_type_mask &= ~(eFunctionNameTypeSelector);
698
0
        if (m_name_type_mask == eFunctionNameTypeNone)
699
0
          return;
700
0
      }
701
9.46k
    }
702
703
    // Still try and get a basename in case someone specifies a name type mask
704
    // of eFunctionNameTypeFull and a name like "A::func"
705
677k
    if (basename.empty()) {
706
548k
      if (name_type_mask & eFunctionNameTypeFull &&
707
548k
          
!CPlusPlusLanguage::IsCPPMangledName(name_cstr)539k
) {
708
528k
        CPlusPlusLanguage::MethodName cpp_method(name);
709
528k
        basename = cpp_method.GetBasename();
710
528k
        if (basename.empty())
711
528k
          CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
712
528k
                                                         basename);
713
528k
      }
714
548k
    }
715
677k
  }
716
717
695k
  if (!basename.empty()) {
718
    // The name supplied was a partial C++ path like "a::count". In this case
719
    // we want to do a lookup on the basename "count" and then make sure any
720
    // matching results contain "a::count" so that it would match "b::a::count"
721
    // and "a::count". This is why we set "match_name_after_lookup" to true
722
640k
    m_lookup_name.SetString(basename);
723
640k
    m_match_name_after_lookup = true;
724
640k
  } else {
725
    // The name is already correct, just use the exact name as supplied, and we
726
    // won't need to check if any matches contain "name"
727
54.8k
    m_lookup_name = name;
728
54.8k
    m_match_name_after_lookup = false;
729
54.8k
  }
730
695k
}
731
732
bool Module::LookupInfo::NameMatchesLookupInfo(
733
24.9k
    ConstString function_name, LanguageType language_type) const {
734
  // We always keep unnamed symbols
735
24.9k
  if (!function_name)
736
3
    return true;
737
738
  // If we match exactly, we can return early
739
24.9k
  if (m_name == function_name)
740
20.0k
    return true;
741
742
  // If function_name is mangled, we'll need to demangle it.
743
  // In the pathologial case where the function name "looks" mangled but is
744
  // actually demangled (e.g. a method named _Zonk), this operation should be
745
  // relatively inexpensive since no demangling is actually occuring. See
746
  // Mangled::SetValue for more context.
747
4.91k
  const bool function_name_may_be_mangled =
748
4.91k
      Mangled::GetManglingScheme(function_name) != Mangled::eManglingSchemeNone;
749
4.91k
  ConstString demangled_function_name = function_name;
750
4.91k
  if (function_name_may_be_mangled) {
751
919
    Mangled mangled_function_name(function_name);
752
919
    demangled_function_name = mangled_function_name.GetDemangledName();
753
919
  }
754
755
  // If the symbol has a language, then let the language make the match.
756
  // Otherwise just check that the demangled function name contains the
757
  // demangled user-provided name.
758
4.91k
  if (Language *language = Language::FindPlugin(language_type))
759
3.98k
    return language->DemangledNameContainsPath(m_name, demangled_function_name);
760
761
927
  llvm::StringRef function_name_ref = demangled_function_name;
762
927
  return function_name_ref.contains(m_name);
763
4.91k
}
764
765
void Module::LookupInfo::Prune(SymbolContextList &sc_list,
766
27.2k
                               size_t start_idx) const {
767
27.2k
  if (m_match_name_after_lookup && 
m_name12.1k
) {
768
12.1k
    SymbolContext sc;
769
12.1k
    size_t i = start_idx;
770
35.8k
    while (i < sc_list.GetSize()) {
771
23.7k
      if (!sc_list.GetContextAtIndex(i, sc))
772
0
        break;
773
774
23.7k
      bool keep_it =
775
23.7k
          NameMatchesLookupInfo(sc.GetFunctionName(), sc.GetLanguage());
776
23.7k
      if (keep_it)
777
23.4k
        ++i;
778
374
      else
779
374
        sc_list.RemoveContextAtIndex(i);
780
23.7k
    }
781
12.1k
  }
782
783
  // If we have only full name matches we might have tried to set breakpoint on
784
  // "func" and specified eFunctionNameTypeFull, but we might have found
785
  // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
786
  // "func()" and "func" should end up matching.
787
27.2k
  if (m_name_type_mask == eFunctionNameTypeFull) {
788
16.8k
    SymbolContext sc;
789
16.8k
    size_t i = start_idx;
790
33.7k
    while (i < sc_list.GetSize()) {
791
16.9k
      if (!sc_list.GetContextAtIndex(i, sc))
792
0
        break;
793
      // Make sure the mangled and demangled names don't match before we try to
794
      // pull anything out
795
16.9k
      ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
796
16.9k
      ConstString full_name(sc.GetFunctionName());
797
16.9k
      if (mangled_name != m_name && 
full_name != m_name2.15k
) {
798
2.15k
        CPlusPlusLanguage::MethodName cpp_method(full_name);
799
2.15k
        if (cpp_method.IsValid()) {
800
2.15k
          if (cpp_method.GetContext().empty()) {
801
2.15k
            if (cpp_method.GetBasename().compare(m_name) != 0) {
802
0
              sc_list.RemoveContextAtIndex(i);
803
0
              continue;
804
0
            }
805
2.15k
          } else {
806
0
            std::string qualified_name;
807
0
            llvm::StringRef anon_prefix("(anonymous namespace)");
808
0
            if (cpp_method.GetContext() == anon_prefix)
809
0
              qualified_name = cpp_method.GetBasename().str();
810
0
            else
811
0
              qualified_name = cpp_method.GetScopeQualifiedName();
812
0
            if (qualified_name != m_name.GetCString()) {
813
0
              sc_list.RemoveContextAtIndex(i);
814
0
              continue;
815
0
            }
816
0
          }
817
2.15k
        }
818
2.15k
      }
819
16.9k
      ++i;
820
16.9k
    }
821
16.8k
  }
822
27.2k
}
823
824
void Module::FindFunctions(const Module::LookupInfo &lookup_info,
825
                           const CompilerDeclContext &parent_decl_ctx,
826
                           const ModuleFunctionSearchOptions &options,
827
2.82M
                           SymbolContextList &sc_list) {
828
  // Find all the functions (not symbols, but debug information functions...
829
2.82M
  if (SymbolFile *symbols = GetSymbolFile()) {
830
2.78M
    symbols->FindFunctions(lookup_info, parent_decl_ctx,
831
2.78M
                           options.include_inlines, sc_list);
832
    // Now check our symbol table for symbols that are code symbols if
833
    // requested
834
2.78M
    if (options.include_symbols) {
835
2.75M
      if (Symtab *symtab = symbols->GetSymtab()) {
836
2.75M
        symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
837
2.75M
                                    lookup_info.GetNameTypeMask(), sc_list);
838
2.75M
      }
839
2.75M
    }
840
2.78M
  }
841
2.82M
}
842
843
void Module::FindFunctions(ConstString name,
844
                           const CompilerDeclContext &parent_decl_ctx,
845
                           FunctionNameType name_type_mask,
846
                           const ModuleFunctionSearchOptions &options,
847
666k
                           SymbolContextList &sc_list) {
848
666k
  const size_t old_size = sc_list.GetSize();
849
666k
  LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
850
666k
  FindFunctions(lookup_info, parent_decl_ctx, options, sc_list);
851
666k
  if (name_type_mask & eFunctionNameTypeAuto) {
852
340
    const size_t new_size = sc_list.GetSize();
853
340
    if (old_size < new_size)
854
54
      lookup_info.Prune(sc_list, old_size);
855
340
  }
856
666k
}
857
858
void Module::FindFunctions(const RegularExpression &regex,
859
                           const ModuleFunctionSearchOptions &options,
860
464
                           SymbolContextList &sc_list) {
861
464
  const size_t start_size = sc_list.GetSize();
862
863
464
  if (SymbolFile *symbols = GetSymbolFile()) {
864
464
    symbols->FindFunctions(regex, options.include_inlines, sc_list);
865
866
    // Now check our symbol table for symbols that are code symbols if
867
    // requested
868
464
    if (options.include_symbols) {
869
216
      Symtab *symtab = symbols->GetSymtab();
870
216
      if (symtab) {
871
216
        std::vector<uint32_t> symbol_indexes;
872
216
        symtab->AppendSymbolIndexesMatchingRegExAndType(
873
216
            regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
874
216
            symbol_indexes);
875
216
        const size_t num_matches = symbol_indexes.size();
876
216
        if (num_matches) {
877
16
          SymbolContext sc(this);
878
16
          const size_t end_functions_added_index = sc_list.GetSize();
879
16
          size_t num_functions_added_to_sc_list =
880
16
              end_functions_added_index - start_size;
881
16
          if (num_functions_added_to_sc_list == 0) {
882
            // No functions were added, just symbols, so we can just append
883
            // them
884
5
            for (size_t i = 0; i < num_matches; 
++i3
) {
885
3
              sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
886
3
              SymbolType sym_type = sc.symbol->GetType();
887
3
              if (sc.symbol && (sym_type == eSymbolTypeCode ||
888
3
                                
sym_type == eSymbolTypeResolver1
))
889
2
                sc_list.Append(sc);
890
3
            }
891
14
          } else {
892
14
            typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
893
14
            FileAddrToIndexMap file_addr_to_index;
894
41
            for (size_t i = start_size; i < end_functions_added_index; 
++i27
) {
895
27
              const SymbolContext &sc = sc_list[i];
896
27
              if (sc.block)
897
0
                continue;
898
27
              file_addr_to_index[sc.function->GetAddressRange()
899
27
                                     .GetBaseAddress()
900
27
                                     .GetFileAddress()] = i;
901
27
            }
902
903
14
            FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
904
            // Functions were added so we need to merge symbols into any
905
            // existing function symbol contexts
906
42
            for (size_t i = start_size; i < num_matches; 
++i28
) {
907
28
              sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
908
28
              SymbolType sym_type = sc.symbol->GetType();
909
28
              if (sc.symbol && sc.symbol->ValueIsAddress() &&
910
28
                  (sym_type == eSymbolTypeCode ||
911
28
                   
sym_type == eSymbolTypeResolver1
)) {
912
27
                FileAddrToIndexMap::const_iterator pos =
913
27
                    file_addr_to_index.find(
914
27
                        sc.symbol->GetAddressRef().GetFileAddress());
915
27
                if (pos == end)
916
0
                  sc_list.Append(sc);
917
27
                else
918
27
                  sc_list[pos->second].symbol = sc.symbol;
919
27
              }
920
28
            }
921
14
          }
922
16
        }
923
216
      }
924
216
    }
925
464
  }
926
464
}
927
928
void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
929
                                  const FileSpec &file, uint32_t line,
930
                                  Function *function,
931
                                  std::vector<Address> &output_local,
932
904
                                  std::vector<Address> &output_extern) {
933
904
  SearchFilterByModule filter(target_sp, m_file);
934
935
  // TODO: Handle SourceLocationSpec column information
936
904
  SourceLocationSpec location_spec(file, line, /*column=*/std::nullopt,
937
904
                                   /*check_inlines=*/true,
938
904
                                   /*exact_match=*/false);
939
904
  AddressResolverFileLine resolver(location_spec);
940
904
  resolver.ResolveAddress(filter);
941
942
978
  for (size_t n = 0; n < resolver.GetNumberOfAddresses(); 
n++74
) {
943
74
    Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
944
74
    Function *f = addr.CalculateSymbolContextFunction();
945
74
    if (f && f == function)
946
48
      output_local.push_back(addr);
947
26
    else
948
26
      output_extern.push_back(addr);
949
74
  }
950
904
}
951
952
void Module::FindTypes_Impl(
953
    ConstString name, const CompilerDeclContext &parent_decl_ctx,
954
    size_t max_matches,
955
    llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
956
461k
    TypeMap &types) {
957
461k
  if (SymbolFile *symbols = GetSymbolFile())
958
461k
    symbols->FindTypes(name, parent_decl_ctx, max_matches,
959
461k
                       searched_symbol_files, types);
960
461k
}
961
962
void Module::FindTypesInNamespace(ConstString type_name,
963
                                  const CompilerDeclContext &parent_decl_ctx,
964
503
                                  size_t max_matches, TypeList &type_list) {
965
503
  TypeMap types_map;
966
503
  llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
967
503
  FindTypes_Impl(type_name, parent_decl_ctx, max_matches, searched_symbol_files,
968
503
                 types_map);
969
503
  if (types_map.GetSize()) {
970
106
    SymbolContext sc;
971
106
    sc.module_sp = shared_from_this();
972
106
    sc.SortTypeList(types_map, type_list);
973
106
  }
974
503
}
975
976
lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, ConstString name,
977
241
                                   bool exact_match) {
978
241
  TypeList type_list;
979
241
  llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
980
241
  FindTypes(name, exact_match, 1, searched_symbol_files, type_list);
981
241
  if (type_list.GetSize())
982
31
    return type_list.GetTypeAtIndex(0);
983
210
  return TypeSP();
984
241
}
985
986
void Module::FindTypes(
987
    ConstString name, bool exact_match, size_t max_matches,
988
    llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
989
461k
    TypeList &types) {
990
461k
  const char *type_name_cstr = name.GetCString();
991
461k
  llvm::StringRef type_scope;
992
461k
  llvm::StringRef type_basename;
993
461k
  TypeClass type_class = eTypeClassAny;
994
461k
  TypeMap typesmap;
995
996
461k
  if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
997
461k
                                    type_class)) {
998
    // Check if "name" starts with "::" which means the qualified type starts
999
    // from the root namespace and implies and exact match. The typenames we
1000
    // get back from clang do not start with "::" so we need to strip this off
1001
    // in order to get the qualified names to match
1002
1.43k
    exact_match = type_scope.consume_front("::");
1003
1004
1.43k
    ConstString type_basename_const_str(type_basename);
1005
1.43k
    FindTypes_Impl(type_basename_const_str, CompilerDeclContext(), max_matches,
1006
1.43k
                   searched_symbol_files, typesmap);
1007
1.43k
    if (typesmap.GetSize())
1008
77
      typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1009
77
                                     exact_match);
1010
459k
  } else {
1011
    // The type is not in a namespace/class scope, just search for it by
1012
    // basename
1013
459k
    if (type_class != eTypeClassAny && 
!type_basename.empty()126
) {
1014
      // The "type_name_cstr" will have been modified if we have a valid type
1015
      // class prefix (like "struct", "class", "union", "typedef" etc).
1016
126
      FindTypes_Impl(ConstString(type_basename), CompilerDeclContext(),
1017
126
                     UINT_MAX, searched_symbol_files, typesmap);
1018
126
      typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1019
126
                                     exact_match);
1020
459k
    } else {
1021
459k
      FindTypes_Impl(name, CompilerDeclContext(), UINT_MAX,
1022
459k
                     searched_symbol_files, typesmap);
1023
459k
      if (exact_match) {
1024
443k
        typesmap.RemoveMismatchedTypes(type_scope, name, type_class,
1025
443k
                                       exact_match);
1026
443k
      }
1027
459k
    }
1028
459k
  }
1029
461k
  if (typesmap.GetSize()) {
1030
938
    SymbolContext sc;
1031
938
    sc.module_sp = shared_from_this();
1032
938
    sc.SortTypeList(typesmap, types);
1033
938
  }
1034
461k
}
1035
1036
void Module::FindTypes(
1037
    llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1038
    llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1039
826
    TypeMap &types) {
1040
  // If a scoped timer is needed, place it in a SymbolFile::FindTypes override.
1041
  // A timer here is too high volume for some cases, for example when calling
1042
  // FindTypes on each object file.
1043
826
  if (SymbolFile *symbols = GetSymbolFile())
1044
826
    symbols->FindTypes(pattern, languages, searched_symbol_files, types);
1045
826
}
1046
1047
static Debugger::DebuggerList 
1048
118k
DebuggersOwningModuleRequestingInterruption(Module &module) {
1049
118k
  Debugger::DebuggerList requestors 
1050
118k
      = Debugger::DebuggersRequestingInterruption();
1051
118k
  Debugger::DebuggerList interruptors;
1052
118k
  if (requestors.empty())
1053
118k
    return interruptors;
1054
    
1055
0
  for (auto debugger_sp : requestors) {
1056
0
    if (!debugger_sp->InterruptRequested())
1057
0
      continue;
1058
0
    if (debugger_sp->GetTargetList()
1059
0
        .AnyTargetContainsModule(module))
1060
0
      interruptors.push_back(debugger_sp);
1061
0
  }
1062
0
  return interruptors;
1063
118k
}
1064
1065
11.4M
SymbolFile *Module::GetSymbolFile(bool can_create, Stream *feedback_strm) {
1066
11.4M
  if (!m_did_load_symfile.load()) {
1067
118k
    std::lock_guard<std::recursive_mutex> guard(m_mutex);
1068
118k
    if (!m_did_load_symfile.load() && 
can_create118k
) {
1069
118k
      Debugger::DebuggerList interruptors 
1070
118k
          = DebuggersOwningModuleRequestingInterruption(*this);
1071
118k
      if (!interruptors.empty()) {
1072
0
        for (auto debugger_sp : interruptors) {
1073
0
          REPORT_INTERRUPTION(*(debugger_sp.get()), 
1074
0
                              "Interrupted fetching symbols for module {0}", 
1075
0
                              this->GetFileSpec());
1076
0
        }
1077
0
        return nullptr;
1078
0
      }
1079
118k
      ObjectFile *obj_file = GetObjectFile();
1080
118k
      if (obj_file != nullptr) {
1081
118k
        LLDB_SCOPED_TIMER();
1082
118k
        m_symfile_up.reset(
1083
118k
            SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1084
118k
        m_did_load_symfile = true;
1085
118k
      }
1086
118k
    }
1087
118k
  }
1088
18.4E
  
return 11.4M
m_symfile_up11.4M
?
m_symfile_up->GetSymbolFile()11.4M
: nullptr;
1089
11.4M
}
1090
1091
2.97M
Symtab *Module::GetSymtab() {
1092
2.97M
  if (SymbolFile *symbols = GetSymbolFile())
1093
2.93M
    return symbols->GetSymtab();
1094
39.3k
  return nullptr;
1095
2.97M
}
1096
1097
void Module::SetFileSpecAndObjectName(const FileSpec &file,
1098
4.70k
                                      ConstString object_name) {
1099
  // Container objects whose paths do not specify a file directly can call this
1100
  // function to correct the file and object names.
1101
4.70k
  m_file = file;
1102
4.70k
  m_mod_time = FileSystem::Instance().GetModificationTime(file);
1103
4.70k
  m_object_name = object_name;
1104
4.70k
}
1105
1106
610k
const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1107
1108
259
std::string Module::GetSpecificationDescription() const {
1109
259
  std::string spec(GetFileSpec().GetPath());
1110
259
  if (m_object_name) {
1111
0
    spec += '(';
1112
0
    spec += m_object_name.GetCString();
1113
0
    spec += ')';
1114
0
  }
1115
259
  return spec;
1116
259
}
1117
1118
void Module::GetDescription(llvm::raw_ostream &s,
1119
12.5k
                            lldb::DescriptionLevel level) {
1120
12.5k
  if (level >= eDescriptionLevelFull) {
1121
553
    if (m_arch.IsValid())
1122
553
      s << llvm::formatv("({0}) ", m_arch.GetArchitectureName());
1123
553
  }
1124
1125
12.5k
  if (level == eDescriptionLevelBrief) {
1126
11.9k
    const char *filename = m_file.GetFilename().GetCString();
1127
11.9k
    if (filename)
1128
11.9k
      s << filename;
1129
11.9k
  } else {
1130
553
    char path[PATH_MAX];
1131
553
    if (m_file.GetPath(path, sizeof(path)))
1132
553
      s << path;
1133
553
  }
1134
1135
12.5k
  const char *object_name = m_object_name.GetCString();
1136
12.5k
  if (object_name)
1137
69
    s << llvm::formatv("({0})", object_name);
1138
12.5k
}
1139
1140
228k
bool Module::FileHasChanged() const {
1141
  // We have provided the DataBuffer for this module to avoid accessing the
1142
  // filesystem. We never want to reload those files.
1143
228k
  if (m_data_sp)
1144
210k
    return false;
1145
18.3k
  if (!m_file_has_changed)
1146
18.3k
    m_file_has_changed =
1147
18.3k
        (FileSystem::Instance().GetModificationTime(m_file) != m_mod_time);
1148
18.3k
  return m_file_has_changed;
1149
228k
}
1150
1151
void Module::ReportWarningOptimization(
1152
647
    std::optional<lldb::user_id_t> debugger_id) {
1153
647
  ConstString file_name = GetFileSpec().GetFilename();
1154
647
  if (file_name.IsEmpty())
1155
0
    return;
1156
1157
647
  StreamString ss;
1158
647
  ss << file_name
1159
647
     << " was compiled with optimization - stepping may behave "
1160
647
        "oddly; variables may not be available.";
1161
647
  Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1162
647
                          &m_optimization_warning);
1163
647
}
1164
1165
void Module::ReportWarningUnsupportedLanguage(
1166
3
    LanguageType language, std::optional<lldb::user_id_t> debugger_id) {
1167
3
  StreamString ss;
1168
3
  ss << "This version of LLDB has no plugin for the language \""
1169
3
     << Language::GetNameForLanguageType(language)
1170
3
     << "\". "
1171
3
        "Inspection of frame variables will be limited.";
1172
3
  Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1173
3
                          &m_language_warning);
1174
3
}
1175
1176
void Module::ReportErrorIfModifyDetected(
1177
0
    const llvm::formatv_object_base &payload) {
1178
0
  if (!m_first_file_changed_log) {
1179
0
    if (FileHasChanged()) {
1180
0
      m_first_file_changed_log = true;
1181
0
      StreamString strm;
1182
0
      strm.PutCString("the object file ");
1183
0
      GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1184
0
      strm.PutCString(" has been modified\n");
1185
0
      strm.PutCString(payload.str());
1186
0
      strm.PutCString("The debug session should be aborted as the original "
1187
0
                      "debug information has been overwritten.");
1188
0
      Debugger::ReportError(std::string(strm.GetString()));
1189
0
    }
1190
0
  }
1191
0
}
1192
1193
22
void Module::ReportError(const llvm::formatv_object_base &payload) {
1194
22
  StreamString strm;
1195
22
  GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelBrief);
1196
22
  strm.PutChar(' ');
1197
22
  strm.PutCString(payload.str());
1198
22
  Debugger::ReportError(strm.GetString().str());
1199
22
}
1200
1201
12
void Module::ReportWarning(const llvm::formatv_object_base &payload) {
1202
12
  StreamString strm;
1203
12
  GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1204
12
  strm.PutChar(' ');
1205
12
  strm.PutCString(payload.str());
1206
12
  Debugger::ReportWarning(std::string(strm.GetString()));
1207
12
}
1208
1209
31
void Module::LogMessage(Log *log, const llvm::formatv_object_base &payload) {
1210
31
  StreamString log_message;
1211
31
  GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1212
31
  log_message.PutCString(": ");
1213
31
  log_message.PutCString(payload.str());
1214
31
  log->PutCString(log_message.GetData());
1215
31
}
1216
1217
void Module::LogMessageVerboseBacktrace(
1218
0
    Log *log, const llvm::formatv_object_base &payload) {
1219
0
  StreamString log_message;
1220
0
  GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1221
0
  log_message.PutCString(": ");
1222
0
  log_message.PutCString(payload.str());
1223
0
  if (log->GetVerbose()) {
1224
0
    std::string back_trace;
1225
0
    llvm::raw_string_ostream stream(back_trace);
1226
0
    llvm::sys::PrintStackTrace(stream);
1227
0
    log_message.PutCString(back_trace);
1228
0
  }
1229
0
  log->PutCString(log_message.GetData());
1230
0
}
1231
1232
98
void Module::Dump(Stream *s) {
1233
98
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
1234
  // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1235
98
  s->Indent();
1236
98
  s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1237
98
            m_object_name ? 
"("0
: "",
1238
98
            m_object_name ? 
m_object_name.GetCString()0
: "",
1239
98
            m_object_name ? 
")"0
: "");
1240
1241
98
  s->IndentMore();
1242
1243
98
  ObjectFile *objfile = GetObjectFile();
1244
98
  if (objfile)
1245
98
    objfile->Dump(s);
1246
1247
98
  if (SymbolFile *symbols = GetSymbolFile())
1248
98
    symbols->Dump(*s);
1249
1250
98
  s->IndentLess();
1251
98
}
1252
1253
14.4k
ConstString Module::GetObjectName() const { return m_object_name; }
1254
1255
10.7M
ObjectFile *Module::GetObjectFile() {
1256
10.7M
  if (!m_did_load_objfile.load()) {
1257
115k
    std::lock_guard<std::recursive_mutex> guard(m_mutex);
1258
115k
    if (!m_did_load_objfile.load()) {
1259
115k
      LLDB_SCOPED_TIMERF("Module::GetObjectFile () module = %s",
1260
115k
                         GetFileSpec().GetFilename().AsCString(""));
1261
115k
      lldb::offset_t data_offset = 0;
1262
115k
      lldb::offset_t file_size = 0;
1263
1264
115k
      if (m_data_sp)
1265
103k
        file_size = m_data_sp->GetByteSize();
1266
11.5k
      else if (m_file)
1267
10.5k
        file_size = FileSystem::Instance().GetByteSize(m_file);
1268
1269
115k
      if (file_size > m_object_offset) {
1270
114k
        m_did_load_objfile = true;
1271
        // FindPlugin will modify its data_sp argument. Do not let it
1272
        // modify our m_data_sp member.
1273
114k
        auto data_sp = m_data_sp;
1274
114k
        m_objfile_sp = ObjectFile::FindPlugin(
1275
114k
            shared_from_this(), &m_file, m_object_offset,
1276
114k
            file_size - m_object_offset, data_sp, data_offset);
1277
114k
        if (m_objfile_sp) {
1278
          // Once we get the object file, update our module with the object
1279
          // file's architecture since it might differ in vendor/os if some
1280
          // parts were unknown.  But since the matching arch might already be
1281
          // more specific than the generic COFF architecture, only merge in
1282
          // those values that overwrite unspecified unknown values.
1283
114k
          m_arch.MergeFrom(m_objfile_sp->GetArchitecture());
1284
114k
        } else {
1285
2
          ReportError("failed to load objfile for {0}\nDebugging will be "
1286
2
                      "degraded for this module.",
1287
2
                      GetFileSpec().GetPath().c_str());
1288
2
        }
1289
114k
      }
1290
115k
    }
1291
115k
  }
1292
10.7M
  return m_objfile_sp.get();
1293
10.7M
}
1294
1295
10.5M
SectionList *Module::GetSectionList() {
1296
  // Populate m_sections_up with sections from objfile.
1297
10.5M
  if (!m_sections_up) {
1298
111k
    ObjectFile *obj_file = GetObjectFile();
1299
111k
    if (obj_file != nullptr)
1300
111k
      obj_file->CreateSections(*GetUnifiedSectionList());
1301
111k
  }
1302
10.5M
  return m_sections_up.get();
1303
10.5M
}
1304
1305
0
void Module::SectionFileAddressesChanged() {
1306
0
  ObjectFile *obj_file = GetObjectFile();
1307
0
  if (obj_file)
1308
0
    obj_file->SectionFileAddressesChanged();
1309
0
  if (SymbolFile *symbols = GetSymbolFile())
1310
0
    symbols->SectionFileAddressesChanged();
1311
0
}
1312
1313
261k
UnwindTable &Module::GetUnwindTable() {
1314
261k
  if (!m_unwind_table) {
1315
6.65k
    m_unwind_table.emplace(*this);
1316
6.65k
    if (!m_symfile_spec)
1317
5.44k
      SymbolLocator::DownloadSymbolFileAsync(GetUUID());
1318
6.65k
  }
1319
261k
  return *m_unwind_table;
1320
261k
}
1321
1322
119k
SectionList *Module::GetUnifiedSectionList() {
1323
119k
  if (!m_sections_up)
1324
118k
    m_sections_up = std::make_unique<SectionList>();
1325
119k
  return m_sections_up.get();
1326
119k
}
1327
1328
const Symbol *Module::FindFirstSymbolWithNameAndType(ConstString name,
1329
128k
                                                     SymbolType symbol_type) {
1330
128k
  LLDB_SCOPED_TIMERF(
1331
128k
      "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1332
128k
      name.AsCString(), symbol_type);
1333
128k
  if (Symtab *symtab = GetSymtab())
1334
128k
    return symtab->FindFirstSymbolWithNameAndType(
1335
128k
        name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1336
175
  return nullptr;
1337
128k
}
1338
void Module::SymbolIndicesToSymbolContextList(
1339
    Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1340
602k
    SymbolContextList &sc_list) {
1341
  // No need to protect this call using m_mutex all other method calls are
1342
  // already thread safe.
1343
1344
602k
  size_t num_indices = symbol_indexes.size();
1345
602k
  if (num_indices > 0) {
1346
6.58k
    SymbolContext sc;
1347
6.58k
    CalculateSymbolContext(&sc);
1348
13.9k
    for (size_t i = 0; i < num_indices; 
i++7.40k
) {
1349
7.40k
      sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1350
7.40k
      if (sc.symbol)
1351
7.40k
        sc_list.Append(sc);
1352
7.40k
    }
1353
6.58k
  }
1354
602k
}
1355
1356
void Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1357
7.15k
                                 SymbolContextList &sc_list) {
1358
7.15k
  LLDB_SCOPED_TIMERF("Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1359
7.15k
                     name.AsCString(), name_type_mask);
1360
7.15k
  if (Symtab *symtab = GetSymtab())
1361
7.15k
    symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1362
7.15k
}
1363
1364
void Module::FindSymbolsWithNameAndType(ConstString name,
1365
                                        SymbolType symbol_type,
1366
607k
                                        SymbolContextList &sc_list) {
1367
  // No need to protect this call using m_mutex all other method calls are
1368
  // already thread safe.
1369
607k
  if (Symtab *symtab = GetSymtab()) {
1370
602k
    std::vector<uint32_t> symbol_indexes;
1371
602k
    symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1372
602k
    SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1373
602k
  }
1374
607k
}
1375
1376
void Module::FindSymbolsMatchingRegExAndType(
1377
    const RegularExpression &regex, SymbolType symbol_type,
1378
0
    SymbolContextList &sc_list, Mangled::NamePreference mangling_preference) {
1379
  // No need to protect this call using m_mutex all other method calls are
1380
  // already thread safe.
1381
0
  LLDB_SCOPED_TIMERF(
1382
0
      "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1383
0
      regex.GetText().str().c_str(), symbol_type);
1384
0
  if (Symtab *symtab = GetSymtab()) {
1385
0
    std::vector<uint32_t> symbol_indexes;
1386
0
    symtab->FindAllSymbolsMatchingRexExAndType(
1387
0
        regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1388
0
        symbol_indexes, mangling_preference);
1389
0
    SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1390
0
  }
1391
0
}
1392
1393
228k
void Module::PreloadSymbols() {
1394
228k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
1395
228k
  SymbolFile *sym_file = GetSymbolFile();
1396
228k
  if (!sym_file)
1397
1.15k
    return;
1398
1399
  // Load the object file symbol table and any symbols from the SymbolFile that
1400
  // get appended using SymbolFile::AddSymbols(...).
1401
227k
  if (Symtab *symtab = sym_file->GetSymtab())
1402
227k
    symtab->PreloadSymbols();
1403
1404
  // Now let the symbol file preload its data and the symbol table will be
1405
  // available without needing to take the module lock.
1406
227k
  sym_file->PreloadSymbols();
1407
227k
}
1408
1409
1.48k
void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1410
1.48k
  if (!FileSystem::Instance().Exists(file))
1411
1
    return;
1412
1.48k
  if (m_symfile_up) {
1413
    // Remove any sections in the unified section list that come from the
1414
    // current symbol vendor.
1415
23
    SectionList *section_list = GetSectionList();
1416
23
    SymbolFile *symbol_file = GetSymbolFile();
1417
23
    if (section_list && symbol_file) {
1418
16
      ObjectFile *obj_file = symbol_file->GetObjectFile();
1419
      // Make sure we have an object file and that the symbol vendor's objfile
1420
      // isn't the same as the module's objfile before we remove any sections
1421
      // for it...
1422
16
      if (obj_file) {
1423
        // Check to make sure we aren't trying to specify the file we already
1424
        // have
1425
16
        if (obj_file->GetFileSpec() == file) {
1426
          // We are being told to add the exact same file that we already have
1427
          // we don't have to do anything.
1428
2
          return;
1429
2
        }
1430
1431
        // Cleare the current symtab as we are going to replace it with a new
1432
        // one
1433
14
        obj_file->ClearSymtab();
1434
1435
        // Clear the unwind table too, as that may also be affected by the
1436
        // symbol file information.
1437
14
        m_unwind_table.reset();
1438
1439
        // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1440
        // instead of a full path to the symbol file within the bundle
1441
        // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1442
        // check this
1443
1444
14
        if (FileSystem::Instance().IsDirectory(file)) {
1445
0
          std::string new_path(file.GetPath());
1446
0
          std::string old_path(obj_file->GetFileSpec().GetPath());
1447
0
          if (llvm::StringRef(old_path).startswith(new_path)) {
1448
            // We specified the same bundle as the symbol file that we already
1449
            // have
1450
0
            return;
1451
0
          }
1452
0
        }
1453
1454
14
        if (obj_file != m_objfile_sp.get()) {
1455
0
          size_t num_sections = section_list->GetNumSections(0);
1456
0
          for (size_t idx = num_sections; idx > 0; --idx) {
1457
0
            lldb::SectionSP section_sp(
1458
0
                section_list->GetSectionAtIndex(idx - 1));
1459
0
            if (section_sp->GetObjectFile() == obj_file) {
1460
0
              section_list->DeleteSection(idx - 1);
1461
0
            }
1462
0
          }
1463
0
        }
1464
14
      }
1465
16
    }
1466
    // Keep all old symbol files around in case there are any lingering type
1467
    // references in any SBValue objects that might have been handed out.
1468
21
    m_old_symfiles.push_back(std::move(m_symfile_up));
1469
21
  }
1470
1.48k
  m_symfile_spec = file;
1471
1.48k
  m_symfile_up.reset();
1472
1.48k
  m_did_load_symfile = false;
1473
1.48k
}
1474
1475
584k
bool Module::IsExecutable() {
1476
584k
  if (GetObjectFile() == nullptr)
1477
0
    return false;
1478
584k
  else
1479
584k
    return GetObjectFile()->IsExecutable();
1480
584k
}
1481
1482
2.43k
bool Module::IsLoadedInTarget(Target *target) {
1483
2.43k
  ObjectFile *obj_file = GetObjectFile();
1484
2.43k
  if (obj_file) {
1485
2.43k
    SectionList *sections = GetSectionList();
1486
2.43k
    if (sections != nullptr) {
1487
2.43k
      size_t num_sections = sections->GetSize();
1488
3.39k
      for (size_t sect_idx = 0; sect_idx < num_sections; 
sect_idx++957
) {
1489
3.17k
        SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1490
3.17k
        if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1491
2.21k
          return true;
1492
2.21k
        }
1493
3.17k
      }
1494
2.43k
    }
1495
2.43k
  }
1496
222
  return false;
1497
2.43k
}
1498
1499
bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1500
234k
                                           Stream &feedback_stream) {
1501
234k
  if (!target) {
1502
0
    error.SetErrorString("invalid destination Target");
1503
0
    return false;
1504
0
  }
1505
1506
234k
  LoadScriptFromSymFile should_load =
1507
234k
      target->TargetProperties::GetLoadScriptFromSymbolFile();
1508
1509
234k
  if (should_load == eLoadScriptFromSymFileFalse)
1510
1.00k
    return false;
1511
1512
233k
  Debugger &debugger = target->GetDebugger();
1513
233k
  const ScriptLanguage script_language = debugger.GetScriptLanguage();
1514
233k
  if (
script_language != eScriptLanguageNone233k
) {
1515
1516
233k
    PlatformSP platform_sp(target->GetPlatform());
1517
1518
233k
    if (!platform_sp) {
1519
0
      error.SetErrorString("invalid Platform");
1520
0
      return false;
1521
0
    }
1522
1523
233k
    FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1524
233k
        target, *this, feedback_stream);
1525
1526
233k
    const uint32_t num_specs = file_specs.GetSize();
1527
233k
    if (num_specs) {
1528
3
      ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1529
3
      if (script_interpreter) {
1530
6
        for (uint32_t i = 0; i < num_specs; 
++i3
) {
1531
3
          FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1532
3
          if (scripting_fspec &&
1533
3
              FileSystem::Instance().Exists(scripting_fspec)) {
1534
3
            if (should_load == eLoadScriptFromSymFileWarn) {
1535
0
              feedback_stream.Printf(
1536
0
                  "warning: '%s' contains a debug script. To run this script "
1537
0
                  "in "
1538
0
                  "this debug session:\n\n    command script import "
1539
0
                  "\"%s\"\n\n"
1540
0
                  "To run all discovered debug scripts in this session:\n\n"
1541
0
                  "    settings set target.load-script-from-symbol-file "
1542
0
                  "true\n",
1543
0
                  GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1544
0
                  scripting_fspec.GetPath().c_str());
1545
0
              return false;
1546
0
            }
1547
3
            StreamString scripting_stream;
1548
3
            scripting_fspec.Dump(scripting_stream.AsRawOstream());
1549
3
            LoadScriptOptions options;
1550
3
            bool did_load = script_interpreter->LoadScriptingModule(
1551
3
                scripting_stream.GetData(), options, error);
1552
3
            if (!did_load)
1553
0
              return false;
1554
3
          }
1555
3
        }
1556
3
      } else {
1557
0
        error.SetErrorString("invalid ScriptInterpreter");
1558
0
        return false;
1559
0
      }
1560
3
    }
1561
233k
  }
1562
233k
  return true;
1563
233k
}
1564
1565
116k
bool Module::SetArchitecture(const ArchSpec &new_arch) {
1566
116k
  if (!m_arch.IsValid()) {
1567
108
    m_arch = new_arch;
1568
108
    return true;
1569
108
  }
1570
115k
  return m_arch.IsCompatibleMatch(new_arch);
1571
116k
}
1572
1573
bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1574
4.97k
                            bool value_is_offset, bool &changed) {
1575
4.97k
  ObjectFile *object_file = GetObjectFile();
1576
4.97k
  if (object_file != nullptr) {
1577
4.97k
    changed = object_file->SetLoadAddress(target, value, value_is_offset);
1578
4.97k
    return true;
1579
4.97k
  } else {
1580
0
    changed = false;
1581
0
  }
1582
0
  return false;
1583
4.97k
}
1584
1585
26.5M
bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1586
26.5M
  const UUID &uuid = module_ref.GetUUID();
1587
1588
26.5M
  if (uuid.IsValid()) {
1589
    // If the UUID matches, then nothing more needs to match...
1590
18.8M
    return (uuid == GetUUID());
1591
18.8M
  }
1592
1593
7.79M
  const FileSpec &file_spec = module_ref.GetFileSpec();
1594
7.79M
  if (!FileSpec::Match(file_spec, m_file) &&
1595
7.79M
      !FileSpec::Match(file_spec, m_platform_file))
1596
7.79M
    return false;
1597
1598
18.4E
  const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1599
18.4E
  if (!FileSpec::Match(platform_file_spec, GetPlatformFileSpec()))
1600
0
    return false;
1601
1602
18.4E
  const ArchSpec &arch = module_ref.GetArchitecture();
1603
18.4E
  if (arch.IsValid()) {
1604
1.23k
    if (!m_arch.IsCompatibleMatch(arch))
1605
4
      return false;
1606
1.23k
  }
1607
1608
18.4E
  ConstString object_name = module_ref.GetObjectName();
1609
18.4E
  if (object_name) {
1610
0
    if (object_name != GetObjectName())
1611
0
      return false;
1612
0
  }
1613
18.4E
  return true;
1614
18.4E
}
1615
1616
bool Module::FindSourceFile(const FileSpec &orig_spec,
1617
40
                            FileSpec &new_spec) const {
1618
40
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
1619
40
  if (auto remapped = m_source_mappings.FindFile(orig_spec)) {
1620
0
    new_spec = *remapped;
1621
0
    return true;
1622
0
  }
1623
40
  return false;
1624
40
}
1625
1626
45.5k
std::optional<std::string> Module::RemapSourceFile(llvm::StringRef path) const {
1627
45.5k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
1628
45.5k
  if (auto remapped = m_source_mappings.RemapPath(path))
1629
198
    return remapped->GetPath();
1630
45.3k
  return {};
1631
45.5k
}
1632
1633
void Module::RegisterXcodeSDK(llvm::StringRef sdk_name,
1634
1.75k
                              llvm::StringRef sysroot) {
1635
1.75k
  auto sdk_path_or_err =
1636
1.75k
      HostInfo::GetSDKRoot(HostInfo::SDKOptions{sdk_name.str()});
1637
1638
1.75k
  if (!sdk_path_or_err) {
1639
2
    Debugger::ReportError("Error while searching for Xcode SDK: " +
1640
2
                          toString(sdk_path_or_err.takeError()));
1641
2
    return;
1642
2
  }
1643
1644
1.75k
  auto sdk_path = *sdk_path_or_err;
1645
1.75k
  if (sdk_path.empty())
1646
4
    return;
1647
  // If the SDK changed for a previously registered source path, update it.
1648
  // This could happend with -fdebug-prefix-map, otherwise it's unlikely.
1649
1.75k
  if (!m_source_mappings.Replace(sysroot, sdk_path, true))
1650
    // In the general case, however, append it to the list.
1651
1.61k
    m_source_mappings.Append(sysroot, sdk_path, false);
1652
1.75k
}
1653
1654
78
bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
1655
78
  if (!arch_spec.IsValid())
1656
0
    return false;
1657
78
  LLDB_LOGF(GetLog(LLDBLog::Object | LLDBLog::Modules),
1658
78
            "module has arch %s, merging/replacing with arch %s",
1659
78
            m_arch.GetTriple().getTriple().c_str(),
1660
78
            arch_spec.GetTriple().getTriple().c_str());
1661
78
  if (!m_arch.IsCompatibleMatch(arch_spec)) {
1662
    // The new architecture is different, we just need to replace it.
1663
0
    return SetArchitecture(arch_spec);
1664
0
  }
1665
1666
  // Merge bits from arch_spec into "merged_arch" and set our architecture.
1667
78
  ArchSpec merged_arch(m_arch);
1668
78
  merged_arch.MergeFrom(arch_spec);
1669
  // SetArchitecture() is a no-op if m_arch is already valid.
1670
78
  m_arch = ArchSpec();
1671
78
  return SetArchitecture(merged_arch);
1672
78
}
1673
1674
97
llvm::VersionTuple Module::GetVersion() {
1675
97
  if (ObjectFile *obj_file = GetObjectFile())
1676
97
    return obj_file->GetVersion();
1677
0
  return llvm::VersionTuple();
1678
97
}
1679
1680
0
bool Module::GetIsDynamicLinkEditor() {
1681
0
  ObjectFile *obj_file = GetObjectFile();
1682
1683
0
  if (obj_file)
1684
0
    return obj_file->GetIsDynamicLinkEditor();
1685
1686
0
  return false;
1687
0
}
1688
1689
18
uint32_t Module::Hash() {
1690
18
  std::string identifier;
1691
18
  llvm::raw_string_ostream id_strm(identifier);
1692
18
  id_strm << m_arch.GetTriple().str() << '-' << m_file.GetPath();
1693
18
  if (m_object_name)
1694
3
    id_strm << '(' << m_object_name << ')';
1695
18
  if (m_object_offset > 0)
1696
4
    id_strm << m_object_offset;
1697
18
  const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
1698
18
  if (mtime > 0)
1699
3
    id_strm << mtime;
1700
18
  return llvm::djbHash(id_strm.str());
1701
18
}
1702
1703
18
std::string Module::GetCacheKey() {
1704
18
  std::string key;
1705
18
  llvm::raw_string_ostream strm(key);
1706
18
  strm << m_arch.GetTriple().str() << '-' << m_file.GetFilename();
1707
18
  if (m_object_name)
1708
3
    strm << '(' << m_object_name << ')';
1709
18
  strm << '-' << llvm::format_hex(Hash(), 10);
1710
18
  return strm.str();
1711
18
}
1712
1713
242k
DataFileCache *Module::GetIndexCache() {
1714
242k
  if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
1715
242k
    return nullptr;
1716
  // NOTE: intentional leak so we don't crash if global destructor chain gets
1717
  // called as other threads still use the result of this function
1718
20
  static DataFileCache *g_data_file_cache =
1719
20
      new DataFileCache(ModuleList::GetGlobalModuleListProperties()
1720
20
                            .GetLLDBIndexCachePath()
1721
20
                            .GetPath());
1722
20
  return g_data_file_cache;
1723
242k
}