1 //===-- Module.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
12 #include "lldb/Core/AddressResolverFileLine.h"
13 #include "lldb/Core/Error.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/DataBuffer.h"
16 #include "lldb/Core/DataBufferHeap.h"
17 #include "lldb/Core/Log.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/RegularExpression.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/StreamString.h"
23 #include "lldb/Core/Timer.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Host/Symbols.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Interpreter/ScriptInterpreter.h"
28 #include "lldb/lldb-private-log.h"
29 #include "lldb/Symbol/CompileUnit.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Symbol/SymbolContext.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Target/CPPLanguageRuntime.h"
34 #include "lldb/Target/ObjCLanguageRuntime.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/SectionLoadList.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Symbol/SymbolFile.h"
41 using namespace lldb_private;
43 // Shared pointers to modules track module lifetimes in
44 // targets and in the global module, but this collection
45 // will track all module objects that are still alive
46 typedef std::vector<Module *> ModuleCollection;
48 static ModuleCollection &
51 // This module collection needs to live past any module, so we could either make it a
52 // shared pointer in each module or just leak is. Since it is only an empty vector by
53 // the time all the modules have gone away, we just leak it for now. If we decide this
54 // is a big problem we can introduce a Finalize method that will tear everything down in
55 // a predictable order.
57 static ModuleCollection *g_module_collection = NULL;
58 if (g_module_collection == NULL)
59 g_module_collection = new ModuleCollection();
61 return *g_module_collection;
65 Module::GetAllocationModuleCollectionMutex()
67 // NOTE: The mutex below must be leaked since the global module list in
68 // the ModuleList class will get torn at some point, and we can't know
69 // if it will tear itself down before the "g_module_collection_mutex" below
70 // will. So we leak a Mutex object below to safeguard against that
72 static Mutex *g_module_collection_mutex = NULL;
73 if (g_module_collection_mutex == NULL)
74 g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
75 return g_module_collection_mutex;
79 Module::GetNumberAllocatedModules ()
81 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
82 return GetModuleCollection().size();
86 Module::GetAllocatedModuleAtIndex (size_t idx)
88 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
89 ModuleCollection &modules = GetModuleCollection();
90 if (idx < modules.size())
96 // These functions help us to determine if modules are still loaded, yet don't require that
97 // you have a command interpreter and can easily be called from an external debugger.
101 ClearModuleInfo (void)
103 const bool mandatory = true;
104 ModuleList::RemoveOrphanSharedModules(mandatory);
108 DumpModuleInfo (void)
110 Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
111 ModuleCollection &modules = GetModuleCollection();
112 const size_t count = modules.size();
113 printf ("%s: %" PRIu64 " modules:\n", __PRETTY_FUNCTION__, (uint64_t)count);
114 for (size_t i=0; i<count; ++i)
118 Module *module = modules[i];
119 const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
120 module->GetDescription(&strm, eDescriptionLevelFull);
121 printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
123 in_shared_module_list,
124 (uint32_t)module->use_count(),
125 strm.GetString().c_str());
132 Module::Module (const ModuleSpec &module_spec) :
133 m_mutex (Mutex::eMutexTypeRecursive),
134 m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
135 m_arch (module_spec.GetArchitecture()),
137 m_file (module_spec.GetFileSpec()),
138 m_platform_file(module_spec.GetPlatformFileSpec()),
139 m_remote_install_file(),
140 m_symfile_spec (module_spec.GetSymbolFileSpec()),
141 m_object_name (module_spec.GetObjectName()),
142 m_object_offset (module_spec.GetObjectOffset()),
143 m_object_mod_time (module_spec.GetObjectModificationTime()),
147 m_source_mappings (),
148 m_did_load_objfile (false),
149 m_did_load_symbol_vendor (false),
150 m_did_parse_uuid (false),
151 m_did_init_ast (false),
152 m_is_dynamic_loader_module (false),
153 m_file_has_changed (false),
154 m_first_file_changed_log (false)
156 // Scope for locker below...
158 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
159 GetModuleCollection().push_back(this);
162 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
164 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
166 m_arch.GetArchitectureName(),
167 m_file.GetPath().c_str(),
168 m_object_name.IsEmpty() ? "" : "(",
169 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
170 m_object_name.IsEmpty() ? "" : ")");
173 Module::Module(const FileSpec& file_spec,
174 const ArchSpec& arch,
175 const ConstString *object_name,
177 const TimeValue *object_mod_time_ptr) :
178 m_mutex (Mutex::eMutexTypeRecursive),
179 m_mod_time (file_spec.GetModificationTime()),
184 m_remote_install_file (),
187 m_object_offset (object_offset),
188 m_object_mod_time (),
192 m_source_mappings (),
193 m_did_load_objfile (false),
194 m_did_load_symbol_vendor (false),
195 m_did_parse_uuid (false),
196 m_did_init_ast (false),
197 m_is_dynamic_loader_module (false),
198 m_file_has_changed (false),
199 m_first_file_changed_log (false)
201 // Scope for locker below...
203 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
204 GetModuleCollection().push_back(this);
208 m_object_name = *object_name;
210 if (object_mod_time_ptr)
211 m_object_mod_time = *object_mod_time_ptr;
213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
215 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
217 m_arch.GetArchitectureName(),
218 m_file.GetPath().c_str(),
219 m_object_name.IsEmpty() ? "" : "(",
220 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
221 m_object_name.IsEmpty() ? "" : ")");
226 // Lock our module down while we tear everything down to make sure
227 // we don't get any access to the module while it is being destroyed
228 Mutex::Locker locker (m_mutex);
229 // Scope for locker below...
231 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
232 ModuleCollection &modules = GetModuleCollection();
233 ModuleCollection::iterator end = modules.end();
234 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
238 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
240 log->Printf ("%p Module::~Module((%s) '%s%s%s%s')",
242 m_arch.GetArchitectureName(),
243 m_file.GetPath().c_str(),
244 m_object_name.IsEmpty() ? "" : "(",
245 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
246 m_object_name.IsEmpty() ? "" : ")");
247 // Release any auto pointers before we start tearing down our member
248 // variables since the object file and symbol files might need to make
249 // function calls back into this module object. The ordering is important
250 // here because symbol files can require the module object file. So we tear
251 // down the symbol file first, then the object file.
252 m_sections_ap.reset();
253 m_symfile_ap.reset();
254 m_objfile_sp.reset();
258 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
262 error.SetErrorString ("object file already exists");
266 Mutex::Locker locker (m_mutex);
269 m_did_load_objfile = true;
270 std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
272 const size_t bytes_read = process_sp->ReadMemory (header_addr,
274 data_ap->GetByteSize(),
276 if (bytes_read == 512)
278 DataBufferSP data_sp(data_ap.release());
279 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
283 s.Printf("0x%16.16" PRIx64, header_addr);
284 m_object_name.SetCString (s.GetData());
286 // Once we get the object file, update our module with the object file's
287 // architecture since it might differ in vendor/os if some parts were
289 m_objfile_sp->GetArchitecture (m_arch);
293 error.SetErrorString ("unable to find suitable object file plug-in");
298 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
303 error.SetErrorString ("invalid process");
306 return m_objfile_sp.get();
310 const lldb_private::UUID&
313 Mutex::Locker locker (m_mutex);
314 if (m_did_parse_uuid == false)
316 ObjectFile * obj_file = GetObjectFile ();
318 if (obj_file != NULL)
320 obj_file->GetUUID(&m_uuid);
321 m_did_parse_uuid = true;
328 Module::GetClangASTContext ()
330 Mutex::Locker locker (m_mutex);
331 if (m_did_init_ast == false)
333 ObjectFile * objfile = GetObjectFile();
334 ArchSpec object_arch;
335 if (objfile && objfile->GetArchitecture(object_arch))
337 m_did_init_ast = true;
339 // LLVM wants this to be set to iOS or MacOSX; if we're working on
340 // a bare-boards type image, change the triple for llvm's benefit.
341 if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
342 && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
344 if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
345 object_arch.GetTriple().getArch() == llvm::Triple::thumb)
347 object_arch.GetTriple().setOS(llvm::Triple::IOS);
351 object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
354 m_ast.SetArchitecture (object_arch);
361 Module::ParseAllDebugSymbols()
363 Mutex::Locker locker (m_mutex);
364 size_t num_comp_units = GetNumCompileUnits();
365 if (num_comp_units == 0)
369 sc.module_sp = shared_from_this();
370 SymbolVendor *symbols = GetSymbolVendor ();
372 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
374 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
378 symbols->ParseVariablesForContext(sc);
380 symbols->ParseCompileUnitFunctions(sc);
382 for (size_t func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
384 symbols->ParseFunctionBlocks(sc);
386 // Parse the variables for this function and all its blocks
387 symbols->ParseVariablesForContext(sc);
391 // Parse all types for this compile unit
393 symbols->ParseTypes(sc);
399 Module::CalculateSymbolContext(SymbolContext* sc)
401 sc->module_sp = shared_from_this();
405 Module::CalculateSymbolContextModule ()
407 return shared_from_this();
411 Module::DumpSymbolContext(Stream *s)
413 s->Printf(", Module{%p}", this);
417 Module::GetNumCompileUnits()
419 Mutex::Locker locker (m_mutex);
420 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
421 SymbolVendor *symbols = GetSymbolVendor ();
423 return symbols->GetNumCompileUnits();
428 Module::GetCompileUnitAtIndex (size_t index)
430 Mutex::Locker locker (m_mutex);
431 size_t num_comp_units = GetNumCompileUnits ();
434 if (index < num_comp_units)
436 SymbolVendor *symbols = GetSymbolVendor ();
438 cu_sp = symbols->GetCompileUnitAtIndex(index);
444 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
446 Mutex::Locker locker (m_mutex);
447 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr);
448 SectionList *section_list = GetSectionList();
450 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
455 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc,
456 bool resolve_tail_call_address)
458 Mutex::Locker locker (m_mutex);
459 uint32_t resolved_flags = 0;
461 // Clear the result symbol context in case we don't find anything, but don't clear the target
464 // Get the section from the section/offset address.
465 SectionSP section_sp (so_addr.GetSection());
467 // Make sure the section matches this module before we try and match anything
468 if (section_sp && section_sp->GetModule().get() == this)
470 // If the section offset based address resolved itself, then this
471 // is the right module.
472 sc.module_sp = shared_from_this();
473 resolved_flags |= eSymbolContextModule;
475 SymbolVendor* sym_vendor = GetSymbolVendor();
477 return resolved_flags;
479 // Resolve the compile unit, function, block, line table or line
480 // entry if requested.
481 if (resolve_scope & eSymbolContextCompUnit ||
482 resolve_scope & eSymbolContextFunction ||
483 resolve_scope & eSymbolContextBlock ||
484 resolve_scope & eSymbolContextLineEntry )
486 resolved_flags |= sym_vendor->ResolveSymbolContext (so_addr, resolve_scope, sc);
489 // Resolve the symbol if requested, but don't re-look it up if we've already found it.
490 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
492 Symtab *symtab = sym_vendor->GetSymtab();
493 if (symtab && so_addr.IsSectionOffset())
495 sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
497 resolve_scope & eSymbolContextFunction && !(resolved_flags & eSymbolContextFunction))
499 bool verify_unique = false; // No need to check again since ResolveSymbolContext failed to find a symbol at this address.
500 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
501 sc.symbol = obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
506 if (sc.symbol->IsSynthetic())
508 // We have a synthetic symbol so lets check if the object file
509 // from the symbol file in the symbol vendor is different than
510 // the object file for the module, and if so search its symbol
511 // table to see if we can come up with a better symbol. For example
512 // dSYM files on MacOSX have an unstripped symbol table inside of
514 ObjectFile *symtab_objfile = symtab->GetObjectFile();
515 if (symtab_objfile && symtab_objfile->IsStripped())
517 SymbolFile *symfile = sym_vendor->GetSymbolFile();
520 ObjectFile *symfile_objfile = symfile->GetObjectFile();
521 if (symfile_objfile != symtab_objfile)
523 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
526 Symbol *symbol = symfile_symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
527 if (symbol && !symbol->IsSynthetic())
536 resolved_flags |= eSymbolContextSymbol;
541 // For function symbols, so_addr may be off by one. This is a convention consistent
542 // with FDE row indices in eh_frame sections, but requires extra logic here to permit
543 // symbol lookup for disassembly and unwind.
544 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol) &&
545 resolve_tail_call_address && so_addr.IsSectionOffset())
547 Address previous_addr = so_addr;
548 previous_addr.Slide(-1);
550 bool do_resolve_tail_call_address = false; // prevent recursion
551 const uint32_t flags = ResolveSymbolContextForAddress(previous_addr, resolve_scope, sc,
552 do_resolve_tail_call_address);
553 if (flags & eSymbolContextSymbol)
555 AddressRange addr_range;
556 if (sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
558 if (addr_range.GetBaseAddress().GetSection() == so_addr.GetSection())
560 // If the requested address is one past the address range of a function (i.e. a tail call),
561 // or the decremented address is the start of a function (i.e. some forms of trampoline),
562 // indicate that the symbol has been resolved.
563 if (so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() ||
564 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() + addr_range.GetByteSize())
566 resolved_flags |= flags;
571 sc.symbol = nullptr; // Don't trust the symbol if the sections didn't match.
577 return resolved_flags;
581 Module::ResolveSymbolContextForFilePath
583 const char *file_path,
586 uint32_t resolve_scope,
587 SymbolContextList& sc_list
590 FileSpec file_spec(file_path, false);
591 return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
595 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
597 Mutex::Locker locker (m_mutex);
598 Timer scoped_timer(__PRETTY_FUNCTION__,
599 "Module::ResolveSymbolContextForFilePath (%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
600 file_spec.GetPath().c_str(),
602 check_inlines ? "yes" : "no",
605 const uint32_t initial_count = sc_list.GetSize();
607 SymbolVendor *symbols = GetSymbolVendor ();
609 symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
611 return sc_list.GetSize() - initial_count;
616 Module::FindGlobalVariables (const ConstString &name,
617 const ClangNamespaceDecl *namespace_decl,
620 VariableList& variables)
622 SymbolVendor *symbols = GetSymbolVendor ();
624 return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
629 Module::FindGlobalVariables (const RegularExpression& regex,
632 VariableList& variables)
634 SymbolVendor *symbols = GetSymbolVendor ();
636 return symbols->FindGlobalVariables(regex, append, max_matches, variables);
641 Module::FindCompileUnits (const FileSpec &path,
643 SymbolContextList &sc_list)
648 const size_t start_size = sc_list.GetSize();
649 const size_t num_compile_units = GetNumCompileUnits();
651 sc.module_sp = shared_from_this();
652 const bool compare_directory = (bool)path.GetDirectory();
653 for (size_t i=0; i<num_compile_units; ++i)
655 sc.comp_unit = GetCompileUnitAtIndex(i).get();
658 if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
662 return sc_list.GetSize() - start_size;
666 Module::FindFunctions (const ConstString &name,
667 const ClangNamespaceDecl *namespace_decl,
668 uint32_t name_type_mask,
669 bool include_symbols,
670 bool include_inlines,
672 SymbolContextList& sc_list)
677 const size_t old_size = sc_list.GetSize();
679 // Find all the functions (not symbols, but debug information functions...
680 SymbolVendor *symbols = GetSymbolVendor ();
682 if (name_type_mask & eFunctionNameTypeAuto)
684 ConstString lookup_name;
685 uint32_t lookup_name_type_mask = 0;
686 bool match_name_after_lookup = false;
687 Module::PrepareForFunctionNameLookup (name,
690 lookup_name_type_mask,
691 match_name_after_lookup);
695 symbols->FindFunctions(lookup_name,
697 lookup_name_type_mask,
702 // Now check our symbol table for symbols that are code symbols if requested
705 Symtab *symtab = symbols->GetSymtab();
707 symtab->FindFunctionSymbols(lookup_name, lookup_name_type_mask, sc_list);
711 if (match_name_after_lookup)
715 while (i<sc_list.GetSize())
717 if (sc_list.GetContextAtIndex(i, sc))
719 const char *func_name = sc.GetFunctionName().GetCString();
720 if (func_name && strstr (func_name, name.GetCString()) == NULL)
722 // Remove the current context
723 sc_list.RemoveContextAtIndex(i);
724 // Don't increment i and continue in the loop
736 symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
738 // Now check our symbol table for symbols that are code symbols if requested
741 Symtab *symtab = symbols->GetSymtab();
743 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
748 return sc_list.GetSize() - old_size;
752 Module::FindFunctions (const RegularExpression& regex,
753 bool include_symbols,
754 bool include_inlines,
756 SymbolContextList& sc_list)
761 const size_t start_size = sc_list.GetSize();
763 SymbolVendor *symbols = GetSymbolVendor ();
766 symbols->FindFunctions(regex, include_inlines, append, sc_list);
768 // Now check our symbol table for symbols that are code symbols if requested
771 Symtab *symtab = symbols->GetSymtab();
774 std::vector<uint32_t> symbol_indexes;
775 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
776 const size_t num_matches = symbol_indexes.size();
779 SymbolContext sc(this);
780 const size_t end_functions_added_index = sc_list.GetSize();
781 size_t num_functions_added_to_sc_list = end_functions_added_index - start_size;
782 if (num_functions_added_to_sc_list == 0)
784 // No functions were added, just symbols, so we can just append them
785 for (size_t i=0; i<num_matches; ++i)
787 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
788 SymbolType sym_type = sc.symbol->GetType();
789 if (sc.symbol && (sym_type == eSymbolTypeCode ||
790 sym_type == eSymbolTypeResolver))
796 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
797 FileAddrToIndexMap file_addr_to_index;
798 for (size_t i=start_size; i<end_functions_added_index; ++i)
800 const SymbolContext &sc = sc_list[i];
803 file_addr_to_index[sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()] = i;
806 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
807 // Functions were added so we need to merge symbols into any
808 // existing function symbol contexts
809 for (size_t i=start_size; i<num_matches; ++i)
811 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
812 SymbolType sym_type = sc.symbol->GetType();
813 if (sc.symbol && (sym_type == eSymbolTypeCode ||
814 sym_type == eSymbolTypeResolver))
816 FileAddrToIndexMap::const_iterator pos = file_addr_to_index.find(sc.symbol->GetAddress().GetFileAddress());
820 sc_list[pos->second].symbol = sc.symbol;
828 return sc_list.GetSize() - start_size;
832 Module::FindAddressesForLine (const lldb::TargetSP target_sp,
833 const FileSpec &file, uint32_t line,
835 std::vector<Address> &output_local, std::vector<Address> &output_extern)
837 SearchFilterByModule filter(target_sp, m_file);
838 AddressResolverFileLine resolver(file, line, true);
839 resolver.ResolveAddress (filter);
841 for (size_t n=0;n<resolver.GetNumberOfAddresses();n++)
843 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
844 Function *f = addr.CalculateSymbolContextFunction();
845 if (f && f == function)
846 output_local.push_back (addr);
848 output_extern.push_back (addr);
853 Module::FindTypes_Impl (const SymbolContext& sc,
854 const ConstString &name,
855 const ClangNamespaceDecl *namespace_decl,
860 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
861 if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
863 SymbolVendor *symbols = GetSymbolVendor ();
865 return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
871 Module::FindTypesInNamespace (const SymbolContext& sc,
872 const ConstString &type_name,
873 const ClangNamespaceDecl *namespace_decl,
877 const bool append = true;
878 return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
882 Module::FindFirstType (const SymbolContext& sc,
883 const ConstString &name,
887 const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
889 return type_list.GetTypeAtIndex(0);
895 Module::FindTypes (const SymbolContext& sc,
896 const ConstString &name,
901 size_t num_matches = 0;
902 const char *type_name_cstr = name.GetCString();
903 std::string type_scope;
904 std::string type_basename;
905 const bool append = true;
906 TypeClass type_class = eTypeClassAny;
907 if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
909 // Check if "name" starts with "::" which means the qualified type starts
910 // from the root namespace and implies and exact match. The typenames we
911 // get back from clang do not start with "::" so we need to strip this off
912 // in order to get the qualfied names to match
914 if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
916 type_scope.erase(0,2);
919 ConstString type_basename_const_str (type_basename.c_str());
920 if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
922 types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
923 num_matches = types.GetSize();
928 // The type is not in a namespace/class scope, just search for it by basename
929 if (type_class != eTypeClassAny)
931 // The "type_name_cstr" will have been modified if we have a valid type class
932 // prefix (like "struct", "class", "union", "typedef" etc).
933 num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
934 types.RemoveMismatchedTypes (type_class);
935 num_matches = types.GetSize();
939 num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
948 Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
950 Mutex::Locker locker (m_mutex);
951 if (m_did_load_symbol_vendor == false && can_create)
953 ObjectFile *obj_file = GetObjectFile ();
954 if (obj_file != NULL)
956 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
957 m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
958 m_did_load_symbol_vendor = true;
961 return m_symfile_ap.get();
965 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
967 // Container objects whose paths do not specify a file directly can call
968 // this function to correct the file and object names.
970 m_mod_time = file.GetModificationTime();
971 m_object_name = object_name;
975 Module::GetArchitecture () const
981 Module::GetSpecificationDescription () const
983 std::string spec(GetFileSpec().GetPath());
987 spec += m_object_name.GetCString();
994 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
996 Mutex::Locker locker (m_mutex);
998 if (level >= eDescriptionLevelFull)
1000 if (m_arch.IsValid())
1001 s->Printf("(%s) ", m_arch.GetArchitectureName());
1004 if (level == eDescriptionLevelBrief)
1006 const char *filename = m_file.GetFilename().GetCString();
1008 s->PutCString (filename);
1012 char path[PATH_MAX];
1013 if (m_file.GetPath(path, sizeof(path)))
1014 s->PutCString(path);
1017 const char *object_name = m_object_name.GetCString();
1019 s->Printf("(%s)", object_name);
1023 Module::ReportError (const char *format, ...)
1025 if (format && format[0])
1028 strm.PutCString("error: ");
1029 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1032 va_start (args, format);
1033 strm.PrintfVarArg(format, args);
1036 const int format_len = strlen(format);
1039 const char last_char = format[format_len-1];
1040 if (last_char != '\n' || last_char != '\r')
1043 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1049 Module::FileHasChanged () const
1051 if (m_file_has_changed == false)
1052 m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
1053 return m_file_has_changed;
1057 Module::ReportErrorIfModifyDetected (const char *format, ...)
1059 if (m_first_file_changed_log == false)
1061 if (FileHasChanged ())
1063 m_first_file_changed_log = true;
1067 strm.PutCString("error: the object file ");
1068 GetDescription(&strm, lldb::eDescriptionLevelFull);
1069 strm.PutCString (" has been modified\n");
1072 va_start (args, format);
1073 strm.PrintfVarArg(format, args);
1076 const int format_len = strlen(format);
1079 const char last_char = format[format_len-1];
1080 if (last_char != '\n' || last_char != '\r')
1083 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
1084 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1091 Module::ReportWarning (const char *format, ...)
1093 if (format && format[0])
1096 strm.PutCString("warning: ");
1097 GetDescription(&strm, lldb::eDescriptionLevelFull);
1101 va_start (args, format);
1102 strm.PrintfVarArg(format, args);
1105 const int format_len = strlen(format);
1108 const char last_char = format[format_len-1];
1109 if (last_char != '\n' || last_char != '\r')
1112 Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
1117 Module::LogMessage (Log *log, const char *format, ...)
1121 StreamString log_message;
1122 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1123 log_message.PutCString (": ");
1125 va_start (args, format);
1126 log_message.PrintfVarArg (format, args);
1128 log->PutCString(log_message.GetString().c_str());
1133 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
1137 StreamString log_message;
1138 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1139 log_message.PutCString (": ");
1141 va_start (args, format);
1142 log_message.PrintfVarArg (format, args);
1144 if (log->GetVerbose())
1145 Host::Backtrace (log_message, 1024);
1146 log->PutCString(log_message.GetString().c_str());
1151 Module::Dump(Stream *s)
1153 Mutex::Locker locker (m_mutex);
1154 //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1156 s->Printf("Module %s%s%s%s\n",
1157 m_file.GetPath().c_str(),
1158 m_object_name ? "(" : "",
1159 m_object_name ? m_object_name.GetCString() : "",
1160 m_object_name ? ")" : "");
1164 ObjectFile *objfile = GetObjectFile ();
1168 SymbolVendor *symbols = GetSymbolVendor ();
1177 Module::GetTypeList ()
1179 SymbolVendor *symbols = GetSymbolVendor ();
1181 return &symbols->GetTypeList();
1186 Module::GetObjectName() const
1188 return m_object_name;
1192 Module::GetObjectFile()
1194 Mutex::Locker locker (m_mutex);
1195 if (m_did_load_objfile == false)
1197 Timer scoped_timer(__PRETTY_FUNCTION__,
1198 "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1199 DataBufferSP data_sp;
1200 lldb::offset_t data_offset = 0;
1201 const lldb::offset_t file_size = m_file.GetByteSize();
1202 if (file_size > m_object_offset)
1204 m_did_load_objfile = true;
1205 m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1208 file_size - m_object_offset,
1213 // Once we get the object file, update our module with the object file's
1214 // architecture since it might differ in vendor/os if some parts were
1216 m_objfile_sp->GetArchitecture (m_arch);
1220 return m_objfile_sp.get();
1224 Module::GetSectionList()
1226 // Populate m_unified_sections_ap with sections from objfile.
1227 if (m_sections_ap.get() == NULL)
1229 ObjectFile *obj_file = GetObjectFile();
1231 obj_file->CreateSections(*GetUnifiedSectionList());
1233 return m_sections_ap.get();
1237 Module::GetUnifiedSectionList()
1239 // Populate m_unified_sections_ap with sections from objfile.
1240 if (m_sections_ap.get() == NULL)
1241 m_sections_ap.reset(new SectionList());
1242 return m_sections_ap.get();
1246 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1248 Timer scoped_timer(__PRETTY_FUNCTION__,
1249 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1252 SymbolVendor* sym_vendor = GetSymbolVendor();
1255 Symtab *symtab = sym_vendor->GetSymtab();
1257 return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1262 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1264 // No need to protect this call using m_mutex all other method calls are
1265 // already thread safe.
1267 size_t num_indices = symbol_indexes.size();
1268 if (num_indices > 0)
1271 CalculateSymbolContext (&sc);
1272 for (size_t i = 0; i < num_indices; i++)
1274 sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1276 sc_list.Append (sc);
1282 Module::FindFunctionSymbols (const ConstString &name,
1283 uint32_t name_type_mask,
1284 SymbolContextList& sc_list)
1286 Timer scoped_timer(__PRETTY_FUNCTION__,
1287 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1290 SymbolVendor* sym_vendor = GetSymbolVendor();
1293 Symtab *symtab = sym_vendor->GetSymtab();
1295 return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1301 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1303 // No need to protect this call using m_mutex all other method calls are
1304 // already thread safe.
1307 Timer scoped_timer(__PRETTY_FUNCTION__,
1308 "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1311 const size_t initial_size = sc_list.GetSize();
1312 SymbolVendor* sym_vendor = GetSymbolVendor();
1315 Symtab *symtab = sym_vendor->GetSymtab();
1318 std::vector<uint32_t> symbol_indexes;
1319 symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1320 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1323 return sc_list.GetSize() - initial_size;
1327 Module::FindSymbolsMatchingRegExAndType (const RegularExpression ®ex, SymbolType symbol_type, SymbolContextList &sc_list)
1329 // No need to protect this call using m_mutex all other method calls are
1330 // already thread safe.
1332 Timer scoped_timer(__PRETTY_FUNCTION__,
1333 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1336 const size_t initial_size = sc_list.GetSize();
1337 SymbolVendor* sym_vendor = GetSymbolVendor();
1340 Symtab *symtab = sym_vendor->GetSymtab();
1343 std::vector<uint32_t> symbol_indexes;
1344 symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1345 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1348 return sc_list.GetSize() - initial_size;
1352 Module::SetSymbolFileFileSpec (const FileSpec &file)
1354 // Remove any sections in the unified section list that come from the current symbol vendor.
1357 SectionList *section_list = GetSectionList();
1358 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1359 if (section_list && symbol_file)
1361 ObjectFile *obj_file = symbol_file->GetObjectFile();
1362 // Make sure we have an object file and that the symbol vendor's objfile isn't
1363 // the same as the module's objfile before we remove any sections for it...
1364 if (obj_file && obj_file != m_objfile_sp.get())
1366 size_t num_sections = section_list->GetNumSections (0);
1367 for (size_t idx = num_sections; idx > 0; --idx)
1369 lldb::SectionSP section_sp (section_list->GetSectionAtIndex (idx - 1));
1370 if (section_sp->GetObjectFile() == obj_file)
1372 section_list->DeleteSection (idx - 1);
1379 m_symfile_spec = file;
1380 m_symfile_ap.reset();
1381 m_did_load_symbol_vendor = false;
1385 Module::IsExecutable ()
1387 if (GetObjectFile() == NULL)
1390 return GetObjectFile()->IsExecutable();
1394 Module::IsLoadedInTarget (Target *target)
1396 ObjectFile *obj_file = GetObjectFile();
1399 SectionList *sections = GetSectionList();
1400 if (sections != NULL)
1402 size_t num_sections = sections->GetSize();
1403 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1405 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1406 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1417 Module::LoadScriptingResourceInTarget (Target *target, Error& error, Stream* feedback_stream)
1421 error.SetErrorString("invalid destination Target");
1425 LoadScriptFromSymFile shoud_load = target->TargetProperties::GetLoadScriptFromSymbolFile();
1427 Debugger &debugger = target->GetDebugger();
1428 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1429 if (script_language != eScriptLanguageNone)
1432 PlatformSP platform_sp(target->GetPlatform());
1436 error.SetErrorString("invalid Platform");
1440 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1444 const uint32_t num_specs = file_specs.GetSize();
1447 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1448 if (script_interpreter)
1450 for (uint32_t i=0; i<num_specs; ++i)
1452 FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1453 if (scripting_fspec && scripting_fspec.Exists())
1455 if (shoud_load == eLoadScriptFromSymFileFalse)
1457 if (shoud_load == eLoadScriptFromSymFileWarn)
1459 if (feedback_stream)
1460 feedback_stream->Printf("warning: '%s' contains a debug script. To run this script in "
1461 "this debug session:\n\n command script import \"%s\"\n\n"
1462 "To run all discovered debug scripts in this session:\n\n"
1463 " settings set target.load-script-from-symbol-file true\n",
1464 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1465 scripting_fspec.GetPath().c_str());
1468 StreamString scripting_stream;
1469 scripting_fspec.Dump(&scripting_stream);
1470 const bool can_reload = true;
1471 const bool init_lldb_globals = false;
1472 bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(),
1483 error.SetErrorString("invalid ScriptInterpreter");
1492 Module::SetArchitecture (const ArchSpec &new_arch)
1494 if (!m_arch.IsValid())
1499 return m_arch.IsExactMatch(new_arch);
1503 Module::SetLoadAddress (Target &target, lldb::addr_t value, bool value_is_offset, bool &changed)
1505 ObjectFile *object_file = GetObjectFile();
1508 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1520 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1522 const UUID &uuid = module_ref.GetUUID();
1526 // If the UUID matches, then nothing more needs to match...
1527 if (uuid == GetUUID())
1533 const FileSpec &file_spec = module_ref.GetFileSpec();
1536 if (!FileSpec::Equal (file_spec, m_file, (bool)file_spec.GetDirectory()))
1540 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1541 if (platform_file_spec)
1543 if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), (bool)platform_file_spec.GetDirectory()))
1547 const ArchSpec &arch = module_ref.GetArchitecture();
1550 if (!m_arch.IsCompatibleMatch(arch))
1554 const ConstString &object_name = module_ref.GetObjectName();
1557 if (object_name != GetObjectName())
1564 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1566 Mutex::Locker locker (m_mutex);
1567 return m_source_mappings.FindFile (orig_spec, new_spec);
1571 Module::RemapSourceFile (const char *path, std::string &new_path) const
1573 Mutex::Locker locker (m_mutex);
1574 return m_source_mappings.RemapPath(path, new_path);
1578 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1580 ObjectFile *obj_file = GetObjectFile();
1582 return obj_file->GetVersion (versions, num_versions);
1584 if (versions && num_versions)
1586 for (uint32_t i=0; i<num_versions; ++i)
1587 versions[i] = UINT32_MAX;
1593 Module::PrepareForFunctionNameLookup (const ConstString &name,
1594 uint32_t name_type_mask,
1595 ConstString &lookup_name,
1596 uint32_t &lookup_name_type_mask,
1597 bool &match_name_after_lookup)
1599 const char *name_cstr = name.GetCString();
1600 lookup_name_type_mask = eFunctionNameTypeNone;
1601 match_name_after_lookup = false;
1602 const char *base_name_start = NULL;
1603 const char *base_name_end = NULL;
1605 if (name_type_mask & eFunctionNameTypeAuto)
1607 if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
1608 lookup_name_type_mask = eFunctionNameTypeFull;
1609 else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
1610 lookup_name_type_mask = eFunctionNameTypeFull;
1613 if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1614 lookup_name_type_mask |= eFunctionNameTypeSelector;
1616 CPPLanguageRuntime::MethodName cpp_method (name);
1617 llvm::StringRef basename (cpp_method.GetBasename());
1618 if (basename.empty())
1620 if (CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1621 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1625 base_name_start = basename.data();
1626 base_name_end = base_name_start + basename.size();
1627 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1633 lookup_name_type_mask = name_type_mask;
1634 if (lookup_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
1636 // If they've asked for a CPP method or function name and it can't be that, we don't
1637 // even need to search for CPP methods or names.
1638 CPPLanguageRuntime::MethodName cpp_method (name);
1639 if (cpp_method.IsValid())
1641 llvm::StringRef basename (cpp_method.GetBasename());
1642 base_name_start = basename.data();
1643 base_name_end = base_name_start + basename.size();
1645 if (!cpp_method.GetQualifiers().empty())
1647 // There is a "const" or other qualifer following the end of the fucntion parens,
1648 // this can't be a eFunctionNameTypeBase
1649 lookup_name_type_mask &= ~(eFunctionNameTypeBase);
1650 if (lookup_name_type_mask == eFunctionNameTypeNone)
1656 if (!CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1658 lookup_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
1659 if (lookup_name_type_mask == eFunctionNameTypeNone)
1665 if (lookup_name_type_mask & eFunctionNameTypeSelector)
1667 if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1669 lookup_name_type_mask &= ~(eFunctionNameTypeSelector);
1670 if (lookup_name_type_mask == eFunctionNameTypeNone)
1676 if (base_name_start &&
1678 base_name_start != name_cstr &&
1679 base_name_start < base_name_end)
1681 // The name supplied was a partial C++ path like "a::count". In this case we want to do a
1682 // lookup on the basename "count" and then make sure any matching results contain "a::count"
1683 // so that it would match "b::a::count" and "a::count". This is why we set "match_name_after_lookup"
1685 lookup_name.SetCStringWithLength(base_name_start, base_name_end - base_name_start);
1686 match_name_after_lookup = true;
1690 // The name is already correct, just use the exact name as supplied, and we won't need
1691 // to check if any matches contain "name"
1693 match_name_after_lookup = false;