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/Host/FileSystem.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/ScriptInterpreter.h"
24 #include "lldb/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/Function.h" // for Function
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Symbol/Symbol.h" // for Symbol
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolFile.h"
30 #include "lldb/Symbol/SymbolVendor.h"
31 #include "lldb/Symbol/Symtab.h" // for Symtab
32 #include "lldb/Symbol/Type.h" // for Type
33 #include "lldb/Symbol/TypeList.h" // for TypeList
34 #include "lldb/Symbol/TypeMap.h"
35 #include "lldb/Symbol/TypeSystem.h"
36 #include "lldb/Target/Language.h"
37 #include "lldb/Target/Platform.h" // for Platform
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Utility/DataBufferHeap.h"
41 #include "lldb/Utility/LLDBAssert.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"
48 #include "lldb/Utility/Timer.h"
51 #include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
54 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
55 #include "Plugins/Language/ObjC/ObjCLanguage.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 targets and in the
83 // global module, but this collection will track all module objects that are
85 typedef std::vector<Module *> ModuleCollection;
87 static ModuleCollection &GetModuleCollection() {
88 // This module collection needs to live past any module, so we could either
89 // make it a shared pointer in each module or just leak is. Since it is only
90 // an empty vector by the time all the modules have gone away, we just leak
91 // it for now. If we decide this is a big problem we can introduce a
92 // Finalize method that will tear everything down in a predictable order.
94 static ModuleCollection *g_module_collection = nullptr;
95 if (g_module_collection == nullptr)
96 g_module_collection = new ModuleCollection();
98 return *g_module_collection;
101 std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() {
102 // NOTE: The mutex below must be leaked since the global module list in
103 // the ModuleList class will get torn at some point, and we can't know if it
104 // will tear itself down before the "g_module_collection_mutex" below will.
105 // So we leak a Mutex object below to safeguard against that
107 static std::recursive_mutex *g_module_collection_mutex = nullptr;
108 if (g_module_collection_mutex == nullptr)
109 g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
110 return *g_module_collection_mutex;
113 size_t Module::GetNumberAllocatedModules() {
114 std::lock_guard<std::recursive_mutex> guard(
115 GetAllocationModuleCollectionMutex());
116 return GetModuleCollection().size();
119 Module *Module::GetAllocatedModuleAtIndex(size_t idx) {
120 std::lock_guard<std::recursive_mutex> guard(
121 GetAllocationModuleCollectionMutex());
122 ModuleCollection &modules = GetModuleCollection();
123 if (idx < modules.size())
128 Module::Module(const ModuleSpec &module_spec)
129 : m_object_offset(0), m_file_has_changed(false),
130 m_first_file_changed_log(false) {
131 // Scope for locker below...
133 std::lock_guard<std::recursive_mutex> guard(
134 GetAllocationModuleCollectionMutex());
135 GetModuleCollection().push_back(this);
138 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
139 LIBLLDB_LOG_MODULES));
141 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
142 module_spec.GetArchitecture().GetArchitectureName(),
143 module_spec.GetFileSpec().GetPath().c_str(),
144 module_spec.GetObjectName().IsEmpty() ? "" : "(",
145 module_spec.GetObjectName().IsEmpty()
147 : module_spec.GetObjectName().AsCString(""),
148 module_spec.GetObjectName().IsEmpty() ? "" : ")");
150 // First extract all module specifications from the file using the local file
151 // path. If there are no specifications, then don't fill anything in
152 ModuleSpecList modules_specs;
153 if (ObjectFile::GetModuleSpecifications(module_spec.GetFileSpec(), 0, 0,
157 // Now make sure that one of the module specifications matches what we just
158 // extract. We might have a module specification that specifies a file
159 // "/usr/lib/dyld" with UUID XXX, but we might have a local version of
160 // "/usr/lib/dyld" that has
161 // UUID YYY and we don't want those to match. If they don't match, just don't
162 // fill any ivars in so we don't accidentally grab the wrong file later since
163 // they don't match...
164 ModuleSpec matching_module_spec;
165 if (modules_specs.FindMatchingModuleSpec(module_spec, matching_module_spec) ==
169 if (module_spec.GetFileSpec())
170 m_mod_time = FileSystem::GetModificationTime(module_spec.GetFileSpec());
171 else if (matching_module_spec.GetFileSpec())
173 FileSystem::GetModificationTime(matching_module_spec.GetFileSpec());
175 // Copy the architecture from the actual spec if we got one back, else use
176 // the one that was specified
177 if (matching_module_spec.GetArchitecture().IsValid())
178 m_arch = matching_module_spec.GetArchitecture();
179 else if (module_spec.GetArchitecture().IsValid())
180 m_arch = module_spec.GetArchitecture();
182 // Copy the file spec over and use the specified one (if there was one) so we
183 // don't use a path that might have gotten resolved a path in
184 // 'matching_module_spec'
185 if (module_spec.GetFileSpec())
186 m_file = module_spec.GetFileSpec();
187 else if (matching_module_spec.GetFileSpec())
188 m_file = matching_module_spec.GetFileSpec();
190 // Copy the platform file spec over
191 if (module_spec.GetPlatformFileSpec())
192 m_platform_file = module_spec.GetPlatformFileSpec();
193 else if (matching_module_spec.GetPlatformFileSpec())
194 m_platform_file = matching_module_spec.GetPlatformFileSpec();
196 // Copy the symbol file spec over
197 if (module_spec.GetSymbolFileSpec())
198 m_symfile_spec = module_spec.GetSymbolFileSpec();
199 else if (matching_module_spec.GetSymbolFileSpec())
200 m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
202 // Copy the object name over
203 if (matching_module_spec.GetObjectName())
204 m_object_name = matching_module_spec.GetObjectName();
206 m_object_name = module_spec.GetObjectName();
208 // Always trust the object offset (file offset) and object modification time
209 // (for mod time in a BSD static archive) of from the matching module
211 m_object_offset = matching_module_spec.GetObjectOffset();
212 m_object_mod_time = matching_module_spec.GetObjectModificationTime();
215 Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
216 const ConstString *object_name, lldb::offset_t object_offset,
217 const llvm::sys::TimePoint<> &object_mod_time)
218 : m_mod_time(FileSystem::GetModificationTime(file_spec)), m_arch(arch),
219 m_file(file_spec), m_object_offset(object_offset),
220 m_object_mod_time(object_mod_time), m_file_has_changed(false),
221 m_first_file_changed_log(false) {
222 // Scope for locker below...
224 std::lock_guard<std::recursive_mutex> guard(
225 GetAllocationModuleCollectionMutex());
226 GetModuleCollection().push_back(this);
230 m_object_name = *object_name;
232 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
233 LIBLLDB_LOG_MODULES));
235 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
236 m_arch.GetArchitectureName(), m_file.GetPath().c_str(),
237 m_object_name.IsEmpty() ? "" : "(",
238 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
239 m_object_name.IsEmpty() ? "" : ")");
243 : m_object_offset(0), m_file_has_changed(false),
244 m_first_file_changed_log(false) {
245 std::lock_guard<std::recursive_mutex> guard(
246 GetAllocationModuleCollectionMutex());
247 GetModuleCollection().push_back(this);
251 // Lock our module down while we tear everything down to make sure we don't
252 // get any access to the module while it is being destroyed
253 std::lock_guard<std::recursive_mutex> guard(m_mutex);
254 // Scope for locker below...
256 std::lock_guard<std::recursive_mutex> guard(
257 GetAllocationModuleCollectionMutex());
258 ModuleCollection &modules = GetModuleCollection();
259 ModuleCollection::iterator end = modules.end();
260 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
264 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
265 LIBLLDB_LOG_MODULES));
267 log->Printf("%p Module::~Module((%s) '%s%s%s%s')",
268 static_cast<void *>(this), m_arch.GetArchitectureName(),
269 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
270 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
271 m_object_name.IsEmpty() ? "" : ")");
272 // Release any auto pointers before we start tearing down our member
273 // variables since the object file and symbol files might need to make
274 // function calls back into this module object. The ordering is important
275 // here because symbol files can require the module object file. So we tear
276 // down the symbol file first, then the object file.
277 m_sections_ap.reset();
278 m_symfile_ap.reset();
279 m_objfile_sp.reset();
282 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
283 lldb::addr_t header_addr, Status &error,
284 size_t size_to_read) {
286 error.SetErrorString("object file already exists");
288 std::lock_guard<std::recursive_mutex> guard(m_mutex);
290 m_did_load_objfile = true;
291 auto data_ap = llvm::make_unique<DataBufferHeap>(size_to_read, 0);
292 Status readmem_error;
293 const size_t bytes_read =
294 process_sp->ReadMemory(header_addr, data_ap->GetBytes(),
295 data_ap->GetByteSize(), readmem_error);
296 if (bytes_read == size_to_read) {
297 DataBufferSP data_sp(data_ap.release());
298 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
299 header_addr, data_sp);
302 s.Printf("0x%16.16" PRIx64, header_addr);
303 m_object_name.SetString(s.GetString());
305 // Once we get the object file, update our module with the object
306 // file's architecture since it might differ in vendor/os if some
307 // parts were unknown.
308 m_objfile_sp->GetArchitecture(m_arch);
310 error.SetErrorString("unable to find suitable object file plug-in");
313 error.SetErrorStringWithFormat("unable to read header from memory: %s",
314 readmem_error.AsCString());
317 error.SetErrorString("invalid process");
320 return m_objfile_sp.get();
323 const lldb_private::UUID &Module::GetUUID() {
324 if (!m_did_set_uuid.load()) {
325 std::lock_guard<std::recursive_mutex> guard(m_mutex);
326 if (!m_did_set_uuid.load()) {
327 ObjectFile *obj_file = GetObjectFile();
329 if (obj_file != nullptr) {
330 obj_file->GetUUID(&m_uuid);
331 m_did_set_uuid = true;
338 void Module::SetUUID(const lldb_private::UUID &uuid) {
339 std::lock_guard<std::recursive_mutex> guard(m_mutex);
340 if (!m_did_set_uuid) {
342 m_did_set_uuid = true;
344 lldbassert(0 && "Attempting to overwrite the existing module UUID");
348 TypeSystem *Module::GetTypeSystemForLanguage(LanguageType language) {
349 return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
352 void Module::ParseAllDebugSymbols() {
353 std::lock_guard<std::recursive_mutex> guard(m_mutex);
354 size_t num_comp_units = GetNumCompileUnits();
355 if (num_comp_units == 0)
359 sc.module_sp = shared_from_this();
360 SymbolVendor *symbols = GetSymbolVendor();
362 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
363 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
365 sc.function = nullptr;
366 symbols->ParseVariablesForContext(sc);
368 symbols->ParseCompileUnitFunctions(sc);
370 for (size_t func_idx = 0;
371 (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) !=
374 symbols->ParseFunctionBlocks(sc);
376 // Parse the variables for this function and all its blocks
377 symbols->ParseVariablesForContext(sc);
380 // Parse all types for this compile unit
381 sc.function = nullptr;
382 symbols->ParseTypes(sc);
387 void Module::CalculateSymbolContext(SymbolContext *sc) {
388 sc->module_sp = shared_from_this();
391 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
393 void Module::DumpSymbolContext(Stream *s) {
394 s->Printf(", Module{%p}", static_cast<void *>(this));
397 size_t Module::GetNumCompileUnits() {
398 std::lock_guard<std::recursive_mutex> guard(m_mutex);
399 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
400 Timer scoped_timer(func_cat, "Module::GetNumCompileUnits (module = %p)",
401 static_cast<void *>(this));
402 SymbolVendor *symbols = GetSymbolVendor();
404 return symbols->GetNumCompileUnits();
408 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
409 std::lock_guard<std::recursive_mutex> guard(m_mutex);
410 size_t num_comp_units = GetNumCompileUnits();
413 if (index < num_comp_units) {
414 SymbolVendor *symbols = GetSymbolVendor();
416 cu_sp = symbols->GetCompileUnitAtIndex(index);
421 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
422 std::lock_guard<std::recursive_mutex> guard(m_mutex);
423 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
424 Timer scoped_timer(func_cat,
425 "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")",
427 SectionList *section_list = GetSectionList();
429 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
433 uint32_t Module::ResolveSymbolContextForAddress(
434 const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc,
435 bool resolve_tail_call_address) {
436 std::lock_guard<std::recursive_mutex> guard(m_mutex);
437 uint32_t resolved_flags = 0;
439 // Clear the result symbol context in case we don't find anything, but don't
443 // Get the section from the section/offset address.
444 SectionSP section_sp(so_addr.GetSection());
446 // Make sure the section matches this module before we try and match anything
447 if (section_sp && section_sp->GetModule().get() == this) {
448 // If the section offset based address resolved itself, then this is the
450 sc.module_sp = shared_from_this();
451 resolved_flags |= eSymbolContextModule;
453 SymbolVendor *sym_vendor = GetSymbolVendor();
455 return resolved_flags;
457 // Resolve the compile unit, function, block, line table or line entry if
459 if (resolve_scope & eSymbolContextCompUnit ||
460 resolve_scope & eSymbolContextFunction ||
461 resolve_scope & eSymbolContextBlock ||
462 resolve_scope & eSymbolContextLineEntry ||
463 resolve_scope & eSymbolContextVariable) {
465 sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc);
468 // Resolve the symbol if requested, but don't re-look it up if we've
470 if (resolve_scope & eSymbolContextSymbol &&
471 !(resolved_flags & eSymbolContextSymbol)) {
472 Symtab *symtab = sym_vendor->GetSymtab();
473 if (symtab && so_addr.IsSectionOffset()) {
474 Symbol *matching_symbol = nullptr;
476 symtab->ForEachSymbolContainingFileAddress(
477 so_addr.GetFileAddress(),
478 [&matching_symbol](Symbol *symbol) -> bool {
479 if (symbol->GetType() != eSymbolTypeInvalid) {
480 matching_symbol = symbol;
481 return false; // Stop iterating
483 return true; // Keep iterating
485 sc.symbol = matching_symbol;
486 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
487 !(resolved_flags & eSymbolContextFunction)) {
488 bool verify_unique = false; // No need to check again since
489 // ResolveSymbolContext failed to find a
490 // symbol at this address.
491 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
493 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
497 if (sc.symbol->IsSynthetic()) {
498 // We have a synthetic symbol so lets check if the object file from
499 // the symbol file in the symbol vendor is different than the
500 // object file for the module, and if so search its symbol table to
501 // see if we can come up with a better symbol. For example dSYM
502 // files on MacOSX have an unstripped symbol table inside of them.
503 ObjectFile *symtab_objfile = symtab->GetObjectFile();
504 if (symtab_objfile && symtab_objfile->IsStripped()) {
505 SymbolFile *symfile = sym_vendor->GetSymbolFile();
507 ObjectFile *symfile_objfile = symfile->GetObjectFile();
508 if (symfile_objfile != symtab_objfile) {
509 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
510 if (symfile_symtab) {
512 symfile_symtab->FindSymbolContainingFileAddress(
513 so_addr.GetFileAddress());
514 if (symbol && !symbol->IsSynthetic()) {
522 resolved_flags |= eSymbolContextSymbol;
527 // For function symbols, so_addr may be off by one. This is a convention
528 // consistent with FDE row indices in eh_frame sections, but requires extra
529 // logic here to permit symbol lookup for disassembly and unwind.
530 if (resolve_scope & eSymbolContextSymbol &&
531 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
532 so_addr.IsSectionOffset()) {
533 Address previous_addr = so_addr;
534 previous_addr.Slide(-1);
536 bool do_resolve_tail_call_address = false; // prevent recursion
537 const uint32_t flags = ResolveSymbolContextForAddress(
538 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
539 if (flags & eSymbolContextSymbol) {
540 AddressRange addr_range;
541 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
542 false, addr_range)) {
543 if (addr_range.GetBaseAddress().GetSection() ==
544 so_addr.GetSection()) {
545 // If the requested address is one past the address range of a
546 // function (i.e. a tail call), or the decremented address is the
547 // start of a function (i.e. some forms of trampoline), indicate
548 // that the symbol has been resolved.
549 if (so_addr.GetOffset() ==
550 addr_range.GetBaseAddress().GetOffset() ||
551 so_addr.GetOffset() ==
552 addr_range.GetBaseAddress().GetOffset() +
553 addr_range.GetByteSize()) {
554 resolved_flags |= flags;
558 nullptr; // Don't trust the symbol if the sections didn't match.
564 return resolved_flags;
567 uint32_t Module::ResolveSymbolContextForFilePath(const char *file_path,
570 uint32_t resolve_scope,
571 SymbolContextList &sc_list) {
572 FileSpec file_spec(file_path, false);
573 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
574 resolve_scope, sc_list);
577 uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec,
580 uint32_t resolve_scope,
581 SymbolContextList &sc_list) {
582 std::lock_guard<std::recursive_mutex> guard(m_mutex);
583 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
584 Timer scoped_timer(func_cat,
585 "Module::ResolveSymbolContextForFilePath (%s:%u, "
586 "check_inlines = %s, resolve_scope = 0x%8.8x)",
587 file_spec.GetPath().c_str(), line,
588 check_inlines ? "yes" : "no", resolve_scope);
590 const uint32_t initial_count = sc_list.GetSize();
592 SymbolVendor *symbols = GetSymbolVendor();
594 symbols->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope,
597 return sc_list.GetSize() - initial_count;
600 size_t Module::FindGlobalVariables(const ConstString &name,
601 const CompilerDeclContext *parent_decl_ctx,
603 VariableList &variables) {
604 SymbolVendor *symbols = GetSymbolVendor();
606 return symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches,
611 size_t Module::FindGlobalVariables(const RegularExpression ®ex,
613 VariableList &variables) {
614 SymbolVendor *symbols = GetSymbolVendor();
616 return symbols->FindGlobalVariables(regex, max_matches, variables);
620 size_t Module::FindCompileUnits(const FileSpec &path, bool append,
621 SymbolContextList &sc_list) {
625 const size_t start_size = sc_list.GetSize();
626 const size_t num_compile_units = GetNumCompileUnits();
628 sc.module_sp = shared_from_this();
629 const bool compare_directory = (bool)path.GetDirectory();
630 for (size_t i = 0; i < num_compile_units; ++i) {
631 sc.comp_unit = GetCompileUnitAtIndex(i).get();
633 if (FileSpec::Equal(*sc.comp_unit, path, compare_directory))
637 return sc_list.GetSize() - start_size;
640 Module::LookupInfo::LookupInfo(const ConstString &name, uint32_t name_type_mask,
641 lldb::LanguageType language)
642 : m_name(name), m_lookup_name(), m_language(language), m_name_type_mask(0),
643 m_match_name_after_lookup(false) {
644 const char *name_cstr = name.GetCString();
645 llvm::StringRef basename;
646 llvm::StringRef context;
648 if (name_type_mask & eFunctionNameTypeAuto) {
649 if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
650 m_name_type_mask = eFunctionNameTypeFull;
651 else if ((language == eLanguageTypeUnknown ||
652 Language::LanguageIsObjC(language)) &&
653 ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
654 m_name_type_mask = eFunctionNameTypeFull;
655 else if (Language::LanguageIsC(language)) {
656 m_name_type_mask = eFunctionNameTypeFull;
658 if ((language == eLanguageTypeUnknown ||
659 Language::LanguageIsObjC(language)) &&
660 ObjCLanguage::IsPossibleObjCSelector(name_cstr))
661 m_name_type_mask |= eFunctionNameTypeSelector;
663 CPlusPlusLanguage::MethodName cpp_method(name);
664 basename = cpp_method.GetBasename();
665 if (basename.empty()) {
666 if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
668 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
670 m_name_type_mask |= eFunctionNameTypeFull;
672 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
676 m_name_type_mask = name_type_mask;
677 if (name_type_mask & eFunctionNameTypeMethod ||
678 name_type_mask & eFunctionNameTypeBase) {
679 // If they've asked for a CPP method or function name and it can't be
680 // that, we don't even need to search for CPP methods or names.
681 CPlusPlusLanguage::MethodName cpp_method(name);
682 if (cpp_method.IsValid()) {
683 basename = cpp_method.GetBasename();
685 if (!cpp_method.GetQualifiers().empty()) {
686 // There is a "const" or other qualifier following the end of the
687 // function parens, this can't be a eFunctionNameTypeBase
688 m_name_type_mask &= ~(eFunctionNameTypeBase);
689 if (m_name_type_mask == eFunctionNameTypeNone)
693 // If the CPP method parser didn't manage to chop this up, try to fill
694 // in the base name if we can. If a::b::c is passed in, we need to just
695 // look up "c", and then we'll filter the result later.
696 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
701 if (name_type_mask & eFunctionNameTypeSelector) {
702 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
703 m_name_type_mask &= ~(eFunctionNameTypeSelector);
704 if (m_name_type_mask == eFunctionNameTypeNone)
709 // Still try and get a basename in case someone specifies a name type mask
710 // of eFunctionNameTypeFull and a name like "A::func"
711 if (basename.empty()) {
712 if (name_type_mask & eFunctionNameTypeFull &&
713 !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
714 CPlusPlusLanguage::MethodName cpp_method(name);
715 basename = cpp_method.GetBasename();
716 if (basename.empty())
717 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
723 if (!basename.empty()) {
724 // The name supplied was a partial C++ path like "a::count". In this case
725 // we want to do a lookup on the basename "count" and then make sure any
726 // matching results contain "a::count" so that it would match "b::a::count"
727 // and "a::count". This is why we set "match_name_after_lookup" to true
728 m_lookup_name.SetString(basename);
729 m_match_name_after_lookup = true;
731 // The name is already correct, just use the exact name as supplied, and we
732 // won't need to check if any matches contain "name"
733 m_lookup_name = name;
734 m_match_name_after_lookup = false;
738 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
739 size_t start_idx) const {
740 if (m_match_name_after_lookup && m_name) {
742 size_t i = start_idx;
743 while (i < sc_list.GetSize()) {
744 if (!sc_list.GetContextAtIndex(i, sc))
746 ConstString full_name(sc.GetFunctionName());
748 ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) {
749 sc_list.RemoveContextAtIndex(i);
756 // If we have only full name matches we might have tried to set breakpoint on
757 // "func" and specified eFunctionNameTypeFull, but we might have found
758 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
759 // "func()" and "func" should end up matching.
760 if (m_name_type_mask == eFunctionNameTypeFull) {
762 size_t i = start_idx;
763 while (i < sc_list.GetSize()) {
764 if (!sc_list.GetContextAtIndex(i, sc))
766 // Make sure the mangled and demangled names don't match before we try to
768 ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
769 ConstString full_name(sc.GetFunctionName());
770 if (mangled_name != m_name && full_name != m_name)
772 CPlusPlusLanguage::MethodName cpp_method(full_name);
773 if (cpp_method.IsValid()) {
774 if (cpp_method.GetContext().empty()) {
775 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
776 sc_list.RemoveContextAtIndex(i);
780 std::string qualified_name;
781 llvm::StringRef anon_prefix("(anonymous namespace)");
782 if (cpp_method.GetContext() == anon_prefix)
783 qualified_name = cpp_method.GetBasename().str();
785 qualified_name = cpp_method.GetScopeQualifiedName();
786 if (qualified_name.compare(m_name.GetCString()) != 0) {
787 sc_list.RemoveContextAtIndex(i);
798 size_t Module::FindFunctions(const ConstString &name,
799 const CompilerDeclContext *parent_decl_ctx,
800 uint32_t name_type_mask, bool include_symbols,
801 bool include_inlines, bool append,
802 SymbolContextList &sc_list) {
806 const size_t old_size = sc_list.GetSize();
808 // Find all the functions (not symbols, but debug information functions...
809 SymbolVendor *symbols = GetSymbolVendor();
811 if (name_type_mask & eFunctionNameTypeAuto) {
812 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
815 symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
816 lookup_info.GetNameTypeMask(), include_inlines,
819 // Now check our symbol table for symbols that are code symbols if
821 if (include_symbols) {
822 Symtab *symtab = symbols->GetSymtab();
824 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
825 lookup_info.GetNameTypeMask(), sc_list);
829 const size_t new_size = sc_list.GetSize();
831 if (old_size < new_size)
832 lookup_info.Prune(sc_list, old_size);
835 symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
836 include_inlines, append, sc_list);
838 // Now check our symbol table for symbols that are code symbols if
840 if (include_symbols) {
841 Symtab *symtab = symbols->GetSymtab();
843 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
848 return sc_list.GetSize() - old_size;
851 size_t Module::FindFunctions(const RegularExpression ®ex,
852 bool include_symbols, bool include_inlines,
853 bool append, SymbolContextList &sc_list) {
857 const size_t start_size = sc_list.GetSize();
859 SymbolVendor *symbols = GetSymbolVendor();
861 symbols->FindFunctions(regex, include_inlines, append, sc_list);
863 // Now check our symbol table for symbols that are code symbols if
865 if (include_symbols) {
866 Symtab *symtab = symbols->GetSymtab();
868 std::vector<uint32_t> symbol_indexes;
869 symtab->AppendSymbolIndexesMatchingRegExAndType(
870 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
872 const size_t num_matches = symbol_indexes.size();
874 SymbolContext sc(this);
875 const size_t end_functions_added_index = sc_list.GetSize();
876 size_t num_functions_added_to_sc_list =
877 end_functions_added_index - start_size;
878 if (num_functions_added_to_sc_list == 0) {
879 // No functions were added, just symbols, so we can just append
881 for (size_t i = 0; i < num_matches; ++i) {
882 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
883 SymbolType sym_type = sc.symbol->GetType();
884 if (sc.symbol && (sym_type == eSymbolTypeCode ||
885 sym_type == eSymbolTypeResolver))
889 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
890 FileAddrToIndexMap file_addr_to_index;
891 for (size_t i = start_size; i < end_functions_added_index; ++i) {
892 const SymbolContext &sc = sc_list[i];
895 file_addr_to_index[sc.function->GetAddressRange()
897 .GetFileAddress()] = i;
900 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
901 // Functions were added so we need to merge symbols into any
902 // existing function symbol contexts
903 for (size_t i = start_size; i < num_matches; ++i) {
904 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
905 SymbolType sym_type = sc.symbol->GetType();
906 if (sc.symbol && sc.symbol->ValueIsAddress() &&
907 (sym_type == eSymbolTypeCode ||
908 sym_type == eSymbolTypeResolver)) {
909 FileAddrToIndexMap::const_iterator pos =
910 file_addr_to_index.find(
911 sc.symbol->GetAddressRef().GetFileAddress());
915 sc_list[pos->second].symbol = sc.symbol;
923 return sc_list.GetSize() - start_size;
926 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
927 const FileSpec &file, uint32_t line,
929 std::vector<Address> &output_local,
930 std::vector<Address> &output_extern) {
931 SearchFilterByModule filter(target_sp, m_file);
932 AddressResolverFileLine resolver(file, line, true);
933 resolver.ResolveAddress(filter);
935 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
936 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
937 Function *f = addr.CalculateSymbolContextFunction();
938 if (f && f == function)
939 output_local.push_back(addr);
941 output_extern.push_back(addr);
945 size_t Module::FindTypes_Impl(
946 const SymbolContext &sc, const ConstString &name,
947 const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
948 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
950 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
951 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
952 if (!sc.module_sp || sc.module_sp.get() == this) {
953 SymbolVendor *symbols = GetSymbolVendor();
955 return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
956 searched_symbol_files, types);
961 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
962 const ConstString &type_name,
963 const CompilerDeclContext *parent_decl_ctx,
964 size_t max_matches, TypeList &type_list) {
965 const bool append = true;
967 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
969 FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
970 searched_symbol_files, types_map);
972 sc.SortTypeList(types_map, type_list);
976 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
977 const ConstString &name, bool exact_match) {
979 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
980 const size_t num_matches =
981 FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
983 return type_list.GetTypeAtIndex(0);
987 size_t Module::FindTypes(
988 const SymbolContext &sc, const ConstString &name, bool exact_match,
990 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
992 size_t num_matches = 0;
993 const char *type_name_cstr = name.GetCString();
994 llvm::StringRef type_scope;
995 llvm::StringRef type_basename;
996 const bool append = true;
997 TypeClass type_class = eTypeClassAny;
1000 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1002 // Check if "name" starts with "::" which means the qualified type starts
1003 // from the root namespace and implies and exact match. The typenames we
1004 // get back from clang do not start with "::" so we need to strip this off
1005 // in order to get the qualified names to match
1006 exact_match = type_scope.consume_front("::");
1008 ConstString type_basename_const_str(type_basename);
1009 if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1010 max_matches, searched_symbol_files, typesmap)) {
1011 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1013 num_matches = typesmap.GetSize();
1016 // The type is not in a namespace/class scope, just search for it by
1018 if (type_class != eTypeClassAny && !type_basename.empty()) {
1019 // The "type_name_cstr" will have been modified if we have a valid type
1020 // class prefix (like "struct", "class", "union", "typedef" etc).
1021 FindTypes_Impl(sc, ConstString(type_basename), nullptr, append,
1022 UINT_MAX, searched_symbol_files, typesmap);
1023 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1025 num_matches = typesmap.GetSize();
1027 num_matches = FindTypes_Impl(sc, name, nullptr, append, UINT_MAX,
1028 searched_symbol_files, typesmap);
1030 std::string name_str(name.AsCString(""));
1031 typesmap.RemoveMismatchedTypes(type_scope, name_str, type_class,
1033 num_matches = typesmap.GetSize();
1037 if (num_matches > 0)
1038 sc.SortTypeList(typesmap, types);
1042 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1043 lldb_private::Stream *feedback_strm) {
1044 if (!m_did_load_symbol_vendor.load()) {
1045 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1046 if (!m_did_load_symbol_vendor.load() && can_create) {
1047 ObjectFile *obj_file = GetObjectFile();
1048 if (obj_file != nullptr) {
1049 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1050 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
1052 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1053 m_did_load_symbol_vendor = true;
1057 return m_symfile_ap.get();
1060 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1061 const ConstString &object_name) {
1062 // Container objects whose paths do not specify a file directly can call this
1063 // function to correct the file and object names.
1065 m_mod_time = FileSystem::GetModificationTime(file);
1066 m_object_name = object_name;
1069 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1071 std::string Module::GetSpecificationDescription() const {
1072 std::string spec(GetFileSpec().GetPath());
1073 if (m_object_name) {
1075 spec += m_object_name.GetCString();
1081 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1082 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1084 if (level >= eDescriptionLevelFull) {
1085 if (m_arch.IsValid())
1086 s->Printf("(%s) ", m_arch.GetArchitectureName());
1089 if (level == eDescriptionLevelBrief) {
1090 const char *filename = m_file.GetFilename().GetCString();
1092 s->PutCString(filename);
1094 char path[PATH_MAX];
1095 if (m_file.GetPath(path, sizeof(path)))
1096 s->PutCString(path);
1099 const char *object_name = m_object_name.GetCString();
1101 s->Printf("(%s)", object_name);
1104 void Module::ReportError(const char *format, ...) {
1105 if (format && format[0]) {
1107 strm.PutCString("error: ");
1108 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1111 va_start(args, format);
1112 strm.PrintfVarArg(format, args);
1115 const int format_len = strlen(format);
1116 if (format_len > 0) {
1117 const char last_char = format[format_len - 1];
1118 if (last_char != '\n' || last_char != '\r')
1121 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1125 bool Module::FileHasChanged() const {
1126 if (!m_file_has_changed)
1127 m_file_has_changed =
1128 (FileSystem::GetModificationTime(m_file) != m_mod_time);
1129 return m_file_has_changed;
1132 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1133 if (!m_first_file_changed_log) {
1134 if (FileHasChanged()) {
1135 m_first_file_changed_log = true;
1138 strm.PutCString("error: the object file ");
1139 GetDescription(&strm, lldb::eDescriptionLevelFull);
1140 strm.PutCString(" has been modified\n");
1143 va_start(args, format);
1144 strm.PrintfVarArg(format, args);
1147 const int format_len = strlen(format);
1148 if (format_len > 0) {
1149 const char last_char = format[format_len - 1];
1150 if (last_char != '\n' || last_char != '\r')
1153 strm.PutCString("The debug session should be aborted as the original "
1154 "debug information has been overwritten.\n");
1155 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1161 void Module::ReportWarning(const char *format, ...) {
1162 if (format && format[0]) {
1164 strm.PutCString("warning: ");
1165 GetDescription(&strm, lldb::eDescriptionLevelFull);
1169 va_start(args, format);
1170 strm.PrintfVarArg(format, args);
1173 const int format_len = strlen(format);
1174 if (format_len > 0) {
1175 const char last_char = format[format_len - 1];
1176 if (last_char != '\n' || last_char != '\r')
1179 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1183 void Module::LogMessage(Log *log, const char *format, ...) {
1184 if (log != nullptr) {
1185 StreamString log_message;
1186 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1187 log_message.PutCString(": ");
1189 va_start(args, format);
1190 log_message.PrintfVarArg(format, args);
1192 log->PutCString(log_message.GetData());
1196 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1197 if (log != nullptr) {
1198 StreamString log_message;
1199 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1200 log_message.PutCString(": ");
1202 va_start(args, format);
1203 log_message.PrintfVarArg(format, args);
1205 if (log->GetVerbose()) {
1206 std::string back_trace;
1207 llvm::raw_string_ostream stream(back_trace);
1208 llvm::sys::PrintStackTrace(stream);
1209 log_message.PutCString(back_trace);
1211 log->PutCString(log_message.GetData());
1215 void Module::Dump(Stream *s) {
1216 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1217 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1219 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1220 m_object_name ? "(" : "",
1221 m_object_name ? m_object_name.GetCString() : "",
1222 m_object_name ? ")" : "");
1226 ObjectFile *objfile = GetObjectFile();
1230 SymbolVendor *symbols = GetSymbolVendor();
1237 TypeList *Module::GetTypeList() {
1238 SymbolVendor *symbols = GetSymbolVendor();
1240 return &symbols->GetTypeList();
1244 const ConstString &Module::GetObjectName() const { return m_object_name; }
1246 ObjectFile *Module::GetObjectFile() {
1247 if (!m_did_load_objfile.load()) {
1248 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1249 if (!m_did_load_objfile.load()) {
1250 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1251 Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s",
1252 GetFileSpec().GetFilename().AsCString(""));
1253 DataBufferSP data_sp;
1254 lldb::offset_t data_offset = 0;
1255 const lldb::offset_t file_size = m_file.GetByteSize();
1256 if (file_size > m_object_offset) {
1257 m_did_load_objfile = true;
1258 m_objfile_sp = ObjectFile::FindPlugin(
1259 shared_from_this(), &m_file, m_object_offset,
1260 file_size - m_object_offset, data_sp, data_offset);
1262 // Once we get the object file, update our module with the object
1263 // file's architecture since it might differ in vendor/os if some
1264 // parts were unknown. But since the matching arch might already be
1265 // more specific than the generic COFF architecture, only merge in
1266 // those values that overwrite unspecified unknown values.
1268 m_objfile_sp->GetArchitecture(new_arch);
1269 m_arch.MergeFrom(new_arch);
1271 ReportError("failed to load objfile for %s",
1272 GetFileSpec().GetPath().c_str());
1277 return m_objfile_sp.get();
1280 SectionList *Module::GetSectionList() {
1281 // Populate m_sections_ap with sections from objfile.
1282 if (!m_sections_ap) {
1283 ObjectFile *obj_file = GetObjectFile();
1284 if (obj_file != nullptr)
1285 obj_file->CreateSections(*GetUnifiedSectionList());
1287 return m_sections_ap.get();
1290 void Module::SectionFileAddressesChanged() {
1291 ObjectFile *obj_file = GetObjectFile();
1293 obj_file->SectionFileAddressesChanged();
1294 SymbolVendor *sym_vendor = GetSymbolVendor();
1295 if (sym_vendor != nullptr)
1296 sym_vendor->SectionFileAddressesChanged();
1299 SectionList *Module::GetUnifiedSectionList() {
1301 m_sections_ap = llvm::make_unique<SectionList>();
1302 return m_sections_ap.get();
1305 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1306 SymbolType symbol_type) {
1307 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1309 func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1310 name.AsCString(), symbol_type);
1311 SymbolVendor *sym_vendor = GetSymbolVendor();
1313 Symtab *symtab = sym_vendor->GetSymtab();
1315 return symtab->FindFirstSymbolWithNameAndType(
1316 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1320 void Module::SymbolIndicesToSymbolContextList(
1321 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1322 SymbolContextList &sc_list) {
1323 // No need to protect this call using m_mutex all other method calls are
1324 // already thread safe.
1326 size_t num_indices = symbol_indexes.size();
1327 if (num_indices > 0) {
1329 CalculateSymbolContext(&sc);
1330 for (size_t i = 0; i < num_indices; i++) {
1331 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1338 size_t Module::FindFunctionSymbols(const ConstString &name,
1339 uint32_t name_type_mask,
1340 SymbolContextList &sc_list) {
1341 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1342 Timer scoped_timer(func_cat,
1343 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1344 name.AsCString(), name_type_mask);
1345 SymbolVendor *sym_vendor = GetSymbolVendor();
1347 Symtab *symtab = sym_vendor->GetSymtab();
1349 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1354 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1355 SymbolType symbol_type,
1356 SymbolContextList &sc_list) {
1357 // No need to protect this call using m_mutex all other method calls are
1358 // already thread safe.
1360 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1362 func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1363 name.AsCString(), symbol_type);
1364 const size_t initial_size = sc_list.GetSize();
1365 SymbolVendor *sym_vendor = GetSymbolVendor();
1367 Symtab *symtab = sym_vendor->GetSymtab();
1369 std::vector<uint32_t> symbol_indexes;
1370 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1371 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1374 return sc_list.GetSize() - initial_size;
1377 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex,
1378 SymbolType symbol_type,
1379 SymbolContextList &sc_list) {
1380 // No need to protect this call using m_mutex all other method calls are
1381 // already thread safe.
1383 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1386 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1387 regex.GetText().str().c_str(), symbol_type);
1388 const size_t initial_size = sc_list.GetSize();
1389 SymbolVendor *sym_vendor = GetSymbolVendor();
1391 Symtab *symtab = sym_vendor->GetSymtab();
1393 std::vector<uint32_t> symbol_indexes;
1394 symtab->FindAllSymbolsMatchingRexExAndType(
1395 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1397 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1400 return sc_list.GetSize() - initial_size;
1403 void Module::PreloadSymbols() {
1404 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1405 SymbolVendor * sym_vendor = GetSymbolVendor();
1409 // Prime the symbol file first, since it adds symbols to the symbol table.
1410 if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) {
1411 symbol_file->PreloadSymbols();
1413 // Now we can prime the symbol table.
1414 if (Symtab * symtab = sym_vendor->GetSymtab()) {
1415 symtab->PreloadSymbols();
1419 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1423 // Remove any sections in the unified section list that come from the
1424 // current symbol vendor.
1425 SectionList *section_list = GetSectionList();
1426 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1427 if (section_list && symbol_file) {
1428 ObjectFile *obj_file = symbol_file->GetObjectFile();
1429 // Make sure we have an object file and that the symbol vendor's objfile
1430 // isn't the same as the module's objfile before we remove any sections
1433 // Check to make sure we aren't trying to specify the file we already
1435 if (obj_file->GetFileSpec() == file) {
1436 // We are being told to add the exact same file that we already have
1437 // we don't have to do anything.
1441 // Cleare the current symtab as we are going to replace it with a new
1443 obj_file->ClearSymtab();
1445 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1446 // instead of a full path to the symbol file within the bundle
1447 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1450 if (llvm::sys::fs::is_directory(file.GetPath())) {
1451 std::string new_path(file.GetPath());
1452 std::string old_path(obj_file->GetFileSpec().GetPath());
1453 if (old_path.find(new_path) == 0) {
1454 // We specified the same bundle as the symbol file that we already
1460 if (obj_file != m_objfile_sp.get()) {
1461 size_t num_sections = section_list->GetNumSections(0);
1462 for (size_t idx = num_sections; idx > 0; --idx) {
1463 lldb::SectionSP section_sp(
1464 section_list->GetSectionAtIndex(idx - 1));
1465 if (section_sp->GetObjectFile() == obj_file) {
1466 section_list->DeleteSection(idx - 1);
1472 // Keep all old symbol files around in case there are any lingering type
1473 // references in any SBValue objects that might have been handed out.
1474 m_old_symfiles.push_back(std::move(m_symfile_ap));
1476 m_symfile_spec = file;
1477 m_symfile_ap.reset();
1478 m_did_load_symbol_vendor = false;
1481 bool Module::IsExecutable() {
1482 if (GetObjectFile() == nullptr)
1485 return GetObjectFile()->IsExecutable();
1488 bool Module::IsLoadedInTarget(Target *target) {
1489 ObjectFile *obj_file = GetObjectFile();
1491 SectionList *sections = GetSectionList();
1492 if (sections != nullptr) {
1493 size_t num_sections = sections->GetSize();
1494 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1495 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1496 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1505 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1506 Stream *feedback_stream) {
1508 error.SetErrorString("invalid destination Target");
1512 LoadScriptFromSymFile should_load =
1513 target->TargetProperties::GetLoadScriptFromSymbolFile();
1515 if (should_load == eLoadScriptFromSymFileFalse)
1518 Debugger &debugger = target->GetDebugger();
1519 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1520 if (script_language != eScriptLanguageNone) {
1522 PlatformSP platform_sp(target->GetPlatform());
1525 error.SetErrorString("invalid Platform");
1529 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1530 target, *this, feedback_stream);
1532 const uint32_t num_specs = file_specs.GetSize();
1534 ScriptInterpreter *script_interpreter =
1535 debugger.GetCommandInterpreter().GetScriptInterpreter();
1536 if (script_interpreter) {
1537 for (uint32_t i = 0; i < num_specs; ++i) {
1538 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1539 if (scripting_fspec && scripting_fspec.Exists()) {
1540 if (should_load == eLoadScriptFromSymFileWarn) {
1541 if (feedback_stream)
1542 feedback_stream->Printf(
1543 "warning: '%s' contains a debug script. To run this script "
1545 "this debug session:\n\n command script import "
1547 "To run all discovered debug scripts in this session:\n\n"
1548 " settings set target.load-script-from-symbol-file "
1550 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1551 scripting_fspec.GetPath().c_str());
1554 StreamString scripting_stream;
1555 scripting_fspec.Dump(&scripting_stream);
1556 const bool can_reload = true;
1557 const bool init_lldb_globals = false;
1558 bool did_load = script_interpreter->LoadScriptingModule(
1559 scripting_stream.GetData(), can_reload, init_lldb_globals,
1566 error.SetErrorString("invalid ScriptInterpreter");
1574 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1575 if (!m_arch.IsValid()) {
1579 return m_arch.IsCompatibleMatch(new_arch);
1582 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1583 bool value_is_offset, bool &changed) {
1584 ObjectFile *object_file = GetObjectFile();
1585 if (object_file != nullptr) {
1586 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1594 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1595 const UUID &uuid = module_ref.GetUUID();
1597 if (uuid.IsValid()) {
1598 // If the UUID matches, then nothing more needs to match...
1599 return (uuid == GetUUID());
1602 const FileSpec &file_spec = module_ref.GetFileSpec();
1604 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1605 !FileSpec::Equal(file_spec, m_platform_file,
1606 (bool)file_spec.GetDirectory()))
1610 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1611 if (platform_file_spec) {
1612 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1613 (bool)platform_file_spec.GetDirectory()))
1617 const ArchSpec &arch = module_ref.GetArchitecture();
1618 if (arch.IsValid()) {
1619 if (!m_arch.IsCompatibleMatch(arch))
1623 const ConstString &object_name = module_ref.GetObjectName();
1625 if (object_name != GetObjectName())
1631 bool Module::FindSourceFile(const FileSpec &orig_spec,
1632 FileSpec &new_spec) const {
1633 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1634 return m_source_mappings.FindFile(orig_spec, new_spec);
1637 bool Module::RemapSourceFile(llvm::StringRef path,
1638 std::string &new_path) const {
1639 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1640 return m_source_mappings.RemapPath(path, new_path);
1643 llvm::VersionTuple Module::GetVersion() {
1644 if (ObjectFile *obj_file = GetObjectFile())
1645 return obj_file->GetVersion();
1646 return llvm::VersionTuple();
1649 bool Module::GetIsDynamicLinkEditor() {
1650 ObjectFile *obj_file = GetObjectFile();
1653 return obj_file->GetIsDynamicLinkEditor();