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/AddressResolverFileLine.h"
13#include "lldb/Core/Error.h"
14#include "lldb/Core/Module.h"
15#include "lldb/Core/DataBuffer.h"
16#include "lldb/Core/DataBufferHeap.h"
17#include "lldb/Core/Log.h"
18#include "lldb/Core/ModuleList.h"
19#include "lldb/Core/ModuleSpec.h"
20#include "lldb/Core/RegularExpression.h"
21#include "lldb/Core/Section.h"
22#include "lldb/Core/StreamString.h"
23#include "lldb/Core/Timer.h"
24#include "lldb/Host/Host.h"
25#include "lldb/Host/Symbols.h"
26#include "lldb/Interpreter/CommandInterpreter.h"
27#include "lldb/Interpreter/ScriptInterpreter.h"
28#include "lldb/lldb-private-log.h"
29#include "lldb/Symbol/CompileUnit.h"
30#include "lldb/Symbol/ObjectFile.h"
31#include "lldb/Symbol/SymbolContext.h"
32#include "lldb/Symbol/SymbolVendor.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
35#include "lldb/Target/Process.h"
36#include "lldb/Target/SectionLoadList.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Symbol/SymbolFile.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
43// Shared pointers to modules track module lifetimes in
44// targets and in the global module, but this collection
45// will track all module objects that are still alive
46typedef std::vector<Module *> ModuleCollection;
47
48static ModuleCollection &
49GetModuleCollection()
50{
51    // This module collection needs to live past any module, so we could either make it a
52    // shared pointer in each module or just leak is.  Since it is only an empty vector by
53    // the time all the modules have gone away, we just leak it for now.  If we decide this
54    // is a big problem we can introduce a Finalize method that will tear everything down in
55    // a predictable order.
56
57    static ModuleCollection *g_module_collection = NULL;
58    if (g_module_collection == NULL)
59        g_module_collection = new ModuleCollection();
60
61    return *g_module_collection;
62}
63
64Mutex *
65Module::GetAllocationModuleCollectionMutex()
66{
67    // NOTE: The mutex below must be leaked since the global module list in
68    // the ModuleList class will get torn at some point, and we can't know
69    // if it will tear itself down before the "g_module_collection_mutex" below
70    // will. So we leak a Mutex object below to safeguard against that
71
72    static Mutex *g_module_collection_mutex = NULL;
73    if (g_module_collection_mutex == NULL)
74        g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
75    return g_module_collection_mutex;
76}
77
78size_t
79Module::GetNumberAllocatedModules ()
80{
81    Mutex::Locker locker (GetAllocationModuleCollectionMutex());
82    return GetModuleCollection().size();
83}
84
85Module *
86Module::GetAllocatedModuleAtIndex (size_t idx)
87{
88    Mutex::Locker locker (GetAllocationModuleCollectionMutex());
89    ModuleCollection &modules = GetModuleCollection();
90    if (idx < modules.size())
91        return modules[idx];
92    return NULL;
93}
94#if 0
95
96// These functions help us to determine if modules are still loaded, yet don't require that
97// you have a command interpreter and can easily be called from an external debugger.
98namespace lldb {
99
100    void
101    ClearModuleInfo (void)
102    {
103        const bool mandatory = true;
104        ModuleList::RemoveOrphanSharedModules(mandatory);
105    }
106
107    void
108    DumpModuleInfo (void)
109    {
110        Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
111        ModuleCollection &modules = GetModuleCollection();
112        const size_t count = modules.size();
113        printf ("%s: %" PRIu64 " modules:\n", __PRETTY_FUNCTION__, (uint64_t)count);
114        for (size_t i=0; i<count; ++i)
115        {
116
117            StreamString strm;
118            Module *module = modules[i];
119            const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
120            module->GetDescription(&strm, eDescriptionLevelFull);
121            printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
122                    module,
123                    in_shared_module_list,
124                    (uint32_t)module->use_count(),
125                    strm.GetString().c_str());
126        }
127    }
128}
129
130#endif
131
132Module::Module (const ModuleSpec &module_spec) :
133    m_mutex (Mutex::eMutexTypeRecursive),
134    m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
135    m_arch (module_spec.GetArchitecture()),
136    m_uuid (),
137    m_file (module_spec.GetFileSpec()),
138    m_platform_file(module_spec.GetPlatformFileSpec()),
139    m_remote_install_file(),
140    m_symfile_spec (module_spec.GetSymbolFileSpec()),
141    m_object_name (module_spec.GetObjectName()),
142    m_object_offset (module_spec.GetObjectOffset()),
143    m_object_mod_time (module_spec.GetObjectModificationTime()),
144    m_objfile_sp (),
145    m_symfile_ap (),
146    m_ast (),
147    m_source_mappings (),
148    m_did_load_objfile (false),
149    m_did_load_symbol_vendor (false),
150    m_did_parse_uuid (false),
151    m_did_init_ast (false),
152    m_is_dynamic_loader_module (false),
153    m_file_has_changed (false),
154    m_first_file_changed_log (false)
155{
156    // Scope for locker below...
157    {
158        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
159        GetModuleCollection().push_back(this);
160    }
161
162    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
163    if (log)
164        log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
165                     this,
166                     m_arch.GetArchitectureName(),
167                     m_file.GetPath().c_str(),
168                     m_object_name.IsEmpty() ? "" : "(",
169                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
170                     m_object_name.IsEmpty() ? "" : ")");
171}
172
173Module::Module(const FileSpec& file_spec,
174               const ArchSpec& arch,
175               const ConstString *object_name,
176               off_t object_offset,
177               const TimeValue *object_mod_time_ptr) :
178    m_mutex (Mutex::eMutexTypeRecursive),
179    m_mod_time (file_spec.GetModificationTime()),
180    m_arch (arch),
181    m_uuid (),
182    m_file (file_spec),
183    m_platform_file(),
184    m_remote_install_file (),
185    m_symfile_spec (),
186    m_object_name (),
187    m_object_offset (object_offset),
188    m_object_mod_time (),
189    m_objfile_sp (),
190    m_symfile_ap (),
191    m_ast (),
192    m_source_mappings (),
193    m_did_load_objfile (false),
194    m_did_load_symbol_vendor (false),
195    m_did_parse_uuid (false),
196    m_did_init_ast (false),
197    m_is_dynamic_loader_module (false),
198    m_file_has_changed (false),
199    m_first_file_changed_log (false)
200{
201    // Scope for locker below...
202    {
203        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
204        GetModuleCollection().push_back(this);
205    }
206
207    if (object_name)
208        m_object_name = *object_name;
209
210    if (object_mod_time_ptr)
211        m_object_mod_time = *object_mod_time_ptr;
212
213    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
214    if (log)
215        log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
216                     this,
217                     m_arch.GetArchitectureName(),
218                     m_file.GetPath().c_str(),
219                     m_object_name.IsEmpty() ? "" : "(",
220                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
221                     m_object_name.IsEmpty() ? "" : ")");
222}
223
224Module::~Module()
225{
226    // Lock our module down while we tear everything down to make sure
227    // we don't get any access to the module while it is being destroyed
228    Mutex::Locker locker (m_mutex);
229    // Scope for locker below...
230    {
231        Mutex::Locker locker (GetAllocationModuleCollectionMutex());
232        ModuleCollection &modules = GetModuleCollection();
233        ModuleCollection::iterator end = modules.end();
234        ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
235        assert (pos != end);
236        modules.erase(pos);
237    }
238    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
239    if (log)
240        log->Printf ("%p Module::~Module((%s) '%s%s%s%s')",
241                     this,
242                     m_arch.GetArchitectureName(),
243                     m_file.GetPath().c_str(),
244                     m_object_name.IsEmpty() ? "" : "(",
245                     m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
246                     m_object_name.IsEmpty() ? "" : ")");
247    // Release any auto pointers before we start tearing down our member
248    // variables since the object file and symbol files might need to make
249    // function calls back into this module object. The ordering is important
250    // here because symbol files can require the module object file. So we tear
251    // down the symbol file first, then the object file.
252    m_sections_ap.reset();
253    m_symfile_ap.reset();
254    m_objfile_sp.reset();
255}
256
257ObjectFile *
258Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
259{
260    if (m_objfile_sp)
261    {
262        error.SetErrorString ("object file already exists");
263    }
264    else
265    {
266        Mutex::Locker locker (m_mutex);
267        if (process_sp)
268        {
269            m_did_load_objfile = true;
270            std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
271            Error readmem_error;
272            const size_t bytes_read = process_sp->ReadMemory (header_addr,
273                                                              data_ap->GetBytes(),
274                                                              data_ap->GetByteSize(),
275                                                              readmem_error);
276            if (bytes_read == 512)
277            {
278                DataBufferSP data_sp(data_ap.release());
279                m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
280                if (m_objfile_sp)
281                {
282                    StreamString s;
283                    s.Printf("0x%16.16" PRIx64, header_addr);
284                    m_object_name.SetCString (s.GetData());
285
286                    // Once we get the object file, update our module with the object file's
287                    // architecture since it might differ in vendor/os if some parts were
288                    // unknown.
289                    m_objfile_sp->GetArchitecture (m_arch);
290                }
291                else
292                {
293                    error.SetErrorString ("unable to find suitable object file plug-in");
294                }
295            }
296            else
297            {
298                error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
299            }
300        }
301        else
302        {
303            error.SetErrorString ("invalid process");
304        }
305    }
306    return m_objfile_sp.get();
307}
308
309
310const lldb_private::UUID&
311Module::GetUUID()
312{
313    Mutex::Locker locker (m_mutex);
314    if (m_did_parse_uuid == false)
315    {
316        ObjectFile * obj_file = GetObjectFile ();
317
318        if (obj_file != NULL)
319        {
320            obj_file->GetUUID(&m_uuid);
321            m_did_parse_uuid = true;
322        }
323    }
324    return m_uuid;
325}
326
327ClangASTContext &
328Module::GetClangASTContext ()
329{
330    Mutex::Locker locker (m_mutex);
331    if (m_did_init_ast == false)
332    {
333        ObjectFile * objfile = GetObjectFile();
334        ArchSpec object_arch;
335        if (objfile && objfile->GetArchitecture(object_arch))
336        {
337            m_did_init_ast = true;
338
339            // LLVM wants this to be set to iOS or MacOSX; if we're working on
340            // a bare-boards type image, change the triple for llvm's benefit.
341            if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
342                && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
343            {
344                if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
345                    object_arch.GetTriple().getArch() == llvm::Triple::thumb)
346                {
347                    object_arch.GetTriple().setOS(llvm::Triple::IOS);
348                }
349                else
350                {
351                    object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
352                }
353            }
354            m_ast.SetArchitecture (object_arch);
355        }
356    }
357    return m_ast;
358}
359
360void
361Module::ParseAllDebugSymbols()
362{
363    Mutex::Locker locker (m_mutex);
364    size_t num_comp_units = GetNumCompileUnits();
365    if (num_comp_units == 0)
366        return;
367
368    SymbolContext sc;
369    sc.module_sp = shared_from_this();
370    SymbolVendor *symbols = GetSymbolVendor ();
371
372    for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
373    {
374        sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
375        if (sc.comp_unit)
376        {
377            sc.function = NULL;
378            symbols->ParseVariablesForContext(sc);
379
380            symbols->ParseCompileUnitFunctions(sc);
381
382            for (size_t func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
383            {
384                symbols->ParseFunctionBlocks(sc);
385
386                // Parse the variables for this function and all its blocks
387                symbols->ParseVariablesForContext(sc);
388            }
389
390
391            // Parse all types for this compile unit
392            sc.function = NULL;
393            symbols->ParseTypes(sc);
394        }
395    }
396}
397
398void
399Module::CalculateSymbolContext(SymbolContext* sc)
400{
401    sc->module_sp = shared_from_this();
402}
403
404ModuleSP
405Module::CalculateSymbolContextModule ()
406{
407    return shared_from_this();
408}
409
410void
411Module::DumpSymbolContext(Stream *s)
412{
413    s->Printf(", Module{%p}", this);
414}
415
416size_t
417Module::GetNumCompileUnits()
418{
419    Mutex::Locker locker (m_mutex);
420    Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
421    SymbolVendor *symbols = GetSymbolVendor ();
422    if (symbols)
423        return symbols->GetNumCompileUnits();
424    return 0;
425}
426
427CompUnitSP
428Module::GetCompileUnitAtIndex (size_t index)
429{
430    Mutex::Locker locker (m_mutex);
431    size_t num_comp_units = GetNumCompileUnits ();
432    CompUnitSP cu_sp;
433
434    if (index < num_comp_units)
435    {
436        SymbolVendor *symbols = GetSymbolVendor ();
437        if (symbols)
438            cu_sp = symbols->GetCompileUnitAtIndex(index);
439    }
440    return cu_sp;
441}
442
443bool
444Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
445{
446    Mutex::Locker locker (m_mutex);
447    Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr);
448    SectionList *section_list = GetSectionList();
449    if (section_list)
450        return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
451    return false;
452}
453
454uint32_t
455Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc,
456                                        bool resolve_tail_call_address)
457{
458    Mutex::Locker locker (m_mutex);
459    uint32_t resolved_flags = 0;
460
461    // Clear the result symbol context in case we don't find anything, but don't clear the target
462    sc.Clear(false);
463
464    // Get the section from the section/offset address.
465    SectionSP section_sp (so_addr.GetSection());
466
467    // Make sure the section matches this module before we try and match anything
468    if (section_sp && section_sp->GetModule().get() == this)
469    {
470        // If the section offset based address resolved itself, then this
471        // is the right module.
472        sc.module_sp = shared_from_this();
473        resolved_flags |= eSymbolContextModule;
474
475        SymbolVendor* sym_vendor = GetSymbolVendor();
476        if (!sym_vendor)
477            return resolved_flags;
478
479        // Resolve the compile unit, function, block, line table or line
480        // entry if requested.
481        if (resolve_scope & eSymbolContextCompUnit    ||
482            resolve_scope & eSymbolContextFunction    ||
483            resolve_scope & eSymbolContextBlock       ||
484            resolve_scope & eSymbolContextLineEntry   )
485        {
486            resolved_flags |= sym_vendor->ResolveSymbolContext (so_addr, resolve_scope, sc);
487        }
488
489        // Resolve the symbol if requested, but don't re-look it up if we've already found it.
490        if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
491        {
492            Symtab *symtab = sym_vendor->GetSymtab();
493            if (symtab && so_addr.IsSectionOffset())
494            {
495                sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
496                if (!sc.symbol &&
497                    resolve_scope & eSymbolContextFunction && !(resolved_flags & eSymbolContextFunction))
498                {
499                    bool verify_unique = false; // No need to check again since ResolveSymbolContext failed to find a symbol at this address.
500                    if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
501                        sc.symbol = obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
502                }
503
504                if (sc.symbol)
505                {
506                    if (sc.symbol->IsSynthetic())
507                    {
508                        // We have a synthetic symbol so lets check if the object file
509                        // from the symbol file in the symbol vendor is different than
510                        // the object file for the module, and if so search its symbol
511                        // table to see if we can come up with a better symbol. For example
512                        // dSYM files on MacOSX have an unstripped symbol table inside of
513                        // them.
514                        ObjectFile *symtab_objfile = symtab->GetObjectFile();
515                        if (symtab_objfile && symtab_objfile->IsStripped())
516                        {
517                            SymbolFile *symfile = sym_vendor->GetSymbolFile();
518                            if (symfile)
519                            {
520                                ObjectFile *symfile_objfile = symfile->GetObjectFile();
521                                if (symfile_objfile != symtab_objfile)
522                                {
523                                    Symtab *symfile_symtab = symfile_objfile->GetSymtab();
524                                    if (symfile_symtab)
525                                    {
526                                        Symbol *symbol = symfile_symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
527                                        if (symbol && !symbol->IsSynthetic())
528                                        {
529                                            sc.symbol = symbol;
530                                        }
531                                    }
532                                }
533                            }
534                        }
535                    }
536                    resolved_flags |= eSymbolContextSymbol;
537                }
538            }
539        }
540
541        // For function symbols, so_addr may be off by one.  This is a convention consistent
542        // with FDE row indices in eh_frame sections, but requires extra logic here to permit
543        // symbol lookup for disassembly and unwind.
544        if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol) &&
545            resolve_tail_call_address && so_addr.IsSectionOffset())
546        {
547            Address previous_addr = so_addr;
548            previous_addr.Slide(-1);
549
550            bool do_resolve_tail_call_address = false; // prevent recursion
551            const uint32_t flags = ResolveSymbolContextForAddress(previous_addr, resolve_scope, sc,
552                                                                  do_resolve_tail_call_address);
553            if (flags & eSymbolContextSymbol)
554            {
555                AddressRange addr_range;
556                if (sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
557                {
558                    if (addr_range.GetBaseAddress().GetSection() == so_addr.GetSection())
559                    {
560                        // If the requested address is one past the address range of a function (i.e. a tail call),
561                        // or the decremented address is the start of a function (i.e. some forms of trampoline),
562                        // indicate that the symbol has been resolved.
563                        if (so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() ||
564                            so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() + addr_range.GetByteSize())
565                        {
566                            resolved_flags |= flags;
567                        }
568                    }
569                    else
570                    {
571                        sc.symbol = nullptr; // Don't trust the symbol if the sections didn't match.
572                    }
573                }
574            }
575        }
576    }
577    return resolved_flags;
578}
579
580uint32_t
581Module::ResolveSymbolContextForFilePath
582(
583    const char *file_path,
584    uint32_t line,
585    bool check_inlines,
586    uint32_t resolve_scope,
587    SymbolContextList& sc_list
588)
589{
590    FileSpec file_spec(file_path, false);
591    return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
592}
593
594uint32_t
595Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
596{
597    Mutex::Locker locker (m_mutex);
598    Timer scoped_timer(__PRETTY_FUNCTION__,
599                       "Module::ResolveSymbolContextForFilePath (%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
600                       file_spec.GetPath().c_str(),
601                       line,
602                       check_inlines ? "yes" : "no",
603                       resolve_scope);
604
605    const uint32_t initial_count = sc_list.GetSize();
606
607    SymbolVendor *symbols = GetSymbolVendor  ();
608    if (symbols)
609        symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
610
611    return sc_list.GetSize() - initial_count;
612}
613
614
615size_t
616Module::FindGlobalVariables (const ConstString &name,
617                             const ClangNamespaceDecl *namespace_decl,
618                             bool append,
619                             size_t max_matches,
620                             VariableList& variables)
621{
622    SymbolVendor *symbols = GetSymbolVendor ();
623    if (symbols)
624        return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
625    return 0;
626}
627
628size_t
629Module::FindGlobalVariables (const RegularExpression& regex,
630                             bool append,
631                             size_t max_matches,
632                             VariableList& variables)
633{
634    SymbolVendor *symbols = GetSymbolVendor ();
635    if (symbols)
636        return symbols->FindGlobalVariables(regex, append, max_matches, variables);
637    return 0;
638}
639
640size_t
641Module::FindCompileUnits (const FileSpec &path,
642                          bool append,
643                          SymbolContextList &sc_list)
644{
645    if (!append)
646        sc_list.Clear();
647
648    const size_t start_size = sc_list.GetSize();
649    const size_t num_compile_units = GetNumCompileUnits();
650    SymbolContext sc;
651    sc.module_sp = shared_from_this();
652    const bool compare_directory = (bool)path.GetDirectory();
653    for (size_t i=0; i<num_compile_units; ++i)
654    {
655        sc.comp_unit = GetCompileUnitAtIndex(i).get();
656        if (sc.comp_unit)
657        {
658            if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
659                sc_list.Append(sc);
660        }
661    }
662    return sc_list.GetSize() - start_size;
663}
664
665size_t
666Module::FindFunctions (const ConstString &name,
667                       const ClangNamespaceDecl *namespace_decl,
668                       uint32_t name_type_mask,
669                       bool include_symbols,
670                       bool include_inlines,
671                       bool append,
672                       SymbolContextList& sc_list)
673{
674    if (!append)
675        sc_list.Clear();
676
677    const size_t old_size = sc_list.GetSize();
678
679    // Find all the functions (not symbols, but debug information functions...
680    SymbolVendor *symbols = GetSymbolVendor ();
681
682    if (name_type_mask & eFunctionNameTypeAuto)
683    {
684        ConstString lookup_name;
685        uint32_t lookup_name_type_mask = 0;
686        bool match_name_after_lookup = false;
687        Module::PrepareForFunctionNameLookup (name,
688                                              name_type_mask,
689                                              lookup_name,
690                                              lookup_name_type_mask,
691                                              match_name_after_lookup);
692
693        if (symbols)
694        {
695            symbols->FindFunctions(lookup_name,
696                                   namespace_decl,
697                                   lookup_name_type_mask,
698                                   include_inlines,
699                                   append,
700                                   sc_list);
701
702            // Now check our symbol table for symbols that are code symbols if requested
703            if (include_symbols)
704            {
705                Symtab *symtab = symbols->GetSymtab();
706                if (symtab)
707                    symtab->FindFunctionSymbols(lookup_name, lookup_name_type_mask, sc_list);
708            }
709        }
710
711        if (match_name_after_lookup)
712        {
713            SymbolContext sc;
714            size_t i = old_size;
715            while (i<sc_list.GetSize())
716            {
717                if (sc_list.GetContextAtIndex(i, sc))
718                {
719                    const char *func_name = sc.GetFunctionName().GetCString();
720                    if (func_name && strstr (func_name, name.GetCString()) == NULL)
721                    {
722                        // Remove the current context
723                        sc_list.RemoveContextAtIndex(i);
724                        // Don't increment i and continue in the loop
725                        continue;
726                    }
727                }
728                ++i;
729            }
730        }
731    }
732    else
733    {
734        if (symbols)
735        {
736            symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
737
738            // Now check our symbol table for symbols that are code symbols if requested
739            if (include_symbols)
740            {
741                Symtab *symtab = symbols->GetSymtab();
742                if (symtab)
743                    symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
744            }
745        }
746    }
747
748    return sc_list.GetSize() - old_size;
749}
750
751size_t
752Module::FindFunctions (const RegularExpression& regex,
753                       bool include_symbols,
754                       bool include_inlines,
755                       bool append,
756                       SymbolContextList& sc_list)
757{
758    if (!append)
759        sc_list.Clear();
760
761    const size_t start_size = sc_list.GetSize();
762
763    SymbolVendor *symbols = GetSymbolVendor ();
764    if (symbols)
765    {
766        symbols->FindFunctions(regex, include_inlines, append, sc_list);
767
768        // Now check our symbol table for symbols that are code symbols if requested
769        if (include_symbols)
770        {
771            Symtab *symtab = symbols->GetSymtab();
772            if (symtab)
773            {
774                std::vector<uint32_t> symbol_indexes;
775                symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
776                const size_t num_matches = symbol_indexes.size();
777                if (num_matches)
778                {
779                    SymbolContext sc(this);
780                    const size_t end_functions_added_index = sc_list.GetSize();
781                    size_t num_functions_added_to_sc_list = end_functions_added_index - start_size;
782                    if (num_functions_added_to_sc_list == 0)
783                    {
784                        // No functions were added, just symbols, so we can just append them
785                        for (size_t i=0; i<num_matches; ++i)
786                        {
787                            sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
788                            SymbolType sym_type = sc.symbol->GetType();
789                            if (sc.symbol && (sym_type == eSymbolTypeCode ||
790                                              sym_type == eSymbolTypeResolver))
791                                sc_list.Append(sc);
792                        }
793                    }
794                    else
795                    {
796                        typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
797                        FileAddrToIndexMap file_addr_to_index;
798                        for (size_t i=start_size; i<end_functions_added_index; ++i)
799                        {
800                            const SymbolContext &sc = sc_list[i];
801                            if (sc.block)
802                                continue;
803                            file_addr_to_index[sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()] = i;
804                        }
805
806                        FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
807                        // Functions were added so we need to merge symbols into any
808                        // existing function symbol contexts
809                        for (size_t i=start_size; i<num_matches; ++i)
810                        {
811                            sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
812                            SymbolType sym_type = sc.symbol->GetType();
813                            if (sc.symbol && (sym_type == eSymbolTypeCode ||
814                                              sym_type == eSymbolTypeResolver))
815                            {
816                                FileAddrToIndexMap::const_iterator pos = file_addr_to_index.find(sc.symbol->GetAddress().GetFileAddress());
817                                if (pos == end)
818                                    sc_list.Append(sc);
819                                else
820                                    sc_list[pos->second].symbol = sc.symbol;
821                            }
822                        }
823                    }
824                }
825            }
826        }
827    }
828    return sc_list.GetSize() - start_size;
829}
830
831void
832Module::FindAddressesForLine (const lldb::TargetSP target_sp,
833                              const FileSpec &file, uint32_t line,
834                              Function *function,
835                              std::vector<Address> &output_local, std::vector<Address> &output_extern)
836{
837    SearchFilterByModule filter(target_sp, m_file);
838    AddressResolverFileLine resolver(file, line, true);
839    resolver.ResolveAddress (filter);
840
841    for (size_t n=0;n<resolver.GetNumberOfAddresses();n++)
842    {
843        Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
844        Function *f = addr.CalculateSymbolContextFunction();
845        if (f && f == function)
846            output_local.push_back (addr);
847        else
848            output_extern.push_back (addr);
849    }
850}
851
852size_t
853Module::FindTypes_Impl (const SymbolContext& sc,
854                        const ConstString &name,
855                        const ClangNamespaceDecl *namespace_decl,
856                        bool append,
857                        size_t max_matches,
858                        TypeList& types)
859{
860    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
861    if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
862    {
863        SymbolVendor *symbols = GetSymbolVendor ();
864        if (symbols)
865            return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
866    }
867    return 0;
868}
869
870size_t
871Module::FindTypesInNamespace (const SymbolContext& sc,
872                              const ConstString &type_name,
873                              const ClangNamespaceDecl *namespace_decl,
874                              size_t max_matches,
875                              TypeList& type_list)
876{
877    const bool append = true;
878    return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
879}
880
881lldb::TypeSP
882Module::FindFirstType (const SymbolContext& sc,
883                       const ConstString &name,
884                       bool exact_match)
885{
886    TypeList type_list;
887    const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
888    if (num_matches)
889        return type_list.GetTypeAtIndex(0);
890    return TypeSP();
891}
892
893
894size_t
895Module::FindTypes (const SymbolContext& sc,
896                   const ConstString &name,
897                   bool exact_match,
898                   size_t max_matches,
899                   TypeList& types)
900{
901    size_t num_matches = 0;
902    const char *type_name_cstr = name.GetCString();
903    std::string type_scope;
904    std::string type_basename;
905    const bool append = true;
906    TypeClass type_class = eTypeClassAny;
907    if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
908    {
909        // Check if "name" starts with "::" which means the qualified type starts
910        // from the root namespace and implies and exact match. The typenames we
911        // get back from clang do not start with "::" so we need to strip this off
912        // in order to get the qualfied names to match
913
914        if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
915        {
916            type_scope.erase(0,2);
917            exact_match = true;
918        }
919        ConstString type_basename_const_str (type_basename.c_str());
920        if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
921        {
922            types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
923            num_matches = types.GetSize();
924        }
925    }
926    else
927    {
928        // The type is not in a namespace/class scope, just search for it by basename
929        if (type_class != eTypeClassAny)
930        {
931            // The "type_name_cstr" will have been modified if we have a valid type class
932            // prefix (like "struct", "class", "union", "typedef" etc).
933            num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
934            types.RemoveMismatchedTypes (type_class);
935            num_matches = types.GetSize();
936        }
937        else
938        {
939            num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
940        }
941    }
942
943    return num_matches;
944
945}
946
947SymbolVendor*
948Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
949{
950    Mutex::Locker locker (m_mutex);
951    if (m_did_load_symbol_vendor == false && can_create)
952    {
953        ObjectFile *obj_file = GetObjectFile ();
954        if (obj_file != NULL)
955        {
956            Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
957            m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
958            m_did_load_symbol_vendor = true;
959        }
960    }
961    return m_symfile_ap.get();
962}
963
964void
965Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
966{
967    // Container objects whose paths do not specify a file directly can call
968    // this function to correct the file and object names.
969    m_file = file;
970    m_mod_time = file.GetModificationTime();
971    m_object_name = object_name;
972}
973
974const ArchSpec&
975Module::GetArchitecture () const
976{
977    return m_arch;
978}
979
980std::string
981Module::GetSpecificationDescription () const
982{
983    std::string spec(GetFileSpec().GetPath());
984    if (m_object_name)
985    {
986        spec += '(';
987        spec += m_object_name.GetCString();
988        spec += ')';
989    }
990    return spec;
991}
992
993void
994Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
995{
996    Mutex::Locker locker (m_mutex);
997
998    if (level >= eDescriptionLevelFull)
999    {
1000        if (m_arch.IsValid())
1001            s->Printf("(%s) ", m_arch.GetArchitectureName());
1002    }
1003
1004    if (level == eDescriptionLevelBrief)
1005    {
1006        const char *filename = m_file.GetFilename().GetCString();
1007        if (filename)
1008            s->PutCString (filename);
1009    }
1010    else
1011    {
1012        char path[PATH_MAX];
1013        if (m_file.GetPath(path, sizeof(path)))
1014            s->PutCString(path);
1015    }
1016
1017    const char *object_name = m_object_name.GetCString();
1018    if (object_name)
1019        s->Printf("(%s)", object_name);
1020}
1021
1022void
1023Module::ReportError (const char *format, ...)
1024{
1025    if (format && format[0])
1026    {
1027        StreamString strm;
1028        strm.PutCString("error: ");
1029        GetDescription(&strm, lldb::eDescriptionLevelBrief);
1030        strm.PutChar (' ');
1031        va_list args;
1032        va_start (args, format);
1033        strm.PrintfVarArg(format, args);
1034        va_end (args);
1035
1036        const int format_len = strlen(format);
1037        if (format_len > 0)
1038        {
1039            const char last_char = format[format_len-1];
1040            if (last_char != '\n' || last_char != '\r')
1041                strm.EOL();
1042        }
1043        Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1044
1045    }
1046}
1047
1048bool
1049Module::FileHasChanged () const
1050{
1051    if (m_file_has_changed == false)
1052        m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
1053    return m_file_has_changed;
1054}
1055
1056void
1057Module::ReportErrorIfModifyDetected (const char *format, ...)
1058{
1059    if (m_first_file_changed_log == false)
1060    {
1061        if (FileHasChanged ())
1062        {
1063            m_first_file_changed_log = true;
1064            if (format)
1065            {
1066                StreamString strm;
1067                strm.PutCString("error: the object file ");
1068                GetDescription(&strm, lldb::eDescriptionLevelFull);
1069                strm.PutCString (" has been modified\n");
1070
1071                va_list args;
1072                va_start (args, format);
1073                strm.PrintfVarArg(format, args);
1074                va_end (args);
1075
1076                const int format_len = strlen(format);
1077                if (format_len > 0)
1078                {
1079                    const char last_char = format[format_len-1];
1080                    if (last_char != '\n' || last_char != '\r')
1081                        strm.EOL();
1082                }
1083                strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
1084                Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1085            }
1086        }
1087    }
1088}
1089
1090void
1091Module::ReportWarning (const char *format, ...)
1092{
1093    if (format && format[0])
1094    {
1095        StreamString strm;
1096        strm.PutCString("warning: ");
1097        GetDescription(&strm, lldb::eDescriptionLevelFull);
1098        strm.PutChar (' ');
1099
1100        va_list args;
1101        va_start (args, format);
1102        strm.PrintfVarArg(format, args);
1103        va_end (args);
1104
1105        const int format_len = strlen(format);
1106        if (format_len > 0)
1107        {
1108            const char last_char = format[format_len-1];
1109            if (last_char != '\n' || last_char != '\r')
1110                strm.EOL();
1111        }
1112        Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
1113    }
1114}
1115
1116void
1117Module::LogMessage (Log *log, const char *format, ...)
1118{
1119    if (log)
1120    {
1121        StreamString log_message;
1122        GetDescription(&log_message, lldb::eDescriptionLevelFull);
1123        log_message.PutCString (": ");
1124        va_list args;
1125        va_start (args, format);
1126        log_message.PrintfVarArg (format, args);
1127        va_end (args);
1128        log->PutCString(log_message.GetString().c_str());
1129    }
1130}
1131
1132void
1133Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
1134{
1135    if (log)
1136    {
1137        StreamString log_message;
1138        GetDescription(&log_message, lldb::eDescriptionLevelFull);
1139        log_message.PutCString (": ");
1140        va_list args;
1141        va_start (args, format);
1142        log_message.PrintfVarArg (format, args);
1143        va_end (args);
1144        if (log->GetVerbose())
1145            Host::Backtrace (log_message, 1024);
1146        log->PutCString(log_message.GetString().c_str());
1147    }
1148}
1149
1150void
1151Module::Dump(Stream *s)
1152{
1153    Mutex::Locker locker (m_mutex);
1154    //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1155    s->Indent();
1156    s->Printf("Module %s%s%s%s\n",
1157              m_file.GetPath().c_str(),
1158              m_object_name ? "(" : "",
1159              m_object_name ? m_object_name.GetCString() : "",
1160              m_object_name ? ")" : "");
1161
1162    s->IndentMore();
1163
1164    ObjectFile *objfile = GetObjectFile ();
1165    if (objfile)
1166        objfile->Dump(s);
1167
1168    SymbolVendor *symbols = GetSymbolVendor ();
1169    if (symbols)
1170        symbols->Dump(s);
1171
1172    s->IndentLess();
1173}
1174
1175
1176TypeList*
1177Module::GetTypeList ()
1178{
1179    SymbolVendor *symbols = GetSymbolVendor ();
1180    if (symbols)
1181        return &symbols->GetTypeList();
1182    return NULL;
1183}
1184
1185const ConstString &
1186Module::GetObjectName() const
1187{
1188    return m_object_name;
1189}
1190
1191ObjectFile *
1192Module::GetObjectFile()
1193{
1194    Mutex::Locker locker (m_mutex);
1195    if (m_did_load_objfile == false)
1196    {
1197        Timer scoped_timer(__PRETTY_FUNCTION__,
1198                           "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1199        DataBufferSP data_sp;
1200        lldb::offset_t data_offset = 0;
1201        const lldb::offset_t file_size = m_file.GetByteSize();
1202        if (file_size > m_object_offset)
1203        {
1204            m_did_load_objfile = true;
1205            m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1206                                                   &m_file,
1207                                                   m_object_offset,
1208                                                   file_size - m_object_offset,
1209                                                   data_sp,
1210                                                   data_offset);
1211            if (m_objfile_sp)
1212            {
1213                // Once we get the object file, update our module with the object file's
1214                // architecture since it might differ in vendor/os if some parts were
1215                // unknown.
1216                m_objfile_sp->GetArchitecture (m_arch);
1217            }
1218        }
1219    }
1220    return m_objfile_sp.get();
1221}
1222
1223SectionList *
1224Module::GetSectionList()
1225{
1226    // Populate m_unified_sections_ap with sections from objfile.
1227    if (m_sections_ap.get() == NULL)
1228    {
1229        ObjectFile *obj_file = GetObjectFile();
1230        if (obj_file)
1231            obj_file->CreateSections(*GetUnifiedSectionList());
1232    }
1233    return m_sections_ap.get();
1234}
1235
1236SectionList *
1237Module::GetUnifiedSectionList()
1238{
1239    // Populate m_unified_sections_ap with sections from objfile.
1240    if (m_sections_ap.get() == NULL)
1241        m_sections_ap.reset(new SectionList());
1242    return m_sections_ap.get();
1243}
1244
1245const Symbol *
1246Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1247{
1248    Timer scoped_timer(__PRETTY_FUNCTION__,
1249                       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1250                       name.AsCString(),
1251                       symbol_type);
1252    SymbolVendor* sym_vendor = GetSymbolVendor();
1253    if (sym_vendor)
1254    {
1255        Symtab *symtab = sym_vendor->GetSymtab();
1256        if (symtab)
1257            return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1258    }
1259    return NULL;
1260}
1261void
1262Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1263{
1264    // No need to protect this call using m_mutex all other method calls are
1265    // already thread safe.
1266
1267    size_t num_indices = symbol_indexes.size();
1268    if (num_indices > 0)
1269    {
1270        SymbolContext sc;
1271        CalculateSymbolContext (&sc);
1272        for (size_t i = 0; i < num_indices; i++)
1273        {
1274            sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1275            if (sc.symbol)
1276                sc_list.Append (sc);
1277        }
1278    }
1279}
1280
1281size_t
1282Module::FindFunctionSymbols (const ConstString &name,
1283                             uint32_t name_type_mask,
1284                             SymbolContextList& sc_list)
1285{
1286    Timer scoped_timer(__PRETTY_FUNCTION__,
1287                       "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1288                       name.AsCString(),
1289                       name_type_mask);
1290    SymbolVendor* sym_vendor = GetSymbolVendor();
1291    if (sym_vendor)
1292    {
1293        Symtab *symtab = sym_vendor->GetSymtab();
1294        if (symtab)
1295            return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1296    }
1297    return 0;
1298}
1299
1300size_t
1301Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1302{
1303    // No need to protect this call using m_mutex all other method calls are
1304    // already thread safe.
1305
1306
1307    Timer scoped_timer(__PRETTY_FUNCTION__,
1308                       "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1309                       name.AsCString(),
1310                       symbol_type);
1311    const size_t initial_size = sc_list.GetSize();
1312    SymbolVendor* sym_vendor = GetSymbolVendor();
1313    if (sym_vendor)
1314    {
1315        Symtab *symtab = sym_vendor->GetSymtab();
1316        if (symtab)
1317        {
1318            std::vector<uint32_t> symbol_indexes;
1319            symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1320            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1321        }
1322    }
1323    return sc_list.GetSize() - initial_size;
1324}
1325
1326size_t
1327Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1328{
1329    // No need to protect this call using m_mutex all other method calls are
1330    // already thread safe.
1331
1332    Timer scoped_timer(__PRETTY_FUNCTION__,
1333                       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1334                       regex.GetText(),
1335                       symbol_type);
1336    const size_t initial_size = sc_list.GetSize();
1337    SymbolVendor* sym_vendor = GetSymbolVendor();
1338    if (sym_vendor)
1339    {
1340        Symtab *symtab = sym_vendor->GetSymtab();
1341        if (symtab)
1342        {
1343            std::vector<uint32_t> symbol_indexes;
1344            symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1345            SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1346        }
1347    }
1348    return sc_list.GetSize() - initial_size;
1349}
1350
1351void
1352Module::SetSymbolFileFileSpec (const FileSpec &file)
1353{
1354    // Remove any sections in the unified section list that come from the current symbol vendor.
1355    if (m_symfile_ap)
1356    {
1357        SectionList *section_list = GetSectionList();
1358        SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1359        if (section_list && symbol_file)
1360        {
1361            ObjectFile *obj_file = symbol_file->GetObjectFile();
1362            // Make sure we have an object file and that the symbol vendor's objfile isn't
1363            // the same as the module's objfile before we remove any sections for it...
1364            if (obj_file && obj_file != m_objfile_sp.get())
1365            {
1366                size_t num_sections = section_list->GetNumSections (0);
1367                for (size_t idx = num_sections; idx > 0; --idx)
1368                {
1369                    lldb::SectionSP section_sp (section_list->GetSectionAtIndex (idx - 1));
1370                    if (section_sp->GetObjectFile() == obj_file)
1371                    {
1372                        section_list->DeleteSection (idx - 1);
1373                    }
1374                }
1375            }
1376        }
1377    }
1378
1379    m_symfile_spec = file;
1380    m_symfile_ap.reset();
1381    m_did_load_symbol_vendor = false;
1382}
1383
1384bool
1385Module::IsExecutable ()
1386{
1387    if (GetObjectFile() == NULL)
1388        return false;
1389    else
1390        return GetObjectFile()->IsExecutable();
1391}
1392
1393bool
1394Module::IsLoadedInTarget (Target *target)
1395{
1396    ObjectFile *obj_file = GetObjectFile();
1397    if (obj_file)
1398    {
1399        SectionList *sections = GetSectionList();
1400        if (sections != NULL)
1401        {
1402            size_t num_sections = sections->GetSize();
1403            for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1404            {
1405                SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1406                if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1407                {
1408                    return true;
1409                }
1410            }
1411        }
1412    }
1413    return false;
1414}
1415
1416bool
1417Module::LoadScriptingResourceInTarget (Target *target, Error& error, Stream* feedback_stream)
1418{
1419    if (!target)
1420    {
1421        error.SetErrorString("invalid destination Target");
1422        return false;
1423    }
1424
1425    LoadScriptFromSymFile shoud_load = target->TargetProperties::GetLoadScriptFromSymbolFile();
1426
1427    Debugger &debugger = target->GetDebugger();
1428    const ScriptLanguage script_language = debugger.GetScriptLanguage();
1429    if (script_language != eScriptLanguageNone)
1430    {
1431
1432        PlatformSP platform_sp(target->GetPlatform());
1433
1434        if (!platform_sp)
1435        {
1436            error.SetErrorString("invalid Platform");
1437            return false;
1438        }
1439
1440        FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1441                                                                                   *this);
1442
1443
1444        const uint32_t num_specs = file_specs.GetSize();
1445        if (num_specs)
1446        {
1447            ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1448            if (script_interpreter)
1449            {
1450                for (uint32_t i=0; i<num_specs; ++i)
1451                {
1452                    FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1453                    if (scripting_fspec && scripting_fspec.Exists())
1454                    {
1455                        if (shoud_load == eLoadScriptFromSymFileFalse)
1456                            return false;
1457                        if (shoud_load == eLoadScriptFromSymFileWarn)
1458                        {
1459                            if (feedback_stream)
1460                                feedback_stream->Printf("warning: '%s' contains a debug script. To run this script in "
1461                                                        "this debug session:\n\n    command script import \"%s\"\n\n"
1462                                                        "To run all discovered debug scripts in this session:\n\n"
1463                                                        "    settings set target.load-script-from-symbol-file true\n",
1464                                                        GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1465                                                        scripting_fspec.GetPath().c_str());
1466                            return false;
1467                        }
1468                        StreamString scripting_stream;
1469                        scripting_fspec.Dump(&scripting_stream);
1470                        const bool can_reload = true;
1471                        const bool init_lldb_globals = false;
1472                        bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(),
1473                                                                                can_reload,
1474                                                                                init_lldb_globals,
1475                                                                                error);
1476                        if (!did_load)
1477                            return false;
1478                    }
1479                }
1480            }
1481            else
1482            {
1483                error.SetErrorString("invalid ScriptInterpreter");
1484                return false;
1485            }
1486        }
1487    }
1488    return true;
1489}
1490
1491bool
1492Module::SetArchitecture (const ArchSpec &new_arch)
1493{
1494    if (!m_arch.IsValid())
1495    {
1496        m_arch = new_arch;
1497        return true;
1498    }
1499    return m_arch.IsExactMatch(new_arch);
1500}
1501
1502bool
1503Module::SetLoadAddress (Target &target, lldb::addr_t value, bool value_is_offset, bool &changed)
1504{
1505    ObjectFile *object_file = GetObjectFile();
1506    if (object_file)
1507    {
1508        changed = object_file->SetLoadAddress(target, value, value_is_offset);
1509        return true;
1510    }
1511    else
1512    {
1513        changed = false;
1514    }
1515    return false;
1516}
1517
1518
1519bool
1520Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1521{
1522    const UUID &uuid = module_ref.GetUUID();
1523
1524    if (uuid.IsValid())
1525    {
1526        // If the UUID matches, then nothing more needs to match...
1527        if (uuid == GetUUID())
1528            return true;
1529        else
1530            return false;
1531    }
1532
1533    const FileSpec &file_spec = module_ref.GetFileSpec();
1534    if (file_spec)
1535    {
1536        if (!FileSpec::Equal (file_spec, m_file, (bool)file_spec.GetDirectory()))
1537            return false;
1538    }
1539
1540    const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1541    if (platform_file_spec)
1542    {
1543        if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), (bool)platform_file_spec.GetDirectory()))
1544            return false;
1545    }
1546
1547    const ArchSpec &arch = module_ref.GetArchitecture();
1548    if (arch.IsValid())
1549    {
1550        if (!m_arch.IsCompatibleMatch(arch))
1551            return false;
1552    }
1553
1554    const ConstString &object_name = module_ref.GetObjectName();
1555    if (object_name)
1556    {
1557        if (object_name != GetObjectName())
1558            return false;
1559    }
1560    return true;
1561}
1562
1563bool
1564Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1565{
1566    Mutex::Locker locker (m_mutex);
1567    return m_source_mappings.FindFile (orig_spec, new_spec);
1568}
1569
1570bool
1571Module::RemapSourceFile (const char *path, std::string &new_path) const
1572{
1573    Mutex::Locker locker (m_mutex);
1574    return m_source_mappings.RemapPath(path, new_path);
1575}
1576
1577uint32_t
1578Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1579{
1580    ObjectFile *obj_file = GetObjectFile();
1581    if (obj_file)
1582        return obj_file->GetVersion (versions, num_versions);
1583
1584    if (versions && num_versions)
1585    {
1586        for (uint32_t i=0; i<num_versions; ++i)
1587            versions[i] = UINT32_MAX;
1588    }
1589    return 0;
1590}
1591
1592void
1593Module::PrepareForFunctionNameLookup (const ConstString &name,
1594                                      uint32_t name_type_mask,
1595                                      ConstString &lookup_name,
1596                                      uint32_t &lookup_name_type_mask,
1597                                      bool &match_name_after_lookup)
1598{
1599    const char *name_cstr = name.GetCString();
1600    lookup_name_type_mask = eFunctionNameTypeNone;
1601    match_name_after_lookup = false;
1602    const char *base_name_start = NULL;
1603    const char *base_name_end = NULL;
1604
1605    if (name_type_mask & eFunctionNameTypeAuto)
1606    {
1607        if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
1608            lookup_name_type_mask = eFunctionNameTypeFull;
1609        else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
1610            lookup_name_type_mask = eFunctionNameTypeFull;
1611        else
1612        {
1613            if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1614                lookup_name_type_mask |= eFunctionNameTypeSelector;
1615
1616            CPPLanguageRuntime::MethodName cpp_method (name);
1617            llvm::StringRef basename (cpp_method.GetBasename());
1618            if (basename.empty())
1619            {
1620                if (CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1621                    lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1622            }
1623            else
1624            {
1625                base_name_start = basename.data();
1626                base_name_end = base_name_start + basename.size();
1627                lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1628            }
1629        }
1630    }
1631    else
1632    {
1633        lookup_name_type_mask = name_type_mask;
1634        if (lookup_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
1635        {
1636            // If they've asked for a CPP method or function name and it can't be that, we don't
1637            // even need to search for CPP methods or names.
1638            CPPLanguageRuntime::MethodName cpp_method (name);
1639            if (cpp_method.IsValid())
1640            {
1641                llvm::StringRef basename (cpp_method.GetBasename());
1642                base_name_start = basename.data();
1643                base_name_end = base_name_start + basename.size();
1644
1645                if (!cpp_method.GetQualifiers().empty())
1646                {
1647                    // There is a "const" or other qualifer following the end of the fucntion parens,
1648                    // this can't be a eFunctionNameTypeBase
1649                    lookup_name_type_mask &= ~(eFunctionNameTypeBase);
1650                    if (lookup_name_type_mask == eFunctionNameTypeNone)
1651                        return;
1652                }
1653            }
1654            else
1655            {
1656                if (!CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1657                {
1658                    lookup_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
1659                    if (lookup_name_type_mask == eFunctionNameTypeNone)
1660                        return;
1661                }
1662            }
1663        }
1664
1665        if (lookup_name_type_mask & eFunctionNameTypeSelector)
1666        {
1667            if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1668            {
1669                lookup_name_type_mask &= ~(eFunctionNameTypeSelector);
1670                if (lookup_name_type_mask == eFunctionNameTypeNone)
1671                    return;
1672            }
1673        }
1674    }
1675
1676    if (base_name_start &&
1677        base_name_end &&
1678        base_name_start != name_cstr &&
1679        base_name_start < base_name_end)
1680    {
1681        // The name supplied was a partial C++ path like "a::count". In this case we want to do a
1682        // lookup on the basename "count" and then make sure any matching results contain "a::count"
1683        // so that it would match "b::a::count" and "a::count". This is why we set "match_name_after_lookup"
1684        // to true
1685        lookup_name.SetCStringWithLength(base_name_start, base_name_end - base_name_start);
1686        match_name_after_lookup = true;
1687    }
1688    else
1689    {
1690        // The name is already correct, just use the exact name as supplied, and we won't need
1691        // to check if any matches contain "name"
1692        lookup_name = name;
1693        match_name_after_lookup = false;
1694    }
1695}
1696