35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/ScopeExit.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,
102 struct __lldb_imp_return_struct {
108 struct __lldb_objc_class {
112 struct __lldb_objc_super {
114 struct __lldb_objc_class *class_ptr;
116 struct __lldb_msg_ref {
121 struct __lldb_imp_return_struct return_struct;
124 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
125 "is_stret: %d is_super: %d, "
126 "is_super2: %d, is_fixup: %d, is_fixed: %d\n",
127 object, sel, is_str_ptr, is_stret,
128 is_super, is_super2, is_fixup, is_fixed);
132 printf("*** Turning string: '%s'", sel);
133 sel = sel_getUid((char *)sel);
135 printf("*** into sel to %p", sel);
139 return_struct.class_addr
140 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
142 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
145 printf("*** Super, class addr: %p\n", return_struct.class_addr);
147 // This code seems a little funny, but has its reasons...
148 // The call to [object class] is here because if this is a class, and has
149 // not been called into yet, we need to do something to force the class to
150 // initialize itself.
151 // Then the call to object_getClass will actually return the correct class,
152 // either the class if object is a class instance, or the meta-class if it
153 // is a class pointer.
154 void *class_ptr = (void *) [(id) object class];
155 return_struct.class_addr = (id) object_getClass((id) object);
157 if (class_ptr == object) {
158 printf ("Found a class object, need to return the meta class %p -> %p\n",
159 class_ptr, return_struct.class_addr);
161 printf ("[object class] returned: %p object_getClass: %p.\n",
162 class_ptr, return_struct.class_addr);
169 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;
171 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;
172 return_struct.sel_addr = sel_getUid (sel_name);
174 printf ("\n*** Got fixed up selector: %p for name %s.\n",
175 return_struct.sel_addr, sel_name);
178 return_struct.sel_addr = sel;
184 : m_valid(true), m_owner(owner), m_header_addr(header_addr) {
200 char memory_buffer[16];
201 ProcessSP process_sp = m_owner->GetProcessSP();
205 process_sp->GetByteOrder(),
206 process_sp->GetAddressByteSize());
207 size_t actual_size = 8 + process_sp->GetAddressByteSize();
210 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size,
error);
211 if (bytes_read != actual_size) {
219 const size_t num_descriptors = data.
GetU32(&offset);
226 if (header_size == 0 || num_descriptors == 0) {
244 const lldb::addr_t desc_ptr = m_header_addr + header_size;
245 const size_t desc_array_size = num_descriptors * descriptor_size;
246 WritableDataBufferSP data_sp(
new DataBufferHeap(desc_array_size,
'\0'));
247 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
249 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
250 process_sp->GetAddressByteSize());
251 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size,
error);
252 if (bytes_read != desc_array_size) {
261 m_code_start_addr = 0;
264 for (
size_t i = 0; i < num_descriptors; i++) {
268 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
271 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
272 m_code_start_addr = code_addr;
273 if (code_addr > m_code_end_addr)
274 m_code_end_addr = code_addr;
276 offset = start_offset + descriptor_size;
282 bool all_the_same =
true;
283 for (
size_t i = 0; i < num_descriptors - 1; i++) {
285 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
287 code_size = this_size;
289 if (this_size != code_size)
290 all_the_same =
false;
291 if (this_size > code_size)
292 code_size = this_size;
296 m_code_end_addr += code_size;
304 if (addr < m_code_start_addr || addr > m_code_end_addr)
307 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
308 for (pos = m_descriptors.begin(); pos != end; pos++) {
309 if (addr <= (*pos).code_start) {
310 flags = (*pos).flags;
319 s.
Printf(
"Header addr: 0x%" PRIx64
" Code start: 0x%" PRIx64
320 " Code End: 0x%" PRIx64
" Next: 0x%" PRIx64
"\n",
321 m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
322 size_t num_elements = m_descriptors.size();
323 for (
size_t i = 0; i < num_elements; i++) {
325 s.
Printf(
"Code start: 0x%" PRIx64
" Flags: %d\n",
326 m_descriptors[i].code_start, m_descriptors[i].flags);
331 const ProcessSP &process_sp,
const ModuleSP &objc_module_sp)
340 ProcessSP process_sp = GetProcessSP();
343 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
351 ProcessSP process_sp = GetProcessSP();
353 Target &target = process_sp->GetTarget();
358 ->IsModuleObjCLibrary(module_sp)) {
366 ConstString trampoline_name(
"gdb_objc_trampolines");
367 const Symbol *trampoline_symbol =
370 if (trampoline_symbol !=
nullptr) {
376 ConstString changed_name(
"gdb_objc_trampolines_changed");
377 const Symbol *changed_symbol =
380 if (changed_symbol !=
nullptr) {
382 if (!changed_symbol_addr.
IsValid())
388 BreakpointSP trampolines_changed_bp_sp =
390 if (trampolines_changed_bp_sp) {
391 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
392 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines,
this,
394 trampolines_changed_bp_sp->SetBreakpointKind(
395 "objc-trampolines-changed");
417 const ABI *abi = process->
GetABI().get();
419 TypeSystemClangSP scratch_ts_sp =
448 if (region_addr != 0)
459 if (!InitializeVTableSymbols())
462 ProcessSP process_sp = GetProcessSP();
465 process_sp->ReadPointerFromMemory(m_trampoline_header,
error);
467 return ReadRegions(region_addr);
474 ProcessSP process_sp = GetProcessSP();
481 InitializeVTableSymbols();
485 while (next_region != 0) {
487 if (!m_regions.back().IsValid()) {
493 m_regions.back().Dump(s);
497 next_region = m_regions.back().GetNextRegionAddr();
505 region_collection::iterator pos, end = m_regions.end();
506 for (pos = m_regions.begin(); pos != end; pos++) {
507 if ((*pos).AddressInRegion(addr, flags))
517 {
"objc_msgSend_fixup",
false,
false,
false,
519 {
"objc_msgSend_fixedup",
false,
false,
false,
521 {
"objc_msgSend_stret",
true,
false,
false,
523 {
"objc_msgSend_stret_fixup",
true,
false,
false,
525 {
"objc_msgSend_stret_fixedup",
true,
false,
false,
527 {
"objc_msgSend_fpret",
false,
false,
false,
529 {
"objc_msgSend_fpret_fixup",
false,
false,
false,
531 {
"objc_msgSend_fpret_fixedup",
false,
false,
false,
533 {
"objc_msgSend_fp2ret",
false,
false,
true,
535 {
"objc_msgSend_fp2ret_fixup",
false,
false,
true,
537 {
"objc_msgSend_fp2ret_fixedup",
false,
false,
true,
540 {
"objc_msgSendSuper_stret",
true,
true,
false,
543 {
"objc_msgSendSuper2_fixup",
false,
true,
true,
545 {
"objc_msgSendSuper2_fixedup",
false,
true,
true,
547 {
"objc_msgSendSuper2_stret",
true,
true,
true,
549 {
"objc_msgSendSuper2_stret_fixup",
true,
true,
true,
551 {
"objc_msgSendSuper2_stret_fixedup",
true,
true,
true,
568 "objc_allocWithZone",
570 "objc_opt_isKindOfClass",
572 "objc_opt_respondsToSelector",
577 const ProcessSP &process_sp,
const ModuleSP &objc_module_sp)
587 ConstString get_impl_name(
"class_getMethodImplementation");
588 ConstString get_impl_stret_name(
"class_getMethodImplementation_stret");
590 ConstString msg_forward_stret_name(
"_objc_msgForward_stret");
592 Target *target = process_sp ? &process_sp->GetTarget() :
nullptr;
593 const Symbol *class_getMethodImplementation =
596 const Symbol *class_getMethodImplementation_stret =
601 const Symbol *msg_forward_stret =
605 if (class_getMethodImplementation)
609 if (class_getMethodImplementation_stret)
615 if (msg_forward_stret)
625 if (process_sp->CanJIT()) {
626 process_sp->GetTarget().GetDebugger().GetErrorStream().Printf(
627 "Could not find implementation lookup function \"%s\""
628 " step in through ObjC method dispatch will not work.\n",
661 const Symbol *msgSend_symbol =
674 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
681 const Symbol *msgSend_symbol =
702 ThreadSP thread_sp(thread.shared_from_this());
720 if (!utility_fn_or_error) {
722 log, utility_fn_or_error.takeError(),
723 "Failed to get Utility Function for implementation lookup: {0}.");
728 LLDB_LOGF(log,
"No method lookup implementation code.");
742 impl_function_caller =
m_impl_code->MakeFunctionCaller(
743 clang_void_ptr_type, dispatch_values, thread_sp,
error);
746 "Error getting function caller for dispatch lookup: \"%s\".",
751 impl_function_caller =
m_impl_code->GetFunctionCaller();
763 exe_ctx, args_addr, dispatch_values, diagnostics)) {
765 LLDB_LOGF(log,
"Error writing function arguments.");
766 diagnostics.
Dump(log);
776 MsgsendMap::iterator pos;
794 ThreadPlanSP ret_plan_sp;
815 llvm::StringRef sym_name;
823 if (!sym_name.empty() && !sym_name.consume_front(
"objc_msgSend$"))
826 this_dispatch = &sel_stub_dispatch;
828 bool in_selector_stub = !sym_name.empty();
833 if (!in_selector_stub)
844 this_dispatch = &vtable_dispatch;
860 const ABI *abi =
nullptr;
863 abi = process_sp->GetABI().get();
869 TypeSystemClangSP scratch_ts_sp =
875 Value void_ptr_value;
892 if (in_selector_stub) {
895 argument_values.
PushValue(void_ptr_value);
899 argument_values.
PushValue(void_ptr_value);
900 argument_values.
PushValue(void_ptr_value);
901 argument_values.
PushValue(void_ptr_value);
905 argument_values.
PushValue(void_ptr_value);
906 argument_values.
PushValue(void_ptr_value);
915 if (obj_addr == 0x0) {
918 "Asked to step to dispatch to nil object, returning empty plan.");
931 if (!in_selector_stub)
948 super_value.
GetScalar() += process_sp->GetAddressByteSize();
955 super_value.
GetScalar() += process_sp->GetAddressByteSize();
960 LLDB_LOGF(log,
"Failed to extract the super class value from the "
961 "class in objc_super.");
964 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
974 super_value.
GetScalar() += process_sp->GetAddressByteSize();
980 LLDB_LOGF(log,
"Failed to extract the class value from objc_super.");
1003 LLDB_LOGF(log,
"Failed to extract the isa value from object.");
1014 assert(objc_runtime !=
nullptr);
1015 if (!in_selector_stub) {
1016 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
1017 isa_addr, sel_addr);
1020 LLDB_LOG(log,
"Resolving call for class - {0} and selector - {1}",
1021 isa_addr, sym_name);
1030 LLDB_LOGF(log,
"Found implementation address in cache: 0x%" PRIx64,
1033 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1062 if (!in_selector_stub) {
1070 sel_str_addr = process_sp->AllocateMemory(
1071 sym_name.size() + 1, ePermissionsReadable | ePermissionsWritable,
1075 "Could not allocate memory for selector string {0}: {1}",
1079 process_sp->WriteMemory(sel_str_addr, sym_name.str().c_str(),
1080 sym_name.size() + 1,
error);
1082 LLDB_LOG(log,
"Could not write string to address {0}", sel_str_addr);
1085 Value sel_ptr_value(void_ptr_value);
1086 sel_ptr_value.
GetScalar() = sel_str_addr;
1087 dispatch_values.
PushValue(sel_ptr_value);
1092 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1098 if (in_selector_stub)
1122 switch (this_dispatch->
fixedup) {
1147 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1148 thread, *
this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1164 if (!this_dispatch && !ret_plan_sp) {
1165 MsgsendMap::iterator pos;
1169 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1170 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)
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.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eEncodingSint
signed integer