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