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