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,
99 struct __lldb_imp_return_struct {
105 struct __lldb_objc_class {
109 struct __lldb_objc_super {
111 struct __lldb_objc_class *class_ptr;
113 struct __lldb_msg_ref {
118 struct __lldb_imp_return_struct return_struct;
121 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
122 "is_stret: %d is_super: %d, "
124 object, sel, is_str_ptr, is_stret,
125 is_super, is_super2);
129 printf("*** Turning string: '%s'", sel);
130 sel = sel_getUid((char *)sel);
132 printf("*** into sel to %p", sel);
136 return_struct.class_addr
137 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
139 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
141#if defined(__arm64e__)
142 return_struct.class_addr =
143 __builtin_ptrauth_strip(return_struct.class_addr, /*ptrauth_key_asda*/ 2);
146 printf("*** Super, class addr: %p\n", return_struct.class_addr);
148 // This code seems a little funny, but has its reasons...
149 // The call to [object class] is here because if this is a class, and has
150 // not been called into yet, we need to do something to force the class to
151 // initialize itself.
152 // Then the call to object_getClass will actually return the correct class,
153 // either the class if object is a class instance, or the meta-class if it
154 // is a class pointer.
155 void *class_ptr = (void *) [(id) object class];
156 return_struct.class_addr = (id) object_getClass((id) object);
158 if (class_ptr == object) {
159 printf ("Found a class object, need to return the meta class %p -> %p\n",
160 class_ptr, return_struct.class_addr);
162 printf ("[object class] returned: %p object_getClass: %p.\n",
163 class_ptr, return_struct.class_addr);
168 return_struct.sel_addr = sel;
190 char memory_buffer[16];
195 process_sp->GetByteOrder(),
196 process_sp->GetAddressByteSize());
197 size_t actual_size = 8 + process_sp->GetAddressByteSize();
201 if (bytes_read != actual_size) {
207 const uint16_t header_size = data.
GetU16(&offset);
208 const uint16_t descriptor_size = data.
GetU16(&offset);
209 const size_t num_descriptors = data.
GetU32(&offset);
216 if (header_size == 0 || num_descriptors == 0) {
235 const size_t desc_array_size = num_descriptors * descriptor_size;
237 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
239 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
240 process_sp->GetAddressByteSize());
241 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size,
error);
242 if (bytes_read != desc_array_size) {
254 for (
size_t i = 0; i < num_descriptors; i++) {
256 uint32_t voffset = desc_extractor.
GetU32(&offset);
257 uint32_t flags = desc_extractor.
GetU32(&offset);
258 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
266 offset = start_offset + descriptor_size;
272 bool all_the_same =
true;
273 for (
size_t i = 0; i < num_descriptors - 1; i++) {
277 code_size = this_size;
279 if (this_size != code_size)
280 all_the_same =
false;
281 if (this_size > code_size)
282 code_size = this_size;
297 std::vector<VTableDescriptor>::iterator pos, end =
m_descriptors.end();
299 if (addr <= (*pos).code_start) {
300 flags = (*pos).flags;
309 s.
Printf(
"Header addr: 0x%" PRIx64
" Code start: 0x%" PRIx64
310 " Code End: 0x%" PRIx64
" Next: 0x%" PRIx64
"\n",
313 for (
size_t i = 0; i < num_elements; i++) {
315 s.
Printf(
"Code start: 0x%" PRIx64
" Flags: %d\n",
343 Target &target = process_sp->GetTarget();
348 ->IsModuleObjCLibrary(module_sp)) {
356 ConstString trampoline_name(
"gdb_objc_trampolines");
357 const Symbol *trampoline_symbol =
360 if (trampoline_symbol !=
nullptr) {
366 ConstString changed_name(
"gdb_objc_trampolines_changed");
367 const Symbol *changed_symbol =
370 if (changed_symbol !=
nullptr) {
372 if (!changed_symbol_addr.
IsValid())
380 if (trampolines_changed_bp_sp) {
384 trampolines_changed_bp_sp->SetBreakpointKind(
385 "objc-trampolines-changed");
407 const ABI *abi = process->
GetABI().get();
438 if (region_addr != 0)
475 while (next_region != 0) {
487 next_region =
m_regions.back().GetNextRegionAddr();
495 region_collection::iterator pos, end =
m_regions.end();
496 for (pos =
m_regions.begin(); pos != end; pos++) {
497 if ((*pos).AddressInRegion(addr, flags))
506 {
"objc_msgSend",
false,
false,
false,
true},
507 {
"objc_msgSend_stret",
true,
false,
false},
508 {
"objc_msgSend_fpret",
false,
false,
false},
509 {
"objc_msgSend_fp2ret",
false,
false,
true},
510 {
"objc_msgSendSuper",
false,
true,
false,
true},
511 {
"objc_msgSendSuper_stret",
true,
true,
false},
512 {
"objc_msgSendSuper2",
false,
true,
true,
true},
513 {
"objc_msgSendSuper2_stret",
true,
true,
true},
529 "objc_allocWithZone",
531 "objc_opt_isKindOfClass",
533 "objc_opt_respondsToSelector",
548 ConstString get_impl_name(
"class_getMethodImplementation");
549 ConstString get_impl_stret_name(
"class_getMethodImplementation_stret");
551 ConstString msg_forward_stret_name(
"_objc_msgForward_stret");
553 Target *target = process_sp ? &process_sp->GetTarget() :
nullptr;
554 const Symbol *class_getMethodImplementation =
557 const Symbol *class_getMethodImplementation_stret =
562 const Symbol *msg_forward_stret =
566 if (class_getMethodImplementation)
570 if (class_getMethodImplementation_stret)
576 if (msg_forward_stret)
586 if (process_sp->CanJIT()) {
587 process_sp->GetTarget().GetDebugger().GetAsyncErrorStream()->Format(
588 "Could not find implementation lookup function \"{0}\" step in "
589 "through ObjC method dispatch will not work.\n",
625 const Symbol *msgSend_symbol =
nullptr;
629 if (msgSend_symbol) {
644 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
651 const Symbol *msgSend_symbol =
672 ThreadSP thread_sp(thread.shared_from_this());
690 if (!utility_fn_or_error) {
692 log, utility_fn_or_error.takeError(),
693 "Failed to get Utility Function for implementation lookup: {0}.");
698 LLDB_LOGF(log,
"No method lookup implementation code.");
704 thread.GetProcess()->GetTarget());
712 impl_function_caller =
m_impl_code->MakeFunctionCaller(
713 clang_void_ptr_type, dispatch_values, thread_sp,
error);
716 "Error getting function caller for dispatch lookup: \"%s\".",
721 impl_function_caller =
m_impl_code->GetFunctionCaller();
733 exe_ctx, args_addr, dispatch_values, diagnostics)) {
735 LLDB_LOGF(log,
"Error writing function arguments.");
736 diagnostics.
Dump(log);
746 MsgsendMap::iterator pos;
765 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
781 Target &target = thread.GetProcess()->GetTarget();
782 llvm::StringRef sym_name;
795 if (!sym_name.empty() && (sym_name.consume_front(
"objc_msgSend$")
796 || sym_name.consume_front(
"objc_msgSendClass$"))) {
797 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
816 this_dispatch = &vtable_dispatch;
832 const ABI *abi =
nullptr;
833 ProcessSP process_sp(thread.CalculateProcess());
835 abi = process_sp->GetABI().get();
839 TargetSP target_sp(thread.CalculateTarget());
847 Value void_ptr_value;
865 argument_values.
PushValue(void_ptr_value);
866 argument_values.
PushValue(void_ptr_value);
867 argument_values.
PushValue(void_ptr_value);
871 argument_values.
PushValue(void_ptr_value);
872 argument_values.
PushValue(void_ptr_value);
881 if (obj_addr == 0x0) {
884 "Asked to step to dispatch to nil object, returning empty plan.");
913 super_value.
GetScalar() += process_sp->GetAddressByteSize();
920 super_value.
GetScalar() += process_sp->GetAddressByteSize();
925 LLDB_LOGF(log,
"Failed to extract the super class value from the "
926 "class in objc_super.");
929 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
939 super_value.
GetScalar() += process_sp->GetAddressByteSize();
945 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
968 LLDB_LOGF(log,
"Failed to extract the isa value from object.");
979 assert(objc_runtime !=
nullptr);
980 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
989 LLDB_LOGF(log,
"Found implementation address in cache: 0x%" PRIx64,
992 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1024 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1057 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1058 thread, *
this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1074 if (!this_dispatch && !ret_plan_sp) {
1075 MsgsendMap::iterator pos;
1078 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)
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
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