34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/ScopeExit.h"
45 "__lldb_objc_find_implementation_for_selector";
46const char *AppleObjCTrampolineHandler::
47 g_lookup_implementation_with_stret_function_code =
50 return_struct.impl_addr =
51 class_getMethodImplementation_stret (return_struct.class_addr,
52 return_struct.sel_addr);
54 return_struct.impl_addr =
55 class_getMethodImplementation (return_struct.class_addr,
56 return_struct.sel_addr);
59 printf ("\n*** Returning implementation: %p.\n",
60 return_struct.impl_addr);
62 return return_struct.impl_addr;
68 return_struct.impl_addr =
69 class_getMethodImplementation (return_struct.class_addr,
70 return_struct.sel_addr);
72 printf ("\n*** getMethodImpletation for addr: 0x%p sel: 0x%p result: 0x%p.\n",
73 return_struct.class_addr, return_struct.sel_addr, return_struct.impl_addr);
75 return return_struct.impl_addr;
84 extern void *class_getMethodImplementation(void *objc_class, void *sel);
85 extern void *class_getMethodImplementation_stret(void *objc_class, void *sel);
86 extern void * object_getClass (id object);
87 extern void * sel_getUid(char *name);
88 extern int printf(const char *format, ...);
91__lldb_objc_find_implementation_for_selector (void *object,
101 struct __lldb_imp_return_struct {
107 struct __lldb_objc_class {
111 struct __lldb_objc_super {
113 struct __lldb_objc_class *class_ptr;
115 struct __lldb_msg_ref {
120 struct __lldb_imp_return_struct return_struct;
123 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
124 "is_stret: %d is_super: %d, "
125 "is_super2: %d, is_fixup: %d, is_fixed: %d\n",
126 object, sel, is_str_ptr, is_stret,
127 is_super, is_super2, is_fixup, is_fixed);
131 printf("*** Turning string: '%s'", sel);
132 sel = sel_getUid((char *)sel);
134 printf("*** into sel to %p", sel);
138 return_struct.class_addr
139 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
141 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
144 printf("*** Super, class addr: %p\n", return_struct.class_addr);
146 // This code seems a little funny, but has its reasons...
147 // The call to [object class] is here because if this is a class, and has
148 // not been called into yet, we need to do something to force the class to
149 // initialize itself.
150 // Then the call to object_getClass will actually return the correct class,
151 // either the class if object is a class instance, or the meta-class if it
152 // is a class pointer.
153 void *class_ptr = (void *) [(id) object class];
154 return_struct.class_addr = (id) object_getClass((id) object);
156 if (class_ptr == object) {
157 printf ("Found a class object, need to return the meta class %p -> %p\n",
158 class_ptr, return_struct.class_addr);
160 printf ("[object class] returned: %p object_getClass: %p.\n",
161 class_ptr, return_struct.class_addr);
168 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;
170 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;
171 return_struct.sel_addr = sel_getUid (sel_name);
173 printf ("\n*** Got fixed up selector: %p for name %s.\n",
174 return_struct.sel_addr, sel_name);
177 return_struct.sel_addr = sel;
183 : m_valid(true), m_owner(owner), m_header_addr(header_addr) {
199 char memory_buffer[16];
200 ProcessSP process_sp = m_owner->GetProcessSP();
204 process_sp->GetByteOrder(),
205 process_sp->GetAddressByteSize());
206 size_t actual_size = 8 + process_sp->GetAddressByteSize();
209 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size,
error);
210 if (bytes_read != actual_size) {
216 const uint16_t header_size = data.
GetU16(&offset);
217 const uint16_t descriptor_size = data.
GetU16(&offset);
218 const size_t num_descriptors = data.
GetU32(&offset);
225 if (header_size == 0 || num_descriptors == 0) {
243 const lldb::addr_t desc_ptr = m_header_addr + header_size;
244 const size_t desc_array_size = num_descriptors * descriptor_size;
246 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
248 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
249 process_sp->GetAddressByteSize());
250 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size,
error);
251 if (bytes_read != desc_array_size) {
260 m_code_start_addr = 0;
263 for (
size_t i = 0; i < num_descriptors; i++) {
265 uint32_t voffset = desc_extractor.
GetU32(&offset);
266 uint32_t flags = desc_extractor.
GetU32(&offset);
267 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
270 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
271 m_code_start_addr = code_addr;
272 if (code_addr > m_code_end_addr)
273 m_code_end_addr = code_addr;
275 offset = start_offset + descriptor_size;
281 bool all_the_same =
true;
282 for (
size_t i = 0; i < num_descriptors - 1; i++) {
284 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
286 code_size = this_size;
288 if (this_size != code_size)
289 all_the_same =
false;
290 if (this_size > code_size)
291 code_size = this_size;
295 m_code_end_addr += code_size;
303 if (addr < m_code_start_addr || addr > m_code_end_addr)
306 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
307 for (pos = m_descriptors.begin(); pos != end; pos++) {
308 if (addr <= (*pos).code_start) {
309 flags = (*pos).flags;
318 s.
Printf(
"Header addr: 0x%" PRIx64
" Code start: 0x%" PRIx64
319 " Code End: 0x%" PRIx64
" Next: 0x%" PRIx64
"\n",
320 m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
321 size_t num_elements = m_descriptors.size();
322 for (
size_t i = 0; i < num_elements; i++) {
324 s.
Printf(
"Code start: 0x%" PRIx64
" Flags: %d\n",
325 m_descriptors[i].code_start, m_descriptors[i].flags);
342 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
352 Target &target = process_sp->GetTarget();
357 ->IsModuleObjCLibrary(module_sp)) {
365 ConstString trampoline_name(
"gdb_objc_trampolines");
366 const Symbol *trampoline_symbol =
369 if (trampoline_symbol !=
nullptr) {
375 ConstString changed_name(
"gdb_objc_trampolines_changed");
376 const Symbol *changed_symbol =
379 if (changed_symbol !=
nullptr) {
381 if (!changed_symbol_addr.
IsValid())
389 if (trampolines_changed_bp_sp) {
390 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
391 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines,
this,
393 trampolines_changed_bp_sp->SetBreakpointKind(
394 "objc-trampolines-changed");
416 const ABI *abi = process->
GetABI().get();
447 if (region_addr != 0)
458 if (!InitializeVTableSymbols())
464 process_sp->ReadPointerFromMemory(m_trampoline_header,
error);
466 return ReadRegions(region_addr);
480 InitializeVTableSymbols();
484 while (next_region != 0) {
486 if (!m_regions.back().IsValid()) {
492 m_regions.back().Dump(s);
496 next_region = m_regions.back().GetNextRegionAddr();
504 region_collection::iterator pos, end = m_regions.end();
505 for (pos = m_regions.begin(); pos != end; pos++) {
506 if ((*pos).AddressInRegion(addr, flags))
516 {
"objc_msgSend_fixup",
false,
false,
false,
518 {
"objc_msgSend_fixedup",
false,
false,
false,
520 {
"objc_msgSend_stret",
true,
false,
false,
522 {
"objc_msgSend_stret_fixup",
true,
false,
false,
524 {
"objc_msgSend_stret_fixedup",
true,
false,
false,
526 {
"objc_msgSend_fpret",
false,
false,
false,
528 {
"objc_msgSend_fpret_fixup",
false,
false,
false,
530 {
"objc_msgSend_fpret_fixedup",
false,
false,
false,
532 {
"objc_msgSend_fp2ret",
false,
false,
true,
534 {
"objc_msgSend_fp2ret_fixup",
false,
false,
true,
536 {
"objc_msgSend_fp2ret_fixedup",
false,
false,
true,
539 {
"objc_msgSendSuper_stret",
true,
true,
false,
542 {
"objc_msgSendSuper2_fixup",
false,
true,
true,
544 {
"objc_msgSendSuper2_fixedup",
false,
true,
true,
546 {
"objc_msgSendSuper2_stret",
true,
true,
true,
548 {
"objc_msgSendSuper2_stret_fixup",
true,
true,
true,
550 {
"objc_msgSendSuper2_stret_fixedup",
true,
true,
true,
567 "objc_allocWithZone",
569 "objc_opt_isKindOfClass",
571 "objc_opt_respondsToSelector",
586 ConstString get_impl_name(
"class_getMethodImplementation");
587 ConstString get_impl_stret_name(
"class_getMethodImplementation_stret");
589 ConstString msg_forward_stret_name(
"_objc_msgForward_stret");
591 Target *target = process_sp ? &process_sp->GetTarget() :
nullptr;
592 const Symbol *class_getMethodImplementation =
595 const Symbol *class_getMethodImplementation_stret =
600 const Symbol *msg_forward_stret =
604 if (class_getMethodImplementation)
608 if (class_getMethodImplementation_stret)
614 if (msg_forward_stret)
624 if (process_sp->CanJIT()) {
625 process_sp->GetTarget().GetDebugger().GetErrorStream().Printf(
626 "Could not find implementation lookup function \"%s\""
627 " step in through ObjC method dispatch will not work.\n",
660 const Symbol *msgSend_symbol =
673 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
680 const Symbol *msgSend_symbol =
701 ThreadSP thread_sp(thread.shared_from_this());
719 if (!utility_fn_or_error) {
721 log, utility_fn_or_error.takeError(),
722 "Failed to get Utility Function for implementation lookup: {0}.");
727 LLDB_LOGF(log,
"No method lookup implementation code.");
741 impl_function_caller =
m_impl_code->MakeFunctionCaller(
742 clang_void_ptr_type, dispatch_values, thread_sp,
error);
745 "Error getting function caller for dispatch lookup: \"%s\".",
750 impl_function_caller =
m_impl_code->GetFunctionCaller();
762 exe_ctx, args_addr, dispatch_values, diagnostics)) {
764 LLDB_LOGF(log,
"Error writing function arguments.");
765 diagnostics.
Dump(log);
775 MsgsendMap::iterator pos;
814 llvm::StringRef sym_name;
822 if (!sym_name.empty() && !sym_name.consume_front(
"objc_msgSend$"))
825 this_dispatch = &sel_stub_dispatch;
827 bool in_selector_stub = !sym_name.empty();
832 if (!in_selector_stub)
843 this_dispatch = &vtable_dispatch;
859 const ABI *abi =
nullptr;
862 abi = process_sp->GetABI().get();
874 Value void_ptr_value;
891 if (in_selector_stub) {
894 argument_values.
PushValue(void_ptr_value);
898 argument_values.
PushValue(void_ptr_value);
899 argument_values.
PushValue(void_ptr_value);
900 argument_values.
PushValue(void_ptr_value);
904 argument_values.
PushValue(void_ptr_value);
905 argument_values.
PushValue(void_ptr_value);
914 if (obj_addr == 0x0) {
917 "Asked to step to dispatch to nil object, returning empty plan.");
930 if (!in_selector_stub)
947 super_value.
GetScalar() += process_sp->GetAddressByteSize();
954 super_value.
GetScalar() += process_sp->GetAddressByteSize();
959 LLDB_LOGF(log,
"Failed to extract the super class value from the "
960 "class in objc_super.");
963 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
973 super_value.
GetScalar() += process_sp->GetAddressByteSize();
979 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
1002 LLDB_LOGF(log,
"Failed to extract the isa value from object.");
1013 assert(objc_runtime !=
nullptr);
1014 if (!in_selector_stub) {
1015 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
1016 isa_addr, sel_addr);
1019 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
1020 isa_addr, sym_name);
1029 LLDB_LOGF(log,
"Found implementation address in cache: 0x%" PRIx64,
1032 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1061 if (!in_selector_stub) {
1069 sel_str_addr = process_sp->AllocateMemory(
1070 sym_name.size() + 1, ePermissionsReadable | ePermissionsWritable,
1074 "Could not allocate memory for selector string {0}: {1}",
1078 process_sp->WriteMemory(sel_str_addr, sym_name.str().c_str(),
1079 sym_name.size() + 1,
error);
1081 LLDB_LOG(log,
"Could not write string to address {0}", sel_str_addr);
1084 Value sel_ptr_value(void_ptr_value);
1085 sel_ptr_value.
GetScalar() = sel_str_addr;
1086 dispatch_values.
PushValue(sel_ptr_value);
1091 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1097 if (in_selector_stub)
1121 switch (this_dispatch->
fixedup) {
1146 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1147 thread, *
this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1163 if (!this_dispatch && !ret_plan_sp) {
1164 MsgsendMap::iterator pos;
1168 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1169 thread, *
this, opt_name);
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOG_ERROR(log, error,...)
virtual bool GetArgumentValues(Thread &thread, ValueList &values) const =0
A section + offset based address class.
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
bool IsValid() const
Check if the object state is valid.
Symbol * CalculateSymbolContextSymbol() const
bool AddressInRegion(lldb::addr_t addr, uint32_t &flags)
lldb::break_id_t m_trampolines_changed_bp_id
lldb::addr_t m_trampoline_header
static bool RefreshTrampolines(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
lldb::ProcessWP m_process_wp
AppleObjCVTables(const lldb::ProcessSP &process_sp, const lldb::ModuleSP &objc_module_sp)
lldb::ModuleSP m_objc_module_sp
bool InitializeVTableSymbols()
bool IsAddressInVTables(lldb::addr_t addr, uint32_t &flags)
static const char * g_lookup_implementation_function_name
These hold the code for the function that finds the implementation of an ObjC message send given the ...
std::string m_lookup_implementation_function_code
static const DispatchFunction g_dispatch_functions[]
lldb::ProcessWP m_process_wp
MsgsendMap m_opt_dispatch_map
lldb::ModuleSP m_objc_module_sp
lldb::addr_t m_msg_forward_stret_addr
lldb::addr_t SetupDispatchFunction(Thread &thread, ValueList &dispatch_values)
std::mutex m_impl_function_mutex
static const char * g_lookup_implementation_with_stret_function_code
static const char * g_opt_dispatch_names[]
std::unique_ptr< AppleObjCVTables > m_vtables_up
std::unique_ptr< UtilityFunction > m_impl_code
~AppleObjCTrampolineHandler()
lldb::addr_t m_msg_forward_addr
static const char * g_lookup_implementation_no_stret_function_code
void ForEachDispatchFunction(std::function< void(lldb::addr_t, const DispatchFunction &)>)
lldb::ThreadPlanSP GetStepThroughDispatchPlan(Thread &thread, bool stop_others)
const DispatchFunction * FindDispatchFunction(lldb::addr_t addr)
AppleObjCTrampolineHandler(const lldb::ProcessSP &process_sp, const lldb::ModuleSP &objc_module_sp)
lldb::addr_t m_impl_stret_fn_addr
lldb::addr_t m_impl_fn_addr
static const char * g_lookup_implementation_function_common_code
FunctionCaller * GetLookupImplementationFunctionCaller()
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
A uniqued constant string class.
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
A subclass of DataBuffer that stores a data buffer on the heap.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Target & GetTargetRef() const
Returns a reference to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
Encapsulates a function that can be called.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
ModuleIterable Modules() const
lldb::addr_t LookupInMethodCache(lldb::addr_t class_addr, lldb::addr_t sel)
static ObjCLanguageRuntime * Get(Process &process)
A plug-in interface definition class for debugging a process.
const lldb::ABISP & GetABI()
Target & GetTarget()
Get the target object pointer for this module.
unsigned long long ULongLong(unsigned long long fail_value=0) const
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
ExecutionContextRef exe_ctx_ref
const char * GetData() const
A stream class that can stream formatted output to a file.
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
lldb::addr_t GetLoadAddress(Target *target) const
bool ValueIsAddress() const
Address & GetAddressRef()
ConstString GetName() const
Address GetAddress() const
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
const ModuleList & GetImages() const
Get accessor for the images for this process.
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
virtual lldb::RegisterContextSP GetRegisterContext()=0
lldb::ProcessSP CalculateProcess() override
lldb::TargetSP CalculateTarget() override
lldb::ProcessSP GetProcess() const
void PushValue(const Value &value)
Value * GetValueAtIndex(size_t idx)
const Scalar & GetScalar() const
Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, Module *module)
@ LoadAddress
A load address value.
@ Scalar
A raw scalar value.
void SetCompilerType(const CompilerType &compiler_type)
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
void SetValueType(ValueType value_type)
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
@ eEncodingSint
signed integer
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP