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/Core/Module.h"
12 #include "lldb/Core/AddressRange.h" // for AddressRange
13 #include "lldb/Core/AddressResolverFileLine.h"
14 #include "lldb/Core/Debugger.h" // for Debugger
15 #include "lldb/Core/FileSpecList.h" // for FileSpecList
16 #include "lldb/Core/Mangled.h" // for Mangled
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/SearchFilter.h" // for SearchFilt...
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/Timer.h"
21 #include "lldb/Host/FileSystem.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/ScriptInterpreter.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/Function.h" // for Function
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/Symbol.h" // for Symbol
29 #include "lldb/Symbol/SymbolContext.h"
30 #include "lldb/Symbol/SymbolFile.h"
31 #include "lldb/Symbol/SymbolVendor.h"
32 #include "lldb/Symbol/Symtab.h" // for Symtab
33 #include "lldb/Symbol/Type.h" // for Type
34 #include "lldb/Symbol/TypeList.h" // for TypeList
35 #include "lldb/Symbol/TypeMap.h"
36 #include "lldb/Symbol/TypeSystem.h"
37 #include "lldb/Target/Language.h"
38 #include "lldb/Target/Platform.h" // for Platform
39 #include "lldb/Target/Process.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Utility/DataBufferHeap.h"
42 #include "lldb/Utility/Log.h"
43 #include "lldb/Utility/Logging.h" // for GetLogIfAn...
44 #include "lldb/Utility/RegularExpression.h"
45 #include "lldb/Utility/Status.h"
46 #include "lldb/Utility/Stream.h" // for Stream
47 #include "lldb/Utility/StreamString.h"
49 #if defined(LLVM_ON_WIN32)
50 #include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
53 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
54 #include "Plugins/Language/ObjC/ObjCLanguage.h"
55 #include "Plugins/ObjectFile/JIT/ObjectFileJIT.h"
57 #include "llvm/ADT/STLExtras.h" // for make_unique
58 #include "llvm/Support/Compiler.h" // for LLVM_PRETT...
59 #include "llvm/Support/FileSystem.h"
60 #include "llvm/Support/Signals.h"
61 #include "llvm/Support/raw_ostream.h" // for raw_string...
63 #include <assert.h> // for assert
64 #include <cstdint> // for uint32_t
65 #include <inttypes.h> // for PRIx64
66 #include <map> // for map
67 #include <stdarg.h> // for va_end
68 #include <string.h> // for size_t
69 #include <type_traits> // for move
70 #include <utility> // for find, pair
72 namespace lldb_private {
73 class CompilerDeclContext;
75 namespace lldb_private {
80 using namespace lldb_private;
82 // Shared pointers to modules track module lifetimes in
83 // targets and in the global module, but this collection
84 // will track all module objects that are still alive
85 typedef std::vector<Module *> ModuleCollection;
87 static ModuleCollection &GetModuleCollection() {
88 // This module collection needs to live past any module, so we could either
90 // shared pointer in each module or just leak is. Since it is only an empty
92 // the time all the modules have gone away, we just leak it for now. If we
94 // is a big problem we can introduce a Finalize method that will tear
96 // a predictable order.
98 static ModuleCollection *g_module_collection = nullptr;
99 if (g_module_collection == nullptr)
100 g_module_collection = new ModuleCollection();
102 return *g_module_collection;
105 std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() {
106 // NOTE: The mutex below must be leaked since the global module list in
107 // the ModuleList class will get torn at some point, and we can't know
108 // if it will tear itself down before the "g_module_collection_mutex" below
109 // will. So we leak a Mutex object below to safeguard against that
111 static std::recursive_mutex *g_module_collection_mutex = nullptr;
112 if (g_module_collection_mutex == nullptr)
113 g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
114 return *g_module_collection_mutex;
117 size_t Module::GetNumberAllocatedModules() {
118 std::lock_guard<std::recursive_mutex> guard(
119 GetAllocationModuleCollectionMutex());
120 return GetModuleCollection().size();
123 Module *Module::GetAllocatedModuleAtIndex(size_t idx) {
124 std::lock_guard<std::recursive_mutex> guard(
125 GetAllocationModuleCollectionMutex());
126 ModuleCollection &modules = GetModuleCollection();
127 if (idx < modules.size())
133 // These functions help us to determine if modules are still loaded, yet don't require that
134 // you have a command interpreter and can easily be called from an external debugger.
138 ClearModuleInfo (void)
140 const bool mandatory = true;
141 ModuleList::RemoveOrphanSharedModules(mandatory);
145 DumpModuleInfo (void)
147 Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex());
148 ModuleCollection &modules = GetModuleCollection();
149 const size_t count = modules.size();
150 printf ("%s: %" PRIu64 " modules:\n", LLVM_PRETTY_FUNCTION, (uint64_t)count);
151 for (size_t i = 0; i < count; ++i)
155 Module *module = modules[i];
156 const bool in_shared_module_list = ModuleList::ModuleIsInCache (module);
157 module->GetDescription(&strm, eDescriptionLevelFull);
158 printf ("%p: shared = %i, ref_count = %3u, module = %s\n",
160 in_shared_module_list,
161 (uint32_t)module->use_count(),
162 strm.GetString().c_str());
169 Module::Module(const ModuleSpec &module_spec)
170 : m_object_offset(0), m_file_has_changed(false),
171 m_first_file_changed_log(false) {
172 // Scope for locker below...
174 std::lock_guard<std::recursive_mutex> guard(
175 GetAllocationModuleCollectionMutex());
176 GetModuleCollection().push_back(this);
179 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
180 LIBLLDB_LOG_MODULES));
182 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
183 module_spec.GetArchitecture().GetArchitectureName(),
184 module_spec.GetFileSpec().GetPath().c_str(),
185 module_spec.GetObjectName().IsEmpty() ? "" : "(",
186 module_spec.GetObjectName().IsEmpty()
188 : module_spec.GetObjectName().AsCString(""),
189 module_spec.GetObjectName().IsEmpty() ? "" : ")");
191 // First extract all module specifications from the file using the local
192 // file path. If there are no specifications, then don't fill anything in
193 ModuleSpecList modules_specs;
194 if (ObjectFile::GetModuleSpecifications(module_spec.GetFileSpec(), 0, 0,
198 // Now make sure that one of the module specifications matches what we just
199 // extract. We might have a module specification that specifies a file
201 // with UUID XXX, but we might have a local version of "/usr/lib/dyld" that
203 // UUID YYY and we don't want those to match. If they don't match, just don't
204 // fill any ivars in so we don't accidentally grab the wrong file later since
205 // they don't match...
206 ModuleSpec matching_module_spec;
207 if (modules_specs.FindMatchingModuleSpec(module_spec, matching_module_spec) ==
211 if (module_spec.GetFileSpec())
212 m_mod_time = FileSystem::GetModificationTime(module_spec.GetFileSpec());
213 else if (matching_module_spec.GetFileSpec())
215 FileSystem::GetModificationTime(matching_module_spec.GetFileSpec());
217 // Copy the architecture from the actual spec if we got one back, else use the
218 // one that was specified
219 if (matching_module_spec.GetArchitecture().IsValid())
220 m_arch = matching_module_spec.GetArchitecture();
221 else if (module_spec.GetArchitecture().IsValid())
222 m_arch = module_spec.GetArchitecture();
224 // Copy the file spec over and use the specified one (if there was one) so we
225 // don't use a path that might have gotten resolved a path in
226 // 'matching_module_spec'
227 if (module_spec.GetFileSpec())
228 m_file = module_spec.GetFileSpec();
229 else if (matching_module_spec.GetFileSpec())
230 m_file = matching_module_spec.GetFileSpec();
232 // Copy the platform file spec over
233 if (module_spec.GetPlatformFileSpec())
234 m_platform_file = module_spec.GetPlatformFileSpec();
235 else if (matching_module_spec.GetPlatformFileSpec())
236 m_platform_file = matching_module_spec.GetPlatformFileSpec();
238 // Copy the symbol file spec over
239 if (module_spec.GetSymbolFileSpec())
240 m_symfile_spec = module_spec.GetSymbolFileSpec();
241 else if (matching_module_spec.GetSymbolFileSpec())
242 m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
244 // Copy the object name over
245 if (matching_module_spec.GetObjectName())
246 m_object_name = matching_module_spec.GetObjectName();
248 m_object_name = module_spec.GetObjectName();
250 // Always trust the object offset (file offset) and object modification
251 // time (for mod time in a BSD static archive) of from the matching
252 // module specification
253 m_object_offset = matching_module_spec.GetObjectOffset();
254 m_object_mod_time = matching_module_spec.GetObjectModificationTime();
257 Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
258 const ConstString *object_name, lldb::offset_t object_offset,
259 const llvm::sys::TimePoint<> &object_mod_time)
260 : m_mod_time(FileSystem::GetModificationTime(file_spec)), m_arch(arch),
261 m_file(file_spec), m_object_offset(object_offset),
262 m_object_mod_time(object_mod_time), m_file_has_changed(false),
263 m_first_file_changed_log(false) {
264 // Scope for locker below...
266 std::lock_guard<std::recursive_mutex> guard(
267 GetAllocationModuleCollectionMutex());
268 GetModuleCollection().push_back(this);
272 m_object_name = *object_name;
274 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
275 LIBLLDB_LOG_MODULES));
277 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
278 m_arch.GetArchitectureName(), m_file.GetPath().c_str(),
279 m_object_name.IsEmpty() ? "" : "(",
280 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
281 m_object_name.IsEmpty() ? "" : ")");
285 : m_object_offset(0), m_file_has_changed(false),
286 m_first_file_changed_log(false) {
287 std::lock_guard<std::recursive_mutex> guard(
288 GetAllocationModuleCollectionMutex());
289 GetModuleCollection().push_back(this);
293 // Lock our module down while we tear everything down to make sure
294 // we don't get any access to the module while it is being destroyed
295 std::lock_guard<std::recursive_mutex> guard(m_mutex);
296 // Scope for locker below...
298 std::lock_guard<std::recursive_mutex> guard(
299 GetAllocationModuleCollectionMutex());
300 ModuleCollection &modules = GetModuleCollection();
301 ModuleCollection::iterator end = modules.end();
302 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
306 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
307 LIBLLDB_LOG_MODULES));
309 log->Printf("%p Module::~Module((%s) '%s%s%s%s')",
310 static_cast<void *>(this), m_arch.GetArchitectureName(),
311 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
312 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
313 m_object_name.IsEmpty() ? "" : ")");
314 // Release any auto pointers before we start tearing down our member
315 // variables since the object file and symbol files might need to make
316 // function calls back into this module object. The ordering is important
317 // here because symbol files can require the module object file. So we tear
318 // down the symbol file first, then the object file.
319 m_sections_ap.reset();
320 m_symfile_ap.reset();
321 m_objfile_sp.reset();
324 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
325 lldb::addr_t header_addr, Status &error,
326 size_t size_to_read) {
328 error.SetErrorString("object file already exists");
330 std::lock_guard<std::recursive_mutex> guard(m_mutex);
332 m_did_load_objfile = true;
333 auto data_ap = llvm::make_unique<DataBufferHeap>(size_to_read, 0);
334 Status readmem_error;
335 const size_t bytes_read =
336 process_sp->ReadMemory(header_addr, data_ap->GetBytes(),
337 data_ap->GetByteSize(), readmem_error);
338 if (bytes_read == size_to_read) {
339 DataBufferSP data_sp(data_ap.release());
340 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
341 header_addr, data_sp);
344 s.Printf("0x%16.16" PRIx64, header_addr);
345 m_object_name.SetString(s.GetString());
347 // Once we get the object file, update our module with the object
349 // architecture since it might differ in vendor/os if some parts were
351 m_objfile_sp->GetArchitecture(m_arch);
353 error.SetErrorString("unable to find suitable object file plug-in");
356 error.SetErrorStringWithFormat("unable to read header from memory: %s",
357 readmem_error.AsCString());
360 error.SetErrorString("invalid process");
363 return m_objfile_sp.get();
366 const lldb_private::UUID &Module::GetUUID() {
367 if (!m_did_parse_uuid.load()) {
368 std::lock_guard<std::recursive_mutex> guard(m_mutex);
369 if (!m_did_parse_uuid.load()) {
370 ObjectFile *obj_file = GetObjectFile();
372 if (obj_file != nullptr) {
373 obj_file->GetUUID(&m_uuid);
374 m_did_parse_uuid = true;
381 TypeSystem *Module::GetTypeSystemForLanguage(LanguageType language) {
382 return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
385 void Module::ParseAllDebugSymbols() {
386 std::lock_guard<std::recursive_mutex> guard(m_mutex);
387 size_t num_comp_units = GetNumCompileUnits();
388 if (num_comp_units == 0)
392 sc.module_sp = shared_from_this();
393 SymbolVendor *symbols = GetSymbolVendor();
395 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
396 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
398 sc.function = nullptr;
399 symbols->ParseVariablesForContext(sc);
401 symbols->ParseCompileUnitFunctions(sc);
403 for (size_t func_idx = 0;
404 (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) !=
407 symbols->ParseFunctionBlocks(sc);
409 // Parse the variables for this function and all its blocks
410 symbols->ParseVariablesForContext(sc);
413 // Parse all types for this compile unit
414 sc.function = nullptr;
415 symbols->ParseTypes(sc);
420 void Module::CalculateSymbolContext(SymbolContext *sc) {
421 sc->module_sp = shared_from_this();
424 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
426 void Module::DumpSymbolContext(Stream *s) {
427 s->Printf(", Module{%p}", static_cast<void *>(this));
430 size_t Module::GetNumCompileUnits() {
431 std::lock_guard<std::recursive_mutex> guard(m_mutex);
432 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
433 Timer scoped_timer(func_cat, "Module::GetNumCompileUnits (module = %p)",
434 static_cast<void *>(this));
435 SymbolVendor *symbols = GetSymbolVendor();
437 return symbols->GetNumCompileUnits();
441 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
442 std::lock_guard<std::recursive_mutex> guard(m_mutex);
443 size_t num_comp_units = GetNumCompileUnits();
446 if (index < num_comp_units) {
447 SymbolVendor *symbols = GetSymbolVendor();
449 cu_sp = symbols->GetCompileUnitAtIndex(index);
454 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
455 std::lock_guard<std::recursive_mutex> guard(m_mutex);
456 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
457 Timer scoped_timer(func_cat,
458 "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")",
460 SectionList *section_list = GetSectionList();
462 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
466 uint32_t Module::ResolveSymbolContextForAddress(
467 const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc,
468 bool resolve_tail_call_address) {
469 std::lock_guard<std::recursive_mutex> guard(m_mutex);
470 uint32_t resolved_flags = 0;
472 // Clear the result symbol context in case we don't find anything, but don't
476 // Get the section from the section/offset address.
477 SectionSP section_sp(so_addr.GetSection());
479 // Make sure the section matches this module before we try and match anything
480 if (section_sp && section_sp->GetModule().get() == this) {
481 // If the section offset based address resolved itself, then this
482 // is the right module.
483 sc.module_sp = shared_from_this();
484 resolved_flags |= eSymbolContextModule;
486 SymbolVendor *sym_vendor = GetSymbolVendor();
488 return resolved_flags;
490 // Resolve the compile unit, function, block, line table or line
491 // entry if requested.
492 if (resolve_scope & eSymbolContextCompUnit ||
493 resolve_scope & eSymbolContextFunction ||
494 resolve_scope & eSymbolContextBlock ||
495 resolve_scope & eSymbolContextLineEntry ||
496 resolve_scope & eSymbolContextVariable) {
498 sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc);
501 // Resolve the symbol if requested, but don't re-look it up if we've already
503 if (resolve_scope & eSymbolContextSymbol &&
504 !(resolved_flags & eSymbolContextSymbol)) {
505 Symtab *symtab = sym_vendor->GetSymtab();
506 if (symtab && so_addr.IsSectionOffset()) {
507 Symbol *matching_symbol = nullptr;
509 symtab->ForEachSymbolContainingFileAddress(
510 so_addr.GetFileAddress(),
511 [&matching_symbol](Symbol *symbol) -> bool {
512 if (symbol->GetType() != eSymbolTypeInvalid) {
513 matching_symbol = symbol;
514 return false; // Stop iterating
516 return true; // Keep iterating
518 sc.symbol = matching_symbol;
519 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
520 !(resolved_flags & eSymbolContextFunction)) {
521 bool verify_unique = false; // No need to check again since
522 // ResolveSymbolContext failed to find a
523 // symbol at this address.
524 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
526 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
530 if (sc.symbol->IsSynthetic()) {
531 // We have a synthetic symbol so lets check if the object file
532 // from the symbol file in the symbol vendor is different than
533 // the object file for the module, and if so search its symbol
534 // table to see if we can come up with a better symbol. For example
535 // dSYM files on MacOSX have an unstripped symbol table inside of
537 ObjectFile *symtab_objfile = symtab->GetObjectFile();
538 if (symtab_objfile && symtab_objfile->IsStripped()) {
539 SymbolFile *symfile = sym_vendor->GetSymbolFile();
541 ObjectFile *symfile_objfile = symfile->GetObjectFile();
542 if (symfile_objfile != symtab_objfile) {
543 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
544 if (symfile_symtab) {
546 symfile_symtab->FindSymbolContainingFileAddress(
547 so_addr.GetFileAddress());
548 if (symbol && !symbol->IsSynthetic()) {
556 resolved_flags |= eSymbolContextSymbol;
561 // For function symbols, so_addr may be off by one. This is a convention
563 // with FDE row indices in eh_frame sections, but requires extra logic here
565 // symbol lookup for disassembly and unwind.
566 if (resolve_scope & eSymbolContextSymbol &&
567 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
568 so_addr.IsSectionOffset()) {
569 Address previous_addr = so_addr;
570 previous_addr.Slide(-1);
572 bool do_resolve_tail_call_address = false; // prevent recursion
573 const uint32_t flags = ResolveSymbolContextForAddress(
574 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
575 if (flags & eSymbolContextSymbol) {
576 AddressRange addr_range;
577 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
578 false, addr_range)) {
579 if (addr_range.GetBaseAddress().GetSection() ==
580 so_addr.GetSection()) {
581 // If the requested address is one past the address range of a
582 // function (i.e. a tail call),
583 // or the decremented address is the start of a function (i.e. some
584 // forms of trampoline),
585 // indicate that the symbol has been resolved.
586 if (so_addr.GetOffset() ==
587 addr_range.GetBaseAddress().GetOffset() ||
588 so_addr.GetOffset() ==
589 addr_range.GetBaseAddress().GetOffset() +
590 addr_range.GetByteSize()) {
591 resolved_flags |= flags;
595 nullptr; // Don't trust the symbol if the sections didn't match.
601 return resolved_flags;
604 uint32_t Module::ResolveSymbolContextForFilePath(const char *file_path,
607 uint32_t resolve_scope,
608 SymbolContextList &sc_list) {
609 FileSpec file_spec(file_path, false);
610 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
611 resolve_scope, sc_list);
614 uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec,
617 uint32_t resolve_scope,
618 SymbolContextList &sc_list) {
619 std::lock_guard<std::recursive_mutex> guard(m_mutex);
620 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
621 Timer scoped_timer(func_cat,
622 "Module::ResolveSymbolContextForFilePath (%s:%u, "
623 "check_inlines = %s, resolve_scope = 0x%8.8x)",
624 file_spec.GetPath().c_str(), line,
625 check_inlines ? "yes" : "no", resolve_scope);
627 const uint32_t initial_count = sc_list.GetSize();
629 SymbolVendor *symbols = GetSymbolVendor();
631 symbols->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope,
634 return sc_list.GetSize() - initial_count;
637 size_t Module::FindGlobalVariables(const ConstString &name,
638 const CompilerDeclContext *parent_decl_ctx,
639 bool append, size_t max_matches,
640 VariableList &variables) {
641 SymbolVendor *symbols = GetSymbolVendor();
643 return symbols->FindGlobalVariables(name, parent_decl_ctx, append,
644 max_matches, variables);
648 size_t Module::FindGlobalVariables(const RegularExpression ®ex, bool append,
650 VariableList &variables) {
651 SymbolVendor *symbols = GetSymbolVendor();
653 return symbols->FindGlobalVariables(regex, append, max_matches, variables);
657 size_t Module::FindCompileUnits(const FileSpec &path, bool append,
658 SymbolContextList &sc_list) {
662 const size_t start_size = sc_list.GetSize();
663 const size_t num_compile_units = GetNumCompileUnits();
665 sc.module_sp = shared_from_this();
666 const bool compare_directory = (bool)path.GetDirectory();
667 for (size_t i = 0; i < num_compile_units; ++i) {
668 sc.comp_unit = GetCompileUnitAtIndex(i).get();
670 if (FileSpec::Equal(*sc.comp_unit, path, compare_directory))
674 return sc_list.GetSize() - start_size;
677 Module::LookupInfo::LookupInfo(const ConstString &name, uint32_t name_type_mask,
678 lldb::LanguageType language)
679 : m_name(name), m_lookup_name(), m_language(language), m_name_type_mask(0),
680 m_match_name_after_lookup(false) {
681 const char *name_cstr = name.GetCString();
682 llvm::StringRef basename;
683 llvm::StringRef context;
685 if (name_type_mask & eFunctionNameTypeAuto) {
686 if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
687 m_name_type_mask = eFunctionNameTypeFull;
688 else if ((language == eLanguageTypeUnknown ||
689 Language::LanguageIsObjC(language)) &&
690 ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
691 m_name_type_mask = eFunctionNameTypeFull;
692 else if (Language::LanguageIsC(language)) {
693 m_name_type_mask = eFunctionNameTypeFull;
695 if ((language == eLanguageTypeUnknown ||
696 Language::LanguageIsObjC(language)) &&
697 ObjCLanguage::IsPossibleObjCSelector(name_cstr))
698 m_name_type_mask |= eFunctionNameTypeSelector;
700 CPlusPlusLanguage::MethodName cpp_method(name);
701 basename = cpp_method.GetBasename();
702 if (basename.empty()) {
703 if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
705 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
707 m_name_type_mask |= eFunctionNameTypeFull;
709 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
713 m_name_type_mask = name_type_mask;
714 if (name_type_mask & eFunctionNameTypeMethod ||
715 name_type_mask & eFunctionNameTypeBase) {
716 // If they've asked for a CPP method or function name and it can't be
718 // even need to search for CPP methods or names.
719 CPlusPlusLanguage::MethodName cpp_method(name);
720 if (cpp_method.IsValid()) {
721 basename = cpp_method.GetBasename();
723 if (!cpp_method.GetQualifiers().empty()) {
724 // There is a "const" or other qualifier following the end of the
726 // this can't be a eFunctionNameTypeBase
727 m_name_type_mask &= ~(eFunctionNameTypeBase);
728 if (m_name_type_mask == eFunctionNameTypeNone)
732 // If the CPP method parser didn't manage to chop this up, try to fill
733 // in the base name if we can.
734 // If a::b::c is passed in, we need to just look up "c", and then we'll
735 // filter the result later.
736 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
741 if (name_type_mask & eFunctionNameTypeSelector) {
742 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
743 m_name_type_mask &= ~(eFunctionNameTypeSelector);
744 if (m_name_type_mask == eFunctionNameTypeNone)
749 // Still try and get a basename in case someone specifies a name type mask
750 // of eFunctionNameTypeFull and a name like "A::func"
751 if (basename.empty()) {
752 if (name_type_mask & eFunctionNameTypeFull &&
753 !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
754 CPlusPlusLanguage::MethodName cpp_method(name);
755 basename = cpp_method.GetBasename();
756 if (basename.empty())
757 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
763 if (!basename.empty()) {
764 // The name supplied was a partial C++ path like "a::count". In this case we
766 // lookup on the basename "count" and then make sure any matching results
767 // contain "a::count"
768 // so that it would match "b::a::count" and "a::count". This is why we set
769 // "match_name_after_lookup"
771 m_lookup_name.SetString(basename);
772 m_match_name_after_lookup = true;
774 // The name is already correct, just use the exact name as supplied, and we
776 // to check if any matches contain "name"
777 m_lookup_name = name;
778 m_match_name_after_lookup = false;
782 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
783 size_t start_idx) const {
784 if (m_match_name_after_lookup && m_name) {
786 size_t i = start_idx;
787 while (i < sc_list.GetSize()) {
788 if (!sc_list.GetContextAtIndex(i, sc))
790 ConstString full_name(sc.GetFunctionName());
792 ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) {
793 sc_list.RemoveContextAtIndex(i);
800 // If we have only full name matches we might have tried to set breakpoint on
801 // "func" and specified eFunctionNameTypeFull, but we might have found
802 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
803 // "func()" and "func" should end up matching.
804 if (m_name_type_mask == eFunctionNameTypeFull) {
806 size_t i = start_idx;
807 while (i < sc_list.GetSize()) {
808 if (!sc_list.GetContextAtIndex(i, sc))
810 // Make sure the mangled and demangled names don't match before we try
811 // to pull anything out
812 ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
813 ConstString full_name(sc.GetFunctionName());
814 if (mangled_name != m_name && full_name != m_name)
816 CPlusPlusLanguage::MethodName cpp_method(full_name);
817 if (cpp_method.IsValid()) {
818 if (cpp_method.GetContext().empty()) {
819 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
820 sc_list.RemoveContextAtIndex(i);
824 std::string qualified_name;
825 llvm::StringRef anon_prefix("(anonymous namespace)");
826 if (cpp_method.GetContext() == anon_prefix)
827 qualified_name = cpp_method.GetBasename().str();
829 qualified_name = cpp_method.GetScopeQualifiedName();
830 if (qualified_name.compare(m_name.GetCString()) != 0) {
831 sc_list.RemoveContextAtIndex(i);
842 size_t Module::FindFunctions(const ConstString &name,
843 const CompilerDeclContext *parent_decl_ctx,
844 uint32_t name_type_mask, bool include_symbols,
845 bool include_inlines, bool append,
846 SymbolContextList &sc_list) {
850 const size_t old_size = sc_list.GetSize();
852 // Find all the functions (not symbols, but debug information functions...
853 SymbolVendor *symbols = GetSymbolVendor();
855 if (name_type_mask & eFunctionNameTypeAuto) {
856 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
859 symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
860 lookup_info.GetNameTypeMask(), include_inlines,
863 // Now check our symbol table for symbols that are code symbols if
865 if (include_symbols) {
866 Symtab *symtab = symbols->GetSymtab();
868 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
869 lookup_info.GetNameTypeMask(), sc_list);
873 const size_t new_size = sc_list.GetSize();
875 if (old_size < new_size)
876 lookup_info.Prune(sc_list, old_size);
879 symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
880 include_inlines, append, sc_list);
882 // Now check our symbol table for symbols that are code symbols if
884 if (include_symbols) {
885 Symtab *symtab = symbols->GetSymtab();
887 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
892 return sc_list.GetSize() - old_size;
895 size_t Module::FindFunctions(const RegularExpression ®ex,
896 bool include_symbols, bool include_inlines,
897 bool append, SymbolContextList &sc_list) {
901 const size_t start_size = sc_list.GetSize();
903 SymbolVendor *symbols = GetSymbolVendor();
905 symbols->FindFunctions(regex, include_inlines, append, sc_list);
907 // Now check our symbol table for symbols that are code symbols if requested
908 if (include_symbols) {
909 Symtab *symtab = symbols->GetSymtab();
911 std::vector<uint32_t> symbol_indexes;
912 symtab->AppendSymbolIndexesMatchingRegExAndType(
913 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
915 const size_t num_matches = symbol_indexes.size();
917 SymbolContext sc(this);
918 const size_t end_functions_added_index = sc_list.GetSize();
919 size_t num_functions_added_to_sc_list =
920 end_functions_added_index - start_size;
921 if (num_functions_added_to_sc_list == 0) {
922 // No functions were added, just symbols, so we can just append them
923 for (size_t i = 0; i < num_matches; ++i) {
924 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
925 SymbolType sym_type = sc.symbol->GetType();
926 if (sc.symbol && (sym_type == eSymbolTypeCode ||
927 sym_type == eSymbolTypeResolver))
931 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
932 FileAddrToIndexMap file_addr_to_index;
933 for (size_t i = start_size; i < end_functions_added_index; ++i) {
934 const SymbolContext &sc = sc_list[i];
937 file_addr_to_index[sc.function->GetAddressRange()
939 .GetFileAddress()] = i;
942 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
943 // Functions were added so we need to merge symbols into any
944 // existing function symbol contexts
945 for (size_t i = start_size; i < num_matches; ++i) {
946 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
947 SymbolType sym_type = sc.symbol->GetType();
948 if (sc.symbol && sc.symbol->ValueIsAddress() &&
949 (sym_type == eSymbolTypeCode ||
950 sym_type == eSymbolTypeResolver)) {
951 FileAddrToIndexMap::const_iterator pos =
952 file_addr_to_index.find(
953 sc.symbol->GetAddressRef().GetFileAddress());
957 sc_list[pos->second].symbol = sc.symbol;
965 return sc_list.GetSize() - start_size;
968 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
969 const FileSpec &file, uint32_t line,
971 std::vector<Address> &output_local,
972 std::vector<Address> &output_extern) {
973 SearchFilterByModule filter(target_sp, m_file);
974 AddressResolverFileLine resolver(file, line, true);
975 resolver.ResolveAddress(filter);
977 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
978 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
979 Function *f = addr.CalculateSymbolContextFunction();
980 if (f && f == function)
981 output_local.push_back(addr);
983 output_extern.push_back(addr);
987 size_t Module::FindTypes_Impl(
988 const SymbolContext &sc, const ConstString &name,
989 const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
990 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
992 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
993 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
994 if (!sc.module_sp || sc.module_sp.get() == this) {
995 SymbolVendor *symbols = GetSymbolVendor();
997 return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
998 searched_symbol_files, types);
1003 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
1004 const ConstString &type_name,
1005 const CompilerDeclContext *parent_decl_ctx,
1006 size_t max_matches, TypeList &type_list) {
1007 const bool append = true;
1009 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1011 FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
1012 searched_symbol_files, types_map);
1014 sc.SortTypeList(types_map, type_list);
1018 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
1019 const ConstString &name, bool exact_match) {
1021 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1022 const size_t num_matches =
1023 FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
1025 return type_list.GetTypeAtIndex(0);
1029 size_t Module::FindTypes(
1030 const SymbolContext &sc, const ConstString &name, bool exact_match,
1032 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1034 size_t num_matches = 0;
1035 const char *type_name_cstr = name.GetCString();
1036 llvm::StringRef type_scope;
1037 llvm::StringRef type_basename;
1038 const bool append = true;
1039 TypeClass type_class = eTypeClassAny;
1041 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1043 // Check if "name" starts with "::" which means the qualified type starts
1044 // from the root namespace and implies and exact match. The typenames we
1045 // get back from clang do not start with "::" so we need to strip this off
1046 // in order to get the qualified names to match
1047 exact_match = type_scope.consume_front("::");
1049 ConstString type_basename_const_str(type_basename);
1050 if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1051 max_matches, searched_symbol_files, typesmap)) {
1052 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1054 num_matches = typesmap.GetSize();
1057 // The type is not in a namespace/class scope, just search for it by
1059 if (type_class != eTypeClassAny) {
1060 // The "type_name_cstr" will have been modified if we have a valid type
1062 // prefix (like "struct", "class", "union", "typedef" etc).
1063 FindTypes_Impl(sc, ConstString(type_basename), nullptr, append,
1064 max_matches, searched_symbol_files, typesmap);
1065 typesmap.RemoveMismatchedTypes(type_class);
1066 num_matches = typesmap.GetSize();
1068 num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches,
1069 searched_symbol_files, typesmap);
1072 if (num_matches > 0)
1073 sc.SortTypeList(typesmap, types);
1077 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1078 lldb_private::Stream *feedback_strm) {
1079 if (!m_did_load_symbol_vendor.load()) {
1080 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1081 if (!m_did_load_symbol_vendor.load() && can_create) {
1082 ObjectFile *obj_file = GetObjectFile();
1083 if (obj_file != nullptr) {
1084 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1085 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
1087 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1088 m_did_load_symbol_vendor = true;
1092 return m_symfile_ap.get();
1095 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1096 const ConstString &object_name) {
1097 // Container objects whose paths do not specify a file directly can call
1098 // this function to correct the file and object names.
1100 m_mod_time = FileSystem::GetModificationTime(file);
1101 m_object_name = object_name;
1104 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1106 std::string Module::GetSpecificationDescription() const {
1107 std::string spec(GetFileSpec().GetPath());
1108 if (m_object_name) {
1110 spec += m_object_name.GetCString();
1116 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1117 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1119 if (level >= eDescriptionLevelFull) {
1120 if (m_arch.IsValid())
1121 s->Printf("(%s) ", m_arch.GetArchitectureName());
1124 if (level == eDescriptionLevelBrief) {
1125 const char *filename = m_file.GetFilename().GetCString();
1127 s->PutCString(filename);
1129 char path[PATH_MAX];
1130 if (m_file.GetPath(path, sizeof(path)))
1131 s->PutCString(path);
1134 const char *object_name = m_object_name.GetCString();
1136 s->Printf("(%s)", object_name);
1139 void Module::ReportError(const char *format, ...) {
1140 if (format && format[0]) {
1142 strm.PutCString("error: ");
1143 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1146 va_start(args, format);
1147 strm.PrintfVarArg(format, args);
1150 const int format_len = strlen(format);
1151 if (format_len > 0) {
1152 const char last_char = format[format_len - 1];
1153 if (last_char != '\n' || last_char != '\r')
1156 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1160 bool Module::FileHasChanged() const {
1161 if (!m_file_has_changed)
1162 m_file_has_changed =
1163 (FileSystem::GetModificationTime(m_file) != m_mod_time);
1164 return m_file_has_changed;
1167 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1168 if (!m_first_file_changed_log) {
1169 if (FileHasChanged()) {
1170 m_first_file_changed_log = true;
1173 strm.PutCString("error: the object file ");
1174 GetDescription(&strm, lldb::eDescriptionLevelFull);
1175 strm.PutCString(" has been modified\n");
1178 va_start(args, format);
1179 strm.PrintfVarArg(format, args);
1182 const int format_len = strlen(format);
1183 if (format_len > 0) {
1184 const char last_char = format[format_len - 1];
1185 if (last_char != '\n' || last_char != '\r')
1188 strm.PutCString("The debug session should be aborted as the original "
1189 "debug information has been overwritten.\n");
1190 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1196 void Module::ReportWarning(const char *format, ...) {
1197 if (format && format[0]) {
1199 strm.PutCString("warning: ");
1200 GetDescription(&strm, lldb::eDescriptionLevelFull);
1204 va_start(args, format);
1205 strm.PrintfVarArg(format, args);
1208 const int format_len = strlen(format);
1209 if (format_len > 0) {
1210 const char last_char = format[format_len - 1];
1211 if (last_char != '\n' || last_char != '\r')
1214 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1218 void Module::LogMessage(Log *log, const char *format, ...) {
1219 if (log != nullptr) {
1220 StreamString log_message;
1221 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1222 log_message.PutCString(": ");
1224 va_start(args, format);
1225 log_message.PrintfVarArg(format, args);
1227 log->PutCString(log_message.GetData());
1231 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1232 if (log != nullptr) {
1233 StreamString log_message;
1234 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1235 log_message.PutCString(": ");
1237 va_start(args, format);
1238 log_message.PrintfVarArg(format, args);
1240 if (log->GetVerbose()) {
1241 std::string back_trace;
1242 llvm::raw_string_ostream stream(back_trace);
1243 llvm::sys::PrintStackTrace(stream);
1244 log_message.PutCString(back_trace);
1246 log->PutCString(log_message.GetData());
1250 void Module::Dump(Stream *s) {
1251 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1252 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1254 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1255 m_object_name ? "(" : "",
1256 m_object_name ? m_object_name.GetCString() : "",
1257 m_object_name ? ")" : "");
1261 ObjectFile *objfile = GetObjectFile();
1265 SymbolVendor *symbols = GetSymbolVendor();
1272 TypeList *Module::GetTypeList() {
1273 SymbolVendor *symbols = GetSymbolVendor();
1275 return &symbols->GetTypeList();
1279 const ConstString &Module::GetObjectName() const { return m_object_name; }
1281 ObjectFile *Module::GetObjectFile() {
1282 if (!m_did_load_objfile.load()) {
1283 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1284 if (!m_did_load_objfile.load()) {
1285 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1286 Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s",
1287 GetFileSpec().GetFilename().AsCString(""));
1288 DataBufferSP data_sp;
1289 lldb::offset_t data_offset = 0;
1290 const lldb::offset_t file_size = m_file.GetByteSize();
1291 if (file_size > m_object_offset) {
1292 m_did_load_objfile = true;
1293 m_objfile_sp = ObjectFile::FindPlugin(
1294 shared_from_this(), &m_file, m_object_offset,
1295 file_size - m_object_offset, data_sp, data_offset);
1297 // Once we get the object file, update our module with the object
1299 // architecture since it might differ in vendor/os if some parts were
1300 // unknown. But since the matching arch might already be more
1302 // than the generic COFF architecture, only merge in those values that
1303 // overwrite unspecified unknown values.
1305 m_objfile_sp->GetArchitecture(new_arch);
1306 m_arch.MergeFrom(new_arch);
1308 ReportError("failed to load objfile for %s",
1309 GetFileSpec().GetPath().c_str());
1314 return m_objfile_sp.get();
1317 SectionList *Module::GetSectionList() {
1318 // Populate m_unified_sections_ap with sections from objfile.
1319 if (!m_sections_ap) {
1320 ObjectFile *obj_file = GetObjectFile();
1321 if (obj_file != nullptr)
1322 obj_file->CreateSections(*GetUnifiedSectionList());
1324 return m_sections_ap.get();
1327 void Module::SectionFileAddressesChanged() {
1328 ObjectFile *obj_file = GetObjectFile();
1330 obj_file->SectionFileAddressesChanged();
1331 SymbolVendor *sym_vendor = GetSymbolVendor();
1332 if (sym_vendor != nullptr)
1333 sym_vendor->SectionFileAddressesChanged();
1336 SectionList *Module::GetUnifiedSectionList() {
1337 // Populate m_unified_sections_ap with sections from objfile.
1339 m_sections_ap = llvm::make_unique<SectionList>();
1340 return m_sections_ap.get();
1343 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1344 SymbolType symbol_type) {
1345 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1347 func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1348 name.AsCString(), symbol_type);
1349 SymbolVendor *sym_vendor = GetSymbolVendor();
1351 Symtab *symtab = sym_vendor->GetSymtab();
1353 return symtab->FindFirstSymbolWithNameAndType(
1354 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1358 void Module::SymbolIndicesToSymbolContextList(
1359 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1360 SymbolContextList &sc_list) {
1361 // No need to protect this call using m_mutex all other method calls are
1362 // already thread safe.
1364 size_t num_indices = symbol_indexes.size();
1365 if (num_indices > 0) {
1367 CalculateSymbolContext(&sc);
1368 for (size_t i = 0; i < num_indices; i++) {
1369 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1376 size_t Module::FindFunctionSymbols(const ConstString &name,
1377 uint32_t name_type_mask,
1378 SymbolContextList &sc_list) {
1379 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1380 Timer scoped_timer(func_cat,
1381 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1382 name.AsCString(), name_type_mask);
1383 SymbolVendor *sym_vendor = GetSymbolVendor();
1385 Symtab *symtab = sym_vendor->GetSymtab();
1387 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1392 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1393 SymbolType symbol_type,
1394 SymbolContextList &sc_list) {
1395 // No need to protect this call using m_mutex all other method calls are
1396 // already thread safe.
1398 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1400 func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1401 name.AsCString(), symbol_type);
1402 const size_t initial_size = sc_list.GetSize();
1403 SymbolVendor *sym_vendor = GetSymbolVendor();
1405 Symtab *symtab = sym_vendor->GetSymtab();
1407 std::vector<uint32_t> symbol_indexes;
1408 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1409 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1412 return sc_list.GetSize() - initial_size;
1415 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex,
1416 SymbolType symbol_type,
1417 SymbolContextList &sc_list) {
1418 // No need to protect this call using m_mutex all other method calls are
1419 // already thread safe.
1421 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1424 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1425 regex.GetText().str().c_str(), symbol_type);
1426 const size_t initial_size = sc_list.GetSize();
1427 SymbolVendor *sym_vendor = GetSymbolVendor();
1429 Symtab *symtab = sym_vendor->GetSymtab();
1431 std::vector<uint32_t> symbol_indexes;
1432 symtab->FindAllSymbolsMatchingRexExAndType(
1433 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1435 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1438 return sc_list.GetSize() - initial_size;
1441 void Module::PreloadSymbols() {
1442 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1443 SymbolVendor * sym_vendor = GetSymbolVendor();
1447 // Prime the symbol file first, since it adds symbols to the symbol table.
1448 if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) {
1449 symbol_file->PreloadSymbols();
1451 // Now we can prime the symbol table.
1452 if (Symtab * symtab = sym_vendor->GetSymtab()) {
1453 symtab->PreloadSymbols();
1457 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1461 // Remove any sections in the unified section list that come from the
1462 // current symbol vendor.
1463 SectionList *section_list = GetSectionList();
1464 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1465 if (section_list && symbol_file) {
1466 ObjectFile *obj_file = symbol_file->GetObjectFile();
1467 // Make sure we have an object file and that the symbol vendor's objfile
1469 // the same as the module's objfile before we remove any sections for
1472 // Check to make sure we aren't trying to specify the file we already
1474 if (obj_file->GetFileSpec() == file) {
1475 // We are being told to add the exact same file that we already have
1476 // we don't have to do anything.
1480 // Cleare the current symtab as we are going to replace it with a new
1482 obj_file->ClearSymtab();
1484 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1486 // of a full path to the symbol file within the bundle
1487 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1490 if (llvm::sys::fs::is_directory(file.GetPath())) {
1491 std::string new_path(file.GetPath());
1492 std::string old_path(obj_file->GetFileSpec().GetPath());
1493 if (old_path.find(new_path) == 0) {
1494 // We specified the same bundle as the symbol file that we already
1500 if (obj_file != m_objfile_sp.get()) {
1501 size_t num_sections = section_list->GetNumSections(0);
1502 for (size_t idx = num_sections; idx > 0; --idx) {
1503 lldb::SectionSP section_sp(
1504 section_list->GetSectionAtIndex(idx - 1));
1505 if (section_sp->GetObjectFile() == obj_file) {
1506 section_list->DeleteSection(idx - 1);
1512 // Keep all old symbol files around in case there are any lingering type
1514 // any SBValue objects that might have been handed out.
1515 m_old_symfiles.push_back(std::move(m_symfile_ap));
1517 m_symfile_spec = file;
1518 m_symfile_ap.reset();
1519 m_did_load_symbol_vendor = false;
1522 bool Module::IsExecutable() {
1523 if (GetObjectFile() == nullptr)
1526 return GetObjectFile()->IsExecutable();
1529 bool Module::IsLoadedInTarget(Target *target) {
1530 ObjectFile *obj_file = GetObjectFile();
1532 SectionList *sections = GetSectionList();
1533 if (sections != nullptr) {
1534 size_t num_sections = sections->GetSize();
1535 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1536 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1537 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1546 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1547 Stream *feedback_stream) {
1549 error.SetErrorString("invalid destination Target");
1553 LoadScriptFromSymFile should_load =
1554 target->TargetProperties::GetLoadScriptFromSymbolFile();
1556 if (should_load == eLoadScriptFromSymFileFalse)
1559 Debugger &debugger = target->GetDebugger();
1560 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1561 if (script_language != eScriptLanguageNone) {
1563 PlatformSP platform_sp(target->GetPlatform());
1566 error.SetErrorString("invalid Platform");
1570 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1571 target, *this, feedback_stream);
1573 const uint32_t num_specs = file_specs.GetSize();
1575 ScriptInterpreter *script_interpreter =
1576 debugger.GetCommandInterpreter().GetScriptInterpreter();
1577 if (script_interpreter) {
1578 for (uint32_t i = 0; i < num_specs; ++i) {
1579 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1580 if (scripting_fspec && scripting_fspec.Exists()) {
1581 if (should_load == eLoadScriptFromSymFileWarn) {
1582 if (feedback_stream)
1583 feedback_stream->Printf(
1584 "warning: '%s' contains a debug script. To run this script "
1586 "this debug session:\n\n command script import "
1588 "To run all discovered debug scripts in this session:\n\n"
1589 " settings set target.load-script-from-symbol-file "
1591 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1592 scripting_fspec.GetPath().c_str());
1595 StreamString scripting_stream;
1596 scripting_fspec.Dump(&scripting_stream);
1597 const bool can_reload = true;
1598 const bool init_lldb_globals = false;
1599 bool did_load = script_interpreter->LoadScriptingModule(
1600 scripting_stream.GetData(), can_reload, init_lldb_globals,
1607 error.SetErrorString("invalid ScriptInterpreter");
1615 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1616 if (!m_arch.IsValid()) {
1620 return m_arch.IsCompatibleMatch(new_arch);
1623 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1624 bool value_is_offset, bool &changed) {
1625 ObjectFile *object_file = GetObjectFile();
1626 if (object_file != nullptr) {
1627 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1635 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1636 const UUID &uuid = module_ref.GetUUID();
1638 if (uuid.IsValid()) {
1639 // If the UUID matches, then nothing more needs to match...
1640 return (uuid == GetUUID());
1643 const FileSpec &file_spec = module_ref.GetFileSpec();
1645 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1646 !FileSpec::Equal(file_spec, m_platform_file,
1647 (bool)file_spec.GetDirectory()))
1651 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1652 if (platform_file_spec) {
1653 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1654 (bool)platform_file_spec.GetDirectory()))
1658 const ArchSpec &arch = module_ref.GetArchitecture();
1659 if (arch.IsValid()) {
1660 if (!m_arch.IsCompatibleMatch(arch))
1664 const ConstString &object_name = module_ref.GetObjectName();
1666 if (object_name != GetObjectName())
1672 bool Module::FindSourceFile(const FileSpec &orig_spec,
1673 FileSpec &new_spec) const {
1674 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1675 return m_source_mappings.FindFile(orig_spec, new_spec);
1678 bool Module::RemapSourceFile(llvm::StringRef path,
1679 std::string &new_path) const {
1680 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1681 return m_source_mappings.RemapPath(path, new_path);
1684 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) {
1685 ObjectFile *obj_file = GetObjectFile();
1687 return obj_file->GetVersion(versions, num_versions);
1689 if (versions != nullptr && num_versions != 0) {
1690 for (uint32_t i = 0; i < num_versions; ++i)
1691 versions[i] = LLDB_INVALID_MODULE_VERSION;
1697 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) {
1699 // Must create a module and place it into a shared pointer before
1700 // we can create an object file since it has a std::weak_ptr back
1701 // to the module, so we need to control the creation carefully in
1702 // this static function
1703 ModuleSP module_sp(new Module());
1704 module_sp->m_objfile_sp =
1705 std::make_shared<ObjectFileJIT>(module_sp, delegate_sp);
1706 if (module_sp->m_objfile_sp) {
1707 // Once we get the object file, update our module with the object file's
1708 // architecture since it might differ in vendor/os if some parts were
1710 module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch);
1717 bool Module::GetIsDynamicLinkEditor() {
1718 ObjectFile *obj_file = GetObjectFile();
1721 return obj_file->GetIsDynamicLinkEditor();
1726 Status Module::LoadInMemory(Target &target, bool set_pc) {
1727 return m_objfile_sp->LoadInMemory(target, set_pc);