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