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_symfile_spec (module_spec.GetSymbolFileSpec()),
139 m_object_name (module_spec.GetObjectName()),
140 m_object_offset (module_spec.GetObjectOffset()),
141 m_object_mod_time (module_spec.GetObjectModificationTime()),
145 m_source_mappings (),
146 m_did_load_objfile (false),
147 m_did_load_symbol_vendor (false),
148 m_did_parse_uuid (false),
149 m_did_init_ast (false),
150 m_is_dynamic_loader_module (false),
151 m_file_has_changed (false),
152 m_first_file_changed_log (false)
154 // Scope for locker below...
156 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
157 GetModuleCollection().push_back(this);
160 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
162 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
164 m_arch.GetArchitectureName(),
165 m_file.GetPath().c_str(),
166 m_object_name.IsEmpty() ? "" : "(",
167 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
168 m_object_name.IsEmpty() ? "" : ")");
171 Module::Module(const FileSpec& file_spec,
172 const ArchSpec& arch,
173 const ConstString *object_name,
175 const TimeValue *object_mod_time_ptr) :
176 m_mutex (Mutex::eMutexTypeRecursive),
177 m_mod_time (file_spec.GetModificationTime()),
184 m_object_offset (object_offset),
185 m_object_mod_time (),
189 m_source_mappings (),
190 m_did_load_objfile (false),
191 m_did_load_symbol_vendor (false),
192 m_did_parse_uuid (false),
193 m_did_init_ast (false),
194 m_is_dynamic_loader_module (false),
195 m_file_has_changed (false),
196 m_first_file_changed_log (false)
198 // Scope for locker below...
200 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
201 GetModuleCollection().push_back(this);
205 m_object_name = *object_name;
207 if (object_mod_time_ptr)
208 m_object_mod_time = *object_mod_time_ptr;
210 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
212 log->Printf ("%p Module::Module((%s) '%s%s%s%s')",
214 m_arch.GetArchitectureName(),
215 m_file.GetPath().c_str(),
216 m_object_name.IsEmpty() ? "" : "(",
217 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
218 m_object_name.IsEmpty() ? "" : ")");
223 // Lock our module down while we tear everything down to make sure
224 // we don't get any access to the module while it is being destroyed
225 Mutex::Locker locker (m_mutex);
226 // Scope for locker below...
228 Mutex::Locker locker (GetAllocationModuleCollectionMutex());
229 ModuleCollection &modules = GetModuleCollection();
230 ModuleCollection::iterator end = modules.end();
231 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
235 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT|LIBLLDB_LOG_MODULES));
237 log->Printf ("%p Module::~Module((%s) '%s%s%s%s')",
239 m_arch.GetArchitectureName(),
240 m_file.GetPath().c_str(),
241 m_object_name.IsEmpty() ? "" : "(",
242 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
243 m_object_name.IsEmpty() ? "" : ")");
244 // Release any auto pointers before we start tearing down our member
245 // variables since the object file and symbol files might need to make
246 // function calls back into this module object. The ordering is important
247 // here because symbol files can require the module object file. So we tear
248 // down the symbol file first, then the object file.
249 m_sections_ap.reset();
250 m_symfile_ap.reset();
251 m_objfile_sp.reset();
255 Module::GetMemoryObjectFile (const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Error &error)
259 error.SetErrorString ("object file already exists");
263 Mutex::Locker locker (m_mutex);
266 m_did_load_objfile = true;
267 std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (512, 0));
269 const size_t bytes_read = process_sp->ReadMemory (header_addr,
271 data_ap->GetByteSize(),
273 if (bytes_read == 512)
275 DataBufferSP data_sp(data_ap.release());
276 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, header_addr, data_sp);
280 s.Printf("0x%16.16" PRIx64, header_addr);
281 m_object_name.SetCString (s.GetData());
283 // Once we get the object file, update our module with the object file's
284 // architecture since it might differ in vendor/os if some parts were
286 m_objfile_sp->GetArchitecture (m_arch);
290 error.SetErrorString ("unable to find suitable object file plug-in");
295 error.SetErrorStringWithFormat ("unable to read header from memory: %s", readmem_error.AsCString());
300 error.SetErrorString ("invalid process");
303 return m_objfile_sp.get();
307 const lldb_private::UUID&
310 Mutex::Locker locker (m_mutex);
311 if (m_did_parse_uuid == false)
313 ObjectFile * obj_file = GetObjectFile ();
315 if (obj_file != NULL)
317 obj_file->GetUUID(&m_uuid);
318 m_did_parse_uuid = true;
325 Module::GetClangASTContext ()
327 Mutex::Locker locker (m_mutex);
328 if (m_did_init_ast == false)
330 ObjectFile * objfile = GetObjectFile();
331 ArchSpec object_arch;
332 if (objfile && objfile->GetArchitecture(object_arch))
334 m_did_init_ast = true;
336 // LLVM wants this to be set to iOS or MacOSX; if we're working on
337 // a bare-boards type image, change the triple for llvm's benefit.
338 if (object_arch.GetTriple().getVendor() == llvm::Triple::Apple
339 && object_arch.GetTriple().getOS() == llvm::Triple::UnknownOS)
341 if (object_arch.GetTriple().getArch() == llvm::Triple::arm ||
342 object_arch.GetTriple().getArch() == llvm::Triple::thumb)
344 object_arch.GetTriple().setOS(llvm::Triple::IOS);
348 object_arch.GetTriple().setOS(llvm::Triple::MacOSX);
351 m_ast.SetArchitecture (object_arch);
358 Module::ParseAllDebugSymbols()
360 Mutex::Locker locker (m_mutex);
361 size_t num_comp_units = GetNumCompileUnits();
362 if (num_comp_units == 0)
366 sc.module_sp = shared_from_this();
367 SymbolVendor *symbols = GetSymbolVendor ();
369 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++)
371 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
375 symbols->ParseVariablesForContext(sc);
377 symbols->ParseCompileUnitFunctions(sc);
379 for (size_t func_idx = 0; (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != NULL; ++func_idx)
381 symbols->ParseFunctionBlocks(sc);
383 // Parse the variables for this function and all its blocks
384 symbols->ParseVariablesForContext(sc);
388 // Parse all types for this compile unit
390 symbols->ParseTypes(sc);
396 Module::CalculateSymbolContext(SymbolContext* sc)
398 sc->module_sp = shared_from_this();
402 Module::CalculateSymbolContextModule ()
404 return shared_from_this();
408 Module::DumpSymbolContext(Stream *s)
410 s->Printf(", Module{%p}", this);
414 Module::GetNumCompileUnits()
416 Mutex::Locker locker (m_mutex);
417 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::GetNumCompileUnits (module = %p)", this);
418 SymbolVendor *symbols = GetSymbolVendor ();
420 return symbols->GetNumCompileUnits();
425 Module::GetCompileUnitAtIndex (size_t index)
427 Mutex::Locker locker (m_mutex);
428 size_t num_comp_units = GetNumCompileUnits ();
431 if (index < num_comp_units)
433 SymbolVendor *symbols = GetSymbolVendor ();
435 cu_sp = symbols->GetCompileUnitAtIndex(index);
441 Module::ResolveFileAddress (lldb::addr_t vm_addr, Address& so_addr)
443 Mutex::Locker locker (m_mutex);
444 Timer scoped_timer(__PRETTY_FUNCTION__, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr);
445 SectionList *section_list = GetSectionList();
447 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
452 Module::ResolveSymbolContextForAddress (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc,
453 bool resolve_tail_call_address)
455 Mutex::Locker locker (m_mutex);
456 uint32_t resolved_flags = 0;
458 // Clear the result symbol context in case we don't find anything, but don't clear the target
461 // Get the section from the section/offset address.
462 SectionSP section_sp (so_addr.GetSection());
464 // Make sure the section matches this module before we try and match anything
465 if (section_sp && section_sp->GetModule().get() == this)
467 // If the section offset based address resolved itself, then this
468 // is the right module.
469 sc.module_sp = shared_from_this();
470 resolved_flags |= eSymbolContextModule;
472 SymbolVendor* sym_vendor = GetSymbolVendor();
474 return resolved_flags;
476 // Resolve the compile unit, function, block, line table or line
477 // entry if requested.
478 if (resolve_scope & eSymbolContextCompUnit ||
479 resolve_scope & eSymbolContextFunction ||
480 resolve_scope & eSymbolContextBlock ||
481 resolve_scope & eSymbolContextLineEntry )
483 resolved_flags |= sym_vendor->ResolveSymbolContext (so_addr, resolve_scope, sc);
486 // Resolve the symbol if requested, but don't re-look it up if we've already found it.
487 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol))
489 Symtab *symtab = sym_vendor->GetSymtab();
490 if (symtab && so_addr.IsSectionOffset())
492 sc.symbol = symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
494 resolve_scope & eSymbolContextFunction && !(resolved_flags & eSymbolContextFunction))
496 bool verify_unique = false; // No need to check again since ResolveSymbolContext failed to find a symbol at this address.
497 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
498 sc.symbol = obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
503 if (sc.symbol->IsSynthetic())
505 // We have a synthetic symbol so lets check if the object file
506 // from the symbol file in the symbol vendor is different than
507 // the object file for the module, and if so search its symbol
508 // table to see if we can come up with a better symbol. For example
509 // dSYM files on MacOSX have an unstripped symbol table inside of
511 ObjectFile *symtab_objfile = symtab->GetObjectFile();
512 if (symtab_objfile && symtab_objfile->IsStripped())
514 SymbolFile *symfile = sym_vendor->GetSymbolFile();
517 ObjectFile *symfile_objfile = symfile->GetObjectFile();
518 if (symfile_objfile != symtab_objfile)
520 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
523 Symbol *symbol = symfile_symtab->FindSymbolContainingFileAddress(so_addr.GetFileAddress());
524 if (symbol && !symbol->IsSynthetic())
533 resolved_flags |= eSymbolContextSymbol;
538 // For function symbols, so_addr may be off by one. This is a convention consistent
539 // with FDE row indices in eh_frame sections, but requires extra logic here to permit
540 // symbol lookup for disassembly and unwind.
541 if (resolve_scope & eSymbolContextSymbol && !(resolved_flags & eSymbolContextSymbol) &&
542 resolve_tail_call_address && so_addr.IsSectionOffset())
544 Address previous_addr = so_addr;
545 previous_addr.Slide(-1);
547 bool do_resolve_tail_call_address = false; // prevent recursion
548 const uint32_t flags = ResolveSymbolContextForAddress(previous_addr, resolve_scope, sc,
549 do_resolve_tail_call_address);
550 if (flags & eSymbolContextSymbol)
552 AddressRange addr_range;
553 if (sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
555 if (addr_range.GetBaseAddress().GetSection() == so_addr.GetSection())
557 // If the requested address is one past the address range of a function (i.e. a tail call),
558 // or the decremented address is the start of a function (i.e. some forms of trampoline),
559 // indicate that the symbol has been resolved.
560 if (so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() ||
561 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() + addr_range.GetByteSize())
563 resolved_flags |= flags;
568 sc.symbol = nullptr; // Don't trust the symbol if the sections didn't match.
574 return resolved_flags;
578 Module::ResolveSymbolContextForFilePath
580 const char *file_path,
583 uint32_t resolve_scope,
584 SymbolContextList& sc_list
587 FileSpec file_spec(file_path, false);
588 return ResolveSymbolContextsForFileSpec (file_spec, line, check_inlines, resolve_scope, sc_list);
592 Module::ResolveSymbolContextsForFileSpec (const FileSpec &file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
594 Mutex::Locker locker (m_mutex);
595 Timer scoped_timer(__PRETTY_FUNCTION__,
596 "Module::ResolveSymbolContextForFilePath (%s:%u, check_inlines = %s, resolve_scope = 0x%8.8x)",
597 file_spec.GetPath().c_str(),
599 check_inlines ? "yes" : "no",
602 const uint32_t initial_count = sc_list.GetSize();
604 SymbolVendor *symbols = GetSymbolVendor ();
606 symbols->ResolveSymbolContext (file_spec, line, check_inlines, resolve_scope, sc_list);
608 return sc_list.GetSize() - initial_count;
613 Module::FindGlobalVariables (const ConstString &name,
614 const ClangNamespaceDecl *namespace_decl,
617 VariableList& variables)
619 SymbolVendor *symbols = GetSymbolVendor ();
621 return symbols->FindGlobalVariables(name, namespace_decl, append, max_matches, variables);
626 Module::FindGlobalVariables (const RegularExpression& regex,
629 VariableList& variables)
631 SymbolVendor *symbols = GetSymbolVendor ();
633 return symbols->FindGlobalVariables(regex, append, max_matches, variables);
638 Module::FindCompileUnits (const FileSpec &path,
640 SymbolContextList &sc_list)
645 const size_t start_size = sc_list.GetSize();
646 const size_t num_compile_units = GetNumCompileUnits();
648 sc.module_sp = shared_from_this();
649 const bool compare_directory = (bool)path.GetDirectory();
650 for (size_t i=0; i<num_compile_units; ++i)
652 sc.comp_unit = GetCompileUnitAtIndex(i).get();
655 if (FileSpec::Equal (*sc.comp_unit, path, compare_directory))
659 return sc_list.GetSize() - start_size;
663 Module::FindFunctions (const ConstString &name,
664 const ClangNamespaceDecl *namespace_decl,
665 uint32_t name_type_mask,
666 bool include_symbols,
667 bool include_inlines,
669 SymbolContextList& sc_list)
674 const size_t old_size = sc_list.GetSize();
676 // Find all the functions (not symbols, but debug information functions...
677 SymbolVendor *symbols = GetSymbolVendor ();
679 if (name_type_mask & eFunctionNameTypeAuto)
681 ConstString lookup_name;
682 uint32_t lookup_name_type_mask = 0;
683 bool match_name_after_lookup = false;
684 Module::PrepareForFunctionNameLookup (name,
687 lookup_name_type_mask,
688 match_name_after_lookup);
692 symbols->FindFunctions(lookup_name,
694 lookup_name_type_mask,
699 // Now check our symbol table for symbols that are code symbols if requested
702 Symtab *symtab = symbols->GetSymtab();
704 symtab->FindFunctionSymbols(lookup_name, lookup_name_type_mask, sc_list);
708 if (match_name_after_lookup)
712 while (i<sc_list.GetSize())
714 if (sc_list.GetContextAtIndex(i, sc))
716 const char *func_name = sc.GetFunctionName().GetCString();
717 if (func_name && strstr (func_name, name.GetCString()) == NULL)
719 // Remove the current context
720 sc_list.RemoveContextAtIndex(i);
721 // Don't increment i and continue in the loop
733 symbols->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, append, sc_list);
735 // Now check our symbol table for symbols that are code symbols if requested
738 Symtab *symtab = symbols->GetSymtab();
740 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
745 return sc_list.GetSize() - old_size;
749 Module::FindFunctions (const RegularExpression& regex,
750 bool include_symbols,
751 bool include_inlines,
753 SymbolContextList& sc_list)
758 const size_t start_size = sc_list.GetSize();
760 SymbolVendor *symbols = GetSymbolVendor ();
763 symbols->FindFunctions(regex, include_inlines, append, sc_list);
765 // Now check our symbol table for symbols that are code symbols if requested
768 Symtab *symtab = symbols->GetSymtab();
771 std::vector<uint32_t> symbol_indexes;
772 symtab->AppendSymbolIndexesMatchingRegExAndType (regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
773 const size_t num_matches = symbol_indexes.size();
776 SymbolContext sc(this);
777 const size_t end_functions_added_index = sc_list.GetSize();
778 size_t num_functions_added_to_sc_list = end_functions_added_index - start_size;
779 if (num_functions_added_to_sc_list == 0)
781 // No functions were added, just symbols, so we can just append them
782 for (size_t i=0; i<num_matches; ++i)
784 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
785 SymbolType sym_type = sc.symbol->GetType();
786 if (sc.symbol && (sym_type == eSymbolTypeCode ||
787 sym_type == eSymbolTypeResolver))
793 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
794 FileAddrToIndexMap file_addr_to_index;
795 for (size_t i=start_size; i<end_functions_added_index; ++i)
797 const SymbolContext &sc = sc_list[i];
800 file_addr_to_index[sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()] = i;
803 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
804 // Functions were added so we need to merge symbols into any
805 // existing function symbol contexts
806 for (size_t i=start_size; i<num_matches; ++i)
808 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
809 SymbolType sym_type = sc.symbol->GetType();
810 if (sc.symbol && (sym_type == eSymbolTypeCode ||
811 sym_type == eSymbolTypeResolver))
813 FileAddrToIndexMap::const_iterator pos = file_addr_to_index.find(sc.symbol->GetAddress().GetFileAddress());
817 sc_list[pos->second].symbol = sc.symbol;
825 return sc_list.GetSize() - start_size;
829 Module::FindAddressesForLine (const lldb::TargetSP target_sp,
830 const FileSpec &file, uint32_t line,
832 std::vector<Address> &output_local, std::vector<Address> &output_extern)
834 SearchFilterByModule filter(target_sp, m_file);
835 AddressResolverFileLine resolver(file, line, true);
836 resolver.ResolveAddress (filter);
838 for (size_t n=0;n<resolver.GetNumberOfAddresses();n++)
840 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
841 Function *f = addr.CalculateSymbolContextFunction();
842 if (f && f == function)
843 output_local.push_back (addr);
845 output_extern.push_back (addr);
850 Module::FindTypes_Impl (const SymbolContext& sc,
851 const ConstString &name,
852 const ClangNamespaceDecl *namespace_decl,
857 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
858 if (sc.module_sp.get() == NULL || sc.module_sp.get() == this)
860 SymbolVendor *symbols = GetSymbolVendor ();
862 return symbols->FindTypes(sc, name, namespace_decl, append, max_matches, types);
868 Module::FindTypesInNamespace (const SymbolContext& sc,
869 const ConstString &type_name,
870 const ClangNamespaceDecl *namespace_decl,
874 const bool append = true;
875 return FindTypes_Impl(sc, type_name, namespace_decl, append, max_matches, type_list);
879 Module::FindFirstType (const SymbolContext& sc,
880 const ConstString &name,
884 const size_t num_matches = FindTypes (sc, name, exact_match, 1, type_list);
886 return type_list.GetTypeAtIndex(0);
892 Module::FindTypes (const SymbolContext& sc,
893 const ConstString &name,
898 size_t num_matches = 0;
899 const char *type_name_cstr = name.GetCString();
900 std::string type_scope;
901 std::string type_basename;
902 const bool append = true;
903 TypeClass type_class = eTypeClassAny;
904 if (Type::GetTypeScopeAndBasename (type_name_cstr, type_scope, type_basename, type_class))
906 // Check if "name" starts with "::" which means the qualified type starts
907 // from the root namespace and implies and exact match. The typenames we
908 // get back from clang do not start with "::" so we need to strip this off
909 // in order to get the qualfied names to match
911 if (type_scope.size() >= 2 && type_scope[0] == ':' && type_scope[1] == ':')
913 type_scope.erase(0,2);
916 ConstString type_basename_const_str (type_basename.c_str());
917 if (FindTypes_Impl(sc, type_basename_const_str, NULL, append, max_matches, types))
919 types.RemoveMismatchedTypes (type_scope, type_basename, type_class, exact_match);
920 num_matches = types.GetSize();
925 // The type is not in a namespace/class scope, just search for it by basename
926 if (type_class != eTypeClassAny)
928 // The "type_name_cstr" will have been modified if we have a valid type class
929 // prefix (like "struct", "class", "union", "typedef" etc).
930 num_matches = FindTypes_Impl(sc, ConstString(type_name_cstr), NULL, append, max_matches, types);
931 types.RemoveMismatchedTypes (type_class);
932 num_matches = types.GetSize();
936 num_matches = FindTypes_Impl(sc, name, NULL, append, max_matches, types);
945 Module::GetSymbolVendor (bool can_create, lldb_private::Stream *feedback_strm)
947 Mutex::Locker locker (m_mutex);
948 if (m_did_load_symbol_vendor == false && can_create)
950 ObjectFile *obj_file = GetObjectFile ();
951 if (obj_file != NULL)
953 Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
954 m_symfile_ap.reset(SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
955 m_did_load_symbol_vendor = true;
958 return m_symfile_ap.get();
962 Module::SetFileSpecAndObjectName (const FileSpec &file, const ConstString &object_name)
964 // Container objects whose paths do not specify a file directly can call
965 // this function to correct the file and object names.
967 m_mod_time = file.GetModificationTime();
968 m_object_name = object_name;
972 Module::GetArchitecture () const
978 Module::GetSpecificationDescription () const
980 std::string spec(GetFileSpec().GetPath());
984 spec += m_object_name.GetCString();
991 Module::GetDescription (Stream *s, lldb::DescriptionLevel level)
993 Mutex::Locker locker (m_mutex);
995 if (level >= eDescriptionLevelFull)
997 if (m_arch.IsValid())
998 s->Printf("(%s) ", m_arch.GetArchitectureName());
1001 if (level == eDescriptionLevelBrief)
1003 const char *filename = m_file.GetFilename().GetCString();
1005 s->PutCString (filename);
1009 char path[PATH_MAX];
1010 if (m_file.GetPath(path, sizeof(path)))
1011 s->PutCString(path);
1014 const char *object_name = m_object_name.GetCString();
1016 s->Printf("(%s)", object_name);
1020 Module::ReportError (const char *format, ...)
1022 if (format && format[0])
1025 strm.PutCString("error: ");
1026 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1029 va_start (args, format);
1030 strm.PrintfVarArg(format, args);
1033 const int format_len = strlen(format);
1036 const char last_char = format[format_len-1];
1037 if (last_char != '\n' || last_char != '\r')
1040 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1046 Module::FileHasChanged () const
1048 if (m_file_has_changed == false)
1049 m_file_has_changed = (m_file.GetModificationTime() != m_mod_time);
1050 return m_file_has_changed;
1054 Module::ReportErrorIfModifyDetected (const char *format, ...)
1056 if (m_first_file_changed_log == false)
1058 if (FileHasChanged ())
1060 m_first_file_changed_log = true;
1064 strm.PutCString("error: the object file ");
1065 GetDescription(&strm, lldb::eDescriptionLevelFull);
1066 strm.PutCString (" has been modified\n");
1069 va_start (args, format);
1070 strm.PrintfVarArg(format, args);
1073 const int format_len = strlen(format);
1076 const char last_char = format[format_len-1];
1077 if (last_char != '\n' || last_char != '\r')
1080 strm.PutCString("The debug session should be aborted as the original debug information has been overwritten.\n");
1081 Host::SystemLog (Host::eSystemLogError, "%s", strm.GetString().c_str());
1088 Module::ReportWarning (const char *format, ...)
1090 if (format && format[0])
1093 strm.PutCString("warning: ");
1094 GetDescription(&strm, lldb::eDescriptionLevelFull);
1098 va_start (args, format);
1099 strm.PrintfVarArg(format, args);
1102 const int format_len = strlen(format);
1105 const char last_char = format[format_len-1];
1106 if (last_char != '\n' || last_char != '\r')
1109 Host::SystemLog (Host::eSystemLogWarning, "%s", strm.GetString().c_str());
1114 Module::LogMessage (Log *log, const char *format, ...)
1118 StreamString log_message;
1119 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1120 log_message.PutCString (": ");
1122 va_start (args, format);
1123 log_message.PrintfVarArg (format, args);
1125 log->PutCString(log_message.GetString().c_str());
1130 Module::LogMessageVerboseBacktrace (Log *log, const char *format, ...)
1134 StreamString log_message;
1135 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1136 log_message.PutCString (": ");
1138 va_start (args, format);
1139 log_message.PrintfVarArg (format, args);
1141 if (log->GetVerbose())
1142 Host::Backtrace (log_message, 1024);
1143 log->PutCString(log_message.GetString().c_str());
1148 Module::Dump(Stream *s)
1150 Mutex::Locker locker (m_mutex);
1151 //s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1153 s->Printf("Module %s%s%s%s\n",
1154 m_file.GetPath().c_str(),
1155 m_object_name ? "(" : "",
1156 m_object_name ? m_object_name.GetCString() : "",
1157 m_object_name ? ")" : "");
1161 ObjectFile *objfile = GetObjectFile ();
1165 SymbolVendor *symbols = GetSymbolVendor ();
1174 Module::GetTypeList ()
1176 SymbolVendor *symbols = GetSymbolVendor ();
1178 return &symbols->GetTypeList();
1183 Module::GetObjectName() const
1185 return m_object_name;
1189 Module::GetObjectFile()
1191 Mutex::Locker locker (m_mutex);
1192 if (m_did_load_objfile == false)
1194 Timer scoped_timer(__PRETTY_FUNCTION__,
1195 "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString(""));
1196 DataBufferSP data_sp;
1197 lldb::offset_t data_offset = 0;
1198 const lldb::offset_t file_size = m_file.GetByteSize();
1199 if (file_size > m_object_offset)
1201 m_did_load_objfile = true;
1202 m_objfile_sp = ObjectFile::FindPlugin (shared_from_this(),
1205 file_size - m_object_offset,
1210 // Once we get the object file, update our module with the object file's
1211 // architecture since it might differ in vendor/os if some parts were
1213 m_objfile_sp->GetArchitecture (m_arch);
1217 return m_objfile_sp.get();
1221 Module::GetSectionList()
1223 // Populate m_unified_sections_ap with sections from objfile.
1224 if (m_sections_ap.get() == NULL)
1226 ObjectFile *obj_file = GetObjectFile();
1228 obj_file->CreateSections(*GetUnifiedSectionList());
1230 return m_sections_ap.get();
1234 Module::GetUnifiedSectionList()
1236 // Populate m_unified_sections_ap with sections from objfile.
1237 if (m_sections_ap.get() == NULL)
1238 m_sections_ap.reset(new SectionList());
1239 return m_sections_ap.get();
1243 Module::FindFirstSymbolWithNameAndType (const ConstString &name, SymbolType symbol_type)
1245 Timer scoped_timer(__PRETTY_FUNCTION__,
1246 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1249 SymbolVendor* sym_vendor = GetSymbolVendor();
1252 Symtab *symtab = sym_vendor->GetSymtab();
1254 return symtab->FindFirstSymbolWithNameAndType (name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1259 Module::SymbolIndicesToSymbolContextList (Symtab *symtab, std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list)
1261 // No need to protect this call using m_mutex all other method calls are
1262 // already thread safe.
1264 size_t num_indices = symbol_indexes.size();
1265 if (num_indices > 0)
1268 CalculateSymbolContext (&sc);
1269 for (size_t i = 0; i < num_indices; i++)
1271 sc.symbol = symtab->SymbolAtIndex (symbol_indexes[i]);
1273 sc_list.Append (sc);
1279 Module::FindFunctionSymbols (const ConstString &name,
1280 uint32_t name_type_mask,
1281 SymbolContextList& sc_list)
1283 Timer scoped_timer(__PRETTY_FUNCTION__,
1284 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1287 SymbolVendor* sym_vendor = GetSymbolVendor();
1290 Symtab *symtab = sym_vendor->GetSymtab();
1292 return symtab->FindFunctionSymbols (name, name_type_mask, sc_list);
1298 Module::FindSymbolsWithNameAndType (const ConstString &name, SymbolType symbol_type, SymbolContextList &sc_list)
1300 // No need to protect this call using m_mutex all other method calls are
1301 // already thread safe.
1304 Timer scoped_timer(__PRETTY_FUNCTION__,
1305 "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1308 const size_t initial_size = sc_list.GetSize();
1309 SymbolVendor* sym_vendor = GetSymbolVendor();
1312 Symtab *symtab = sym_vendor->GetSymtab();
1315 std::vector<uint32_t> symbol_indexes;
1316 symtab->FindAllSymbolsWithNameAndType (name, symbol_type, symbol_indexes);
1317 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1320 return sc_list.GetSize() - initial_size;
1324 Module::FindSymbolsMatchingRegExAndType (const RegularExpression ®ex, SymbolType symbol_type, SymbolContextList &sc_list)
1326 // No need to protect this call using m_mutex all other method calls are
1327 // already thread safe.
1329 Timer scoped_timer(__PRETTY_FUNCTION__,
1330 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1333 const size_t initial_size = sc_list.GetSize();
1334 SymbolVendor* sym_vendor = GetSymbolVendor();
1337 Symtab *symtab = sym_vendor->GetSymtab();
1340 std::vector<uint32_t> symbol_indexes;
1341 symtab->FindAllSymbolsMatchingRexExAndType (regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, symbol_indexes);
1342 SymbolIndicesToSymbolContextList (symtab, symbol_indexes, sc_list);
1345 return sc_list.GetSize() - initial_size;
1349 Module::SetSymbolFileFileSpec (const FileSpec &file)
1351 // Remove any sections in the unified section list that come from the current symbol vendor.
1354 SectionList *section_list = GetSectionList();
1355 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1356 if (section_list && symbol_file)
1358 ObjectFile *obj_file = symbol_file->GetObjectFile();
1359 // Make sure we have an object file and that the symbol vendor's objfile isn't
1360 // the same as the module's objfile before we remove any sections for it...
1361 if (obj_file && obj_file != m_objfile_sp.get())
1363 size_t num_sections = section_list->GetNumSections (0);
1364 for (size_t idx = num_sections; idx > 0; --idx)
1366 lldb::SectionSP section_sp (section_list->GetSectionAtIndex (idx - 1));
1367 if (section_sp->GetObjectFile() == obj_file)
1369 section_list->DeleteSection (idx - 1);
1376 m_symfile_spec = file;
1377 m_symfile_ap.reset();
1378 m_did_load_symbol_vendor = false;
1382 Module::IsExecutable ()
1384 if (GetObjectFile() == NULL)
1387 return GetObjectFile()->IsExecutable();
1391 Module::IsLoadedInTarget (Target *target)
1393 ObjectFile *obj_file = GetObjectFile();
1396 SectionList *sections = GetSectionList();
1397 if (sections != NULL)
1399 size_t num_sections = sections->GetSize();
1400 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++)
1402 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1403 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS)
1414 Module::LoadScriptingResourceInTarget (Target *target, Error& error, Stream* feedback_stream)
1418 error.SetErrorString("invalid destination Target");
1422 LoadScriptFromSymFile shoud_load = target->TargetProperties::GetLoadScriptFromSymbolFile();
1424 Debugger &debugger = target->GetDebugger();
1425 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1426 if (script_language != eScriptLanguageNone)
1429 PlatformSP platform_sp(target->GetPlatform());
1433 error.SetErrorString("invalid Platform");
1437 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources (target,
1441 const uint32_t num_specs = file_specs.GetSize();
1444 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1445 if (script_interpreter)
1447 for (uint32_t i=0; i<num_specs; ++i)
1449 FileSpec scripting_fspec (file_specs.GetFileSpecAtIndex(i));
1450 if (scripting_fspec && scripting_fspec.Exists())
1452 if (shoud_load == eLoadScriptFromSymFileFalse)
1454 if (shoud_load == eLoadScriptFromSymFileWarn)
1456 if (feedback_stream)
1457 feedback_stream->Printf("warning: '%s' contains a debug script. To run this script in "
1458 "this debug session:\n\n command script import \"%s\"\n\n"
1459 "To run all discovered debug scripts in this session:\n\n"
1460 " settings set target.load-script-from-symbol-file true\n",
1461 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1462 scripting_fspec.GetPath().c_str());
1465 StreamString scripting_stream;
1466 scripting_fspec.Dump(&scripting_stream);
1467 const bool can_reload = true;
1468 const bool init_lldb_globals = false;
1469 bool did_load = script_interpreter->LoadScriptingModule(scripting_stream.GetData(),
1480 error.SetErrorString("invalid ScriptInterpreter");
1489 Module::SetArchitecture (const ArchSpec &new_arch)
1491 if (!m_arch.IsValid())
1496 return m_arch.IsExactMatch(new_arch);
1500 Module::SetLoadAddress (Target &target, lldb::addr_t offset, bool &changed)
1502 size_t num_loaded_sections = 0;
1503 SectionList *section_list = GetSectionList ();
1506 const size_t num_sections = section_list->GetSize();
1507 size_t sect_idx = 0;
1508 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1510 // Iterate through the object file sections to find the
1511 // first section that starts of file offset zero and that
1512 // has bytes in the file...
1513 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
1514 // Only load non-thread specific sections when given a slide
1515 if (section_sp && !section_sp->IsThreadSpecific())
1517 if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + offset))
1518 ++num_loaded_sections;
1522 changed = num_loaded_sections > 0;
1523 return num_loaded_sections > 0;
1528 Module::MatchesModuleSpec (const ModuleSpec &module_ref)
1530 const UUID &uuid = module_ref.GetUUID();
1534 // If the UUID matches, then nothing more needs to match...
1535 if (uuid == GetUUID())
1541 const FileSpec &file_spec = module_ref.GetFileSpec();
1544 if (!FileSpec::Equal (file_spec, m_file, (bool)file_spec.GetDirectory()))
1548 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1549 if (platform_file_spec)
1551 if (!FileSpec::Equal (platform_file_spec, GetPlatformFileSpec (), (bool)platform_file_spec.GetDirectory()))
1555 const ArchSpec &arch = module_ref.GetArchitecture();
1558 if (!m_arch.IsCompatibleMatch(arch))
1562 const ConstString &object_name = module_ref.GetObjectName();
1565 if (object_name != GetObjectName())
1572 Module::FindSourceFile (const FileSpec &orig_spec, FileSpec &new_spec) const
1574 Mutex::Locker locker (m_mutex);
1575 return m_source_mappings.FindFile (orig_spec, new_spec);
1579 Module::RemapSourceFile (const char *path, std::string &new_path) const
1581 Mutex::Locker locker (m_mutex);
1582 return m_source_mappings.RemapPath(path, new_path);
1586 Module::GetVersion (uint32_t *versions, uint32_t num_versions)
1588 ObjectFile *obj_file = GetObjectFile();
1590 return obj_file->GetVersion (versions, num_versions);
1592 if (versions && num_versions)
1594 for (uint32_t i=0; i<num_versions; ++i)
1595 versions[i] = UINT32_MAX;
1601 Module::PrepareForFunctionNameLookup (const ConstString &name,
1602 uint32_t name_type_mask,
1603 ConstString &lookup_name,
1604 uint32_t &lookup_name_type_mask,
1605 bool &match_name_after_lookup)
1607 const char *name_cstr = name.GetCString();
1608 lookup_name_type_mask = eFunctionNameTypeNone;
1609 match_name_after_lookup = false;
1610 const char *base_name_start = NULL;
1611 const char *base_name_end = NULL;
1613 if (name_type_mask & eFunctionNameTypeAuto)
1615 if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
1616 lookup_name_type_mask = eFunctionNameTypeFull;
1617 else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
1618 lookup_name_type_mask = eFunctionNameTypeFull;
1621 if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1622 lookup_name_type_mask |= eFunctionNameTypeSelector;
1624 CPPLanguageRuntime::MethodName cpp_method (name);
1625 llvm::StringRef basename (cpp_method.GetBasename());
1626 if (basename.empty())
1628 if (CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1629 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1633 base_name_start = basename.data();
1634 base_name_end = base_name_start + basename.size();
1635 lookup_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
1641 lookup_name_type_mask = name_type_mask;
1642 if (lookup_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
1644 // If they've asked for a CPP method or function name and it can't be that, we don't
1645 // even need to search for CPP methods or names.
1646 CPPLanguageRuntime::MethodName cpp_method (name);
1647 if (cpp_method.IsValid())
1649 llvm::StringRef basename (cpp_method.GetBasename());
1650 base_name_start = basename.data();
1651 base_name_end = base_name_start + basename.size();
1653 if (!cpp_method.GetQualifiers().empty())
1655 // There is a "const" or other qualifer following the end of the fucntion parens,
1656 // this can't be a eFunctionNameTypeBase
1657 lookup_name_type_mask &= ~(eFunctionNameTypeBase);
1658 if (lookup_name_type_mask == eFunctionNameTypeNone)
1664 if (!CPPLanguageRuntime::StripNamespacesFromVariableName (name_cstr, base_name_start, base_name_end))
1666 lookup_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
1667 if (lookup_name_type_mask == eFunctionNameTypeNone)
1673 if (lookup_name_type_mask & eFunctionNameTypeSelector)
1675 if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
1677 lookup_name_type_mask &= ~(eFunctionNameTypeSelector);
1678 if (lookup_name_type_mask == eFunctionNameTypeNone)
1684 if (base_name_start &&
1686 base_name_start != name_cstr &&
1687 base_name_start < base_name_end)
1689 // The name supplied was a partial C++ path like "a::count". In this case we want to do a
1690 // lookup on the basename "count" and then make sure any matching results contain "a::count"
1691 // so that it would match "b::a::count" and "a::count". This is why we set "match_name_after_lookup"
1693 lookup_name.SetCStringWithLength(base_name_start, base_name_end - base_name_start);
1694 match_name_after_lookup = true;
1698 // The name is already correct, just use the exact name as supplied, and we won't need
1699 // to check if any matches contain "name"
1701 match_name_after_lookup = false;