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     if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename))
700     {
701         // Check if "name" starts with "::" which means the qualified type starts
702         // from the root namespace and implies and exact match. The typenames we
703         // get back from clang do not start with "::" so we need to strip this off
704         // in order to get the qualfied names to match
705 
706         if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
707         {
708             type_scope.erase(0,2);
709             exact_match = true;
710         }
711         ConstString type_basename_const_str (type_basename.c_str());
712         if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
713         {
714             types.RemoveMismatchedTypes (type_scope, type_basename, exact_match);
715             num_matches = types.GetSize();
716         }
717     }
718     else
719     {
720         // The type is not in a namespace/class scope, just search for it by basename
721         num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
722     }
723 
724     return num_matches;
725 
726 }
727 
728 //uint32_t
729 //Module::FindTypes(const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, const char *udt_name, TypeList& types)
730 //{
731 //  Timer scoped_timer(__PRETTY_FUNCTION__);
732 //  SymbolVendor *symbols = GetSymbolVendor ();
733 //  if (symbols)
734 //      return symbols->FindTypes(sc, regex, append, max_matches, encoding, udt_name, types);
735 //  return 0;
736 //
737 //}
738 
739 SymbolVendor*
740 Module::GetSymbolVendor (bool can_create)
741 {
742     Mutex::Locker locker (m_mutex);
743     if (m_did_load_symbol_vendor == false && can_create)
744     {
745         ObjectFile *obj_file = GetObjectFile ();
746         if (obj_file != NULL)
747         {
748             Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
749             m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this()));
750             m_did_load_symbol_vendor = true;
751         }
752     }
753     return m_symfile_ap.get();
754 }
755 
756 void
757 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
758 {
759     // Container objects whose paths do not specify a file directly can call
760     // this function to correct the file and object names.
761     m_file = file;
762     m_mod_time = file.GetModificationTime();
763     m_object_name = object_name;
764 }
765 
766 const ArchSpec&
767 Module::GetArchitecture () const
768 {
769     return m_arch;
770 }
771 
772 void
773 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
774 {
775     Mutex::Locker locker (m_mutex);
776 
777     if (level >= eDescriptionLevelFull)
778     {
779         if (m_arch.IsValid())
780             s->Printf("(%s) ", m_arch.GetArchitectureName());
781     }
782 
783     if (level == eDescriptionLevelBrief)
784     {
785         const char *filename = m_file.GetFilename().GetCString();
786         if (filename)
787             s->PutCString (filename);
788     }
789     else
790     {
791         char path[PATH_MAX];
792         if (m_file.GetPath(path, sizeof(path)))
793             s->PutCString(path);
794     }
795 
796     const char *object_name = m_object_name.GetCString();
797     if (object_name)
798         s->Printf("(%s)", object_name);
799 }
800 
801 void
802 Module::ReportError (const char *format, ...)
803 {
804     if (format && format[0])
805     {
806         StreamString strm;
807         strm.PutCString("error: ");
808         GetDescription(&strm, lldb::eDescriptionLevelBrief);
809         strm.PutChar (' ');
810         va_list args;
811         va_start (args, format);
812         strm.PrintfVarArg(format, args);
813         va_end (args);
814 
815         const int format_len = strlen(format);
816         if (format_len > 0)
817         {
818             const char last_char = format[format_len-1];
819             if (last_char != '\n' || last_char != '\r')
820                 strm.EOL();
821         }
822         Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
823 
824     }
825 }
826 
827 bool
828 Module::FileHasChanged () const
829 {
830     if (m_file_has_changed == false)
831         m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
832     return m_file_has_changed;
833 }
834 
835 void
836 Module::ReportErrorIfModifyDetected (const char *format, ...)
837 {
838     if (m_first_file_changed_log == false)
839     {
840         if (FileHasChanged ())
841         {
842             m_first_file_changed_log = true;
843             if (format)
844             {
845                 StreamString strm;
846                 strm.PutCString("error: the object file ");
847                 GetDescription(&strm, lldb::eDescriptionLevelFull);
848                 strm.PutCString (" has been modified\n");
849 
850                 va_list args;
851                 va_start (args, format);
852                 strm.PrintfVarArg(format, args);
853                 va_end (args);
854 
855                 const int format_len = strlen(format);
856                 if (format_len > 0)
857                 {
858                     const char last_char = format[format_len-1];
859                     if (last_char != '\n' || last_char != '\r')
860                         strm.EOL();
861                 }
862                 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
863                 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
864             }
865         }
866     }
867 }
868 
869 void
870 Module::ReportWarning (const char *format, ...)
871 {
872     if (format && format[0])
873     {
874         StreamString strm;
875         strm.PutCString("warning: ");
876         GetDescription(&strm, lldb::eDescriptionLevelFull);
877         strm.PutChar (' ');
878 
879         va_list args;
880         va_start (args, format);
881         strm.PrintfVarArg(format, args);
882         va_end (args);
883 
884         const int format_len = strlen(format);
885         if (format_len > 0)
886         {
887             const char last_char = format[format_len-1];
888             if (last_char != '\n' || last_char != '\r')
889                 strm.EOL();
890         }
891         Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
892     }
893 }
894 
895 void
896 Module::LogMessage (Log *log, const char *format, ...)
897 {
898     if (log)
899     {
900         StreamString log_message;
901         GetDescription(&log_message, lldb::eDescriptionLevelFull);
902         log_message.PutCString (": ");
903         va_list args;
904         va_start (args, format);
905         log_message.PrintfVarArg (format, args);
906         va_end (args);
907         log->PutCString(log_message.GetString().c_str());
908     }
909 }
910 
911 void
912 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
913 {
914     if (log)
915     {
916         StreamString log_message;
917         GetDescription(&log_message, lldb::eDescriptionLevelFull);
918         log_message.PutCString (": ");
919         va_list args;
920         va_start (args, format);
921         log_message.PrintfVarArg (format, args);
922         va_end (args);
923         if (log->GetVerbose())
924             Host::Backtrace (log_message, 1024);
925         log->PutCString(log_message.GetString().c_str());
926     }
927 }
928 
929 void
930 Module::Dump(Stream *s)
931 {
932     Mutex::Locker locker (m_mutex);
933     //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
934     s->Indent();
935     s->Printf("Module %s/%s%s%s%s\n",
936               m_file.GetDirectory().AsCString(),
937               m_file.GetFilename().AsCString(),
938               m_object_name ? "(" : "",
939               m_object_name ? m_object_name.GetCString() : "",
940               m_object_name ? ")" : "");
941 
942     s->IndentMore();
943     ObjectFile *objfile = GetObjectFile ();
944 
945     if (objfile)
946         objfile->Dump(s);
947 
948     SymbolVendor *symbols = GetSymbolVendor ();
949 
950     if (symbols)
951         symbols->Dump(s);
952 
953     s->IndentLess();
954 }
955 
956 
957 TypeList*
958 Module::GetTypeList ()
959 {
960     SymbolVendor *symbols = GetSymbolVendor ();
961     if (symbols)
962         return &symbols->GetTypeList();
963     return NULL;
964 }
965 
966 const ConstString &
967 Module::GetObjectName() const
968 {
969     return m_object_name;
970 }
971 
972 ObjectFile *
973 Module::GetObjectFile()
974 {
975     Mutex::Locker locker (m_mutex);
976     if (m_did_load_objfile == false)
977     {
978         m_did_load_objfile = true;
979         Timer scoped_timer(__PRETTY_FUNCTION__,
980                            "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
981         DataBufferSP file_data_sp;
982         m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
983                                                &m_file,
984                                                m_object_offset,
985                                                m_file.GetByteSize(),
986                                                file_data_sp);
987         if (m_objfile_sp)
988         {
989 			// Once we get the object file, update our module with the object file's
990 			// architecture since it might differ in vendor/os if some parts were
991 			// unknown.
992             m_objfile_sp->GetArchitecture (m_arch);
993         }
994     }
995     return m_objfile_sp.get();
996 }
997 
998 
999 const Symbol *
1000 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1001 {
1002     Timer scoped_timer(__PRETTY_FUNCTION__,
1003                        "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1004                        name.AsCString(),
1005                        symbol_type);
1006     ObjectFile *objfile = GetObjectFile();
1007     if (objfile)
1008     {
1009         Symtab *symtab = objfile->GetSymtab();
1010         if (symtab)
1011             return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1012     }
1013     return NULL;
1014 }
1015 void
1016 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1017 {
1018     // No need to protect this call using m_mutex all other method calls are
1019     // already thread safe.
1020 
1021     size_t num_indices = symbol_indexes.size();
1022     if (num_indices > 0)
1023     {
1024         SymbolContext sc;
1025         CalculateSymbolContext (&sc);
1026         for (size_t i = 0; i < num_indices; i++)
1027         {
1028             sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1029             if (sc.symbol)
1030                 sc_list.Append (sc);
1031         }
1032     }
1033 }
1034 
1035 size_t
1036 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1037 {
1038     // No need to protect this call using m_mutex all other method calls are
1039     // already thread safe.
1040 
1041 
1042     Timer scoped_timer(__PRETTY_FUNCTION__,
1043                        "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1044                        name.AsCString(),
1045                        symbol_type);
1046     const size_t initial_size = sc_list.GetSize();
1047     ObjectFile *objfile = GetObjectFile ();
1048     if (objfile)
1049     {
1050         Symtab *symtab = objfile->GetSymtab();
1051         if (symtab)
1052         {
1053             std::vector<uint32_t> symbol_indexes;
1054             symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1055             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1056         }
1057     }
1058     return sc_list.GetSize() - initial_size;
1059 }
1060 
1061 size_t
1062 Module::FindSymbolsMatchingRegExAndType (const RegularExpression &regex, SymbolType symbol_type, SymbolContextList &sc_list)
1063 {
1064     // No need to protect this call using m_mutex all other method calls are
1065     // already thread safe.
1066 
1067     Timer scoped_timer(__PRETTY_FUNCTION__,
1068                        "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1069                        regex.GetText(),
1070                        symbol_type);
1071     const size_t initial_size = sc_list.GetSize();
1072     ObjectFile *objfile = GetObjectFile ();
1073     if (objfile)
1074     {
1075         Symtab *symtab = objfile->GetSymtab();
1076         if (symtab)
1077         {
1078             std::vector<uint32_t> symbol_indexes;
1079             symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1080             SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1081         }
1082     }
1083     return sc_list.GetSize() - initial_size;
1084 }
1085 
1086 const TimeValue &
1087 Module::GetModificationTime () const
1088 {
1089     return m_mod_time;
1090 }
1091 
1092 bool
1093 Module::IsExecutable ()
1094 {
1095     if (GetObjectFile() == NULL)
1096         return false;
1097     else
1098         return GetObjectFile()->IsExecutable();
1099 }
1100 
1101 bool
1102 Module::IsLoadedInTarget (Target *target)
1103 {
1104     ObjectFile *obj_file = GetObjectFile();
1105     if (obj_file)
1106     {
1107         SectionList *sections = obj_file->GetSectionList();
1108         if (sections != NULL)
1109         {
1110             size_t num_sections = sections->GetSize();
1111             for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1112             {
1113                 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1114                 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1115                 {
1116                     return true;
1117                 }
1118             }
1119         }
1120     }
1121     return false;
1122 }
1123 bool
1124 Module::SetArchitecture (const ArchSpec &new_arch)
1125 {
1126     if (!m_arch.IsValid())
1127     {
1128         m_arch = new_arch;
1129         return true;
1130     }
1131     return m_arch == new_arch;
1132 }
1133 
1134 bool
1135 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1136 {
1137     size_t num_loaded_sections = 0;
1138     ObjectFile *objfile = GetObjectFile();
1139     if (objfile)
1140     {
1141         SectionList *section_list = objfile->GetSectionList ();
1142         if (section_list)
1143         {
1144             const size_t num_sections = section_list->GetSize();
1145             size_t sect_idx = 0;
1146             for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1147             {
1148                 // Iterate through the object file sections to find the
1149                 // first section that starts of file offset zero and that
1150                 // has bytes in the file...
1151                 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1152                 // Only load non-thread specific sections when given a slide
1153                 if (section_sp && !section_sp->IsThreadSpecific())
1154                 {
1155                     if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1156                         ++num_loaded_sections;
1157                 }
1158             }
1159         }
1160     }
1161     changed = num_loaded_sections > 0;
1162     return num_loaded_sections > 0;
1163 }
1164 
1165 
1166 bool
1167 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1168 {
1169     const UUID &uuid = module_ref.GetUUID();
1170 
1171     if (uuid.IsValid())
1172     {
1173         // If the UUID matches, then nothing more needs to match...
1174         if (uuid == GetUUID())
1175             return true;
1176         else
1177             return false;
1178     }
1179 
1180     const FileSpec &file_spec = module_ref.GetFileSpec();
1181     if (file_spec)
1182     {
1183         if (!FileSpec::Equal (file_spec, m_file, file_spec.GetDirectory()))
1184             return false;
1185     }
1186 
1187     const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1188     if (platform_file_spec)
1189     {
1190         if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), platform_file_spec.GetDirectory()))
1191             return false;
1192     }
1193 
1194     const ArchSpec &arch = module_ref.GetArchitecture();
1195     if (arch.IsValid())
1196     {
1197         if (m_arch != arch)
1198             return false;
1199     }
1200 
1201     const ConstString &object_name = module_ref.GetObjectName();
1202     if (object_name)
1203     {
1204         if (object_name != GetObjectName())
1205             return false;
1206     }
1207     return true;
1208 }
1209 
1210 bool
1211 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1212 {
1213     Mutex::Locker locker (m_mutex);
1214     return m_source_mappings.FindFile (orig_spec, new_spec);
1215 }
1216 
1217 bool
1218 Module::RemapSourceFile (const char *path, std::string &new_path) const
1219 {
1220     Mutex::Locker locker (m_mutex);
1221     return m_source_mappings.RemapPath(path, new_path);
1222 }
1223 
1224 uint32_t
1225 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1226 {
1227     ObjectFile *obj_file = GetObjectFile();
1228     if (obj_file)
1229         return obj_file->GetVersion (versions, num_versions);
1230 
1231     if (versions && num_versions)
1232     {
1233         for (uint32_t i=0; i<num_versions; ++i)
1234             versions[i] = UINT32_MAX;
1235     }
1236     return 0;
1237 }
1238