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