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