Module.cpp revision 2418fddf2e200c827da5bc6c855f3d4971b2d867
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
26using namespace lldb;
27using 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
32typedef std::vector<Module *> ModuleCollection;
33
34static ModuleCollection &
35GetModuleCollection()
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
50Mutex *
51Module::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
64size_t
65Module::GetNumberAllocatedModules ()
66{
67    Mutex::Locker locker (GetAllocationModuleCollectionMutex());
68    return GetModuleCollection().size();
69}
70
71Module *
72Module::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.
84namespace lldb {
85
86    void
87    ClearModuleInfo (void)
88    {
89        ModuleList::RemoveOrphanSharedModules();
90    }
91
92    void
93    DumpModuleInfo (void)
94    {
95        Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
96        ModuleCollection &modules = GetModuleCollection();
97        const size_t count = modules.size();
98        printf ("%s: %zu modules:\n", __PRETTY_FUNCTION__, count);
99        for (size_t i=0; i<count; ++i)
100        {
101
102            StreamString strm;
103            Module *module = modules[i];
104            const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
105            module->GetDescription(&strm, eDescriptionLevelFull);
106            printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
107                    module,
108                    in_shared_module_list,
109                    (uint32_t)module->use_count(),
110                    strm.GetString().c_str());
111        }
112    }
113}
114
115#endif
116
117Module::Module (const ModuleSpec &module_spec) :
118    m_mutex (Mutex::eMutexTypeRecursive),
119    m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
120    m_arch (module_spec.GetArchitecture()),
121    m_uuid (),
122    m_file (module_spec.GetFileSpec()),
123    m_platform_file(module_spec.GetPlatformFileSpec()),
124    m_symfile_spec (module_spec.GetSymbolFileSpec()),
125    m_object_name (module_spec.GetObjectName()),
126    m_object_offset (module_spec.GetObjectOffset()),
127    m_objfile_sp (),
128    m_symfile_ap (),
129    m_ast (),
130    m_source_mappings (),
131    m_did_load_objfile (false),
132    m_did_load_symbol_vendor (false),
133    m_did_parse_uuid (false),
134    m_did_init_ast (false),
135    m_is_dynamic_loader_module (false),
136    m_was_modified (false)
137{
138    // Scope for locker below...
139    {
140        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
141        GetModuleCollection().push_back(this);
142    }
143
144    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
145    if (log)
146        log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
147                     this,
148                     m_arch.GetArchitectureName(),
149                     m_file.GetDirectory().AsCString(""),
150                     m_file.GetFilename().AsCString(""),
151                     m_object_name.IsEmpty() ? "" : "(",
152                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
153                     m_object_name.IsEmpty() ? "" : ")");
154}
155
156Module::Module(const FileSpec& file_spec,
157               const ArchSpec& arch,
158               const ConstString *object_name,
159               off_t object_offset) :
160    m_mutex (Mutex::eMutexTypeRecursive),
161    m_mod_time (file_spec.GetModificationTime()),
162    m_arch (arch),
163    m_uuid (),
164    m_file (file_spec),
165    m_platform_file(),
166    m_symfile_spec (),
167    m_object_name (),
168    m_object_offset (object_offset),
169    m_objfile_sp (),
170    m_symfile_ap (),
171    m_ast (),
172    m_source_mappings (),
173    m_did_load_objfile (false),
174    m_did_load_symbol_vendor (false),
175    m_did_parse_uuid (false),
176    m_did_init_ast (false),
177    m_is_dynamic_loader_module (false),
178    m_was_modified (false)
179{
180    // Scope for locker below...
181    {
182        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
183        GetModuleCollection().push_back(this);
184    }
185
186    if (object_name)
187        m_object_name = *object_name;
188    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
189    if (log)
190        log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
191                     this,
192                     m_arch.GetArchitectureName(),
193                     m_file.GetDirectory().AsCString(""),
194                     m_file.GetFilename().AsCString(""),
195                     m_object_name.IsEmpty() ? "" : "(",
196                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
197                     m_object_name.IsEmpty() ? "" : ")");
198}
199
200Module::~Module()
201{
202    // Scope for locker below...
203    {
204        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
205        ModuleCollection &modules = GetModuleCollection();
206        ModuleCollection::iterator end = modules.end();
207        ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
208        if (pos != end)
209            modules.erase(pos);
210    }
211    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
212    if (log)
213        log->Printf ("%p Module::~Module((%s) '%s/%s%s%s%s')",
214                     this,
215                     m_arch.GetArchitectureName(),
216                     m_file.GetDirectory().AsCString(""),
217                     m_file.GetFilename().AsCString(""),
218                     m_object_name.IsEmpty() ? "" : "(",
219                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
220                     m_object_name.IsEmpty() ? "" : ")");
221    // Release any auto pointers before we start tearing down our member
222    // variables since the object file and symbol files might need to make
223    // function calls back into this module object. The ordering is important
224    // here because symbol files can require the module object file. So we tear
225    // down the symbol file first, then the object file.
226    m_symfile_ap.reset();
227    m_objfile_sp.reset();
228}
229
230ObjectFile *
231Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
232{
233    if (m_objfile_sp)
234    {
235        error.SetErrorString ("object file already exists");
236    }
237    else
238    {
239        Mutex::Locker locker (m_mutex);
240        if (process_sp)
241        {
242            StreamString s;
243            if (m_file.GetFilename())
244                s << m_file.GetFilename();
245                s.Printf("[0x%16.16llx]", header_addr);
246                m_file.GetFilename().SetCString (s.GetData());
247            m_did_load_objfile = true;
248            std::auto_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
249            Error readmem_error;
250            const size_t bytes_read = process_sp->ReadMemory (header_addr,
251                                                              data_ap->GetBytes(),
252                                                              data_ap->GetByteSize(),
253                                                              readmem_error);
254            if (bytes_read == 512)
255            {
256                DataBufferSP data_sp(data_ap.release());
257                m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
258                if (m_objfile_sp)
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
284const lldb_private::UUID&
285Module::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
301ClangASTContext &
302Module::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
318void
319Module::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
358void
359Module::CalculateSymbolContext(SymbolContext* sc)
360{
361    sc->module_sp = shared_from_this();
362}
363
364ModuleSP
365Module::CalculateSymbolContextModule ()
366{
367    return shared_from_this();
368}
369
370void
371Module::DumpSymbolContext(Stream *s)
372{
373    s->Printf(", Module{%p}", this);
374}
375
376uint32_t
377Module::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
387CompUnitSP
388Module::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
403bool
404Module::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
414uint32_t
415Module::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
468uint32_t
469Module::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
482uint32_t
483Module::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
505uint32_t
506Module::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}
513uint32_t
514Module::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
522uint32_t
523Module::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 (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
539            sc_list.Append(sc);
540    }
541    return sc_list.GetSize() - start_size;
542}
543
544uint32_t
545Module::FindFunctions (const ConstString &name,
546                       const ClangNamespaceDecl *namespace_decl,
547                       uint32_t name_type_mask,
548                       bool include_symbols,
549                       bool include_inlines,
550                       bool append,
551                       SymbolContextList& sc_list)
552{
553    if (!append)
554        sc_list.Clear();
555
556    const uint32_t start_size = sc_list.GetSize();
557
558    // Find all the functions (not symbols, but debug information functions...
559    SymbolVendor *symbols = GetSymbolVendor ();
560    if (symbols)
561        symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
562
563    // Now check our symbol table for symbols that are code symbols if requested
564    if (include_symbols)
565    {
566        ObjectFile *objfile = GetObjectFile();
567        if (objfile)
568        {
569            Symtab *symtab = objfile->GetSymtab();
570            if (symtab)
571            {
572                std::vector<uint32_t> symbol_indexes;
573                symtab->FindAllSymbolsWithNameAndType (name, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
574                const uint32_t num_matches = symbol_indexes.size();
575                if (num_matches)
576                {
577                    const bool merge_symbol_into_function = true;
578                    SymbolContext sc(this);
579                    for (uint32_t i=0; i<num_matches; i++)
580                    {
581                        sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
582                        sc_list.AppendIfUnique (sc, merge_symbol_into_function);
583                    }
584                }
585            }
586        }
587    }
588    return sc_list.GetSize() - start_size;
589}
590
591uint32_t
592Module::FindFunctions (const RegularExpression& regex,
593                       bool include_symbols,
594                       bool include_inlines,
595                       bool append,
596                       SymbolContextList& sc_list)
597{
598    if (!append)
599        sc_list.Clear();
600
601    const uint32_t start_size = sc_list.GetSize();
602
603    SymbolVendor *symbols = GetSymbolVendor ();
604    if (symbols)
605        symbols->FindFunctions(regex, include_inlines, append, sc_list);
606    // Now check our symbol table for symbols that are code symbols if requested
607    if (include_symbols)
608    {
609        ObjectFile *objfile = GetObjectFile();
610        if (objfile)
611        {
612            Symtab *symtab = objfile->GetSymtab();
613            if (symtab)
614            {
615                std::vector<uint32_t> symbol_indexes;
616                symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
617                const uint32_t num_matches = symbol_indexes.size();
618                if (num_matches)
619                {
620                    const bool merge_symbol_into_function = true;
621                    SymbolContext sc(this);
622                    for (uint32_t i=0; i<num_matches; i++)
623                    {
624                        sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
625                        sc_list.AppendIfUnique (sc, merge_symbol_into_function);
626                    }
627                }
628            }
629        }
630    }
631    return sc_list.GetSize() - start_size;
632}
633
634uint32_t
635Module::FindTypes_Impl (const SymbolContext& sc, const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, TypeList& types)
636{
637    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
638    if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
639    {
640        SymbolVendor *symbols = GetSymbolVendor ();
641        if (symbols)
642            return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
643    }
644    return 0;
645}
646
647// depending on implementation details, type lookup might fail because of
648// embedded spurious namespace:: prefixes. this call strips them, paying
649// attention to the fact that a type might have namespace'd type names as
650// arguments to templates, and those must not be stripped off
651static const char*
652StripTypeName(const char* name_cstr)
653{
654    // Protect against null c string.
655    if (!name_cstr)
656        return name_cstr;
657    const char* skip_namespace = strstr(name_cstr, "::");
658    const char* template_arg_char = strchr(name_cstr, '<');
659    while (skip_namespace != NULL)
660    {
661        if (template_arg_char != NULL &&
662            skip_namespace > template_arg_char) // but namespace'd template arguments are still good to go
663            break;
664        name_cstr = skip_namespace+2;
665        skip_namespace = strstr(name_cstr, "::");
666    }
667    return name_cstr;
668}
669
670uint32_t
671Module::FindTypes (const SymbolContext& sc,  const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, TypeList& types)
672{
673    uint32_t retval = FindTypes_Impl(sc, name, namespace_decl, append, max_matches, types);
674
675    if (retval == 0)
676    {
677        const char *orig_name = name.GetCString();
678        const char *stripped = StripTypeName(orig_name);
679        // Only do this lookup if StripTypeName has stripped the name:
680        if (stripped != orig_name)
681           return FindTypes_Impl(sc, ConstString(stripped), namespace_decl, append, max_matches, types);
682        else
683            return 0;
684    }
685    else
686        return retval;
687
688}
689
690//uint32_t
691//Module::FindTypes(const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, const char *udt_name, TypeList& types)
692//{
693//  Timer scoped_timer(__PRETTY_FUNCTION__);
694//  SymbolVendor *symbols = GetSymbolVendor ();
695//  if (symbols)
696//      return symbols->FindTypes(sc, regex, append, max_matches, encoding, udt_name, types);
697//  return 0;
698//
699//}
700
701SymbolVendor*
702Module::GetSymbolVendor (bool can_create)
703{
704    Mutex::Locker locker (m_mutex);
705    if (m_did_load_symbol_vendor == false && can_create)
706    {
707        ObjectFile *obj_file = GetObjectFile ();
708        if (obj_file != NULL)
709        {
710            Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
711            m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this()));
712            m_did_load_symbol_vendor = true;
713        }
714    }
715    return m_symfile_ap.get();
716}
717
718void
719Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
720{
721    // Container objects whose paths do not specify a file directly can call
722    // this function to correct the file and object names.
723    m_file = file;
724    m_mod_time = file.GetModificationTime();
725    m_object_name = object_name;
726}
727
728const ArchSpec&
729Module::GetArchitecture () const
730{
731    return m_arch;
732}
733
734void
735Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
736{
737    Mutex::Locker locker (m_mutex);
738
739    if (level >= eDescriptionLevelFull)
740    {
741        if (m_arch.IsValid())
742            s->Printf("(%s) ", m_arch.GetArchitectureName());
743    }
744
745    if (level == eDescriptionLevelBrief)
746    {
747        const char *filename = m_file.GetFilename().GetCString();
748        if (filename)
749            s->PutCString (filename);
750    }
751    else
752    {
753        char path[PATH_MAX];
754        if (m_file.GetPath(path, sizeof(path)))
755            s->PutCString(path);
756    }
757
758    const char *object_name = m_object_name.GetCString();
759    if (object_name)
760        s->Printf("(%s)", object_name);
761}
762
763void
764Module::ReportError (const char *format, ...)
765{
766    if (format && format[0])
767    {
768        StreamString strm;
769        strm.PutCString("error: ");
770        GetDescription(&strm, lldb::eDescriptionLevelBrief);
771        strm.PutChar (' ');
772        va_list args;
773        va_start (args, format);
774        strm.PrintfVarArg(format, args);
775        va_end (args);
776
777        const int format_len = strlen(format);
778        if (format_len > 0)
779        {
780            const char last_char = format[format_len-1];
781            if (last_char != '\n' || last_char != '\r')
782                strm.EOL();
783        }
784        Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
785
786    }
787}
788
789void
790Module::ReportErrorIfModifyDetected (const char *format, ...)
791{
792    if (!GetModified(true) && GetModified(false))
793    {
794        if (format)
795        {
796            StreamString strm;
797            strm.PutCString("error: the object file ");
798            GetDescription(&strm, lldb::eDescriptionLevelFull);
799            strm.PutCString (" has been modified\n");
800
801            va_list args;
802            va_start (args, format);
803            strm.PrintfVarArg(format, args);
804            va_end (args);
805
806            const int format_len = strlen(format);
807            if (format_len > 0)
808            {
809                const char last_char = format[format_len-1];
810                if (last_char != '\n' || last_char != '\r')
811                    strm.EOL();
812            }
813            strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
814            Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
815        }
816    }
817}
818
819void
820Module::ReportWarning (const char *format, ...)
821{
822    if (format && format[0])
823    {
824        StreamString strm;
825        strm.PutCString("warning: ");
826        GetDescription(&strm, lldb::eDescriptionLevelFull);
827        strm.PutChar (' ');
828
829        va_list args;
830        va_start (args, format);
831        strm.PrintfVarArg(format, args);
832        va_end (args);
833
834        const int format_len = strlen(format);
835        if (format_len > 0)
836        {
837            const char last_char = format[format_len-1];
838            if (last_char != '\n' || last_char != '\r')
839                strm.EOL();
840        }
841        Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
842    }
843}
844
845void
846Module::LogMessage (Log *log, const char *format, ...)
847{
848    if (log)
849    {
850        StreamString log_message;
851        GetDescription(&log_message, lldb::eDescriptionLevelFull);
852        log_message.PutCString (": ");
853        va_list args;
854        va_start (args, format);
855        log_message.PrintfVarArg (format, args);
856        va_end (args);
857        log->PutCString(log_message.GetString().c_str());
858    }
859}
860
861bool
862Module::GetModified (bool use_cached_only)
863{
864    if (m_was_modified == false && use_cached_only == false)
865    {
866        TimeValue curr_mod_time (m_file.GetModificationTime());
867        m_was_modified = curr_mod_time != m_mod_time;
868    }
869    return m_was_modified;
870}
871
872bool
873Module::SetModified (bool b)
874{
875    const bool prev_value = m_was_modified;
876    m_was_modified = b;
877    return prev_value;
878}
879
880
881void
882Module::Dump(Stream *s)
883{
884    Mutex::Locker locker (m_mutex);
885    //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
886    s->Indent();
887    s->Printf("Module %s/%s%s%s%s\n",
888              m_file.GetDirectory().AsCString(),
889              m_file.GetFilename().AsCString(),
890              m_object_name ? "(" : "",
891              m_object_name ? m_object_name.GetCString() : "",
892              m_object_name ? ")" : "");
893
894    s->IndentMore();
895    ObjectFile *objfile = GetObjectFile ();
896
897    if (objfile)
898        objfile->Dump(s);
899
900    SymbolVendor *symbols = GetSymbolVendor ();
901
902    if (symbols)
903        symbols->Dump(s);
904
905    s->IndentLess();
906}
907
908
909TypeList*
910Module::GetTypeList ()
911{
912    SymbolVendor *symbols = GetSymbolVendor ();
913    if (symbols)
914        return &symbols->GetTypeList();
915    return NULL;
916}
917
918const ConstString &
919Module::GetObjectName() const
920{
921    return m_object_name;
922}
923
924ObjectFile *
925Module::GetObjectFile()
926{
927    Mutex::Locker locker (m_mutex);
928    if (m_did_load_objfile == false)
929    {
930        m_did_load_objfile = true;
931        Timer scoped_timer(__PRETTY_FUNCTION__,
932                           "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
933        DataBufferSP file_data_sp;
934        m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
935                                               &m_file,
936                                               m_object_offset,
937                                               m_file.GetByteSize(),
938                                               file_data_sp);
939        if (m_objfile_sp)
940        {
941			// Once we get the object file, update our module with the object file's
942			// architecture since it might differ in vendor/os if some parts were
943			// unknown.
944            m_objfile_sp->GetArchitecture (m_arch);
945        }
946    }
947    return m_objfile_sp.get();
948}
949
950
951const Symbol *
952Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
953{
954    Timer scoped_timer(__PRETTY_FUNCTION__,
955                       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
956                       name.AsCString(),
957                       symbol_type);
958    ObjectFile *objfile = GetObjectFile();
959    if (objfile)
960    {
961        Symtab *symtab = objfile->GetSymtab();
962        if (symtab)
963            return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
964    }
965    return NULL;
966}
967void
968Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
969{
970    // No need to protect this call using m_mutex all other method calls are
971    // already thread safe.
972
973    size_t num_indices = symbol_indexes.size();
974    if (num_indices > 0)
975    {
976        SymbolContext sc;
977        CalculateSymbolContext (&sc);
978        for (size_t i = 0; i < num_indices; i++)
979        {
980            sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
981            if (sc.symbol)
982                sc_list.Append (sc);
983        }
984    }
985}
986
987size_t
988Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
989{
990    // No need to protect this call using m_mutex all other method calls are
991    // already thread safe.
992
993
994    Timer scoped_timer(__PRETTY_FUNCTION__,
995                       "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
996                       name.AsCString(),
997                       symbol_type);
998    const size_t initial_size = sc_list.GetSize();
999    ObjectFile *objfile = GetObjectFile ();
1000    if (objfile)
1001    {
1002        Symtab *symtab = objfile->GetSymtab();
1003        if (symtab)
1004        {
1005            std::vector<uint32_t> symbol_indexes;
1006            symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1007            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1008        }
1009    }
1010    return sc_list.GetSize() - initial_size;
1011}
1012
1013size_t
1014Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1015{
1016    // No need to protect this call using m_mutex all other method calls are
1017    // already thread safe.
1018
1019    Timer scoped_timer(__PRETTY_FUNCTION__,
1020                       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1021                       regex.GetText(),
1022                       symbol_type);
1023    const size_t initial_size = sc_list.GetSize();
1024    ObjectFile *objfile = GetObjectFile ();
1025    if (objfile)
1026    {
1027        Symtab *symtab = objfile->GetSymtab();
1028        if (symtab)
1029        {
1030            std::vector<uint32_t> symbol_indexes;
1031            symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1032            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1033        }
1034    }
1035    return sc_list.GetSize() - initial_size;
1036}
1037
1038const TimeValue &
1039Module::GetModificationTime () const
1040{
1041    return m_mod_time;
1042}
1043
1044bool
1045Module::IsExecutable ()
1046{
1047    if (GetObjectFile() == NULL)
1048        return false;
1049    else
1050        return GetObjectFile()->IsExecutable();
1051}
1052
1053bool
1054Module::IsLoadedInTarget (Target *target)
1055{
1056    ObjectFile *obj_file = GetObjectFile();
1057    if (obj_file)
1058    {
1059        SectionList *sections = obj_file->GetSectionList();
1060        if (sections != NULL)
1061        {
1062            size_t num_sections = sections->GetSize();
1063            for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1064            {
1065                SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1066                if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1067                {
1068                    return true;
1069                }
1070            }
1071        }
1072    }
1073    return false;
1074}
1075bool
1076Module::SetArchitecture (const ArchSpec &new_arch)
1077{
1078    if (!m_arch.IsValid())
1079    {
1080        m_arch = new_arch;
1081        return true;
1082    }
1083    return m_arch == new_arch;
1084}
1085
1086bool
1087Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1088{
1089    changed = false;
1090    ObjectFile *image_object_file = GetObjectFile();
1091    if (image_object_file)
1092    {
1093        SectionList *section_list = image_object_file->GetSectionList ();
1094        if (section_list)
1095        {
1096            const size_t num_sections = section_list->GetSize();
1097            size_t sect_idx = 0;
1098            for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1099            {
1100                // Iterate through the object file sections to find the
1101                // first section that starts of file offset zero and that
1102                // has bytes in the file...
1103                Section *section = section_list->GetSectionAtIndex (sect_idx).get();
1104                if (section)
1105                {
1106                    if (target.GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress() + offset))
1107                        changed = true;
1108                }
1109            }
1110            return sect_idx > 0;
1111        }
1112    }
1113    return false;
1114}
1115
1116
1117bool
1118Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1119{
1120    const UUID &uuid = module_ref.GetUUID();
1121
1122    if (uuid.IsValid())
1123    {
1124        // If the UUID matches, then nothing more needs to match...
1125        if (uuid == GetUUID())
1126            return true;
1127        else
1128            return false;
1129    }
1130
1131    const FileSpec &file_spec = module_ref.GetFileSpec();
1132    if (file_spec)
1133    {
1134        if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1135            return false;
1136    }
1137
1138    const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1139    if (platform_file_spec)
1140    {
1141        if (!FileSpec::Equal (platform_file_spec, m_platform_file, platform_file_spec.GetDirectory()))
1142            return false;
1143    }
1144
1145    const ArchSpec &arch = module_ref.GetArchitecture();
1146    if (arch.IsValid())
1147    {
1148        if (m_arch != arch)
1149            return false;
1150    }
1151
1152    const ConstString &object_name = module_ref.GetObjectName();
1153    if (object_name)
1154    {
1155        if (object_name != GetObjectName())
1156            return false;
1157    }
1158    return true;
1159}
1160
1161bool
1162Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1163{
1164    Mutex::Locker locker (m_mutex);
1165    return m_source_mappings.FindFile (orig_spec, new_spec);
1166}
1167
1168bool
1169Module::RemapSourceFile (const char *path, std::string &new_path) const
1170{
1171    Mutex::Locker locker (m_mutex);
1172    return m_source_mappings.RemapPath(path, new_path);
1173}
1174
1175