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