1 //===-- ModuleList.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/ModuleList.h"
10 #include "lldb/Core/FileSpecList.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Host/FileSystem.h"
14 #include "lldb/Interpreter/OptionValueFileSpec.h"
15 #include "lldb/Interpreter/OptionValueFileSpecList.h"
16 #include "lldb/Interpreter/OptionValueProperties.h"
17 #include "lldb/Interpreter/Property.h"
18 #include "lldb/Symbol/LocateSymbolFile.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolContext.h"
21 #include "lldb/Symbol/TypeList.h"
22 #include "lldb/Symbol/VariableList.h"
23 #include "lldb/Utility/ArchSpec.h"
24 #include "lldb/Utility/ConstString.h"
25 #include "lldb/Utility/LLDBLog.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/UUID.h"
28 #include "lldb/lldb-defines.h"
29
30 #if defined(_WIN32)
31 #include "lldb/Host/windows/PosixApi.h"
32 #endif
33
34 #include "clang/Driver/Driver.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Threading.h"
38 #include "llvm/Support/raw_ostream.h"
39
40 #include <chrono>
41 #include <memory>
42 #include <mutex>
43 #include <string>
44 #include <utility>
45
46 namespace lldb_private {
47 class Function;
48 }
49 namespace lldb_private {
50 class RegularExpression;
51 }
52 namespace lldb_private {
53 class Stream;
54 }
55 namespace lldb_private {
56 class SymbolFile;
57 }
58 namespace lldb_private {
59 class Target;
60 }
61
62 using namespace lldb;
63 using namespace lldb_private;
64
65 namespace {
66
67 #define LLDB_PROPERTIES_modulelist
68 #include "CoreProperties.inc"
69
70 enum {
71 #define LLDB_PROPERTIES_modulelist
72 #include "CorePropertiesEnum.inc"
73 };
74
75 } // namespace
76
ModuleListProperties()77 ModuleListProperties::ModuleListProperties() {
78 m_collection_sp =
79 std::make_shared<OptionValueProperties>(ConstString("symbols"));
80 m_collection_sp->Initialize(g_modulelist_properties);
81 m_collection_sp->SetValueChangedCallback(ePropertySymLinkPaths,
82 [this] { UpdateSymlinkMappings(); });
83
84 llvm::SmallString<128> path;
85 if (clang::driver::Driver::getDefaultModuleCachePath(path)) {
86 lldbassert(SetClangModulesCachePath(FileSpec(path)));
87 }
88
89 path.clear();
90 if (llvm::sys::path::cache_directory(path)) {
91 llvm::sys::path::append(path, "lldb");
92 llvm::sys::path::append(path, "IndexCache");
93 lldbassert(SetLLDBIndexCachePath(FileSpec(path)));
94 }
95
96 }
97
GetEnableExternalLookup() const98 bool ModuleListProperties::GetEnableExternalLookup() const {
99 const uint32_t idx = ePropertyEnableExternalLookup;
100 return m_collection_sp->GetPropertyAtIndexAsBoolean(
101 nullptr, idx, g_modulelist_properties[idx].default_uint_value != 0);
102 }
103
SetEnableExternalLookup(bool new_value)104 bool ModuleListProperties::SetEnableExternalLookup(bool new_value) {
105 return m_collection_sp->SetPropertyAtIndexAsBoolean(
106 nullptr, ePropertyEnableExternalLookup, new_value);
107 }
108
GetClangModulesCachePath() const109 FileSpec ModuleListProperties::GetClangModulesCachePath() const {
110 return m_collection_sp
111 ->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
112 ePropertyClangModulesCachePath)
113 ->GetCurrentValue();
114 }
115
SetClangModulesCachePath(const FileSpec & path)116 bool ModuleListProperties::SetClangModulesCachePath(const FileSpec &path) {
117 return m_collection_sp->SetPropertyAtIndexAsFileSpec(
118 nullptr, ePropertyClangModulesCachePath, path);
119 }
120
GetLLDBIndexCachePath() const121 FileSpec ModuleListProperties::GetLLDBIndexCachePath() const {
122 return m_collection_sp
123 ->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
124 ePropertyLLDBIndexCachePath)
125 ->GetCurrentValue();
126 }
127
SetLLDBIndexCachePath(const FileSpec & path)128 bool ModuleListProperties::SetLLDBIndexCachePath(const FileSpec &path) {
129 return m_collection_sp->SetPropertyAtIndexAsFileSpec(
130 nullptr, ePropertyLLDBIndexCachePath, path);
131 }
132
GetEnableLLDBIndexCache() const133 bool ModuleListProperties::GetEnableLLDBIndexCache() const {
134 const uint32_t idx = ePropertyEnableLLDBIndexCache;
135 return m_collection_sp->GetPropertyAtIndexAsBoolean(
136 nullptr, idx, g_modulelist_properties[idx].default_uint_value != 0);
137 }
138
SetEnableLLDBIndexCache(bool new_value)139 bool ModuleListProperties::SetEnableLLDBIndexCache(bool new_value) {
140 return m_collection_sp->SetPropertyAtIndexAsBoolean(
141 nullptr, ePropertyEnableLLDBIndexCache, new_value);
142 }
143
GetLLDBIndexCacheMaxByteSize()144 uint64_t ModuleListProperties::GetLLDBIndexCacheMaxByteSize() {
145 const uint32_t idx = ePropertyLLDBIndexCacheMaxByteSize;
146 return m_collection_sp->GetPropertyAtIndexAsUInt64(
147 nullptr, idx, g_modulelist_properties[idx].default_uint_value);
148 }
149
GetLLDBIndexCacheMaxPercent()150 uint64_t ModuleListProperties::GetLLDBIndexCacheMaxPercent() {
151 const uint32_t idx = ePropertyLLDBIndexCacheMaxPercent;
152 return m_collection_sp->GetPropertyAtIndexAsUInt64(
153 nullptr, idx, g_modulelist_properties[idx].default_uint_value);
154 }
155
GetLLDBIndexCacheExpirationDays()156 uint64_t ModuleListProperties::GetLLDBIndexCacheExpirationDays() {
157 const uint32_t idx = ePropertyLLDBIndexCacheExpirationDays;
158 return m_collection_sp->GetPropertyAtIndexAsUInt64(
159 nullptr, idx, g_modulelist_properties[idx].default_uint_value);
160 }
161
UpdateSymlinkMappings()162 void ModuleListProperties::UpdateSymlinkMappings() {
163 FileSpecList list = m_collection_sp
164 ->GetPropertyAtIndexAsOptionValueFileSpecList(
165 nullptr, false, ePropertySymLinkPaths)
166 ->GetCurrentValue();
167 llvm::sys::ScopedWriter lock(m_symlink_paths_mutex);
168 const bool notify = false;
169 m_symlink_paths.Clear(notify);
170 for (FileSpec symlink : list) {
171 FileSpec resolved;
172 Status status = FileSystem::Instance().Readlink(symlink, resolved);
173 if (status.Success())
174 m_symlink_paths.Append(symlink.GetPath(), resolved.GetPath(), notify);
175 }
176 }
177
GetSymlinkMappings() const178 PathMappingList ModuleListProperties::GetSymlinkMappings() const {
179 llvm::sys::ScopedReader lock(m_symlink_paths_mutex);
180 return m_symlink_paths;
181 }
182
GetLoadSymbolOnDemand()183 bool ModuleListProperties::GetLoadSymbolOnDemand() {
184 const uint32_t idx = ePropertyLoadSymbolOnDemand;
185 return m_collection_sp->GetPropertyAtIndexAsBoolean(
186 nullptr, idx, g_modulelist_properties[idx].default_uint_value != 0);
187 }
188
ModuleList()189 ModuleList::ModuleList() : m_modules(), m_modules_mutex() {}
190
ModuleList(const ModuleList & rhs)191 ModuleList::ModuleList(const ModuleList &rhs) : m_modules(), m_modules_mutex() {
192 std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex);
193 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex);
194 m_modules = rhs.m_modules;
195 }
196
ModuleList(ModuleList::Notifier * notifier)197 ModuleList::ModuleList(ModuleList::Notifier *notifier)
198 : m_modules(), m_modules_mutex(), m_notifier(notifier) {}
199
operator =(const ModuleList & rhs)200 const ModuleList &ModuleList::operator=(const ModuleList &rhs) {
201 if (this != &rhs) {
202 std::lock(m_modules_mutex, rhs.m_modules_mutex);
203 std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex,
204 std::adopt_lock);
205 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex,
206 std::adopt_lock);
207 m_modules = rhs.m_modules;
208 }
209 return *this;
210 }
211
212 ModuleList::~ModuleList() = default;
213
AppendImpl(const ModuleSP & module_sp,bool use_notifier)214 void ModuleList::AppendImpl(const ModuleSP &module_sp, bool use_notifier) {
215 if (module_sp) {
216 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
217 m_modules.push_back(module_sp);
218 if (use_notifier && m_notifier)
219 m_notifier->NotifyModuleAdded(*this, module_sp);
220 }
221 }
222
Append(const ModuleSP & module_sp,bool notify)223 void ModuleList::Append(const ModuleSP &module_sp, bool notify) {
224 AppendImpl(module_sp, notify);
225 }
226
ReplaceEquivalent(const ModuleSP & module_sp,llvm::SmallVectorImpl<lldb::ModuleSP> * old_modules)227 void ModuleList::ReplaceEquivalent(
228 const ModuleSP &module_sp,
229 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules) {
230 if (module_sp) {
231 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
232
233 // First remove any equivalent modules. Equivalent modules are modules
234 // whose path, platform path and architecture match.
235 ModuleSpec equivalent_module_spec(module_sp->GetFileSpec(),
236 module_sp->GetArchitecture());
237 equivalent_module_spec.GetPlatformFileSpec() =
238 module_sp->GetPlatformFileSpec();
239
240 size_t idx = 0;
241 while (idx < m_modules.size()) {
242 ModuleSP test_module_sp(m_modules[idx]);
243 if (test_module_sp->MatchesModuleSpec(equivalent_module_spec)) {
244 if (old_modules)
245 old_modules->push_back(test_module_sp);
246 RemoveImpl(m_modules.begin() + idx);
247 } else {
248 ++idx;
249 }
250 }
251 // Now add the new module to the list
252 Append(module_sp);
253 }
254 }
255
AppendIfNeeded(const ModuleSP & new_module,bool notify)256 bool ModuleList::AppendIfNeeded(const ModuleSP &new_module, bool notify) {
257 if (new_module) {
258 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
259 for (const ModuleSP &module_sp : m_modules) {
260 if (module_sp.get() == new_module.get())
261 return false; // Already in the list
262 }
263 // Only push module_sp on the list if it wasn't already in there.
264 Append(new_module, notify);
265 return true;
266 }
267 return false;
268 }
269
Append(const ModuleList & module_list)270 void ModuleList::Append(const ModuleList &module_list) {
271 for (auto pos : module_list.m_modules)
272 Append(pos);
273 }
274
AppendIfNeeded(const ModuleList & module_list)275 bool ModuleList::AppendIfNeeded(const ModuleList &module_list) {
276 bool any_in = false;
277 for (auto pos : module_list.m_modules) {
278 if (AppendIfNeeded(pos))
279 any_in = true;
280 }
281 return any_in;
282 }
283
RemoveImpl(const ModuleSP & module_sp,bool use_notifier)284 bool ModuleList::RemoveImpl(const ModuleSP &module_sp, bool use_notifier) {
285 if (module_sp) {
286 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
287 collection::iterator pos, end = m_modules.end();
288 for (pos = m_modules.begin(); pos != end; ++pos) {
289 if (pos->get() == module_sp.get()) {
290 m_modules.erase(pos);
291 if (use_notifier && m_notifier)
292 m_notifier->NotifyModuleRemoved(*this, module_sp);
293 return true;
294 }
295 }
296 }
297 return false;
298 }
299
300 ModuleList::collection::iterator
RemoveImpl(ModuleList::collection::iterator pos,bool use_notifier)301 ModuleList::RemoveImpl(ModuleList::collection::iterator pos,
302 bool use_notifier) {
303 ModuleSP module_sp(*pos);
304 collection::iterator retval = m_modules.erase(pos);
305 if (use_notifier && m_notifier)
306 m_notifier->NotifyModuleRemoved(*this, module_sp);
307 return retval;
308 }
309
Remove(const ModuleSP & module_sp,bool notify)310 bool ModuleList::Remove(const ModuleSP &module_sp, bool notify) {
311 return RemoveImpl(module_sp, notify);
312 }
313
ReplaceModule(const lldb::ModuleSP & old_module_sp,const lldb::ModuleSP & new_module_sp)314 bool ModuleList::ReplaceModule(const lldb::ModuleSP &old_module_sp,
315 const lldb::ModuleSP &new_module_sp) {
316 if (!RemoveImpl(old_module_sp, false))
317 return false;
318 AppendImpl(new_module_sp, false);
319 if (m_notifier)
320 m_notifier->NotifyModuleUpdated(*this, old_module_sp, new_module_sp);
321 return true;
322 }
323
RemoveIfOrphaned(const Module * module_ptr)324 bool ModuleList::RemoveIfOrphaned(const Module *module_ptr) {
325 if (module_ptr) {
326 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
327 collection::iterator pos, end = m_modules.end();
328 for (pos = m_modules.begin(); pos != end; ++pos) {
329 if (pos->get() == module_ptr) {
330 if (pos->unique()) {
331 pos = RemoveImpl(pos);
332 return true;
333 } else
334 return false;
335 }
336 }
337 }
338 return false;
339 }
340
RemoveOrphans(bool mandatory)341 size_t ModuleList::RemoveOrphans(bool mandatory) {
342 std::unique_lock<std::recursive_mutex> lock(m_modules_mutex, std::defer_lock);
343
344 if (mandatory) {
345 lock.lock();
346 } else {
347 // Not mandatory, remove orphans if we can get the mutex
348 if (!lock.try_lock())
349 return 0;
350 }
351 size_t remove_count = 0;
352 // Modules might hold shared pointers to other modules, so removing one
353 // module might make other other modules orphans. Keep removing modules until
354 // there are no further modules that can be removed.
355 bool made_progress = true;
356 while (made_progress) {
357 // Keep track if we make progress this iteration.
358 made_progress = false;
359 collection::iterator pos = m_modules.begin();
360 while (pos != m_modules.end()) {
361 if (pos->unique()) {
362 pos = RemoveImpl(pos);
363 ++remove_count;
364 // We did make progress.
365 made_progress = true;
366 } else {
367 ++pos;
368 }
369 }
370 }
371 return remove_count;
372 }
373
Remove(ModuleList & module_list)374 size_t ModuleList::Remove(ModuleList &module_list) {
375 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
376 size_t num_removed = 0;
377 collection::iterator pos, end = module_list.m_modules.end();
378 for (pos = module_list.m_modules.begin(); pos != end; ++pos) {
379 if (Remove(*pos, false /* notify */))
380 ++num_removed;
381 }
382 if (m_notifier)
383 m_notifier->NotifyModulesRemoved(module_list);
384 return num_removed;
385 }
386
Clear()387 void ModuleList::Clear() { ClearImpl(); }
388
Destroy()389 void ModuleList::Destroy() { ClearImpl(); }
390
ClearImpl(bool use_notifier)391 void ModuleList::ClearImpl(bool use_notifier) {
392 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
393 if (use_notifier && m_notifier)
394 m_notifier->NotifyWillClearList(*this);
395 m_modules.clear();
396 }
397
GetModulePointerAtIndex(size_t idx) const398 Module *ModuleList::GetModulePointerAtIndex(size_t idx) const {
399 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
400 if (idx < m_modules.size())
401 return m_modules[idx].get();
402 return nullptr;
403 }
404
GetModuleAtIndex(size_t idx) const405 ModuleSP ModuleList::GetModuleAtIndex(size_t idx) const {
406 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
407 return GetModuleAtIndexUnlocked(idx);
408 }
409
GetModuleAtIndexUnlocked(size_t idx) const410 ModuleSP ModuleList::GetModuleAtIndexUnlocked(size_t idx) const {
411 ModuleSP module_sp;
412 if (idx < m_modules.size())
413 module_sp = m_modules[idx];
414 return module_sp;
415 }
416
FindFunctions(ConstString name,FunctionNameType name_type_mask,const ModuleFunctionSearchOptions & options,SymbolContextList & sc_list) const417 void ModuleList::FindFunctions(ConstString name,
418 FunctionNameType name_type_mask,
419 const ModuleFunctionSearchOptions &options,
420 SymbolContextList &sc_list) const {
421 const size_t old_size = sc_list.GetSize();
422
423 if (name_type_mask & eFunctionNameTypeAuto) {
424 Module::LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
425
426 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
427 for (const ModuleSP &module_sp : m_modules) {
428 module_sp->FindFunctions(lookup_info.GetLookupName(),
429 CompilerDeclContext(),
430 lookup_info.GetNameTypeMask(), options, sc_list);
431 }
432
433 const size_t new_size = sc_list.GetSize();
434
435 if (old_size < new_size)
436 lookup_info.Prune(sc_list, old_size);
437 } else {
438 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
439 for (const ModuleSP &module_sp : m_modules) {
440 module_sp->FindFunctions(name, CompilerDeclContext(), name_type_mask,
441 options, sc_list);
442 }
443 }
444 }
445
FindFunctionSymbols(ConstString name,lldb::FunctionNameType name_type_mask,SymbolContextList & sc_list)446 void ModuleList::FindFunctionSymbols(ConstString name,
447 lldb::FunctionNameType name_type_mask,
448 SymbolContextList &sc_list) {
449 const size_t old_size = sc_list.GetSize();
450
451 if (name_type_mask & eFunctionNameTypeAuto) {
452 Module::LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
453
454 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
455 for (const ModuleSP &module_sp : m_modules) {
456 module_sp->FindFunctionSymbols(lookup_info.GetLookupName(),
457 lookup_info.GetNameTypeMask(), sc_list);
458 }
459
460 const size_t new_size = sc_list.GetSize();
461
462 if (old_size < new_size)
463 lookup_info.Prune(sc_list, old_size);
464 } else {
465 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
466 for (const ModuleSP &module_sp : m_modules) {
467 module_sp->FindFunctionSymbols(name, name_type_mask, sc_list);
468 }
469 }
470 }
471
FindFunctions(const RegularExpression & name,const ModuleFunctionSearchOptions & options,SymbolContextList & sc_list)472 void ModuleList::FindFunctions(const RegularExpression &name,
473 const ModuleFunctionSearchOptions &options,
474 SymbolContextList &sc_list) {
475 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
476 for (const ModuleSP &module_sp : m_modules)
477 module_sp->FindFunctions(name, options, sc_list);
478 }
479
FindCompileUnits(const FileSpec & path,SymbolContextList & sc_list) const480 void ModuleList::FindCompileUnits(const FileSpec &path,
481 SymbolContextList &sc_list) const {
482 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
483 for (const ModuleSP &module_sp : m_modules)
484 module_sp->FindCompileUnits(path, sc_list);
485 }
486
FindGlobalVariables(ConstString name,size_t max_matches,VariableList & variable_list) const487 void ModuleList::FindGlobalVariables(ConstString name, size_t max_matches,
488 VariableList &variable_list) const {
489 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
490 for (const ModuleSP &module_sp : m_modules) {
491 module_sp->FindGlobalVariables(name, CompilerDeclContext(), max_matches,
492 variable_list);
493 }
494 }
495
FindGlobalVariables(const RegularExpression & regex,size_t max_matches,VariableList & variable_list) const496 void ModuleList::FindGlobalVariables(const RegularExpression ®ex,
497 size_t max_matches,
498 VariableList &variable_list) const {
499 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
500 for (const ModuleSP &module_sp : m_modules)
501 module_sp->FindGlobalVariables(regex, max_matches, variable_list);
502 }
503
FindSymbolsWithNameAndType(ConstString name,SymbolType symbol_type,SymbolContextList & sc_list) const504 void ModuleList::FindSymbolsWithNameAndType(ConstString name,
505 SymbolType symbol_type,
506 SymbolContextList &sc_list) const {
507 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
508 for (const ModuleSP &module_sp : m_modules)
509 module_sp->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
510 }
511
FindSymbolsMatchingRegExAndType(const RegularExpression & regex,lldb::SymbolType symbol_type,SymbolContextList & sc_list) const512 void ModuleList::FindSymbolsMatchingRegExAndType(
513 const RegularExpression ®ex, lldb::SymbolType symbol_type,
514 SymbolContextList &sc_list) const {
515 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
516 for (const ModuleSP &module_sp : m_modules)
517 module_sp->FindSymbolsMatchingRegExAndType(regex, symbol_type, sc_list);
518 }
519
FindModules(const ModuleSpec & module_spec,ModuleList & matching_module_list) const520 void ModuleList::FindModules(const ModuleSpec &module_spec,
521 ModuleList &matching_module_list) const {
522 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
523 for (const ModuleSP &module_sp : m_modules) {
524 if (module_sp->MatchesModuleSpec(module_spec))
525 matching_module_list.Append(module_sp);
526 }
527 }
528
FindModule(const Module * module_ptr) const529 ModuleSP ModuleList::FindModule(const Module *module_ptr) const {
530 ModuleSP module_sp;
531
532 // Scope for "locker"
533 {
534 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
535 collection::const_iterator pos, end = m_modules.end();
536
537 for (pos = m_modules.begin(); pos != end; ++pos) {
538 if ((*pos).get() == module_ptr) {
539 module_sp = (*pos);
540 break;
541 }
542 }
543 }
544 return module_sp;
545 }
546
FindModule(const UUID & uuid) const547 ModuleSP ModuleList::FindModule(const UUID &uuid) const {
548 ModuleSP module_sp;
549
550 if (uuid.IsValid()) {
551 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
552 collection::const_iterator pos, end = m_modules.end();
553
554 for (pos = m_modules.begin(); pos != end; ++pos) {
555 if ((*pos)->GetUUID() == uuid) {
556 module_sp = (*pos);
557 break;
558 }
559 }
560 }
561 return module_sp;
562 }
563
FindTypes(Module * search_first,ConstString name,bool name_is_fully_qualified,size_t max_matches,llvm::DenseSet<SymbolFile * > & searched_symbol_files,TypeList & types) const564 void ModuleList::FindTypes(Module *search_first, ConstString name,
565 bool name_is_fully_qualified, size_t max_matches,
566 llvm::DenseSet<SymbolFile *> &searched_symbol_files,
567 TypeList &types) const {
568 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
569
570 collection::const_iterator pos, end = m_modules.end();
571 if (search_first) {
572 for (pos = m_modules.begin(); pos != end; ++pos) {
573 if (search_first == pos->get()) {
574 search_first->FindTypes(name, name_is_fully_qualified, max_matches,
575 searched_symbol_files, types);
576
577 if (types.GetSize() >= max_matches)
578 return;
579 }
580 }
581 }
582
583 for (pos = m_modules.begin(); pos != end; ++pos) {
584 // Search the module if the module is not equal to the one in the symbol
585 // context "sc". If "sc" contains a empty module shared pointer, then the
586 // comparison will always be true (valid_module_ptr != nullptr).
587 if (search_first != pos->get())
588 (*pos)->FindTypes(name, name_is_fully_qualified, max_matches,
589 searched_symbol_files, types);
590
591 if (types.GetSize() >= max_matches)
592 return;
593 }
594 }
595
FindSourceFile(const FileSpec & orig_spec,FileSpec & new_spec) const596 bool ModuleList::FindSourceFile(const FileSpec &orig_spec,
597 FileSpec &new_spec) const {
598 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
599 for (const ModuleSP &module_sp : m_modules) {
600 if (module_sp->FindSourceFile(orig_spec, new_spec))
601 return true;
602 }
603 return false;
604 }
605
FindAddressesForLine(const lldb::TargetSP target_sp,const FileSpec & file,uint32_t line,Function * function,std::vector<Address> & output_local,std::vector<Address> & output_extern)606 void ModuleList::FindAddressesForLine(const lldb::TargetSP target_sp,
607 const FileSpec &file, uint32_t line,
608 Function *function,
609 std::vector<Address> &output_local,
610 std::vector<Address> &output_extern) {
611 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
612 for (const ModuleSP &module_sp : m_modules) {
613 module_sp->FindAddressesForLine(target_sp, file, line, function,
614 output_local, output_extern);
615 }
616 }
617
FindFirstModule(const ModuleSpec & module_spec) const618 ModuleSP ModuleList::FindFirstModule(const ModuleSpec &module_spec) const {
619 ModuleSP module_sp;
620 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
621 collection::const_iterator pos, end = m_modules.end();
622 for (pos = m_modules.begin(); pos != end; ++pos) {
623 ModuleSP module_sp(*pos);
624 if (module_sp->MatchesModuleSpec(module_spec))
625 return module_sp;
626 }
627 return module_sp;
628 }
629
GetSize() const630 size_t ModuleList::GetSize() const {
631 size_t size = 0;
632 {
633 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
634 size = m_modules.size();
635 }
636 return size;
637 }
638
Dump(Stream * s) const639 void ModuleList::Dump(Stream *s) const {
640 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
641 for (const ModuleSP &module_sp : m_modules)
642 module_sp->Dump(s);
643 }
644
LogUUIDAndPaths(Log * log,const char * prefix_cstr)645 void ModuleList::LogUUIDAndPaths(Log *log, const char *prefix_cstr) {
646 if (log != nullptr) {
647 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
648 collection::const_iterator pos, begin = m_modules.begin(),
649 end = m_modules.end();
650 for (pos = begin; pos != end; ++pos) {
651 Module *module = pos->get();
652 const FileSpec &module_file_spec = module->GetFileSpec();
653 LLDB_LOGF(log, "%s[%u] %s (%s) \"%s\"", prefix_cstr ? prefix_cstr : "",
654 (uint32_t)std::distance(begin, pos),
655 module->GetUUID().GetAsString().c_str(),
656 module->GetArchitecture().GetArchitectureName(),
657 module_file_spec.GetPath().c_str());
658 }
659 }
660 }
661
ResolveFileAddress(lldb::addr_t vm_addr,Address & so_addr) const662 bool ModuleList::ResolveFileAddress(lldb::addr_t vm_addr,
663 Address &so_addr) const {
664 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
665 for (const ModuleSP &module_sp : m_modules) {
666 if (module_sp->ResolveFileAddress(vm_addr, so_addr))
667 return true;
668 }
669
670 return false;
671 }
672
673 uint32_t
ResolveSymbolContextForAddress(const Address & so_addr,SymbolContextItem resolve_scope,SymbolContext & sc) const674 ModuleList::ResolveSymbolContextForAddress(const Address &so_addr,
675 SymbolContextItem resolve_scope,
676 SymbolContext &sc) const {
677 // The address is already section offset so it has a module
678 uint32_t resolved_flags = 0;
679 ModuleSP module_sp(so_addr.GetModule());
680 if (module_sp) {
681 resolved_flags =
682 module_sp->ResolveSymbolContextForAddress(so_addr, resolve_scope, sc);
683 } else {
684 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
685 collection::const_iterator pos, end = m_modules.end();
686 for (pos = m_modules.begin(); pos != end; ++pos) {
687 resolved_flags =
688 (*pos)->ResolveSymbolContextForAddress(so_addr, resolve_scope, sc);
689 if (resolved_flags != 0)
690 break;
691 }
692 }
693
694 return resolved_flags;
695 }
696
ResolveSymbolContextForFilePath(const char * file_path,uint32_t line,bool check_inlines,SymbolContextItem resolve_scope,SymbolContextList & sc_list) const697 uint32_t ModuleList::ResolveSymbolContextForFilePath(
698 const char *file_path, uint32_t line, bool check_inlines,
699 SymbolContextItem resolve_scope, SymbolContextList &sc_list) const {
700 FileSpec file_spec(file_path);
701 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
702 resolve_scope, sc_list);
703 }
704
ResolveSymbolContextsForFileSpec(const FileSpec & file_spec,uint32_t line,bool check_inlines,SymbolContextItem resolve_scope,SymbolContextList & sc_list) const705 uint32_t ModuleList::ResolveSymbolContextsForFileSpec(
706 const FileSpec &file_spec, uint32_t line, bool check_inlines,
707 SymbolContextItem resolve_scope, SymbolContextList &sc_list) const {
708 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
709 for (const ModuleSP &module_sp : m_modules) {
710 module_sp->ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
711 resolve_scope, sc_list);
712 }
713
714 return sc_list.GetSize();
715 }
716
GetIndexForModule(const Module * module) const717 size_t ModuleList::GetIndexForModule(const Module *module) const {
718 if (module) {
719 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
720 collection::const_iterator pos;
721 collection::const_iterator begin = m_modules.begin();
722 collection::const_iterator end = m_modules.end();
723 for (pos = begin; pos != end; ++pos) {
724 if ((*pos).get() == module)
725 return std::distance(begin, pos);
726 }
727 }
728 return LLDB_INVALID_INDEX32;
729 }
730
731 namespace {
732 struct SharedModuleListInfo {
733 ModuleList module_list;
734 ModuleListProperties module_list_properties;
735 };
736 }
GetSharedModuleListInfo()737 static SharedModuleListInfo &GetSharedModuleListInfo()
738 {
739 static SharedModuleListInfo *g_shared_module_list_info = nullptr;
740 static llvm::once_flag g_once_flag;
741 llvm::call_once(g_once_flag, []() {
742 // NOTE: Intentionally leak the module list so a program doesn't have to
743 // cleanup all modules and object files as it exits. This just wastes time
744 // doing a bunch of cleanup that isn't required.
745 if (g_shared_module_list_info == nullptr)
746 g_shared_module_list_info = new SharedModuleListInfo();
747 });
748 return *g_shared_module_list_info;
749 }
750
GetSharedModuleList()751 static ModuleList &GetSharedModuleList() {
752 return GetSharedModuleListInfo().module_list;
753 }
754
GetGlobalModuleListProperties()755 ModuleListProperties &ModuleList::GetGlobalModuleListProperties() {
756 return GetSharedModuleListInfo().module_list_properties;
757 }
758
ModuleIsInCache(const Module * module_ptr)759 bool ModuleList::ModuleIsInCache(const Module *module_ptr) {
760 if (module_ptr) {
761 ModuleList &shared_module_list = GetSharedModuleList();
762 return shared_module_list.FindModule(module_ptr).get() != nullptr;
763 }
764 return false;
765 }
766
FindSharedModules(const ModuleSpec & module_spec,ModuleList & matching_module_list)767 void ModuleList::FindSharedModules(const ModuleSpec &module_spec,
768 ModuleList &matching_module_list) {
769 GetSharedModuleList().FindModules(module_spec, matching_module_list);
770 }
771
RemoveOrphanSharedModules(bool mandatory)772 size_t ModuleList::RemoveOrphanSharedModules(bool mandatory) {
773 return GetSharedModuleList().RemoveOrphans(mandatory);
774 }
775
776 Status
GetSharedModule(const ModuleSpec & module_spec,ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr,llvm::SmallVectorImpl<lldb::ModuleSP> * old_modules,bool * did_create_ptr,bool always_create)777 ModuleList::GetSharedModule(const ModuleSpec &module_spec, ModuleSP &module_sp,
778 const FileSpecList *module_search_paths_ptr,
779 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules,
780 bool *did_create_ptr, bool always_create) {
781 ModuleList &shared_module_list = GetSharedModuleList();
782 std::lock_guard<std::recursive_mutex> guard(
783 shared_module_list.m_modules_mutex);
784 char path[PATH_MAX];
785
786 Status error;
787
788 module_sp.reset();
789
790 if (did_create_ptr)
791 *did_create_ptr = false;
792
793 const UUID *uuid_ptr = module_spec.GetUUIDPtr();
794 const FileSpec &module_file_spec = module_spec.GetFileSpec();
795 const ArchSpec &arch = module_spec.GetArchitecture();
796
797 // Make sure no one else can try and get or create a module while this
798 // function is actively working on it by doing an extra lock on the global
799 // mutex list.
800 if (!always_create) {
801 ModuleList matching_module_list;
802 shared_module_list.FindModules(module_spec, matching_module_list);
803 const size_t num_matching_modules = matching_module_list.GetSize();
804
805 if (num_matching_modules > 0) {
806 for (size_t module_idx = 0; module_idx < num_matching_modules;
807 ++module_idx) {
808 module_sp = matching_module_list.GetModuleAtIndex(module_idx);
809
810 // Make sure the file for the module hasn't been modified
811 if (module_sp->FileHasChanged()) {
812 if (old_modules)
813 old_modules->push_back(module_sp);
814
815 Log *log = GetLog(LLDBLog::Modules);
816 if (log != nullptr)
817 LLDB_LOGF(
818 log, "%p '%s' module changed: removing from global module list",
819 static_cast<void *>(module_sp.get()),
820 module_sp->GetFileSpec().GetFilename().GetCString());
821
822 shared_module_list.Remove(module_sp);
823 module_sp.reset();
824 } else {
825 // The module matches and the module was not modified from when it
826 // was last loaded.
827 return error;
828 }
829 }
830 }
831 }
832
833 if (module_sp)
834 return error;
835
836 module_sp = std::make_shared<Module>(module_spec);
837 // Make sure there are a module and an object file since we can specify a
838 // valid file path with an architecture that might not be in that file. By
839 // getting the object file we can guarantee that the architecture matches
840 if (module_sp->GetObjectFile()) {
841 // If we get in here we got the correct arch, now we just need to verify
842 // the UUID if one was given
843 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
844 module_sp.reset();
845 } else {
846 if (module_sp->GetObjectFile() &&
847 module_sp->GetObjectFile()->GetType() ==
848 ObjectFile::eTypeStubLibrary) {
849 module_sp.reset();
850 } else {
851 if (did_create_ptr) {
852 *did_create_ptr = true;
853 }
854
855 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
856 return error;
857 }
858 }
859 } else {
860 module_sp.reset();
861 }
862
863 if (module_search_paths_ptr) {
864 const auto num_directories = module_search_paths_ptr->GetSize();
865 for (size_t idx = 0; idx < num_directories; ++idx) {
866 auto search_path_spec = module_search_paths_ptr->GetFileSpecAtIndex(idx);
867 FileSystem::Instance().Resolve(search_path_spec);
868 namespace fs = llvm::sys::fs;
869 if (!FileSystem::Instance().IsDirectory(search_path_spec))
870 continue;
871 search_path_spec.AppendPathComponent(
872 module_spec.GetFileSpec().GetFilename().GetStringRef());
873 if (!FileSystem::Instance().Exists(search_path_spec))
874 continue;
875
876 auto resolved_module_spec(module_spec);
877 resolved_module_spec.GetFileSpec() = search_path_spec;
878 module_sp = std::make_shared<Module>(resolved_module_spec);
879 if (module_sp->GetObjectFile()) {
880 // If we get in here we got the correct arch, now we just need to
881 // verify the UUID if one was given
882 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
883 module_sp.reset();
884 } else {
885 if (module_sp->GetObjectFile()->GetType() ==
886 ObjectFile::eTypeStubLibrary) {
887 module_sp.reset();
888 } else {
889 if (did_create_ptr)
890 *did_create_ptr = true;
891
892 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
893 return Status();
894 }
895 }
896 } else {
897 module_sp.reset();
898 }
899 }
900 }
901
902 // Either the file didn't exist where at the path, or no path was given, so
903 // we now have to use more extreme measures to try and find the appropriate
904 // module.
905
906 // Fixup the incoming path in case the path points to a valid file, yet the
907 // arch or UUID (if one was passed in) don't match.
908 ModuleSpec located_binary_modulespec =
909 Symbols::LocateExecutableObjectFile(module_spec);
910
911 // Don't look for the file if it appears to be the same one we already
912 // checked for above...
913 if (located_binary_modulespec.GetFileSpec() != module_file_spec) {
914 if (!FileSystem::Instance().Exists(
915 located_binary_modulespec.GetFileSpec())) {
916 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
917 if (path[0] == '\0')
918 module_file_spec.GetPath(path, sizeof(path));
919 // How can this check ever be true? This branch it is false, and we
920 // haven't modified file_spec.
921 if (FileSystem::Instance().Exists(
922 located_binary_modulespec.GetFileSpec())) {
923 std::string uuid_str;
924 if (uuid_ptr && uuid_ptr->IsValid())
925 uuid_str = uuid_ptr->GetAsString();
926
927 if (arch.IsValid()) {
928 if (!uuid_str.empty())
929 error.SetErrorStringWithFormat(
930 "'%s' does not contain the %s architecture and UUID %s", path,
931 arch.GetArchitectureName(), uuid_str.c_str());
932 else
933 error.SetErrorStringWithFormat(
934 "'%s' does not contain the %s architecture.", path,
935 arch.GetArchitectureName());
936 }
937 } else {
938 error.SetErrorStringWithFormat("'%s' does not exist", path);
939 }
940 if (error.Fail())
941 module_sp.reset();
942 return error;
943 }
944
945 // Make sure no one else can try and get or create a module while this
946 // function is actively working on it by doing an extra lock on the global
947 // mutex list.
948 ModuleSpec platform_module_spec(module_spec);
949 platform_module_spec.GetFileSpec() =
950 located_binary_modulespec.GetFileSpec();
951 platform_module_spec.GetPlatformFileSpec() =
952 located_binary_modulespec.GetFileSpec();
953 platform_module_spec.GetSymbolFileSpec() =
954 located_binary_modulespec.GetSymbolFileSpec();
955 ModuleList matching_module_list;
956 shared_module_list.FindModules(platform_module_spec, matching_module_list);
957 if (!matching_module_list.IsEmpty()) {
958 module_sp = matching_module_list.GetModuleAtIndex(0);
959
960 // If we didn't have a UUID in mind when looking for the object file,
961 // then we should make sure the modification time hasn't changed!
962 if (platform_module_spec.GetUUIDPtr() == nullptr) {
963 auto file_spec_mod_time = FileSystem::Instance().GetModificationTime(
964 located_binary_modulespec.GetFileSpec());
965 if (file_spec_mod_time != llvm::sys::TimePoint<>()) {
966 if (file_spec_mod_time != module_sp->GetModificationTime()) {
967 if (old_modules)
968 old_modules->push_back(module_sp);
969 shared_module_list.Remove(module_sp);
970 module_sp.reset();
971 }
972 }
973 }
974 }
975
976 if (!module_sp) {
977 module_sp = std::make_shared<Module>(platform_module_spec);
978 // Make sure there are a module and an object file since we can specify a
979 // valid file path with an architecture that might not be in that file.
980 // By getting the object file we can guarantee that the architecture
981 // matches
982 if (module_sp && module_sp->GetObjectFile()) {
983 if (module_sp->GetObjectFile()->GetType() ==
984 ObjectFile::eTypeStubLibrary) {
985 module_sp.reset();
986 } else {
987 if (did_create_ptr)
988 *did_create_ptr = true;
989
990 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
991 }
992 } else {
993 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
994
995 if (located_binary_modulespec.GetFileSpec()) {
996 if (arch.IsValid())
997 error.SetErrorStringWithFormat(
998 "unable to open %s architecture in '%s'",
999 arch.GetArchitectureName(), path);
1000 else
1001 error.SetErrorStringWithFormat("unable to open '%s'", path);
1002 } else {
1003 std::string uuid_str;
1004 if (uuid_ptr && uuid_ptr->IsValid())
1005 uuid_str = uuid_ptr->GetAsString();
1006
1007 if (!uuid_str.empty())
1008 error.SetErrorStringWithFormat(
1009 "cannot locate a module for UUID '%s'", uuid_str.c_str());
1010 else
1011 error.SetErrorString("cannot locate a module");
1012 }
1013 }
1014 }
1015 }
1016
1017 return error;
1018 }
1019
RemoveSharedModule(lldb::ModuleSP & module_sp)1020 bool ModuleList::RemoveSharedModule(lldb::ModuleSP &module_sp) {
1021 return GetSharedModuleList().Remove(module_sp);
1022 }
1023
RemoveSharedModuleIfOrphaned(const Module * module_ptr)1024 bool ModuleList::RemoveSharedModuleIfOrphaned(const Module *module_ptr) {
1025 return GetSharedModuleList().RemoveIfOrphaned(module_ptr);
1026 }
1027
LoadScriptingResourcesInTarget(Target * target,std::list<Status> & errors,Stream * feedback_stream,bool continue_on_error)1028 bool ModuleList::LoadScriptingResourcesInTarget(Target *target,
1029 std::list<Status> &errors,
1030 Stream *feedback_stream,
1031 bool continue_on_error) {
1032 if (!target)
1033 return false;
1034 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1035 for (auto module : m_modules) {
1036 Status error;
1037 if (module) {
1038 if (!module->LoadScriptingResourceInTarget(target, error,
1039 feedback_stream)) {
1040 if (error.Fail() && error.AsCString()) {
1041 error.SetErrorStringWithFormat("unable to load scripting data for "
1042 "module %s - error reported was %s",
1043 module->GetFileSpec()
1044 .GetFileNameStrippingExtension()
1045 .GetCString(),
1046 error.AsCString());
1047 errors.push_back(error);
1048
1049 if (!continue_on_error)
1050 return false;
1051 }
1052 }
1053 }
1054 }
1055 return errors.empty();
1056 }
1057
ForEach(std::function<bool (const ModuleSP & module_sp)> const & callback) const1058 void ModuleList::ForEach(
1059 std::function<bool(const ModuleSP &module_sp)> const &callback) const {
1060 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1061 for (const auto &module : m_modules) {
1062 // If the callback returns false, then stop iterating and break out
1063 if (!callback(module))
1064 break;
1065 }
1066 }
1067