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