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