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