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