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