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