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