34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/ScopeExit.h"
36#include "llvm/Support/Error.h"
46 "__lldb_objc_find_implementation_for_selector";
47const char *AppleObjCTrampolineHandler::
48 g_lookup_implementation_with_stret_function_code =
51 return_struct.impl_addr =
52 class_getMethodImplementation_stret (return_struct.class_addr,
53 return_struct.sel_addr);
55 return_struct.impl_addr =
56 class_getMethodImplementation (return_struct.class_addr,
57 return_struct.sel_addr);
60 printf ("\n*** Returning implementation: %p.\n",
61 return_struct.impl_addr);
63 return return_struct.impl_addr;
69 return_struct.impl_addr =
70 class_getMethodImplementation (return_struct.class_addr,
71 return_struct.sel_addr);
73 printf ("\n*** getMethodImpletation for addr: 0x%p sel: 0x%p result: 0x%p.\n",
74 return_struct.class_addr, return_struct.sel_addr, return_struct.impl_addr);
76 return return_struct.impl_addr;
85 extern void *class_getMethodImplementation(void *objc_class, void *sel);
86 extern void *class_getMethodImplementation_stret(void *objc_class, void *sel);
87 extern void * object_getClass (id object);
88 extern void * sel_getUid(char *name);
89 extern int printf(const char *format, ...);
92__lldb_objc_find_implementation_for_selector (void *object,
100 struct __lldb_imp_return_struct {
106 struct __lldb_objc_class {
110 struct __lldb_objc_super {
112 struct __lldb_objc_class *class_ptr;
114 struct __lldb_msg_ref {
119 struct __lldb_imp_return_struct return_struct;
122 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
123 "is_stret: %d is_super: %d, "
125 object, sel, is_str_ptr, is_stret,
126 is_super, is_super2);
130 printf("*** Turning string: '%s'", sel);
131 sel = sel_getUid((char *)sel);
133 printf("*** into sel to %p", sel);
137 return_struct.class_addr
138 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
140 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
142#if defined(__arm64e__)
143 return_struct.class_addr =
144 __builtin_ptrauth_strip(return_struct.class_addr, /*ptrauth_key_asda*/ 2);
147 printf("*** Super, class addr: %p\n", return_struct.class_addr);
149 // This code seems a little funny, but has its reasons...
150 // The call to [object class] is here because if this is a class, and has
151 // not been called into yet, we need to do something to force the class to
152 // initialize itself.
153 // Then the call to object_getClass will actually return the correct class,
154 // either the class if object is a class instance, or the meta-class if it
155 // is a class pointer.
156 void *class_ptr = (void *) [(id) object class];
157 return_struct.class_addr = (id) object_getClass((id) object);
159 if (class_ptr == object) {
160 printf ("Found a class object, need to return the meta class %p -> %p\n",
161 class_ptr, return_struct.class_addr);
163 printf ("[object class] returned: %p object_getClass: %p.\n",
164 class_ptr, return_struct.class_addr);
169 return_struct.sel_addr = sel;
191 char memory_buffer[16];
196 process_sp->GetByteOrder(),
197 process_sp->GetAddressByteSize());
198 size_t actual_size = 8 + process_sp->GetAddressByteSize();
202 if (bytes_read != actual_size) {
208 const uint16_t header_size = data.
GetU16(&offset);
209 const uint16_t descriptor_size = data.
GetU16(&offset);
210 const size_t num_descriptors = data.
GetU32(&offset);
217 if (header_size == 0 || num_descriptors == 0) {
236 const size_t desc_array_size = num_descriptors * descriptor_size;
238 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
240 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
241 process_sp->GetAddressByteSize());
242 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size,
error);
243 if (bytes_read != desc_array_size) {
255 for (
size_t i = 0; i < num_descriptors; i++) {
257 uint32_t voffset = desc_extractor.
GetU32(&offset);
258 uint32_t flags = desc_extractor.
GetU32(&offset);
259 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
267 offset = start_offset + descriptor_size;
273 bool all_the_same =
true;
274 for (
size_t i = 0; i < num_descriptors - 1; i++) {
278 code_size = this_size;
280 if (this_size != code_size)
281 all_the_same =
false;
282 if (this_size > code_size)
283 code_size = this_size;
298 std::vector<VTableDescriptor>::iterator pos, end =
m_descriptors.end();
300 if (addr <= (*pos).code_start) {
301 flags = (*pos).flags;
310 s.
Printf(
"Header addr: 0x%" PRIx64
" Code start: 0x%" PRIx64
311 " Code End: 0x%" PRIx64
" Next: 0x%" PRIx64
"\n",
314 for (
size_t i = 0; i < num_elements; i++) {
316 s.
Printf(
"Code start: 0x%" PRIx64
" Flags: %d\n",
344 Target &target = process_sp->GetTarget();
349 ->IsModuleObjCLibrary(module_sp)) {
357 ConstString trampoline_name(
"gdb_objc_trampolines");
358 const Symbol *trampoline_symbol =
361 if (trampoline_symbol !=
nullptr) {
367 ConstString changed_name(
"gdb_objc_trampolines_changed");
368 const Symbol *changed_symbol =
371 if (changed_symbol !=
nullptr) {
373 if (!changed_symbol_addr.
IsValid())
381 if (trampolines_changed_bp_sp) {
385 trampolines_changed_bp_sp->SetBreakpointKind(
386 "objc-trampolines-changed");
408 const ABI *abi = process->
GetABI().get();
439 if (region_addr != 0)
456 llvm::Expected<lldb::addr_t> region_addr =
459 llvm::consumeError(region_addr.takeError());
478 while (next_region != 0) {
490 next_region =
m_regions.back().GetNextRegionAddr();
498 region_collection::iterator pos, end =
m_regions.end();
499 for (pos =
m_regions.begin(); pos != end; pos++) {
500 if ((*pos).AddressInRegion(addr, flags))
509 {
"objc_msgSend",
false,
false,
false,
true},
510 {
"objc_msgSend_stret",
true,
false,
false},
511 {
"objc_msgSend_fpret",
false,
false,
false},
512 {
"objc_msgSend_fp2ret",
false,
false,
true},
513 {
"objc_msgSendSuper",
false,
true,
false,
true},
514 {
"objc_msgSendSuper_stret",
true,
true,
false},
515 {
"objc_msgSendSuper2",
false,
true,
true,
true},
516 {
"objc_msgSendSuper2_stret",
true,
true,
true},
532 "objc_allocWithZone",
534 "objc_opt_isKindOfClass",
536 "objc_opt_respondsToSelector",
551 ConstString get_impl_name(
"class_getMethodImplementation");
552 ConstString get_impl_stret_name(
"class_getMethodImplementation_stret");
554 ConstString msg_forward_stret_name(
"_objc_msgForward_stret");
556 Target *target = process_sp ? &process_sp->GetTarget() :
nullptr;
557 const Symbol *class_getMethodImplementation =
560 const Symbol *class_getMethodImplementation_stret =
565 const Symbol *msg_forward_stret =
569 if (class_getMethodImplementation)
573 if (class_getMethodImplementation_stret)
579 if (msg_forward_stret)
589 if (process_sp->CanJIT()) {
590 process_sp->GetTarget().GetDebugger().GetAsyncErrorStream()->Format(
591 "Could not find implementation lookup function \"{0}\" step in "
592 "through ObjC method dispatch will not work.\n",
628 const Symbol *msgSend_symbol =
nullptr;
632 if (msgSend_symbol) {
647 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
654 const Symbol *msgSend_symbol =
675 ThreadSP thread_sp(thread.shared_from_this());
693 if (!utility_fn_or_error) {
695 log, utility_fn_or_error.takeError(),
696 "Failed to get Utility Function for implementation lookup: {0}.");
701 LLDB_LOGF(log,
"No method lookup implementation code.");
707 thread.GetProcess()->GetTarget());
715 impl_function_caller =
m_impl_code->MakeFunctionCaller(
716 clang_void_ptr_type, dispatch_values, thread_sp,
error);
719 "Error getting function caller for dispatch lookup: \"%s\".",
724 impl_function_caller =
m_impl_code->GetFunctionCaller();
736 exe_ctx, args_addr, dispatch_values, diagnostics)) {
738 LLDB_LOGF(log,
"Error writing function arguments.");
739 diagnostics.
Dump(log);
749 MsgsendMap::iterator pos;
768 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
784 Target &target = thread.GetProcess()->GetTarget();
785 llvm::StringRef sym_name;
798 if (!sym_name.empty() && (sym_name.consume_front(
"objc_msgSend$")
799 || sym_name.consume_front(
"objc_msgSendClass$"))) {
800 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
819 this_dispatch = &vtable_dispatch;
835 const ABI *abi =
nullptr;
836 ProcessSP process_sp(thread.CalculateProcess());
838 abi = process_sp->GetABI().get();
842 TargetSP target_sp(thread.CalculateTarget());
850 Value void_ptr_value;
868 argument_values.
PushValue(void_ptr_value);
869 argument_values.
PushValue(void_ptr_value);
870 argument_values.
PushValue(void_ptr_value);
874 argument_values.
PushValue(void_ptr_value);
875 argument_values.
PushValue(void_ptr_value);
884 if (obj_addr == 0x0) {
887 "Asked to step to dispatch to nil object, returning empty plan.");
916 super_value.
GetScalar() += process_sp->GetAddressByteSize();
923 super_value.
GetScalar() += process_sp->GetAddressByteSize();
928 LLDB_LOGF(log,
"Failed to extract the super class value from the "
929 "class in objc_super.");
932 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
942 super_value.
GetScalar() += process_sp->GetAddressByteSize();
948 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
971 LLDB_LOGF(log,
"Failed to extract the isa value from object.");
982 assert(objc_runtime !=
nullptr);
987 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
996 LLDB_LOGF(log,
"Found implementation address in cache: 0x%" PRIx64,
999 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1031 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1064 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1065 thread, *
this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1081 if (!this_dispatch && !ret_plan_sp) {
1082 MsgsendMap::iterator pos;
1085 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
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
AppleObjCVTables * m_owner
lldb::addr_t m_code_end_addr
lldb::addr_t m_next_region
std::vector< VTableDescriptor > m_descriptors
lldb::addr_t m_code_start_addr
bool AddressInRegion(lldb::addr_t addr, uint32_t &flags)
lldb::addr_t m_header_addr
lldb::ProcessSP GetProcessSP()
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)
region_collection m_regions
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.
A uniqued constant string class.
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)
virtual ObjCISA GetPointerISA(ObjCISA isa)
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
lldb::SymbolType GetType() const
Address GetAddress() const
Symbol * ResolveReExportedSymbol(Target &target, const lldb::ModuleSP &containing_module_sp=lldb::ModuleSP()) const
Find the symbol this re-exported symbol resolves to.
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
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)
const ModuleList & GetImages() const
Get accessor for the images for this process.
void PushValue(const Value &value)
Value * GetValueAtIndex(size_t idx)
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
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