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