1 //===-- Module.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/lldb-python.h"
11 
12 #include "lldb/Core/Error.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/DataBuffer.h"
15 #include "lldb/Core/DataBufferHeap.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/RegularExpression.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Core/Timer.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Host/Symbols.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/ScriptInterpreter.h"
27 #include "lldb/lldb-private-log.h"
28 #include "lldb/Symbol/CompileUnit.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Symbol/SymbolContext.h"
31 #include "lldb/Symbol/SymbolVendor.h"
32 #include "lldb/Target/CPPLanguageRuntime.h"
33 #include "lldb/Target/ObjCLanguageRuntime.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/Target.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 // Shared pointers to modules track module lifetimes in
41 // targets and in the global module, but this collection
42 // will track all module objects that are still alive
43 typedef std::vector<Module *> ModuleCollection;
44 
45 static ModuleCollection &
46 GetModuleCollection()
47 {
48     // This module collection needs to live past any module, so we could either make it a
49     // shared pointer in each module or just leak is.  Since it is only an empty vector by
50     // the time all the modules have gone away, we just leak it for now.  If we decide this
51     // is a big problem we can introduce a Finalize method that will tear everything down in
52     // a predictable order.
53 
54     static ModuleCollection *g_module_collection = NULL;
55     if (g_module_collection == NULL)
56         g_module_collection = new ModuleCollection();
57 
58     return *g_module_collection;
59 }
60 
61 Mutex *
62 Module::GetAllocationModuleCollectionMutex()
63 {
64     // NOTE: The mutex below must be leaked since the global module list in
65     // the ModuleList class will get torn at some point, and we can't know
66     // if it will tear itself down before the "g_module_collection_mutex" below
67     // will. So we leak a Mutex object below to safeguard against that
68 
69     static Mutex *g_module_collection_mutex = NULL;
70     if (g_module_collection_mutex == NULL)
71         g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
72     return g_module_collection_mutex;
73 }
74 
75 size_t
76 Module::GetNumberAllocatedModules ()
77 {
78     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
79     return GetModuleCollection().size();
80 }
81 
82 Module *
83 Module::GetAllocatedModuleAtIndex (size_t idx)
84 {
85     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
86     ModuleCollection &modules = GetModuleCollection();
87     if (idx < modules.size())
88         return modules[idx];
89     return NULL;
90 }
91 #if 0
92 
93 // These functions help us to determine if modules are still loaded, yet don't require that
94 // you have a command interpreter and can easily be called from an external debugger.
95 namespace lldb {
96 
97     void
98     ClearModuleInfo (void)
99     {
100         const bool mandatory = true;
101         ModuleList::RemoveOrphanSharedModules(mandatory);
102     }
103 
104     void
105     DumpModuleInfo (void)
106     {
107         Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
108         ModuleCollection &modules = GetModuleCollection();
109         const size_t count = modules.size();
110         printf ("%s: %" PRIu64 " modules:\n", __PRETTY_FUNCTION__, (uint64_t)count);
111         for (size_t i=0; i<count; ++i)
112         {
113 
114             StreamString strm;
115             Module *module = modules[i];
116             const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
117             module->GetDescription(&strm, eDescriptionLevelFull);
118             printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
119                     module,
120                     in_shared_module_list,
121                     (uint32_t)module->use_count(),
122                     strm.GetString().c_str());
123         }
124     }
125 }
126 
127 #endif
128 
129 Module::Module (const ModuleSpec &module_spec) :
130     m_mutex (Mutex::eMutexTypeRecursive),
131     m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
132     m_arch (module_spec.GetArchitecture()),
133     m_uuid (),
134     m_file (module_spec.GetFileSpec()),
135     m_platform_file(module_spec.GetPlatformFileSpec()),
136     m_symfile_spec (module_spec.GetSymbolFileSpec()),
137     m_object_name (module_spec.GetObjectName()),
138     m_object_offset (module_spec.GetObjectOffset()),
139     m_object_mod_time (module_spec.GetObjectModificationTime()),
140     m_objfile_sp (),
141     m_symfile_ap (),
142     m_ast (),
143     m_source_mappings (),
144     m_did_load_objfile (false),
145     m_did_load_symbol_vendor (false),
146     m_did_parse_uuid (false),
147     m_did_init_ast (false),
148     m_is_dynamic_loader_module (false),
149     m_file_has_changed (false),
150     m_first_file_changed_log (false)
151 {
152     // Scope for locker below...
153     {
154         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
155         GetModuleCollection().push_back(this);
156     }
157 
158     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
159     if (log)
160         log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
161                      this,
162                      m_arch.GetArchitectureName(),
163                      m_file.GetPath().c_str(),
164                      m_object_name.IsEmpty() ? "" : "(",
165                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
166                      m_object_name.IsEmpty() ? "" : ")");
167 }
168 
169 Module::Module(const FileSpec& file_spec,
170                const ArchSpec& arch,
171                const ConstString *object_name,
172                off_t object_offset,
173                const TimeValue *object_mod_time_ptr) :
174     m_mutex (Mutex::eMutexTypeRecursive),
175     m_mod_time (file_spec.GetModificationTime()),
176     m_arch (arch),
177     m_uuid (),
178     m_file (file_spec),
179     m_platform_file(),
180     m_symfile_spec (),
181     m_object_name (),
182     m_object_offset (object_offset),
183     m_object_mod_time (),
184     m_objfile_sp (),
185     m_symfile_ap (),
186     m_ast (),
187     m_source_mappings (),
188     m_did_load_objfile (false),
189     m_did_load_symbol_vendor (false),
190     m_did_parse_uuid (false),
191     m_did_init_ast (false),
192     m_is_dynamic_loader_module (false),
193     m_file_has_changed (false),
194     m_first_file_changed_log (false)
195 {
196     // Scope for locker below...
197     {
198         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
199         GetModuleCollection().push_back(this);
200     }
201 
202     if (object_name)
203         m_object_name = *object_name;
204 
205     if (object_mod_time_ptr)
206         m_object_mod_time = *object_mod_time_ptr;
207 
208     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
209     if (log)
210         log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
211                      this,
212                      m_arch.GetArchitectureName(),
213                      m_file.GetPath().c_str(),
214                      m_object_name.IsEmpty() ? "" : "(",
215                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
216                      m_object_name.IsEmpty() ? "" : ")");
217 }
218 
219 Module::~Module()
220 {
221     // Lock our module down while we tear everything down to make sure
222     // we don't get any access to the module while it is being destroyed
223     Mutex::Locker locker (m_mutex);
224     // Scope for locker below...
225     {
226         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
227         ModuleCollection &modules = GetModuleCollection();
228         ModuleCollection::iterator end = modules.end();
229         ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
230         assert (pos != end);
231         modules.erase(pos);
232     }
233     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
234     if (log)
235         log->Printf ("%p Module::~Module((%s) '%s%s%s%s')",
236                      this,
237                      m_arch.GetArchitectureName(),
238                      m_file.GetPath().c_str(),
239                      m_object_name.IsEmpty() ? "" : "(",
240                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
241                      m_object_name.IsEmpty() ? "" : ")");
242     // Release any auto pointers before we start tearing down our member
243     // variables since the object file and symbol files might need to make
244     // function calls back into this module object. The ordering is important
245     // here because symbol files can require the module object file. So we tear
246     // down the symbol file first, then the object file.
247     m_symfile_ap.reset();
248     m_objfile_sp.reset();
249 }
250 
251 ObjectFile *
252 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
253 {
254     if (m_objfile_sp)
255     {
256         error.SetErrorString ("object file already exists");
257     }
258     else
259     {
260         Mutex::Locker locker (m_mutex);
261         if (process_sp)
262         {
263             m_did_load_objfile = true;
264             std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
265             Error readmem_error;
266             const size_t bytes_read = process_sp->ReadMemory (header_addr,
267                                                               data_ap->GetBytes(),
268                                                               data_ap->GetByteSize(),
269                                                               readmem_error);
270             if (bytes_read == 512)
271             {
272                 DataBufferSP data_sp(data_ap.release());
273                 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
274                 if (m_objfile_sp)
275                 {
276                     StreamString s;
277                     s.Printf("0x%16.16" PRIx64, header_addr);
278                     m_object_name.SetCString (s.GetData());
279 
280                     // Once we get the object file, update our module with the object file's
281                     // architecture since it might differ in vendor/os if some parts were
282                     // unknown.
283                     m_objfile_sp->GetArchitecture (m_arch);
284                 }
285                 else
286                 {
287                     error.SetErrorString ("unable to find suitable object file plug-in");
288                 }
289             }
290             else
291             {
292                 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
293             }
294         }
295         else
296         {
297             error.SetErrorString ("invalid process");
298         }
299     }
300     return m_objfile_sp.get();
301 }
302 
303 
304 const lldb_private::UUID&
305 Module::GetUUID()
306 {
307     Mutex::Locker locker (m_mutex);
308     if (m_did_parse_uuid == false)
309     {
310         ObjectFile * obj_file = GetObjectFile ();
311 
312         if (obj_file != NULL)
313         {
314             obj_file->GetUUID(&m_uuid);
315             m_did_parse_uuid = true;
316         }
317     }
318     return m_uuid;
319 }
320 
321 ClangASTContext &
322 Module::GetClangASTContext ()
323 {
324     Mutex::Locker locker (m_mutex);
325     if (m_did_init_ast == false)
326     {
327         ObjectFile * objfile = GetObjectFile();
328         ArchSpec object_arch;
329         if (objfile && objfile->GetArchitecture(object_arch))
330         {
331             m_did_init_ast = true;
332 
333             // LLVM wants this to be set to iOS or MacOSX; if we're working on
334             // a bare-boards type image, change the triple for llvm's benefit.
335             if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
336                 && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
337             {
338                 if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
339                     object_arch.GetTriple().getArch() == llvm::Triple::thumb)
340                 {
341                     object_arch.GetTriple().setOS(llvm::Triple::IOS);
342                 }
343                 else
344                 {
345                     object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
346                 }
347             }
348             m_ast.SetArchitecture (object_arch);
349         }
350     }
351     return m_ast;
352 }
353 
354 void
355 Module::ParseAllDebugSymbols()
356 {
357     Mutex::Locker locker (m_mutex);
358     size_t num_comp_units = GetNumCompileUnits();
359     if (num_comp_units == 0)
360         return;
361 
362     SymbolContext sc;
363     sc.module_sp = shared_from_this();
364     SymbolVendor *symbols = GetSymbolVendor ();
365 
366     for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
367     {
368         sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
369         if (sc.comp_unit)
370         {
371             sc.function = NULL;
372             symbols->ParseVariablesForContext(sc);
373 
374             symbols->ParseCompileUnitFunctions(sc);
375 
376             for (size_t func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
377             {
378                 symbols->ParseFunctionBlocks(sc);
379 
380                 // Parse the variables for this function and all its blocks
381                 symbols->ParseVariablesForContext(sc);
382             }
383 
384 
385             // Parse all types for this compile unit
386             sc.function = NULL;
387             symbols->ParseTypes(sc);
388         }
389     }
390 }
391 
392 void
393 Module::CalculateSymbolContext(SymbolContext* sc)
394 {
395     sc->module_sp = shared_from_this();
396 }
397 
398 ModuleSP
399 Module::CalculateSymbolContextModule ()
400 {
401     return shared_from_this();
402 }
403 
404 void
405 Module::DumpSymbolContext(Stream *s)
406 {
407     s->Printf(", Module{%p}", this);
408 }
409 
410 size_t
411 Module::GetNumCompileUnits()
412 {
413     Mutex::Locker locker (m_mutex);
414     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
415     SymbolVendor *symbols = GetSymbolVendor ();
416     if (symbols)
417         return symbols->GetNumCompileUnits();
418     return 0;
419 }
420 
421 CompUnitSP
422 Module::GetCompileUnitAtIndex (size_t index)
423 {
424     Mutex::Locker locker (m_mutex);
425     size_t num_comp_units = GetNumCompileUnits ();
426     CompUnitSP cu_sp;
427 
428     if (index < num_comp_units)
429     {
430         SymbolVendor *symbols = GetSymbolVendor ();
431         if (symbols)
432             cu_sp = symbols->GetCompileUnitAtIndex(index);
433     }
434     return cu_sp;
435 }
436 
437 bool
438 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
439 {
440     Mutex::Locker locker (m_mutex);
441     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr);
442     ObjectFile* ofile = GetObjectFile();
443     if (ofile)
444         return so_addr.ResolveAddressUsingFileSections(vm_addr, ofile->GetSectionList());
445     return false;
446 }
447 
448 uint32_t
449 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
450 {
451     Mutex::Locker locker (m_mutex);
452     uint32_t resolved_flags = 0;
453 
454     // Clear the result symbol context in case we don't find anything, but don't clear the target
455     sc.Clear(false);
456 
457     // Get the section from the section/offset address.
458     SectionSP section_sp (so_addr.GetSection());
459 
460     // Make sure the section matches this module before we try and match anything
461     if (section_sp && section_sp->GetModule().get() == this)
462     {
463         // If the section offset based address resolved itself, then this
464         // is the right module.
465         sc.module_sp = shared_from_this();
466         resolved_flags |= eSymbolContextModule;
467 
468         // Resolve the compile unit, function, block, line table or line
469         // entry if requested.
470         if (resolve_scope & eSymbolContextCompUnit    ||
471             resolve_scope & eSymbolContextFunction    ||
472             resolve_scope & eSymbolContextBlock       ||
473             resolve_scope & eSymbolContextLineEntry   )
474         {
475             SymbolVendor *symbols = GetSymbolVendor ();
476             if (symbols)
477                 resolved_flags |= symbols->ResolveSymbolContext (so_addr, resolve_scope, sc);
478         }
479 
480         // Resolve the symbol if requested, but don't re-look it up if we've already found it.
481         if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
482         {
483             ObjectFile* ofile = GetObjectFile();
484             if (ofile)
485             {
486                 Symtab *symtab = ofile->GetSymtab();
487                 if (symtab)
488                 {
489                     if (so_addr.IsSectionOffset())
490                     {
491                         sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
492                         if (sc.symbol)
493                             resolved_flags |= eSymbolContextSymbol;
494                     }
495                 }
496             }
497         }
498     }
499     return resolved_flags;
500 }
501 
502 uint32_t
503 Module::ResolveSymbolContextForFilePath
504 (
505     const char *file_path,
506     uint32_t line,
507     bool check_inlines,
508     uint32_t resolve_scope,
509     SymbolContextList& sc_list
510 )
511 {
512     FileSpec file_spec(file_path, false);
513     return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
514 }
515 
516 uint32_t
517 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
518 {
519     Mutex::Locker locker (m_mutex);
520     Timer scoped_timer(__PRETTY_FUNCTION__,
521                        "Module::ResolveSymbolContextForFilePath (%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
522                        file_spec.GetPath().c_str(),
523                        line,
524                        check_inlines ? "yes" : "no",
525                        resolve_scope);
526 
527     const uint32_t initial_count = sc_list.GetSize();
528 
529     SymbolVendor *symbols = GetSymbolVendor  ();
530     if (symbols)
531         symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
532 
533     return sc_list.GetSize() - initial_count;
534 }
535 
536 
537 size_t
538 Module::FindGlobalVariables (const ConstString &name,
539                              const ClangNamespaceDecl *namespace_decl,
540                              bool append,
541                              size_t max_matches,
542                              VariableList& variables)
543 {
544     SymbolVendor *symbols = GetSymbolVendor ();
545     if (symbols)
546         return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
547     return 0;
548 }
549 
550 size_t
551 Module::FindGlobalVariables (const RegularExpression& regex,
552                              bool append,
553                              size_t max_matches,
554                              VariableList& variables)
555 {
556     SymbolVendor *symbols = GetSymbolVendor ();
557     if (symbols)
558         return symbols->FindGlobalVariables(regex, append, max_matches, variables);
559     return 0;
560 }
561 
562 size_t
563 Module::FindCompileUnits (const FileSpec &path,
564                           bool append,
565                           SymbolContextList &sc_list)
566 {
567     if (!append)
568         sc_list.Clear();
569 
570     const size_t start_size = sc_list.GetSize();
571     const size_t num_compile_units = GetNumCompileUnits();
572     SymbolContext sc;
573     sc.module_sp = shared_from_this();
574     const bool compare_directory = path.GetDirectory();
575     for (size_t i=0; i<num_compile_units; ++i)
576     {
577         sc.comp_unit = GetCompileUnitAtIndex(i).get();
578         if (sc.comp_unit)
579         {
580             if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
581                 sc_list.Append(sc);
582         }
583     }
584     return sc_list.GetSize() - start_size;
585 }
586 
587 size_t
588 Module::FindFunctions (const ConstString &name,
589                        const ClangNamespaceDecl *namespace_decl,
590                        uint32_t name_type_mask,
591                        bool include_symbols,
592                        bool include_inlines,
593                        bool append,
594                        SymbolContextList& sc_list)
595 {
596     if (!append)
597         sc_list.Clear();
598 
599     const size_t old_size = sc_list.GetSize();
600 
601     // Find all the functions (not symbols, but debug information functions...
602     SymbolVendor *symbols = GetSymbolVendor ();
603 
604     if (name_type_mask & eFunctionNameTypeAuto)
605     {
606         ConstString lookup_name;
607         uint32_t lookup_name_type_mask = 0;
608         bool match_name_after_lookup = false;
609         Module::PrepareForFunctionNameLookup (name,
610                                               name_type_mask,
611                                               lookup_name,
612                                               lookup_name_type_mask,
613                                               match_name_after_lookup);
614 
615         if (symbols)
616             symbols->FindFunctions(lookup_name,
617                                    namespace_decl,
618                                    lookup_name_type_mask,
619                                    include_inlines,
620                                    append,
621                                    sc_list);
622 
623         // Now check our symbol table for symbols that are code symbols if requested
624         if (include_symbols)
625         {
626             ObjectFile *objfile = GetObjectFile();
627             if (objfile)
628             {
629                 Symtab *symtab = objfile->GetSymtab();
630                 if (symtab)
631                     symtab->FindFunctionSymbols(lookup_name, lookup_name_type_mask, sc_list);
632             }
633         }
634 
635         if (match_name_after_lookup)
636         {
637             SymbolContext sc;
638             size_t i = old_size;
639             while (i<sc_list.GetSize())
640             {
641                 if (sc_list.GetContextAtIndex(i, sc))
642                 {
643                     const char *func_name = sc.GetFunctionName().GetCString();
644                     if (func_name && strstr (func_name, name.GetCString()) == NULL)
645                     {
646                         // Remove the current context
647                         sc_list.RemoveContextAtIndex(i);
648                         // Don't increment i and continue in the loop
649                         continue;
650                     }
651                 }
652                 ++i;
653             }
654         }
655 
656     }
657     else
658     {
659         if (symbols)
660             symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
661 
662         // Now check our symbol table for symbols that are code symbols if requested
663         if (include_symbols)
664         {
665             ObjectFile *objfile = GetObjectFile();
666             if (objfile)
667             {
668                 Symtab *symtab = objfile->GetSymtab();
669                 if (symtab)
670                     symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
671             }
672         }
673     }
674 
675     return sc_list.GetSize() - old_size;
676 }
677 
678 size_t
679 Module::FindFunctions (const RegularExpression& regex,
680                        bool include_symbols,
681                        bool include_inlines,
682                        bool append,
683                        SymbolContextList& sc_list)
684 {
685     if (!append)
686         sc_list.Clear();
687 
688     const size_t start_size = sc_list.GetSize();
689 
690     SymbolVendor *symbols = GetSymbolVendor ();
691     if (symbols)
692         symbols->FindFunctions(regex, include_inlines, append, sc_list);
693     // Now check our symbol table for symbols that are code symbols if requested
694     if (include_symbols)
695     {
696         ObjectFile *objfile = GetObjectFile();
697         if (objfile)
698         {
699             Symtab *symtab = objfile->GetSymtab();
700             if (symtab)
701             {
702                 std::vector<uint32_t> symbol_indexes;
703                 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
704                 const size_t num_matches = symbol_indexes.size();
705                 if (num_matches)
706                 {
707                     SymbolContext sc(this);
708                     const size_t end_functions_added_index = sc_list.GetSize();
709                     size_t num_functions_added_to_sc_list = end_functions_added_index - start_size;
710                     if (num_functions_added_to_sc_list == 0)
711                     {
712                         // No functions were added, just symbols, so we can just append them
713                         for (size_t i=0; i<num_matches; ++i)
714                         {
715                             sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
716                             SymbolType sym_type = sc.symbol->GetType();
717                             if (sc.symbol && (sym_type == eSymbolTypeCode ||
718                                               sym_type == eSymbolTypeResolver))
719                                 sc_list.Append(sc);
720                         }
721                     }
722                     else
723                     {
724                         typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
725                         FileAddrToIndexMap file_addr_to_index;
726                         for (size_t i=start_size; i<end_functions_added_index; ++i)
727                         {
728                             const SymbolContext &sc = sc_list[i];
729                             if (sc.block)
730                                 continue;
731                             file_addr_to_index[sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()] = i;
732                         }
733 
734                         FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
735                         // Functions were added so we need to merge symbols into any
736                         // existing function symbol contexts
737                         for (size_t i=start_size; i<num_matches; ++i)
738                         {
739                             sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
740                             SymbolType sym_type = sc.symbol->GetType();
741                             if (sc.symbol && (sym_type == eSymbolTypeCode ||
742                                               sym_type == eSymbolTypeResolver))
743                             {
744                                 FileAddrToIndexMap::const_iterator pos = file_addr_to_index.find(sc.symbol->GetAddress().GetFileAddress());
745                                 if (pos == end)
746                                     sc_list.Append(sc);
747                                 else
748                                     sc_list[pos->second].symbol = sc.symbol;
749                             }
750                         }
751                     }
752                 }
753             }
754         }
755     }
756     return sc_list.GetSize() - start_size;
757 }
758 
759 size_t
760 Module::FindTypes_Impl (const SymbolContext& sc,
761                         const ConstString &name,
762                         const ClangNamespaceDecl *namespace_decl,
763                         bool append,
764                         size_t max_matches,
765                         TypeList& types)
766 {
767     Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
768     if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
769     {
770         SymbolVendor *symbols = GetSymbolVendor ();
771         if (symbols)
772             return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
773     }
774     return 0;
775 }
776 
777 size_t
778 Module::FindTypesInNamespace (const SymbolContext& sc,
779                               const ConstString &type_name,
780                               const ClangNamespaceDecl *namespace_decl,
781                               size_t max_matches,
782                               TypeList& type_list)
783 {
784     const bool append = true;
785     return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
786 }
787 
788 lldb::TypeSP
789 Module::FindFirstType (const SymbolContext& sc,
790                        const ConstString &name,
791                        bool exact_match)
792 {
793     TypeList type_list;
794     const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
795     if (num_matches)
796         return type_list.GetTypeAtIndex(0);
797     return TypeSP();
798 }
799 
800 
801 size_t
802 Module::FindTypes (const SymbolContext& sc,
803                    const ConstString &name,
804                    bool exact_match,
805                    size_t max_matches,
806                    TypeList& types)
807 {
808     size_t num_matches = 0;
809     const char *type_name_cstr = name.GetCString();
810     std::string type_scope;
811     std::string type_basename;
812     const bool append = true;
813     TypeClass type_class = eTypeClassAny;
814     if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
815     {
816         // Check if "name" starts with "::" which means the qualified type starts
817         // from the root namespace and implies and exact match. The typenames we
818         // get back from clang do not start with "::" so we need to strip this off
819         // in order to get the qualfied names to match
820 
821         if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
822         {
823             type_scope.erase(0,2);
824             exact_match = true;
825         }
826         ConstString type_basename_const_str (type_basename.c_str());
827         if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
828         {
829             types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
830             num_matches = types.GetSize();
831         }
832     }
833     else
834     {
835         // The type is not in a namespace/class scope, just search for it by basename
836         if (type_class != eTypeClassAny)
837         {
838             // The "type_name_cstr" will have been modified if we have a valid type class
839             // prefix (like "struct", "class", "union", "typedef" etc).
840             num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
841             types.RemoveMismatchedTypes (type_class);
842             num_matches = types.GetSize();
843         }
844         else
845         {
846             num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
847         }
848     }
849 
850     return num_matches;
851 
852 }
853 
854 SymbolVendor*
855 Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
856 {
857     Mutex::Locker locker (m_mutex);
858     if (m_did_load_symbol_vendor == false && can_create)
859     {
860         ObjectFile *obj_file = GetObjectFile ();
861         if (obj_file != NULL)
862         {
863             Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
864             m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
865             m_did_load_symbol_vendor = true;
866         }
867     }
868     return m_symfile_ap.get();
869 }
870 
871 void
872 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
873 {
874     // Container objects whose paths do not specify a file directly can call
875     // this function to correct the file and object names.
876     m_file = file;
877     m_mod_time = file.GetModificationTime();
878     m_object_name = object_name;
879 }
880 
881 const ArchSpec&
882 Module::GetArchitecture () const
883 {
884     return m_arch;
885 }
886 
887 std::string
888 Module::GetSpecificationDescription () const
889 {
890     std::string spec(GetFileSpec().GetPath());
891     if (m_object_name)
892     {
893         spec += '(';
894         spec += m_object_name.GetCString();
895         spec += ')';
896     }
897     return spec;
898 }
899 
900 void
901 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
902 {
903     Mutex::Locker locker (m_mutex);
904 
905     if (level >= eDescriptionLevelFull)
906     {
907         if (m_arch.IsValid())
908             s->Printf("(%s) ", m_arch.GetArchitectureName());
909     }
910 
911     if (level == eDescriptionLevelBrief)
912     {
913         const char *filename = m_file.GetFilename().GetCString();
914         if (filename)
915             s->PutCString (filename);
916     }
917     else
918     {
919         char path[PATH_MAX];
920         if (m_file.GetPath(path, sizeof(path)))
921             s->PutCString(path);
922     }
923 
924     const char *object_name = m_object_name.GetCString();
925     if (object_name)
926         s->Printf("(%s)", object_name);
927 }
928 
929 void
930 Module::ReportError (const char *format, ...)
931 {
932     if (format && format[0])
933     {
934         StreamString strm;
935         strm.PutCString("error: ");
936         GetDescription(&strm, lldb::eDescriptionLevelBrief);
937         strm.PutChar (' ');
938         va_list args;
939         va_start (args, format);
940         strm.PrintfVarArg(format, args);
941         va_end (args);
942 
943         const int format_len = strlen(format);
944         if (format_len > 0)
945         {
946             const char last_char = format[format_len-1];
947             if (last_char != '\n' || last_char != '\r')
948                 strm.EOL();
949         }
950         Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
951 
952     }
953 }
954 
955 bool
956 Module::FileHasChanged () const
957 {
958     if (m_file_has_changed == false)
959         m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
960     return m_file_has_changed;
961 }
962 
963 void
964 Module::ReportErrorIfModifyDetected (const char *format, ...)
965 {
966     if (m_first_file_changed_log == false)
967     {
968         if (FileHasChanged ())
969         {
970             m_first_file_changed_log = true;
971             if (format)
972             {
973                 StreamString strm;
974                 strm.PutCString("error: the object file ");
975                 GetDescription(&strm, lldb::eDescriptionLevelFull);
976                 strm.PutCString (" has been modified\n");
977 
978                 va_list args;
979                 va_start (args, format);
980                 strm.PrintfVarArg(format, args);
981                 va_end (args);
982 
983                 const int format_len = strlen(format);
984                 if (format_len > 0)
985                 {
986                     const char last_char = format[format_len-1];
987                     if (last_char != '\n' || last_char != '\r')
988                         strm.EOL();
989                 }
990                 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
991                 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
992             }
993         }
994     }
995 }
996 
997 void
998 Module::ReportWarning (const char *format, ...)
999 {
1000     if (format && format[0])
1001     {
1002         StreamString strm;
1003         strm.PutCString("warning: ");
1004         GetDescription(&strm, lldb::eDescriptionLevelFull);
1005         strm.PutChar (' ');
1006 
1007         va_list args;
1008         va_start (args, format);
1009         strm.PrintfVarArg(format, args);
1010         va_end (args);
1011 
1012         const int format_len = strlen(format);
1013         if (format_len > 0)
1014         {
1015             const char last_char = format[format_len-1];
1016             if (last_char != '\n' || last_char != '\r')
1017                 strm.EOL();
1018         }
1019         Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
1020     }
1021 }
1022 
1023 void
1024 Module::LogMessage (Log *log, const char *format, ...)
1025 {
1026     if (log)
1027     {
1028         StreamString log_message;
1029         GetDescription(&log_message, lldb::eDescriptionLevelFull);
1030         log_message.PutCString (": ");
1031         va_list args;
1032         va_start (args, format);
1033         log_message.PrintfVarArg (format, args);
1034         va_end (args);
1035         log->PutCString(log_message.GetString().c_str());
1036     }
1037 }
1038 
1039 void
1040 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
1041 {
1042     if (log)
1043     {
1044         StreamString log_message;
1045         GetDescription(&log_message, lldb::eDescriptionLevelFull);
1046         log_message.PutCString (": ");
1047         va_list args;
1048         va_start (args, format);
1049         log_message.PrintfVarArg (format, args);
1050         va_end (args);
1051         if (log->GetVerbose())
1052             Host::Backtrace (log_message, 1024);
1053         log->PutCString(log_message.GetString().c_str());
1054     }
1055 }
1056 
1057 void
1058 Module::Dump(Stream *s)
1059 {
1060     Mutex::Locker locker (m_mutex);
1061     //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1062     s->Indent();
1063     s->Printf("Module %s%s%s%s\n",
1064               m_file.GetPath().c_str(),
1065               m_object_name ? "(" : "",
1066               m_object_name ? m_object_name.GetCString() : "",
1067               m_object_name ? ")" : "");
1068 
1069     s->IndentMore();
1070     ObjectFile *objfile = GetObjectFile ();
1071 
1072     if (objfile)
1073         objfile->Dump(s);
1074 
1075     SymbolVendor *symbols = GetSymbolVendor ();
1076 
1077     if (symbols)
1078         symbols->Dump(s);
1079 
1080     s->IndentLess();
1081 }
1082 
1083 
1084 TypeList*
1085 Module::GetTypeList ()
1086 {
1087     SymbolVendor *symbols = GetSymbolVendor ();
1088     if (symbols)
1089         return &symbols->GetTypeList();
1090     return NULL;
1091 }
1092 
1093 const ConstString &
1094 Module::GetObjectName() const
1095 {
1096     return m_object_name;
1097 }
1098 
1099 ObjectFile *
1100 Module::GetObjectFile()
1101 {
1102     Mutex::Locker locker (m_mutex);
1103     if (m_did_load_objfile == false)
1104     {
1105         m_did_load_objfile = true;
1106         Timer scoped_timer(__PRETTY_FUNCTION__,
1107                            "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1108         DataBufferSP data_sp;
1109         lldb::offset_t data_offset = 0;
1110         m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1111                                                &m_file,
1112                                                m_object_offset,
1113                                                m_file.GetByteSize(),
1114                                                data_sp,
1115                                                data_offset);
1116         if (m_objfile_sp)
1117         {
1118 			// Once we get the object file, update our module with the object file's
1119 			// architecture since it might differ in vendor/os if some parts were
1120 			// unknown.
1121             m_objfile_sp->GetArchitecture (m_arch);
1122         }
1123     }
1124     return m_objfile_sp.get();
1125 }
1126 
1127 
1128 const Symbol *
1129 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1130 {
1131     Timer scoped_timer(__PRETTY_FUNCTION__,
1132                        "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1133                        name.AsCString(),
1134                        symbol_type);
1135     ObjectFile *objfile = GetObjectFile();
1136     if (objfile)
1137     {
1138         Symtab *symtab = objfile->GetSymtab();
1139         if (symtab)
1140             return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1141     }
1142     return NULL;
1143 }
1144 void
1145 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1146 {
1147     // No need to protect this call using m_mutex all other method calls are
1148     // already thread safe.
1149 
1150     size_t num_indices = symbol_indexes.size();
1151     if (num_indices > 0)
1152     {
1153         SymbolContext sc;
1154         CalculateSymbolContext (&sc);
1155         for (size_t i = 0; i < num_indices; i++)
1156         {
1157             sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1158             if (sc.symbol)
1159                 sc_list.Append (sc);
1160         }
1161     }
1162 }
1163 
1164 size_t
1165 Module::FindFunctionSymbols (const ConstString &name,
1166                              uint32_t name_type_mask,
1167                              SymbolContextList& sc_list)
1168 {
1169     Timer scoped_timer(__PRETTY_FUNCTION__,
1170                        "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1171                        name.AsCString(),
1172                        name_type_mask);
1173     ObjectFile *objfile = GetObjectFile ();
1174     if (objfile)
1175     {
1176         Symtab *symtab = objfile->GetSymtab();
1177         if (symtab)
1178             return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1179     }
1180     return 0;
1181 }
1182 
1183 size_t
1184 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1185 {
1186     // No need to protect this call using m_mutex all other method calls are
1187     // already thread safe.
1188 
1189 
1190     Timer scoped_timer(__PRETTY_FUNCTION__,
1191                        "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1192                        name.AsCString(),
1193                        symbol_type);
1194     const size_t initial_size = sc_list.GetSize();
1195     ObjectFile *objfile = GetObjectFile ();
1196     if (objfile)
1197     {
1198         Symtab *symtab = objfile->GetSymtab();
1199         if (symtab)
1200         {
1201             std::vector<uint32_t> symbol_indexes;
1202             symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1203             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1204         }
1205     }
1206     return sc_list.GetSize() - initial_size;
1207 }
1208 
1209 size_t
1210 Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1211 {
1212     // No need to protect this call using m_mutex all other method calls are
1213     // already thread safe.
1214 
1215     Timer scoped_timer(__PRETTY_FUNCTION__,
1216                        "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1217                        regex.GetText(),
1218                        symbol_type);
1219     const size_t initial_size = sc_list.GetSize();
1220     ObjectFile *objfile = GetObjectFile ();
1221     if (objfile)
1222     {
1223         Symtab *symtab = objfile->GetSymtab();
1224         if (symtab)
1225         {
1226             std::vector<uint32_t> symbol_indexes;
1227             symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1228             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1229         }
1230     }
1231     return sc_list.GetSize() - initial_size;
1232 }
1233 
1234 void
1235 Module::SetSymbolFileFileSpec (const FileSpec &file)
1236 {
1237     m_symfile_spec = file;
1238     m_symfile_ap.reset();
1239     m_did_load_symbol_vendor = false;
1240 }
1241 
1242 
1243 bool
1244 Module::IsExecutable ()
1245 {
1246     if (GetObjectFile() == NULL)
1247         return false;
1248     else
1249         return GetObjectFile()->IsExecutable();
1250 }
1251 
1252 bool
1253 Module::IsLoadedInTarget (Target *target)
1254 {
1255     ObjectFile *obj_file = GetObjectFile();
1256     if (obj_file)
1257     {
1258         SectionList *sections = obj_file->GetSectionList();
1259         if (sections != NULL)
1260         {
1261             size_t num_sections = sections->GetSize();
1262             for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1263             {
1264                 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1265                 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1266                 {
1267                     return true;
1268                 }
1269             }
1270         }
1271     }
1272     return false;
1273 }
1274 
1275 bool
1276 Module::LoadScriptingResourceInTarget (Target *target, Error& error, Stream* feedback_stream)
1277 {
1278     if (!target)
1279     {
1280         error.SetErrorString("invalid destination Target");
1281         return false;
1282     }
1283 
1284     LoadScriptFromSymFile shoud_load = target->TargetProperties::GetLoadScriptFromSymbolFile();
1285 
1286     Debugger &debugger = target->GetDebugger();
1287     const ScriptLanguage script_language = debugger.GetScriptLanguage();
1288     if (script_language != eScriptLanguageNone)
1289     {
1290 
1291         PlatformSP platform_sp(target->GetPlatform());
1292 
1293         if (!platform_sp)
1294         {
1295             error.SetErrorString("invalid Platform");
1296             return false;
1297         }
1298 
1299         FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1300                                                                                    *this);
1301 
1302 
1303         const uint32_t num_specs = file_specs.GetSize();
1304         if (num_specs)
1305         {
1306             ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1307             if (script_interpreter)
1308             {
1309                 for (uint32_t i=0; i<num_specs; ++i)
1310                 {
1311                     FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1312                     if (scripting_fspec && scripting_fspec.Exists())
1313                     {
1314                         if (shoud_load == eLoadScriptFromSymFileFalse)
1315                             return false;
1316                         if (shoud_load == eLoadScriptFromSymFileWarn)
1317                         {
1318                             if (feedback_stream)
1319                                 feedback_stream->Printf("warning: '%s' contains a debug script. To run this script in this debug session:\n\n    command script import \"%s\"\n\nTo run all discovered debug scripts in this session:\n\n    settings set target.load-script-from-symbol-file true\n"
1320                                                         ,GetFileSpec().GetFileNameStrippingExtension().GetCString(),scripting_fspec.GetPath().c_str());
1321                             return false;
1322                         }
1323                         StreamString scripting_stream;
1324                         scripting_fspec.Dump(&scripting_stream);
1325                         const bool can_reload = true;
1326                         const bool init_lldb_globals = false;
1327                         bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(), can_reload, init_lldb_globals, error);
1328                         if (!did_load)
1329                             return false;
1330                     }
1331                 }
1332             }
1333             else
1334             {
1335                 error.SetErrorString("invalid ScriptInterpreter");
1336                 return false;
1337             }
1338         }
1339     }
1340     return true;
1341 }
1342 
1343 bool
1344 Module::SetArchitecture (const ArchSpec &new_arch)
1345 {
1346     if (!m_arch.IsValid())
1347     {
1348         m_arch = new_arch;
1349         return true;
1350     }
1351     return m_arch.IsExactMatch(new_arch);
1352 }
1353 
1354 bool
1355 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1356 {
1357     size_t num_loaded_sections = 0;
1358     ObjectFile *objfile = GetObjectFile();
1359     if (objfile)
1360     {
1361         SectionList *section_list = objfile->GetSectionList ();
1362         if (section_list)
1363         {
1364             const size_t num_sections = section_list->GetSize();
1365             size_t sect_idx = 0;
1366             for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1367             {
1368                 // Iterate through the object file sections to find the
1369                 // first section that starts of file offset zero and that
1370                 // has bytes in the file...
1371                 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1372                 // Only load non-thread specific sections when given a slide
1373                 if (section_sp && !section_sp->IsThreadSpecific())
1374                 {
1375                     if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1376                         ++num_loaded_sections;
1377                 }
1378             }
1379         }
1380     }
1381     changed = num_loaded_sections > 0;
1382     return num_loaded_sections > 0;
1383 }
1384 
1385 
1386 bool
1387 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1388 {
1389     const UUID &uuid = module_ref.GetUUID();
1390 
1391     if (uuid.IsValid())
1392     {
1393         // If the UUID matches, then nothing more needs to match...
1394         if (uuid == GetUUID())
1395             return true;
1396         else
1397             return false;
1398     }
1399 
1400     const FileSpec &file_spec = module_ref.GetFileSpec();
1401     if (file_spec)
1402     {
1403         if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1404             return false;
1405     }
1406 
1407     const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1408     if (platform_file_spec)
1409     {
1410         if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), platform_file_spec.GetDirectory()))
1411             return false;
1412     }
1413 
1414     const ArchSpec &arch = module_ref.GetArchitecture();
1415     if (arch.IsValid())
1416     {
1417         if (!m_arch.IsCompatibleMatch(arch))
1418             return false;
1419     }
1420 
1421     const ConstString &object_name = module_ref.GetObjectName();
1422     if (object_name)
1423     {
1424         if (object_name != GetObjectName())
1425             return false;
1426     }
1427     return true;
1428 }
1429 
1430 bool
1431 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1432 {
1433     Mutex::Locker locker (m_mutex);
1434     return m_source_mappings.FindFile (orig_spec, new_spec);
1435 }
1436 
1437 bool
1438 Module::RemapSourceFile (const char *path, std::string &new_path) const
1439 {
1440     Mutex::Locker locker (m_mutex);
1441     return m_source_mappings.RemapPath(path, new_path);
1442 }
1443 
1444 uint32_t
1445 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1446 {
1447     ObjectFile *obj_file = GetObjectFile();
1448     if (obj_file)
1449         return obj_file->GetVersion (versions, num_versions);
1450 
1451     if (versions && num_versions)
1452     {
1453         for (uint32_t i=0; i<num_versions; ++i)
1454             versions[i] = UINT32_MAX;
1455     }
1456     return 0;
1457 }
1458 
1459 void
1460 Module::PrepareForFunctionNameLookup (const ConstString &name,
1461                                       uint32_t name_type_mask,
1462                                       ConstString &lookup_name,
1463                                       uint32_t &lookup_name_type_mask,
1464                                       bool &match_name_after_lookup)
1465 {
1466     const char *name_cstr = name.GetCString();
1467     lookup_name_type_mask = eFunctionNameTypeNone;
1468     match_name_after_lookup = false;
1469     const char *base_name_start = NULL;
1470     const char *base_name_end = NULL;
1471 
1472     if (name_type_mask & eFunctionNameTypeAuto)
1473     {
1474         if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
1475             lookup_name_type_mask = eFunctionNameTypeFull;
1476         else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
1477             lookup_name_type_mask = eFunctionNameTypeFull;
1478         else
1479         {
1480             if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1481                 lookup_name_type_mask |= eFunctionNameTypeSelector;
1482 
1483             CPPLanguageRuntime::MethodName cpp_method (name);
1484             llvm::StringRef basename (cpp_method.GetBasename());
1485             if (basename.empty())
1486             {
1487                 if (CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1488                     lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1489             }
1490             else
1491             {
1492                 base_name_start = basename.data();
1493                 base_name_end = base_name_start + basename.size();
1494                 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1495             }
1496         }
1497     }
1498     else
1499     {
1500         lookup_name_type_mask = name_type_mask;
1501         if (lookup_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
1502         {
1503             // If they've asked for a CPP method or function name and it can't be that, we don't
1504             // even need to search for CPP methods or names.
1505             CPPLanguageRuntime::MethodName cpp_method (name);
1506             if (cpp_method.IsValid())
1507             {
1508                 llvm::StringRef basename (cpp_method.GetBasename());
1509                 base_name_start = basename.data();
1510                 base_name_end = base_name_start + basename.size();
1511 
1512                 if (!cpp_method.GetQualifiers().empty())
1513                 {
1514                     // There is a "const" or other qualifer following the end of the fucntion parens,
1515                     // this can't be a eFunctionNameTypeBase
1516                     lookup_name_type_mask &= ~(eFunctionNameTypeBase);
1517                     if (lookup_name_type_mask == eFunctionNameTypeNone)
1518                         return;
1519                 }
1520             }
1521             else
1522             {
1523                 if (!CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1524                 {
1525                     lookup_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
1526                     if (lookup_name_type_mask == eFunctionNameTypeNone)
1527                         return;
1528                 }
1529             }
1530         }
1531 
1532         if (lookup_name_type_mask & eFunctionNameTypeSelector)
1533         {
1534             if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1535             {
1536                 lookup_name_type_mask &= ~(eFunctionNameTypeSelector);
1537                 if (lookup_name_type_mask == eFunctionNameTypeNone)
1538                     return;
1539             }
1540         }
1541     }
1542 
1543     if (base_name_start &&
1544         base_name_end &&
1545         base_name_start != name_cstr &&
1546         base_name_start < base_name_end)
1547     {
1548         // The name supplied was a partial C++ path like "a::count". In this case we want to do a
1549         // lookup on the basename "count" and then make sure any matching results contain "a::count"
1550         // so that it would match "b::a::count" and "a::count". This is why we set "match_name_after_lookup"
1551         // to true
1552         lookup_name.SetCStringWithLength(base_name_start, base_name_end - base_name_start);
1553         match_name_after_lookup = true;
1554     }
1555     else
1556     {
1557         // The name is already correct, just use the exact name as supplied, and we won't need
1558         // to check if any matches contain "name"
1559         lookup_name = name;
1560         match_name_after_lookup = false;
1561     }
1562 }