LLDB mainline
AppleObjCTrampolineHandler.cpp
Go to the documentation of this file.
1//===-- AppleObjCTrampolineHandler.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/Value.h"
21#include "lldb/Symbol/Symbol.h"
22#include "lldb/Target/ABI.h"
24#include "lldb/Target/Process.h"
26#include "lldb/Target/Target.h"
27#include "lldb/Target/Thread.h"
32#include "lldb/Utility/Log.h"
33
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/ScopeExit.h"
36
38
39#include <memory>
40
41using namespace lldb;
42using namespace lldb_private;
43
45 "__lldb_objc_find_implementation_for_selector";
46const char *AppleObjCTrampolineHandler::
47 g_lookup_implementation_with_stret_function_code =
48 R"(
49 if (is_stret) {
50 return_struct.impl_addr =
51 class_getMethodImplementation_stret (return_struct.class_addr,
52 return_struct.sel_addr);
53 } else {
54 return_struct.impl_addr =
55 class_getMethodImplementation (return_struct.class_addr,
56 return_struct.sel_addr);
57 }
58 if (debug)
59 printf ("\n*** Returning implementation: %p.\n",
60 return_struct.impl_addr);
61
62 return return_struct.impl_addr;
63}
64)";
65const char *
67 R"(
68 return_struct.impl_addr =
69 class_getMethodImplementation (return_struct.class_addr,
70 return_struct.sel_addr);
71 if (debug)
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);
74
75 return return_struct.impl_addr;
76}
77)";
78
79const char
81 R"(
82extern "C"
83{
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, ...);
89}
90extern "C" void *
91__lldb_objc_find_implementation_for_selector (void *object,
92 void *sel,
93 int is_str_ptr,
94 int is_stret,
95 int is_super,
96 int is_super2,
97 int debug)
98{
99 struct __lldb_imp_return_struct {
100 void *class_addr;
101 void *sel_addr;
102 void *impl_addr;
103 };
104
105 struct __lldb_objc_class {
106 void *isa;
107 void *super_ptr;
108 };
109 struct __lldb_objc_super {
110 void *receiver;
111 struct __lldb_objc_class *class_ptr;
112 };
113 struct __lldb_msg_ref {
114 void *dont_know;
115 void *sel;
116 };
117
118 struct __lldb_imp_return_struct return_struct;
119
120 if (debug)
121 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
122 "is_stret: %d is_super: %d, "
123 "is_super2: %d\n",
124 object, sel, is_str_ptr, is_stret,
125 is_super, is_super2);
126
127 if (is_str_ptr) {
128 if (debug)
129 printf("*** Turning string: '%s'", sel);
130 sel = sel_getUid((char *)sel);
131 if (debug)
132 printf("*** into sel to %p", sel);
133 }
134 if (is_super) {
135 if (is_super2) {
136 return_struct.class_addr
137 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
138 } else {
139 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
140 }
141#if defined(__arm64e__)
142 return_struct.class_addr =
143 __builtin_ptrauth_strip(return_struct.class_addr, /*ptrauth_key_asda*/ 2);
144#endif
145 if (debug)
146 printf("*** Super, class addr: %p\n", return_struct.class_addr);
147 } else {
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);
157 if (debug) {
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);
161 } else {
162 printf ("[object class] returned: %p object_getClass: %p.\n",
163 class_ptr, return_struct.class_addr);
164 }
165 }
166 }
167
168 return_struct.sel_addr = sel;
169
170)";
171
177
179
181 // The header looks like:
182 //
183 // uint16_t headerSize
184 // uint16_t descSize
185 // uint32_t descCount
186 // void * next
187 //
188 // First read in the header:
189
190 char memory_buffer[16];
191 ProcessSP process_sp = m_owner->GetProcessSP();
192 if (!process_sp)
193 return;
194 DataExtractor data(memory_buffer, sizeof(memory_buffer),
195 process_sp->GetByteOrder(),
196 process_sp->GetAddressByteSize());
197 size_t actual_size = 8 + process_sp->GetAddressByteSize();
199 size_t bytes_read =
200 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
201 if (bytes_read != actual_size) {
202 m_valid = false;
203 return;
204 }
205
206 lldb::offset_t offset = 0;
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);
210
211 m_next_region = data.GetAddress(&offset);
212
213 // If the header size is 0, that means we've come in too early before this
214 // data is set up.
215 // Set ourselves as not valid, and continue.
216 if (header_size == 0 || num_descriptors == 0) {
217 m_valid = false;
218 return;
219 }
220
221 // Now read in all the descriptors:
222 // The descriptor looks like:
223 //
224 // uint32_t offset
225 // uint32_t flags
226 //
227 // Where offset is either 0 - in which case it is unused, or it is
228 // the offset of the vtable code from the beginning of the
229 // descriptor record. Below, we'll convert that into an absolute
230 // code address, since I don't want to have to compute it over and
231 // over.
232
233 // Ingest the whole descriptor array:
234 const lldb::addr_t desc_ptr = m_header_addr + header_size;
235 const size_t desc_array_size = num_descriptors * descriptor_size;
236 WritableDataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
237 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
238
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) {
243 m_valid = false;
244 return;
245 }
246
247 // The actual code for the vtables will be laid out consecutively, so I also
248 // compute the start and end of the whole code block.
249
250 offset = 0;
252 m_code_end_addr = 0;
253
254 for (size_t i = 0; i < num_descriptors; i++) {
255 lldb::addr_t start_offset = offset;
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;
259 m_descriptors.push_back(VTableDescriptor(flags, code_addr));
260
261 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
262 m_code_start_addr = code_addr;
263 if (code_addr > m_code_end_addr)
264 m_code_end_addr = code_addr;
265
266 offset = start_offset + descriptor_size;
267 }
268 // Finally, a little bird told me that all the vtable code blocks
269 // are the same size. Let's compute the blocks and if they are all
270 // the same add the size to the code end address:
271 lldb::addr_t code_size = 0;
272 bool all_the_same = true;
273 for (size_t i = 0; i < num_descriptors - 1; i++) {
274 lldb::addr_t this_size =
275 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
276 if (code_size == 0)
277 code_size = this_size;
278 else {
279 if (this_size != code_size)
280 all_the_same = false;
281 if (this_size > code_size)
282 code_size = this_size;
283 }
284 }
285 if (all_the_same)
286 m_code_end_addr += code_size;
287}
288
290 AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
291 if (!IsValid())
292 return false;
293
294 if (addr < m_code_start_addr || addr > m_code_end_addr)
295 return false;
296
297 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
298 for (pos = m_descriptors.begin(); pos != end; pos++) {
299 if (addr <= (*pos).code_start) {
300 flags = (*pos).flags;
301 return true;
302 }
303 }
304 return false;
305}
306
308 Stream &s) {
309 s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
310 " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
312 size_t num_elements = m_descriptors.size();
313 for (size_t i = 0; i < num_elements; i++) {
314 s.Indent();
315 s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
316 m_descriptors[i].code_start, m_descriptors[i].flags);
317 }
318}
319
328
330 ProcessSP process_sp = GetProcessSP();
331 if (process_sp) {
333 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
334 }
335}
336
339 return true;
340
341 ProcessSP process_sp = GetProcessSP();
342 if (process_sp) {
343 Target &target = process_sp->GetTarget();
344
345 if (!m_objc_module_sp) {
346 for (ModuleSP module_sp : target.GetImages().Modules()) {
347 if (ObjCLanguageRuntime::Get(*process_sp)
348 ->IsModuleObjCLibrary(module_sp)) {
349 m_objc_module_sp = module_sp;
350 break;
351 }
352 }
353 }
354
355 if (m_objc_module_sp) {
356 ConstString trampoline_name("gdb_objc_trampolines");
357 const Symbol *trampoline_symbol =
358 m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
360 if (trampoline_symbol != nullptr) {
361 m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
363 return false;
364
365 // Next look up the "changed" symbol and set a breakpoint on that...
366 ConstString changed_name("gdb_objc_trampolines_changed");
367 const Symbol *changed_symbol =
368 m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
370 if (changed_symbol != nullptr) {
371 const Address changed_symbol_addr = changed_symbol->GetAddress();
372 if (!changed_symbol_addr.IsValid())
373 return false;
374
375 lldb::addr_t changed_addr =
376 changed_symbol_addr.GetOpcodeLoadAddress(&target);
377 if (changed_addr != LLDB_INVALID_ADDRESS) {
378 BreakpointSP trampolines_changed_bp_sp =
379 target.CreateBreakpoint(changed_addr, true, false);
380 if (trampolines_changed_bp_sp) {
381 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
382 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
383 true);
384 trampolines_changed_bp_sp->SetBreakpointKind(
385 "objc-trampolines-changed");
386 return true;
387 }
388 }
389 }
390 }
391 }
392 }
393 return false;
394}
395
397 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
398 lldb::user_id_t break_loc_id) {
399 AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
400 if (vtable_handler->InitializeVTableSymbols()) {
401 // The Update function is called with the address of an added region. So we
402 // grab that address, and
403 // feed it into ReadRegions. Of course, our friend the ABI will get the
404 // values for us.
405 ExecutionContext exe_ctx(context->exe_ctx_ref);
406 Process *process = exe_ctx.GetProcessPtr();
407 const ABI *abi = process->GetABI().get();
408
409 TypeSystemClangSP scratch_ts_sp =
411 if (!scratch_ts_sp)
412 return false;
413
414 ValueList argument_values;
415 Value input_value;
416 CompilerType clang_void_ptr_type =
417 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
418
420 // input_value.SetContext (Value::eContextTypeClangType,
421 // clang_void_ptr_type);
422 input_value.SetCompilerType(clang_void_ptr_type);
423 argument_values.PushValue(input_value);
424
425 bool success =
426 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
427 if (!success)
428 return false;
429
430 // Now get a pointer value from the zeroth argument.
432 DataExtractor data;
433 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
434 nullptr);
435 lldb::offset_t offset = 0;
436 lldb::addr_t region_addr = data.GetAddress(&offset);
437
438 if (region_addr != 0)
439 vtable_handler->ReadRegions(region_addr);
440 }
441 return false;
442}
443
445 // The no argument version reads the start region from the value of
446 // the gdb_regions_header, and gets started from there.
447
448 m_regions.clear();
450 return false;
452 ProcessSP process_sp = GetProcessSP();
453 if (process_sp) {
454 lldb::addr_t region_addr =
455 process_sp->ReadPointerFromMemory(m_trampoline_header, error);
456 if (error.Success())
457 return ReadRegions(region_addr);
458 }
459 return false;
460}
461
463 lldb::addr_t region_addr) {
464 ProcessSP process_sp = GetProcessSP();
465 if (!process_sp)
466 return false;
467
468 Log *log = GetLog(LLDBLog::Step);
469
470 // We aren't starting at the trampoline symbol.
472 lldb::addr_t next_region = region_addr;
473
474 // Read in the sizes of the headers.
475 while (next_region != 0) {
476 m_regions.push_back(VTableRegion(this, next_region));
477 if (!m_regions.back().IsValid()) {
478 m_regions.clear();
479 return false;
480 }
481 if (log) {
482 StreamString s;
483 m_regions.back().Dump(s);
484 LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());
485 }
486
487 next_region = m_regions.back().GetNextRegionAddr();
488 }
489
490 return true;
491}
492
494 lldb::addr_t addr, uint32_t &flags) {
495 region_collection::iterator pos, end = m_regions.end();
496 for (pos = m_regions.begin(); pos != end; pos++) {
497 if ((*pos).AddressInRegion(addr, flags))
498 return true;
499 }
500 return false;
501}
502
505 // NAME STRET SUPER SUPER2 ReExp
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},
514};
515
516// This is the table of ObjC "accelerated dispatch" functions. They are a set
517// of objc methods that are "seldom overridden" and so the compiler replaces the
518// objc_msgSend with a call to one of the dispatch functions. That will check
519// whether the method has been overridden, and directly call the Foundation
520// implementation if not.
521// This table is supposed to be complete. If ones get added in the future, we
522// will have to add them to the table.
524 "objc_alloc",
525 "objc_autorelease",
526 "objc_release",
527 "objc_retain",
528 "objc_alloc_init",
529 "objc_allocWithZone",
530 "objc_opt_class",
531 "objc_opt_isKindOfClass",
532 "objc_opt_new",
533 "objc_opt_respondsToSelector",
534 "objc_opt_self",
535};
536
538 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
539 : m_process_wp(), m_objc_module_sp(objc_module_sp),
544 if (process_sp)
545 m_process_wp = process_sp;
546 // Look up the known resolution functions:
547
548 ConstString get_impl_name("class_getMethodImplementation");
549 ConstString get_impl_stret_name("class_getMethodImplementation_stret");
550 ConstString msg_forward_name("_objc_msgForward");
551 ConstString msg_forward_stret_name("_objc_msgForward_stret");
552
553 Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
554 const Symbol *class_getMethodImplementation =
555 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
557 const Symbol *class_getMethodImplementation_stret =
558 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
560 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
561 msg_forward_name, eSymbolTypeCode);
562 const Symbol *msg_forward_stret =
563 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
565
566 if (class_getMethodImplementation)
568 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
569 target);
570 if (class_getMethodImplementation_stret)
572 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
573 target);
574 if (msg_forward)
575 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
576 if (msg_forward_stret)
578 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
579
580 // FIXME: Do some kind of logging here.
582 // If we can't even find the ordinary get method implementation function,
583 // then we aren't going to be able to
584 // step through any method dispatches. Warn to that effect and get out of
585 // here.
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",
590 get_impl_name);
591 }
592 return;
593 }
594
595 // We will either set the implementation to the _stret or non_stret version,
596 // so either way it's safe to start filling the m_lookup_..._code here.
599
601 // It there is no stret return lookup function, assume that it is the same
602 // as the straight lookup:
604 // Also we will use the version of the lookup code that doesn't rely on the
605 // stret version of the function.
608 } else {
611 }
612
613 // Look up the addresses for the objc dispatch functions and cache
614 // them. For now I'm inspecting the symbol names dynamically to
615 // figure out how to dispatch to them. If it becomes more
616 // complicated than this we can turn the g_dispatch_functions char *
617 // array into a template table, and populate the DispatchFunction
618 // map from there.
619
620 for (size_t i = 0; i != std::size(g_dispatch_functions); i++) {
621 const AppleObjCTrampolineHandler::DispatchFunction &dispatch_function =
623 ConstString name_const_str(dispatch_function.name);
624 // If this might be a re-exported symbol look there first.
625 const Symbol *msgSend_symbol = nullptr;
626 if (dispatch_function.might_be_reexport) {
627 msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(
628 name_const_str, eSymbolTypeReExported);
629 if (msgSend_symbol) {
630 while (msgSend_symbol->GetType() == eSymbolTypeReExported) {
631 msgSend_symbol = msgSend_symbol->ResolveReExportedSymbol(*target);
632 if (!msgSend_symbol)
633 break;
634 }
635 }
636 }
637 if (!msgSend_symbol)
638 msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(
639 name_const_str, eSymbolTypeCode);
640
641 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
642 lldb::addr_t sym_addr =
643 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
644 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
645 }
646 }
647
648 // Similarly, cache the addresses of the "optimized dispatch" function.
649 for (size_t i = 0; i != std::size(g_opt_dispatch_names); i++) {
650 ConstString name_const_str(g_opt_dispatch_names[i]);
651 const Symbol *msgSend_symbol =
652 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
654 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
655 lldb::addr_t sym_addr =
656 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
657
658 m_opt_dispatch_map.emplace(sym_addr, i);
659 }
660 }
661
662 // Build our vtable dispatch handler here:
664 std::make_unique<AppleObjCVTables>(process_sp, m_objc_module_sp);
665 if (m_vtables_up)
666 m_vtables_up->ReadRegions();
667}
668
671 ValueList &dispatch_values) {
672 ThreadSP thread_sp(thread.shared_from_this());
673 ExecutionContext exe_ctx(thread_sp);
674 Log *log = GetLog(LLDBLog::Step);
675
677 FunctionCaller *impl_function_caller = nullptr;
678
679 // Scope for mutex locker:
680 {
681 std::lock_guard<std::mutex> guard(m_impl_function_mutex);
682
683 // First stage is to make the ClangUtility to hold our injected function:
684
685 if (!m_impl_code) {
687 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
690 if (!utility_fn_or_error) {
692 log, utility_fn_or_error.takeError(),
693 "Failed to get Utility Function for implementation lookup: {0}.");
694 return args_addr;
695 }
696 m_impl_code = std::move(*utility_fn_or_error);
697 } else {
698 LLDB_LOGF(log, "No method lookup implementation code.");
700 }
701
702 // Next make the runner function for our implementation utility function.
704 thread.GetProcess()->GetTarget());
705 if (!scratch_ts_sp)
707
708 CompilerType clang_void_ptr_type =
709 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
711
712 impl_function_caller = m_impl_code->MakeFunctionCaller(
713 clang_void_ptr_type, dispatch_values, thread_sp, error);
714 if (error.Fail()) {
715 LLDB_LOGF(log,
716 "Error getting function caller for dispatch lookup: \"%s\".",
717 error.AsCString());
718 return args_addr;
719 }
720 } else {
721 impl_function_caller = m_impl_code->GetFunctionCaller();
722 }
723 }
724
725 // Now write down the argument values for this particular call.
726 // This looks like it might be a race condition if other threads
727 // were calling into here, but actually it isn't because we allocate
728 // a new args structure for this call by passing args_addr =
729 // LLDB_INVALID_ADDRESS...
730
731 DiagnosticManager diagnostics;
732 if (!impl_function_caller->WriteFunctionArguments(
733 exe_ctx, args_addr, dispatch_values, diagnostics)) {
734 if (log) {
735 LLDB_LOGF(log, "Error writing function arguments.");
736 diagnostics.Dump(log);
737 }
738 return args_addr;
739 }
740
741 return args_addr;
742}
743
746 MsgsendMap::iterator pos;
747 pos = m_msgSend_map.find(addr);
748 if (pos != m_msgSend_map.end()) {
749 return &g_dispatch_functions[(*pos).second];
750 }
751 return nullptr;
752}
753
755 std::function<void(lldb::addr_t, const DispatchFunction &)> callback) {
756 for (auto elem : m_msgSend_map) {
757 callback(elem.first, g_dispatch_functions[elem.second]);
758 }
759}
760
763 bool stop_others) {
764 ThreadPlanSP ret_plan_sp;
765 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
766
767 DispatchFunction vtable_dispatch = {"vtable", false, false, false};
768 // The selector specific stubs are a wrapper for objc_msgSend. They don't get
769 // passed a SEL, but instead the selector string is encoded in the stub
770 // name, in the form:
771 // objc_msgSend$SelectorName
772 // and the stub figures out the uniqued selector. If we find ourselves in
773 // one of these stubs, we strip off the selector string and pass that to the
774 // implementation finder function, which looks up the SEL (you have to do this
775 // in process) and passes that to the runtime lookup function.
776
777 // First step is to see if we're in a selector-specific dispatch stub.
778 // Those are of the form _objc_msgSend$<SELECTOR>, so see if the current
779 // function has that name:
780 Address func_addr;
781 Target &target = thread.GetProcess()->GetTarget();
782 llvm::StringRef sym_name;
783 const DispatchFunction *this_dispatch = nullptr;
784
785 if (target.ResolveLoadAddress(curr_pc, func_addr)) {
786 const Symbol *curr_sym = func_addr.CalculateSymbolContextSymbol();
787 if (curr_sym)
788 sym_name = curr_sym->GetName().GetStringRef();
789 }
790
791 // objc has introduced new accelerated dispatch stubs which figure out the
792 // selector and in some cases the object in one way or another, then call
793 // objc_msgSend. If we're in one of those stubs, we can use "step through
794 // direct dispatch" plan to get to the actual dispatch.
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>(
798 thread, *this);
799 return ret_plan_sp;
800 }
801
802 // Second step is to look and see if we are in one of the known ObjC
803 // dispatch functions. We've already compiled a table of same, so
804 // consult it.
805
806 this_dispatch = FindDispatchFunction(curr_pc);
807
808 // Next check to see if we are in a vtable region:
809
810 if (!this_dispatch && m_vtables_up) {
811 uint32_t flags;
812 if (m_vtables_up->IsAddressInVTables(curr_pc, flags)) {
813 vtable_dispatch.stret_return =
816 this_dispatch = &vtable_dispatch;
817 }
818 }
819
820 // Since we set this_dispatch in both the vtable & sel specific stub cases
821 // this if will be used for all three of those cases.
822 if (this_dispatch) {
823 Log *log = GetLog(LLDBLog::Step);
824
825 // We are decoding a method dispatch. First job is to pull the
826 // arguments out. If we are in a regular stub, we get self & selector,
827 // but if we are in a selector-specific stub, we'll have to get that from
828 // the string sym_name.
829
830 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
831
832 const ABI *abi = nullptr;
833 ProcessSP process_sp(thread.CalculateProcess());
834 if (process_sp)
835 abi = process_sp->GetABI().get();
836 if (abi == nullptr)
837 return ret_plan_sp;
838
839 TargetSP target_sp(thread.CalculateTarget());
840
841 TypeSystemClangSP scratch_ts_sp =
843 if (!scratch_ts_sp)
844 return ret_plan_sp;
845
846 ValueList argument_values;
847 Value void_ptr_value;
848 CompilerType clang_void_ptr_type =
849 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
851 // void_ptr_value.SetContext (Value::eContextTypeClangType,
852 // clang_void_ptr_type);
853 void_ptr_value.SetCompilerType(clang_void_ptr_type);
854
855 int obj_index;
856 int sel_index;
857
858 // If this is a struct return dispatch, then the first argument is
859 // the return struct pointer, and the object is the second, and
860 // the selector is the third.
861 // Otherwise the object is the first and the selector the second.
862 if (this_dispatch->stret_return) {
863 obj_index = 1;
864 sel_index = 2;
865 argument_values.PushValue(void_ptr_value);
866 argument_values.PushValue(void_ptr_value);
867 argument_values.PushValue(void_ptr_value);
868 } else {
869 obj_index = 0;
870 sel_index = 1;
871 argument_values.PushValue(void_ptr_value);
872 argument_values.PushValue(void_ptr_value);
873 }
874
875 bool success = abi->GetArgumentValues(thread, argument_values);
876 if (!success)
877 return ret_plan_sp;
878
879 lldb::addr_t obj_addr =
880 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
881 if (obj_addr == 0x0) {
882 LLDB_LOGF(
883 log,
884 "Asked to step to dispatch to nil object, returning empty plan.");
885 return ret_plan_sp;
886 }
887
888 ExecutionContext exe_ctx(thread.shared_from_this());
889 // isa_addr will store the class pointer that the method is being
890 // dispatched to - so either the class directly or the super class
891 // if this is one of the objc_msgSendSuper flavors. That's mostly
892 // used to look up the class/selector pair in our cache.
893
896 // Get the sel address from the arguments.
897 sel_addr =
898 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
899
900 // Figure out the class this is being dispatched to and see if
901 // we've already cached this method call, If so we can push a
902 // run-to-address plan directly. Otherwise we have to figure out
903 // where the implementation lives.
904
905 if (this_dispatch->is_super) {
906 if (this_dispatch->is_super2) {
907 // In the objc_msgSendSuper2 case, we don't get the object
908 // directly, we get a structure containing the object and the
909 // class to which the super message is being sent. So we need
910 // to dig the super out of the class and use that.
911
912 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
913 super_value.GetScalar() += process_sp->GetAddressByteSize();
914 super_value.ResolveValue(&exe_ctx);
915
916 if (super_value.GetScalar().IsValid()) {
917
918 // isa_value now holds the class pointer. The second word of the
919 // class pointer is the super-class pointer:
920 super_value.GetScalar() += process_sp->GetAddressByteSize();
921 super_value.ResolveValue(&exe_ctx);
922 if (super_value.GetScalar().IsValid())
923 isa_addr = super_value.GetScalar().ULongLong();
924 else {
925 LLDB_LOGF(log, "Failed to extract the super class value from the "
926 "class in objc_super.");
927 }
928 } else {
929 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
930 }
931 } else {
932 // In the objc_msgSendSuper case, we don't get the object
933 // directly, we get a two element structure containing the
934 // object and the super class to which the super message is
935 // being sent. So the class we want is the second element of
936 // this structure.
937
938 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
939 super_value.GetScalar() += process_sp->GetAddressByteSize();
940 super_value.ResolveValue(&exe_ctx);
941
942 if (super_value.GetScalar().IsValid()) {
943 isa_addr = super_value.GetScalar().ULongLong();
944 } else {
945 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
946 }
947 }
948 } else {
949 // In the direct dispatch case, the object->isa is the class pointer we
950 // want.
951
952 // This is a little cheesy, but since object->isa is the first field,
953 // making the object value a load address value and resolving it will get
954 // the pointer sized data pointed to by that value...
955
956 // Note, it isn't a fatal error not to be able to get the
957 // address from the object, since this might be a "tagged
958 // pointer" which isn't a real object, but rather some word
959 // length encoded dingus.
960
961 Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
962
964 isa_value.ResolveValue(&exe_ctx);
965 if (isa_value.GetScalar().IsValid()) {
966 isa_addr = isa_value.GetScalar().ULongLong();
967 } else {
968 LLDB_LOGF(log, "Failed to extract the isa value from object.");
969 }
970 }
971
972 // Okay, we've got the address of the class for which we're resolving this,
973 // let's see if it's in our cache:
975 // If this is a regular dispatch, look up the sel in our addr to sel cache:
976 if (isa_addr != LLDB_INVALID_ADDRESS) {
977 ObjCLanguageRuntime *objc_runtime =
978 ObjCLanguageRuntime::Get(*thread.GetProcess());
979 assert(objc_runtime != nullptr);
980 LLDB_LOG(log, "Resolving call for class - {0} and selector - {1}",
981 isa_addr, sel_addr);
982 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
983 }
984 // If it is a selector-specific stub dispatch, look in the string cache:
985
986 if (impl_addr != LLDB_INVALID_ADDRESS) {
987 // Yup, it was in the cache, so we can run to that address directly.
988
989 LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,
990 impl_addr);
991
992 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
993 stop_others);
994 } else {
995 // We haven't seen this class/selector pair yet. Look it up.
996 StreamString errors;
997 Address impl_code_address;
998
999 ValueList dispatch_values;
1000
1001 // We've will inject a little function in the target that takes the
1002 // object, selector/selector string and some flags,
1003 // and figures out the implementation. Looks like:
1004 // void *__lldb_objc_find_implementation_for_selector (void *object,
1005 // void *sel,
1006 // int
1007 // is_str_ptr,
1008 // int is_stret,
1009 // int is_super,
1010 // int is_super2,
1011 // int debug)
1012 // If we don't have an actual SEL, but rather a string version of the
1013 // selector WE injected, set is_str_ptr to true, and sel to the address
1014 // of the string.
1015 // So set up the arguments for that call.
1016
1017 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1018 lldb::addr_t sel_str_addr = LLDB_INVALID_ADDRESS;
1019 // Push the selector from arguments.
1020 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1021
1022 Value flag_value;
1023 CompilerType clang_int_type =
1024 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1027 flag_value.SetCompilerType(clang_int_type);
1028
1029 // We are passing in a sel addr now a string pointer in all cases for now.
1030 flag_value.GetScalar() = 0;
1031 dispatch_values.PushValue(flag_value);
1032
1033 if (this_dispatch->stret_return)
1034 flag_value.GetScalar() = 1;
1035 else
1036 flag_value.GetScalar() = 0;
1037 dispatch_values.PushValue(flag_value);
1038
1039 if (this_dispatch->is_super)
1040 flag_value.GetScalar() = 1;
1041 else
1042 flag_value.GetScalar() = 0;
1043 dispatch_values.PushValue(flag_value);
1044
1045 if (this_dispatch->is_super2)
1046 flag_value.GetScalar() = 1;
1047 else
1048 flag_value.GetScalar() = 0;
1049 dispatch_values.PushValue(flag_value);
1050
1051 if (log && log->GetVerbose())
1052 flag_value.GetScalar() = 1;
1053 else
1054 flag_value.GetScalar() = 0;
1055 dispatch_values.PushValue(flag_value);
1056
1057 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1058 thread, *this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1059 sym_name);
1060 if (log) {
1061 StreamString s;
1062 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1063 LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());
1064 }
1065 }
1066 }
1067
1068 // Next, check if we have hit an "optimized dispatch" function. This will
1069 // either directly call the base implementation or dispatch an objc_msgSend
1070 // if the method has been overridden. So we just do a "step in/step out",
1071 // setting a breakpoint on objc_msgSend, and if we hit the msgSend, we
1072 // will automatically step in again. That's the job of the
1073 // AppleThreadPlanStepThroughDirectDispatch.
1074 if (!this_dispatch && !ret_plan_sp) {
1075 MsgsendMap::iterator pos;
1076 pos = m_opt_dispatch_map.find(curr_pc);
1077 if (pos != m_opt_dispatch_map.end()) {
1078 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1079 thread, *this);
1080 }
1081 }
1082
1083 return ret_plan_sp;
1084}
1085
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
virtual bool GetArgumentValues(Thread &thread, ValueList &values) const =0
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition Address.cpp:358
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
Symbol * CalculateSymbolContextSymbol() const
Definition Address.cpp:887
static bool RefreshTrampolines(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
AppleObjCVTables(const lldb::ProcessSP &process_sp, const lldb::ModuleSP &objc_module_sp)
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 ...
static const DispatchFunction g_dispatch_functions[]
lldb::addr_t SetupDispatchFunction(Thread &thread, ValueList &dispatch_values)
std::unique_ptr< AppleObjCVTables > m_vtables_up
std::unique_ptr< UtilityFunction > m_impl_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)
Generic representation of a type in a programming language.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
A subclass of DataBuffer that stores a data buffer on the heap.
An data extractor class.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
uint64_t GetAddress(lldb::offset_t *offset_ptr) const
Extract an address from *offset_ptr.
uint16_t GetU16(lldb::offset_t *offset_ptr) const
Extract a uint16_t value from *offset_ptr.
"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.
bool GetVerbose() const
Definition Log.cpp:300
ModuleIterable Modules() const
Definition ModuleList.h:570
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.
Definition Process.h:357
const lldb::ABISP & GetABI()
Definition Process.cpp:1483
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1256
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:365
bool IsValid() const
Definition Scalar.h:111
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.
An error handling class.
Definition Status.h:118
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
const char * GetData() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
lldb::addr_t GetLoadAddress(Target *target) const
Definition Symbol.cpp:504
bool ValueIsAddress() const
Definition Symbol.cpp:165
Address & GetAddressRef()
Definition Symbol.h:73
ConstString GetName() const
Definition Symbol.cpp:511
lldb::SymbolType GetType() const
Definition Symbol.h:169
Address GetAddress() const
Definition Symbol.h:89
Symbol * ResolveReExportedSymbol(Target &target) const
Definition Symbol.cpp:483
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3449
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.
Definition Target.cpp:2826
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)
Definition Target.cpp:504
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1241
void PushValue(const Value &value)
Definition Value.cpp:694
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:698
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:113
Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, Module *module)
Definition Value.cpp:323
@ LoadAddress
A load address value.
Definition Value.h:49
@ Scalar
A raw scalar value.
Definition Value.h:45
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:589
void SetValueType(ValueType value_type)
Definition Value.h:89
#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.
Definition Log.h:327
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
@ eDescriptionLevelFull
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:85
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
@ eSymbolTypeReExported
@ eEncodingSint
signed integer
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP