Module.cpp revision a7e864cb0a450c7ef65b6f9f6c9bae839c405906
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, eSymbolTypeCode, 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                        sc_list.AppendIfUnique (sc, merge_symbol_into_function);
619                    }
620                }
621            }
622        }
623    }
624    return sc_list.GetSize() - start_size;
625}
626
627size_t
628Module::FindFunctions (const RegularExpression& regex,
629                       bool include_symbols,
630                       bool include_inlines,
631                       bool append,
632                       SymbolContextList& sc_list)
633{
634    if (!append)
635        sc_list.Clear();
636
637    const size_t start_size = sc_list.GetSize();
638
639    SymbolVendor *symbols = GetSymbolVendor ();
640    if (symbols)
641        symbols->FindFunctions(regex, include_inlines, append, sc_list);
642    // Now check our symbol table for symbols that are code symbols if requested
643    if (include_symbols)
644    {
645        ObjectFile *objfile = GetObjectFile();
646        if (objfile)
647        {
648            Symtab *symtab = objfile->GetSymtab();
649            if (symtab)
650            {
651                std::vector<uint32_t> symbol_indexes;
652                symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
653                const size_t num_matches = symbol_indexes.size();
654                if (num_matches)
655                {
656                    const bool merge_symbol_into_function = true;
657                    SymbolContext sc(this);
658                    for (size_t i=0; i<num_matches; i++)
659                    {
660                        sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
661                        sc_list.AppendIfUnique (sc, merge_symbol_into_function);
662                    }
663                }
664            }
665        }
666    }
667    return sc_list.GetSize() - start_size;
668}
669
670size_t
671Module::FindTypes_Impl (const SymbolContext& sc,
672                        const ConstString &name,
673                        const ClangNamespaceDecl *namespace_decl,
674                        bool append,
675                        size_t max_matches,
676                        TypeList& types)
677{
678    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
679    if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
680    {
681        SymbolVendor *symbols = GetSymbolVendor ();
682        if (symbols)
683            return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
684    }
685    return 0;
686}
687
688size_t
689Module::FindTypesInNamespace (const SymbolContext& sc,
690                              const ConstString &type_name,
691                              const ClangNamespaceDecl *namespace_decl,
692                              size_t max_matches,
693                              TypeList& type_list)
694{
695    const bool append = true;
696    return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
697}
698
699lldb::TypeSP
700Module::FindFirstType (const SymbolContext& sc,
701                       const ConstString &name,
702                       bool exact_match)
703{
704    TypeList type_list;
705    const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
706    if (num_matches)
707        return type_list.GetTypeAtIndex(0);
708    return TypeSP();
709}
710
711
712size_t
713Module::FindTypes (const SymbolContext& sc,
714                   const ConstString &name,
715                   bool exact_match,
716                   size_t max_matches,
717                   TypeList& types)
718{
719    size_t num_matches = 0;
720    const char *type_name_cstr = name.GetCString();
721    std::string type_scope;
722    std::string type_basename;
723    const bool append = true;
724    TypeClass type_class = eTypeClassAny;
725    if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
726    {
727        // Check if "name" starts with "::" which means the qualified type starts
728        // from the root namespace and implies and exact match. The typenames we
729        // get back from clang do not start with "::" so we need to strip this off
730        // in order to get the qualfied names to match
731
732        if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
733        {
734            type_scope.erase(0,2);
735            exact_match = true;
736        }
737        ConstString type_basename_const_str (type_basename.c_str());
738        if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
739        {
740            types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
741            num_matches = types.GetSize();
742        }
743    }
744    else
745    {
746        // The type is not in a namespace/class scope, just search for it by basename
747        if (type_class != eTypeClassAny)
748        {
749            // The "type_name_cstr" will have been modified if we have a valid type class
750            // prefix (like "struct", "class", "union", "typedef" etc).
751            num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
752            types.RemoveMismatchedTypes (type_class);
753            num_matches = types.GetSize();
754        }
755        else
756        {
757            num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
758        }
759    }
760
761    return num_matches;
762
763}
764
765SymbolVendor*
766Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
767{
768    Mutex::Locker locker (m_mutex);
769    if (m_did_load_symbol_vendor == false && can_create)
770    {
771        ObjectFile *obj_file = GetObjectFile ();
772        if (obj_file != NULL)
773        {
774            Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
775            m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
776            m_did_load_symbol_vendor = true;
777        }
778    }
779    return m_symfile_ap.get();
780}
781
782void
783Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
784{
785    // Container objects whose paths do not specify a file directly can call
786    // this function to correct the file and object names.
787    m_file = file;
788    m_mod_time = file.GetModificationTime();
789    m_object_name = object_name;
790}
791
792const ArchSpec&
793Module::GetArchitecture () const
794{
795    return m_arch;
796}
797
798void
799Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
800{
801    Mutex::Locker locker (m_mutex);
802
803    if (level >= eDescriptionLevelFull)
804    {
805        if (m_arch.IsValid())
806            s->Printf("(%s) ", m_arch.GetArchitectureName());
807    }
808
809    if (level == eDescriptionLevelBrief)
810    {
811        const char *filename = m_file.GetFilename().GetCString();
812        if (filename)
813            s->PutCString (filename);
814    }
815    else
816    {
817        char path[PATH_MAX];
818        if (m_file.GetPath(path, sizeof(path)))
819            s->PutCString(path);
820    }
821
822    const char *object_name = m_object_name.GetCString();
823    if (object_name)
824        s->Printf("(%s)", object_name);
825}
826
827void
828Module::ReportError (const char *format, ...)
829{
830    if (format && format[0])
831    {
832        StreamString strm;
833        strm.PutCString("error: ");
834        GetDescription(&strm, lldb::eDescriptionLevelBrief);
835        strm.PutChar (' ');
836        va_list args;
837        va_start (args, format);
838        strm.PrintfVarArg(format, args);
839        va_end (args);
840
841        const int format_len = strlen(format);
842        if (format_len > 0)
843        {
844            const char last_char = format[format_len-1];
845            if (last_char != '\n' || last_char != '\r')
846                strm.EOL();
847        }
848        Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
849
850    }
851}
852
853bool
854Module::FileHasChanged () const
855{
856    if (m_file_has_changed == false)
857        m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
858    return m_file_has_changed;
859}
860
861void
862Module::ReportErrorIfModifyDetected (const char *format, ...)
863{
864    if (m_first_file_changed_log == false)
865    {
866        if (FileHasChanged ())
867        {
868            m_first_file_changed_log = true;
869            if (format)
870            {
871                StreamString strm;
872                strm.PutCString("error: the object file ");
873                GetDescription(&strm, lldb::eDescriptionLevelFull);
874                strm.PutCString (" has been modified\n");
875
876                va_list args;
877                va_start (args, format);
878                strm.PrintfVarArg(format, args);
879                va_end (args);
880
881                const int format_len = strlen(format);
882                if (format_len > 0)
883                {
884                    const char last_char = format[format_len-1];
885                    if (last_char != '\n' || last_char != '\r')
886                        strm.EOL();
887                }
888                strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
889                Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
890            }
891        }
892    }
893}
894
895void
896Module::ReportWarning (const char *format, ...)
897{
898    if (format && format[0])
899    {
900        StreamString strm;
901        strm.PutCString("warning: ");
902        GetDescription(&strm, lldb::eDescriptionLevelFull);
903        strm.PutChar (' ');
904
905        va_list args;
906        va_start (args, format);
907        strm.PrintfVarArg(format, args);
908        va_end (args);
909
910        const int format_len = strlen(format);
911        if (format_len > 0)
912        {
913            const char last_char = format[format_len-1];
914            if (last_char != '\n' || last_char != '\r')
915                strm.EOL();
916        }
917        Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
918    }
919}
920
921void
922Module::LogMessage (Log *log, const char *format, ...)
923{
924    if (log)
925    {
926        StreamString log_message;
927        GetDescription(&log_message, lldb::eDescriptionLevelFull);
928        log_message.PutCString (": ");
929        va_list args;
930        va_start (args, format);
931        log_message.PrintfVarArg (format, args);
932        va_end (args);
933        log->PutCString(log_message.GetString().c_str());
934    }
935}
936
937void
938Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
939{
940    if (log)
941    {
942        StreamString log_message;
943        GetDescription(&log_message, lldb::eDescriptionLevelFull);
944        log_message.PutCString (": ");
945        va_list args;
946        va_start (args, format);
947        log_message.PrintfVarArg (format, args);
948        va_end (args);
949        if (log->GetVerbose())
950            Host::Backtrace (log_message, 1024);
951        log->PutCString(log_message.GetString().c_str());
952    }
953}
954
955void
956Module::Dump(Stream *s)
957{
958    Mutex::Locker locker (m_mutex);
959    //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
960    s->Indent();
961    s->Printf("Module %s/%s%s%s%s\n",
962              m_file.GetDirectory().AsCString(),
963              m_file.GetFilename().AsCString(),
964              m_object_name ? "(" : "",
965              m_object_name ? m_object_name.GetCString() : "",
966              m_object_name ? ")" : "");
967
968    s->IndentMore();
969    ObjectFile *objfile = GetObjectFile ();
970
971    if (objfile)
972        objfile->Dump(s);
973
974    SymbolVendor *symbols = GetSymbolVendor ();
975
976    if (symbols)
977        symbols->Dump(s);
978
979    s->IndentLess();
980}
981
982
983TypeList*
984Module::GetTypeList ()
985{
986    SymbolVendor *symbols = GetSymbolVendor ();
987    if (symbols)
988        return &symbols->GetTypeList();
989    return NULL;
990}
991
992const ConstString &
993Module::GetObjectName() const
994{
995    return m_object_name;
996}
997
998ObjectFile *
999Module::GetObjectFile()
1000{
1001    Mutex::Locker locker (m_mutex);
1002    if (m_did_load_objfile == false)
1003    {
1004        m_did_load_objfile = true;
1005        Timer scoped_timer(__PRETTY_FUNCTION__,
1006                           "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1007        DataBufferSP data_sp;
1008        lldb::offset_t data_offset = 0;
1009        m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1010                                               &m_file,
1011                                               m_object_offset,
1012                                               m_file.GetByteSize(),
1013                                               data_sp,
1014                                               data_offset);
1015        if (m_objfile_sp)
1016        {
1017			// Once we get the object file, update our module with the object file's
1018			// architecture since it might differ in vendor/os if some parts were
1019			// unknown.
1020            m_objfile_sp->GetArchitecture (m_arch);
1021        }
1022    }
1023    return m_objfile_sp.get();
1024}
1025
1026
1027const Symbol *
1028Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1029{
1030    Timer scoped_timer(__PRETTY_FUNCTION__,
1031                       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1032                       name.AsCString(),
1033                       symbol_type);
1034    ObjectFile *objfile = GetObjectFile();
1035    if (objfile)
1036    {
1037        Symtab *symtab = objfile->GetSymtab();
1038        if (symtab)
1039            return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1040    }
1041    return NULL;
1042}
1043void
1044Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1045{
1046    // No need to protect this call using m_mutex all other method calls are
1047    // already thread safe.
1048
1049    size_t num_indices = symbol_indexes.size();
1050    if (num_indices > 0)
1051    {
1052        SymbolContext sc;
1053        CalculateSymbolContext (&sc);
1054        for (size_t i = 0; i < num_indices; i++)
1055        {
1056            sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1057            if (sc.symbol)
1058                sc_list.Append (sc);
1059        }
1060    }
1061}
1062
1063size_t
1064Module::FindFunctionSymbols (const ConstString &name,
1065                             uint32_t name_type_mask,
1066                             SymbolContextList& sc_list)
1067{
1068    Timer scoped_timer(__PRETTY_FUNCTION__,
1069                       "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1070                       name.AsCString(),
1071                       name_type_mask);
1072    ObjectFile *objfile = GetObjectFile ();
1073    if (objfile)
1074    {
1075        Symtab *symtab = objfile->GetSymtab();
1076        if (symtab)
1077            return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1078    }
1079    return 0;
1080}
1081
1082size_t
1083Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1084{
1085    // No need to protect this call using m_mutex all other method calls are
1086    // already thread safe.
1087
1088
1089    Timer scoped_timer(__PRETTY_FUNCTION__,
1090                       "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1091                       name.AsCString(),
1092                       symbol_type);
1093    const size_t initial_size = sc_list.GetSize();
1094    ObjectFile *objfile = GetObjectFile ();
1095    if (objfile)
1096    {
1097        Symtab *symtab = objfile->GetSymtab();
1098        if (symtab)
1099        {
1100            std::vector<uint32_t> symbol_indexes;
1101            symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1102            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1103        }
1104    }
1105    return sc_list.GetSize() - initial_size;
1106}
1107
1108size_t
1109Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1110{
1111    // No need to protect this call using m_mutex all other method calls are
1112    // already thread safe.
1113
1114    Timer scoped_timer(__PRETTY_FUNCTION__,
1115                       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1116                       regex.GetText(),
1117                       symbol_type);
1118    const size_t initial_size = sc_list.GetSize();
1119    ObjectFile *objfile = GetObjectFile ();
1120    if (objfile)
1121    {
1122        Symtab *symtab = objfile->GetSymtab();
1123        if (symtab)
1124        {
1125            std::vector<uint32_t> symbol_indexes;
1126            symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1127            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1128        }
1129    }
1130    return sc_list.GetSize() - initial_size;
1131}
1132
1133const TimeValue &
1134Module::GetModificationTime () const
1135{
1136    return m_mod_time;
1137}
1138
1139bool
1140Module::IsExecutable ()
1141{
1142    if (GetObjectFile() == NULL)
1143        return false;
1144    else
1145        return GetObjectFile()->IsExecutable();
1146}
1147
1148bool
1149Module::IsLoadedInTarget (Target *target)
1150{
1151    ObjectFile *obj_file = GetObjectFile();
1152    if (obj_file)
1153    {
1154        SectionList *sections = obj_file->GetSectionList();
1155        if (sections != NULL)
1156        {
1157            size_t num_sections = sections->GetSize();
1158            for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1159            {
1160                SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1161                if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1162                {
1163                    return true;
1164                }
1165            }
1166        }
1167    }
1168    return false;
1169}
1170
1171bool
1172Module::LoadScriptingResourceInTarget (Target *target, Error& error)
1173{
1174    if (!target)
1175    {
1176        error.SetErrorString("invalid destination Target");
1177        return false;
1178    }
1179
1180    Debugger &debugger = target->GetDebugger();
1181    const ScriptLanguage script_language = debugger.GetScriptLanguage();
1182    if (script_language != eScriptLanguageNone)
1183    {
1184
1185        PlatformSP platform_sp(target->GetPlatform());
1186
1187        if (!platform_sp)
1188        {
1189            error.SetErrorString("invalid Platform");
1190            return false;
1191        }
1192
1193        ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1194        if (script_interpreter)
1195        {
1196            FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1197                                                                                       *this);
1198
1199
1200            const uint32_t num_specs = file_specs.GetSize();
1201            if (num_specs)
1202            {
1203                for (uint32_t i=0; i<num_specs; ++i)
1204                {
1205                    FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1206                    if (scripting_fspec && scripting_fspec.Exists())
1207                    {
1208
1209                        StreamString scripting_stream;
1210                        scripting_fspec.Dump(&scripting_stream);
1211                        const bool can_reload = false;
1212                        const bool init_lldb_globals = false;
1213                        bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(), can_reload, init_lldb_globals, error);
1214                        if (!did_load)
1215                            return false;
1216                    }
1217                }
1218            }
1219        }
1220        else
1221        {
1222            error.SetErrorString("invalid ScriptInterpreter");
1223            return false;
1224        }
1225    }
1226    return true;
1227}
1228
1229bool
1230Module::SetArchitecture (const ArchSpec &new_arch)
1231{
1232    if (!m_arch.IsValid())
1233    {
1234        m_arch = new_arch;
1235        return true;
1236    }
1237    return m_arch.IsExactMatch(new_arch);
1238}
1239
1240bool
1241Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1242{
1243    size_t num_loaded_sections = 0;
1244    ObjectFile *objfile = GetObjectFile();
1245    if (objfile)
1246    {
1247        SectionList *section_list = objfile->GetSectionList ();
1248        if (section_list)
1249        {
1250            const size_t num_sections = section_list->GetSize();
1251            size_t sect_idx = 0;
1252            for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1253            {
1254                // Iterate through the object file sections to find the
1255                // first section that starts of file offset zero and that
1256                // has bytes in the file...
1257                SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1258                // Only load non-thread specific sections when given a slide
1259                if (section_sp && !section_sp->IsThreadSpecific())
1260                {
1261                    if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1262                        ++num_loaded_sections;
1263                }
1264            }
1265        }
1266    }
1267    changed = num_loaded_sections > 0;
1268    return num_loaded_sections > 0;
1269}
1270
1271
1272bool
1273Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1274{
1275    const UUID &uuid = module_ref.GetUUID();
1276
1277    if (uuid.IsValid())
1278    {
1279        // If the UUID matches, then nothing more needs to match...
1280        if (uuid == GetUUID())
1281            return true;
1282        else
1283            return false;
1284    }
1285
1286    const FileSpec &file_spec = module_ref.GetFileSpec();
1287    if (file_spec)
1288    {
1289        if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1290            return false;
1291    }
1292
1293    const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1294    if (platform_file_spec)
1295    {
1296        if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), platform_file_spec.GetDirectory()))
1297            return false;
1298    }
1299
1300    const ArchSpec &arch = module_ref.GetArchitecture();
1301    if (arch.IsValid())
1302    {
1303        if (!m_arch.IsCompatibleMatch(arch))
1304            return false;
1305    }
1306
1307    const ConstString &object_name = module_ref.GetObjectName();
1308    if (object_name)
1309    {
1310        if (object_name != GetObjectName())
1311            return false;
1312    }
1313    return true;
1314}
1315
1316bool
1317Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1318{
1319    Mutex::Locker locker (m_mutex);
1320    return m_source_mappings.FindFile (orig_spec, new_spec);
1321}
1322
1323bool
1324Module::RemapSourceFile (const char *path, std::string &new_path) const
1325{
1326    Mutex::Locker locker (m_mutex);
1327    return m_source_mappings.RemapPath(path, new_path);
1328}
1329
1330uint32_t
1331Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1332{
1333    ObjectFile *obj_file = GetObjectFile();
1334    if (obj_file)
1335        return obj_file->GetVersion (versions, num_versions);
1336
1337    if (versions && num_versions)
1338    {
1339        for (uint32_t i=0; i<num_versions; ++i)
1340            versions[i] = UINT32_MAX;
1341    }
1342    return 0;
1343}
1344