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