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