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