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