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/ObjectFile.h"
26 #include "lldb/Symbol/SymbolFile.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 assignments 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                                               eLanguageTypeUnknown, // TODO: add support
376                                               lookup_name,
377                                               lookup_name_type_mask,
378                                               match_name_after_lookup);
379 
380         Mutex::Locker locker(m_modules_mutex);
381         collection::const_iterator pos, end = m_modules.end();
382         for (pos = m_modules.begin(); pos != end; ++pos)
383         {
384             (*pos)->FindFunctions (lookup_name,
385                                    NULL,
386                                    lookup_name_type_mask,
387                                    include_symbols,
388                                    include_inlines,
389                                    true,
390                                    sc_list);
391         }
392 
393         if (match_name_after_lookup)
394         {
395             SymbolContext sc;
396             size_t i = old_size;
397             while (i<sc_list.GetSize())
398             {
399                 if (sc_list.GetContextAtIndex(i, sc))
400                 {
401                     const char *func_name = sc.GetFunctionName().GetCString();
402                     if (func_name && strstr (func_name, name.GetCString()) == NULL)
403                     {
404                         // Remove the current context
405                         sc_list.RemoveContextAtIndex(i);
406                         // Don't increment i and continue in the loop
407                         continue;
408                     }
409                 }
410                 ++i;
411             }
412         }
413 
414     }
415     else
416     {
417         Mutex::Locker locker(m_modules_mutex);
418         collection::const_iterator pos, end = m_modules.end();
419         for (pos = m_modules.begin(); pos != end; ++pos)
420         {
421             (*pos)->FindFunctions (name, NULL, name_type_mask, include_symbols, include_inlines, true, sc_list);
422         }
423     }
424     return sc_list.GetSize() - old_size;
425 }
426 
427 size_t
428 ModuleList::FindFunctionSymbols (const ConstString &name,
429                                  uint32_t name_type_mask,
430                                  SymbolContextList& sc_list)
431 {
432     const size_t old_size = sc_list.GetSize();
433 
434     if (name_type_mask & eFunctionNameTypeAuto)
435     {
436         ConstString lookup_name;
437         uint32_t lookup_name_type_mask = 0;
438         bool match_name_after_lookup = false;
439         Module::PrepareForFunctionNameLookup (name, name_type_mask,
440                                               eLanguageTypeUnknown, // TODO: add support
441                                               lookup_name,
442                                               lookup_name_type_mask,
443                                               match_name_after_lookup);
444 
445         Mutex::Locker locker(m_modules_mutex);
446         collection::const_iterator pos, end = m_modules.end();
447         for (pos = m_modules.begin(); pos != end; ++pos)
448         {
449             (*pos)->FindFunctionSymbols (lookup_name,
450                                    lookup_name_type_mask,
451                                    sc_list);
452         }
453 
454         if (match_name_after_lookup)
455         {
456             SymbolContext sc;
457             size_t i = old_size;
458             while (i<sc_list.GetSize())
459             {
460                 if (sc_list.GetContextAtIndex(i, sc))
461                 {
462                     const char *func_name = sc.GetFunctionName().GetCString();
463                     if (func_name && strstr (func_name, name.GetCString()) == NULL)
464                     {
465                         // Remove the current context
466                         sc_list.RemoveContextAtIndex(i);
467                         // Don't increment i and continue in the loop
468                         continue;
469                     }
470                 }
471                 ++i;
472             }
473         }
474 
475     }
476     else
477     {
478         Mutex::Locker locker(m_modules_mutex);
479         collection::const_iterator pos, end = m_modules.end();
480         for (pos = m_modules.begin(); pos != end; ++pos)
481         {
482             (*pos)->FindFunctionSymbols (name, name_type_mask, sc_list);
483         }
484     }
485 
486     return sc_list.GetSize() - old_size;
487 }
488 
489 
490 size_t
491 ModuleList::FindFunctions(const RegularExpression &name,
492                           bool include_symbols,
493                           bool include_inlines,
494                           bool append,
495                           SymbolContextList& sc_list)
496 {
497     const size_t old_size = sc_list.GetSize();
498 
499     Mutex::Locker locker(m_modules_mutex);
500     collection::const_iterator pos, end = m_modules.end();
501     for (pos = m_modules.begin(); pos != end; ++pos)
502     {
503         (*pos)->FindFunctions (name, include_symbols, include_inlines, append, sc_list);
504     }
505 
506     return sc_list.GetSize() - old_size;
507 }
508 
509 size_t
510 ModuleList::FindCompileUnits (const FileSpec &path,
511                               bool append,
512                               SymbolContextList &sc_list) const
513 {
514     if (!append)
515         sc_list.Clear();
516 
517     Mutex::Locker locker(m_modules_mutex);
518     collection::const_iterator pos, end = m_modules.end();
519     for (pos = m_modules.begin(); pos != end; ++pos)
520     {
521         (*pos)->FindCompileUnits (path, true, sc_list);
522     }
523 
524     return sc_list.GetSize();
525 }
526 
527 size_t
528 ModuleList::FindGlobalVariables (const ConstString &name,
529                                  bool append,
530                                  size_t max_matches,
531                                  VariableList& variable_list) const
532 {
533     size_t initial_size = variable_list.GetSize();
534     Mutex::Locker locker(m_modules_mutex);
535     collection::const_iterator pos, end = m_modules.end();
536     for (pos = m_modules.begin(); pos != end; ++pos)
537     {
538         (*pos)->FindGlobalVariables (name, NULL, append, max_matches, variable_list);
539     }
540     return variable_list.GetSize() - initial_size;
541 }
542 
543 
544 size_t
545 ModuleList::FindGlobalVariables (const RegularExpression& regex,
546                                  bool append,
547                                  size_t max_matches,
548                                  VariableList& variable_list) const
549 {
550     size_t initial_size = variable_list.GetSize();
551     Mutex::Locker locker(m_modules_mutex);
552     collection::const_iterator pos, end = m_modules.end();
553     for (pos = m_modules.begin(); pos != end; ++pos)
554     {
555         (*pos)->FindGlobalVariables (regex, append, max_matches, variable_list);
556     }
557     return variable_list.GetSize() - initial_size;
558 }
559 
560 
561 size_t
562 ModuleList::FindSymbolsWithNameAndType (const ConstString &name,
563                                         SymbolType symbol_type,
564                                         SymbolContextList &sc_list,
565                                         bool append) const
566 {
567     Mutex::Locker locker(m_modules_mutex);
568     if (!append)
569         sc_list.Clear();
570     size_t initial_size = sc_list.GetSize();
571 
572     collection::const_iterator pos, end = m_modules.end();
573     for (pos = m_modules.begin(); pos != end; ++pos)
574         (*pos)->FindSymbolsWithNameAndType (name, symbol_type, sc_list);
575     return sc_list.GetSize() - initial_size;
576 }
577 
578 size_t
579 ModuleList::FindSymbolsMatchingRegExAndType (const RegularExpression &regex,
580                                              lldb::SymbolType symbol_type,
581                                              SymbolContextList &sc_list,
582                                              bool append) const
583 {
584     Mutex::Locker locker(m_modules_mutex);
585     if (!append)
586         sc_list.Clear();
587     size_t initial_size = sc_list.GetSize();
588 
589     collection::const_iterator pos, end = m_modules.end();
590     for (pos = m_modules.begin(); pos != end; ++pos)
591         (*pos)->FindSymbolsMatchingRegExAndType (regex, symbol_type, sc_list);
592     return sc_list.GetSize() - initial_size;
593 }
594 
595 size_t
596 ModuleList::FindModules (const ModuleSpec &module_spec, ModuleList& matching_module_list) const
597 {
598     size_t existing_matches = matching_module_list.GetSize();
599 
600     Mutex::Locker locker(m_modules_mutex);
601     collection::const_iterator pos, end = m_modules.end();
602     for (pos = m_modules.begin(); pos != end; ++pos)
603     {
604         ModuleSP module_sp(*pos);
605         if (module_sp->MatchesModuleSpec (module_spec))
606             matching_module_list.Append(module_sp);
607     }
608     return matching_module_list.GetSize() - existing_matches;
609 }
610 
611 ModuleSP
612 ModuleList::FindModule (const Module *module_ptr) const
613 {
614     ModuleSP module_sp;
615 
616     // Scope for "locker"
617     {
618         Mutex::Locker locker(m_modules_mutex);
619         collection::const_iterator pos, end = m_modules.end();
620 
621         for (pos = m_modules.begin(); pos != end; ++pos)
622         {
623             if ((*pos).get() == module_ptr)
624             {
625                 module_sp = (*pos);
626                 break;
627             }
628         }
629     }
630     return module_sp;
631 
632 }
633 
634 ModuleSP
635 ModuleList::FindModule (const UUID &uuid) const
636 {
637     ModuleSP module_sp;
638 
639     if (uuid.IsValid())
640     {
641         Mutex::Locker locker(m_modules_mutex);
642         collection::const_iterator pos, end = m_modules.end();
643 
644         for (pos = m_modules.begin(); pos != end; ++pos)
645         {
646             if ((*pos)->GetUUID() == uuid)
647             {
648                 module_sp = (*pos);
649                 break;
650             }
651         }
652     }
653     return module_sp;
654 }
655 
656 
657 size_t
658 ModuleList::FindTypes (const SymbolContext& sc, const ConstString &name, bool name_is_fully_qualified, size_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeList& types) const
659 {
660     Mutex::Locker locker(m_modules_mutex);
661 
662     size_t total_matches = 0;
663     collection::const_iterator pos, end = m_modules.end();
664     if (sc.module_sp)
665     {
666         // The symbol context "sc" contains a module so we want to search that
667         // one first if it is in our list...
668         for (pos = m_modules.begin(); pos != end; ++pos)
669         {
670             if (sc.module_sp.get() == (*pos).get())
671             {
672                 total_matches += (*pos)->FindTypes (sc, name, name_is_fully_qualified, max_matches, searched_symbol_files, types);
673 
674                 if (total_matches >= max_matches)
675                     break;
676             }
677         }
678     }
679 
680     if (total_matches < max_matches)
681     {
682         SymbolContext world_sc;
683         for (pos = m_modules.begin(); pos != end; ++pos)
684         {
685             // Search the module if the module is not equal to the one in the symbol
686             // context "sc". If "sc" contains a empty module shared pointer, then
687             // the comparison will always be true (valid_module_ptr != NULL).
688             if (sc.module_sp.get() != (*pos).get())
689                 total_matches += (*pos)->FindTypes (world_sc, name, name_is_fully_qualified, max_matches, searched_symbol_files, types);
690 
691             if (total_matches >= max_matches)
692                 break;
693         }
694     }
695 
696     return total_matches;
697 }
698 
699 bool
700 ModuleList::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
701 {
702     Mutex::Locker locker(m_modules_mutex);
703     collection::const_iterator pos, end = m_modules.end();
704     for (pos = m_modules.begin(); pos != end; ++pos)
705     {
706         if ((*pos)->FindSourceFile (orig_spec, new_spec))
707             return true;
708     }
709     return false;
710 }
711 
712 void
713 ModuleList::FindAddressesForLine (const lldb::TargetSP target_sp,
714                                   const FileSpec &file, uint32_t line,
715                                   Function *function,
716                                   std::vector<Address> &output_local, std::vector<Address> &output_extern)
717 {
718     Mutex::Locker locker(m_modules_mutex);
719     collection::const_iterator pos, end = m_modules.end();
720     for (pos = m_modules.begin(); pos != end; ++pos)
721     {
722         (*pos)->FindAddressesForLine(target_sp, file, line, function, output_local, output_extern);
723     }
724 }
725 
726 ModuleSP
727 ModuleList::FindFirstModule (const ModuleSpec &module_spec) const
728 {
729     ModuleSP module_sp;
730     Mutex::Locker locker(m_modules_mutex);
731     collection::const_iterator pos, end = m_modules.end();
732     for (pos = m_modules.begin(); pos != end; ++pos)
733     {
734         ModuleSP module_sp(*pos);
735         if (module_sp->MatchesModuleSpec (module_spec))
736             return module_sp;
737     }
738     return module_sp;
739 
740 }
741 
742 size_t
743 ModuleList::GetSize() const
744 {
745     size_t size = 0;
746     {
747         Mutex::Locker locker(m_modules_mutex);
748         size = m_modules.size();
749     }
750     return size;
751 }
752 
753 
754 void
755 ModuleList::Dump(Stream *s) const
756 {
757 //  s.Printf("%.*p: ", (int)sizeof(void*) * 2, this);
758 //  s.Indent();
759 //  s << "ModuleList\n";
760 
761     Mutex::Locker locker(m_modules_mutex);
762     collection::const_iterator pos, end = m_modules.end();
763     for (pos = m_modules.begin(); pos != end; ++pos)
764     {
765         (*pos)->Dump(s);
766     }
767 }
768 
769 void
770 ModuleList::LogUUIDAndPaths (Log *log, const char *prefix_cstr)
771 {
772     if (log)
773     {
774         Mutex::Locker locker(m_modules_mutex);
775         collection::const_iterator pos, begin = m_modules.begin(), end = m_modules.end();
776         for (pos = begin; pos != end; ++pos)
777         {
778             Module *module = pos->get();
779             const FileSpec &module_file_spec = module->GetFileSpec();
780             log->Printf ("%s[%u] %s (%s) \"%s\"",
781                          prefix_cstr ? prefix_cstr : "",
782                          (uint32_t)std::distance (begin, pos),
783                          module->GetUUID().GetAsString().c_str(),
784                          module->GetArchitecture().GetArchitectureName(),
785                          module_file_spec.GetPath().c_str());
786         }
787     }
788 }
789 
790 bool
791 ModuleList::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr) const
792 {
793     Mutex::Locker locker(m_modules_mutex);
794     collection::const_iterator pos, end = m_modules.end();
795     for (pos = m_modules.begin(); pos != end; ++pos)
796     {
797         if ((*pos)->ResolveFileAddress (vm_addr, so_addr))
798             return true;
799     }
800 
801     return false;
802 }
803 
804 uint32_t
805 ModuleList::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc) const
806 {
807     // The address is already section offset so it has a module
808     uint32_t resolved_flags = 0;
809     ModuleSP module_sp (so_addr.GetModule());
810     if (module_sp)
811     {
812         resolved_flags = module_sp->ResolveSymbolContextForAddress (so_addr,
813                                                                     resolve_scope,
814                                                                     sc);
815     }
816     else
817     {
818         Mutex::Locker locker(m_modules_mutex);
819         collection::const_iterator pos, end = m_modules.end();
820         for (pos = m_modules.begin(); pos != end; ++pos)
821         {
822             resolved_flags = (*pos)->ResolveSymbolContextForAddress (so_addr,
823                                                                      resolve_scope,
824                                                                      sc);
825             if (resolved_flags != 0)
826                 break;
827         }
828     }
829 
830     return resolved_flags;
831 }
832 
833 uint32_t
834 ModuleList::ResolveSymbolContextForFilePath
835 (
836     const char *file_path,
837     uint32_t line,
838     bool check_inlines,
839     uint32_t resolve_scope,
840     SymbolContextList& sc_list
841 )  const
842 {
843     FileSpec file_spec(file_path, false);
844     return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
845 }
846 
847 uint32_t
848 ModuleList::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list) const
849 {
850     Mutex::Locker locker(m_modules_mutex);
851     collection::const_iterator pos, end = m_modules.end();
852     for (pos = m_modules.begin(); pos != end; ++pos)
853     {
854         (*pos)->ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
855     }
856 
857     return sc_list.GetSize();
858 }
859 
860 size_t
861 ModuleList::GetIndexForModule (const Module *module) const
862 {
863     if (module)
864     {
865         Mutex::Locker locker(m_modules_mutex);
866         collection::const_iterator pos;
867         collection::const_iterator begin = m_modules.begin();
868         collection::const_iterator end = m_modules.end();
869         for (pos = begin; pos != end; ++pos)
870         {
871             if ((*pos).get() == module)
872                 return std::distance (begin, pos);
873         }
874     }
875     return LLDB_INVALID_INDEX32;
876 }
877 
878 static ModuleList &
879 GetSharedModuleList ()
880 {
881     static ModuleList *g_shared_module_list = NULL;
882     static std::once_flag g_once_flag;
883     std::call_once(g_once_flag, [](){
884         // NOTE: Intentionally leak the module list so a program doesn't have to
885         // cleanup all modules and object files as it exits. This just wastes time
886         // doing a bunch of cleanup that isn't required.
887         if (g_shared_module_list == NULL)
888             g_shared_module_list = new ModuleList(); // <--- Intentional leak!!!
889     });
890     return *g_shared_module_list;
891 }
892 
893 bool
894 ModuleList::ModuleIsInCache (const Module *module_ptr)
895 {
896     if (module_ptr)
897     {
898         ModuleList &shared_module_list = GetSharedModuleList ();
899         return shared_module_list.FindModule (module_ptr).get() != NULL;
900     }
901     return false;
902 }
903 
904 size_t
905 ModuleList::FindSharedModules (const ModuleSpec &module_spec, ModuleList &matching_module_list)
906 {
907     return GetSharedModuleList ().FindModules (module_spec, matching_module_list);
908 }
909 
910 size_t
911 ModuleList::RemoveOrphanSharedModules (bool mandatory)
912 {
913     return GetSharedModuleList ().RemoveOrphans(mandatory);
914 }
915 
916 Error
917 ModuleList::GetSharedModule
918 (
919     const ModuleSpec &module_spec,
920     ModuleSP &module_sp,
921     const FileSpecList *module_search_paths_ptr,
922     ModuleSP *old_module_sp_ptr,
923     bool *did_create_ptr,
924     bool always_create
925 )
926 {
927     ModuleList &shared_module_list = GetSharedModuleList ();
928     Mutex::Locker locker(shared_module_list.m_modules_mutex);
929     char path[PATH_MAX];
930 
931     Error error;
932 
933     module_sp.reset();
934 
935     if (did_create_ptr)
936         *did_create_ptr = false;
937     if (old_module_sp_ptr)
938         old_module_sp_ptr->reset();
939 
940     const UUID *uuid_ptr = module_spec.GetUUIDPtr();
941     const FileSpec &module_file_spec = module_spec.GetFileSpec();
942     const ArchSpec &arch = module_spec.GetArchitecture();
943 
944     // Make sure no one else can try and get or create a module while this
945     // function is actively working on it by doing an extra lock on the
946     // global mutex list.
947     if (always_create == false)
948     {
949         ModuleList matching_module_list;
950         const size_t num_matching_modules = shared_module_list.FindModules (module_spec, matching_module_list);
951         if (num_matching_modules > 0)
952         {
953             for (size_t module_idx = 0; module_idx < num_matching_modules; ++module_idx)
954             {
955                 module_sp = matching_module_list.GetModuleAtIndex(module_idx);
956 
957                 // Make sure the file for the module hasn't been modified
958                 if (module_sp->FileHasChanged())
959                 {
960                     if (old_module_sp_ptr && !old_module_sp_ptr->get())
961                         *old_module_sp_ptr = module_sp;
962 
963                     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_MODULES));
964                     if (log)
965                         log->Printf("module changed: %p, removing from global module list",
966                                     static_cast<void*>(module_sp.get()));
967 
968                     shared_module_list.Remove (module_sp);
969                     module_sp.reset();
970                 }
971                 else
972                 {
973                     // The module matches and the module was not modified from
974                     // when it was last loaded.
975                     return error;
976                 }
977             }
978         }
979     }
980 
981     if (module_sp)
982         return error;
983 
984     module_sp.reset (new Module (module_spec));
985     // Make sure there are a module and an object file since we can specify
986     // a valid file path with an architecture that might not be in that file.
987     // By getting the object file we can guarantee that the architecture matches
988     if (module_sp->GetObjectFile())
989     {
990         // If we get in here we got the correct arch, now we just need
991         // to verify the UUID if one was given
992         if (uuid_ptr && *uuid_ptr != module_sp->GetUUID())
993         {
994             module_sp.reset();
995         }
996         else
997         {
998             if (module_sp->GetObjectFile() && module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeStubLibrary)
999             {
1000                 module_sp.reset();
1001             }
1002             else
1003             {
1004                 if (did_create_ptr)
1005                 {
1006                     *did_create_ptr = true;
1007                 }
1008 
1009                 shared_module_list.ReplaceEquivalent(module_sp);
1010                 return error;
1011             }
1012         }
1013     }
1014     else
1015     {
1016         module_sp.reset();
1017     }
1018 
1019     if (module_search_paths_ptr)
1020     {
1021         const auto num_directories = module_search_paths_ptr->GetSize();
1022         for (size_t idx = 0; idx < num_directories; ++idx)
1023         {
1024             auto search_path_spec = module_search_paths_ptr->GetFileSpecAtIndex(idx);
1025             if (!search_path_spec.ResolvePath())
1026                 continue;
1027             if (!search_path_spec.Exists() || !search_path_spec.IsDirectory())
1028                 continue;
1029             search_path_spec.AppendPathComponent(module_spec.GetFileSpec().GetFilename().AsCString());
1030             if (!search_path_spec.Exists())
1031                 continue;
1032 
1033             auto resolved_module_spec(module_spec);
1034             resolved_module_spec.GetFileSpec() = search_path_spec;
1035             module_sp.reset (new Module (resolved_module_spec));
1036             if (module_sp->GetObjectFile())
1037             {
1038                 // If we get in here we got the correct arch, now we just need
1039                 // to verify the UUID if one was given
1040                 if (uuid_ptr && *uuid_ptr != module_sp->GetUUID())
1041                 {
1042                     module_sp.reset();
1043                 }
1044                 else
1045                 {
1046                     if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeStubLibrary)
1047                     {
1048                         module_sp.reset();
1049                     }
1050                     else
1051                     {
1052                         if (did_create_ptr)
1053                             *did_create_ptr = true;
1054 
1055                         shared_module_list.ReplaceEquivalent(module_sp);
1056                         return Error();
1057                     }
1058                 }
1059             }
1060             else
1061             {
1062                 module_sp.reset();
1063             }
1064         }
1065     }
1066 
1067     // Either the file didn't exist where at the path, or no path was given, so
1068     // we now have to use more extreme measures to try and find the appropriate
1069     // module.
1070 
1071     // Fixup the incoming path in case the path points to a valid file, yet
1072     // the arch or UUID (if one was passed in) don't match.
1073     ModuleSpec located_binary_modulespec = Symbols::LocateExecutableObjectFile (module_spec);
1074 
1075     // Don't look for the file if it appears to be the same one we already
1076     // checked for above...
1077     if (located_binary_modulespec.GetFileSpec() != module_file_spec)
1078     {
1079         if (!located_binary_modulespec.GetFileSpec().Exists())
1080         {
1081             located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1082             if (path[0] == '\0')
1083                 module_file_spec.GetPath(path, sizeof(path));
1084             // How can this check ever be true? This branch it is false, and we haven't modified file_spec.
1085             if (located_binary_modulespec.GetFileSpec().Exists())
1086             {
1087                 std::string uuid_str;
1088                 if (uuid_ptr && uuid_ptr->IsValid())
1089                     uuid_str = uuid_ptr->GetAsString();
1090 
1091                 if (arch.IsValid())
1092                 {
1093                     if (!uuid_str.empty())
1094                         error.SetErrorStringWithFormat("'%s' does not contain the %s architecture and UUID %s", path, arch.GetArchitectureName(), uuid_str.c_str());
1095                     else
1096                         error.SetErrorStringWithFormat("'%s' does not contain the %s architecture.", path, arch.GetArchitectureName());
1097                 }
1098             }
1099             else
1100             {
1101                 error.SetErrorStringWithFormat("'%s' does not exist", path);
1102             }
1103             if (error.Fail())
1104                 module_sp.reset();
1105             return error;
1106         }
1107 
1108 
1109         // Make sure no one else can try and get or create a module while this
1110         // function is actively working on it by doing an extra lock on the
1111         // global mutex list.
1112         ModuleSpec platform_module_spec(module_spec);
1113         platform_module_spec.GetFileSpec() = located_binary_modulespec.GetFileSpec();
1114         platform_module_spec.GetPlatformFileSpec() = located_binary_modulespec.GetFileSpec();
1115         platform_module_spec.GetSymbolFileSpec() = located_binary_modulespec.GetSymbolFileSpec();
1116         ModuleList matching_module_list;
1117         if (shared_module_list.FindModules (platform_module_spec, matching_module_list) > 0)
1118         {
1119             module_sp = matching_module_list.GetModuleAtIndex(0);
1120 
1121             // If we didn't have a UUID in mind when looking for the object file,
1122             // then we should make sure the modification time hasn't changed!
1123             if (platform_module_spec.GetUUIDPtr() == NULL)
1124             {
1125                 TimeValue file_spec_mod_time(located_binary_modulespec.GetFileSpec().GetModificationTime());
1126                 if (file_spec_mod_time.IsValid())
1127                 {
1128                     if (file_spec_mod_time != module_sp->GetModificationTime())
1129                     {
1130                         if (old_module_sp_ptr)
1131                             *old_module_sp_ptr = module_sp;
1132                         shared_module_list.Remove (module_sp);
1133                         module_sp.reset();
1134                     }
1135                 }
1136             }
1137         }
1138 
1139         if (module_sp.get() == NULL)
1140         {
1141             module_sp.reset (new Module (platform_module_spec));
1142             // Make sure there are a module and an object file since we can specify
1143             // a valid file path with an architecture that might not be in that file.
1144             // By getting the object file we can guarantee that the architecture matches
1145             if (module_sp && module_sp->GetObjectFile())
1146             {
1147                 if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeStubLibrary)
1148                 {
1149                     module_sp.reset();
1150                 }
1151                 else
1152                 {
1153                     if (did_create_ptr)
1154                         *did_create_ptr = true;
1155 
1156                     shared_module_list.ReplaceEquivalent(module_sp);
1157                 }
1158             }
1159             else
1160             {
1161                 located_binary_modulespec.GetFileSpec().GetPath(path, sizeof(path));
1162 
1163                 if (located_binary_modulespec.GetFileSpec())
1164                 {
1165                     if (arch.IsValid())
1166                         error.SetErrorStringWithFormat("unable to open %s architecture in '%s'", arch.GetArchitectureName(), path);
1167                     else
1168                         error.SetErrorStringWithFormat("unable to open '%s'", path);
1169                 }
1170                 else
1171                 {
1172                     std::string uuid_str;
1173                     if (uuid_ptr && uuid_ptr->IsValid())
1174                         uuid_str = uuid_ptr->GetAsString();
1175 
1176                     if (!uuid_str.empty())
1177                         error.SetErrorStringWithFormat("cannot locate a module for UUID '%s'", uuid_str.c_str());
1178                     else
1179                         error.SetErrorStringWithFormat("cannot locate a module");
1180                 }
1181             }
1182         }
1183     }
1184 
1185     return error;
1186 }
1187 
1188 bool
1189 ModuleList::RemoveSharedModule (lldb::ModuleSP &module_sp)
1190 {
1191     return GetSharedModuleList ().Remove (module_sp);
1192 }
1193 
1194 bool
1195 ModuleList::RemoveSharedModuleIfOrphaned (const Module *module_ptr)
1196 {
1197     return GetSharedModuleList ().RemoveIfOrphaned (module_ptr);
1198 }
1199 
1200 bool
1201 ModuleList::LoadScriptingResourcesInTarget (Target *target,
1202                                             std::list<Error>& errors,
1203                                             Stream *feedback_stream,
1204                                             bool continue_on_error)
1205 {
1206     if (!target)
1207         return false;
1208     Mutex::Locker locker(m_modules_mutex);
1209     for (auto module : m_modules)
1210     {
1211         Error error;
1212         if (module)
1213         {
1214             if (!module->LoadScriptingResourceInTarget(target, error, feedback_stream))
1215             {
1216                 if (error.Fail() && error.AsCString())
1217                 {
1218                     error.SetErrorStringWithFormat("unable to load scripting data for module %s - error reported was %s",
1219                                                    module->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1220                                                    error.AsCString());
1221                     errors.push_back(error);
1222 
1223                     if (!continue_on_error)
1224                         return false;
1225                 }
1226             }
1227         }
1228     }
1229     return errors.size() == 0;
1230 }
1231 
1232 void
1233 ModuleList::ForEach (std::function <bool (const ModuleSP &module_sp)> const &callback) const
1234 {
1235     Mutex::Locker locker(m_modules_mutex);
1236     for (const auto &module : m_modules)
1237     {
1238         // If the callback returns false, then stop iterating and break out
1239         if (!callback (module))
1240             break;
1241     }
1242 }
1243