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/Core/Error.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/DataBuffer.h"
13 #include "lldb/Core/DataBufferHeap.h"
14 #include "lldb/Core/Log.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/RegularExpression.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Core/StreamString.h"
20 #include "lldb/Core/Timer.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Host/Symbols.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/ScriptInterpreter.h"
25 #include "lldb/lldb-private-log.h"
26 #include "lldb/Symbol/CompileUnit.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolVendor.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/Target.h"
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 
36 // Shared pointers to modules track module lifetimes in
37 // targets and in the global module, but this collection
38 // will track all module objects that are still alive
39 typedef std::vector<Module *> ModuleCollection;
40 
41 static ModuleCollection &
42 GetModuleCollection()
43 {
44     // This module collection needs to live past any module, so we could either make it a
45     // shared pointer in each module or just leak is.  Since it is only an empty vector by
46     // the time all the modules have gone away, we just leak it for now.  If we decide this
47     // is a big problem we can introduce a Finalize method that will tear everything down in
48     // a predictable order.
49 
50     static ModuleCollection *g_module_collection = NULL;
51     if (g_module_collection == NULL)
52         g_module_collection = new ModuleCollection();
53 
54     return *g_module_collection;
55 }
56 
57 Mutex *
58 Module::GetAllocationModuleCollectionMutex()
59 {
60     // NOTE: The mutex below must be leaked since the global module list in
61     // the ModuleList class will get torn at some point, and we can't know
62     // if it will tear itself down before the "g_module_collection_mutex" below
63     // will. So we leak a Mutex object below to safeguard against that
64 
65     static Mutex *g_module_collection_mutex = NULL;
66     if (g_module_collection_mutex == NULL)
67         g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
68     return g_module_collection_mutex;
69 }
70 
71 size_t
72 Module::GetNumberAllocatedModules ()
73 {
74     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
75     return GetModuleCollection().size();
76 }
77 
78 Module *
79 Module::GetAllocatedModuleAtIndex (size_t idx)
80 {
81     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
82     ModuleCollection &modules = GetModuleCollection();
83     if (idx < modules.size())
84         return modules[idx];
85     return NULL;
86 }
87 #if 0
88 
89 // These functions help us to determine if modules are still loaded, yet don't require that
90 // you have a command interpreter and can easily be called from an external debugger.
91 namespace lldb {
92 
93     void
94     ClearModuleInfo (void)
95     {
96         const bool mandatory = true;
97         ModuleList::RemoveOrphanSharedModules(mandatory);
98     }
99 
100     void
101     DumpModuleInfo (void)
102     {
103         Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
104         ModuleCollection &modules = GetModuleCollection();
105         const size_t count = modules.size();
106         printf ("%s: %llu modules:\n", __PRETTY_FUNCTION__, (uint64_t)count);
107         for (size_t i=0; i<count; ++i)
108         {
109 
110             StreamString strm;
111             Module *module = modules[i];
112             const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
113             module->GetDescription(&strm, eDescriptionLevelFull);
114             printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
115                     module,
116                     in_shared_module_list,
117                     (uint32_t)module->use_count(),
118                     strm.GetString().c_str());
119         }
120     }
121 }
122 
123 #endif
124 
125 Module::Module (const ModuleSpec &module_spec) :
126     m_mutex (Mutex::eMutexTypeRecursive),
127     m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
128     m_arch (module_spec.GetArchitecture()),
129     m_uuid (),
130     m_file (module_spec.GetFileSpec()),
131     m_platform_file(module_spec.GetPlatformFileSpec()),
132     m_symfile_spec (module_spec.GetSymbolFileSpec()),
133     m_object_name (module_spec.GetObjectName()),
134     m_object_offset (module_spec.GetObjectOffset()),
135     m_objfile_sp (),
136     m_symfile_ap (),
137     m_ast (),
138     m_source_mappings (),
139     m_did_load_objfile (false),
140     m_did_load_symbol_vendor (false),
141     m_did_parse_uuid (false),
142     m_did_init_ast (false),
143     m_is_dynamic_loader_module (false),
144     m_file_has_changed (false),
145     m_first_file_changed_log (false)
146 {
147     // Scope for locker below...
148     {
149         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
150         GetModuleCollection().push_back(this);
151     }
152 
153     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
154     if (log)
155         log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
156                      this,
157                      m_arch.GetArchitectureName(),
158                      m_file.GetDirectory().AsCString(""),
159                      m_file.GetFilename().AsCString(""),
160                      m_object_name.IsEmpty() ? "" : "(",
161                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
162                      m_object_name.IsEmpty() ? "" : ")");
163 }
164 
165 Module::Module(const FileSpec& file_spec,
166                const ArchSpec& arch,
167                const ConstString *object_name,
168                off_t object_offset) :
169     m_mutex (Mutex::eMutexTypeRecursive),
170     m_mod_time (file_spec.GetModificationTime()),
171     m_arch (arch),
172     m_uuid (),
173     m_file (file_spec),
174     m_platform_file(),
175     m_symfile_spec (),
176     m_object_name (),
177     m_object_offset (object_offset),
178     m_objfile_sp (),
179     m_symfile_ap (),
180     m_ast (),
181     m_source_mappings (),
182     m_did_load_objfile (false),
183     m_did_load_symbol_vendor (false),
184     m_did_parse_uuid (false),
185     m_did_init_ast (false),
186     m_is_dynamic_loader_module (false),
187     m_file_has_changed (false),
188     m_first_file_changed_log (false)
189 {
190     // Scope for locker below...
191     {
192         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
193         GetModuleCollection().push_back(this);
194     }
195 
196     if (object_name)
197         m_object_name = *object_name;
198     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
199     if (log)
200         log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
201                      this,
202                      m_arch.GetArchitectureName(),
203                      m_file.GetDirectory().AsCString(""),
204                      m_file.GetFilename().AsCString(""),
205                      m_object_name.IsEmpty() ? "" : "(",
206                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
207                      m_object_name.IsEmpty() ? "" : ")");
208 }
209 
210 Module::~Module()
211 {
212     // Scope for locker below...
213     {
214         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
215         ModuleCollection &modules = GetModuleCollection();
216         ModuleCollection::iterator end = modules.end();
217         ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
218         assert (pos != end);
219         modules.erase(pos);
220     }
221     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
222     if (log)
223         log->Printf ("%p Module::~Module((%s) '%s/%s%s%s%s')",
224                      this,
225                      m_arch.GetArchitectureName(),
226                      m_file.GetDirectory().AsCString(""),
227                      m_file.GetFilename().AsCString(""),
228                      m_object_name.IsEmpty() ? "" : "(",
229                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
230                      m_object_name.IsEmpty() ? "" : ")");
231     // Release any auto pointers before we start tearing down our member
232     // variables since the object file and symbol files might need to make
233     // function calls back into this module object. The ordering is important
234     // here because symbol files can require the module object file. So we tear
235     // down the symbol file first, then the object file.
236     m_symfile_ap.reset();
237     m_objfile_sp.reset();
238 }
239 
240 ObjectFile *
241 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
242 {
243     if (m_objfile_sp)
244     {
245         error.SetErrorString ("object file already exists");
246     }
247     else
248     {
249         Mutex::Locker locker (m_mutex);
250         if (process_sp)
251         {
252             m_did_load_objfile = true;
253             std::auto_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
254             Error readmem_error;
255             const size_t bytes_read = process_sp->ReadMemory (header_addr,
256                                                               data_ap->GetBytes(),
257                                                               data_ap->GetByteSize(),
258                                                               readmem_error);
259             if (bytes_read == 512)
260             {
261                 DataBufferSP data_sp(data_ap.release());
262                 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
263                 if (m_objfile_sp)
264                 {
265                     StreamString s;
266                     s.Printf("0x%16.16llx", header_addr);
267                     m_object_name.SetCString (s.GetData());
268 
269                     // Once we get the object file, update our module with the object file's
270                     // architecture since it might differ in vendor/os if some parts were
271                     // unknown.
272                     m_objfile_sp->GetArchitecture (m_arch);
273                 }
274                 else
275                 {
276                     error.SetErrorString ("unable to find suitable object file plug-in");
277                 }
278             }
279             else
280             {
281                 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
282             }
283         }
284         else
285         {
286             error.SetErrorString ("invalid process");
287         }
288     }
289     return m_objfile_sp.get();
290 }
291 
292 
293 const lldb_private::UUID&
294 Module::GetUUID()
295 {
296     Mutex::Locker locker (m_mutex);
297     if (m_did_parse_uuid == false)
298     {
299         ObjectFile * obj_file = GetObjectFile ();
300 
301         if (obj_file != NULL)
302         {
303             obj_file->GetUUID(&m_uuid);
304             m_did_parse_uuid = true;
305         }
306     }
307     return m_uuid;
308 }
309 
310 ClangASTContext &
311 Module::GetClangASTContext ()
312 {
313     Mutex::Locker locker (m_mutex);
314     if (m_did_init_ast == false)
315     {
316         ObjectFile * objfile = GetObjectFile();
317         ArchSpec object_arch;
318         if (objfile && objfile->GetArchitecture(object_arch))
319         {
320             m_did_init_ast = true;
321 
322             // LLVM wants this to be set to iOS or MacOSX; if we're working on
323             // a bare-boards type image, change the triple for llvm's benefit.
324             if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
325                 && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
326             {
327                 if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
328                     object_arch.GetTriple().getArch() == llvm::Triple::thumb)
329                 {
330                     object_arch.GetTriple().setOS(llvm::Triple::IOS);
331                 }
332                 else
333                 {
334                     object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
335                 }
336             }
337             m_ast.SetArchitecture (object_arch);
338         }
339     }
340     return m_ast;
341 }
342 
343 void
344 Module::ParseAllDebugSymbols()
345 {
346     Mutex::Locker locker (m_mutex);
347     uint32_t num_comp_units = GetNumCompileUnits();
348     if (num_comp_units == 0)
349         return;
350 
351     SymbolContext sc;
352     sc.module_sp = shared_from_this();
353     uint32_t cu_idx;
354     SymbolVendor *symbols = GetSymbolVendor ();
355 
356     for (cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
357     {
358         sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
359         if (sc.comp_unit)
360         {
361             sc.function = NULL;
362             symbols->ParseVariablesForContext(sc);
363 
364             symbols->ParseCompileUnitFunctions(sc);
365 
366             uint32_t func_idx;
367             for (func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
368             {
369                 symbols->ParseFunctionBlocks(sc);
370 
371                 // Parse the variables for this function and all its blocks
372                 symbols->ParseVariablesForContext(sc);
373             }
374 
375 
376             // Parse all types for this compile unit
377             sc.function = NULL;
378             symbols->ParseTypes(sc);
379         }
380     }
381 }
382 
383 void
384 Module::CalculateSymbolContext(SymbolContext* sc)
385 {
386     sc->module_sp = shared_from_this();
387 }
388 
389 ModuleSP
390 Module::CalculateSymbolContextModule ()
391 {
392     return shared_from_this();
393 }
394 
395 void
396 Module::DumpSymbolContext(Stream *s)
397 {
398     s->Printf(", Module{%p}", this);
399 }
400 
401 uint32_t
402 Module::GetNumCompileUnits()
403 {
404     Mutex::Locker locker (m_mutex);
405     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
406     SymbolVendor *symbols = GetSymbolVendor ();
407     if (symbols)
408         return symbols->GetNumCompileUnits();
409     return 0;
410 }
411 
412 CompUnitSP
413 Module::GetCompileUnitAtIndex (uint32_t index)
414 {
415     Mutex::Locker locker (m_mutex);
416     uint32_t num_comp_units = GetNumCompileUnits ();
417     CompUnitSP cu_sp;
418 
419     if (index < num_comp_units)
420     {
421         SymbolVendor *symbols = GetSymbolVendor ();
422         if (symbols)
423             cu_sp = symbols->GetCompileUnitAtIndex(index);
424     }
425     return cu_sp;
426 }
427 
428 bool
429 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
430 {
431     Mutex::Locker locker (m_mutex);
432     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%llx)", vm_addr);
433     ObjectFile* ofile = GetObjectFile();
434     if (ofile)
435         return so_addr.ResolveAddressUsingFileSections(vm_addr, ofile->GetSectionList());
436     return false;
437 }
438 
439 uint32_t
440 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
441 {
442     Mutex::Locker locker (m_mutex);
443     uint32_t resolved_flags = 0;
444 
445     // Clear the result symbol context in case we don't find anything
446     sc.Clear();
447 
448     // Get the section from the section/offset address.
449     SectionSP section_sp (so_addr.GetSection());
450 
451     // Make sure the section matches this module before we try and match anything
452     if (section_sp && section_sp->GetModule().get() == this)
453     {
454         // If the section offset based address resolved itself, then this
455         // is the right module.
456         sc.module_sp = shared_from_this();
457         resolved_flags |= eSymbolContextModule;
458 
459         // Resolve the compile unit, function, block, line table or line
460         // entry if requested.
461         if (resolve_scope & eSymbolContextCompUnit    ||
462             resolve_scope & eSymbolContextFunction    ||
463             resolve_scope & eSymbolContextBlock       ||
464             resolve_scope & eSymbolContextLineEntry   )
465         {
466             SymbolVendor *symbols = GetSymbolVendor ();
467             if (symbols)
468                 resolved_flags |= symbols->ResolveSymbolContext (so_addr, resolve_scope, sc);
469         }
470 
471         // Resolve the symbol if requested, but don't re-look it up if we've already found it.
472         if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
473         {
474             ObjectFile* ofile = GetObjectFile();
475             if (ofile)
476             {
477                 Symtab *symtab = ofile->GetSymtab();
478                 if (symtab)
479                 {
480                     if (so_addr.IsSectionOffset())
481                     {
482                         sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
483                         if (sc.symbol)
484                             resolved_flags |= eSymbolContextSymbol;
485                     }
486                 }
487             }
488         }
489     }
490     return resolved_flags;
491 }
492 
493 uint32_t
494 Module::ResolveSymbolContextForFilePath
495 (
496     const char *file_path,
497     uint32_t line,
498     bool check_inlines,
499     uint32_t resolve_scope,
500     SymbolContextList& sc_list
501 )
502 {
503     FileSpec file_spec(file_path, false);
504     return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
505 }
506 
507 uint32_t
508 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
509 {
510     Mutex::Locker locker (m_mutex);
511     Timer scoped_timer(__PRETTY_FUNCTION__,
512                        "Module::ResolveSymbolContextForFilePath (%s%s%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
513                        file_spec.GetDirectory().AsCString(""),
514                        file_spec.GetDirectory() ? "/" : "",
515                        file_spec.GetFilename().AsCString(""),
516                        line,
517                        check_inlines ? "yes" : "no",
518                        resolve_scope);
519 
520     const uint32_t initial_count = sc_list.GetSize();
521 
522     SymbolVendor *symbols = GetSymbolVendor  ();
523     if (symbols)
524         symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
525 
526     return sc_list.GetSize() - initial_count;
527 }
528 
529 
530 uint32_t
531 Module::FindGlobalVariables(const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
532 {
533     SymbolVendor *symbols = GetSymbolVendor ();
534     if (symbols)
535         return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
536     return 0;
537 }
538 uint32_t
539 Module::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
540 {
541     SymbolVendor *symbols = GetSymbolVendor ();
542     if (symbols)
543         return symbols->FindGlobalVariables(regex, append, max_matches, variables);
544     return 0;
545 }
546 
547 uint32_t
548 Module::FindCompileUnits (const FileSpec &path,
549                           bool append,
550                           SymbolContextList &sc_list)
551 {
552     if (!append)
553         sc_list.Clear();
554 
555     const uint32_t start_size = sc_list.GetSize();
556     const uint32_t num_compile_units = GetNumCompileUnits();
557     SymbolContext sc;
558     sc.module_sp = shared_from_this();
559     const bool compare_directory = path.GetDirectory();
560     for (uint32_t i=0; i<num_compile_units; ++i)
561     {
562         sc.comp_unit = GetCompileUnitAtIndex(i).get();
563         if (sc.comp_unit)
564         {
565             if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
566                 sc_list.Append(sc);
567         }
568     }
569     return sc_list.GetSize() - start_size;
570 }
571 
572 uint32_t
573 Module::FindFunctions (const ConstString &name,
574                        const ClangNamespaceDecl *namespace_decl,
575                        uint32_t name_type_mask,
576                        bool include_symbols,
577                        bool include_inlines,
578                        bool append,
579                        SymbolContextList& sc_list)
580 {
581     if (!append)
582         sc_list.Clear();
583 
584     const uint32_t start_size = sc_list.GetSize();
585 
586     // Find all the functions (not symbols, but debug information functions...
587     SymbolVendor *symbols = GetSymbolVendor ();
588     if (symbols)
589         symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
590 
591     // Now check our symbol table for symbols that are code symbols if requested
592     if (include_symbols)
593     {
594         ObjectFile *objfile = GetObjectFile();
595         if (objfile)
596         {
597             Symtab *symtab = objfile->GetSymtab();
598             if (symtab)
599             {
600                 std::vector<uint32_t> symbol_indexes;
601                 symtab->FindAllSymbolsWithNameAndType (name, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
602                 const uint32_t num_matches = symbol_indexes.size();
603                 if (num_matches)
604                 {
605                     const bool merge_symbol_into_function = true;
606                     SymbolContext sc(this);
607                     for (uint32_t i=0; i<num_matches; i++)
608                     {
609                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
610                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
611                     }
612                 }
613             }
614         }
615     }
616     return sc_list.GetSize() - start_size;
617 }
618 
619 uint32_t
620 Module::FindFunctions (const RegularExpression& regex,
621                        bool include_symbols,
622                        bool include_inlines,
623                        bool append,
624                        SymbolContextList& sc_list)
625 {
626     if (!append)
627         sc_list.Clear();
628 
629     const uint32_t start_size = sc_list.GetSize();
630 
631     SymbolVendor *symbols = GetSymbolVendor ();
632     if (symbols)
633         symbols->FindFunctions(regex, include_inlines, append, sc_list);
634     // Now check our symbol table for symbols that are code symbols if requested
635     if (include_symbols)
636     {
637         ObjectFile *objfile = GetObjectFile();
638         if (objfile)
639         {
640             Symtab *symtab = objfile->GetSymtab();
641             if (symtab)
642             {
643                 std::vector<uint32_t> symbol_indexes;
644                 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
645                 const uint32_t num_matches = symbol_indexes.size();
646                 if (num_matches)
647                 {
648                     const bool merge_symbol_into_function = true;
649                     SymbolContext sc(this);
650                     for (uint32_t i=0; i<num_matches; i++)
651                     {
652                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
653                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
654                     }
655                 }
656             }
657         }
658     }
659     return sc_list.GetSize() - start_size;
660 }
661 
662 uint32_t
663 Module::FindTypes_Impl (const SymbolContext& sc,
664                         const ConstString &name,
665                         const ClangNamespaceDecl *namespace_decl,
666                         bool append,
667                         uint32_t max_matches,
668                         TypeList& types)
669 {
670     Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
671     if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
672     {
673         SymbolVendor *symbols = GetSymbolVendor ();
674         if (symbols)
675             return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
676     }
677     return 0;
678 }
679 
680 uint32_t
681 Module::FindTypesInNamespace (const SymbolContext& sc,
682                               const ConstString &type_name,
683                               const ClangNamespaceDecl *namespace_decl,
684                               uint32_t max_matches,
685                               TypeList& type_list)
686 {
687     const bool append = true;
688     return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
689 }
690 
691 uint32_t
692 Module::FindTypes (const SymbolContext& sc,
693                    const ConstString &name,
694                    bool exact_match,
695                    uint32_t max_matches,
696                    TypeList& types)
697 {
698     uint32_t num_matches = 0;
699     const char *type_name_cstr = name.GetCString();
700     std::string type_scope;
701     std::string type_basename;
702     const bool append = true;
703     TypeClass type_class = eTypeClassAny;
704     if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
705     {
706         // Check if "name" starts with "::" which means the qualified type starts
707         // from the root namespace and implies and exact match. The typenames we
708         // get back from clang do not start with "::" so we need to strip this off
709         // in order to get the qualfied names to match
710 
711         if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
712         {
713             type_scope.erase(0,2);
714             exact_match = true;
715         }
716         ConstString type_basename_const_str (type_basename.c_str());
717         if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
718         {
719             types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
720             num_matches = types.GetSize();
721         }
722     }
723     else
724     {
725         // The type is not in a namespace/class scope, just search for it by basename
726         if (type_class != eTypeClassAny)
727         {
728             // The "type_name_cstr" will have been modified if we have a valid type class
729             // prefix (like "struct", "class", "union", "typedef" etc).
730             num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
731             types.RemoveMismatchedTypes (type_class);
732             num_matches = types.GetSize();
733         }
734         else
735         {
736             num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
737         }
738     }
739 
740     return num_matches;
741 
742 }
743 
744 //uint32_t
745 //Module::FindTypes(const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, const char *udt_name, TypeList& types)
746 //{
747 //  Timer scoped_timer(__PRETTY_FUNCTION__);
748 //  SymbolVendor *symbols = GetSymbolVendor ();
749 //  if (symbols)
750 //      return symbols->FindTypes(sc, regex, append, max_matches, encoding, udt_name, types);
751 //  return 0;
752 //
753 //}
754 
755 SymbolVendor*
756 Module::GetSymbolVendor (bool can_create)
757 {
758     Mutex::Locker locker (m_mutex);
759     if (m_did_load_symbol_vendor == false && can_create)
760     {
761         ObjectFile *obj_file = GetObjectFile ();
762         if (obj_file != NULL)
763         {
764             Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
765             m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this()));
766             m_did_load_symbol_vendor = true;
767         }
768     }
769     return m_symfile_ap.get();
770 }
771 
772 void
773 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
774 {
775     // Container objects whose paths do not specify a file directly can call
776     // this function to correct the file and object names.
777     m_file = file;
778     m_mod_time = file.GetModificationTime();
779     m_object_name = object_name;
780 }
781 
782 const ArchSpec&
783 Module::GetArchitecture () const
784 {
785     return m_arch;
786 }
787 
788 void
789 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
790 {
791     Mutex::Locker locker (m_mutex);
792 
793     if (level >= eDescriptionLevelFull)
794     {
795         if (m_arch.IsValid())
796             s->Printf("(%s) ", m_arch.GetArchitectureName());
797     }
798 
799     if (level == eDescriptionLevelBrief)
800     {
801         const char *filename = m_file.GetFilename().GetCString();
802         if (filename)
803             s->PutCString (filename);
804     }
805     else
806     {
807         char path[PATH_MAX];
808         if (m_file.GetPath(path, sizeof(path)))
809             s->PutCString(path);
810     }
811 
812     const char *object_name = m_object_name.GetCString();
813     if (object_name)
814         s->Printf("(%s)", object_name);
815 }
816 
817 void
818 Module::ReportError (const char *format, ...)
819 {
820     if (format && format[0])
821     {
822         StreamString strm;
823         strm.PutCString("error: ");
824         GetDescription(&strm, lldb::eDescriptionLevelBrief);
825         strm.PutChar (' ');
826         va_list args;
827         va_start (args, format);
828         strm.PrintfVarArg(format, args);
829         va_end (args);
830 
831         const int format_len = strlen(format);
832         if (format_len > 0)
833         {
834             const char last_char = format[format_len-1];
835             if (last_char != '\n' || last_char != '\r')
836                 strm.EOL();
837         }
838         Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
839 
840     }
841 }
842 
843 bool
844 Module::FileHasChanged () const
845 {
846     if (m_file_has_changed == false)
847         m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
848     return m_file_has_changed;
849 }
850 
851 void
852 Module::ReportErrorIfModifyDetected (const char *format, ...)
853 {
854     if (m_first_file_changed_log == false)
855     {
856         if (FileHasChanged ())
857         {
858             m_first_file_changed_log = true;
859             if (format)
860             {
861                 StreamString strm;
862                 strm.PutCString("error: the object file ");
863                 GetDescription(&strm, lldb::eDescriptionLevelFull);
864                 strm.PutCString (" has been modified\n");
865 
866                 va_list args;
867                 va_start (args, format);
868                 strm.PrintfVarArg(format, args);
869                 va_end (args);
870 
871                 const int format_len = strlen(format);
872                 if (format_len > 0)
873                 {
874                     const char last_char = format[format_len-1];
875                     if (last_char != '\n' || last_char != '\r')
876                         strm.EOL();
877                 }
878                 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
879                 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
880             }
881         }
882     }
883 }
884 
885 void
886 Module::ReportWarning (const char *format, ...)
887 {
888     if (format && format[0])
889     {
890         StreamString strm;
891         strm.PutCString("warning: ");
892         GetDescription(&strm, lldb::eDescriptionLevelFull);
893         strm.PutChar (' ');
894 
895         va_list args;
896         va_start (args, format);
897         strm.PrintfVarArg(format, args);
898         va_end (args);
899 
900         const int format_len = strlen(format);
901         if (format_len > 0)
902         {
903             const char last_char = format[format_len-1];
904             if (last_char != '\n' || last_char != '\r')
905                 strm.EOL();
906         }
907         Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
908     }
909 }
910 
911 void
912 Module::LogMessage (Log *log, const char *format, ...)
913 {
914     if (log)
915     {
916         StreamString log_message;
917         GetDescription(&log_message, lldb::eDescriptionLevelFull);
918         log_message.PutCString (": ");
919         va_list args;
920         va_start (args, format);
921         log_message.PrintfVarArg (format, args);
922         va_end (args);
923         log->PutCString(log_message.GetString().c_str());
924     }
925 }
926 
927 void
928 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
929 {
930     if (log)
931     {
932         StreamString log_message;
933         GetDescription(&log_message, lldb::eDescriptionLevelFull);
934         log_message.PutCString (": ");
935         va_list args;
936         va_start (args, format);
937         log_message.PrintfVarArg (format, args);
938         va_end (args);
939         if (log->GetVerbose())
940             Host::Backtrace (log_message, 1024);
941         log->PutCString(log_message.GetString().c_str());
942     }
943 }
944 
945 void
946 Module::Dump(Stream *s)
947 {
948     Mutex::Locker locker (m_mutex);
949     //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
950     s->Indent();
951     s->Printf("Module %s/%s%s%s%s\n",
952               m_file.GetDirectory().AsCString(),
953               m_file.GetFilename().AsCString(),
954               m_object_name ? "(" : "",
955               m_object_name ? m_object_name.GetCString() : "",
956               m_object_name ? ")" : "");
957 
958     s->IndentMore();
959     ObjectFile *objfile = GetObjectFile ();
960 
961     if (objfile)
962         objfile->Dump(s);
963 
964     SymbolVendor *symbols = GetSymbolVendor ();
965 
966     if (symbols)
967         symbols->Dump(s);
968 
969     s->IndentLess();
970 }
971 
972 
973 TypeList*
974 Module::GetTypeList ()
975 {
976     SymbolVendor *symbols = GetSymbolVendor ();
977     if (symbols)
978         return &symbols->GetTypeList();
979     return NULL;
980 }
981 
982 const ConstString &
983 Module::GetObjectName() const
984 {
985     return m_object_name;
986 }
987 
988 ObjectFile *
989 Module::GetObjectFile()
990 {
991     Mutex::Locker locker (m_mutex);
992     if (m_did_load_objfile == false)
993     {
994         m_did_load_objfile = true;
995         Timer scoped_timer(__PRETTY_FUNCTION__,
996                            "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
997         DataBufferSP file_data_sp;
998         m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
999                                                &m_file,
1000                                                m_object_offset,
1001                                                m_file.GetByteSize(),
1002                                                file_data_sp);
1003         if (m_objfile_sp)
1004         {
1005 			// Once we get the object file, update our module with the object file's
1006 			// architecture since it might differ in vendor/os if some parts were
1007 			// unknown.
1008             m_objfile_sp->GetArchitecture (m_arch);
1009         }
1010     }
1011     return m_objfile_sp.get();
1012 }
1013 
1014 
1015 const Symbol *
1016 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1017 {
1018     Timer scoped_timer(__PRETTY_FUNCTION__,
1019                        "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1020                        name.AsCString(),
1021                        symbol_type);
1022     ObjectFile *objfile = GetObjectFile();
1023     if (objfile)
1024     {
1025         Symtab *symtab = objfile->GetSymtab();
1026         if (symtab)
1027             return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1028     }
1029     return NULL;
1030 }
1031 void
1032 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1033 {
1034     // No need to protect this call using m_mutex all other method calls are
1035     // already thread safe.
1036 
1037     size_t num_indices = symbol_indexes.size();
1038     if (num_indices > 0)
1039     {
1040         SymbolContext sc;
1041         CalculateSymbolContext (&sc);
1042         for (size_t i = 0; i < num_indices; i++)
1043         {
1044             sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1045             if (sc.symbol)
1046                 sc_list.Append (sc);
1047         }
1048     }
1049 }
1050 
1051 size_t
1052 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1053 {
1054     // No need to protect this call using m_mutex all other method calls are
1055     // already thread safe.
1056 
1057 
1058     Timer scoped_timer(__PRETTY_FUNCTION__,
1059                        "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1060                        name.AsCString(),
1061                        symbol_type);
1062     const size_t initial_size = sc_list.GetSize();
1063     ObjectFile *objfile = GetObjectFile ();
1064     if (objfile)
1065     {
1066         Symtab *symtab = objfile->GetSymtab();
1067         if (symtab)
1068         {
1069             std::vector<uint32_t> symbol_indexes;
1070             symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1071             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1072         }
1073     }
1074     return sc_list.GetSize() - initial_size;
1075 }
1076 
1077 size_t
1078 Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1079 {
1080     // No need to protect this call using m_mutex all other method calls are
1081     // already thread safe.
1082 
1083     Timer scoped_timer(__PRETTY_FUNCTION__,
1084                        "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1085                        regex.GetText(),
1086                        symbol_type);
1087     const size_t initial_size = sc_list.GetSize();
1088     ObjectFile *objfile = GetObjectFile ();
1089     if (objfile)
1090     {
1091         Symtab *symtab = objfile->GetSymtab();
1092         if (symtab)
1093         {
1094             std::vector<uint32_t> symbol_indexes;
1095             symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1096             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1097         }
1098     }
1099     return sc_list.GetSize() - initial_size;
1100 }
1101 
1102 const TimeValue &
1103 Module::GetModificationTime () const
1104 {
1105     return m_mod_time;
1106 }
1107 
1108 bool
1109 Module::IsExecutable ()
1110 {
1111     if (GetObjectFile() == NULL)
1112         return false;
1113     else
1114         return GetObjectFile()->IsExecutable();
1115 }
1116 
1117 bool
1118 Module::IsLoadedInTarget (Target *target)
1119 {
1120     ObjectFile *obj_file = GetObjectFile();
1121     if (obj_file)
1122     {
1123         SectionList *sections = obj_file->GetSectionList();
1124         if (sections != NULL)
1125         {
1126             size_t num_sections = sections->GetSize();
1127             for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1128             {
1129                 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1130                 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1131                 {
1132                     return true;
1133                 }
1134             }
1135         }
1136     }
1137     return false;
1138 }
1139 
1140 bool
1141 Module::LoadScriptingResourceInTarget (Target *target, Error& error)
1142 {
1143     if (!target)
1144     {
1145         error.SetErrorString("invalid destination Target");
1146         return false;
1147     }
1148 
1149     PlatformSP platform_sp(target->GetPlatform());
1150 
1151     if (!platform_sp)
1152     {
1153         error.SetErrorString("invalid Platform");
1154         return false;
1155     }
1156 
1157     ModuleSpec module_spec(GetFileSpec());
1158     FileSpec scripting_fspec = platform_sp->LocateExecutableScriptingResource(module_spec);
1159     Debugger &debugger(target->GetDebugger());
1160     if (scripting_fspec && scripting_fspec.Exists())
1161     {
1162         ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1163         if (script_interpreter)
1164         {
1165             StreamString scripting_stream;
1166             scripting_fspec.Dump(&scripting_stream);
1167             bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(), false, true, error);
1168             if (!did_load)
1169                 return false;
1170         }
1171         else
1172         {
1173             error.SetErrorString("invalid ScriptInterpreter");
1174             return false;
1175         }
1176     }
1177     return true;
1178 }
1179 
1180 bool
1181 Module::SetArchitecture (const ArchSpec &new_arch)
1182 {
1183     if (!m_arch.IsValid())
1184     {
1185         m_arch = new_arch;
1186         return true;
1187     }
1188     return m_arch == new_arch;
1189 }
1190 
1191 bool
1192 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1193 {
1194     size_t num_loaded_sections = 0;
1195     ObjectFile *objfile = GetObjectFile();
1196     if (objfile)
1197     {
1198         SectionList *section_list = objfile->GetSectionList ();
1199         if (section_list)
1200         {
1201             const size_t num_sections = section_list->GetSize();
1202             size_t sect_idx = 0;
1203             for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1204             {
1205                 // Iterate through the object file sections to find the
1206                 // first section that starts of file offset zero and that
1207                 // has bytes in the file...
1208                 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1209                 // Only load non-thread specific sections when given a slide
1210                 if (section_sp && !section_sp->IsThreadSpecific())
1211                 {
1212                     if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1213                         ++num_loaded_sections;
1214                 }
1215             }
1216         }
1217     }
1218     changed = num_loaded_sections > 0;
1219     return num_loaded_sections > 0;
1220 }
1221 
1222 
1223 bool
1224 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1225 {
1226     const UUID &uuid = module_ref.GetUUID();
1227 
1228     if (uuid.IsValid())
1229     {
1230         // If the UUID matches, then nothing more needs to match...
1231         if (uuid == GetUUID())
1232             return true;
1233         else
1234             return false;
1235     }
1236 
1237     const FileSpec &file_spec = module_ref.GetFileSpec();
1238     if (file_spec)
1239     {
1240         if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1241             return false;
1242     }
1243 
1244     const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1245     if (platform_file_spec)
1246     {
1247         if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), platform_file_spec.GetDirectory()))
1248             return false;
1249     }
1250 
1251     const ArchSpec &arch = module_ref.GetArchitecture();
1252     if (arch.IsValid())
1253     {
1254         if (m_arch != arch)
1255             return false;
1256     }
1257 
1258     const ConstString &object_name = module_ref.GetObjectName();
1259     if (object_name)
1260     {
1261         if (object_name != GetObjectName())
1262             return false;
1263     }
1264     return true;
1265 }
1266 
1267 bool
1268 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1269 {
1270     Mutex::Locker locker (m_mutex);
1271     return m_source_mappings.FindFile (orig_spec, new_spec);
1272 }
1273 
1274 bool
1275 Module::RemapSourceFile (const char *path, std::string &new_path) const
1276 {
1277     Mutex::Locker locker (m_mutex);
1278     return m_source_mappings.RemapPath(path, new_path);
1279 }
1280 
1281 uint32_t
1282 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1283 {
1284     ObjectFile *obj_file = GetObjectFile();
1285     if (obj_file)
1286         return obj_file->GetVersion (versions, num_versions);
1287 
1288     if (versions && num_versions)
1289     {
1290         for (uint32_t i=0; i<num_versions; ++i)
1291             versions[i] = UINT32_MAX;
1292     }
1293     return 0;
1294 }
1295