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/Target.h"
37 #include "lldb/Symbol/SymbolFile.h"
40 using namespace lldb_private;
42 // Shared pointers to modules track module lifetimes in
43 // targets and in the global module, but this collection
44 // will track all module objects that are still alive
45 typedef std::vector<Module *> ModuleCollection;
47 static ModuleCollection &
50 // This module collection needs to live past any module, so we could either make it a
51 // shared pointer in each module or just leak is. Since it is only an empty vector by
52 // the time all the modules have gone away, we just leak it for now. If we decide this
53 // is a big problem we can introduce a Finalize method that will tear everything down in
54 // a predictable order.
56 static ModuleCollection *g_module_collection = NULL;
57 if (g_module_collection == NULL)
58 g_module_collection = new ModuleCollection();
60 return *g_module_collection;
64 Module::GetAllocationModuleCollectionMutex()
66 // NOTE: The mutex below must be leaked since the global module list in
67 // the ModuleList class will get torn at some point, and we can't know
68 // if it will tear itself down before the "g_module_collection_mutex" below
69 // will. So we leak a Mutex object below to safeguard against that
71 static Mutex *g_module_collection_mutex = NULL;
72 if (g_module_collection_mutex == NULL)
73 g_module_collection_mutex = new Mutex (Mutex::eMutexTypeRecursive); // NOTE: known leak
74 return g_module_collection_mutex;
78 Module::GetNumberAllocatedModules ()
80 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
81 return GetModuleCollection().size();
85 Module::GetAllocatedModuleAtIndex (size_t idx)
87 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
88 ModuleCollection &modules = GetModuleCollection();
89 if (idx < modules.size())
95 // These functions help us to determine if modules are still loaded, yet don't require that
96 // you have a command interpreter and can easily be called from an external debugger.
100 ClearModuleInfo (void)
102 const bool mandatory = true;
103 ModuleList::RemoveOrphanSharedModules(mandatory);
107 DumpModuleInfo (void)
109 Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
110 ModuleCollection &modules = GetModuleCollection();
111 const size_t count = modules.size();
112 printf ("%s: %" PRIu64 " modules:\n", __PRETTY_FUNCTION__, (uint64_t)count);
113 for (size_t i=0; i<count; ++i)
117 Module *module = modules[i];
118 const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
119 module->GetDescription(&strm, eDescriptionLevelFull);
120 printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
122 in_shared_module_list,
123 (uint32_t)module->use_count(),
124 strm.GetString().c_str());
131 Module::Module (const ModuleSpec &module_spec) :
132 m_mutex (Mutex::eMutexTypeRecursive),
133 m_mod_time (module_spec.GetFileSpec().GetModificationTime()),
134 m_arch (module_spec.GetArchitecture()),
136 m_file (module_spec.GetFileSpec()),
137 m_platform_file(module_spec.GetPlatformFileSpec()),
138 m_remote_install_file(),
139 m_symfile_spec (module_spec.GetSymbolFileSpec()),
140 m_object_name (module_spec.GetObjectName()),
141 m_object_offset (module_spec.GetObjectOffset()),
142 m_object_mod_time (module_spec.GetObjectModificationTime()),
146 m_source_mappings (),
147 m_did_load_objfile (false),
148 m_did_load_symbol_vendor (false),
149 m_did_parse_uuid (false),
150 m_did_init_ast (false),
151 m_is_dynamic_loader_module (false),
152 m_file_has_changed (false),
153 m_first_file_changed_log (false)
155 // Scope for locker below...
157 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
158 GetModuleCollection().push_back(this);
161 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
163 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
165 m_arch.GetArchitectureName(),
166 m_file.GetPath().c_str(),
167 m_object_name.IsEmpty() ? "" : "(",
168 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
169 m_object_name.IsEmpty() ? "" : ")");
172 Module::Module(const FileSpec& file_spec,
173 const ArchSpec& arch,
174 const ConstString *object_name,
176 const TimeValue *object_mod_time_ptr) :
177 m_mutex (Mutex::eMutexTypeRecursive),
178 m_mod_time (file_spec.GetModificationTime()),
183 m_remote_install_file (),
186 m_object_offset (object_offset),
187 m_object_mod_time (),
191 m_source_mappings (),
192 m_did_load_objfile (false),
193 m_did_load_symbol_vendor (false),
194 m_did_parse_uuid (false),
195 m_did_init_ast (false),
196 m_is_dynamic_loader_module (false),
197 m_file_has_changed (false),
198 m_first_file_changed_log (false)
200 // Scope for locker below...
202 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
203 GetModuleCollection().push_back(this);
207 m_object_name = *object_name;
209 if (object_mod_time_ptr)
210 m_object_mod_time = *object_mod_time_ptr;
212 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
214 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
216 m_arch.GetArchitectureName(),
217 m_file.GetPath().c_str(),
218 m_object_name.IsEmpty() ? "" : "(",
219 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
220 m_object_name.IsEmpty() ? "" : ")");
225 // Lock our module down while we tear everything down to make sure
226 // we don't get any access to the module while it is being destroyed
227 Mutex::Locker locker (m_mutex);
228 // Scope for locker below...
230 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
231 ModuleCollection &modules = GetModuleCollection();
232 ModuleCollection::iterator end = modules.end();
233 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
237 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
239 log->Printf ("%p Module::~Module((%s) '%s%s%s%s')",
241 m_arch.GetArchitectureName(),
242 m_file.GetPath().c_str(),
243 m_object_name.IsEmpty() ? "" : "(",
244 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
245 m_object_name.IsEmpty() ? "" : ")");
246 // Release any auto pointers before we start tearing down our member
247 // variables since the object file and symbol files might need to make
248 // function calls back into this module object. The ordering is important
249 // here because symbol files can require the module object file. So we tear
250 // down the symbol file first, then the object file.
251 m_sections_ap.reset();
252 m_symfile_ap.reset();
253 m_objfile_sp.reset();
257 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
261 error.SetErrorString ("object file already exists");
265 Mutex::Locker locker (m_mutex);
268 m_did_load_objfile = true;
269 std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
271 const size_t bytes_read = process_sp->ReadMemory (header_addr,
273 data_ap->GetByteSize(),
275 if (bytes_read == 512)
277 DataBufferSP data_sp(data_ap.release());
278 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
282 s.Printf("0x%16.16" PRIx64, header_addr);
283 m_object_name.SetCString (s.GetData());
285 // Once we get the object file, update our module with the object file's
286 // architecture since it might differ in vendor/os if some parts were
288 m_objfile_sp->GetArchitecture (m_arch);
292 error.SetErrorString ("unable to find suitable object file plug-in");
297 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
302 error.SetErrorString ("invalid process");
305 return m_objfile_sp.get();
309 const lldb_private::UUID&
312 Mutex::Locker locker (m_mutex);
313 if (m_did_parse_uuid == false)
315 ObjectFile * obj_file = GetObjectFile ();
317 if (obj_file != NULL)
319 obj_file->GetUUID(&m_uuid);
320 m_did_parse_uuid = true;
327 Module::GetClangASTContext ()
329 Mutex::Locker locker (m_mutex);
330 if (m_did_init_ast == false)
332 ObjectFile * objfile = GetObjectFile();
333 ArchSpec object_arch;
334 if (objfile && objfile->GetArchitecture(object_arch))
336 m_did_init_ast = true;
338 // LLVM wants this to be set to iOS or MacOSX; if we're working on
339 // a bare-boards type image, change the triple for llvm's benefit.
340 if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
341 && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
343 if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
344 object_arch.GetTriple().getArch() == llvm::Triple::thumb)
346 object_arch.GetTriple().setOS(llvm::Triple::IOS);
350 object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
353 m_ast.SetArchitecture (object_arch);
360 Module::ParseAllDebugSymbols()
362 Mutex::Locker locker (m_mutex);
363 size_t num_comp_units = GetNumCompileUnits();
364 if (num_comp_units == 0)
368 sc.module_sp = shared_from_this();
369 SymbolVendor *symbols = GetSymbolVendor ();
371 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
373 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
377 symbols->ParseVariablesForContext(sc);
379 symbols->ParseCompileUnitFunctions(sc);
381 for (size_t func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
383 symbols->ParseFunctionBlocks(sc);
385 // Parse the variables for this function and all its blocks
386 symbols->ParseVariablesForContext(sc);
390 // Parse all types for this compile unit
392 symbols->ParseTypes(sc);
398 Module::CalculateSymbolContext(SymbolContext* sc)
400 sc->module_sp = shared_from_this();
404 Module::CalculateSymbolContextModule ()
406 return shared_from_this();
410 Module::DumpSymbolContext(Stream *s)
412 s->Printf(", Module{%p}", this);
416 Module::GetNumCompileUnits()
418 Mutex::Locker locker (m_mutex);
419 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
420 SymbolVendor *symbols = GetSymbolVendor ();
422 return symbols->GetNumCompileUnits();
427 Module::GetCompileUnitAtIndex (size_t index)
429 Mutex::Locker locker (m_mutex);
430 size_t num_comp_units = GetNumCompileUnits ();
433 if (index < num_comp_units)
435 SymbolVendor *symbols = GetSymbolVendor ();
437 cu_sp = symbols->GetCompileUnitAtIndex(index);
443 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
445 Mutex::Locker locker (m_mutex);
446 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr);
447 SectionList *section_list = GetSectionList();
449 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
454 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc,
455 bool resolve_tail_call_address)
457 Mutex::Locker locker (m_mutex);
458 uint32_t resolved_flags = 0;
460 // Clear the result symbol context in case we don't find anything, but don't clear the target
463 // Get the section from the section/offset address.
464 SectionSP section_sp (so_addr.GetSection());
466 // Make sure the section matches this module before we try and match anything
467 if (section_sp && section_sp->GetModule().get() == this)
469 // If the section offset based address resolved itself, then this
470 // is the right module.
471 sc.module_sp = shared_from_this();
472 resolved_flags |= eSymbolContextModule;
474 SymbolVendor* sym_vendor = GetSymbolVendor();
476 return resolved_flags;
478 // Resolve the compile unit, function, block, line table or line
479 // entry if requested.
480 if (resolve_scope & eSymbolContextCompUnit ||
481 resolve_scope & eSymbolContextFunction ||
482 resolve_scope & eSymbolContextBlock ||
483 resolve_scope & eSymbolContextLineEntry )
485 resolved_flags |= sym_vendor->ResolveSymbolContext (so_addr, resolve_scope, sc);
488 // Resolve the symbol if requested, but don't re-look it up if we've already found it.
489 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
491 Symtab *symtab = sym_vendor->GetSymtab();
492 if (symtab && so_addr.IsSectionOffset())
494 sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
496 resolve_scope & eSymbolContextFunction && !(resolved_flags & eSymbolContextFunction))
498 bool verify_unique = false; // No need to check again since ResolveSymbolContext failed to find a symbol at this address.
499 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
500 sc.symbol = obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
505 if (sc.symbol->IsSynthetic())
507 // We have a synthetic symbol so lets check if the object file
508 // from the symbol file in the symbol vendor is different than
509 // the object file for the module, and if so search its symbol
510 // table to see if we can come up with a better symbol. For example
511 // dSYM files on MacOSX have an unstripped symbol table inside of
513 ObjectFile *symtab_objfile = symtab->GetObjectFile();
514 if (symtab_objfile && symtab_objfile->IsStripped())
516 SymbolFile *symfile = sym_vendor->GetSymbolFile();
519 ObjectFile *symfile_objfile = symfile->GetObjectFile();
520 if (symfile_objfile != symtab_objfile)
522 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
525 Symbol *symbol = symfile_symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
526 if (symbol && !symbol->IsSynthetic())
535 resolved_flags |= eSymbolContextSymbol;
540 // For function symbols, so_addr may be off by one. This is a convention consistent
541 // with FDE row indices in eh_frame sections, but requires extra logic here to permit
542 // symbol lookup for disassembly and unwind.
543 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol) &&
544 resolve_tail_call_address && so_addr.IsSectionOffset())
546 Address previous_addr = so_addr;
547 previous_addr.Slide(-1);
549 bool do_resolve_tail_call_address = false; // prevent recursion
550 const uint32_t flags = ResolveSymbolContextForAddress(previous_addr, resolve_scope, sc,
551 do_resolve_tail_call_address);
552 if (flags & eSymbolContextSymbol)
554 AddressRange addr_range;
555 if (sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
557 if (addr_range.GetBaseAddress().GetSection() == so_addr.GetSection())
559 // If the requested address is one past the address range of a function (i.e. a tail call),
560 // or the decremented address is the start of a function (i.e. some forms of trampoline),
561 // indicate that the symbol has been resolved.
562 if (so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() ||
563 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() + addr_range.GetByteSize())
565 resolved_flags |= flags;
570 sc.symbol = nullptr; // Don't trust the symbol if the sections didn't match.
576 return resolved_flags;
580 Module::ResolveSymbolContextForFilePath
582 const char *file_path,
585 uint32_t resolve_scope,
586 SymbolContextList& sc_list
589 FileSpec file_spec(file_path, false);
590 return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
594 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
596 Mutex::Locker locker (m_mutex);
597 Timer scoped_timer(__PRETTY_FUNCTION__,
598 "Module::ResolveSymbolContextForFilePath (%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
599 file_spec.GetPath().c_str(),
601 check_inlines ? "yes" : "no",
604 const uint32_t initial_count = sc_list.GetSize();
606 SymbolVendor *symbols = GetSymbolVendor ();
608 symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
610 return sc_list.GetSize() - initial_count;
615 Module::FindGlobalVariables (const ConstString &name,
616 const ClangNamespaceDecl *namespace_decl,
619 VariableList& variables)
621 SymbolVendor *symbols = GetSymbolVendor ();
623 return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
628 Module::FindGlobalVariables (const RegularExpression& regex,
631 VariableList& variables)
633 SymbolVendor *symbols = GetSymbolVendor ();
635 return symbols->FindGlobalVariables(regex, append, max_matches, variables);
640 Module::FindCompileUnits (const FileSpec &path,
642 SymbolContextList &sc_list)
647 const size_t start_size = sc_list.GetSize();
648 const size_t num_compile_units = GetNumCompileUnits();
650 sc.module_sp = shared_from_this();
651 const bool compare_directory = (bool)path.GetDirectory();
652 for (size_t i=0; i<num_compile_units; ++i)
654 sc.comp_unit = GetCompileUnitAtIndex(i).get();
657 if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
661 return sc_list.GetSize() - start_size;
665 Module::FindFunctions (const ConstString &name,
666 const ClangNamespaceDecl *namespace_decl,
667 uint32_t name_type_mask,
668 bool include_symbols,
669 bool include_inlines,
671 SymbolContextList& sc_list)
676 const size_t old_size = sc_list.GetSize();
678 // Find all the functions (not symbols, but debug information functions...
679 SymbolVendor *symbols = GetSymbolVendor ();
681 if (name_type_mask & eFunctionNameTypeAuto)
683 ConstString lookup_name;
684 uint32_t lookup_name_type_mask = 0;
685 bool match_name_after_lookup = false;
686 Module::PrepareForFunctionNameLookup (name,
689 lookup_name_type_mask,
690 match_name_after_lookup);
694 symbols->FindFunctions(lookup_name,
696 lookup_name_type_mask,
701 // Now check our symbol table for symbols that are code symbols if requested
704 Symtab *symtab = symbols->GetSymtab();
706 symtab->FindFunctionSymbols(lookup_name, lookup_name_type_mask, sc_list);
710 if (match_name_after_lookup)
714 while (i<sc_list.GetSize())
716 if (sc_list.GetContextAtIndex(i, sc))
718 const char *func_name = sc.GetFunctionName().GetCString();
719 if (func_name && strstr (func_name, name.GetCString()) == NULL)
721 // Remove the current context
722 sc_list.RemoveContextAtIndex(i);
723 // Don't increment i and continue in the loop
735 symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
737 // Now check our symbol table for symbols that are code symbols if requested
740 Symtab *symtab = symbols->GetSymtab();
742 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
747 return sc_list.GetSize() - old_size;
751 Module::FindFunctions (const RegularExpression& regex,
752 bool include_symbols,
753 bool include_inlines,
755 SymbolContextList& sc_list)
760 const size_t start_size = sc_list.GetSize();
762 SymbolVendor *symbols = GetSymbolVendor ();
765 symbols->FindFunctions(regex, include_inlines, append, sc_list);
767 // Now check our symbol table for symbols that are code symbols if requested
770 Symtab *symtab = symbols->GetSymtab();
773 std::vector<uint32_t> symbol_indexes;
774 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
775 const size_t num_matches = symbol_indexes.size();
778 SymbolContext sc(this);
779 const size_t end_functions_added_index = sc_list.GetSize();
780 size_t num_functions_added_to_sc_list = end_functions_added_index - start_size;
781 if (num_functions_added_to_sc_list == 0)
783 // No functions were added, just symbols, so we can just append them
784 for (size_t i=0; i<num_matches; ++i)
786 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
787 SymbolType sym_type = sc.symbol->GetType();
788 if (sc.symbol && (sym_type == eSymbolTypeCode ||
789 sym_type == eSymbolTypeResolver))
795 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
796 FileAddrToIndexMap file_addr_to_index;
797 for (size_t i=start_size; i<end_functions_added_index; ++i)
799 const SymbolContext &sc = sc_list[i];
802 file_addr_to_index[sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()] = i;
805 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
806 // Functions were added so we need to merge symbols into any
807 // existing function symbol contexts
808 for (size_t i=start_size; i<num_matches; ++i)
810 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
811 SymbolType sym_type = sc.symbol->GetType();
812 if (sc.symbol && (sym_type == eSymbolTypeCode ||
813 sym_type == eSymbolTypeResolver))
815 FileAddrToIndexMap::const_iterator pos = file_addr_to_index.find(sc.symbol->GetAddress().GetFileAddress());
819 sc_list[pos->second].symbol = sc.symbol;
827 return sc_list.GetSize() - start_size;
831 Module::FindAddressesForLine (const lldb::TargetSP target_sp,
832 const FileSpec &file, uint32_t line,
834 std::vector<Address> &output_local, std::vector<Address> &output_extern)
836 SearchFilterByModule filter(target_sp, m_file);
837 AddressResolverFileLine resolver(file, line, true);
838 resolver.ResolveAddress (filter);
840 for (size_t n=0;n<resolver.GetNumberOfAddresses();n++)
842 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
843 Function *f = addr.CalculateSymbolContextFunction();
844 if (f && f == function)
845 output_local.push_back (addr);
847 output_extern.push_back (addr);
852 Module::FindTypes_Impl (const SymbolContext& sc,
853 const ConstString &name,
854 const ClangNamespaceDecl *namespace_decl,
859 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
860 if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
862 SymbolVendor *symbols = GetSymbolVendor ();
864 return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
870 Module::FindTypesInNamespace (const SymbolContext& sc,
871 const ConstString &type_name,
872 const ClangNamespaceDecl *namespace_decl,
876 const bool append = true;
877 return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
881 Module::FindFirstType (const SymbolContext& sc,
882 const ConstString &name,
886 const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
888 return type_list.GetTypeAtIndex(0);
894 Module::FindTypes (const SymbolContext& sc,
895 const ConstString &name,
900 size_t num_matches = 0;
901 const char *type_name_cstr = name.GetCString();
902 std::string type_scope;
903 std::string type_basename;
904 const bool append = true;
905 TypeClass type_class = eTypeClassAny;
906 if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
908 // Check if "name" starts with "::" which means the qualified type starts
909 // from the root namespace and implies and exact match. The typenames we
910 // get back from clang do not start with "::" so we need to strip this off
911 // in order to get the qualfied names to match
913 if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
915 type_scope.erase(0,2);
918 ConstString type_basename_const_str (type_basename.c_str());
919 if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
921 types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
922 num_matches = types.GetSize();
927 // The type is not in a namespace/class scope, just search for it by basename
928 if (type_class != eTypeClassAny)
930 // The "type_name_cstr" will have been modified if we have a valid type class
931 // prefix (like "struct", "class", "union", "typedef" etc).
932 num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
933 types.RemoveMismatchedTypes (type_class);
934 num_matches = types.GetSize();
938 num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
947 Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
949 Mutex::Locker locker (m_mutex);
950 if (m_did_load_symbol_vendor == false && can_create)
952 ObjectFile *obj_file = GetObjectFile ();
953 if (obj_file != NULL)
955 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
956 m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
957 m_did_load_symbol_vendor = true;
960 return m_symfile_ap.get();
964 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
966 // Container objects whose paths do not specify a file directly can call
967 // this function to correct the file and object names.
969 m_mod_time = file.GetModificationTime();
970 m_object_name = object_name;
974 Module::GetArchitecture () const
980 Module::GetSpecificationDescription () const
982 std::string spec(GetFileSpec().GetPath());
986 spec += m_object_name.GetCString();
993 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
995 Mutex::Locker locker (m_mutex);
997 if (level >= eDescriptionLevelFull)
999 if (m_arch.IsValid())
1000 s->Printf("(%s) ", m_arch.GetArchitectureName());
1003 if (level == eDescriptionLevelBrief)
1005 const char *filename = m_file.GetFilename().GetCString();
1007 s->PutCString (filename);
1011 char path[PATH_MAX];
1012 if (m_file.GetPath(path, sizeof(path)))
1013 s->PutCString(path);
1016 const char *object_name = m_object_name.GetCString();
1018 s->Printf("(%s)", object_name);
1022 Module::ReportError (const char *format, ...)
1024 if (format && format[0])
1027 strm.PutCString("error: ");
1028 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1031 va_start (args, format);
1032 strm.PrintfVarArg(format, args);
1035 const int format_len = strlen(format);
1038 const char last_char = format[format_len-1];
1039 if (last_char != '\n' || last_char != '\r')
1042 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1048 Module::FileHasChanged () const
1050 if (m_file_has_changed == false)
1051 m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
1052 return m_file_has_changed;
1056 Module::ReportErrorIfModifyDetected (const char *format, ...)
1058 if (m_first_file_changed_log == false)
1060 if (FileHasChanged ())
1062 m_first_file_changed_log = true;
1066 strm.PutCString("error: the object file ");
1067 GetDescription(&strm, lldb::eDescriptionLevelFull);
1068 strm.PutCString (" has been modified\n");
1071 va_start (args, format);
1072 strm.PrintfVarArg(format, args);
1075 const int format_len = strlen(format);
1078 const char last_char = format[format_len-1];
1079 if (last_char != '\n' || last_char != '\r')
1082 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
1083 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1090 Module::ReportWarning (const char *format, ...)
1092 if (format && format[0])
1095 strm.PutCString("warning: ");
1096 GetDescription(&strm, lldb::eDescriptionLevelFull);
1100 va_start (args, format);
1101 strm.PrintfVarArg(format, args);
1104 const int format_len = strlen(format);
1107 const char last_char = format[format_len-1];
1108 if (last_char != '\n' || last_char != '\r')
1111 Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
1116 Module::LogMessage (Log *log, const char *format, ...)
1120 StreamString log_message;
1121 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1122 log_message.PutCString (": ");
1124 va_start (args, format);
1125 log_message.PrintfVarArg (format, args);
1127 log->PutCString(log_message.GetString().c_str());
1132 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
1136 StreamString log_message;
1137 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1138 log_message.PutCString (": ");
1140 va_start (args, format);
1141 log_message.PrintfVarArg (format, args);
1143 if (log->GetVerbose())
1144 Host::Backtrace (log_message, 1024);
1145 log->PutCString(log_message.GetString().c_str());
1150 Module::Dump(Stream *s)
1152 Mutex::Locker locker (m_mutex);
1153 //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1155 s->Printf("Module %s%s%s%s\n",
1156 m_file.GetPath().c_str(),
1157 m_object_name ? "(" : "",
1158 m_object_name ? m_object_name.GetCString() : "",
1159 m_object_name ? ")" : "");
1163 ObjectFile *objfile = GetObjectFile ();
1167 SymbolVendor *symbols = GetSymbolVendor ();
1176 Module::GetTypeList ()
1178 SymbolVendor *symbols = GetSymbolVendor ();
1180 return &symbols->GetTypeList();
1185 Module::GetObjectName() const
1187 return m_object_name;
1191 Module::GetObjectFile()
1193 Mutex::Locker locker (m_mutex);
1194 if (m_did_load_objfile == false)
1196 Timer scoped_timer(__PRETTY_FUNCTION__,
1197 "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1198 DataBufferSP data_sp;
1199 lldb::offset_t data_offset = 0;
1200 const lldb::offset_t file_size = m_file.GetByteSize();
1201 if (file_size > m_object_offset)
1203 m_did_load_objfile = true;
1204 m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1207 file_size - m_object_offset,
1212 // Once we get the object file, update our module with the object file's
1213 // architecture since it might differ in vendor/os if some parts were
1215 m_objfile_sp->GetArchitecture (m_arch);
1219 return m_objfile_sp.get();
1223 Module::GetSectionList()
1225 // Populate m_unified_sections_ap with sections from objfile.
1226 if (m_sections_ap.get() == NULL)
1228 ObjectFile *obj_file = GetObjectFile();
1230 obj_file->CreateSections(*GetUnifiedSectionList());
1232 return m_sections_ap.get();
1236 Module::GetUnifiedSectionList()
1238 // Populate m_unified_sections_ap with sections from objfile.
1239 if (m_sections_ap.get() == NULL)
1240 m_sections_ap.reset(new SectionList());
1241 return m_sections_ap.get();
1245 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1247 Timer scoped_timer(__PRETTY_FUNCTION__,
1248 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1251 SymbolVendor* sym_vendor = GetSymbolVendor();
1254 Symtab *symtab = sym_vendor->GetSymtab();
1256 return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1261 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1263 // No need to protect this call using m_mutex all other method calls are
1264 // already thread safe.
1266 size_t num_indices = symbol_indexes.size();
1267 if (num_indices > 0)
1270 CalculateSymbolContext (&sc);
1271 for (size_t i = 0; i < num_indices; i++)
1273 sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1275 sc_list.Append (sc);
1281 Module::FindFunctionSymbols (const ConstString &name,
1282 uint32_t name_type_mask,
1283 SymbolContextList& sc_list)
1285 Timer scoped_timer(__PRETTY_FUNCTION__,
1286 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1289 SymbolVendor* sym_vendor = GetSymbolVendor();
1292 Symtab *symtab = sym_vendor->GetSymtab();
1294 return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1300 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1302 // No need to protect this call using m_mutex all other method calls are
1303 // already thread safe.
1306 Timer scoped_timer(__PRETTY_FUNCTION__,
1307 "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1310 const size_t initial_size = sc_list.GetSize();
1311 SymbolVendor* sym_vendor = GetSymbolVendor();
1314 Symtab *symtab = sym_vendor->GetSymtab();
1317 std::vector<uint32_t> symbol_indexes;
1318 symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1319 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1322 return sc_list.GetSize() - initial_size;
1326 Module::FindSymbolsMatchingRegExAndType (const RegularExpression ®ex, SymbolType symbol_type, SymbolContextList &sc_list)
1328 // No need to protect this call using m_mutex all other method calls are
1329 // already thread safe.
1331 Timer scoped_timer(__PRETTY_FUNCTION__,
1332 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1335 const size_t initial_size = sc_list.GetSize();
1336 SymbolVendor* sym_vendor = GetSymbolVendor();
1339 Symtab *symtab = sym_vendor->GetSymtab();
1342 std::vector<uint32_t> symbol_indexes;
1343 symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1344 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1347 return sc_list.GetSize() - initial_size;
1351 Module::SetSymbolFileFileSpec (const FileSpec &file)
1353 // Remove any sections in the unified section list that come from the current symbol vendor.
1356 SectionList *section_list = GetSectionList();
1357 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1358 if (section_list && symbol_file)
1360 ObjectFile *obj_file = symbol_file->GetObjectFile();
1361 // Make sure we have an object file and that the symbol vendor's objfile isn't
1362 // the same as the module's objfile before we remove any sections for it...
1363 if (obj_file && obj_file != m_objfile_sp.get())
1365 size_t num_sections = section_list->GetNumSections (0);
1366 for (size_t idx = num_sections; idx > 0; --idx)
1368 lldb::SectionSP section_sp (section_list->GetSectionAtIndex (idx - 1));
1369 if (section_sp->GetObjectFile() == obj_file)
1371 section_list->DeleteSection (idx - 1);
1378 m_symfile_spec = file;
1379 m_symfile_ap.reset();
1380 m_did_load_symbol_vendor = false;
1384 Module::IsExecutable ()
1386 if (GetObjectFile() == NULL)
1389 return GetObjectFile()->IsExecutable();
1393 Module::IsLoadedInTarget (Target *target)
1395 ObjectFile *obj_file = GetObjectFile();
1398 SectionList *sections = GetSectionList();
1399 if (sections != NULL)
1401 size_t num_sections = sections->GetSize();
1402 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1404 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1405 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1416 Module::LoadScriptingResourceInTarget (Target *target, Error& error, Stream* feedback_stream)
1420 error.SetErrorString("invalid destination Target");
1424 LoadScriptFromSymFile shoud_load = target->TargetProperties::GetLoadScriptFromSymbolFile();
1426 Debugger &debugger = target->GetDebugger();
1427 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1428 if (script_language != eScriptLanguageNone)
1431 PlatformSP platform_sp(target->GetPlatform());
1435 error.SetErrorString("invalid Platform");
1439 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1443 const uint32_t num_specs = file_specs.GetSize();
1446 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1447 if (script_interpreter)
1449 for (uint32_t i=0; i<num_specs; ++i)
1451 FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1452 if (scripting_fspec && scripting_fspec.Exists())
1454 if (shoud_load == eLoadScriptFromSymFileFalse)
1456 if (shoud_load == eLoadScriptFromSymFileWarn)
1458 if (feedback_stream)
1459 feedback_stream->Printf("warning: '%s' contains a debug script. To run this script in "
1460 "this debug session:\n\n command script import \"%s\"\n\n"
1461 "To run all discovered debug scripts in this session:\n\n"
1462 " settings set target.load-script-from-symbol-file true\n",
1463 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1464 scripting_fspec.GetPath().c_str());
1467 StreamString scripting_stream;
1468 scripting_fspec.Dump(&scripting_stream);
1469 const bool can_reload = true;
1470 const bool init_lldb_globals = false;
1471 bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(),
1482 error.SetErrorString("invalid ScriptInterpreter");
1491 Module::SetArchitecture (const ArchSpec &new_arch)
1493 if (!m_arch.IsValid())
1498 return m_arch.IsExactMatch(new_arch);
1502 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1504 size_t num_loaded_sections = 0;
1505 SectionList *section_list = GetSectionList ();
1508 const size_t num_sections = section_list->GetSize();
1509 size_t sect_idx = 0;
1510 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1512 // Iterate through the object file sections to find the
1513 // first section that starts of file offset zero and that
1514 // has bytes in the file...
1515 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1516 // Only load non-thread specific sections when given a slide
1517 if (section_sp && !section_sp->IsThreadSpecific())
1519 if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1520 ++num_loaded_sections;
1524 changed = num_loaded_sections > 0;
1525 return num_loaded_sections > 0;
1530 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1532 const UUID &uuid = module_ref.GetUUID();
1536 // If the UUID matches, then nothing more needs to match...
1537 if (uuid == GetUUID())
1543 const FileSpec &file_spec = module_ref.GetFileSpec();
1546 if (!FileSpec::Equal (file_spec, m_file, (bool)file_spec.GetDirectory()))
1550 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1551 if (platform_file_spec)
1553 if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), (bool)platform_file_spec.GetDirectory()))
1557 const ArchSpec &arch = module_ref.GetArchitecture();
1560 if (!m_arch.IsCompatibleMatch(arch))
1564 const ConstString &object_name = module_ref.GetObjectName();
1567 if (object_name != GetObjectName())
1574 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1576 Mutex::Locker locker (m_mutex);
1577 return m_source_mappings.FindFile (orig_spec, new_spec);
1581 Module::RemapSourceFile (const char *path, std::string &new_path) const
1583 Mutex::Locker locker (m_mutex);
1584 return m_source_mappings.RemapPath(path, new_path);
1588 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1590 ObjectFile *obj_file = GetObjectFile();
1592 return obj_file->GetVersion (versions, num_versions);
1594 if (versions && num_versions)
1596 for (uint32_t i=0; i<num_versions; ++i)
1597 versions[i] = UINT32_MAX;
1603 Module::PrepareForFunctionNameLookup (const ConstString &name,
1604 uint32_t name_type_mask,
1605 ConstString &lookup_name,
1606 uint32_t &lookup_name_type_mask,
1607 bool &match_name_after_lookup)
1609 const char *name_cstr = name.GetCString();
1610 lookup_name_type_mask = eFunctionNameTypeNone;
1611 match_name_after_lookup = false;
1612 const char *base_name_start = NULL;
1613 const char *base_name_end = NULL;
1615 if (name_type_mask & eFunctionNameTypeAuto)
1617 if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
1618 lookup_name_type_mask = eFunctionNameTypeFull;
1619 else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
1620 lookup_name_type_mask = eFunctionNameTypeFull;
1623 if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1624 lookup_name_type_mask |= eFunctionNameTypeSelector;
1626 CPPLanguageRuntime::MethodName cpp_method (name);
1627 llvm::StringRef basename (cpp_method.GetBasename());
1628 if (basename.empty())
1630 if (CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1631 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1635 base_name_start = basename.data();
1636 base_name_end = base_name_start + basename.size();
1637 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1643 lookup_name_type_mask = name_type_mask;
1644 if (lookup_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
1646 // If they've asked for a CPP method or function name and it can't be that, we don't
1647 // even need to search for CPP methods or names.
1648 CPPLanguageRuntime::MethodName cpp_method (name);
1649 if (cpp_method.IsValid())
1651 llvm::StringRef basename (cpp_method.GetBasename());
1652 base_name_start = basename.data();
1653 base_name_end = base_name_start + basename.size();
1655 if (!cpp_method.GetQualifiers().empty())
1657 // There is a "const" or other qualifer following the end of the fucntion parens,
1658 // this can't be a eFunctionNameTypeBase
1659 lookup_name_type_mask &= ~(eFunctionNameTypeBase);
1660 if (lookup_name_type_mask == eFunctionNameTypeNone)
1666 if (!CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1668 lookup_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
1669 if (lookup_name_type_mask == eFunctionNameTypeNone)
1675 if (lookup_name_type_mask & eFunctionNameTypeSelector)
1677 if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1679 lookup_name_type_mask &= ~(eFunctionNameTypeSelector);
1680 if (lookup_name_type_mask == eFunctionNameTypeNone)
1686 if (base_name_start &&
1688 base_name_start != name_cstr &&
1689 base_name_start < base_name_end)
1691 // The name supplied was a partial C++ path like "a::count". In this case we want to do a
1692 // lookup on the basename "count" and then make sure any matching results contain "a::count"
1693 // so that it would match "b::a::count" and "a::count". This is why we set "match_name_after_lookup"
1695 lookup_name.SetCStringWithLength(base_name_start, base_name_end - base_name_start);
1696 match_name_after_lookup = true;
1700 // The name is already correct, just use the exact name as supplied, and we won't need
1701 // to check if any matches contain "name"
1703 match_name_after_lookup = false;