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 is_fixup,
98 int is_fixed,
99 int debug)
100{
101 struct __lldb_imp_return_struct {
102 void *class_addr;
103 void *sel_addr;
104 void *impl_addr;
105 };
106
107 struct __lldb_objc_class {
108 void *isa;
109 void *super_ptr;
110 };
111 struct __lldb_objc_super {
112 void *receiver;
113 struct __lldb_objc_class *class_ptr;
114 };
115 struct __lldb_msg_ref {
116 void *dont_know;
117 void *sel;
118 };
119
120 struct __lldb_imp_return_struct return_struct;
121
122 if (debug)
123 printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "
124 "is_stret: %d is_super: %d, "
125 "is_super2: %d, is_fixup: %d, is_fixed: %d\n",
126 object, sel, is_str_ptr, is_stret,
127 is_super, is_super2, is_fixup, is_fixed);
128
129 if (is_str_ptr) {
130 if (debug)
131 printf("*** Turning string: '%s'", sel);
132 sel = sel_getUid((char *)sel);
133 if (debug)
134 printf("*** into sel to %p", sel);
135 }
136 if (is_super) {
137 if (is_super2) {
138 return_struct.class_addr
139 = ((__lldb_objc_super *) object)->class_ptr->super_ptr;
140 } else {
141 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;
142 }
143#if defined(__arm64e__)
144 return_struct.class_addr =
145 __builtin_ptrauth_strip(return_struct.class_addr, /*ptrauth_key_asda*/ 2);
146#endif
147 if (debug)
148 printf("*** Super, class addr: %p\n", return_struct.class_addr);
149 } else {
150 // This code seems a little funny, but has its reasons...
151 // The call to [object class] is here because if this is a class, and has
152 // not been called into yet, we need to do something to force the class to
153 // initialize itself.
154 // Then the call to object_getClass will actually return the correct class,
155 // either the class if object is a class instance, or the meta-class if it
156 // is a class pointer.
157 void *class_ptr = (void *) [(id) object class];
158 return_struct.class_addr = (id) object_getClass((id) object);
159 if (debug) {
160 if (class_ptr == object) {
161 printf ("Found a class object, need to return the meta class %p -> %p\n",
162 class_ptr, return_struct.class_addr);
163 } else {
164 printf ("[object class] returned: %p object_getClass: %p.\n",
165 class_ptr, return_struct.class_addr);
166 }
167 }
168 }
169
170 if (is_fixup) {
171 if (is_fixed) {
172 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;
173 } else {
174 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;
175 return_struct.sel_addr = sel_getUid (sel_name);
176 if (debug)
177 printf ("\n*** Got fixed up selector: %p for name %s.\n",
178 return_struct.sel_addr, sel_name);
179 }
180 } else {
181 return_struct.sel_addr = sel;
182 }
183)";
184
190
192
194 // The header looks like:
195 //
196 // uint16_t headerSize
197 // uint16_t descSize
198 // uint32_t descCount
199 // void * next
200 //
201 // First read in the header:
202
203 char memory_buffer[16];
204 ProcessSP process_sp = m_owner->GetProcessSP();
205 if (!process_sp)
206 return;
207 DataExtractor data(memory_buffer, sizeof(memory_buffer),
208 process_sp->GetByteOrder(),
209 process_sp->GetAddressByteSize());
210 size_t actual_size = 8 + process_sp->GetAddressByteSize();
212 size_t bytes_read =
213 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
214 if (bytes_read != actual_size) {
215 m_valid = false;
216 return;
217 }
218
219 lldb::offset_t offset = 0;
220 const uint16_t header_size = data.GetU16(&offset);
221 const uint16_t descriptor_size = data.GetU16(&offset);
222 const size_t num_descriptors = data.GetU32(&offset);
223
224 m_next_region = data.GetAddress(&offset);
225
226 // If the header size is 0, that means we've come in too early before this
227 // data is set up.
228 // Set ourselves as not valid, and continue.
229 if (header_size == 0 || num_descriptors == 0) {
230 m_valid = false;
231 return;
232 }
233
234 // Now read in all the descriptors:
235 // The descriptor looks like:
236 //
237 // uint32_t offset
238 // uint32_t flags
239 //
240 // Where offset is either 0 - in which case it is unused, or it is
241 // the offset of the vtable code from the beginning of the
242 // descriptor record. Below, we'll convert that into an absolute
243 // code address, since I don't want to have to compute it over and
244 // over.
245
246 // Ingest the whole descriptor array:
247 const lldb::addr_t desc_ptr = m_header_addr + header_size;
248 const size_t desc_array_size = num_descriptors * descriptor_size;
249 WritableDataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
250 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
251
252 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
253 process_sp->GetAddressByteSize());
254 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);
255 if (bytes_read != desc_array_size) {
256 m_valid = false;
257 return;
258 }
259
260 // The actual code for the vtables will be laid out consecutively, so I also
261 // compute the start and end of the whole code block.
262
263 offset = 0;
265 m_code_end_addr = 0;
266
267 for (size_t i = 0; i < num_descriptors; i++) {
268 lldb::addr_t start_offset = offset;
269 uint32_t voffset = desc_extractor.GetU32(&offset);
270 uint32_t flags = desc_extractor.GetU32(&offset);
271 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
272 m_descriptors.push_back(VTableDescriptor(flags, code_addr));
273
274 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
275 m_code_start_addr = code_addr;
276 if (code_addr > m_code_end_addr)
277 m_code_end_addr = code_addr;
278
279 offset = start_offset + descriptor_size;
280 }
281 // Finally, a little bird told me that all the vtable code blocks
282 // are the same size. Let's compute the blocks and if they are all
283 // the same add the size to the code end address:
284 lldb::addr_t code_size = 0;
285 bool all_the_same = true;
286 for (size_t i = 0; i < num_descriptors - 1; i++) {
287 lldb::addr_t this_size =
288 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
289 if (code_size == 0)
290 code_size = this_size;
291 else {
292 if (this_size != code_size)
293 all_the_same = false;
294 if (this_size > code_size)
295 code_size = this_size;
296 }
297 }
298 if (all_the_same)
299 m_code_end_addr += code_size;
300}
301
303 AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
304 if (!IsValid())
305 return false;
306
307 if (addr < m_code_start_addr || addr > m_code_end_addr)
308 return false;
309
310 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
311 for (pos = m_descriptors.begin(); pos != end; pos++) {
312 if (addr <= (*pos).code_start) {
313 flags = (*pos).flags;
314 return true;
315 }
316 }
317 return false;
318}
319
321 Stream &s) {
322 s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
323 " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
325 size_t num_elements = m_descriptors.size();
326 for (size_t i = 0; i < num_elements; i++) {
327 s.Indent();
328 s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
329 m_descriptors[i].code_start, m_descriptors[i].flags);
330 }
331}
332
341
343 ProcessSP process_sp = GetProcessSP();
344 if (process_sp) {
346 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
347 }
348}
349
352 return true;
353
354 ProcessSP process_sp = GetProcessSP();
355 if (process_sp) {
356 Target &target = process_sp->GetTarget();
357
358 if (!m_objc_module_sp) {
359 for (ModuleSP module_sp : target.GetImages().Modules()) {
360 if (ObjCLanguageRuntime::Get(*process_sp)
361 ->IsModuleObjCLibrary(module_sp)) {
362 m_objc_module_sp = module_sp;
363 break;
364 }
365 }
366 }
367
368 if (m_objc_module_sp) {
369 ConstString trampoline_name("gdb_objc_trampolines");
370 const Symbol *trampoline_symbol =
371 m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
373 if (trampoline_symbol != nullptr) {
374 m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
376 return false;
377
378 // Next look up the "changed" symbol and set a breakpoint on that...
379 ConstString changed_name("gdb_objc_trampolines_changed");
380 const Symbol *changed_symbol =
381 m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
383 if (changed_symbol != nullptr) {
384 const Address changed_symbol_addr = changed_symbol->GetAddress();
385 if (!changed_symbol_addr.IsValid())
386 return false;
387
388 lldb::addr_t changed_addr =
389 changed_symbol_addr.GetOpcodeLoadAddress(&target);
390 if (changed_addr != LLDB_INVALID_ADDRESS) {
391 BreakpointSP trampolines_changed_bp_sp =
392 target.CreateBreakpoint(changed_addr, true, false);
393 if (trampolines_changed_bp_sp) {
394 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
395 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
396 true);
397 trampolines_changed_bp_sp->SetBreakpointKind(
398 "objc-trampolines-changed");
399 return true;
400 }
401 }
402 }
403 }
404 }
405 }
406 return false;
407}
408
410 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
411 lldb::user_id_t break_loc_id) {
412 AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
413 if (vtable_handler->InitializeVTableSymbols()) {
414 // The Update function is called with the address of an added region. So we
415 // grab that address, and
416 // feed it into ReadRegions. Of course, our friend the ABI will get the
417 // values for us.
418 ExecutionContext exe_ctx(context->exe_ctx_ref);
419 Process *process = exe_ctx.GetProcessPtr();
420 const ABI *abi = process->GetABI().get();
421
422 TypeSystemClangSP scratch_ts_sp =
424 if (!scratch_ts_sp)
425 return false;
426
427 ValueList argument_values;
428 Value input_value;
429 CompilerType clang_void_ptr_type =
430 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
431
433 // input_value.SetContext (Value::eContextTypeClangType,
434 // clang_void_ptr_type);
435 input_value.SetCompilerType(clang_void_ptr_type);
436 argument_values.PushValue(input_value);
437
438 bool success =
439 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
440 if (!success)
441 return false;
442
443 // Now get a pointer value from the zeroth argument.
445 DataExtractor data;
446 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
447 nullptr);
448 lldb::offset_t offset = 0;
449 lldb::addr_t region_addr = data.GetAddress(&offset);
450
451 if (region_addr != 0)
452 vtable_handler->ReadRegions(region_addr);
453 }
454 return false;
455}
456
458 // The no argument version reads the start region from the value of
459 // the gdb_regions_header, and gets started from there.
460
461 m_regions.clear();
463 return false;
465 ProcessSP process_sp = GetProcessSP();
466 if (process_sp) {
467 lldb::addr_t region_addr =
468 process_sp->ReadPointerFromMemory(m_trampoline_header, error);
469 if (error.Success())
470 return ReadRegions(region_addr);
471 }
472 return false;
473}
474
476 lldb::addr_t region_addr) {
477 ProcessSP process_sp = GetProcessSP();
478 if (!process_sp)
479 return false;
480
481 Log *log = GetLog(LLDBLog::Step);
482
483 // We aren't starting at the trampoline symbol.
485 lldb::addr_t next_region = region_addr;
486
487 // Read in the sizes of the headers.
488 while (next_region != 0) {
489 m_regions.push_back(VTableRegion(this, next_region));
490 if (!m_regions.back().IsValid()) {
491 m_regions.clear();
492 return false;
493 }
494 if (log) {
495 StreamString s;
496 m_regions.back().Dump(s);
497 LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());
498 }
499
500 next_region = m_regions.back().GetNextRegionAddr();
501 }
502
503 return true;
504}
505
507 lldb::addr_t addr, uint32_t &flags) {
508 region_collection::iterator pos, end = m_regions.end();
509 for (pos = m_regions.begin(); pos != end; pos++) {
510 if ((*pos).AddressInRegion(addr, flags))
511 return true;
512 }
513 return false;
514}
515
518 // NAME STRET SUPER SUPER2 FIXUP TYPE
519 {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
520 {"objc_msgSend_fixup", false, false, false,
522 {"objc_msgSend_fixedup", false, false, false,
524 {"objc_msgSend_stret", true, false, false,
526 {"objc_msgSend_stret_fixup", true, false, false,
528 {"objc_msgSend_stret_fixedup", true, false, false,
530 {"objc_msgSend_fpret", false, false, false,
532 {"objc_msgSend_fpret_fixup", false, false, false,
534 {"objc_msgSend_fpret_fixedup", false, false, false,
536 {"objc_msgSend_fp2ret", false, false, true,
538 {"objc_msgSend_fp2ret_fixup", false, false, true,
540 {"objc_msgSend_fp2ret_fixedup", false, false, true,
542 {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
543 {"objc_msgSendSuper_stret", true, true, false,
545 {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
546 {"objc_msgSendSuper2_fixup", false, true, true,
548 {"objc_msgSendSuper2_fixedup", false, true, true,
550 {"objc_msgSendSuper2_stret", true, true, true,
552 {"objc_msgSendSuper2_stret_fixup", true, true, true,
554 {"objc_msgSendSuper2_stret_fixedup", true, true, true,
556};
557
558// This is the table of ObjC "accelerated dispatch" functions. They are a set
559// of objc methods that are "seldom overridden" and so the compiler replaces the
560// objc_msgSend with a call to one of the dispatch functions. That will check
561// whether the method has been overridden, and directly call the Foundation
562// implementation if not.
563// This table is supposed to be complete. If ones get added in the future, we
564// will have to add them to the table.
566 "objc_alloc",
567 "objc_autorelease",
568 "objc_release",
569 "objc_retain",
570 "objc_alloc_init",
571 "objc_allocWithZone",
572 "objc_opt_class",
573 "objc_opt_isKindOfClass",
574 "objc_opt_new",
575 "objc_opt_respondsToSelector",
576 "objc_opt_self",
577};
578
580 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
581 : m_process_wp(), m_objc_module_sp(objc_module_sp),
586 if (process_sp)
587 m_process_wp = process_sp;
588 // Look up the known resolution functions:
589
590 ConstString get_impl_name("class_getMethodImplementation");
591 ConstString get_impl_stret_name("class_getMethodImplementation_stret");
592 ConstString msg_forward_name("_objc_msgForward");
593 ConstString msg_forward_stret_name("_objc_msgForward_stret");
594
595 Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
596 const Symbol *class_getMethodImplementation =
597 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
599 const Symbol *class_getMethodImplementation_stret =
600 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
602 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
603 msg_forward_name, eSymbolTypeCode);
604 const Symbol *msg_forward_stret =
605 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
607
608 if (class_getMethodImplementation)
610 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
611 target);
612 if (class_getMethodImplementation_stret)
614 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
615 target);
616 if (msg_forward)
617 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
618 if (msg_forward_stret)
620 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
621
622 // FIXME: Do some kind of logging here.
624 // If we can't even find the ordinary get method implementation function,
625 // then we aren't going to be able to
626 // step through any method dispatches. Warn to that effect and get out of
627 // here.
628 if (process_sp->CanJIT()) {
629 process_sp->GetTarget().GetDebugger().GetAsyncErrorStream()->Format(
630 "Could not find implementation lookup function \"{0}\" step in "
631 "through ObjC method dispatch will not work.\n",
632 get_impl_name);
633 }
634 return;
635 }
636
637 // We will either set the implementation to the _stret or non_stret version,
638 // so either way it's safe to start filling the m_lookup_..._code here.
641
643 // It there is no stret return lookup function, assume that it is the same
644 // as the straight lookup:
646 // Also we will use the version of the lookup code that doesn't rely on the
647 // stret version of the function.
650 } else {
653 }
654
655 // Look up the addresses for the objc dispatch functions and cache
656 // them. For now I'm inspecting the symbol names dynamically to
657 // figure out how to dispatch to them. If it becomes more
658 // complicated than this we can turn the g_dispatch_functions char *
659 // array into a template table, and populate the DispatchFunction
660 // map from there.
661
662 for (size_t i = 0; i != std::size(g_dispatch_functions); i++) {
663 ConstString name_const_str(g_dispatch_functions[i].name);
664 const Symbol *msgSend_symbol =
665 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
667 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
668 // FIXME: Make g_dispatch_functions static table of
669 // DispatchFunctions, and have the map be address->index.
670 // Problem is we also need to lookup the dispatch function. For
671 // now we could have a side table of stret & non-stret dispatch
672 // functions. If that's as complex as it gets, we're fine.
673
674 lldb::addr_t sym_addr =
675 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
676
677 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
678 }
679 }
680
681 // Similarly, cache the addresses of the "optimized dispatch" function.
682 for (size_t i = 0; i != std::size(g_opt_dispatch_names); i++) {
683 ConstString name_const_str(g_opt_dispatch_names[i]);
684 const Symbol *msgSend_symbol =
685 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
687 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
688 lldb::addr_t sym_addr =
689 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
690
691 m_opt_dispatch_map.emplace(sym_addr, i);
692 }
693 }
694
695 // Build our vtable dispatch handler here:
697 std::make_unique<AppleObjCVTables>(process_sp, m_objc_module_sp);
698 if (m_vtables_up)
699 m_vtables_up->ReadRegions();
700}
701
704 ValueList &dispatch_values) {
705 ThreadSP thread_sp(thread.shared_from_this());
706 ExecutionContext exe_ctx(thread_sp);
707 Log *log = GetLog(LLDBLog::Step);
708
710 FunctionCaller *impl_function_caller = nullptr;
711
712 // Scope for mutex locker:
713 {
714 std::lock_guard<std::mutex> guard(m_impl_function_mutex);
715
716 // First stage is to make the ClangUtility to hold our injected function:
717
718 if (!m_impl_code) {
720 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
723 if (!utility_fn_or_error) {
725 log, utility_fn_or_error.takeError(),
726 "Failed to get Utility Function for implementation lookup: {0}.");
727 return args_addr;
728 }
729 m_impl_code = std::move(*utility_fn_or_error);
730 } else {
731 LLDB_LOGF(log, "No method lookup implementation code.");
733 }
734
735 // Next make the runner function for our implementation utility function.
737 thread.GetProcess()->GetTarget());
738 if (!scratch_ts_sp)
740
741 CompilerType clang_void_ptr_type =
742 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
744
745 impl_function_caller = m_impl_code->MakeFunctionCaller(
746 clang_void_ptr_type, dispatch_values, thread_sp, error);
747 if (error.Fail()) {
748 LLDB_LOGF(log,
749 "Error getting function caller for dispatch lookup: \"%s\".",
750 error.AsCString());
751 return args_addr;
752 }
753 } else {
754 impl_function_caller = m_impl_code->GetFunctionCaller();
755 }
756 }
757
758 // Now write down the argument values for this particular call.
759 // This looks like it might be a race condition if other threads
760 // were calling into here, but actually it isn't because we allocate
761 // a new args structure for this call by passing args_addr =
762 // LLDB_INVALID_ADDRESS...
763
764 DiagnosticManager diagnostics;
765 if (!impl_function_caller->WriteFunctionArguments(
766 exe_ctx, args_addr, dispatch_values, diagnostics)) {
767 if (log) {
768 LLDB_LOGF(log, "Error writing function arguments.");
769 diagnostics.Dump(log);
770 }
771 return args_addr;
772 }
773
774 return args_addr;
775}
776
779 MsgsendMap::iterator pos;
780 pos = m_msgSend_map.find(addr);
781 if (pos != m_msgSend_map.end()) {
782 return &g_dispatch_functions[(*pos).second];
783 }
784 return nullptr;
785}
786
788 std::function<void(lldb::addr_t, const DispatchFunction &)> callback) {
789 for (auto elem : m_msgSend_map) {
790 callback(elem.first, g_dispatch_functions[elem.second]);
791 }
792}
793
796 bool stop_others) {
797 ThreadPlanSP ret_plan_sp;
798 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
799
800 DispatchFunction vtable_dispatch = {"vtable", false, false, false,
802 // The selector specific stubs are a wrapper for objc_msgSend. They don't get
803 // passed a SEL, but instead the selector string is encoded in the stub
804 // name, in the form:
805 // objc_msgSend$SelectorName
806 // and the stub figures out the uniqued selector. If we find ourselves in
807 // one of these stubs, we strip off the selector string and pass that to the
808 // implementation finder function, which looks up the SEL (you have to do this
809 // in process) and passes that to the runtime lookup function.
810
811 // First step is to see if we're in a selector-specific dispatch stub.
812 // Those are of the form _objc_msgSend$<SELECTOR>, so see if the current
813 // function has that name:
814 Address func_addr;
815 Target &target = thread.GetProcess()->GetTarget();
816 llvm::StringRef sym_name;
817 const DispatchFunction *this_dispatch = nullptr;
818
819 if (target.ResolveLoadAddress(curr_pc, func_addr)) {
820 const Symbol *curr_sym = func_addr.CalculateSymbolContextSymbol();
821 if (curr_sym)
822 sym_name = curr_sym->GetName().GetStringRef();
823 }
824
825 // objc has introduced new accelerated dispatch stubs which figure out the
826 // selector and in some cases the object in one way or another, then call
827 // objc_msgSend. If we're in one of those stubs, we can use "step through
828 // direct dispatch" plan to get to the actual dispatch.
829 if (!sym_name.empty() && (sym_name.consume_front("objc_msgSend$")
830 || sym_name.consume_front("objc_msgSendClass$"))) {
831 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
832 thread, *this);
833 return ret_plan_sp;
834 }
835
836 // Second step is to look and see if we are in one of the known ObjC
837 // dispatch functions. We've already compiled a table of same, so
838 // consult it.
839
840 this_dispatch = FindDispatchFunction(curr_pc);
841
842 // Next check to see if we are in a vtable region:
843
844 if (!this_dispatch && m_vtables_up) {
845 uint32_t flags;
846 if (m_vtables_up->IsAddressInVTables(curr_pc, flags)) {
847 vtable_dispatch.stret_return =
850 this_dispatch = &vtable_dispatch;
851 }
852 }
853
854 // Since we set this_dispatch in both the vtable & sel specific stub cases
855 // this if will be used for all three of those cases.
856 if (this_dispatch) {
857 Log *log = GetLog(LLDBLog::Step);
858
859 // We are decoding a method dispatch. First job is to pull the
860 // arguments out. If we are in a regular stub, we get self & selector,
861 // but if we are in a selector-specific stub, we'll have to get that from
862 // the string sym_name.
863
864 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
865
866 const ABI *abi = nullptr;
867 ProcessSP process_sp(thread.CalculateProcess());
868 if (process_sp)
869 abi = process_sp->GetABI().get();
870 if (abi == nullptr)
871 return ret_plan_sp;
872
873 TargetSP target_sp(thread.CalculateTarget());
874
875 TypeSystemClangSP scratch_ts_sp =
877 if (!scratch_ts_sp)
878 return ret_plan_sp;
879
880 ValueList argument_values;
881 Value void_ptr_value;
882 CompilerType clang_void_ptr_type =
883 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
885 // void_ptr_value.SetContext (Value::eContextTypeClangType,
886 // clang_void_ptr_type);
887 void_ptr_value.SetCompilerType(clang_void_ptr_type);
888
889 int obj_index;
890 int sel_index;
891
892 // If this is a struct return dispatch, then the first argument is
893 // the return struct pointer, and the object is the second, and
894 // the selector is the third.
895 // Otherwise the object is the first and the selector the second.
896 if (this_dispatch->stret_return) {
897 obj_index = 1;
898 sel_index = 2;
899 argument_values.PushValue(void_ptr_value);
900 argument_values.PushValue(void_ptr_value);
901 argument_values.PushValue(void_ptr_value);
902 } else {
903 obj_index = 0;
904 sel_index = 1;
905 argument_values.PushValue(void_ptr_value);
906 argument_values.PushValue(void_ptr_value);
907 }
908
909 bool success = abi->GetArgumentValues(thread, argument_values);
910 if (!success)
911 return ret_plan_sp;
912
913 lldb::addr_t obj_addr =
914 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
915 if (obj_addr == 0x0) {
916 LLDB_LOGF(
917 log,
918 "Asked to step to dispatch to nil object, returning empty plan.");
919 return ret_plan_sp;
920 }
921
922 ExecutionContext exe_ctx(thread.shared_from_this());
923 // isa_addr will store the class pointer that the method is being
924 // dispatched to - so either the class directly or the super class
925 // if this is one of the objc_msgSendSuper flavors. That's mostly
926 // used to look up the class/selector pair in our cache.
927
930 // Get the sel address from the arguments.
931 sel_addr =
932 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
933
934 // Figure out the class this is being dispatched to and see if
935 // we've already cached this method call, If so we can push a
936 // run-to-address plan directly. Otherwise we have to figure out
937 // where the implementation lives.
938
939 if (this_dispatch->is_super) {
940 if (this_dispatch->is_super2) {
941 // In the objc_msgSendSuper2 case, we don't get the object
942 // directly, we get a structure containing the object and the
943 // class to which the super message is being sent. So we need
944 // to dig the super out of the class and use that.
945
946 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
947 super_value.GetScalar() += process_sp->GetAddressByteSize();
948 super_value.ResolveValue(&exe_ctx);
949
950 if (super_value.GetScalar().IsValid()) {
951
952 // isa_value now holds the class pointer. The second word of the
953 // class pointer is the super-class pointer:
954 super_value.GetScalar() += process_sp->GetAddressByteSize();
955 super_value.ResolveValue(&exe_ctx);
956 if (super_value.GetScalar().IsValid())
957 isa_addr = super_value.GetScalar().ULongLong();
958 else {
959 LLDB_LOGF(log, "Failed to extract the super class value from the "
960 "class in objc_super.");
961 }
962 } else {
963 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
964 }
965 } else {
966 // In the objc_msgSendSuper case, we don't get the object
967 // directly, we get a two element structure containing the
968 // object and the super class to which the super message is
969 // being sent. So the class we want is the second element of
970 // this structure.
971
972 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
973 super_value.GetScalar() += process_sp->GetAddressByteSize();
974 super_value.ResolveValue(&exe_ctx);
975
976 if (super_value.GetScalar().IsValid()) {
977 isa_addr = super_value.GetScalar().ULongLong();
978 } else {
979 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
980 }
981 }
982 } else {
983 // In the direct dispatch case, the object->isa is the class pointer we
984 // want.
985
986 // This is a little cheesy, but since object->isa is the first field,
987 // making the object value a load address value and resolving it will get
988 // the pointer sized data pointed to by that value...
989
990 // Note, it isn't a fatal error not to be able to get the
991 // address from the object, since this might be a "tagged
992 // pointer" which isn't a real object, but rather some word
993 // length encoded dingus.
994
995 Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
996
998 isa_value.ResolveValue(&exe_ctx);
999 if (isa_value.GetScalar().IsValid()) {
1000 isa_addr = isa_value.GetScalar().ULongLong();
1001 } else {
1002 LLDB_LOGF(log, "Failed to extract the isa value from object.");
1003 }
1004 }
1005
1006 // Okay, we've got the address of the class for which we're resolving this,
1007 // let's see if it's in our cache:
1009 // If this is a regular dispatch, look up the sel in our addr to sel cache:
1010 if (isa_addr != LLDB_INVALID_ADDRESS) {
1011 ObjCLanguageRuntime *objc_runtime =
1012 ObjCLanguageRuntime::Get(*thread.GetProcess());
1013 assert(objc_runtime != nullptr);
1014 LLDB_LOG(log, "Resolving call for class - {0} and selector - {1}",
1015 isa_addr, sel_addr);
1016 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1017 }
1018 // If it is a selector-specific stub dispatch, look in the string cache:
1019
1020 if (impl_addr != LLDB_INVALID_ADDRESS) {
1021 // Yup, it was in the cache, so we can run to that address directly.
1022
1023 LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,
1024 impl_addr);
1025
1026 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1027 stop_others);
1028 } else {
1029 // We haven't seen this class/selector pair yet. Look it up.
1030 StreamString errors;
1031 Address impl_code_address;
1032
1033 ValueList dispatch_values;
1034
1035 // We've will inject a little function in the target that takes the
1036 // object, selector/selector string and some flags,
1037 // and figures out the implementation. Looks like:
1038 // void *__lldb_objc_find_implementation_for_selector (void *object,
1039 // void *sel,
1040 // int
1041 // is_str_ptr,
1042 // int is_stret,
1043 // int is_super,
1044 // int is_super2,
1045 // int is_fixup,
1046 // int is_fixed,
1047 // int debug)
1048 // If we don't have an actual SEL, but rather a string version of the
1049 // selector WE injected, set is_str_ptr to true, and sel to the address
1050 // of the string.
1051 // So set up the arguments for that call.
1052
1053 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1054 lldb::addr_t sel_str_addr = LLDB_INVALID_ADDRESS;
1055 // Push the selector from arguments.
1056 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1057
1058 Value flag_value;
1059 CompilerType clang_int_type =
1060 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1063 flag_value.SetCompilerType(clang_int_type);
1064
1065 // We are passing in a sel addr now a string pointer in all cases for now.
1066 flag_value.GetScalar() = 0;
1067 dispatch_values.PushValue(flag_value);
1068
1069 if (this_dispatch->stret_return)
1070 flag_value.GetScalar() = 1;
1071 else
1072 flag_value.GetScalar() = 0;
1073 dispatch_values.PushValue(flag_value);
1074
1075 if (this_dispatch->is_super)
1076 flag_value.GetScalar() = 1;
1077 else
1078 flag_value.GetScalar() = 0;
1079 dispatch_values.PushValue(flag_value);
1080
1081 if (this_dispatch->is_super2)
1082 flag_value.GetScalar() = 1;
1083 else
1084 flag_value.GetScalar() = 0;
1085 dispatch_values.PushValue(flag_value);
1086
1087 switch (this_dispatch->fixedup) {
1089 flag_value.GetScalar() = 0;
1090 dispatch_values.PushValue(flag_value);
1091 dispatch_values.PushValue(flag_value);
1092 break;
1094 flag_value.GetScalar() = 1;
1095 dispatch_values.PushValue(flag_value);
1096 flag_value.GetScalar() = 1;
1097 dispatch_values.PushValue(flag_value);
1098 break;
1100 flag_value.GetScalar() = 1;
1101 dispatch_values.PushValue(flag_value);
1102 flag_value.GetScalar() = 0;
1103 dispatch_values.PushValue(flag_value);
1104 break;
1105 }
1106 if (log && log->GetVerbose())
1107 flag_value.GetScalar() = 1;
1108 else
1109 flag_value.GetScalar() = 0;
1110 dispatch_values.PushValue(flag_value);
1111
1112 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1113 thread, *this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1114 sym_name);
1115 if (log) {
1116 StreamString s;
1117 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1118 LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());
1119 }
1120 }
1121 }
1122
1123 // Next, check if we have hit an "optimized dispatch" function. This will
1124 // either directly call the base implementation or dispatch an objc_msgSend
1125 // if the method has been overridden. So we just do a "step in/step out",
1126 // setting a breakpoint on objc_msgSend, and if we hit the msgSend, we
1127 // will automatically step in again. That's the job of the
1128 // AppleThreadPlanStepThroughDirectDispatch.
1129 if (!this_dispatch && !ret_plan_sp) {
1130 MsgsendMap::iterator pos;
1131 pos = m_opt_dispatch_map.find(curr_pc);
1132 if (pos != m_opt_dispatch_map.end()) {
1133 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1134 thread, *this);
1135 }
1136 }
1137
1138 return ret_plan_sp;
1139}
1140
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:1482
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1255
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
Address GetAddress() const
Definition Symbol.h:89
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3448
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
@ 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