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