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(ConstString(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(
903 ConstString(module_spec.GetFileSpec().GetFilename()));
904 if (it == m_name_to_modules.end())
905 return;
906 const llvm::SmallVectorImpl<ModuleSP> &vector = it->second;
907 for (const ModuleSP &module_sp : vector) {
908 if (module_sp->MatchesModuleSpec(module_spec))
909 matching_module_list.Append(module_sp);
910 }
911 }
912
913 void AddToMap(const ModuleSP &module_sp) {
914 llvm::StringRef name = module_sp->GetFileSpec().GetFilename();
915 if (name.empty())
916 return;
917 m_name_to_modules[ConstString(name)].push_back(module_sp);
918 }
919
920 void RemoveFromMap(const ModuleWP module_wp, bool if_orphaned = false) {
921 if (auto module_sp = module_wp.lock()) {
922 ConstString name = ConstString(module_sp->GetFileSpec().GetFilename());
923 if (!m_name_to_modules.contains(name))
924 return;
925 llvm::SmallVectorImpl<ModuleSP> &vec = m_name_to_modules[name];
926 for (auto *it = vec.begin(); it != vec.end(); ++it) {
927 if (it->get() == module_sp.get()) {
928 // Since module_sp increases the refcount by 1, the use count should
929 // be the regular use count + 1.
930 constexpr long kUseCountOrphaned =
931 kUseCountSharedModuleListOrphaned + 1;
932 if (!if_orphaned || it->use_count() == kUseCountOrphaned) {
933 vec.erase(it);
934 break;
935 }
936 }
937 }
938 }
939 }
940
941 void ReplaceEquivalentInMap(const ModuleSP &module_sp) {
942 RemoveEquivalentModulesFromMap(module_sp);
943 AddToMap(module_sp);
944 }
945
946 void RemoveEquivalentModulesFromMap(const ModuleSP &module_sp) {
947 llvm::StringRef name = module_sp->GetFileSpec().GetFilename();
948 if (name.empty())
949 return;
950
951 auto it = m_name_to_modules.find(ConstString(name));
952 if (it == m_name_to_modules.end())
953 return;
954
955 // First remove any equivalent modules. Equivalent modules are modules
956 // whose path, platform path and architecture match.
957 ModuleSpec equivalent_module_spec(module_sp->GetFileSpec(),
958 module_sp->GetArchitecture());
959 equivalent_module_spec.GetPlatformFileSpec() =
960 module_sp->GetPlatformFileSpec();
961
962 llvm::SmallVectorImpl<ModuleSP> &vec = it->second;
963 llvm::erase_if(vec, [&equivalent_module_spec](ModuleSP &element) {
964 return element->MatchesModuleSpec(equivalent_module_spec);
965 });
966 }
967
968 /// Remove orphans from the vector and return the removed modules.
969 ModuleList RemoveOrphansFromVector(llvm::SmallVectorImpl<ModuleSP> &vec) {
970 // remove_if moves the elements that match the condition to the end of the
971 // container, and returns an iterator to the first element that was moved.
972 auto *to_remove_start = llvm::remove_if(vec, [](const ModuleSP &module) {
973 return module.use_count() == kUseCountSharedModuleListOrphaned;
974 });
975
976 ModuleList to_remove;
977 for (ModuleSP *it = to_remove_start; it != vec.end(); ++it)
978 to_remove.Append(*it);
979
980 vec.erase(to_remove_start, vec.end());
981 return to_remove;
982 }
983
984 /// Remove orphans that exist in both the map and list. This does not remove
985 /// any orphans that exist exclusively on the list.
986 ///
987 /// The mutex must be locked by the caller.
988 int RemoveOrphansFromMapAndList() {
989 // Modules might hold shared pointers to other modules, so removing one
990 // module might orphan other modules. Keep removing modules until
991 // there are no further modules that can be removed.
992 int remove_count = 0;
993 int previous_remove_count;
994 do {
995 previous_remove_count = remove_count;
996 for (auto &[name, vec] : m_name_to_modules) {
997 if (vec.empty())
998 continue;
999 ModuleList to_remove = RemoveOrphansFromVector(vec);
1000 remove_count += to_remove.GetSize();
1001 m_list.Remove(to_remove);
1002 }
1003 // Break when fixed-point is reached.
1004 } while (previous_remove_count != remove_count);
1005
1006 return remove_count;
1007 }
1008
1009 ModuleList m_list;
1010
1011 /// A hash map from a module's filename to all the modules that share that
1012 /// filename, for fast module lookups by name.
1013 llvm::DenseMap<ConstString, llvm::SmallVector<ModuleSP, 1>> m_name_to_modules;
1014
1015 /// The use count of a module held only by m_list and m_name_to_modules.
1016 static constexpr long kUseCountSharedModuleListOrphaned = 2;
1017};
1018
1019struct SharedModuleListInfo {
1020 SharedModuleList module_list;
1021 ModuleListProperties module_list_properties;
1022};
1023} // namespace
1024static SharedModuleListInfo &GetSharedModuleListInfo() {
1025 static SharedModuleListInfo *g_shared_module_list_info = nullptr;
1026 static llvm::once_flag g_once_flag;
1027 llvm::call_once(g_once_flag, []() {
1028 // NOTE: Intentionally leak the module list so a program doesn't have to
1029 // cleanup all modules and object files as it exits. This just wastes time
1030 // doing a bunch of cleanup that isn't required.
1031 if (g_shared_module_list_info == nullptr)
1032 g_shared_module_list_info = new SharedModuleListInfo();
1033 });
1034 return *g_shared_module_list_info;
1035}
1036
1037static SharedModuleList &GetSharedModuleList() {
1038 return GetSharedModuleListInfo().module_list;
1039}
1040
1044
1045bool ModuleList::ModuleIsInCache(const Module *module_ptr) {
1046 if (module_ptr) {
1047 SharedModuleList &shared_module_list = GetSharedModuleList();
1048 return shared_module_list.FindModule(*module_ptr).get() != nullptr;
1049 }
1050 return false;
1051}
1052
1054 ModuleList &matching_module_list) {
1055 GetSharedModuleList().FindModules(module_spec, matching_module_list);
1056}
1057
1059 return GetSharedModuleList().FindModule(uuid);
1060}
1061
1063 return GetSharedModuleList().RemoveOrphans(mandatory);
1064}
1065
1066Status
1067ModuleList::GetSharedModule(const ModuleSpec &module_spec, ModuleSP &module_sp,
1069 bool *did_create_ptr, bool invoke_locate_callback,
1070 bool invoke_symbol_locators) {
1071 SharedModuleList &shared_module_list = GetSharedModuleList();
1072 std::lock_guard<std::recursive_mutex> guard(shared_module_list.GetMutex());
1073 char path[PATH_MAX];
1074
1075 Status error;
1076
1077 module_sp.reset();
1078
1079 if (did_create_ptr)
1080 *did_create_ptr = false;
1081
1082 const UUID *uuid_ptr = module_spec.GetUUIDPtr();
1083 const FileSpec &module_file_spec = module_spec.GetFileSpec();
1084 const ArchSpec &arch = module_spec.GetArchitecture();
1085
1086 // Make sure no one else can try and get or create a module while this
1087 // function is actively working on it by doing an extra lock on the global
1088 // mutex list.
1089 {
1090 ModuleList matching_module_list;
1091 shared_module_list.FindModules(module_spec, matching_module_list);
1092 const size_t num_matching_modules = matching_module_list.GetSize();
1093
1094 if (num_matching_modules > 0) {
1095 for (size_t module_idx = 0; module_idx < num_matching_modules;
1096 ++module_idx) {
1097 module_sp = matching_module_list.GetModuleAtIndex(module_idx);
1098
1099 // Make sure the file for the module hasn't been modified
1100 if (module_sp->FileHasChanged()) {
1101 if (old_modules)
1102 old_modules->push_back(module_sp);
1103
1104 Log *log = GetLog(LLDBLog::Modules);
1105 LLDB_LOG(
1106 log,
1107 "{0:x} '{1}' module changed: removing from global module list",
1108 static_cast<void *>(module_sp.get()),
1109 module_sp->GetFileSpec().GetFilename());
1110
1111 shared_module_list.Remove(module_sp);
1112 module_sp.reset();
1113 } else {
1114 // The module matches and the module was not modified from when it
1115 // was last loaded.
1116 return error;
1117 }
1118 }
1119 }
1120 }
1121
1122 if (module_sp)
1123 return error;
1124
1125 // Try platform's locate module callback before second attempt.
1126 // The platform can come from either the Target (if available) or directly
1127 // from the ModuleSpec (useful when Target is not yet created, e.g., during
1128 // target creation for launch mode).
1129 if (invoke_locate_callback) {
1130 PlatformSP platform_sp;
1131 if (TargetSP target_sp = module_spec.GetTargetSP()) {
1132 if (target_sp->IsValid())
1133 platform_sp = target_sp->GetPlatform();
1134 }
1135 if (!platform_sp)
1136 platform_sp = module_spec.GetPlatformSP();
1137
1138 if (platform_sp) {
1139 FileSpec symbol_file_spec;
1140 platform_sp->CallLocateModuleCallbackIfSet(
1141 module_spec, module_sp, symbol_file_spec, did_create_ptr);
1142 if (module_sp) {
1143 // The callback found a module.
1144 return error;
1145 }
1146 }
1147 }
1148
1149 module_sp = std::make_shared<Module>(module_spec);
1150 // Make sure there are a module and an object file since we can specify a
1151 // valid file path with an architecture that might not be in that file. By
1152 // getting the object file we can guarantee that the architecture matches
1153 if (module_sp->GetObjectFile()) {
1154 // If we get in here we got the correct arch, now we just need to verify
1155 // the UUID if one was given
1156 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
1157 module_sp.reset();
1158 } else {
1159 if (module_sp->GetObjectFile() && module_sp->GetObjectFile()->GetType() ==
1161 module_sp.reset();
1162 } else {
1163 if (did_create_ptr) {
1164 *did_create_ptr = true;
1165 }
1166
1167 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1168 return error;
1169 }
1170 }
1171 } else {
1172 module_sp.reset();
1173 }
1174
1175 // Get module search paths from the target if available.
1176 lldb::TargetSP target_sp = module_spec.GetTargetSP();
1177 FileSpecList module_search_paths;
1178 if (target_sp)
1179 module_search_paths = target_sp->GetExecutableSearchPaths();
1180
1181 if (!module_search_paths.IsEmpty()) {
1182 const auto num_directories = module_search_paths.GetSize();
1183 for (size_t idx = 0; idx < num_directories; ++idx) {
1184 auto search_path_spec = module_search_paths.GetFileSpecAtIndex(idx);
1185 FileSystem::Instance().Resolve(search_path_spec);
1186 namespace fs = llvm::sys::fs;
1187 if (!FileSystem::Instance().IsDirectory(search_path_spec))
1188 continue;
1189 search_path_spec.AppendPathComponent(
1190 module_spec.GetFileSpec().GetFilename());
1191 if (!FileSystem::Instance().Exists(search_path_spec))
1192 continue;
1193
1194 auto resolved_module_spec(module_spec);
1195 resolved_module_spec.GetFileSpec() = search_path_spec;
1196 module_sp = std::make_shared<Module>(resolved_module_spec);
1197 if (module_sp->GetObjectFile()) {
1198 // If we get in here we got the correct arch, now we just need to
1199 // verify the UUID if one was given
1200 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID()) {
1201 module_sp.reset();
1202 } else {
1203 if (module_sp->GetObjectFile()->GetType() ==
1205 module_sp.reset();
1206 } else {
1207 if (did_create_ptr)
1208 *did_create_ptr = true;
1209
1210 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1211 return Status();
1212 }
1213 }
1214 } else {
1215 module_sp.reset();
1216 }
1217 }
1218 }
1219
1220 // Either the file didn't exist where at the path, or no path was given, so we
1221 // now either have to use more extreme measures to try and find the
1222 // appropriate module or end our search here.
1223 if (!invoke_symbol_locators) {
1224 std::string uuid_str;
1225 if (uuid_ptr && uuid_ptr->IsValid())
1226 uuid_str = uuid_ptr->GetAsString();
1227 if (!uuid_str.empty())
1229 "cannot locate module for UUID '{}'", uuid_str);
1230 return Status::FromErrorString("cannot locate module");
1231 }
1232
1233 // Fixup the incoming path in case the path points to a valid file, yet the
1234 // arch or UUID (if one was passed in) don't match.
1235 ModuleSpec located_binary_modulespec;
1236 StatisticsMap symbol_locator_map;
1237 located_binary_modulespec = PluginManager::LocateExecutableObjectFile(
1238 module_spec, symbol_locator_map);
1239 // Don't look for the file if it appears to be the same one we already
1240 // checked for above...
1241 if (located_binary_modulespec.GetFileSpec() != module_file_spec) {
1242 if (!FileSystem::Instance().Exists(
1243 located_binary_modulespec.GetFileSpec())) {
1244 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1245 if (path[0] == '\0')
1246 module_file_spec.GetPath(path, sizeof(path));
1247 // How can this check ever be true? This branch it is false, and we
1248 // haven't modified file_spec.
1249 if (FileSystem::Instance().Exists(
1250 located_binary_modulespec.GetFileSpec())) {
1251 std::string uuid_str;
1252 if (uuid_ptr && uuid_ptr->IsValid())
1253 uuid_str = uuid_ptr->GetAsString();
1254
1255 if (arch.IsValid()) {
1256 if (!uuid_str.empty())
1258 "'%s' does not contain the %s architecture and UUID %s", path,
1259 arch.GetArchitectureName(), uuid_str.c_str());
1260 else
1262 "'%s' does not contain the %s architecture.", path,
1263 arch.GetArchitectureName());
1264 }
1265 } else {
1266 error = Status::FromErrorStringWithFormat("'%s' does not exist", path);
1267 }
1268 if (error.Fail())
1269 module_sp.reset();
1270 return error;
1271 }
1272
1273 // Make sure no one else can try and get or create a module while this
1274 // function is actively working on it by doing an extra lock on the global
1275 // mutex list.
1276 ModuleSpec platform_module_spec(module_spec);
1277 platform_module_spec.GetFileSpec() =
1278 located_binary_modulespec.GetFileSpec();
1279 platform_module_spec.GetPlatformFileSpec() =
1280 located_binary_modulespec.GetFileSpec();
1281 platform_module_spec.GetSymbolFileSpec() =
1282 located_binary_modulespec.GetSymbolFileSpec();
1283 ModuleList matching_module_list;
1284 shared_module_list.FindModules(platform_module_spec, matching_module_list);
1285 if (!matching_module_list.IsEmpty()) {
1286 module_sp = matching_module_list.GetModuleAtIndex(0);
1287
1288 // If we didn't have a UUID in mind when looking for the object file,
1289 // then we should make sure the modification time hasn't changed!
1290 if (platform_module_spec.GetUUIDPtr() == nullptr) {
1291 auto file_spec_mod_time = FileSystem::Instance().GetModificationTime(
1292 located_binary_modulespec.GetFileSpec());
1293 if (file_spec_mod_time != llvm::sys::TimePoint<>()) {
1294 if (file_spec_mod_time != module_sp->GetModificationTime()) {
1295 if (old_modules)
1296 old_modules->push_back(module_sp);
1297 shared_module_list.Remove(module_sp);
1298 module_sp.reset();
1299 }
1300 }
1301 }
1302 }
1303
1304 if (!module_sp) {
1305 module_sp = std::make_shared<Module>(platform_module_spec);
1306 // Make sure there are a module and an object file since we can specify a
1307 // valid file path with an architecture that might not be in that file.
1308 // By getting the object file we can guarantee that the architecture
1309 // matches
1310 if (module_sp && module_sp->GetObjectFile()) {
1311 module_sp->GetSymbolLocatorStatistics().merge(symbol_locator_map);
1312 if (module_sp->GetObjectFile()->GetType() ==
1314 module_sp.reset();
1315 } else {
1316 if (did_create_ptr)
1317 *did_create_ptr = true;
1318
1319 shared_module_list.ReplaceEquivalent(module_sp, old_modules);
1320 }
1321 } else {
1322 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1323
1324 if (located_binary_modulespec.GetFileSpec()) {
1325 if (arch.IsValid())
1327 "unable to open %s architecture in '%s'",
1328 arch.GetArchitectureName(), path);
1329 else
1330 error =
1331 Status::FromErrorStringWithFormat("unable to open '%s'", path);
1332 } else {
1333 std::string uuid_str;
1334 if (uuid_ptr && uuid_ptr->IsValid())
1335 uuid_str = uuid_ptr->GetAsString();
1336
1337 if (!uuid_str.empty())
1339 "cannot locate a module for UUID '%s'", uuid_str.c_str());
1340 else
1341 error = Status::FromErrorString("cannot locate a module");
1342 }
1343 }
1344 }
1345 }
1346
1347 return error;
1348}
1349
1351 return GetSharedModuleList().Remove(module_sp);
1352}
1353
1355 return GetSharedModuleList().RemoveIfOrphaned(module_wp);
1356}
1357
1358static bool LoadScriptingModule(const FileSpec &scripting_fspec,
1359 ScriptInterpreter &script_interpreter,
1360 Target &target, Status &error) {
1361 assert(scripting_fspec);
1362
1363 StreamString scripting_stream;
1364 scripting_fspec.Dump(scripting_stream.AsRawOstream());
1365 LoadScriptOptions options;
1366 return script_interpreter.LoadScriptingModule(
1367 scripting_stream.GetData(), options, error,
1368 /*module_sp*/ nullptr, /*extra_path*/ {}, target.shared_from_this());
1369}
1370
1372 Target &target,
1373 Status &error) {
1374 Log *log = GetLog(LLDBLog::Modules);
1375
1376 Debugger &debugger = target.GetDebugger();
1377 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1378 if (script_language == eScriptLanguageNone)
1379 return true;
1380
1381 ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1382 if (!script_interpreter) {
1383 error = Status::FromErrorString("invalid ScriptInterpreter");
1384 return false;
1385 }
1386
1387 PlatformSP platform_sp = target.GetPlatform();
1388 if (!platform_sp) {
1389 error = Status::FromErrorString("invalid Platform");
1390 return false;
1391 }
1392
1393 StreamString feedback_stream;
1394 llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile> file_specs =
1395 platform_sp->LocateExecutableScriptingResources(&target, module,
1396 feedback_stream);
1397
1398 if (!feedback_stream.Empty())
1399 debugger.ReportWarning(feedback_stream.GetString().str(), debugger.GetID());
1400
1401 const bool trusted = platform_sp->IsSymbolFileTrusted(module);
1402
1403 for (const auto &[scripting_fspec, load_style] : file_specs) {
1404 if (load_style == eLoadScriptFromSymFileFalse)
1405 continue;
1406
1407 if (!FileSystem::Instance().Exists(scripting_fspec))
1408 continue;
1409
1410 switch (load_style) {
1412 llvm_unreachable("case already handled");
1414 break;
1416 if (trusted)
1417 break;
1418 LLVM_FALLTHROUGH;
1420 debugger.ReportWarning(
1421 llvm::formatv(
1422 // clang-format off
1423R"('{0}' contains {1} debug script. To run this script in this debug session:
1424
1425 command script import "{2}"
1426
1427To run all discovered debug scripts in this session:
1428
1429 settings set target.load-script-from-symbol-file true
1430)",
1431 // clang-format on
1433 trusted ? "a trusted" : "an untrusted",
1434 scripting_fspec.GetPath()),
1435 debugger.GetID());
1436
1437 continue;
1438 }
1439
1440 LLDB_LOG(log, "Auto-loading {0}", scripting_fspec.GetPath());
1441
1442 if (!LoadScriptingModule(scripting_fspec, *script_interpreter, target,
1443 error)) {
1444 LLDB_LOG(log, "Failed to load '{0}'. Remaining scripts won't be loaded.",
1445 scripting_fspec.GetPath());
1446 return false;
1447 }
1448 }
1449
1450 return true;
1451}
1452
1454 std::list<Status> &errors,
1455 bool continue_on_error) {
1456 if (!target)
1457 return false;
1458 m_modules_mutex.lock();
1459 // Don't hold the module list mutex while loading the scripting resources,
1460 // The initializer might do any amount of work, and having that happen while
1461 // the module list is held is asking for A/B locking problems.
1462 const ModuleList tmp_module_list(*this);
1463 m_modules_mutex.unlock();
1464
1465 for (auto module : tmp_module_list.ModulesNoLocking()) {
1466 if (module) {
1467 Status error;
1468 if (!LoadScriptingResourceInTargetForModule(*module, *target, error)) {
1469 if (error.Fail() && error.AsCString()) {
1471 "unable to load scripting data for "
1472 "module {0} - error reported was {1}",
1473 module->GetFileSpec().GetFileNameStrippingExtension(),
1474 error.AsCString());
1475 errors.push_back(std::move(error));
1476 if (!continue_on_error)
1477 return false;
1479 }
1480 }
1481 }
1482 return errors.empty();
1483}
1484
1486 std::function<IterationAction(const ModuleSP &module_sp)> const &callback)
1487 const {
1488 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1489 for (const auto &module_sp : m_modules) {
1490 assert(module_sp != nullptr);
1491 if (callback(module_sp) == IterationAction::Stop)
1492 break;
1493 }
1494}
1495
1497 std::function<bool(lldb_private::Module &module_sp)> const &callback)
1498 const {
1499 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1500 for (const auto &module_sp : m_modules) {
1501 assert(module_sp != nullptr);
1502 if (callback(*module_sp))
1503 return true;
1504 }
1505
1506 return false;
1507}
1508
1510 // scoped_lock locks both mutexes at once.
1511 std::scoped_lock<std::recursive_mutex, std::recursive_mutex> lock(
1513 m_modules.swap(other.m_modules);
1514}
1515
1516void ModuleList::PreloadSymbols(bool parallelize) const {
1517 std::lock_guard<std::recursive_mutex> guard(m_modules_mutex);
1518
1519 if (!parallelize) {
1520 for (const ModuleSP &module_sp : m_modules)
1521 module_sp->PreloadSymbols();
1522 return;
1523 }
1524
1525 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1526 for (const ModuleSP &module_sp : m_modules)
1527 task_group.async([module_sp] {
1528 if (module_sp)
1529 module_sp->PreloadSymbols();
1530 });
1531 task_group.wait();
1532}
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:101
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:70
FileSpec & GetFileSpec()
Definition ModuleSpec.h:58
lldb::PlatformSP GetPlatformSP() const
Definition ModuleSpec.h:153
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:94
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:82
lldb::TargetSP GetTargetSP() const
Definition ModuleSpec.h:143
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:1362
lldb::PlatformSP GetPlatform()
Definition Target.h:2004
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
Definition Type.cpp:201
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:62
@ eLoadScriptFromSymFileTrusted
Definition Target.h:65
@ eLoadScriptFromSymFileFalse
Definition Target.h:63
@ eLoadScriptFromSymFileWarn
Definition Target.h:64
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