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