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