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/Log.h"
42 #include "lldb/Utility/Logging.h" // for GetLogIfAn...
43 #include "lldb/Utility/RegularExpression.h"
44 #include "lldb/Utility/Status.h"
45 #include "lldb/Utility/Stream.h" // for Stream
46 #include "lldb/Utility/StreamString.h"
47 #include "lldb/Utility/Timer.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())
132 Module::Module(const ModuleSpec &module_spec)
133 : m_object_offset(0), m_file_has_changed(false),
134 m_first_file_changed_log(false) {
135 // Scope for locker below...
137 std::lock_guard<std::recursive_mutex> guard(
138 GetAllocationModuleCollectionMutex());
139 GetModuleCollection().push_back(this);
142 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
143 LIBLLDB_LOG_MODULES));
145 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
146 module_spec.GetArchitecture().GetArchitectureName(),
147 module_spec.GetFileSpec().GetPath().c_str(),
148 module_spec.GetObjectName().IsEmpty() ? "" : "(",
149 module_spec.GetObjectName().IsEmpty()
151 : module_spec.GetObjectName().AsCString(""),
152 module_spec.GetObjectName().IsEmpty() ? "" : ")");
154 // First extract all module specifications from the file using the local
155 // file path. If there are no specifications, then don't fill anything in
156 ModuleSpecList modules_specs;
157 if (ObjectFile::GetModuleSpecifications(module_spec.GetFileSpec(), 0, 0,
161 // Now make sure that one of the module specifications matches what we just
162 // extract. We might have a module specification that specifies a file
164 // with UUID XXX, but we might have a local version of "/usr/lib/dyld" that
166 // UUID YYY and we don't want those to match. If they don't match, just don't
167 // fill any ivars in so we don't accidentally grab the wrong file later since
168 // they don't match...
169 ModuleSpec matching_module_spec;
170 if (modules_specs.FindMatchingModuleSpec(module_spec, matching_module_spec) ==
174 if (module_spec.GetFileSpec())
175 m_mod_time = FileSystem::GetModificationTime(module_spec.GetFileSpec());
176 else if (matching_module_spec.GetFileSpec())
178 FileSystem::GetModificationTime(matching_module_spec.GetFileSpec());
180 // Copy the architecture from the actual spec if we got one back, else use the
181 // one that was specified
182 if (matching_module_spec.GetArchitecture().IsValid())
183 m_arch = matching_module_spec.GetArchitecture();
184 else if (module_spec.GetArchitecture().IsValid())
185 m_arch = module_spec.GetArchitecture();
187 // Copy the file spec over and use the specified one (if there was one) so we
188 // don't use a path that might have gotten resolved a path in
189 // 'matching_module_spec'
190 if (module_spec.GetFileSpec())
191 m_file = module_spec.GetFileSpec();
192 else if (matching_module_spec.GetFileSpec())
193 m_file = matching_module_spec.GetFileSpec();
195 // Copy the platform file spec over
196 if (module_spec.GetPlatformFileSpec())
197 m_platform_file = module_spec.GetPlatformFileSpec();
198 else if (matching_module_spec.GetPlatformFileSpec())
199 m_platform_file = matching_module_spec.GetPlatformFileSpec();
201 // Copy the symbol file spec over
202 if (module_spec.GetSymbolFileSpec())
203 m_symfile_spec = module_spec.GetSymbolFileSpec();
204 else if (matching_module_spec.GetSymbolFileSpec())
205 m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
207 // Copy the object name over
208 if (matching_module_spec.GetObjectName())
209 m_object_name = matching_module_spec.GetObjectName();
211 m_object_name = module_spec.GetObjectName();
213 // Always trust the object offset (file offset) and object modification
214 // time (for mod time in a BSD static archive) of from the matching
215 // module specification
216 m_object_offset = matching_module_spec.GetObjectOffset();
217 m_object_mod_time = matching_module_spec.GetObjectModificationTime();
220 Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
221 const ConstString *object_name, lldb::offset_t object_offset,
222 const llvm::sys::TimePoint<> &object_mod_time)
223 : m_mod_time(FileSystem::GetModificationTime(file_spec)), m_arch(arch),
224 m_file(file_spec), m_object_offset(object_offset),
225 m_object_mod_time(object_mod_time), m_file_has_changed(false),
226 m_first_file_changed_log(false) {
227 // Scope for locker below...
229 std::lock_guard<std::recursive_mutex> guard(
230 GetAllocationModuleCollectionMutex());
231 GetModuleCollection().push_back(this);
235 m_object_name = *object_name;
237 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
238 LIBLLDB_LOG_MODULES));
240 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this),
241 m_arch.GetArchitectureName(), m_file.GetPath().c_str(),
242 m_object_name.IsEmpty() ? "" : "(",
243 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
244 m_object_name.IsEmpty() ? "" : ")");
248 : m_object_offset(0), m_file_has_changed(false),
249 m_first_file_changed_log(false) {
250 std::lock_guard<std::recursive_mutex> guard(
251 GetAllocationModuleCollectionMutex());
252 GetModuleCollection().push_back(this);
256 // Lock our module down while we tear everything down to make sure
257 // we don't get any access to the module while it is being destroyed
258 std::lock_guard<std::recursive_mutex> guard(m_mutex);
259 // Scope for locker below...
261 std::lock_guard<std::recursive_mutex> guard(
262 GetAllocationModuleCollectionMutex());
263 ModuleCollection &modules = GetModuleCollection();
264 ModuleCollection::iterator end = modules.end();
265 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
269 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT |
270 LIBLLDB_LOG_MODULES));
272 log->Printf("%p Module::~Module((%s) '%s%s%s%s')",
273 static_cast<void *>(this), m_arch.GetArchitectureName(),
274 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
275 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
276 m_object_name.IsEmpty() ? "" : ")");
277 // Release any auto pointers before we start tearing down our member
278 // variables since the object file and symbol files might need to make
279 // function calls back into this module object. The ordering is important
280 // here because symbol files can require the module object file. So we tear
281 // down the symbol file first, then the object file.
282 m_sections_ap.reset();
283 m_symfile_ap.reset();
284 m_objfile_sp.reset();
287 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
288 lldb::addr_t header_addr, Status &error,
289 size_t size_to_read) {
291 error.SetErrorString("object file already exists");
293 std::lock_guard<std::recursive_mutex> guard(m_mutex);
295 m_did_load_objfile = true;
296 auto data_ap = llvm::make_unique<DataBufferHeap>(size_to_read, 0);
297 Status readmem_error;
298 const size_t bytes_read =
299 process_sp->ReadMemory(header_addr, data_ap->GetBytes(),
300 data_ap->GetByteSize(), readmem_error);
301 if (bytes_read == size_to_read) {
302 DataBufferSP data_sp(data_ap.release());
303 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
304 header_addr, data_sp);
307 s.Printf("0x%16.16" PRIx64, header_addr);
308 m_object_name.SetString(s.GetString());
310 // Once we get the object file, update our module with the object
312 // architecture since it might differ in vendor/os if some parts were
314 m_objfile_sp->GetArchitecture(m_arch);
316 error.SetErrorString("unable to find suitable object file plug-in");
319 error.SetErrorStringWithFormat("unable to read header from memory: %s",
320 readmem_error.AsCString());
323 error.SetErrorString("invalid process");
326 return m_objfile_sp.get();
329 const lldb_private::UUID &Module::GetUUID() {
330 if (!m_did_parse_uuid.load()) {
331 std::lock_guard<std::recursive_mutex> guard(m_mutex);
332 if (!m_did_parse_uuid.load()) {
333 ObjectFile *obj_file = GetObjectFile();
335 if (obj_file != nullptr) {
336 obj_file->GetUUID(&m_uuid);
337 m_did_parse_uuid = true;
344 TypeSystem *Module::GetTypeSystemForLanguage(LanguageType language) {
345 return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
348 void Module::ParseAllDebugSymbols() {
349 std::lock_guard<std::recursive_mutex> guard(m_mutex);
350 size_t num_comp_units = GetNumCompileUnits();
351 if (num_comp_units == 0)
355 sc.module_sp = shared_from_this();
356 SymbolVendor *symbols = GetSymbolVendor();
358 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
359 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
361 sc.function = nullptr;
362 symbols->ParseVariablesForContext(sc);
364 symbols->ParseCompileUnitFunctions(sc);
366 for (size_t func_idx = 0;
367 (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) !=
370 symbols->ParseFunctionBlocks(sc);
372 // Parse the variables for this function and all its blocks
373 symbols->ParseVariablesForContext(sc);
376 // Parse all types for this compile unit
377 sc.function = nullptr;
378 symbols->ParseTypes(sc);
383 void Module::CalculateSymbolContext(SymbolContext *sc) {
384 sc->module_sp = shared_from_this();
387 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
389 void Module::DumpSymbolContext(Stream *s) {
390 s->Printf(", Module{%p}", static_cast<void *>(this));
393 size_t Module::GetNumCompileUnits() {
394 std::lock_guard<std::recursive_mutex> guard(m_mutex);
395 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
396 Timer scoped_timer(func_cat, "Module::GetNumCompileUnits (module = %p)",
397 static_cast<void *>(this));
398 SymbolVendor *symbols = GetSymbolVendor();
400 return symbols->GetNumCompileUnits();
404 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
405 std::lock_guard<std::recursive_mutex> guard(m_mutex);
406 size_t num_comp_units = GetNumCompileUnits();
409 if (index < num_comp_units) {
410 SymbolVendor *symbols = GetSymbolVendor();
412 cu_sp = symbols->GetCompileUnitAtIndex(index);
417 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
418 std::lock_guard<std::recursive_mutex> guard(m_mutex);
419 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
420 Timer scoped_timer(func_cat,
421 "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")",
423 SectionList *section_list = GetSectionList();
425 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
429 uint32_t Module::ResolveSymbolContextForAddress(
430 const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc,
431 bool resolve_tail_call_address) {
432 std::lock_guard<std::recursive_mutex> guard(m_mutex);
433 uint32_t resolved_flags = 0;
435 // Clear the result symbol context in case we don't find anything, but don't
439 // Get the section from the section/offset address.
440 SectionSP section_sp(so_addr.GetSection());
442 // Make sure the section matches this module before we try and match anything
443 if (section_sp && section_sp->GetModule().get() == this) {
444 // If the section offset based address resolved itself, then this
445 // is the right module.
446 sc.module_sp = shared_from_this();
447 resolved_flags |= eSymbolContextModule;
449 SymbolVendor *sym_vendor = GetSymbolVendor();
451 return resolved_flags;
453 // Resolve the compile unit, function, block, line table or line
454 // entry if requested.
455 if (resolve_scope & eSymbolContextCompUnit ||
456 resolve_scope & eSymbolContextFunction ||
457 resolve_scope & eSymbolContextBlock ||
458 resolve_scope & eSymbolContextLineEntry ||
459 resolve_scope & eSymbolContextVariable) {
461 sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc);
464 // Resolve the symbol if requested, but don't re-look it up if we've already
466 if (resolve_scope & eSymbolContextSymbol &&
467 !(resolved_flags & eSymbolContextSymbol)) {
468 Symtab *symtab = sym_vendor->GetSymtab();
469 if (symtab && so_addr.IsSectionOffset()) {
470 Symbol *matching_symbol = nullptr;
472 symtab->ForEachSymbolContainingFileAddress(
473 so_addr.GetFileAddress(),
474 [&matching_symbol](Symbol *symbol) -> bool {
475 if (symbol->GetType() != eSymbolTypeInvalid) {
476 matching_symbol = symbol;
477 return false; // Stop iterating
479 return true; // Keep iterating
481 sc.symbol = matching_symbol;
482 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
483 !(resolved_flags & eSymbolContextFunction)) {
484 bool verify_unique = false; // No need to check again since
485 // ResolveSymbolContext failed to find a
486 // symbol at this address.
487 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
489 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
493 if (sc.symbol->IsSynthetic()) {
494 // We have a synthetic symbol so lets check if the object file
495 // from the symbol file in the symbol vendor is different than
496 // the object file for the module, and if so search its symbol
497 // table to see if we can come up with a better symbol. For example
498 // dSYM files on MacOSX have an unstripped symbol table inside of
500 ObjectFile *symtab_objfile = symtab->GetObjectFile();
501 if (symtab_objfile && symtab_objfile->IsStripped()) {
502 SymbolFile *symfile = sym_vendor->GetSymbolFile();
504 ObjectFile *symfile_objfile = symfile->GetObjectFile();
505 if (symfile_objfile != symtab_objfile) {
506 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
507 if (symfile_symtab) {
509 symfile_symtab->FindSymbolContainingFileAddress(
510 so_addr.GetFileAddress());
511 if (symbol && !symbol->IsSynthetic()) {
519 resolved_flags |= eSymbolContextSymbol;
524 // For function symbols, so_addr may be off by one. This is a convention
526 // with FDE row indices in eh_frame sections, but requires extra logic here
528 // symbol lookup for disassembly and unwind.
529 if (resolve_scope & eSymbolContextSymbol &&
530 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
531 so_addr.IsSectionOffset()) {
532 Address previous_addr = so_addr;
533 previous_addr.Slide(-1);
535 bool do_resolve_tail_call_address = false; // prevent recursion
536 const uint32_t flags = ResolveSymbolContextForAddress(
537 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
538 if (flags & eSymbolContextSymbol) {
539 AddressRange addr_range;
540 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
541 false, addr_range)) {
542 if (addr_range.GetBaseAddress().GetSection() ==
543 so_addr.GetSection()) {
544 // If the requested address is one past the address range of a
545 // function (i.e. a tail call),
546 // or the decremented address is the start of a function (i.e. some
547 // forms of trampoline),
548 // indicate 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,
602 bool append, size_t max_matches,
603 VariableList &variables) {
604 SymbolVendor *symbols = GetSymbolVendor();
606 return symbols->FindGlobalVariables(name, parent_decl_ctx, append,
607 max_matches, variables);
611 size_t Module::FindGlobalVariables(const RegularExpression ®ex, bool append,
613 VariableList &variables) {
614 SymbolVendor *symbols = GetSymbolVendor();
616 return symbols->FindGlobalVariables(regex, append, 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
681 // even need to search for CPP methods or names.
682 CPlusPlusLanguage::MethodName cpp_method(name);
683 if (cpp_method.IsValid()) {
684 basename = cpp_method.GetBasename();
686 if (!cpp_method.GetQualifiers().empty()) {
687 // There is a "const" or other qualifier following the end of the
689 // this can't be a eFunctionNameTypeBase
690 m_name_type_mask &= ~(eFunctionNameTypeBase);
691 if (m_name_type_mask == eFunctionNameTypeNone)
695 // If the CPP method parser didn't manage to chop this up, try to fill
696 // in the base name if we can.
697 // If a::b::c is passed in, we need to just look up "c", and then we'll
698 // filter the result later.
699 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
704 if (name_type_mask & eFunctionNameTypeSelector) {
705 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
706 m_name_type_mask &= ~(eFunctionNameTypeSelector);
707 if (m_name_type_mask == eFunctionNameTypeNone)
712 // Still try and get a basename in case someone specifies a name type mask
713 // of eFunctionNameTypeFull and a name like "A::func"
714 if (basename.empty()) {
715 if (name_type_mask & eFunctionNameTypeFull &&
716 !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
717 CPlusPlusLanguage::MethodName cpp_method(name);
718 basename = cpp_method.GetBasename();
719 if (basename.empty())
720 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
726 if (!basename.empty()) {
727 // The name supplied was a partial C++ path like "a::count". In this case we
729 // lookup on the basename "count" and then make sure any matching results
730 // contain "a::count"
731 // so that it would match "b::a::count" and "a::count". This is why we set
732 // "match_name_after_lookup"
734 m_lookup_name.SetString(basename);
735 m_match_name_after_lookup = true;
737 // The name is already correct, just use the exact name as supplied, and we
739 // to check if any matches contain "name"
740 m_lookup_name = name;
741 m_match_name_after_lookup = false;
745 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
746 size_t start_idx) const {
747 if (m_match_name_after_lookup && m_name) {
749 size_t i = start_idx;
750 while (i < sc_list.GetSize()) {
751 if (!sc_list.GetContextAtIndex(i, sc))
753 ConstString full_name(sc.GetFunctionName());
755 ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) {
756 sc_list.RemoveContextAtIndex(i);
763 // If we have only full name matches we might have tried to set breakpoint on
764 // "func" and specified eFunctionNameTypeFull, but we might have found
765 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
766 // "func()" and "func" should end up matching.
767 if (m_name_type_mask == eFunctionNameTypeFull) {
769 size_t i = start_idx;
770 while (i < sc_list.GetSize()) {
771 if (!sc_list.GetContextAtIndex(i, sc))
773 // Make sure the mangled and demangled names don't match before we try
774 // to pull anything out
775 ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
776 ConstString full_name(sc.GetFunctionName());
777 if (mangled_name != m_name && full_name != m_name)
779 CPlusPlusLanguage::MethodName cpp_method(full_name);
780 if (cpp_method.IsValid()) {
781 if (cpp_method.GetContext().empty()) {
782 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
783 sc_list.RemoveContextAtIndex(i);
787 std::string qualified_name;
788 llvm::StringRef anon_prefix("(anonymous namespace)");
789 if (cpp_method.GetContext() == anon_prefix)
790 qualified_name = cpp_method.GetBasename().str();
792 qualified_name = cpp_method.GetScopeQualifiedName();
793 if (qualified_name.compare(m_name.GetCString()) != 0) {
794 sc_list.RemoveContextAtIndex(i);
805 size_t Module::FindFunctions(const ConstString &name,
806 const CompilerDeclContext *parent_decl_ctx,
807 uint32_t name_type_mask, bool include_symbols,
808 bool include_inlines, bool append,
809 SymbolContextList &sc_list) {
813 const size_t old_size = sc_list.GetSize();
815 // Find all the functions (not symbols, but debug information functions...
816 SymbolVendor *symbols = GetSymbolVendor();
818 if (name_type_mask & eFunctionNameTypeAuto) {
819 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
822 symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
823 lookup_info.GetNameTypeMask(), include_inlines,
826 // Now check our symbol table for symbols that are code symbols if
828 if (include_symbols) {
829 Symtab *symtab = symbols->GetSymtab();
831 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
832 lookup_info.GetNameTypeMask(), sc_list);
836 const size_t new_size = sc_list.GetSize();
838 if (old_size < new_size)
839 lookup_info.Prune(sc_list, old_size);
842 symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
843 include_inlines, append, sc_list);
845 // Now check our symbol table for symbols that are code symbols if
847 if (include_symbols) {
848 Symtab *symtab = symbols->GetSymtab();
850 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
855 return sc_list.GetSize() - old_size;
858 size_t Module::FindFunctions(const RegularExpression ®ex,
859 bool include_symbols, bool include_inlines,
860 bool append, SymbolContextList &sc_list) {
864 const size_t start_size = sc_list.GetSize();
866 SymbolVendor *symbols = GetSymbolVendor();
868 symbols->FindFunctions(regex, include_inlines, append, sc_list);
870 // Now check our symbol table for symbols that are code symbols if requested
871 if (include_symbols) {
872 Symtab *symtab = symbols->GetSymtab();
874 std::vector<uint32_t> symbol_indexes;
875 symtab->AppendSymbolIndexesMatchingRegExAndType(
876 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
878 const size_t num_matches = symbol_indexes.size();
880 SymbolContext sc(this);
881 const size_t end_functions_added_index = sc_list.GetSize();
882 size_t num_functions_added_to_sc_list =
883 end_functions_added_index - start_size;
884 if (num_functions_added_to_sc_list == 0) {
885 // No functions were added, just symbols, so we can just append them
886 for (size_t i = 0; i < num_matches; ++i) {
887 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
888 SymbolType sym_type = sc.symbol->GetType();
889 if (sc.symbol && (sym_type == eSymbolTypeCode ||
890 sym_type == eSymbolTypeResolver))
894 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
895 FileAddrToIndexMap file_addr_to_index;
896 for (size_t i = start_size; i < end_functions_added_index; ++i) {
897 const SymbolContext &sc = sc_list[i];
900 file_addr_to_index[sc.function->GetAddressRange()
902 .GetFileAddress()] = i;
905 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
906 // Functions were added so we need to merge symbols into any
907 // existing function symbol contexts
908 for (size_t i = start_size; i < num_matches; ++i) {
909 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
910 SymbolType sym_type = sc.symbol->GetType();
911 if (sc.symbol && sc.symbol->ValueIsAddress() &&
912 (sym_type == eSymbolTypeCode ||
913 sym_type == eSymbolTypeResolver)) {
914 FileAddrToIndexMap::const_iterator pos =
915 file_addr_to_index.find(
916 sc.symbol->GetAddressRef().GetFileAddress());
920 sc_list[pos->second].symbol = sc.symbol;
928 return sc_list.GetSize() - start_size;
931 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
932 const FileSpec &file, uint32_t line,
934 std::vector<Address> &output_local,
935 std::vector<Address> &output_extern) {
936 SearchFilterByModule filter(target_sp, m_file);
937 AddressResolverFileLine resolver(file, line, true);
938 resolver.ResolveAddress(filter);
940 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
941 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
942 Function *f = addr.CalculateSymbolContextFunction();
943 if (f && f == function)
944 output_local.push_back(addr);
946 output_extern.push_back(addr);
950 size_t Module::FindTypes_Impl(
951 const SymbolContext &sc, const ConstString &name,
952 const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
953 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
955 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
956 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
957 if (!sc.module_sp || sc.module_sp.get() == this) {
958 SymbolVendor *symbols = GetSymbolVendor();
960 return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
961 searched_symbol_files, types);
966 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
967 const ConstString &type_name,
968 const CompilerDeclContext *parent_decl_ctx,
969 size_t max_matches, TypeList &type_list) {
970 const bool append = true;
972 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
974 FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
975 searched_symbol_files, types_map);
977 sc.SortTypeList(types_map, type_list);
981 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
982 const ConstString &name, bool exact_match) {
984 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
985 const size_t num_matches =
986 FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
988 return type_list.GetTypeAtIndex(0);
992 size_t Module::FindTypes(
993 const SymbolContext &sc, const ConstString &name, bool exact_match,
995 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
997 size_t num_matches = 0;
998 const char *type_name_cstr = name.GetCString();
999 llvm::StringRef type_scope;
1000 llvm::StringRef type_basename;
1001 const bool append = true;
1002 TypeClass type_class = eTypeClassAny;
1004 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1006 // Check if "name" starts with "::" which means the qualified type starts
1007 // from the root namespace and implies and exact match. The typenames we
1008 // get back from clang do not start with "::" so we need to strip this off
1009 // in order to get the qualified names to match
1010 exact_match = type_scope.consume_front("::");
1012 ConstString type_basename_const_str(type_basename);
1013 if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1014 max_matches, searched_symbol_files, typesmap)) {
1015 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1017 num_matches = typesmap.GetSize();
1020 // The type is not in a namespace/class scope, just search for it by
1022 if (type_class != eTypeClassAny) {
1023 // The "type_name_cstr" will have been modified if we have a valid type
1025 // prefix (like "struct", "class", "union", "typedef" etc).
1026 FindTypes_Impl(sc, ConstString(type_basename), nullptr, append,
1027 max_matches, searched_symbol_files, typesmap);
1028 typesmap.RemoveMismatchedTypes(type_class);
1029 num_matches = typesmap.GetSize();
1031 num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches,
1032 searched_symbol_files, typesmap);
1035 if (num_matches > 0)
1036 sc.SortTypeList(typesmap, types);
1040 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1041 lldb_private::Stream *feedback_strm) {
1042 if (!m_did_load_symbol_vendor.load()) {
1043 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1044 if (!m_did_load_symbol_vendor.load() && can_create) {
1045 ObjectFile *obj_file = GetObjectFile();
1046 if (obj_file != nullptr) {
1047 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1048 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
1050 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1051 m_did_load_symbol_vendor = true;
1055 return m_symfile_ap.get();
1058 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1059 const ConstString &object_name) {
1060 // Container objects whose paths do not specify a file directly can call
1061 // this function to correct the file and object names.
1063 m_mod_time = FileSystem::GetModificationTime(file);
1064 m_object_name = object_name;
1067 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1069 std::string Module::GetSpecificationDescription() const {
1070 std::string spec(GetFileSpec().GetPath());
1071 if (m_object_name) {
1073 spec += m_object_name.GetCString();
1079 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1080 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1082 if (level >= eDescriptionLevelFull) {
1083 if (m_arch.IsValid())
1084 s->Printf("(%s) ", m_arch.GetArchitectureName());
1087 if (level == eDescriptionLevelBrief) {
1088 const char *filename = m_file.GetFilename().GetCString();
1090 s->PutCString(filename);
1092 char path[PATH_MAX];
1093 if (m_file.GetPath(path, sizeof(path)))
1094 s->PutCString(path);
1097 const char *object_name = m_object_name.GetCString();
1099 s->Printf("(%s)", object_name);
1102 void Module::ReportError(const char *format, ...) {
1103 if (format && format[0]) {
1105 strm.PutCString("error: ");
1106 GetDescription(&strm, lldb::eDescriptionLevelBrief);
1109 va_start(args, format);
1110 strm.PrintfVarArg(format, args);
1113 const int format_len = strlen(format);
1114 if (format_len > 0) {
1115 const char last_char = format[format_len - 1];
1116 if (last_char != '\n' || last_char != '\r')
1119 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1123 bool Module::FileHasChanged() const {
1124 if (!m_file_has_changed)
1125 m_file_has_changed =
1126 (FileSystem::GetModificationTime(m_file) != m_mod_time);
1127 return m_file_has_changed;
1130 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1131 if (!m_first_file_changed_log) {
1132 if (FileHasChanged()) {
1133 m_first_file_changed_log = true;
1136 strm.PutCString("error: the object file ");
1137 GetDescription(&strm, lldb::eDescriptionLevelFull);
1138 strm.PutCString(" has been modified\n");
1141 va_start(args, format);
1142 strm.PrintfVarArg(format, args);
1145 const int format_len = strlen(format);
1146 if (format_len > 0) {
1147 const char last_char = format[format_len - 1];
1148 if (last_char != '\n' || last_char != '\r')
1151 strm.PutCString("The debug session should be aborted as the original "
1152 "debug information has been overwritten.\n");
1153 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1159 void Module::ReportWarning(const char *format, ...) {
1160 if (format && format[0]) {
1162 strm.PutCString("warning: ");
1163 GetDescription(&strm, lldb::eDescriptionLevelFull);
1167 va_start(args, format);
1168 strm.PrintfVarArg(format, args);
1171 const int format_len = strlen(format);
1172 if (format_len > 0) {
1173 const char last_char = format[format_len - 1];
1174 if (last_char != '\n' || last_char != '\r')
1177 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1181 void Module::LogMessage(Log *log, const char *format, ...) {
1182 if (log != nullptr) {
1183 StreamString log_message;
1184 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1185 log_message.PutCString(": ");
1187 va_start(args, format);
1188 log_message.PrintfVarArg(format, args);
1190 log->PutCString(log_message.GetData());
1194 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1195 if (log != nullptr) {
1196 StreamString log_message;
1197 GetDescription(&log_message, lldb::eDescriptionLevelFull);
1198 log_message.PutCString(": ");
1200 va_start(args, format);
1201 log_message.PrintfVarArg(format, args);
1203 if (log->GetVerbose()) {
1204 std::string back_trace;
1205 llvm::raw_string_ostream stream(back_trace);
1206 llvm::sys::PrintStackTrace(stream);
1207 log_message.PutCString(back_trace);
1209 log->PutCString(log_message.GetData());
1213 void Module::Dump(Stream *s) {
1214 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1215 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1217 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1218 m_object_name ? "(" : "",
1219 m_object_name ? m_object_name.GetCString() : "",
1220 m_object_name ? ")" : "");
1224 ObjectFile *objfile = GetObjectFile();
1228 SymbolVendor *symbols = GetSymbolVendor();
1235 TypeList *Module::GetTypeList() {
1236 SymbolVendor *symbols = GetSymbolVendor();
1238 return &symbols->GetTypeList();
1242 const ConstString &Module::GetObjectName() const { return m_object_name; }
1244 ObjectFile *Module::GetObjectFile() {
1245 if (!m_did_load_objfile.load()) {
1246 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1247 if (!m_did_load_objfile.load()) {
1248 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1249 Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s",
1250 GetFileSpec().GetFilename().AsCString(""));
1251 DataBufferSP data_sp;
1252 lldb::offset_t data_offset = 0;
1253 const lldb::offset_t file_size = m_file.GetByteSize();
1254 if (file_size > m_object_offset) {
1255 m_did_load_objfile = true;
1256 m_objfile_sp = ObjectFile::FindPlugin(
1257 shared_from_this(), &m_file, m_object_offset,
1258 file_size - m_object_offset, data_sp, data_offset);
1260 // Once we get the object file, update our module with the object
1262 // architecture since it might differ in vendor/os if some parts were
1263 // unknown. But since the matching arch might already be more
1265 // than the generic COFF architecture, only merge in those values that
1266 // 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_unified_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() {
1300 // Populate m_unified_sections_ap with sections from objfile.
1302 m_sections_ap = llvm::make_unique<SectionList>();
1303 return m_sections_ap.get();
1306 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1307 SymbolType symbol_type) {
1308 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1310 func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1311 name.AsCString(), symbol_type);
1312 SymbolVendor *sym_vendor = GetSymbolVendor();
1314 Symtab *symtab = sym_vendor->GetSymtab();
1316 return symtab->FindFirstSymbolWithNameAndType(
1317 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1321 void Module::SymbolIndicesToSymbolContextList(
1322 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1323 SymbolContextList &sc_list) {
1324 // No need to protect this call using m_mutex all other method calls are
1325 // already thread safe.
1327 size_t num_indices = symbol_indexes.size();
1328 if (num_indices > 0) {
1330 CalculateSymbolContext(&sc);
1331 for (size_t i = 0; i < num_indices; i++) {
1332 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1339 size_t Module::FindFunctionSymbols(const ConstString &name,
1340 uint32_t name_type_mask,
1341 SymbolContextList &sc_list) {
1342 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1343 Timer scoped_timer(func_cat,
1344 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1345 name.AsCString(), name_type_mask);
1346 SymbolVendor *sym_vendor = GetSymbolVendor();
1348 Symtab *symtab = sym_vendor->GetSymtab();
1350 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1355 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1356 SymbolType symbol_type,
1357 SymbolContextList &sc_list) {
1358 // No need to protect this call using m_mutex all other method calls are
1359 // already thread safe.
1361 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1363 func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1364 name.AsCString(), symbol_type);
1365 const size_t initial_size = sc_list.GetSize();
1366 SymbolVendor *sym_vendor = GetSymbolVendor();
1368 Symtab *symtab = sym_vendor->GetSymtab();
1370 std::vector<uint32_t> symbol_indexes;
1371 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1372 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1375 return sc_list.GetSize() - initial_size;
1378 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex,
1379 SymbolType symbol_type,
1380 SymbolContextList &sc_list) {
1381 // No need to protect this call using m_mutex all other method calls are
1382 // already thread safe.
1384 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1387 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1388 regex.GetText().str().c_str(), symbol_type);
1389 const size_t initial_size = sc_list.GetSize();
1390 SymbolVendor *sym_vendor = GetSymbolVendor();
1392 Symtab *symtab = sym_vendor->GetSymtab();
1394 std::vector<uint32_t> symbol_indexes;
1395 symtab->FindAllSymbolsMatchingRexExAndType(
1396 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1398 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1401 return sc_list.GetSize() - initial_size;
1404 void Module::PreloadSymbols() {
1405 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1406 SymbolVendor * sym_vendor = GetSymbolVendor();
1410 // Prime the symbol file first, since it adds symbols to the symbol table.
1411 if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) {
1412 symbol_file->PreloadSymbols();
1414 // Now we can prime the symbol table.
1415 if (Symtab * symtab = sym_vendor->GetSymtab()) {
1416 symtab->PreloadSymbols();
1420 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1424 // Remove any sections in the unified section list that come from the
1425 // current symbol vendor.
1426 SectionList *section_list = GetSectionList();
1427 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1428 if (section_list && symbol_file) {
1429 ObjectFile *obj_file = symbol_file->GetObjectFile();
1430 // Make sure we have an object file and that the symbol vendor's objfile
1432 // the same as the module's objfile before we remove any sections for
1435 // Check to make sure we aren't trying to specify the file we already
1437 if (obj_file->GetFileSpec() == file) {
1438 // We are being told to add the exact same file that we already have
1439 // we don't have to do anything.
1443 // Cleare the current symtab as we are going to replace it with a new
1445 obj_file->ClearSymtab();
1447 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1449 // of a full path to the symbol file within the bundle
1450 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1453 if (llvm::sys::fs::is_directory(file.GetPath())) {
1454 std::string new_path(file.GetPath());
1455 std::string old_path(obj_file->GetFileSpec().GetPath());
1456 if (old_path.find(new_path) == 0) {
1457 // We specified the same bundle as the symbol file that we already
1463 if (obj_file != m_objfile_sp.get()) {
1464 size_t num_sections = section_list->GetNumSections(0);
1465 for (size_t idx = num_sections; idx > 0; --idx) {
1466 lldb::SectionSP section_sp(
1467 section_list->GetSectionAtIndex(idx - 1));
1468 if (section_sp->GetObjectFile() == obj_file) {
1469 section_list->DeleteSection(idx - 1);
1475 // Keep all old symbol files around in case there are any lingering type
1477 // any SBValue objects that might have been handed out.
1478 m_old_symfiles.push_back(std::move(m_symfile_ap));
1480 m_symfile_spec = file;
1481 m_symfile_ap.reset();
1482 m_did_load_symbol_vendor = false;
1485 bool Module::IsExecutable() {
1486 if (GetObjectFile() == nullptr)
1489 return GetObjectFile()->IsExecutable();
1492 bool Module::IsLoadedInTarget(Target *target) {
1493 ObjectFile *obj_file = GetObjectFile();
1495 SectionList *sections = GetSectionList();
1496 if (sections != nullptr) {
1497 size_t num_sections = sections->GetSize();
1498 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1499 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1500 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1509 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1510 Stream *feedback_stream) {
1512 error.SetErrorString("invalid destination Target");
1516 LoadScriptFromSymFile should_load =
1517 target->TargetProperties::GetLoadScriptFromSymbolFile();
1519 if (should_load == eLoadScriptFromSymFileFalse)
1522 Debugger &debugger = target->GetDebugger();
1523 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1524 if (script_language != eScriptLanguageNone) {
1526 PlatformSP platform_sp(target->GetPlatform());
1529 error.SetErrorString("invalid Platform");
1533 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1534 target, *this, feedback_stream);
1536 const uint32_t num_specs = file_specs.GetSize();
1538 ScriptInterpreter *script_interpreter =
1539 debugger.GetCommandInterpreter().GetScriptInterpreter();
1540 if (script_interpreter) {
1541 for (uint32_t i = 0; i < num_specs; ++i) {
1542 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1543 if (scripting_fspec && scripting_fspec.Exists()) {
1544 if (should_load == eLoadScriptFromSymFileWarn) {
1545 if (feedback_stream)
1546 feedback_stream->Printf(
1547 "warning: '%s' contains a debug script. To run this script "
1549 "this debug session:\n\n command script import "
1551 "To run all discovered debug scripts in this session:\n\n"
1552 " settings set target.load-script-from-symbol-file "
1554 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1555 scripting_fspec.GetPath().c_str());
1558 StreamString scripting_stream;
1559 scripting_fspec.Dump(&scripting_stream);
1560 const bool can_reload = true;
1561 const bool init_lldb_globals = false;
1562 bool did_load = script_interpreter->LoadScriptingModule(
1563 scripting_stream.GetData(), can_reload, init_lldb_globals,
1570 error.SetErrorString("invalid ScriptInterpreter");
1578 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1579 if (!m_arch.IsValid()) {
1583 return m_arch.IsCompatibleMatch(new_arch);
1586 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1587 bool value_is_offset, bool &changed) {
1588 ObjectFile *object_file = GetObjectFile();
1589 if (object_file != nullptr) {
1590 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1598 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1599 const UUID &uuid = module_ref.GetUUID();
1601 if (uuid.IsValid()) {
1602 // If the UUID matches, then nothing more needs to match...
1603 return (uuid == GetUUID());
1606 const FileSpec &file_spec = module_ref.GetFileSpec();
1608 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1609 !FileSpec::Equal(file_spec, m_platform_file,
1610 (bool)file_spec.GetDirectory()))
1614 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1615 if (platform_file_spec) {
1616 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1617 (bool)platform_file_spec.GetDirectory()))
1621 const ArchSpec &arch = module_ref.GetArchitecture();
1622 if (arch.IsValid()) {
1623 if (!m_arch.IsCompatibleMatch(arch))
1627 const ConstString &object_name = module_ref.GetObjectName();
1629 if (object_name != GetObjectName())
1635 bool Module::FindSourceFile(const FileSpec &orig_spec,
1636 FileSpec &new_spec) const {
1637 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1638 return m_source_mappings.FindFile(orig_spec, new_spec);
1641 bool Module::RemapSourceFile(llvm::StringRef path,
1642 std::string &new_path) const {
1643 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1644 return m_source_mappings.RemapPath(path, new_path);
1647 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) {
1648 ObjectFile *obj_file = GetObjectFile();
1650 return obj_file->GetVersion(versions, num_versions);
1652 if (versions != nullptr && num_versions != 0) {
1653 for (uint32_t i = 0; i < num_versions; ++i)
1654 versions[i] = LLDB_INVALID_MODULE_VERSION;
1660 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) {
1662 // Must create a module and place it into a shared pointer before
1663 // we can create an object file since it has a std::weak_ptr back
1664 // to the module, so we need to control the creation carefully in
1665 // this static function
1666 ModuleSP module_sp(new Module());
1667 module_sp->m_objfile_sp =
1668 std::make_shared<ObjectFileJIT>(module_sp, delegate_sp);
1669 if (module_sp->m_objfile_sp) {
1670 // Once we get the object file, update our module with the object file's
1671 // architecture since it might differ in vendor/os if some parts were
1673 module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch);
1680 bool Module::GetIsDynamicLinkEditor() {
1681 ObjectFile *obj_file = GetObjectFile();
1684 return obj_file->GetIsDynamicLinkEditor();
1689 Status Module::LoadInMemory(Target &target, bool set_pc) {
1690 return m_objfile_sp->LoadInMemory(target, set_pc);