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/Error.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/Logging.h" // for GetLogIfAn...
45 #include "lldb/Utility/RegularExpression.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, Error &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);
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 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
433 "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 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
457 "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")",
459 SectionList *section_list = GetSectionList();
461 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
465 uint32_t Module::ResolveSymbolContextForAddress(
466 const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc,
467 bool resolve_tail_call_address) {
468 std::lock_guard<std::recursive_mutex> guard(m_mutex);
469 uint32_t resolved_flags = 0;
471 // Clear the result symbol context in case we don't find anything, but don't
475 // Get the section from the section/offset address.
476 SectionSP section_sp(so_addr.GetSection());
478 // Make sure the section matches this module before we try and match anything
479 if (section_sp && section_sp->GetModule().get() == this) {
480 // If the section offset based address resolved itself, then this
481 // is the right module.
482 sc.module_sp = shared_from_this();
483 resolved_flags |= eSymbolContextModule;
485 SymbolVendor *sym_vendor = GetSymbolVendor();
487 return resolved_flags;
489 // Resolve the compile unit, function, block, line table or line
490 // entry if requested.
491 if (resolve_scope & eSymbolContextCompUnit ||
492 resolve_scope & eSymbolContextFunction ||
493 resolve_scope & eSymbolContextBlock ||
494 resolve_scope & eSymbolContextLineEntry ||
495 resolve_scope & eSymbolContextVariable) {
497 sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc);
500 // Resolve the symbol if requested, but don't re-look it up if we've already
502 if (resolve_scope & eSymbolContextSymbol &&
503 !(resolved_flags & eSymbolContextSymbol)) {
504 Symtab *symtab = sym_vendor->GetSymtab();
505 if (symtab && so_addr.IsSectionOffset()) {
506 Symbol *matching_symbol = nullptr;
508 symtab->ForEachSymbolContainingFileAddress(
509 so_addr.GetFileAddress(),
510 [&matching_symbol](Symbol *symbol) -> bool {
511 if (symbol->GetType() != eSymbolTypeInvalid) {
512 matching_symbol = symbol;
513 return false; // Stop iterating
515 return true; // Keep iterating
517 sc.symbol = matching_symbol;
518 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
519 !(resolved_flags & eSymbolContextFunction)) {
520 bool verify_unique = false; // No need to check again since
521 // ResolveSymbolContext failed to find a
522 // symbol at this address.
523 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
525 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
529 if (sc.symbol->IsSynthetic()) {
530 // We have a synthetic symbol so lets check if the object file
531 // from the symbol file in the symbol vendor is different than
532 // the object file for the module, and if so search its symbol
533 // table to see if we can come up with a better symbol. For example
534 // dSYM files on MacOSX have an unstripped symbol table inside of
536 ObjectFile *symtab_objfile = symtab->GetObjectFile();
537 if (symtab_objfile && symtab_objfile->IsStripped()) {
538 SymbolFile *symfile = sym_vendor->GetSymbolFile();
540 ObjectFile *symfile_objfile = symfile->GetObjectFile();
541 if (symfile_objfile != symtab_objfile) {
542 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
543 if (symfile_symtab) {
545 symfile_symtab->FindSymbolContainingFileAddress(
546 so_addr.GetFileAddress());
547 if (symbol && !symbol->IsSynthetic()) {
555 resolved_flags |= eSymbolContextSymbol;
560 // For function symbols, so_addr may be off by one. This is a convention
562 // with FDE row indices in eh_frame sections, but requires extra logic here
564 // symbol lookup for disassembly and unwind.
565 if (resolve_scope & eSymbolContextSymbol &&
566 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
567 so_addr.IsSectionOffset()) {
568 Address previous_addr = so_addr;
569 previous_addr.Slide(-1);
571 bool do_resolve_tail_call_address = false; // prevent recursion
572 const uint32_t flags = ResolveSymbolContextForAddress(
573 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
574 if (flags & eSymbolContextSymbol) {
575 AddressRange addr_range;
576 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
577 false, addr_range)) {
578 if (addr_range.GetBaseAddress().GetSection() ==
579 so_addr.GetSection()) {
580 // If the requested address is one past the address range of a
581 // function (i.e. a tail call),
582 // or the decremented address is the start of a function (i.e. some
583 // forms of trampoline),
584 // indicate that the symbol has been resolved.
585 if (so_addr.GetOffset() ==
586 addr_range.GetBaseAddress().GetOffset() ||
587 so_addr.GetOffset() ==
588 addr_range.GetBaseAddress().GetOffset() +
589 addr_range.GetByteSize()) {
590 resolved_flags |= flags;
594 nullptr; // Don't trust the symbol if the sections didn't match.
600 return resolved_flags;
603 uint32_t Module::ResolveSymbolContextForFilePath(const char *file_path,
606 uint32_t resolve_scope,
607 SymbolContextList &sc_list) {
608 FileSpec file_spec(file_path, false);
609 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
610 resolve_scope, sc_list);
613 uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec,
616 uint32_t resolve_scope,
617 SymbolContextList &sc_list) {
618 std::lock_guard<std::recursive_mutex> guard(m_mutex);
619 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
620 "Module::ResolveSymbolContextForFilePath (%s:%u, "
621 "check_inlines = %s, resolve_scope = 0x%8.8x)",
622 file_spec.GetPath().c_str(), line,
623 check_inlines ? "yes" : "no", resolve_scope);
625 const uint32_t initial_count = sc_list.GetSize();
627 SymbolVendor *symbols = GetSymbolVendor();
629 symbols->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope,
632 return sc_list.GetSize() - initial_count;
635 size_t Module::FindGlobalVariables(const ConstString &name,
636 const CompilerDeclContext *parent_decl_ctx,
637 bool append, size_t max_matches,
638 VariableList &variables) {
639 SymbolVendor *symbols = GetSymbolVendor();
641 return symbols->FindGlobalVariables(name, parent_decl_ctx, append,
642 max_matches, variables);
646 size_t Module::FindGlobalVariables(const RegularExpression ®ex, bool append,
648 VariableList &variables) {
649 SymbolVendor *symbols = GetSymbolVendor();
651 return symbols->FindGlobalVariables(regex, append, max_matches, variables);
655 size_t Module::FindCompileUnits(const FileSpec &path, bool append,
656 SymbolContextList &sc_list) {
660 const size_t start_size = sc_list.GetSize();
661 const size_t num_compile_units = GetNumCompileUnits();
663 sc.module_sp = shared_from_this();
664 const bool compare_directory = (bool)path.GetDirectory();
665 for (size_t i = 0; i < num_compile_units; ++i) {
666 sc.comp_unit = GetCompileUnitAtIndex(i).get();
668 if (FileSpec::Equal(*sc.comp_unit, path, compare_directory))
672 return sc_list.GetSize() - start_size;
675 Module::LookupInfo::LookupInfo(const ConstString &name, uint32_t name_type_mask,
676 lldb::LanguageType language)
677 : m_name(name), m_lookup_name(), m_language(language), m_name_type_mask(0),
678 m_match_name_after_lookup(false) {
679 const char *name_cstr = name.GetCString();
680 llvm::StringRef basename;
681 llvm::StringRef context;
683 if (name_type_mask & eFunctionNameTypeAuto) {
684 if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
685 m_name_type_mask = eFunctionNameTypeFull;
686 else if ((language == eLanguageTypeUnknown ||
687 Language::LanguageIsObjC(language)) &&
688 ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
689 m_name_type_mask = eFunctionNameTypeFull;
690 else if (Language::LanguageIsC(language)) {
691 m_name_type_mask = eFunctionNameTypeFull;
693 if ((language == eLanguageTypeUnknown ||
694 Language::LanguageIsObjC(language)) &&
695 ObjCLanguage::IsPossibleObjCSelector(name_cstr))
696 m_name_type_mask |= eFunctionNameTypeSelector;
698 CPlusPlusLanguage::MethodName cpp_method(name);
699 basename = cpp_method.GetBasename();
700 if (basename.empty()) {
701 if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
703 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
705 m_name_type_mask |= eFunctionNameTypeFull;
707 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
711 m_name_type_mask = name_type_mask;
712 if (name_type_mask & eFunctionNameTypeMethod ||
713 name_type_mask & eFunctionNameTypeBase) {
714 // If they've asked for a CPP method or function name and it can't be
716 // even need to search for CPP methods or names.
717 CPlusPlusLanguage::MethodName cpp_method(name);
718 if (cpp_method.IsValid()) {
719 basename = cpp_method.GetBasename();
721 if (!cpp_method.GetQualifiers().empty()) {
722 // There is a "const" or other qualifier following the end of the
724 // this can't be a eFunctionNameTypeBase
725 m_name_type_mask &= ~(eFunctionNameTypeBase);
726 if (m_name_type_mask == eFunctionNameTypeNone)
730 // If the CPP method parser didn't manage to chop this up, try to fill
731 // in the base name if we can.
732 // If a::b::c is passed in, we need to just look up "c", and then we'll
733 // filter the result later.
734 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
739 if (name_type_mask & eFunctionNameTypeSelector) {
740 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
741 m_name_type_mask &= ~(eFunctionNameTypeSelector);
742 if (m_name_type_mask == eFunctionNameTypeNone)
747 // Still try and get a basename in case someone specifies a name type mask
748 // of eFunctionNameTypeFull and a name like "A::func"
749 if (basename.empty()) {
750 if (name_type_mask & eFunctionNameTypeFull &&
751 !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
752 CPlusPlusLanguage::MethodName cpp_method(name);
753 basename = cpp_method.GetBasename();
754 if (basename.empty())
755 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
761 if (!basename.empty()) {
762 // The name supplied was a partial C++ path like "a::count". In this case we
764 // lookup on the basename "count" and then make sure any matching results
765 // contain "a::count"
766 // so that it would match "b::a::count" and "a::count". This is why we set
767 // "match_name_after_lookup"
769 m_lookup_name.SetString(basename);
770 m_match_name_after_lookup = true;
772 // The name is already correct, just use the exact name as supplied, and we
774 // to check if any matches contain "name"
775 m_lookup_name = name;
776 m_match_name_after_lookup = false;
780 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
781 size_t start_idx) const {
782 if (m_match_name_after_lookup && m_name) {
784 size_t i = start_idx;
785 while (i < sc_list.GetSize()) {
786 if (!sc_list.GetContextAtIndex(i, sc))
788 ConstString full_name(sc.GetFunctionName());
790 ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) {
791 sc_list.RemoveContextAtIndex(i);
798 // If we have only full name matches we might have tried to set breakpoint on
799 // "func" and specified eFunctionNameTypeFull, but we might have found
800 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
801 // "func()" and "func" should end up matching.
802 if (m_name_type_mask == eFunctionNameTypeFull) {
804 size_t i = start_idx;
805 while (i < sc_list.GetSize()) {
806 if (!sc_list.GetContextAtIndex(i, sc))
808 // Make sure the mangled and demangled names don't match before we try
809 // to pull anything out
810 ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
811 ConstString full_name(sc.GetFunctionName());
812 if (mangled_name != m_name && full_name != m_name)
814 CPlusPlusLanguage::MethodName cpp_method(full_name);
815 if (cpp_method.IsValid()) {
816 if (cpp_method.GetContext().empty()) {
817 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
818 sc_list.RemoveContextAtIndex(i);
822 std::string qualified_name;
823 llvm::StringRef anon_prefix("(anonymous namespace)");
824 if (cpp_method.GetContext() == anon_prefix)
825 qualified_name = cpp_method.GetBasename().str();
827 qualified_name = cpp_method.GetScopeQualifiedName();
828 if (qualified_name.compare(m_name.GetCString()) != 0) {
829 sc_list.RemoveContextAtIndex(i);
840 size_t Module::FindFunctions(const ConstString &name,
841 const CompilerDeclContext *parent_decl_ctx,
842 uint32_t name_type_mask, bool include_symbols,
843 bool include_inlines, bool append,
844 SymbolContextList &sc_list) {
848 const size_t old_size = sc_list.GetSize();
850 // Find all the functions (not symbols, but debug information functions...
851 SymbolVendor *symbols = GetSymbolVendor();
853 if (name_type_mask & eFunctionNameTypeAuto) {
854 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
857 symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
858 lookup_info.GetNameTypeMask(), include_inlines,
861 // Now check our symbol table for symbols that are code symbols if
863 if (include_symbols) {
864 Symtab *symtab = symbols->GetSymtab();
866 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
867 lookup_info.GetNameTypeMask(), sc_list);
871 const size_t new_size = sc_list.GetSize();
873 if (old_size < new_size)
874 lookup_info.Prune(sc_list, old_size);
877 symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
878 include_inlines, append, sc_list);
880 // Now check our symbol table for symbols that are code symbols if
882 if (include_symbols) {
883 Symtab *symtab = symbols->GetSymtab();
885 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
890 return sc_list.GetSize() - old_size;
893 size_t Module::FindFunctions(const RegularExpression ®ex,
894 bool include_symbols, bool include_inlines,
895 bool append, SymbolContextList &sc_list) {
899 const size_t start_size = sc_list.GetSize();
901 SymbolVendor *symbols = GetSymbolVendor();
903 symbols->FindFunctions(regex, include_inlines, append, sc_list);
905 // Now check our symbol table for symbols that are code symbols if requested
906 if (include_symbols) {
907 Symtab *symtab = symbols->GetSymtab();
909 std::vector<uint32_t> symbol_indexes;
910 symtab->AppendSymbolIndexesMatchingRegExAndType(
911 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
913 const size_t num_matches = symbol_indexes.size();
915 SymbolContext sc(this);
916 const size_t end_functions_added_index = sc_list.GetSize();
917 size_t num_functions_added_to_sc_list =
918 end_functions_added_index - start_size;
919 if (num_functions_added_to_sc_list == 0) {
920 // No functions were added, just symbols, so we can just append them
921 for (size_t i = 0; i < num_matches; ++i) {
922 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
923 SymbolType sym_type = sc.symbol->GetType();
924 if (sc.symbol && (sym_type == eSymbolTypeCode ||
925 sym_type == eSymbolTypeResolver))
929 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
930 FileAddrToIndexMap file_addr_to_index;
931 for (size_t i = start_size; i < end_functions_added_index; ++i) {
932 const SymbolContext &sc = sc_list[i];
935 file_addr_to_index[sc.function->GetAddressRange()
937 .GetFileAddress()] = i;
940 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
941 // Functions were added so we need to merge symbols into any
942 // existing function symbol contexts
943 for (size_t i = start_size; i < num_matches; ++i) {
944 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
945 SymbolType sym_type = sc.symbol->GetType();
946 if (sc.symbol && sc.symbol->ValueIsAddress() &&
947 (sym_type == eSymbolTypeCode ||
948 sym_type == eSymbolTypeResolver)) {
949 FileAddrToIndexMap::const_iterator pos =
950 file_addr_to_index.find(
951 sc.symbol->GetAddressRef().GetFileAddress());
955 sc_list[pos->second].symbol = sc.symbol;
963 return sc_list.GetSize() - start_size;
966 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
967 const FileSpec &file, uint32_t line,
969 std::vector<Address> &output_local,
970 std::vector<Address> &output_extern) {
971 SearchFilterByModule filter(target_sp, m_file);
972 AddressResolverFileLine resolver(file, line, true);
973 resolver.ResolveAddress(filter);
975 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
976 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
977 Function *f = addr.CalculateSymbolContextFunction();
978 if (f && f == function)
979 output_local.push_back(addr);
981 output_extern.push_back(addr);
985 size_t Module::FindTypes_Impl(
986 const SymbolContext &sc, const ConstString &name,
987 const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
988 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
990 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
991 if (!sc.module_sp || sc.module_sp.get() == this) {
992 SymbolVendor *symbols = GetSymbolVendor();
994 return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
995 searched_symbol_files, types);
1000 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
1001 const ConstString &type_name,
1002 const CompilerDeclContext *parent_decl_ctx,
1003 size_t max_matches, TypeList &type_list) {
1004 const bool append = true;
1006 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1008 FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
1009 searched_symbol_files, types_map);
1011 sc.SortTypeList(types_map, type_list);
1015 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
1016 const ConstString &name, bool exact_match) {
1018 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1019 const size_t num_matches =
1020 FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
1022 return type_list.GetTypeAtIndex(0);
1026 size_t Module::FindTypes(
1027 const SymbolContext &sc, const ConstString &name, bool exact_match,
1029 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1031 size_t num_matches = 0;
1032 const char *type_name_cstr = name.GetCString();
1033 llvm::StringRef type_scope;
1034 llvm::StringRef type_basename;
1035 const bool append = true;
1036 TypeClass type_class = eTypeClassAny;
1038 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1040 // Check if "name" starts with "::" which means the qualified type starts
1041 // from the root namespace and implies and exact match. The typenames we
1042 // get back from clang do not start with "::" so we need to strip this off
1043 // in order to get the qualified names to match
1044 exact_match = type_scope.consume_front("::");
1046 ConstString type_basename_const_str(type_basename);
1047 if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1048 max_matches, searched_symbol_files, typesmap)) {
1049 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1051 num_matches = typesmap.GetSize();
1054 // The type is not in a namespace/class scope, just search for it by
1056 if (type_class != eTypeClassAny) {
1057 // The "type_name_cstr" will have been modified if we have a valid type
1059 // prefix (like "struct", "class", "union", "typedef" etc).
1060 FindTypes_Impl(sc, ConstString(type_basename), nullptr, append,
1061 max_matches, searched_symbol_files, typesmap);
1062 typesmap.RemoveMismatchedTypes(type_class);
1063 num_matches = typesmap.GetSize();
1065 num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches,
1066 searched_symbol_files, typesmap);
1069 if (num_matches > 0)
1070 sc.SortTypeList(typesmap, types);
1074 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1075 lldb_private::Stream *feedback_strm) {
1076 if (!m_did_load_symbol_vendor.load()) {
1077 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1078 if (!m_did_load_symbol_vendor.load() && can_create) {
1079 ObjectFile *obj_file = GetObjectFile();
1080 if (obj_file != nullptr) {
1081 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
1083 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1084 m_did_load_symbol_vendor = true;
1088 return m_symfile_ap.get();
1091 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1092 const ConstString &object_name) {
1093 // Container objects whose paths do not specify a file directly can call
1094 // this function to correct the file and object names.
1096 m_mod_time = FileSystem::GetModificationTime(file);
1097 m_object_name = object_name;
1100 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1102 std::string Module::GetSpecificationDescription() const {
1103 std::string spec(GetFileSpec().GetPath());
1104 if (m_object_name) {
1106 spec += m_object_name.GetCString();
1112 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1113 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1115 if (level >= eDescriptionLevelFull) {
1116 if (m_arch.IsValid())
1117 s->Printf("(%s) ", m_arch.GetArchitectureName());
1120 if (level == eDescriptionLevelBrief) {
1121 const char *filename = m_file.GetFilename().GetCString();
1123 s->PutCString(filename);
1125 char path[PATH_MAX];
1126 if (m_file.GetPath(path, sizeof(path)))
1127 s->PutCString(path);
1130 const char *object_name = m_object_name.GetCString();
1132 s->Printf("(%s)", object_name);
1135 void Module::ReportError(const char *format, ...) {
1136 if (format && format[0]) {
1138 strm.PutCString("error: ");
1139 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1142 va_start(args, format);
1143 strm.PrintfVarArg(format, args);
1146 const int format_len = strlen(format);
1147 if (format_len > 0) {
1148 const char last_char = format[format_len - 1];
1149 if (last_char != '\n' || last_char != '\r')
1152 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1156 bool Module::FileHasChanged() const {
1157 if (!m_file_has_changed)
1158 m_file_has_changed =
1159 (FileSystem::GetModificationTime(m_file) != m_mod_time);
1160 return m_file_has_changed;
1163 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1164 if (!m_first_file_changed_log) {
1165 if (FileHasChanged()) {
1166 m_first_file_changed_log = true;
1169 strm.PutCString("error: the object file ");
1170 GetDescription(&strm, lldb::eDescriptionLevelFull);
1171 strm.PutCString(" has been modified\n");
1174 va_start(args, format);
1175 strm.PrintfVarArg(format, args);
1178 const int format_len = strlen(format);
1179 if (format_len > 0) {
1180 const char last_char = format[format_len - 1];
1181 if (last_char != '\n' || last_char != '\r')
1184 strm.PutCString("The debug session should be aborted as the original "
1185 "debug information has been overwritten.\n");
1186 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1192 void Module::ReportWarning(const char *format, ...) {
1193 if (format && format[0]) {
1195 strm.PutCString("warning: ");
1196 GetDescription(&strm, lldb::eDescriptionLevelFull);
1200 va_start(args, format);
1201 strm.PrintfVarArg(format, args);
1204 const int format_len = strlen(format);
1205 if (format_len > 0) {
1206 const char last_char = format[format_len - 1];
1207 if (last_char != '\n' || last_char != '\r')
1210 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1214 void Module::LogMessage(Log *log, const char *format, ...) {
1215 if (log != nullptr) {
1216 StreamString log_message;
1217 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1218 log_message.PutCString(": ");
1220 va_start(args, format);
1221 log_message.PrintfVarArg(format, args);
1223 log->PutCString(log_message.GetData());
1227 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1228 if (log != nullptr) {
1229 StreamString log_message;
1230 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1231 log_message.PutCString(": ");
1233 va_start(args, format);
1234 log_message.PrintfVarArg(format, args);
1236 if (log->GetVerbose()) {
1237 std::string back_trace;
1238 llvm::raw_string_ostream stream(back_trace);
1239 llvm::sys::PrintStackTrace(stream);
1240 log_message.PutCString(back_trace);
1242 log->PutCString(log_message.GetData());
1246 void Module::Dump(Stream *s) {
1247 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1248 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1250 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1251 m_object_name ? "(" : "",
1252 m_object_name ? m_object_name.GetCString() : "",
1253 m_object_name ? ")" : "");
1257 ObjectFile *objfile = GetObjectFile();
1261 SymbolVendor *symbols = GetSymbolVendor();
1268 TypeList *Module::GetTypeList() {
1269 SymbolVendor *symbols = GetSymbolVendor();
1271 return &symbols->GetTypeList();
1275 const ConstString &Module::GetObjectName() const { return m_object_name; }
1277 ObjectFile *Module::GetObjectFile() {
1278 if (!m_did_load_objfile.load()) {
1279 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1280 if (!m_did_load_objfile.load()) {
1281 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1282 "Module::GetObjectFile () module = %s",
1283 GetFileSpec().GetFilename().AsCString(""));
1284 DataBufferSP data_sp;
1285 lldb::offset_t data_offset = 0;
1286 const lldb::offset_t file_size = m_file.GetByteSize();
1287 if (file_size > m_object_offset) {
1288 m_did_load_objfile = true;
1289 m_objfile_sp = ObjectFile::FindPlugin(
1290 shared_from_this(), &m_file, m_object_offset,
1291 file_size - m_object_offset, data_sp, data_offset);
1293 // Once we get the object file, update our module with the object
1295 // architecture since it might differ in vendor/os if some parts were
1296 // unknown. But since the matching arch might already be more
1298 // than the generic COFF architecture, only merge in those values that
1299 // overwrite unspecified unknown values.
1301 m_objfile_sp->GetArchitecture(new_arch);
1302 m_arch.MergeFrom(new_arch);
1304 ReportError("failed to load objfile for %s",
1305 GetFileSpec().GetPath().c_str());
1310 return m_objfile_sp.get();
1313 SectionList *Module::GetSectionList() {
1314 // Populate m_unified_sections_ap with sections from objfile.
1315 if (!m_sections_ap) {
1316 ObjectFile *obj_file = GetObjectFile();
1317 if (obj_file != nullptr)
1318 obj_file->CreateSections(*GetUnifiedSectionList());
1320 return m_sections_ap.get();
1323 void Module::SectionFileAddressesChanged() {
1324 ObjectFile *obj_file = GetObjectFile();
1326 obj_file->SectionFileAddressesChanged();
1327 SymbolVendor *sym_vendor = GetSymbolVendor();
1328 if (sym_vendor != nullptr)
1329 sym_vendor->SectionFileAddressesChanged();
1332 SectionList *Module::GetUnifiedSectionList() {
1333 // Populate m_unified_sections_ap with sections from objfile.
1335 m_sections_ap = llvm::make_unique<SectionList>();
1336 return m_sections_ap.get();
1339 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1340 SymbolType symbol_type) {
1342 LLVM_PRETTY_FUNCTION,
1343 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1344 name.AsCString(), symbol_type);
1345 SymbolVendor *sym_vendor = GetSymbolVendor();
1347 Symtab *symtab = sym_vendor->GetSymtab();
1349 return symtab->FindFirstSymbolWithNameAndType(
1350 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1354 void Module::SymbolIndicesToSymbolContextList(
1355 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1356 SymbolContextList &sc_list) {
1357 // No need to protect this call using m_mutex all other method calls are
1358 // already thread safe.
1360 size_t num_indices = symbol_indexes.size();
1361 if (num_indices > 0) {
1363 CalculateSymbolContext(&sc);
1364 for (size_t i = 0; i < num_indices; i++) {
1365 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1372 size_t Module::FindFunctionSymbols(const ConstString &name,
1373 uint32_t name_type_mask,
1374 SymbolContextList &sc_list) {
1375 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1376 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1377 name.AsCString(), name_type_mask);
1378 SymbolVendor *sym_vendor = GetSymbolVendor();
1380 Symtab *symtab = sym_vendor->GetSymtab();
1382 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1387 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1388 SymbolType symbol_type,
1389 SymbolContextList &sc_list) {
1390 // No need to protect this call using m_mutex all other method calls are
1391 // already thread safe.
1394 LLVM_PRETTY_FUNCTION,
1395 "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1396 name.AsCString(), symbol_type);
1397 const size_t initial_size = sc_list.GetSize();
1398 SymbolVendor *sym_vendor = GetSymbolVendor();
1400 Symtab *symtab = sym_vendor->GetSymtab();
1402 std::vector<uint32_t> symbol_indexes;
1403 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1404 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1407 return sc_list.GetSize() - initial_size;
1410 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex,
1411 SymbolType symbol_type,
1412 SymbolContextList &sc_list) {
1413 // No need to protect this call using m_mutex all other method calls are
1414 // already thread safe.
1417 LLVM_PRETTY_FUNCTION,
1418 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1419 regex.GetText().str().c_str(), symbol_type);
1420 const size_t initial_size = sc_list.GetSize();
1421 SymbolVendor *sym_vendor = GetSymbolVendor();
1423 Symtab *symtab = sym_vendor->GetSymtab();
1425 std::vector<uint32_t> symbol_indexes;
1426 symtab->FindAllSymbolsMatchingRexExAndType(
1427 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1429 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1432 return sc_list.GetSize() - initial_size;
1435 void Module::PreloadSymbols() {
1436 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1437 SymbolVendor * sym_vendor = GetSymbolVendor();
1441 // Prime the symbol file first, since it adds symbols to the symbol table.
1442 if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) {
1443 symbol_file->PreloadSymbols();
1445 // Now we can prime the symbol table.
1446 if (Symtab * symtab = sym_vendor->GetSymtab()) {
1447 symtab->PreloadSymbols();
1451 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1455 // Remove any sections in the unified section list that come from the
1456 // current symbol vendor.
1457 SectionList *section_list = GetSectionList();
1458 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1459 if (section_list && symbol_file) {
1460 ObjectFile *obj_file = symbol_file->GetObjectFile();
1461 // Make sure we have an object file and that the symbol vendor's objfile
1463 // the same as the module's objfile before we remove any sections for
1466 // Check to make sure we aren't trying to specify the file we already
1468 if (obj_file->GetFileSpec() == file) {
1469 // We are being told to add the exact same file that we already have
1470 // we don't have to do anything.
1474 // Cleare the current symtab as we are going to replace it with a new
1476 obj_file->ClearSymtab();
1478 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1480 // of a full path to the symbol file within the bundle
1481 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1484 if (llvm::sys::fs::is_directory(file.GetPath())) {
1485 std::string new_path(file.GetPath());
1486 std::string old_path(obj_file->GetFileSpec().GetPath());
1487 if (old_path.find(new_path) == 0) {
1488 // We specified the same bundle as the symbol file that we already
1494 if (obj_file != m_objfile_sp.get()) {
1495 size_t num_sections = section_list->GetNumSections(0);
1496 for (size_t idx = num_sections; idx > 0; --idx) {
1497 lldb::SectionSP section_sp(
1498 section_list->GetSectionAtIndex(idx - 1));
1499 if (section_sp->GetObjectFile() == obj_file) {
1500 section_list->DeleteSection(idx - 1);
1506 // Keep all old symbol files around in case there are any lingering type
1508 // any SBValue objects that might have been handed out.
1509 m_old_symfiles.push_back(std::move(m_symfile_ap));
1511 m_symfile_spec = file;
1512 m_symfile_ap.reset();
1513 m_did_load_symbol_vendor = false;
1516 bool Module::IsExecutable() {
1517 if (GetObjectFile() == nullptr)
1520 return GetObjectFile()->IsExecutable();
1523 bool Module::IsLoadedInTarget(Target *target) {
1524 ObjectFile *obj_file = GetObjectFile();
1526 SectionList *sections = GetSectionList();
1527 if (sections != nullptr) {
1528 size_t num_sections = sections->GetSize();
1529 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1530 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1531 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1540 bool Module::LoadScriptingResourceInTarget(Target *target, Error &error,
1541 Stream *feedback_stream) {
1543 error.SetErrorString("invalid destination Target");
1547 LoadScriptFromSymFile should_load =
1548 target->TargetProperties::GetLoadScriptFromSymbolFile();
1550 if (should_load == eLoadScriptFromSymFileFalse)
1553 Debugger &debugger = target->GetDebugger();
1554 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1555 if (script_language != eScriptLanguageNone) {
1557 PlatformSP platform_sp(target->GetPlatform());
1560 error.SetErrorString("invalid Platform");
1564 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1565 target, *this, feedback_stream);
1567 const uint32_t num_specs = file_specs.GetSize();
1569 ScriptInterpreter *script_interpreter =
1570 debugger.GetCommandInterpreter().GetScriptInterpreter();
1571 if (script_interpreter) {
1572 for (uint32_t i = 0; i < num_specs; ++i) {
1573 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1574 if (scripting_fspec && scripting_fspec.Exists()) {
1575 if (should_load == eLoadScriptFromSymFileWarn) {
1576 if (feedback_stream)
1577 feedback_stream->Printf(
1578 "warning: '%s' contains a debug script. To run this script "
1580 "this debug session:\n\n command script import "
1582 "To run all discovered debug scripts in this session:\n\n"
1583 " settings set target.load-script-from-symbol-file "
1585 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1586 scripting_fspec.GetPath().c_str());
1589 StreamString scripting_stream;
1590 scripting_fspec.Dump(&scripting_stream);
1591 const bool can_reload = true;
1592 const bool init_lldb_globals = false;
1593 bool did_load = script_interpreter->LoadScriptingModule(
1594 scripting_stream.GetData(), can_reload, init_lldb_globals,
1601 error.SetErrorString("invalid ScriptInterpreter");
1609 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1610 if (!m_arch.IsValid()) {
1614 return m_arch.IsCompatibleMatch(new_arch);
1617 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1618 bool value_is_offset, bool &changed) {
1619 ObjectFile *object_file = GetObjectFile();
1620 if (object_file != nullptr) {
1621 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1629 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1630 const UUID &uuid = module_ref.GetUUID();
1632 if (uuid.IsValid()) {
1633 // If the UUID matches, then nothing more needs to match...
1634 return (uuid == GetUUID());
1637 const FileSpec &file_spec = module_ref.GetFileSpec();
1639 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1640 !FileSpec::Equal(file_spec, m_platform_file,
1641 (bool)file_spec.GetDirectory()))
1645 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1646 if (platform_file_spec) {
1647 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1648 (bool)platform_file_spec.GetDirectory()))
1652 const ArchSpec &arch = module_ref.GetArchitecture();
1653 if (arch.IsValid()) {
1654 if (!m_arch.IsCompatibleMatch(arch))
1658 const ConstString &object_name = module_ref.GetObjectName();
1660 if (object_name != GetObjectName())
1666 bool Module::FindSourceFile(const FileSpec &orig_spec,
1667 FileSpec &new_spec) const {
1668 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1669 return m_source_mappings.FindFile(orig_spec, new_spec);
1672 bool Module::RemapSourceFile(llvm::StringRef path,
1673 std::string &new_path) const {
1674 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1675 return m_source_mappings.RemapPath(path, new_path);
1678 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) {
1679 ObjectFile *obj_file = GetObjectFile();
1681 return obj_file->GetVersion(versions, num_versions);
1683 if (versions != nullptr && num_versions != 0) {
1684 for (uint32_t i = 0; i < num_versions; ++i)
1685 versions[i] = LLDB_INVALID_MODULE_VERSION;
1691 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) {
1693 // Must create a module and place it into a shared pointer before
1694 // we can create an object file since it has a std::weak_ptr back
1695 // to the module, so we need to control the creation carefully in
1696 // this static function
1697 ModuleSP module_sp(new Module());
1698 module_sp->m_objfile_sp =
1699 std::make_shared<ObjectFileJIT>(module_sp, delegate_sp);
1700 if (module_sp->m_objfile_sp) {
1701 // Once we get the object file, update our module with the object file's
1702 // architecture since it might differ in vendor/os if some parts were
1704 module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch);
1711 bool Module::GetIsDynamicLinkEditor() {
1712 ObjectFile *obj_file = GetObjectFile();
1715 return obj_file->GetIsDynamicLinkEditor();
1720 Error Module::LoadInMemory(Target &target, bool set_pc) {
1721 return m_objfile_sp->LoadInMemory(target, set_pc);