LLDB mainline
ModuleList.cpp
Go to the documentation of this file.
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
10#include "lldb/Core/Debugger.h"
11#include "lldb/Core/Module.h"
24#include "lldb/Target/Target.h"
29#include "lldb/Utility/Log.h"
30#include "lldb/Utility/UUID.h"
31#include "lldb/lldb-defines.h"
32#include "llvm/Support/ThreadPool.h"
33
34#if defined(_WIN32)
36#endif
37
38#include "llvm/ADT/StringRef.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/Threading.h"
41#include "llvm/Support/raw_ostream.h"
42
43#include <chrono>
44#include <memory>
45#include <mutex>
46#include <string>
47#include <utility>
48
49namespace lldb_private {
50class Function;
51}
52namespace lldb_private {
54}
55namespace lldb_private {
56class Stream;
57}
58namespace lldb_private {
59class SymbolFile;
60}
61namespace lldb_private {
62class Target;
63}
64
65using namespace lldb;
66using namespace lldb_private;
67
68namespace {
69
70#define LLDB_PROPERTIES_modulelist
71#include "CoreProperties.inc"
72
73enum {
74#define LLDB_PROPERTIES_modulelist
75#include "CorePropertiesEnum.inc"
76};
77
78} // namespace
79
81 m_collection_sp = std::make_shared<OptionValueProperties>("symbols");
82 m_collection_sp->Initialize(g_modulelist_properties_def);
83 m_collection_sp->SetValueChangedCallback(ePropertySymLinkPaths,
84 [this] { UpdateSymlinkMappings(); });
85
86 llvm::SmallString<128> path;
87 if (llvm::sys::path::cache_directory(path)) {
88 llvm::sys::path::append(path, "lldb");
89 llvm::sys::path::append(path, "IndexCache");
91 }
92}
93
95 const uint32_t idx = ePropertyEnableExternalLookup;
97 idx, g_modulelist_properties[idx].default_uint_value != 0);
98}
99
101 return SetPropertyAtIndex(ePropertyEnableExternalLookup, new_value);
102}
103
105 // Backward compatibility alias.
106 if (GetPropertyAtIndexAs<bool>(ePropertyEnableBackgroundLookup, false))
108
109 const uint32_t idx = ePropertyAutoDownload;
111 idx, static_cast<lldb::SymbolDownload>(
112 g_modulelist_properties[idx].default_uint_value));
113}
114
116 const uint32_t idx = ePropertySharedCacheBinaryLoading;
118 idx, static_cast<lldb::SymbolSharedCacheUse>(
119 g_modulelist_properties[idx].default_uint_value));
120}
121
123 const uint32_t idx = ePropertyClangModulesCachePath;
124 return GetPropertyAtIndexAs<FileSpec>(idx, {});
125}
126
128 const uint32_t idx = ePropertyClangModulesCachePath;
129 return SetPropertyAtIndex(idx, path);
130}
131
133 const uint32_t idx = ePropertyLLDBIndexCachePath;
134 return GetPropertyAtIndexAs<FileSpec>(idx, {});
135}
136
138 const uint32_t idx = ePropertyLLDBIndexCachePath;
139 return SetPropertyAtIndex(idx, path);
140}
141
143 const uint32_t idx = ePropertyEnableLLDBIndexCache;
145 idx, g_modulelist_properties[idx].default_uint_value != 0);
146}
147
149 return SetPropertyAtIndex(ePropertyEnableLLDBIndexCache, new_value);
150}
151
153 const uint32_t idx = ePropertyEnableLLDBIndexCacheMemoryModules;
155 idx, g_modulelist_properties[idx].default_uint_value != 0);
156}
157
159 bool new_value) {
160 return SetPropertyAtIndex(ePropertyEnableLLDBIndexCacheMemoryModules,
161 new_value);
162}
163
165 const uint32_t idx = ePropertyLLDBIndexCacheMaxByteSize;
167 idx, g_modulelist_properties[idx].default_uint_value);
168}
169
171 const uint32_t idx = ePropertyLLDBIndexCacheMaxPercent;
173 idx, g_modulelist_properties[idx].default_uint_value);
174}
175
177 const uint32_t idx = ePropertyLLDBIndexCacheExpirationDays;
179 idx, g_modulelist_properties[idx].default_uint_value);
180}
181
183 FileSpecList list =
184 GetPropertyAtIndexAs<FileSpecList>(ePropertySymLinkPaths, {});
185 llvm::sys::ScopedWriter lock(m_symlink_paths_mutex);
186 const bool notify = false;
187 m_symlink_paths.Clear(notify);
188 for (auto symlink : list) {
189 FileSpec resolved;
190 Status status = FileSystem::Instance().Readlink(symlink, resolved);
191 if (status.Success())
192 m_symlink_paths.Append(symlink.GetPath(), resolved.GetPath(), notify);
193 }
194}
195
197 llvm::sys::ScopedReader lock(m_symlink_paths_mutex);
198 return m_symlink_paths;
199}
200
202 const uint32_t idx = ePropertyLoadSymbolOnDemand;
204 idx, g_modulelist_properties[idx].default_uint_value != 0);
205}
206
208 const uint32_t idx = ePropertyDemangledNameInfoCacheSize;
210 idx, g_modulelist_properties[idx].default_uint_value);
211}
212
214
216 std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex);
217 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex);
218 m_modules = rhs.m_modules;
219}
220
223
225 if (this != &rhs) {
226 std::lock(m_modules_mutex, rhs.m_modules_mutex);
227 std::lock_guard<std::recursive_mutex> lhs_guard(m_modules_mutex,
228 std::adopt_lock);
229 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.m_modules_mutex,
230 std::adopt_lock);
231 m_modules = rhs.m_modules;
232 }
233 return *this;
234}
235
236ModuleList::~ModuleList() = default;
237
238void ModuleList::AppendImpl(const ModuleSP &module_sp, bool use_notifier) {
239 if (!module_sp)
240 return;
241 {
242 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
243 // We are required to keep the first element of the Module List as the
244 // executable module. So check here and if the first module is NOT an
245 // but the new one is, we insert this module at the beginning, rather than
246 // at the end.
247 // We don't need to do any of this if the list is empty:
248 if (m_modules.empty()) {
249 m_modules.push_back(module_sp);
250 } else {
251 // Since producing the ObjectFile may take some work, first check the
252 // 0th element, and only if that's NOT an executable look at the
253 // incoming ObjectFile. That way in the normal case we only look at the
254 // element 0 ObjectFile.
255 lldb_private::ObjectFile *elem_zero_obj = m_modules[0]->GetObjectFile();
256 const bool elem_zero_is_executable =
257 elem_zero_obj &&
258 elem_zero_obj->GetType() == ObjectFile::Type::eTypeExecutable;
259 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
260 if (!elem_zero_is_executable && obj &&
262 m_modules.insert(m_modules.begin(), module_sp);
263 } else {
264 m_modules.push_back(module_sp);
265 }
266 }
267 }
268 // Release the mutex before calling the notifier to avoid deadlock
269 // NotifyModuleAdded should be thread-safe
270 if (use_notifier && m_notifier)
271 m_notifier->NotifyModuleAdded(*this, module_sp);
272}
273
274void ModuleList::Append(const ModuleSP &module_sp, bool notify) {
275 AppendImpl(module_sp, notify);
276}
277
279 const ModuleSP &module_sp,
281 if (module_sp) {
282 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
283
284 // First remove any equivalent modules. Equivalent modules are modules
285 // whose path, platform path and architecture match.
286 ModuleSpec equivalent_module_spec(module_sp->GetFileSpec(),
287 module_sp->GetArchitecture());
288 equivalent_module_spec.GetPlatformFileSpec() =
289 module_sp->GetPlatformFileSpec();
290
291 size_t idx = 0;
292 while (idx < m_modules.size()) {
293 ModuleSP test_module_sp(m_modules[idx]);
294 if (test_module_sp->MatchesModuleSpec(equivalent_module_spec)) {
295 if (old_modules)
296 old_modules->push_back(test_module_sp);
297 RemoveImpl(m_modules.begin() + idx);
298 } else {
299 ++idx;
300 }
301 }
302 // Now add the new module to the list
303 Append(module_sp);
304 }
305}
306
307bool ModuleList::AppendIfNeeded(const ModuleSP &new_module, bool notify) {
308 if (new_module) {
309 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
310 for (const ModuleSP &module_sp : m_modules) {
311 if (module_sp.get() == new_module.get())
312 return false; // Already in the list
313 }
314 // Only push module_sp on the list if it wasn't already in there.
315 Append(new_module, notify);
316 return true;
317 }
318 return false;
319}
320
321void ModuleList::Append(const ModuleList &module_list) {
322 for (auto pos : module_list.m_modules)
323 Append(pos);
324}
325
326bool ModuleList::AppendIfNeeded(const ModuleList &module_list) {
327 bool any_in = false;
328 for (auto pos : module_list.m_modules) {
329 if (AppendIfNeeded(pos))
330 any_in = true;
331 }
332 return any_in;
333}
334
335bool ModuleList::RemoveImpl(const ModuleSP &module_sp, bool use_notifier) {
336 if (module_sp) {
337 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
338 collection::iterator pos, end = m_modules.end();
339 for (pos = m_modules.begin(); pos != end; ++pos) {
340 if (pos->get() == module_sp.get()) {
341 m_modules.erase(pos);
342 if (use_notifier && m_notifier)
343 m_notifier->NotifyModuleRemoved(*this, module_sp);
344 return true;
345 }
346 }
347 }
348 return false;
349}
350
351ModuleList::collection::iterator
352ModuleList::RemoveImpl(ModuleList::collection::iterator pos,
353 bool use_notifier) {
354 ModuleSP module_sp(*pos);
355 collection::iterator retval = m_modules.erase(pos);
356 if (use_notifier && m_notifier)
357 m_notifier->NotifyModuleRemoved(*this, module_sp);
358 return retval;
359}
360
361bool ModuleList::Remove(const ModuleSP &module_sp, bool notify) {
362 return RemoveImpl(module_sp, notify);
363}
364
366 const lldb::ModuleSP &new_module_sp) {
367 if (!RemoveImpl(old_module_sp, false))
368 return false;
369 AppendImpl(new_module_sp, false);
370 if (m_notifier)
371 m_notifier->NotifyModuleUpdated(*this, old_module_sp, new_module_sp);
372 return true;
373}
374
376 if (auto module_sp = module_wp.lock()) {
377 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
378 collection::iterator pos, end = m_modules.end();
379 for (pos = m_modules.begin(); pos != end; ++pos) {
380 if (pos->get() == module_sp.get()) {
381 // Since module_sp increases the refcount by 1, the use count should be
382 // the regular use count + 1.
383 constexpr long kUseCountOrphaned = kUseCountModuleListOrphaned + 1;
384 if (pos->use_count() == kUseCountOrphaned) {
385 pos = RemoveImpl(pos);
386 return true;
387 }
388 return false;
389 }
390 }
391 }
392 return false;
393}
394
395size_t ModuleList::RemoveOrphans(bool mandatory) {
396 std::unique_lock<std::recursive_mutex> lock(m_modules_mutex, std::defer_lock);
397
398 if (mandatory) {
399 lock.lock();
400 } else {
401 // Not mandatory, remove orphans if we can get the mutex
402 if (!lock.try_lock())
403 return 0;
404 }
405 size_t remove_count = 0;
406 // Modules might hold shared pointers to other modules, so removing one
407 // module might make other modules orphans. Keep removing modules until
408 // there are no further modules that can be removed.
409 bool made_progress = true;
410 while (made_progress) {
411 // Keep track if we make progress this iteration.
412 made_progress = false;
413 collection::iterator pos = m_modules.begin();
414 while (pos != m_modules.end()) {
415 if (pos->use_count() == kUseCountModuleListOrphaned) {
416 pos = RemoveImpl(pos);
417 ++remove_count;
418 // We did make progress.
419 made_progress = true;
420 } else {
421 ++pos;
422 }
423 }
424 }
425 return remove_count;
426}
427
428size_t ModuleList::Remove(ModuleList &module_list) {
429 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
430 size_t num_removed = 0;
431 collection::iterator pos, end = module_list.m_modules.end();
432 for (pos = module_list.m_modules.begin(); pos != end; ++pos) {
433 if (Remove(*pos, false /* notify */))
434 ++num_removed;
435 }
436 if (m_notifier)
437 m_notifier->NotifyModulesRemoved(module_list);
438 return num_removed;
439}
440
442
444
445void ModuleList::ClearImpl(bool use_notifier) {
446 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
447 if (use_notifier && m_notifier)
448 m_notifier->NotifyWillClearList(*this);
449 m_modules.clear();
450}
451
453 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
454 if (idx < m_modules.size())
455 return m_modules[idx].get();
456 return nullptr;
457}
458
460 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
461 return GetModuleAtIndexUnlocked(idx);
462}
463
465 ModuleSP module_sp;
466 if (idx < m_modules.size())
467 module_sp = m_modules[idx];
468 return module_sp;
469}
470
472 FunctionNameType name_type_mask,
473 const ModuleFunctionSearchOptions &options,
474 SymbolContextList &sc_list) const {
475 if (name_type_mask & eFunctionNameTypeAuto) {
476 std::vector<Module::LookupInfo> lookup_infos =
477 Module::LookupInfo::MakeLookupInfos(name, name_type_mask,
479 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
480 for (const auto &lookup_info : lookup_infos) {
481 const size_t old_size = sc_list.GetSize();
482 for (const ModuleSP &module_sp : m_modules) {
483 module_sp->FindFunctions(lookup_info, CompilerDeclContext(), options,
484 sc_list);
485 }
486
487 const size_t new_size = sc_list.GetSize();
488 if (old_size < new_size)
489 lookup_info.Prune(sc_list, old_size);
490 }
491 } else {
492 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
493 for (const ModuleSP &module_sp : m_modules) {
494 module_sp->FindFunctions(name, CompilerDeclContext(), name_type_mask,
495 options, sc_list);
496 }
497 }
498}
499
501 lldb::FunctionNameType name_type_mask,
502 SymbolContextList &sc_list) {
503 if (name_type_mask & eFunctionNameTypeAuto) {
504 std::vector<Module::LookupInfo> lookup_infos =
505 Module::LookupInfo::MakeLookupInfos(name, name_type_mask,
507
508 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
509 for (const auto &lookup_info : lookup_infos) {
510 const size_t old_size = sc_list.GetSize();
511 for (const ModuleSP &module_sp : m_modules) {
512 module_sp->FindFunctionSymbols(lookup_info.GetLookupName(),
513 lookup_info.GetNameTypeMask(), sc_list);
514 }
515
516 const size_t new_size = sc_list.GetSize();
517
518 if (old_size < new_size)
519 lookup_info.Prune(sc_list, old_size);
520 }
521 } else {
522 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
523 for (const ModuleSP &module_sp : m_modules) {
524 module_sp->FindFunctionSymbols(name, name_type_mask, sc_list);
525 }
526 }
527}
528
530 const ModuleFunctionSearchOptions &options,
531 SymbolContextList &sc_list) {
532 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
533 for (const ModuleSP &module_sp : m_modules)
534 module_sp->FindFunctions(name, options, sc_list);
535}
536
538 SymbolContextList &sc_list) const {
539 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
540 for (const ModuleSP &module_sp : m_modules)
541 module_sp->FindCompileUnits(path, sc_list);
542}
543
544void ModuleList::FindGlobalVariables(ConstString name, size_t max_matches,
545 VariableList &variable_list) const {
546 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
547 for (const ModuleSP &module_sp : m_modules) {
548 module_sp->FindGlobalVariables(name, CompilerDeclContext(), max_matches,
549 variable_list);
550 }
551}
552
554 size_t max_matches,
555 VariableList &variable_list) const {
556 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
557 for (const ModuleSP &module_sp : m_modules)
558 module_sp->FindGlobalVariables(regex, max_matches, variable_list);
559}
560
562 SymbolType symbol_type,
563 SymbolContextList &sc_list) const {
564 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
565 for (const ModuleSP &module_sp : m_modules)
566 module_sp->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
567}
568
570 const RegularExpression &regex, lldb::SymbolType symbol_type,
571 SymbolContextList &sc_list) const {
572 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
573 for (const ModuleSP &module_sp : m_modules)
574 module_sp->FindSymbolsMatchingRegExAndType(regex, symbol_type, sc_list);
575}
576
577void ModuleList::FindModules(const ModuleSpec &module_spec,
578 ModuleList &matching_module_list) const {
579 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
580 for (const ModuleSP &module_sp : m_modules) {
581 if (module_sp->MatchesModuleSpec(module_spec))
582 matching_module_list.Append(module_sp);
583 }
584}
585
586ModuleSP ModuleList::FindModule(const Module *module_ptr) const {
587 ModuleSP module_sp;
588
589 // Scope for "locker"
590 {
591 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
592 collection::const_iterator pos, end = m_modules.end();
593
594 for (pos = m_modules.begin(); pos != end; ++pos) {
595 if ((*pos).get() == module_ptr) {
596 module_sp = (*pos);
597 break;
598 }
599 }
600 }
601 return module_sp;
602}
603
605 ModuleSP module_sp;
606
607 if (uuid.IsValid()) {
608 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
609 collection::const_iterator pos, end = m_modules.end();
610
611 for (pos = m_modules.begin(); pos != end; ++pos) {
612 if ((*pos)->GetUUID() == uuid) {
613 module_sp = (*pos);
614 break;
615 }
616 }
617 }
618 return module_sp;
619}
620
622 ModuleSP module_sp;
623 ForEach([&](const ModuleSP &m) {
624 if (m->GetID() == uid) {
625 module_sp = m;
627 }
628
630 });
631
632 return module_sp;
633}
634
635void ModuleList::FindTypes(Module *search_first, const TypeQuery &query,
636 TypeResults &results) const {
637 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
638 if (search_first) {
639 search_first->FindTypes(query, results);
640 if (results.Done(query))
641 return;
642 }
643 for (const auto &module_sp : m_modules) {
644 if (search_first != module_sp.get()) {
645 module_sp->FindTypes(query, results);
646 if (results.Done(query))
647 return;
648 }
649 }
650}
651
653 FileSpec &new_spec) const {
654 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
655 for (const ModuleSP &module_sp : m_modules) {
656 if (module_sp->FindSourceFile(orig_spec, new_spec))
657 return true;
658 }
659 return false;
660}
661
663 const FileSpec &file, uint32_t line,
664 Function *function,
665 std::vector<Address> &output_local,
666 std::vector<Address> &output_extern) {
667 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
668 for (const ModuleSP &module_sp : m_modules) {
669 module_sp->FindAddressesForLine(target_sp, file, line, function,
670 output_local, output_extern);
671 }
672}
673
675 ModuleSP module_sp;
676 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
677 collection::const_iterator pos, end = m_modules.end();
678 for (pos = m_modules.begin(); pos != end; ++pos) {
679 ModuleSP module_sp(*pos);
680 if (module_sp->MatchesModuleSpec(module_spec))
681 return module_sp;
682 }
683 return module_sp;
684}
685
686size_t ModuleList::GetSize() const {
687 size_t size = 0;
688 {
689 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
690 size = m_modules.size();
691 }
692 return size;
693}
694
695void ModuleList::Dump(Stream *s) const {
696 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
697 for (const ModuleSP &module_sp : m_modules)
698 module_sp->Dump(s);
699}
700
701void ModuleList::LogUUIDAndPaths(Log *log, const char *prefix_cstr) {
702 if (log != nullptr) {
703 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
704 collection::const_iterator pos, begin = m_modules.begin(),
705 end = m_modules.end();
706 for (pos = begin; pos != end; ++pos) {
707 Module *module = pos->get();
708 const FileSpec &module_file_spec = module->GetFileSpec();
709 LLDB_LOGF(log, "%s[%u] %s (%s) \"%s\"", prefix_cstr ? prefix_cstr : "",
710 (uint32_t)std::distance(begin, pos),
711 module->GetUUID().GetAsString().c_str(),
713 module_file_spec.GetPath().c_str());
714 }
715 }
716}
717
719 Address &so_addr) const {
720 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
721 for (const ModuleSP &module_sp : m_modules) {
722 if (module_sp->ResolveFileAddress(vm_addr, so_addr))
723 return true;
724 }
725
726 return false;
727}
728
729uint32_t
731 SymbolContextItem resolve_scope,
732 SymbolContext &sc) const {
733 // The address is already section offset so it has a module
734 uint32_t resolved_flags = 0;
735 ModuleSP module_sp(so_addr.GetModule());
736 if (module_sp) {
737 resolved_flags =
738 module_sp->ResolveSymbolContextForAddress(so_addr, resolve_scope, sc);
739 } else {
740 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
741 collection::const_iterator pos, end = m_modules.end();
742 for (pos = m_modules.begin(); pos != end; ++pos) {
743 resolved_flags =
744 (*pos)->ResolveSymbolContextForAddress(so_addr, resolve_scope, sc);
745 if (resolved_flags != 0)
746 break;
747 }
748 }
749
750 return resolved_flags;
751}
752
754 const char *file_path, uint32_t line, bool check_inlines,
755 SymbolContextItem resolve_scope, SymbolContextList &sc_list) const {
756 FileSpec file_spec(file_path);
757 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
758 resolve_scope, sc_list);
759}
760
762 const FileSpec &file_spec, uint32_t line, bool check_inlines,
763 SymbolContextItem resolve_scope, SymbolContextList &sc_list) const {
764 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
765 for (const ModuleSP &module_sp : m_modules) {
766 module_sp->ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
767 resolve_scope, sc_list);
768 }
769
770 return sc_list.GetSize();
771}
772
773size_t ModuleList::GetIndexForModule(const Module *module) const {
774 if (module) {
775 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
776 collection::const_iterator pos;
777 collection::const_iterator begin = m_modules.begin();
778 collection::const_iterator end = m_modules.end();
779 for (pos = begin; pos != end; ++pos) {
780 if ((*pos).get() == module)
781 return std::distance(begin, pos);
782 }
783 }
785}
786
787namespace {
788/// A wrapper around ModuleList for shared modules. Provides fast lookups for
789/// file-based ModuleSpec queries.
790class SharedModuleList {
791public:
792 /// Finds all the modules matching the module_spec, and adds them to \p
793 /// matching_module_list.
794 void FindModules(const ModuleSpec &module_spec,
795 ModuleList &matching_module_list) const {
796 std::lock_guard<std::recursive_mutex> guard(GetMutex());
797 // Try map first for performance - if found, skip expensive full list
798 // search.
799 FindModulesInMap(module_spec, matching_module_list);
800 if (!matching_module_list.IsEmpty())
801 return;
802 m_list.FindModules(module_spec, matching_module_list);
803 // Assert that modules were found in the list but not the map, it's
804 // because the module_spec has no filename or the found module has a
805 // different filename. For example, when searching by UUID and finding a
806 // module with an alias.
807 assert((matching_module_list.IsEmpty() ||
808 module_spec.GetFileSpec().GetFilename().empty() ||
809 module_spec.GetFileSpec().GetFilename() !=
810 matching_module_list.GetModuleAtIndex(0)
811 ->GetFileSpec()
812 .GetFilename()) &&
813 "Search by name not found in SharedModuleList's map");
814 }
815
816 ModuleSP FindModule(const Module &module) {
817
818 std::lock_guard<std::recursive_mutex> guard(GetMutex());
819 if (ModuleSP result = FindModuleInMap(module))
820 return result;
821 return m_list.FindModule(&module);
822 }
823
824 // UUID searches bypass map since UUIDs aren't indexed by filename.
825 ModuleSP FindModule(const UUID &uuid) const {
826 return m_list.FindModule(uuid);
827 }
828
829 void Append(const ModuleSP &module_sp, bool use_notifier) {
830 if (!module_sp)
831 return;
832 std::lock_guard<std::recursive_mutex> guard(GetMutex());
833 m_list.Append(module_sp, use_notifier);
834 AddToMap(module_sp);
835 }
836
837 size_t RemoveOrphans(bool mandatory) {
838 std::unique_lock<std::recursive_mutex> lock(GetMutex(), std::defer_lock);
839 if (mandatory) {
840 lock.lock();
841 } else {
842 if (!lock.try_lock())
843 return 0;
844 }
845 size_t total_count = 0;
846 size_t run_count;
847 do {
848 // Remove indexed orphans first, then remove non-indexed orphans. This
849 // order is important because the shared count will be different if a
850 // module is indexed or not.
851 run_count = RemoveOrphansFromMapAndList();
852 run_count += m_list.RemoveOrphans(mandatory);
853 total_count += run_count;
854 // Because removing orphans might make new orphans, remove from both
855 // containers until a fixed-point is reached.
856 } while (run_count != 0);
857
858 return total_count;
859 }
860
861 bool Remove(const ModuleSP &module_sp, bool use_notifier = true) {
862 if (!module_sp)
863 return false;
864 std::lock_guard<std::recursive_mutex> guard(GetMutex());
865 RemoveFromMap(module_sp);
866 return m_list.Remove(module_sp, use_notifier);
867 }
868
869 void ReplaceEquivalent(const ModuleSP &module_sp,
870 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules) {
871 std::lock_guard<std::recursive_mutex> guard(GetMutex());
872 m_list.ReplaceEquivalent(module_sp, old_modules);
873 ReplaceEquivalentInMap(module_sp);
874 }
875
876 bool RemoveIfOrphaned(const ModuleWP module_wp) {
877 std::lock_guard<std::recursive_mutex> guard(GetMutex());
878 RemoveFromMap(module_wp, /*if_orphaned=*/true);
879 return m_list.RemoveIfOrphaned(module_wp);
880 }
881
882 std::recursive_mutex &GetMutex() const { return m_list.GetMutex(); }
883
884private:
885 ModuleSP FindModuleInMap(const Module &module) const {
886 if (module.GetFileSpec().GetFilename().empty())
887 return ModuleSP();
888 llvm::StringRef name = module.GetFileSpec().GetFilename();
889 auto it = m_name_to_modules.find(name);
890 if (it == m_name_to_modules.end())
891 return ModuleSP();
892 const llvm::SmallVectorImpl<ModuleSP> &vector = it->second;
893 for (const ModuleSP &module_sp : vector) {
894 if (module_sp.get() == &module)
895 return module_sp;
896 }
897 return ModuleSP();
898 }
899
900 void FindModulesInMap(const ModuleSpec &module_spec,
901 ModuleList &matching_module_list) const {
902 auto it = m_name_to_modules.find(module_spec.GetFileSpec().GetFilename());
903 if (it == m_name_to_modules.end())
904 return;
905 const llvm::SmallVectorImpl<ModuleSP> &vector = it->second;
906 for (const ModuleSP &module_sp : vector) {
907 if (module_sp->MatchesModuleSpec(module_spec))
908 matching_module_list.Append(module_sp);
909 }
910 }
911
912 void AddToMap(const ModuleSP &module_sp) {
913 llvm::StringRef name = module_sp->GetFileSpec().GetFilename();
914 if (name.empty())
915 return;
916 m_name_to_modules[name].push_back(module_sp);
917 }
918
919 void RemoveFromMap(const ModuleWP module_wp, bool if_orphaned = false) {
920 if (auto module_sp = module_wp.lock()) {
921 llvm::StringRef name = module_sp->GetFileSpec().GetFilename();
922 if (!m_name_to_modules.contains(name))
923 return;
924 llvm::SmallVectorImpl<ModuleSP> &vec = m_name_to_modules[name];
925 for (auto *it = vec.begin(); it != vec.end(); ++it) {
926 if (it->get() == module_sp.get()) {
927 // Since module_sp increases the refcount by 1, the use count should
928 // be the regular use count + 1.
929 constexpr long kUseCountOrphaned =
930 kUseCountSharedModuleListOrphaned + 1;
931 if (!if_orphaned || it->use_count() == kUseCountOrphaned) {
932 vec.erase(it);
933 break;
934 }
935 }
936 }
937 }
938 }
939
940 void ReplaceEquivalentInMap(const ModuleSP &module_sp) {
941 RemoveEquivalentModulesFromMap(module_sp);
942 AddToMap(module_sp);
943 }
944
945 void RemoveEquivalentModulesFromMap(const ModuleSP &module_sp) {
946 llvm::StringRef name = module_sp->GetFileSpec().GetFilename();
947 if (name.empty())
948 return;
949
950 auto it = m_name_to_modules.find(name);
951 if (it == m_name_to_modules.end())
952 return;
953
954 // First remove any equivalent modules. Equivalent modules are modules
955 // whose path, platform path and architecture match.
956 ModuleSpec equivalent_module_spec(module_sp->GetFileSpec(),
957 module_sp->GetArchitecture());
958 equivalent_module_spec.GetPlatformFileSpec() =
959 module_sp->GetPlatformFileSpec();
960
961 llvm::SmallVectorImpl<ModuleSP> &vec = it->second;
962 llvm::erase_if(vec, [&equivalent_module_spec](ModuleSP &element) {
963 return element->MatchesModuleSpec(equivalent_module_spec);
964 });
965 }
966
967 /// Remove orphans from the vector and return the removed modules.
968 ModuleList RemoveOrphansFromVector(llvm::SmallVectorImpl<ModuleSP> &vec) {
969 // remove_if moves the elements that match the condition to the end of the
970 // container, and returns an iterator to the first element that was moved.
971 auto *to_remove_start = llvm::remove_if(vec, [](const ModuleSP &module) {
972 return module.use_count() == kUseCountSharedModuleListOrphaned;
973 });
974
975 ModuleList to_remove;
976 for (ModuleSP *it = to_remove_start; it != vec.end(); ++it)
977 to_remove.Append(*it);
978
979 vec.erase(to_remove_start, vec.end());
980 return to_remove;
981 }
982
983 /// Remove orphans that exist in both the map and list. This does not remove
984 /// any orphans that exist exclusively on the list.
985 ///
986 /// The mutex must be locked by the caller.
987 int RemoveOrphansFromMapAndList() {
988 // Modules might hold shared pointers to other modules, so removing one
989 // module might orphan other modules. Keep removing modules until
990 // there are no further modules that can be removed.
991 int remove_count = 0;
992 int previous_remove_count;
993 do {
994 previous_remove_count = remove_count;
995 for (auto &[name, vec] : m_name_to_modules) {
996 if (vec.empty())
997 continue;
998 ModuleList to_remove = RemoveOrphansFromVector(vec);
999 remove_count += to_remove.GetSize();
1000 m_list.Remove(to_remove);
1001 }
1002 // Break when fixed-point is reached.
1003 } while (previous_remove_count != remove_count);
1004
1005 return remove_count;
1006 }
1007
1008 ModuleList m_list;
1009
1010 /// A hash map from a module's filename to all the modules that share that
1011 /// filename, for fast module lookups by name.
1012 llvm::StringMap<llvm::SmallVector<ModuleSP, 1>> m_name_to_modules;
1013
1014 /// The use count of a module held only by m_list and m_name_to_modules.
1015 static constexpr long kUseCountSharedModuleListOrphaned = 2;
1016};
1017
1018struct SharedModuleListInfo {
1019 SharedModuleList module_list;
1020 ModuleListProperties module_list_properties;
1021};
1022} // namespace
1023static SharedModuleListInfo &GetSharedModuleListInfo() {
1024 static SharedModuleListInfo *g_shared_module_list_info = nullptr;
1025 static llvm::once_flag g_once_flag;
1026 llvm::call_once(g_once_flag, []() {
1027 // NOTE: Intentionally leak the module list so a program doesn't have to
1028 // cleanup all modules and object files as it exits. This just wastes time
1029 // doing a bunch of cleanup that isn't required.
1030 if (g_shared_module_list_info == nullptr)
1031 g_shared_module_list_info = new SharedModuleListInfo();
1032 });
1033 return *g_shared_module_list_info;
1034}
1035
1036static SharedModuleList &GetSharedModuleList() {
1037 return GetSharedModuleListInfo().module_list;
1038}
1039
1043
1044bool ModuleList::ModuleIsInCache(const Module *module_ptr) {
1045 if (module_ptr) {
1046 SharedModuleList &shared_module_list = GetSharedModuleList();
1047 return shared_module_list.FindModule(*module_ptr).get() != nullptr;
1048 }
1049 return false;
1050}
1051
1053 ModuleList &matching_module_list) {
1054 GetSharedModuleList().FindModules(module_spec, matching_module_list);
1055}
1056
1058 return GetSharedModuleList().FindModule(uuid);
1059}
1060
1062 return GetSharedModuleList().RemoveOrphans(mandatory);
1063}
1064
1065Status
1066ModuleList::GetSharedModule(const ModuleSpec &module_spec, ModuleSP &module_sp,
1068 bool *did_create_ptr, bool invoke_locate_callback,
1069 bool invoke_symbol_locators) {
1070 SharedModuleList &shared_module_list = GetSharedModuleList();
1071 std::lock_guard<std::recursive_mutex> guard(shared_module_list.GetMutex());
1072 char path[PATH_MAX];
1073
1074 Status error;
1075
1076 module_sp.reset();
1077
1078 if (did_create_ptr)
1079 *did_create_ptr = false;
1080
1081 const UUID *uuid_ptr = module_spec.GetUUIDPtr();
1082 const FileSpec &module_file_spec = module_spec.GetFileSpec();
1083 const ArchSpec &arch = module_spec.GetArchitecture();
1084
1085 // Make sure no one else can try and get or create a module while this
1086 // function is actively working on it by doing an extra lock on the global
1087 // mutex list.
1088 {
1089 ModuleList matching_module_list;
1090 shared_module_list.FindModules(module_spec, matching_module_list);
1091 const size_t num_matching_modules = matching_module_list.GetSize();
1092
1093 if (num_matching_modules > 0) {
1094 for (size_t module_idx = 0; module_idx < num_matching_modules;
1095 ++module_idx) {
1096 module_sp = matching_module_list.GetModuleAtIndex(module_idx);
1097
1098 // Make sure the file for the module hasn't been modified
1099 if (module_sp->FileHasChanged()) {
1100 if (old_modules)
1101 old_modules->push_back(module_sp);
1102
1103 Log *log = GetLog(LLDBLog::Modules);
1104 LLDB_LOG(
1105 log,
1106 "{0:x} '{1}' module changed: removing from global module list",
1107 static_cast<void *>(module_sp.get()),
1108 module_sp->GetFileSpec().GetFilename());
1109
1110 shared_module_list.Remove(module_sp);
1111 module_sp.reset();
1112 } else {
1113 // The module matches and the module was not modified from when it
1114 // was last loaded.
1115 return error;
1116 }
1117 }
1118 }
1119 }
1120
1121 if (module_sp)
1122 return error;
1123
1124 // Try platform's locate module callback before second attempt.
1125 // The platform can come from either the Target (if available) or directly
1126 // from the ModuleSpec (useful when Target is not yet created, e.g., during
1127 // target creation for launch mode).
1128 if (invoke_locate_callback) {
1129 PlatformSP platform_sp;
1130 if (TargetSP target_sp = module_spec.GetTargetSP()) {
1131 if (target_sp->IsValid())
1132 platform_sp = target_sp->GetPlatform();
1133 }
1134 if (!platform_sp)
1135 platform_sp = module_spec.GetPlatformSP();
1136
1137 if (platform_sp) {
1138 FileSpec symbol_file_spec;
1139 platform_sp->CallLocateModuleCallbackIfSet(
1140 module_spec, module_sp, symbol_file_spec, did_create_ptr);
1141 if (module_sp) {
1142 // The callback found a module.
1143 return error;
1144 }
1145 }
1146 }
1147
1148 module_sp = std::make_shared<Module>(module_spec);
1149 // Make sure there are a module and an object file since we can specify a
1150 // valid file path with an architecture that might not be in that file. By
1151 // getting the object file we can guarantee that the architecture matches
1152 if (module_sp->GetObjectFile()) {
1153 // If we get in here we got the correct arch, now we just need to verify
1154 // the UUID if one was given
1155 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
1156 module_sp.reset();
1157 } else {
1158 if (module_sp->GetObjectFile() && module_sp->GetObjectFile()->GetType() ==
1160 module_sp.reset();
1161 } else {
1162 if (did_create_ptr) {
1163 *did_create_ptr = true;
1164 }
1165
1166 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1167 return error;
1168 }
1169 }
1170 } else {
1171 module_sp.reset();
1172 }
1173
1174 // Get module search paths from the target if available.
1175 lldb::TargetSP target_sp = module_spec.GetTargetSP();
1176 FileSpecList module_search_paths;
1177 if (target_sp)
1178 module_search_paths = target_sp->GetExecutableSearchPaths();
1179
1180 if (!module_search_paths.IsEmpty()) {
1181 const auto num_directories = module_search_paths.GetSize();
1182 for (size_t idx = 0; idx < num_directories; ++idx) {
1183 auto search_path_spec = module_search_paths.GetFileSpecAtIndex(idx);
1184 FileSystem::Instance().Resolve(search_path_spec);
1185 namespace fs = llvm::sys::fs;
1186 if (!FileSystem::Instance().IsDirectory(search_path_spec))
1187 continue;
1188 search_path_spec.AppendPathComponent(
1189 module_spec.GetFileSpec().GetFilename());
1190 if (!FileSystem::Instance().Exists(search_path_spec))
1191 continue;
1192
1193 auto resolved_module_spec(module_spec);
1194 resolved_module_spec.GetFileSpec() = search_path_spec;
1195 module_sp = std::make_shared<Module>(resolved_module_spec);
1196 if (module_sp->GetObjectFile()) {
1197 // If we get in here we got the correct arch, now we just need to
1198 // verify the UUID if one was given
1199 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
1200 module_sp.reset();
1201 } else {
1202 if (module_sp->GetObjectFile()->GetType() ==
1204 module_sp.reset();
1205 } else {
1206 if (did_create_ptr)
1207 *did_create_ptr = true;
1208
1209 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1210 return Status();
1211 }
1212 }
1213 } else {
1214 module_sp.reset();
1215 }
1216 }
1217 }
1218
1219 // Either the file didn't exist where at the path, or no path was given, so we
1220 // now either have to use more extreme measures to try and find the
1221 // appropriate module or end our search here.
1222 if (!invoke_symbol_locators) {
1223 std::string uuid_str;
1224 if (uuid_ptr && uuid_ptr->IsValid())
1225 uuid_str = uuid_ptr->GetAsString();
1226 if (!uuid_str.empty())
1228 "cannot locate module for UUID '{}'", uuid_str);
1229 return Status::FromErrorString("cannot locate module");
1230 }
1231
1232 // Fixup the incoming path in case the path points to a valid file, yet the
1233 // arch or UUID (if one was passed in) don't match.
1234 ModuleSpec located_binary_modulespec;
1235 StatisticsMap symbol_locator_map;
1236 located_binary_modulespec = PluginManager::LocateExecutableObjectFile(
1237 module_spec, symbol_locator_map);
1238 // Don't look for the file if it appears to be the same one we already
1239 // checked for above...
1240 if (located_binary_modulespec.GetFileSpec() != module_file_spec) {
1241 if (!FileSystem::Instance().Exists(
1242 located_binary_modulespec.GetFileSpec())) {
1243 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1244 if (path[0] == '\0')
1245 module_file_spec.GetPath(path, sizeof(path));
1246 // How can this check ever be true? This branch it is false, and we
1247 // haven't modified file_spec.
1248 if (FileSystem::Instance().Exists(
1249 located_binary_modulespec.GetFileSpec())) {
1250 std::string uuid_str;
1251 if (uuid_ptr && uuid_ptr->IsValid())
1252 uuid_str = uuid_ptr->GetAsString();
1253
1254 if (arch.IsValid()) {
1255 if (!uuid_str.empty())
1257 "'%s' does not contain the %s architecture and UUID %s", path,
1258 arch.GetArchitectureName(), uuid_str.c_str());
1259 else
1261 "'%s' does not contain the %s architecture.", path,
1262 arch.GetArchitectureName());
1263 }
1264 } else {
1265 error = Status::FromErrorStringWithFormat("'%s' does not exist", path);
1266 }
1267 if (error.Fail())
1268 module_sp.reset();
1269 return error;
1270 }
1271
1272 // Make sure no one else can try and get or create a module while this
1273 // function is actively working on it by doing an extra lock on the global
1274 // mutex list.
1275 ModuleSpec platform_module_spec(module_spec);
1276 platform_module_spec.GetFileSpec() =
1277 located_binary_modulespec.GetFileSpec();
1278 platform_module_spec.GetPlatformFileSpec() =
1279 located_binary_modulespec.GetFileSpec();
1280 platform_module_spec.GetSymbolFileSpec() =
1281 located_binary_modulespec.GetSymbolFileSpec();
1282 ModuleList matching_module_list;
1283 shared_module_list.FindModules(platform_module_spec, matching_module_list);
1284 if (!matching_module_list.IsEmpty()) {
1285 module_sp = matching_module_list.GetModuleAtIndex(0);
1286
1287 // If we didn't have a UUID in mind when looking for the object file,
1288 // then we should make sure the modification time hasn't changed!
1289 if (platform_module_spec.GetUUIDPtr() == nullptr) {
1290 auto file_spec_mod_time = FileSystem::Instance().GetModificationTime(
1291 located_binary_modulespec.GetFileSpec());
1292 if (file_spec_mod_time != llvm::sys::TimePoint<>()) {
1293 if (file_spec_mod_time != module_sp->GetModificationTime()) {
1294 if (old_modules)
1295 old_modules->push_back(module_sp);
1296 shared_module_list.Remove(module_sp);
1297 module_sp.reset();
1298 }
1299 }
1300 }
1301 }
1302
1303 if (!module_sp) {
1304 module_sp = std::make_shared<Module>(platform_module_spec);
1305 // Make sure there are a module and an object file since we can specify a
1306 // valid file path with an architecture that might not be in that file.
1307 // By getting the object file we can guarantee that the architecture
1308 // matches
1309 if (module_sp && module_sp->GetObjectFile()) {
1310 module_sp->GetSymbolLocatorStatistics().merge(symbol_locator_map);
1311 if (module_sp->GetObjectFile()->GetType() ==
1313 module_sp.reset();
1314 } else {
1315 if (did_create_ptr)
1316 *did_create_ptr = true;
1317
1318 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1319 }
1320 } else {
1321 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1322
1323 if (located_binary_modulespec.GetFileSpec()) {
1324 if (arch.IsValid())
1326 "unable to open %s architecture in '%s'",
1327 arch.GetArchitectureName(), path);
1328 else
1329 error =
1330 Status::FromErrorStringWithFormat("unable to open '%s'", path);
1331 } else {
1332 std::string uuid_str;
1333 if (uuid_ptr && uuid_ptr->IsValid())
1334 uuid_str = uuid_ptr->GetAsString();
1335
1336 if (!uuid_str.empty())
1338 "cannot locate a module for UUID '%s'", uuid_str.c_str());
1339 else
1340 error = Status::FromErrorString("cannot locate a module");
1341 }
1342 }
1343 }
1344 }
1345
1346 return error;
1347}
1348
1350 return GetSharedModuleList().Remove(module_sp);
1351}
1352
1354 return GetSharedModuleList().RemoveIfOrphaned(module_wp);
1355}
1356
1357static bool LoadScriptingModule(const FileSpec &scripting_fspec,
1358 ScriptInterpreter &script_interpreter,
1359 Target &target, Status &error) {
1360 assert(scripting_fspec);
1361
1362 StreamString scripting_stream;
1363 scripting_fspec.Dump(scripting_stream.AsRawOstream());
1364 LoadScriptOptions options;
1365 return script_interpreter.LoadScriptingModule(
1366 scripting_stream.GetData(), options, error,
1367 /*module_sp*/ nullptr, /*extra_path*/ {}, target.shared_from_this());
1368}
1369
1371 Target &target,
1372 Status &error) {
1373 Log *log = GetLog(LLDBLog::Modules);
1374
1375 Debugger &debugger = target.GetDebugger();
1376 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1377 if (script_language == eScriptLanguageNone)
1378 return true;
1379
1380 ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1381 if (!script_interpreter) {
1382 error = Status::FromErrorString("invalid ScriptInterpreter");
1383 return false;
1384 }
1385
1386 PlatformSP platform_sp = target.GetPlatform();
1387 if (!platform_sp) {
1388 error = Status::FromErrorString("invalid Platform");
1389 return false;
1390 }
1391
1392 StreamString feedback_stream;
1393 llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile> file_specs =
1394 platform_sp->LocateExecutableScriptingResources(&target, module,
1395 feedback_stream);
1396
1397 if (!feedback_stream.Empty())
1398 debugger.ReportWarning(feedback_stream.GetString().str(), debugger.GetID());
1399
1400 const bool trusted = platform_sp->IsSymbolFileTrusted(module);
1401
1402 for (const auto &[scripting_fspec, load_style] : file_specs) {
1403 if (load_style == eLoadScriptFromSymFileFalse)
1404 continue;
1405
1406 if (!FileSystem::Instance().Exists(scripting_fspec))
1407 continue;
1408
1409 switch (load_style) {
1411 llvm_unreachable("case already handled");
1413 break;
1415 if (trusted)
1416 break;
1417 LLVM_FALLTHROUGH;
1419 debugger.ReportWarning(
1420 llvm::formatv(
1421 // clang-format off
1422R"('{0}' contains {1} debug script. To run this script in this debug session:
1423
1424 command script import "{2}"
1425
1426To run all discovered debug scripts in this session:
1427
1428 settings set target.load-script-from-symbol-file true
1429)",
1430 // clang-format on
1432 trusted ? "a trusted" : "an untrusted",
1433 scripting_fspec.GetPath()),
1434 debugger.GetID());
1435
1436 continue;
1437 }
1438
1439 LLDB_LOG(log, "Auto-loading {0}", scripting_fspec.GetPath());
1440
1441 if (!LoadScriptingModule(scripting_fspec, *script_interpreter, target,
1442 error)) {
1443 LLDB_LOG(log, "Failed to load '{0}'. Remaining scripts won't be loaded.",
1444 scripting_fspec.GetPath());
1445 return false;
1446 }
1447 }
1448
1449 return true;
1450}
1451
1453 std::list<Status> &errors,
1454 bool continue_on_error) {
1455 if (!target)
1456 return false;
1457 m_modules_mutex.lock();
1458 // Don't hold the module list mutex while loading the scripting resources,
1459 // The initializer might do any amount of work, and having that happen while
1460 // the module list is held is asking for A/B locking problems.
1461 const ModuleList tmp_module_list(*this);
1462 m_modules_mutex.unlock();
1463
1464 for (auto module : tmp_module_list.ModulesNoLocking()) {
1465 if (module) {
1466 Status error;
1467 if (!LoadScriptingResourceInTargetForModule(*module, *target, error)) {
1468 if (error.Fail() && error.AsCString()) {
1470 "unable to load scripting data for "
1471 "module {0} - error reported was {1}",
1472 module->GetFileSpec().GetFileNameStrippingExtension(),
1473 error.AsCString());
1474 errors.push_back(std::move(error));
1475 if (!continue_on_error)
1476 return false;
1478 }
1479 }
1480 }
1481 return errors.empty();
1482}
1483
1485 std::function<IterationAction(const ModuleSP &module_sp)> const &callback)
1486 const {
1487 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1488 for (const auto &module_sp : m_modules) {
1489 assert(module_sp != nullptr);
1490 if (callback(module_sp) == IterationAction::Stop)
1491 break;
1492 }
1493}
1494
1496 std::function<bool(lldb_private::Module &module_sp)> const &callback)
1497 const {
1498 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1499 for (const auto &module_sp : m_modules) {
1500 assert(module_sp != nullptr);
1501 if (callback(*module_sp))
1502 return true;
1503 }
1504
1505 return false;
1506}
1507
1509 // scoped_lock locks both mutexes at once.
1510 std::scoped_lock<std::recursive_mutex, std::recursive_mutex> lock(
1512 m_modules.swap(other.m_modules);
1513}
1514
1515void ModuleList::PreloadSymbols(bool parallelize) const {
1516 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1517
1518 if (!parallelize) {
1519 for (const ModuleSP &module_sp : m_modules)
1520 module_sp->PreloadSymbols();
1521 return;
1522 }
1523
1524 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1525 for (const ModuleSP &module_sp : m_modules)
1526 task_group.async([module_sp] {
1527 if (module_sp)
1528 module_sp->PreloadSymbols();
1529 });
1530 task_group.wait();
1531}
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
static SharedModuleListInfo & GetSharedModuleListInfo()
static bool LoadScriptingModule(const FileSpec &scripting_fspec, ScriptInterpreter &script_interpreter, Target &target, Status &error)
static SharedModuleList & GetSharedModuleList()
A section + offset based address class.
Definition Address.h:62
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:275
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:455
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:745
Represents a generic declaration context in a program.
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:103
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:458
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:341
llvm::sys::TimePoint GetModificationTime(const FileSpec &file_spec) const
Returns the modification time of the given file.
Status Readlink(const FileSpec &src, FileSpec &dst)
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
A class that describes a function.
Definition Function.h:386
bool SetClangModulesCachePath(const FileSpec &path)
lldb::SymbolDownload GetSymbolAutoDownload() const
bool SetLLDBIndexCachePath(const FileSpec &path)
bool SetEnableExternalLookup(bool new_value)
PathMappingList GetSymlinkMappings() const
uint64_t GetDemangledNameInfoCacheSize() const
lldb::SymbolSharedCacheUse GetSharedCacheBinaryLoading() const
FileSpec GetClangModulesCachePath() const
llvm::sys::RWMutex m_symlink_paths_mutex
Definition ModuleList.h:95
bool GetEnableLLDBIndexCacheMemoryModules() const
bool SetEnableLLDBIndexCache(bool new_value)
bool SetEnableLLDBIndexCacheMemoryModules(bool new_value)
virtual void NotifyModuleRemoved(const ModuleList &module_list, const lldb::ModuleSP &module_sp)=0
A collection class for Module objects.
Definition ModuleList.h:128
bool ReplaceModule(const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp)
collection m_modules
The collection of modules.
Definition ModuleList.h:558
void ClearImpl(bool use_notifier=true)
uint32_t ResolveSymbolContextsForFileSpec(const FileSpec &file_spec, uint32_t line, bool check_inlines, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) const
Resolve items in the symbol context for a given file and line. (const FileSpec&,...
static bool RemoveSharedModule(lldb::ModuleSP &module_sp)
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool invoke_locate_callback=true, bool invoke_symbol_locators=true)
void FindFunctions(ConstString name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
bool FindSourceFile(const FileSpec &orig_spec, FileSpec &new_spec) const
bool AnyOf(std::function< bool(lldb_private::Module &module)> const &callback) const
Returns true if 'callback' returns true for one of the modules in this ModuleList.
ModuleIterableNoLocking ModulesNoLocking() const
Definition ModuleList.h:580
static constexpr long kUseCountModuleListOrphaned
An orphaned module that lives only in the ModuleList has a count of 1.
Definition ModuleList.h:564
static bool ModuleIsInCache(const Module *module_ptr)
void FindGlobalVariables(ConstString name, size_t max_matches, VariableList &variable_list) const
Find global and static variables by name.
void Swap(ModuleList &other)
Atomically swaps the contents of this module list with other.
size_t GetIndexForModule(const Module *module) const
bool RemoveImpl(const lldb::ModuleSP &module_sp, bool use_notifier=true)
lldb::ModuleSP FindFirstModule(const ModuleSpec &module_spec) const
Finds the first module whose file specification matches module_spec.
void Clear()
Clear the object's state.
ModuleList()
Default constructor.
void Dump(Stream *s) const
Dump the description of each module contained in this list.
void FindTypes(Module *search_first, const TypeQuery &query, lldb_private::TypeResults &results) const
Find types using a type-matching object that contains all search parameters.
uint32_t ResolveSymbolContextForFilePath(const char *file_path, uint32_t line, bool check_inlines, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) const
Resolve items in the symbol context for a given file and line. (const char*,uint32_t,...
static bool LoadScriptingResourceInTargetForModule(Module &module, Target &target, Status &error)
lldb::ModuleSP GetModuleAtIndexUnlocked(size_t idx) const
Get the module shared pointer for the module at index idx without acquiring the ModuleList mutex.
static bool RemoveSharedModuleIfOrphaned(const lldb::ModuleWP module_ptr)
void FindCompileUnits(const FileSpec &path, SymbolContextList &sc_list) const
Find compile units by partial or full path.
void PreloadSymbols(bool parallelize) const
For each module in this ModuleList, preload its symbols.
const ModuleList & operator=(const ModuleList &rhs)
Assignment operator.
std::recursive_mutex m_modules_mutex
Definition ModuleList.h:559
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
Module * GetModulePointerAtIndex(size_t idx) const
Get the module pointer for the module at index idx.
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
static lldb::ModuleSP FindSharedModule(const UUID &uuid)
lldb::ModuleSP FindModule(const Module *module_ptr) const
static ModuleListProperties & GetGlobalModuleListProperties()
void FindModules(const ModuleSpec &module_spec, ModuleList &matching_module_list) const
Finds modules whose file specification matches module_spec.
void FindAddressesForLine(const lldb::TargetSP target_sp, const FileSpec &file, uint32_t line, Function *function, std::vector< Address > &output_local, std::vector< Address > &output_extern)
Find addresses by file/line.
uint32_t ResolveSymbolContextForAddress(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc) const
Resolve the symbol context for the given address. (const Address&,uint32_t,SymbolContext&)
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
size_t RemoveOrphans(bool mandatory)
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
static size_t RemoveOrphanSharedModules(bool mandatory)
void Destroy()
Clear the object's state.
void AppendImpl(const lldb::ModuleSP &module_sp, bool use_notifier=true)
void ReplaceEquivalent(const lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules=nullptr)
Append a module to the module list and remove any equivalent modules.
void FindFunctionSymbols(ConstString name, lldb::FunctionNameType name_type_mask, SymbolContextList &sc_list)
static void FindSharedModules(const ModuleSpec &module_spec, ModuleList &matching_module_list)
bool LoadScriptingResourcesInTarget(Target *target, std::list< Status > &errors, bool continue_on_error=true)
void FindSymbolsMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) const
size_t GetSize() const
Gets the size of the module list.
bool RemoveIfOrphaned(const lldb::ModuleWP module_ptr)
void LogUUIDAndPaths(Log *log, const char *prefix_cstr)
void ForEach(std::function< IterationAction(const lldb::ModuleSP &module_sp)> const &callback) const
Applies 'callback' to each module in this ModuleList.
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:69
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
lldb::PlatformSP GetPlatformSP() const
Definition ModuleSpec.h:152
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:81
lldb::TargetSP GetTargetSP() const
Definition ModuleSpec.h:142
static std::vector< LookupInfo > MakeLookupInfos(ConstString name, lldb::FunctionNameType name_type_mask, lldb::LanguageType lang_type, ConstString lookup_name_override={})
Creates a vector of lookup infos for function name resolution.
Definition Module.cpp:683
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
const lldb_private::UUID & GetUUID()
Get a reference to the UUID value contained in this object.
Definition Module.cpp:337
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition Module.cpp:1017
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:447
void FindTypes(const TypeQuery &query, TypeResults &results)
Find types using a type-matching object that contains all search parameters.
Definition Module.cpp:953
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:55
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition ObjectFile.h:65
static ModuleSpec LocateExecutableObjectFile(const ModuleSpec &module_spec, StatisticsMap &map)
lldb::OptionValuePropertiesSP m_collection_sp
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
virtual bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={})
A class to count time for plugins.
Definition Statistics.h:94
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
Provides public interface for all SymbolFiles.
Definition SymbolFile.h:51
Debugger & GetDebugger() const
Definition Target.h:1365
lldb::PlatformSP GetPlatform()
Definition Target.h:2007
A class that contains all state required for type lookups.
This class tracks the state and results of a TypeQuery.
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
Represents UUID's of various sizes.
Definition UUID.h:27
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
#define LLDB_INVALID_INDEX32
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
@ eLoadScriptFromSymFileTrue
Definition Target.h:65
@ eLoadScriptFromSymFileTrusted
Definition Target.h:68
@ eLoadScriptFromSymFileFalse
Definition Target.h:66
@ eLoadScriptFromSymFileWarn
Definition Target.h:67
IterationAction
Useful for callbacks whose return type indicates whether to continue iteration or short-circuit.
ScriptLanguage
Script interpreter types.
@ eScriptLanguageNone
std::weak_ptr< lldb_private::Module > ModuleWP
std::shared_ptr< lldb_private::Platform > PlatformSP
@ eLanguageTypeUnknown
Unknown or invalid language value.
SymbolType
Symbol types.
uint64_t user_id_t
Definition lldb-types.h:83
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
@ eSymbolDownloadBackground
std::shared_ptr< lldb_private::Module > ModuleSP
Options used by Module::FindFunctions.
Definition Module.h:67
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47
#define PATH_MAX