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/Core/Module.h"
11 #include "lldb/Core/DataBuffer.h"
12 #include "lldb/Core/DataBufferHeap.h"
13 #include "lldb/Core/Log.h"
14 #include "lldb/Core/ModuleList.h"
15 #include "lldb/Core/RegularExpression.h"
16 #include "lldb/Core/StreamString.h"
17 #include "lldb/Core/Timer.h"
18 #include "lldb/Host/Host.h"
19 #include "lldb/lldb-private-log.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/SymbolContext.h"
22 #include "lldb/Symbol/SymbolVendor.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/Target.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 // Shared pointers to modules track module lifetimes in
30 // targets and in the global module, but this collection
31 // will track all module objects that are still alive
32 typedef std::vector<Module *> ModuleCollection;
33 
34 static ModuleCollection &
35 GetModuleCollection()
36 {
37     // This module collection needs to live past any module, so we could either make it a
38     // shared pointer in each module or just leak is.  Since it is only an empty vector by
39     // the time all the modules have gone away, we just leak it for now.  If we decide this
40     // is a big problem we can introduce a Finalize method that will tear everything down in
41     // a predictable order.
42 
43     static ModuleCollection *g_module_collection = NULL;
44     if (g_module_collection == NULL)
45         g_module_collection = new ModuleCollection();
46 
47     return *g_module_collection;
48 }
49 
50 Mutex *
51 Module::GetAllocationModuleCollectionMutex()
52 {
53     // NOTE: The mutex below must be leaked since the global module list in
54     // the ModuleList class will get torn at some point, and we can't know
55     // if it will tear itself down before the "g_module_collection_mutex" below
56     // will. So we leak a Mutex object below to safeguard against that
57 
58     static Mutex *g_module_collection_mutex = NULL;
59     if (g_module_collection_mutex == NULL)
60         g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
61     return g_module_collection_mutex;
62 }
63 
64 size_t
65 Module::GetNumberAllocatedModules ()
66 {
67     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
68     return GetModuleCollection().size();
69 }
70 
71 Module *
72 Module::GetAllocatedModuleAtIndex (size_t idx)
73 {
74     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
75     ModuleCollection &modules = GetModuleCollection();
76     if (idx < modules.size())
77         return modules[idx];
78     return NULL;
79 }
80 #if 0
81 
82 // These functions help us to determine if modules are still loaded, yet don't require that
83 // you have a command interpreter and can easily be called from an external debugger.
84 namespace lldb {
85 
86     void
87     ClearModuleInfo (void)
88     {
89         const bool mandatory = true;
90         ModuleList::RemoveOrphanSharedModules(mandatory);
91     }
92 
93     void
94     DumpModuleInfo (void)
95     {
96         Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
97         ModuleCollection &modules = GetModuleCollection();
98         const size_t count = modules.size();
99         printf ("%s: %zu modules:\n", __PRETTY_FUNCTION__, count);
100         for (size_t i=0; i<count; ++i)
101         {
102 
103             StreamString strm;
104             Module *module = modules[i];
105             const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
106             module->GetDescription(&strm, eDescriptionLevelFull);
107             printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
108                     module,
109                     in_shared_module_list,
110                     (uint32_t)module->use_count(),
111                     strm.GetString().c_str());
112         }
113     }
114 }
115 
116 #endif
117 
118 Module::Module (const ModuleSpec &module_spec) :
119     m_mutex (Mutex::eMutexTypeRecursive),
120     m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
121     m_arch (module_spec.GetArchitecture()),
122     m_uuid (),
123     m_file (module_spec.GetFileSpec()),
124     m_platform_file(module_spec.GetPlatformFileSpec()),
125     m_symfile_spec (module_spec.GetSymbolFileSpec()),
126     m_object_name (module_spec.GetObjectName()),
127     m_object_offset (module_spec.GetObjectOffset()),
128     m_objfile_sp (),
129     m_symfile_ap (),
130     m_ast (),
131     m_source_mappings (),
132     m_did_load_objfile (false),
133     m_did_load_symbol_vendor (false),
134     m_did_parse_uuid (false),
135     m_did_init_ast (false),
136     m_is_dynamic_loader_module (false),
137     m_file_has_changed (false),
138     m_first_file_changed_log (false)
139 {
140     // Scope for locker below...
141     {
142         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
143         GetModuleCollection().push_back(this);
144     }
145 
146     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
147     if (log)
148         log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
149                      this,
150                      m_arch.GetArchitectureName(),
151                      m_file.GetDirectory().AsCString(""),
152                      m_file.GetFilename().AsCString(""),
153                      m_object_name.IsEmpty() ? "" : "(",
154                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
155                      m_object_name.IsEmpty() ? "" : ")");
156 }
157 
158 Module::Module(const FileSpec& file_spec,
159                const ArchSpec& arch,
160                const ConstString *object_name,
161                off_t object_offset) :
162     m_mutex (Mutex::eMutexTypeRecursive),
163     m_mod_time (file_spec.GetModificationTime()),
164     m_arch (arch),
165     m_uuid (),
166     m_file (file_spec),
167     m_platform_file(),
168     m_symfile_spec (),
169     m_object_name (),
170     m_object_offset (object_offset),
171     m_objfile_sp (),
172     m_symfile_ap (),
173     m_ast (),
174     m_source_mappings (),
175     m_did_load_objfile (false),
176     m_did_load_symbol_vendor (false),
177     m_did_parse_uuid (false),
178     m_did_init_ast (false),
179     m_is_dynamic_loader_module (false),
180     m_file_has_changed (false),
181     m_first_file_changed_log (false)
182 {
183     // Scope for locker below...
184     {
185         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
186         GetModuleCollection().push_back(this);
187     }
188 
189     if (object_name)
190         m_object_name = *object_name;
191     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
192     if (log)
193         log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
194                      this,
195                      m_arch.GetArchitectureName(),
196                      m_file.GetDirectory().AsCString(""),
197                      m_file.GetFilename().AsCString(""),
198                      m_object_name.IsEmpty() ? "" : "(",
199                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
200                      m_object_name.IsEmpty() ? "" : ")");
201 }
202 
203 Module::~Module()
204 {
205     // Scope for locker below...
206     {
207         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
208         ModuleCollection &modules = GetModuleCollection();
209         ModuleCollection::iterator end = modules.end();
210         ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
211         if (pos != end)
212             modules.erase(pos);
213     }
214     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
215     if (log)
216         log->Printf ("%p Module::~Module((%s) '%s/%s%s%s%s')",
217                      this,
218                      m_arch.GetArchitectureName(),
219                      m_file.GetDirectory().AsCString(""),
220                      m_file.GetFilename().AsCString(""),
221                      m_object_name.IsEmpty() ? "" : "(",
222                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
223                      m_object_name.IsEmpty() ? "" : ")");
224     // Release any auto pointers before we start tearing down our member
225     // variables since the object file and symbol files might need to make
226     // function calls back into this module object. The ordering is important
227     // here because symbol files can require the module object file. So we tear
228     // down the symbol file first, then the object file.
229     m_symfile_ap.reset();
230     m_objfile_sp.reset();
231 }
232 
233 ObjectFile *
234 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
235 {
236     if (m_objfile_sp)
237     {
238         error.SetErrorString ("object file already exists");
239     }
240     else
241     {
242         Mutex::Locker locker (m_mutex);
243         if (process_sp)
244         {
245             m_did_load_objfile = true;
246             std::auto_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
247             Error readmem_error;
248             const size_t bytes_read = process_sp->ReadMemory (header_addr,
249                                                               data_ap->GetBytes(),
250                                                               data_ap->GetByteSize(),
251                                                               readmem_error);
252             if (bytes_read == 512)
253             {
254                 DataBufferSP data_sp(data_ap.release());
255                 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
256                 if (m_objfile_sp)
257                 {
258                     StreamString s;
259                     s.Printf("0x%16.16llx", header_addr);
260                     m_object_name.SetCString (s.GetData());
261 
262                     // Once we get the object file, update our module with the object file's
263                     // architecture since it might differ in vendor/os if some parts were
264                     // unknown.
265                     m_objfile_sp->GetArchitecture (m_arch);
266                 }
267                 else
268                 {
269                     error.SetErrorString ("unable to find suitable object file plug-in");
270                 }
271             }
272             else
273             {
274                 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
275             }
276         }
277         else
278         {
279             error.SetErrorString ("invalid process");
280         }
281     }
282     return m_objfile_sp.get();
283 }
284 
285 
286 const lldb_private::UUID&
287 Module::GetUUID()
288 {
289     Mutex::Locker locker (m_mutex);
290     if (m_did_parse_uuid == false)
291     {
292         ObjectFile * obj_file = GetObjectFile ();
293 
294         if (obj_file != NULL)
295         {
296             obj_file->GetUUID(&m_uuid);
297             m_did_parse_uuid = true;
298         }
299     }
300     return m_uuid;
301 }
302 
303 ClangASTContext &
304 Module::GetClangASTContext ()
305 {
306     Mutex::Locker locker (m_mutex);
307     if (m_did_init_ast == false)
308     {
309         ObjectFile * objfile = GetObjectFile();
310         ArchSpec object_arch;
311         if (objfile && objfile->GetArchitecture(object_arch))
312         {
313             m_did_init_ast = true;
314             m_ast.SetArchitecture (object_arch);
315         }
316     }
317     return m_ast;
318 }
319 
320 void
321 Module::ParseAllDebugSymbols()
322 {
323     Mutex::Locker locker (m_mutex);
324     uint32_t num_comp_units = GetNumCompileUnits();
325     if (num_comp_units == 0)
326         return;
327 
328     SymbolContext sc;
329     sc.module_sp = shared_from_this();
330     uint32_t cu_idx;
331     SymbolVendor *symbols = GetSymbolVendor ();
332 
333     for (cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
334     {
335         sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
336         if (sc.comp_unit)
337         {
338             sc.function = NULL;
339             symbols->ParseVariablesForContext(sc);
340 
341             symbols->ParseCompileUnitFunctions(sc);
342 
343             uint32_t func_idx;
344             for (func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
345             {
346                 symbols->ParseFunctionBlocks(sc);
347 
348                 // Parse the variables for this function and all its blocks
349                 symbols->ParseVariablesForContext(sc);
350             }
351 
352 
353             // Parse all types for this compile unit
354             sc.function = NULL;
355             symbols->ParseTypes(sc);
356         }
357     }
358 }
359 
360 void
361 Module::CalculateSymbolContext(SymbolContext* sc)
362 {
363     sc->module_sp = shared_from_this();
364 }
365 
366 ModuleSP
367 Module::CalculateSymbolContextModule ()
368 {
369     return shared_from_this();
370 }
371 
372 void
373 Module::DumpSymbolContext(Stream *s)
374 {
375     s->Printf(", Module{%p}", this);
376 }
377 
378 uint32_t
379 Module::GetNumCompileUnits()
380 {
381     Mutex::Locker locker (m_mutex);
382     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
383     SymbolVendor *symbols = GetSymbolVendor ();
384     if (symbols)
385         return symbols->GetNumCompileUnits();
386     return 0;
387 }
388 
389 CompUnitSP
390 Module::GetCompileUnitAtIndex (uint32_t index)
391 {
392     Mutex::Locker locker (m_mutex);
393     uint32_t num_comp_units = GetNumCompileUnits ();
394     CompUnitSP cu_sp;
395 
396     if (index < num_comp_units)
397     {
398         SymbolVendor *symbols = GetSymbolVendor ();
399         if (symbols)
400             cu_sp = symbols->GetCompileUnitAtIndex(index);
401     }
402     return cu_sp;
403 }
404 
405 bool
406 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
407 {
408     Mutex::Locker locker (m_mutex);
409     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%llx)", vm_addr);
410     ObjectFile* ofile = GetObjectFile();
411     if (ofile)
412         return so_addr.ResolveAddressUsingFileSections(vm_addr, ofile->GetSectionList());
413     return false;
414 }
415 
416 uint32_t
417 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
418 {
419     Mutex::Locker locker (m_mutex);
420     uint32_t resolved_flags = 0;
421 
422     // Clear the result symbol context in case we don't find anything
423     sc.Clear();
424 
425     // Get the section from the section/offset address.
426     SectionSP section_sp (so_addr.GetSection());
427 
428     // Make sure the section matches this module before we try and match anything
429     if (section_sp && section_sp->GetModule().get() == this)
430     {
431         // If the section offset based address resolved itself, then this
432         // is the right module.
433         sc.module_sp = shared_from_this();
434         resolved_flags |= eSymbolContextModule;
435 
436         // Resolve the compile unit, function, block, line table or line
437         // entry if requested.
438         if (resolve_scope & eSymbolContextCompUnit    ||
439             resolve_scope & eSymbolContextFunction    ||
440             resolve_scope & eSymbolContextBlock       ||
441             resolve_scope & eSymbolContextLineEntry   )
442         {
443             SymbolVendor *symbols = GetSymbolVendor ();
444             if (symbols)
445                 resolved_flags |= symbols->ResolveSymbolContext (so_addr, resolve_scope, sc);
446         }
447 
448         // Resolve the symbol if requested, but don't re-look it up if we've already found it.
449         if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
450         {
451             ObjectFile* ofile = GetObjectFile();
452             if (ofile)
453             {
454                 Symtab *symtab = ofile->GetSymtab();
455                 if (symtab)
456                 {
457                     if (so_addr.IsSectionOffset())
458                     {
459                         sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
460                         if (sc.symbol)
461                             resolved_flags |= eSymbolContextSymbol;
462                     }
463                 }
464             }
465         }
466     }
467     return resolved_flags;
468 }
469 
470 uint32_t
471 Module::ResolveSymbolContextForFilePath
472 (
473     const char *file_path,
474     uint32_t line,
475     bool check_inlines,
476     uint32_t resolve_scope,
477     SymbolContextList& sc_list
478 )
479 {
480     FileSpec file_spec(file_path, false);
481     return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
482 }
483 
484 uint32_t
485 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
486 {
487     Mutex::Locker locker (m_mutex);
488     Timer scoped_timer(__PRETTY_FUNCTION__,
489                        "Module::ResolveSymbolContextForFilePath (%s%s%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
490                        file_spec.GetDirectory().AsCString(""),
491                        file_spec.GetDirectory() ? "/" : "",
492                        file_spec.GetFilename().AsCString(""),
493                        line,
494                        check_inlines ? "yes" : "no",
495                        resolve_scope);
496 
497     const uint32_t initial_count = sc_list.GetSize();
498 
499     SymbolVendor *symbols = GetSymbolVendor  ();
500     if (symbols)
501         symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
502 
503     return sc_list.GetSize() - initial_count;
504 }
505 
506 
507 uint32_t
508 Module::FindGlobalVariables(const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
509 {
510     SymbolVendor *symbols = GetSymbolVendor ();
511     if (symbols)
512         return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
513     return 0;
514 }
515 uint32_t
516 Module::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
517 {
518     SymbolVendor *symbols = GetSymbolVendor ();
519     if (symbols)
520         return symbols->FindGlobalVariables(regex, append, max_matches, variables);
521     return 0;
522 }
523 
524 uint32_t
525 Module::FindCompileUnits (const FileSpec &path,
526                           bool append,
527                           SymbolContextList &sc_list)
528 {
529     if (!append)
530         sc_list.Clear();
531 
532     const uint32_t start_size = sc_list.GetSize();
533     const uint32_t num_compile_units = GetNumCompileUnits();
534     SymbolContext sc;
535     sc.module_sp = shared_from_this();
536     const bool compare_directory = path.GetDirectory();
537     for (uint32_t i=0; i<num_compile_units; ++i)
538     {
539         sc.comp_unit = GetCompileUnitAtIndex(i).get();
540         if (sc.comp_unit)
541         {
542             if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
543                 sc_list.Append(sc);
544         }
545     }
546     return sc_list.GetSize() - start_size;
547 }
548 
549 uint32_t
550 Module::FindFunctions (const ConstString &name,
551                        const ClangNamespaceDecl *namespace_decl,
552                        uint32_t name_type_mask,
553                        bool include_symbols,
554                        bool include_inlines,
555                        bool append,
556                        SymbolContextList& sc_list)
557 {
558     if (!append)
559         sc_list.Clear();
560 
561     const uint32_t start_size = sc_list.GetSize();
562 
563     // Find all the functions (not symbols, but debug information functions...
564     SymbolVendor *symbols = GetSymbolVendor ();
565     if (symbols)
566         symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
567 
568     // Now check our symbol table for symbols that are code symbols if requested
569     if (include_symbols)
570     {
571         ObjectFile *objfile = GetObjectFile();
572         if (objfile)
573         {
574             Symtab *symtab = objfile->GetSymtab();
575             if (symtab)
576             {
577                 std::vector<uint32_t> symbol_indexes;
578                 symtab->FindAllSymbolsWithNameAndType (name, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
579                 const uint32_t num_matches = symbol_indexes.size();
580                 if (num_matches)
581                 {
582                     const bool merge_symbol_into_function = true;
583                     SymbolContext sc(this);
584                     for (uint32_t i=0; i<num_matches; i++)
585                     {
586                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
587                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
588                     }
589                 }
590             }
591         }
592     }
593     return sc_list.GetSize() - start_size;
594 }
595 
596 uint32_t
597 Module::FindFunctions (const RegularExpression& regex,
598                        bool include_symbols,
599                        bool include_inlines,
600                        bool append,
601                        SymbolContextList& sc_list)
602 {
603     if (!append)
604         sc_list.Clear();
605 
606     const uint32_t start_size = sc_list.GetSize();
607 
608     SymbolVendor *symbols = GetSymbolVendor ();
609     if (symbols)
610         symbols->FindFunctions(regex, include_inlines, append, sc_list);
611     // Now check our symbol table for symbols that are code symbols if requested
612     if (include_symbols)
613     {
614         ObjectFile *objfile = GetObjectFile();
615         if (objfile)
616         {
617             Symtab *symtab = objfile->GetSymtab();
618             if (symtab)
619             {
620                 std::vector<uint32_t> symbol_indexes;
621                 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
622                 const uint32_t num_matches = symbol_indexes.size();
623                 if (num_matches)
624                 {
625                     const bool merge_symbol_into_function = true;
626                     SymbolContext sc(this);
627                     for (uint32_t i=0; i<num_matches; i++)
628                     {
629                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
630                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
631                     }
632                 }
633             }
634         }
635     }
636     return sc_list.GetSize() - start_size;
637 }
638 
639 uint32_t
640 Module::FindTypes_Impl (const SymbolContext& sc,
641                         const ConstString &name,
642                         const ClangNamespaceDecl *namespace_decl,
643                         bool append,
644                         uint32_t max_matches,
645                         TypeList& types)
646 {
647     Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
648     if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
649     {
650         SymbolVendor *symbols = GetSymbolVendor ();
651         if (symbols)
652             return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
653     }
654     return 0;
655 }
656 
657 uint32_t
658 Module::FindTypesInNamespace (const SymbolContext& sc,
659                               const ConstString &type_name,
660                               const ClangNamespaceDecl *namespace_decl,
661                               uint32_t max_matches,
662                               TypeList& type_list)
663 {
664     const bool append = true;
665     return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
666 }
667 
668 uint32_t
669 Module::FindTypes (const SymbolContext& sc,
670                    const ConstString &name,
671                    bool exact_match,
672                    uint32_t max_matches,
673                    TypeList& types)
674 {
675     uint32_t num_matches = 0;
676     const char *type_name_cstr = name.GetCString();
677     std::string type_scope;
678     std::string type_basename;
679     const bool append = true;
680     if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename))
681     {
682         // Check if "name" starts with "::" which means the qualified type starts
683         // from the root namespace and implies and exact match. The typenames we
684         // get back from clang do not start with "::" so we need to strip this off
685         // in order to get the qualfied names to match
686 
687         if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
688         {
689             type_scope.erase(0,2);
690             exact_match = true;
691         }
692         ConstString type_basename_const_str (type_basename.c_str());
693         if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
694         {
695             types.RemoveMismatchedTypes (type_scope, type_basename, exact_match);
696             num_matches = types.GetSize();
697         }
698     }
699     else
700     {
701         // The type is not in a namespace/class scope, just search for it by basename
702         num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
703     }
704 
705     return num_matches;
706 
707 }
708 
709 //uint32_t
710 //Module::FindTypes(const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, const char *udt_name, TypeList& types)
711 //{
712 //  Timer scoped_timer(__PRETTY_FUNCTION__);
713 //  SymbolVendor *symbols = GetSymbolVendor ();
714 //  if (symbols)
715 //      return symbols->FindTypes(sc, regex, append, max_matches, encoding, udt_name, types);
716 //  return 0;
717 //
718 //}
719 
720 SymbolVendor*
721 Module::GetSymbolVendor (bool can_create)
722 {
723     Mutex::Locker locker (m_mutex);
724     if (m_did_load_symbol_vendor == false && can_create)
725     {
726         ObjectFile *obj_file = GetObjectFile ();
727         if (obj_file != NULL)
728         {
729             Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
730             m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this()));
731             m_did_load_symbol_vendor = true;
732         }
733     }
734     return m_symfile_ap.get();
735 }
736 
737 void
738 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
739 {
740     // Container objects whose paths do not specify a file directly can call
741     // this function to correct the file and object names.
742     m_file = file;
743     m_mod_time = file.GetModificationTime();
744     m_object_name = object_name;
745 }
746 
747 const ArchSpec&
748 Module::GetArchitecture () const
749 {
750     return m_arch;
751 }
752 
753 void
754 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
755 {
756     Mutex::Locker locker (m_mutex);
757 
758     if (level >= eDescriptionLevelFull)
759     {
760         if (m_arch.IsValid())
761             s->Printf("(%s) ", m_arch.GetArchitectureName());
762     }
763 
764     if (level == eDescriptionLevelBrief)
765     {
766         const char *filename = m_file.GetFilename().GetCString();
767         if (filename)
768             s->PutCString (filename);
769     }
770     else
771     {
772         char path[PATH_MAX];
773         if (m_file.GetPath(path, sizeof(path)))
774             s->PutCString(path);
775     }
776 
777     const char *object_name = m_object_name.GetCString();
778     if (object_name)
779         s->Printf("(%s)", object_name);
780 }
781 
782 void
783 Module::ReportError (const char *format, ...)
784 {
785     if (format && format[0])
786     {
787         StreamString strm;
788         strm.PutCString("error: ");
789         GetDescription(&strm, lldb::eDescriptionLevelBrief);
790         strm.PutChar (' ');
791         va_list args;
792         va_start (args, format);
793         strm.PrintfVarArg(format, args);
794         va_end (args);
795 
796         const int format_len = strlen(format);
797         if (format_len > 0)
798         {
799             const char last_char = format[format_len-1];
800             if (last_char != '\n' || last_char != '\r')
801                 strm.EOL();
802         }
803         Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
804 
805     }
806 }
807 
808 bool
809 Module::FileHasChanged () const
810 {
811     if (m_file_has_changed == false)
812         m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
813     return m_file_has_changed;
814 }
815 
816 void
817 Module::ReportErrorIfModifyDetected (const char *format, ...)
818 {
819     if (m_first_file_changed_log == false)
820     {
821         if (FileHasChanged ())
822         {
823             m_first_file_changed_log = true;
824             if (format)
825             {
826                 StreamString strm;
827                 strm.PutCString("error: the object file ");
828                 GetDescription(&strm, lldb::eDescriptionLevelFull);
829                 strm.PutCString (" has been modified\n");
830 
831                 va_list args;
832                 va_start (args, format);
833                 strm.PrintfVarArg(format, args);
834                 va_end (args);
835 
836                 const int format_len = strlen(format);
837                 if (format_len > 0)
838                 {
839                     const char last_char = format[format_len-1];
840                     if (last_char != '\n' || last_char != '\r')
841                         strm.EOL();
842                 }
843                 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
844                 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
845             }
846         }
847     }
848 }
849 
850 void
851 Module::ReportWarning (const char *format, ...)
852 {
853     if (format && format[0])
854     {
855         StreamString strm;
856         strm.PutCString("warning: ");
857         GetDescription(&strm, lldb::eDescriptionLevelFull);
858         strm.PutChar (' ');
859 
860         va_list args;
861         va_start (args, format);
862         strm.PrintfVarArg(format, args);
863         va_end (args);
864 
865         const int format_len = strlen(format);
866         if (format_len > 0)
867         {
868             const char last_char = format[format_len-1];
869             if (last_char != '\n' || last_char != '\r')
870                 strm.EOL();
871         }
872         Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
873     }
874 }
875 
876 void
877 Module::LogMessage (Log *log, const char *format, ...)
878 {
879     if (log)
880     {
881         StreamString log_message;
882         GetDescription(&log_message, lldb::eDescriptionLevelFull);
883         log_message.PutCString (": ");
884         va_list args;
885         va_start (args, format);
886         log_message.PrintfVarArg (format, args);
887         va_end (args);
888         log->PutCString(log_message.GetString().c_str());
889     }
890 }
891 
892 void
893 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
894 {
895     if (log)
896     {
897         StreamString log_message;
898         GetDescription(&log_message, lldb::eDescriptionLevelFull);
899         log_message.PutCString (": ");
900         va_list args;
901         va_start (args, format);
902         log_message.PrintfVarArg (format, args);
903         va_end (args);
904         if (log->GetVerbose())
905             Host::Backtrace (log_message, 1024);
906         log->PutCString(log_message.GetString().c_str());
907     }
908 }
909 
910 void
911 Module::Dump(Stream *s)
912 {
913     Mutex::Locker locker (m_mutex);
914     //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
915     s->Indent();
916     s->Printf("Module %s/%s%s%s%s\n",
917               m_file.GetDirectory().AsCString(),
918               m_file.GetFilename().AsCString(),
919               m_object_name ? "(" : "",
920               m_object_name ? m_object_name.GetCString() : "",
921               m_object_name ? ")" : "");
922 
923     s->IndentMore();
924     ObjectFile *objfile = GetObjectFile ();
925 
926     if (objfile)
927         objfile->Dump(s);
928 
929     SymbolVendor *symbols = GetSymbolVendor ();
930 
931     if (symbols)
932         symbols->Dump(s);
933 
934     s->IndentLess();
935 }
936 
937 
938 TypeList*
939 Module::GetTypeList ()
940 {
941     SymbolVendor *symbols = GetSymbolVendor ();
942     if (symbols)
943         return &symbols->GetTypeList();
944     return NULL;
945 }
946 
947 const ConstString &
948 Module::GetObjectName() const
949 {
950     return m_object_name;
951 }
952 
953 ObjectFile *
954 Module::GetObjectFile()
955 {
956     Mutex::Locker locker (m_mutex);
957     if (m_did_load_objfile == false)
958     {
959         m_did_load_objfile = true;
960         Timer scoped_timer(__PRETTY_FUNCTION__,
961                            "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
962         DataBufferSP file_data_sp;
963         m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
964                                                &m_file,
965                                                m_object_offset,
966                                                m_file.GetByteSize(),
967                                                file_data_sp);
968         if (m_objfile_sp)
969         {
970 			// Once we get the object file, update our module with the object file's
971 			// architecture since it might differ in vendor/os if some parts were
972 			// unknown.
973             m_objfile_sp->GetArchitecture (m_arch);
974         }
975     }
976     return m_objfile_sp.get();
977 }
978 
979 
980 const Symbol *
981 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
982 {
983     Timer scoped_timer(__PRETTY_FUNCTION__,
984                        "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
985                        name.AsCString(),
986                        symbol_type);
987     ObjectFile *objfile = GetObjectFile();
988     if (objfile)
989     {
990         Symtab *symtab = objfile->GetSymtab();
991         if (symtab)
992             return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
993     }
994     return NULL;
995 }
996 void
997 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
998 {
999     // No need to protect this call using m_mutex all other method calls are
1000     // already thread safe.
1001 
1002     size_t num_indices = symbol_indexes.size();
1003     if (num_indices > 0)
1004     {
1005         SymbolContext sc;
1006         CalculateSymbolContext (&sc);
1007         for (size_t i = 0; i < num_indices; i++)
1008         {
1009             sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1010             if (sc.symbol)
1011                 sc_list.Append (sc);
1012         }
1013     }
1014 }
1015 
1016 size_t
1017 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1018 {
1019     // No need to protect this call using m_mutex all other method calls are
1020     // already thread safe.
1021 
1022 
1023     Timer scoped_timer(__PRETTY_FUNCTION__,
1024                        "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1025                        name.AsCString(),
1026                        symbol_type);
1027     const size_t initial_size = sc_list.GetSize();
1028     ObjectFile *objfile = GetObjectFile ();
1029     if (objfile)
1030     {
1031         Symtab *symtab = objfile->GetSymtab();
1032         if (symtab)
1033         {
1034             std::vector<uint32_t> symbol_indexes;
1035             symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1036             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1037         }
1038     }
1039     return sc_list.GetSize() - initial_size;
1040 }
1041 
1042 size_t
1043 Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1044 {
1045     // No need to protect this call using m_mutex all other method calls are
1046     // already thread safe.
1047 
1048     Timer scoped_timer(__PRETTY_FUNCTION__,
1049                        "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1050                        regex.GetText(),
1051                        symbol_type);
1052     const size_t initial_size = sc_list.GetSize();
1053     ObjectFile *objfile = GetObjectFile ();
1054     if (objfile)
1055     {
1056         Symtab *symtab = objfile->GetSymtab();
1057         if (symtab)
1058         {
1059             std::vector<uint32_t> symbol_indexes;
1060             symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1061             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1062         }
1063     }
1064     return sc_list.GetSize() - initial_size;
1065 }
1066 
1067 const TimeValue &
1068 Module::GetModificationTime () const
1069 {
1070     return m_mod_time;
1071 }
1072 
1073 bool
1074 Module::IsExecutable ()
1075 {
1076     if (GetObjectFile() == NULL)
1077         return false;
1078     else
1079         return GetObjectFile()->IsExecutable();
1080 }
1081 
1082 bool
1083 Module::IsLoadedInTarget (Target *target)
1084 {
1085     ObjectFile *obj_file = GetObjectFile();
1086     if (obj_file)
1087     {
1088         SectionList *sections = obj_file->GetSectionList();
1089         if (sections != NULL)
1090         {
1091             size_t num_sections = sections->GetSize();
1092             for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1093             {
1094                 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1095                 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1096                 {
1097                     return true;
1098                 }
1099             }
1100         }
1101     }
1102     return false;
1103 }
1104 bool
1105 Module::SetArchitecture (const ArchSpec &new_arch)
1106 {
1107     if (!m_arch.IsValid())
1108     {
1109         m_arch = new_arch;
1110         return true;
1111     }
1112     return m_arch == new_arch;
1113 }
1114 
1115 bool
1116 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1117 {
1118     size_t num_loaded_sections = 0;
1119     ObjectFile *objfile = GetObjectFile();
1120     if (objfile)
1121     {
1122         SectionList *section_list = objfile->GetSectionList ();
1123         if (section_list)
1124         {
1125             const size_t num_sections = section_list->GetSize();
1126             size_t sect_idx = 0;
1127             for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1128             {
1129                 // Iterate through the object file sections to find the
1130                 // first section that starts of file offset zero and that
1131                 // has bytes in the file...
1132                 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1133                 // Only load non-thread specific sections when given a slide
1134                 if (section_sp && !section_sp->IsThreadSpecific())
1135                 {
1136                     if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1137                         ++num_loaded_sections;
1138                 }
1139             }
1140         }
1141     }
1142     changed = num_loaded_sections > 0;
1143     return num_loaded_sections > 0;
1144 }
1145 
1146 
1147 bool
1148 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1149 {
1150     const UUID &uuid = module_ref.GetUUID();
1151 
1152     if (uuid.IsValid())
1153     {
1154         // If the UUID matches, then nothing more needs to match...
1155         if (uuid == GetUUID())
1156             return true;
1157         else
1158             return false;
1159     }
1160 
1161     const FileSpec &file_spec = module_ref.GetFileSpec();
1162     if (file_spec)
1163     {
1164         if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1165             return false;
1166     }
1167 
1168     const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1169     if (platform_file_spec)
1170     {
1171         if (!FileSpec::Equal (platform_file_spec, m_platform_file, platform_file_spec.GetDirectory()))
1172             return false;
1173     }
1174 
1175     const ArchSpec &arch = module_ref.GetArchitecture();
1176     if (arch.IsValid())
1177     {
1178         if (m_arch != arch)
1179             return false;
1180     }
1181 
1182     const ConstString &object_name = module_ref.GetObjectName();
1183     if (object_name)
1184     {
1185         if (object_name != GetObjectName())
1186             return false;
1187     }
1188     return true;
1189 }
1190 
1191 bool
1192 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1193 {
1194     Mutex::Locker locker (m_mutex);
1195     return m_source_mappings.FindFile (orig_spec, new_spec);
1196 }
1197 
1198 bool
1199 Module::RemapSourceFile (const char *path, std::string &new_path) const
1200 {
1201     Mutex::Locker locker (m_mutex);
1202     return m_source_mappings.RemapPath(path, new_path);
1203 }
1204 
1205