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