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