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/Module.h"
11 #include "lldb/Core/Log.h"
12 #include "lldb/Core/ModuleList.h"
13 #include "lldb/Core/RegularExpression.h"
14 #include "lldb/Core/StreamString.h"
15 #include "lldb/Core/Timer.h"
16 #include "lldb/Host/Host.h"
17 #include "lldb/lldb-private-log.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Symbol/SymbolVendor.h"
21 
22 using namespace lldb;
23 using namespace lldb_private;
24 
25 // Shared pointers to modules track module lifetimes in
26 // targets and in the global module, but this collection
27 // will track all module objects that are still alive
28 typedef std::vector<Module *> ModuleCollection;
29 
30 static ModuleCollection &
31 GetModuleCollection()
32 {
33     // This module collection needs to live past any module, so we could either make it a
34     // shared pointer in each module or just leak is.  Since it is only an empty vector by
35     // the time all the modules have gone away, we just leak it for now.  If we decide this
36     // is a big problem we can introduce a Finalize method that will tear everything down in
37     // a predictable order.
38 
39     static ModuleCollection *g_module_collection = NULL;
40     if (g_module_collection == NULL)
41         g_module_collection = new ModuleCollection();
42 
43     return *g_module_collection;
44 }
45 
46 Mutex *
47 Module::GetAllocationModuleCollectionMutex()
48 {
49     // NOTE: The mutex below must be leaked since the global module list in
50     // the ModuleList class will get torn at some point, and we can't know
51     // if it will tear itself down before the "g_module_collection_mutex" below
52     // will. So we leak a Mutex object below to safeguard against that
53 
54     static Mutex *g_module_collection_mutex = NULL;
55     if (g_module_collection_mutex == NULL)
56         g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
57     return g_module_collection_mutex;
58 }
59 
60 size_t
61 Module::GetNumberAllocatedModules ()
62 {
63     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
64     return GetModuleCollection().size();
65 }
66 
67 Module *
68 Module::GetAllocatedModuleAtIndex (size_t idx)
69 {
70     Mutex::Locker locker (GetAllocationModuleCollectionMutex());
71     ModuleCollection &modules = GetModuleCollection();
72     if (idx < modules.size())
73         return modules[idx];
74     return NULL;
75 }
76 #if 0
77 
78 // These functions help us to determine if modules are still loaded, yet don't require that
79 // you have a command interpreter and can easily be called from an external debugger.
80 namespace lldb {
81 
82     void
83     ClearModuleInfo (void)
84     {
85         ModuleList::RemoveOrphanSharedModules();
86     }
87 
88     void
89     DumpModuleInfo (void)
90     {
91         Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
92         ModuleCollection &modules = GetModuleCollection();
93         const size_t count = modules.size();
94         printf ("%s: %zu modules:\n", __PRETTY_FUNCTION__, count);
95         for (size_t i=0; i<count; ++i)
96         {
97 
98             StreamString strm;
99             Module *module = modules[i];
100             const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
101             module->GetDescription(&strm, eDescriptionLevelFull);
102             printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
103                     module,
104                     in_shared_module_list,
105                     (uint32_t)module->use_count(),
106                     strm.GetString().c_str());
107         }
108     }
109 }
110 
111 #endif
112 
113 
114 Module::Module(const FileSpec& file_spec, const ArchSpec& arch, const ConstString *object_name, off_t object_offset) :
115     m_mutex (Mutex::eMutexTypeRecursive),
116     m_mod_time (file_spec.GetModificationTime()),
117     m_arch (arch),
118     m_uuid (),
119     m_file (file_spec),
120     m_platform_file(),
121     m_object_name (),
122     m_object_offset (object_offset),
123     m_objfile_sp (),
124     m_symfile_ap (),
125     m_ast (),
126     m_did_load_objfile (false),
127     m_did_load_symbol_vendor (false),
128     m_did_parse_uuid (false),
129     m_did_init_ast (false),
130     m_is_dynamic_loader_module (false),
131     m_was_modified (false)
132 {
133     // Scope for locker below...
134     {
135         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
136         GetModuleCollection().push_back(this);
137     }
138 
139     if (object_name)
140         m_object_name = *object_name;
141     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
142     if (log)
143         log->Printf ("%p Module::Module((%s) '%s/%s%s%s%s')",
144                      this,
145                      m_arch.GetArchitectureName(),
146                      m_file.GetDirectory().AsCString(""),
147                      m_file.GetFilename().AsCString(""),
148                      m_object_name.IsEmpty() ? "" : "(",
149                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
150                      m_object_name.IsEmpty() ? "" : ")");
151 }
152 
153 Module::~Module()
154 {
155     // Scope for locker below...
156     {
157         Mutex::Locker locker (GetAllocationModuleCollectionMutex());
158         ModuleCollection &modules = GetModuleCollection();
159         ModuleCollection::iterator end = modules.end();
160         ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
161         if (pos != end)
162             modules.erase(pos);
163     }
164     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
165     if (log)
166         log->Printf ("%p Module::~Module((%s) '%s/%s%s%s%s')",
167                      this,
168                      m_arch.GetArchitectureName(),
169                      m_file.GetDirectory().AsCString(""),
170                      m_file.GetFilename().AsCString(""),
171                      m_object_name.IsEmpty() ? "" : "(",
172                      m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
173                      m_object_name.IsEmpty() ? "" : ")");
174     // Release any auto pointers before we start tearing down our member
175     // variables since the object file and symbol files might need to make
176     // function calls back into this module object. The ordering is important
177     // here because symbol files can require the module object file. So we tear
178     // down the symbol file first, then the object file.
179     m_symfile_ap.reset();
180     m_objfile_sp.reset();
181 }
182 
183 
184 const lldb_private::UUID&
185 Module::GetUUID()
186 {
187     Mutex::Locker locker (m_mutex);
188     if (m_did_parse_uuid == false)
189     {
190         ObjectFile * obj_file = GetObjectFile ();
191 
192         if (obj_file != NULL)
193         {
194             obj_file->GetUUID(&m_uuid);
195             m_did_parse_uuid = true;
196         }
197     }
198     return m_uuid;
199 }
200 
201 ClangASTContext &
202 Module::GetClangASTContext ()
203 {
204     Mutex::Locker locker (m_mutex);
205     if (m_did_init_ast == false)
206     {
207         ObjectFile * objfile = GetObjectFile();
208         ArchSpec object_arch;
209         if (objfile && objfile->GetArchitecture(object_arch))
210         {
211             m_did_init_ast = true;
212             m_ast.SetArchitecture (object_arch);
213         }
214     }
215     return m_ast;
216 }
217 
218 void
219 Module::ParseAllDebugSymbols()
220 {
221     Mutex::Locker locker (m_mutex);
222     uint32_t num_comp_units = GetNumCompileUnits();
223     if (num_comp_units == 0)
224         return;
225 
226     SymbolContext sc;
227     sc.module_sp = shared_from_this();
228     uint32_t cu_idx;
229     SymbolVendor *symbols = GetSymbolVendor ();
230 
231     for (cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
232     {
233         sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
234         if (sc.comp_unit)
235         {
236             sc.function = NULL;
237             symbols->ParseVariablesForContext(sc);
238 
239             symbols->ParseCompileUnitFunctions(sc);
240 
241             uint32_t func_idx;
242             for (func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
243             {
244                 symbols->ParseFunctionBlocks(sc);
245 
246                 // Parse the variables for this function and all its blocks
247                 symbols->ParseVariablesForContext(sc);
248             }
249 
250 
251             // Parse all types for this compile unit
252             sc.function = NULL;
253             symbols->ParseTypes(sc);
254         }
255     }
256 }
257 
258 void
259 Module::CalculateSymbolContext(SymbolContext* sc)
260 {
261     sc->module_sp = shared_from_this();
262 }
263 
264 Module *
265 Module::CalculateSymbolContextModule ()
266 {
267     return this;
268 }
269 
270 void
271 Module::DumpSymbolContext(Stream *s)
272 {
273     s->Printf(", Module{%p}", this);
274 }
275 
276 uint32_t
277 Module::GetNumCompileUnits()
278 {
279     Mutex::Locker locker (m_mutex);
280     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
281     SymbolVendor *symbols = GetSymbolVendor ();
282     if (symbols)
283         return symbols->GetNumCompileUnits();
284     return 0;
285 }
286 
287 CompUnitSP
288 Module::GetCompileUnitAtIndex (uint32_t index)
289 {
290     Mutex::Locker locker (m_mutex);
291     uint32_t num_comp_units = GetNumCompileUnits ();
292     CompUnitSP cu_sp;
293 
294     if (index < num_comp_units)
295     {
296         SymbolVendor *symbols = GetSymbolVendor ();
297         if (symbols)
298             cu_sp = symbols->GetCompileUnitAtIndex(index);
299     }
300     return cu_sp;
301 }
302 
303 bool
304 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
305 {
306     Mutex::Locker locker (m_mutex);
307     Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%llx)", vm_addr);
308     ObjectFile* ofile = GetObjectFile();
309     if (ofile)
310         return so_addr.ResolveAddressUsingFileSections(vm_addr, ofile->GetSectionList());
311     return false;
312 }
313 
314 uint32_t
315 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
316 {
317     Mutex::Locker locker (m_mutex);
318     uint32_t resolved_flags = 0;
319 
320     // Clear the result symbol context in case we don't find anything
321     sc.Clear();
322 
323     // Get the section from the section/offset address.
324     const Section *section = so_addr.GetSection();
325 
326     // Make sure the section matches this module before we try and match anything
327     if (section && section->GetModule() == this)
328     {
329         // If the section offset based address resolved itself, then this
330         // is the right module.
331         sc.module_sp = shared_from_this();
332         resolved_flags |= eSymbolContextModule;
333 
334         // Resolve the compile unit, function, block, line table or line
335         // entry if requested.
336         if (resolve_scope & eSymbolContextCompUnit    ||
337             resolve_scope & eSymbolContextFunction    ||
338             resolve_scope & eSymbolContextBlock       ||
339             resolve_scope & eSymbolContextLineEntry   )
340         {
341             SymbolVendor *symbols = GetSymbolVendor ();
342             if (symbols)
343                 resolved_flags |= symbols->ResolveSymbolContext (so_addr, resolve_scope, sc);
344         }
345 
346         // Resolve the symbol if requested, but don't re-look it up if we've already found it.
347         if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
348         {
349             ObjectFile* ofile = GetObjectFile();
350             if (ofile)
351             {
352                 Symtab *symtab = ofile->GetSymtab();
353                 if (symtab)
354                 {
355                     if (so_addr.IsSectionOffset())
356                     {
357                         sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
358                         if (sc.symbol)
359                             resolved_flags |= eSymbolContextSymbol;
360                     }
361                 }
362             }
363         }
364     }
365     return resolved_flags;
366 }
367 
368 uint32_t
369 Module::ResolveSymbolContextForFilePath
370 (
371     const char *file_path,
372     uint32_t line,
373     bool check_inlines,
374     uint32_t resolve_scope,
375     SymbolContextList& sc_list
376 )
377 {
378     FileSpec file_spec(file_path, false);
379     return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
380 }
381 
382 uint32_t
383 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
384 {
385     Mutex::Locker locker (m_mutex);
386     Timer scoped_timer(__PRETTY_FUNCTION__,
387                        "Module::ResolveSymbolContextForFilePath (%s%s%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
388                        file_spec.GetDirectory().AsCString(""),
389                        file_spec.GetDirectory() ? "/" : "",
390                        file_spec.GetFilename().AsCString(""),
391                        line,
392                        check_inlines ? "yes" : "no",
393                        resolve_scope);
394 
395     const uint32_t initial_count = sc_list.GetSize();
396 
397     SymbolVendor *symbols = GetSymbolVendor  ();
398     if (symbols)
399         symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
400 
401     return sc_list.GetSize() - initial_count;
402 }
403 
404 
405 uint32_t
406 Module::FindGlobalVariables(const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
407 {
408     SymbolVendor *symbols = GetSymbolVendor ();
409     if (symbols)
410         return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
411     return 0;
412 }
413 uint32_t
414 Module::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
415 {
416     SymbolVendor *symbols = GetSymbolVendor ();
417     if (symbols)
418         return symbols->FindGlobalVariables(regex, append, max_matches, variables);
419     return 0;
420 }
421 
422 uint32_t
423 Module::FindCompileUnits (const FileSpec &path,
424                           bool append,
425                           SymbolContextList &sc_list)
426 {
427     if (!append)
428         sc_list.Clear();
429 
430     const uint32_t start_size = sc_list.GetSize();
431     const uint32_t num_compile_units = GetNumCompileUnits();
432     SymbolContext sc;
433     sc.module_sp = shared_from_this();
434     const bool compare_directory = path.GetDirectory();
435     for (uint32_t i=0; i<num_compile_units; ++i)
436     {
437         sc.comp_unit = GetCompileUnitAtIndex(i).get();
438         if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
439             sc_list.Append(sc);
440     }
441     return sc_list.GetSize() - start_size;
442 }
443 
444 uint32_t
445 Module::FindFunctions (const ConstString &name,
446                        const ClangNamespaceDecl *namespace_decl,
447                        uint32_t name_type_mask,
448                        bool include_symbols,
449                        bool append,
450                        SymbolContextList& sc_list)
451 {
452     if (!append)
453         sc_list.Clear();
454 
455     const uint32_t start_size = sc_list.GetSize();
456 
457     // Find all the functions (not symbols, but debug information functions...
458     SymbolVendor *symbols = GetSymbolVendor ();
459     if (symbols)
460         symbols->FindFunctions(name, namespace_decl, name_type_mask, append, sc_list);
461 
462     // Now check our symbol table for symbols that are code symbols if requested
463     if (include_symbols)
464     {
465         ObjectFile *objfile = GetObjectFile();
466         if (objfile)
467         {
468             Symtab *symtab = objfile->GetSymtab();
469             if (symtab)
470             {
471                 std::vector<uint32_t> symbol_indexes;
472                 symtab->FindAllSymbolsWithNameAndType (name, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
473                 const uint32_t num_matches = symbol_indexes.size();
474                 if (num_matches)
475                 {
476                     const bool merge_symbol_into_function = true;
477                     SymbolContext sc(this);
478                     for (uint32_t i=0; i<num_matches; i++)
479                     {
480                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
481                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
482                     }
483                 }
484             }
485         }
486     }
487     return sc_list.GetSize() - start_size;
488 }
489 
490 uint32_t
491 Module::FindFunctions (const RegularExpression& regex,
492                        bool include_symbols,
493                        bool append,
494                        SymbolContextList& sc_list)
495 {
496     if (!append)
497         sc_list.Clear();
498 
499     const uint32_t start_size = sc_list.GetSize();
500 
501     SymbolVendor *symbols = GetSymbolVendor ();
502     if (symbols)
503         symbols->FindFunctions(regex, append, sc_list);
504     // Now check our symbol table for symbols that are code symbols if requested
505     if (include_symbols)
506     {
507         ObjectFile *objfile = GetObjectFile();
508         if (objfile)
509         {
510             Symtab *symtab = objfile->GetSymtab();
511             if (symtab)
512             {
513                 std::vector<uint32_t> symbol_indexes;
514                 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeCode, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
515                 const uint32_t num_matches = symbol_indexes.size();
516                 if (num_matches)
517                 {
518                     const bool merge_symbol_into_function = true;
519                     SymbolContext sc(this);
520                     for (uint32_t i=0; i<num_matches; i++)
521                     {
522                         sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
523                         sc_list.AppendIfUnique (sc, merge_symbol_into_function);
524                     }
525                 }
526             }
527         }
528     }
529     return sc_list.GetSize() - start_size;
530 }
531 
532 uint32_t
533 Module::FindTypes_Impl (const SymbolContext& sc, const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, TypeList& types)
534 {
535     Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
536     if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
537     {
538         SymbolVendor *symbols = GetSymbolVendor ();
539         if (symbols)
540             return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
541     }
542     return 0;
543 }
544 
545 // depending on implementation details, type lookup might fail because of
546 // embedded spurious namespace:: prefixes. this call strips them, paying
547 // attention to the fact that a type might have namespace'd type names as
548 // arguments to templates, and those must not be stripped off
549 static const char*
550 StripTypeName(const char* name_cstr)
551 {
552     // Protect against null c string.
553     if (!name_cstr)
554         return name_cstr;
555     const char* skip_namespace = strstr(name_cstr, "::");
556     const char* template_arg_char = strchr(name_cstr, '<');
557     while (skip_namespace != NULL)
558     {
559         if (template_arg_char != NULL &&
560             skip_namespace > template_arg_char) // but namespace'd template arguments are still good to go
561             break;
562         name_cstr = skip_namespace+2;
563         skip_namespace = strstr(name_cstr, "::");
564     }
565     return name_cstr;
566 }
567 
568 uint32_t
569 Module::FindTypes (const SymbolContext& sc,  const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, TypeList& types)
570 {
571     uint32_t retval = FindTypes_Impl(sc, name, namespace_decl, append, max_matches, types);
572 
573     if (retval == 0)
574     {
575         const char *orig_name = name.GetCString();
576         const char *stripped = StripTypeName(orig_name);
577         // Only do this lookup if StripTypeName has stripped the name:
578         if (stripped != orig_name)
579            return FindTypes_Impl(sc, ConstString(stripped), namespace_decl, append, max_matches, types);
580         else
581             return 0;
582     }
583     else
584         return retval;
585 
586 }
587 
588 //uint32_t
589 //Module::FindTypes(const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, const char *udt_name, TypeList& types)
590 //{
591 //  Timer scoped_timer(__PRETTY_FUNCTION__);
592 //  SymbolVendor *symbols = GetSymbolVendor ();
593 //  if (symbols)
594 //      return symbols->FindTypes(sc, regex, append, max_matches, encoding, udt_name, types);
595 //  return 0;
596 //
597 //}
598 
599 SymbolVendor*
600 Module::GetSymbolVendor (bool can_create)
601 {
602     Mutex::Locker locker (m_mutex);
603     if (m_did_load_symbol_vendor == false && can_create)
604     {
605         ObjectFile *obj_file = GetObjectFile ();
606         if (obj_file != NULL)
607         {
608             Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
609             m_symfile_ap.reset(SymbolVendor::FindPlugin(this));
610             m_did_load_symbol_vendor = true;
611         }
612     }
613     return m_symfile_ap.get();
614 }
615 
616 void
617 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
618 {
619     // Container objects whose paths do not specify a file directly can call
620     // this function to correct the file and object names.
621     m_file = file;
622     m_mod_time = file.GetModificationTime();
623     m_object_name = object_name;
624 }
625 
626 const ArchSpec&
627 Module::GetArchitecture () const
628 {
629     return m_arch;
630 }
631 
632 void
633 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
634 {
635     Mutex::Locker locker (m_mutex);
636 
637     if (level >= eDescriptionLevelFull)
638     {
639         if (m_arch.IsValid())
640             s->Printf("(%s) ", m_arch.GetArchitectureName());
641     }
642 
643     if (level == eDescriptionLevelBrief)
644     {
645         const char *filename = m_file.GetFilename().GetCString();
646         if (filename)
647             s->PutCString (filename);
648     }
649     else
650     {
651         char path[PATH_MAX];
652         if (m_file.GetPath(path, sizeof(path)))
653             s->PutCString(path);
654     }
655 
656     const char *object_name = m_object_name.GetCString();
657     if (object_name)
658         s->Printf("(%s)", object_name);
659 }
660 
661 void
662 Module::ReportError (const char *format, ...)
663 {
664     if (format && format[0])
665     {
666         StreamString strm;
667         strm.PutCString("error: ");
668         GetDescription(&strm, lldb::eDescriptionLevelBrief);
669         strm.PutChar (' ');
670         va_list args;
671         va_start (args, format);
672         strm.PrintfVarArg(format, args);
673         va_end (args);
674 
675         const int format_len = strlen(format);
676         if (format_len > 0)
677         {
678             const char last_char = format[format_len-1];
679             if (last_char != '\n' || last_char != '\r')
680                 strm.EOL();
681         }
682         Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
683 
684     }
685 }
686 
687 void
688 Module::ReportErrorIfModifyDetected (const char *format, ...)
689 {
690     if (!GetModified(true) && GetModified(false))
691     {
692         if (format)
693         {
694             StreamString strm;
695             strm.PutCString("error: the object file ");
696             GetDescription(&strm, lldb::eDescriptionLevelFull);
697             strm.PutCString (" has been modified\n");
698 
699             va_list args;
700             va_start (args, format);
701             strm.PrintfVarArg(format, args);
702             va_end (args);
703 
704             const int format_len = strlen(format);
705             if (format_len > 0)
706             {
707                 const char last_char = format[format_len-1];
708                 if (last_char != '\n' || last_char != '\r')
709                     strm.EOL();
710             }
711             strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
712             Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
713         }
714     }
715 }
716 
717 void
718 Module::ReportWarning (const char *format, ...)
719 {
720     if (format && format[0])
721     {
722         StreamString strm;
723         strm.PutCString("warning: ");
724         GetDescription(&strm, lldb::eDescriptionLevelFull);
725         strm.PutChar (' ');
726 
727         va_list args;
728         va_start (args, format);
729         strm.PrintfVarArg(format, args);
730         va_end (args);
731 
732         const int format_len = strlen(format);
733         if (format_len > 0)
734         {
735             const char last_char = format[format_len-1];
736             if (last_char != '\n' || last_char != '\r')
737                 strm.EOL();
738         }
739         Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
740     }
741 }
742 
743 void
744 Module::LogMessage (Log *log, const char *format, ...)
745 {
746     if (log)
747     {
748         StreamString log_message;
749         GetDescription(&log_message, lldb::eDescriptionLevelFull);
750         log_message.PutCString (": ");
751         va_list args;
752         va_start (args, format);
753         log_message.PrintfVarArg (format, args);
754         va_end (args);
755         log->PutCString(log_message.GetString().c_str());
756     }
757 }
758 
759 bool
760 Module::GetModified (bool use_cached_only)
761 {
762     if (m_was_modified == false && use_cached_only == false)
763     {
764         TimeValue curr_mod_time (m_file.GetModificationTime());
765         m_was_modified = curr_mod_time != m_mod_time;
766     }
767     return m_was_modified;
768 }
769 
770 bool
771 Module::SetModified (bool b)
772 {
773     const bool prev_value = m_was_modified;
774     m_was_modified = b;
775     return prev_value;
776 }
777 
778 
779 void
780 Module::Dump(Stream *s)
781 {
782     Mutex::Locker locker (m_mutex);
783     //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
784     s->Indent();
785     s->Printf("Module %s/%s%s%s%s\n",
786               m_file.GetDirectory().AsCString(),
787               m_file.GetFilename().AsCString(),
788               m_object_name ? "(" : "",
789               m_object_name ? m_object_name.GetCString() : "",
790               m_object_name ? ")" : "");
791 
792     s->IndentMore();
793     ObjectFile *objfile = GetObjectFile ();
794 
795     if (objfile)
796         objfile->Dump(s);
797 
798     SymbolVendor *symbols = GetSymbolVendor ();
799 
800     if (symbols)
801         symbols->Dump(s);
802 
803     s->IndentLess();
804 }
805 
806 
807 TypeList*
808 Module::GetTypeList ()
809 {
810     SymbolVendor *symbols = GetSymbolVendor ();
811     if (symbols)
812         return &symbols->GetTypeList();
813     return NULL;
814 }
815 
816 const ConstString &
817 Module::GetObjectName() const
818 {
819     return m_object_name;
820 }
821 
822 ObjectFile *
823 Module::GetObjectFile()
824 {
825     Mutex::Locker locker (m_mutex);
826     if (m_did_load_objfile == false)
827     {
828         m_did_load_objfile = true;
829         Timer scoped_timer(__PRETTY_FUNCTION__,
830                            "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
831         DataBufferSP file_data_sp;
832         m_objfile_sp = ObjectFile::FindPlugin(this, &m_file, m_object_offset, m_file.GetByteSize(), file_data_sp);
833         if (m_objfile_sp)
834         {
835 			// Once we get the object file, update our module with the object file's
836 			// architecture since it might differ in vendor/os if some parts were
837 			// unknown.
838             m_objfile_sp->GetArchitecture (m_arch);
839         }
840     }
841     return m_objfile_sp.get();
842 }
843 
844 
845 const Symbol *
846 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
847 {
848     Timer scoped_timer(__PRETTY_FUNCTION__,
849                        "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
850                        name.AsCString(),
851                        symbol_type);
852     ObjectFile *objfile = GetObjectFile();
853     if (objfile)
854     {
855         Symtab *symtab = objfile->GetSymtab();
856         if (symtab)
857             return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
858     }
859     return NULL;
860 }
861 void
862 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
863 {
864     // No need to protect this call using m_mutex all other method calls are
865     // already thread safe.
866 
867     size_t num_indices = symbol_indexes.size();
868     if (num_indices > 0)
869     {
870         SymbolContext sc;
871         CalculateSymbolContext (&sc);
872         for (size_t i = 0; i < num_indices; i++)
873         {
874             sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
875             if (sc.symbol)
876                 sc_list.Append (sc);
877         }
878     }
879 }
880 
881 size_t
882 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
883 {
884     // No need to protect this call using m_mutex all other method calls are
885     // already thread safe.
886 
887 
888     Timer scoped_timer(__PRETTY_FUNCTION__,
889                        "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
890                        name.AsCString(),
891                        symbol_type);
892     const size_t initial_size = sc_list.GetSize();
893     ObjectFile *objfile = GetObjectFile ();
894     if (objfile)
895     {
896         Symtab *symtab = objfile->GetSymtab();
897         if (symtab)
898         {
899             std::vector<uint32_t> symbol_indexes;
900             symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
901             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
902         }
903     }
904     return sc_list.GetSize() - initial_size;
905 }
906 
907 size_t
908 Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
909 {
910     // No need to protect this call using m_mutex all other method calls are
911     // already thread safe.
912 
913     Timer scoped_timer(__PRETTY_FUNCTION__,
914                        "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
915                        regex.GetText(),
916                        symbol_type);
917     const size_t initial_size = sc_list.GetSize();
918     ObjectFile *objfile = GetObjectFile ();
919     if (objfile)
920     {
921         Symtab *symtab = objfile->GetSymtab();
922         if (symtab)
923         {
924             std::vector<uint32_t> symbol_indexes;
925             symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
926             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
927         }
928     }
929     return sc_list.GetSize() - initial_size;
930 }
931 
932 const TimeValue &
933 Module::GetModificationTime () const
934 {
935     return m_mod_time;
936 }
937 
938 bool
939 Module::IsExecutable ()
940 {
941     if (GetObjectFile() == NULL)
942         return false;
943     else
944         return GetObjectFile()->IsExecutable();
945 }
946 
947 bool
948 Module::IsLoadedInTarget (Target *target)
949 {
950     ObjectFile *obj_file = GetObjectFile();
951     if (obj_file)
952     {
953         SectionList *sections = obj_file->GetSectionList();
954         if (sections != NULL)
955         {
956             size_t num_sections = sections->GetSize();
957             for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
958             {
959                 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
960                 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
961                 {
962                     return true;
963                 }
964             }
965         }
966     }
967     return false;
968 }
969 bool
970 Module::SetArchitecture (const ArchSpec &new_arch)
971 {
972     if (!m_arch.IsValid())
973     {
974         m_arch = new_arch;
975         return true;
976     }
977     return m_arch == new_arch;
978 }
979 
980