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