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 auto scratch_ts_or_err =
413 if (!scratch_ts_or_err) {
415 scratch_ts_or_err.takeError(),
416 "Couldn't get the scratch type system: {0}");
417 return false;
418 }
419 lldb::TypeSystemSP scratch_ts_sp = *scratch_ts_or_err;
420 if (!scratch_ts_sp)
421 return false;
422
423 ValueList argument_values;
424 Value input_value;
425 CompilerType clang_void_ptr_type =
426 scratch_ts_sp->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
427
429 // input_value.SetContext (Value::eContextTypeClangType,
430 // clang_void_ptr_type);
431 input_value.SetCompilerType(clang_void_ptr_type);
432 argument_values.PushValue(input_value);
433
434 bool success =
435 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
436 if (!success)
437 return false;
438
439 // Now get a pointer value from the zeroth argument.
441 DataExtractor data;
442 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
443 nullptr);
444 lldb::offset_t offset = 0;
445 lldb::addr_t region_addr = data.GetAddress(&offset);
446
447 if (region_addr != 0)
448 vtable_handler->ReadRegions(region_addr);
449 }
450 return false;
451}
452
454 // The no argument version reads the start region from the value of
455 // the gdb_regions_header, and gets started from there.
456
457 m_regions.clear();
459 return false;
460 ProcessSP process_sp = GetProcessSP();
461 if (!process_sp)
462 return false;
463
464 llvm::Expected<lldb::addr_t> region_addr =
465 process_sp->ReadPointerFromMemory(m_trampoline_header);
466 if (!region_addr) {
467 llvm::consumeError(region_addr.takeError());
468 return false;
469 }
470 return ReadRegions(*region_addr);
471}
472
474 lldb::addr_t region_addr) {
475 ProcessSP process_sp = GetProcessSP();
476 if (!process_sp)
477 return false;
478
479 Log *log = GetLog(LLDBLog::Step);
480
481 // We aren't starting at the trampoline symbol.
483 lldb::addr_t next_region = region_addr;
484
485 // Read in the sizes of the headers.
486 while (next_region != 0) {
487 m_regions.push_back(VTableRegion(this, next_region));
488 if (!m_regions.back().IsValid()) {
489 m_regions.clear();
490 return false;
491 }
492 if (log) {
493 StreamString s;
494 m_regions.back().Dump(s);
495 LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());
496 }
497
498 next_region = m_regions.back().GetNextRegionAddr();
499 }
500
501 return true;
502}
503
505 lldb::addr_t addr, uint32_t &flags) {
506 region_collection::iterator pos, end = m_regions.end();
507 for (pos = m_regions.begin(); pos != end; pos++) {
508 if ((*pos).AddressInRegion(addr, flags))
509 return true;
510 }
511 return false;
512}
513
516 // NAME STRET SUPER SUPER2 ReExp
517 {"objc_msgSend", false, false, false, true},
518 {"objc_msgSend_stret", true, false, false},
519 {"objc_msgSend_fpret", false, false, false},
520 {"objc_msgSend_fp2ret", false, false, true},
521 {"objc_msgSendSuper", false, true, false, true},
522 {"objc_msgSendSuper_stret", true, true, false},
523 {"objc_msgSendSuper2", false, true, true, true},
524 {"objc_msgSendSuper2_stret", true, true, true},
525};
526
527// This is the table of ObjC "accelerated dispatch" functions. They are a set
528// of objc methods that are "seldom overridden" and so the compiler replaces the
529// objc_msgSend with a call to one of the dispatch functions. That will check
530// whether the method has been overridden, and directly call the Foundation
531// implementation if not.
532// This table is supposed to be complete. If ones get added in the future, we
533// will have to add them to the table.
535 "objc_alloc",
536 "objc_autorelease",
537 "objc_release",
538 "objc_retain",
539 "objc_alloc_init",
540 "objc_allocWithZone",
541 "objc_opt_class",
542 "objc_opt_isKindOfClass",
543 "objc_opt_new",
544 "objc_opt_respondsToSelector",
545 "objc_opt_self",
546};
547
549 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
550 : m_process_wp(), m_objc_module_sp(objc_module_sp),
555 if (process_sp)
556 m_process_wp = process_sp;
557 // Look up the known resolution functions:
558
559 ConstString get_impl_name("class_getMethodImplementation");
560 ConstString get_impl_stret_name("class_getMethodImplementation_stret");
561 ConstString msg_forward_name("_objc_msgForward");
562 ConstString msg_forward_stret_name("_objc_msgForward_stret");
563
564 Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
565 const Symbol *class_getMethodImplementation =
566 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
568 const Symbol *class_getMethodImplementation_stret =
569 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
571 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
572 msg_forward_name, eSymbolTypeCode);
573 const Symbol *msg_forward_stret =
574 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
576
577 if (class_getMethodImplementation)
579 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
580 target);
581 if (class_getMethodImplementation_stret)
583 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
584 target);
585 if (msg_forward)
586 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
587 if (msg_forward_stret)
589 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
590
591 // FIXME: Do some kind of logging here.
593 // If we can't even find the ordinary get method implementation function,
594 // then we aren't going to be able to
595 // step through any method dispatches. Warn to that effect and get out of
596 // here.
597 if (process_sp->CanJIT()) {
598 process_sp->GetTarget().GetDebugger().GetAsyncErrorStream()->Format(
599 "Could not find implementation lookup function \"{0}\" step in "
600 "through ObjC method dispatch will not work.\n",
601 get_impl_name);
602 }
603 return;
604 }
605
606 // We will either set the implementation to the _stret or non_stret version,
607 // so either way it's safe to start filling the m_lookup_..._code here.
610
612 // It there is no stret return lookup function, assume that it is the same
613 // as the straight lookup:
615 // Also we will use the version of the lookup code that doesn't rely on the
616 // stret version of the function.
619 } else {
622 }
623
624 // Look up the addresses for the objc dispatch functions and cache
625 // them. For now I'm inspecting the symbol names dynamically to
626 // figure out how to dispatch to them. If it becomes more
627 // complicated than this we can turn the g_dispatch_functions char *
628 // array into a template table, and populate the DispatchFunction
629 // map from there.
630
631 for (size_t i = 0; i != std::size(g_dispatch_functions); i++) {
632 const AppleObjCTrampolineHandler::DispatchFunction &dispatch_function =
634 ConstString name_const_str(dispatch_function.name);
635 // If this might be a re-exported symbol look there first.
636 const Symbol *msgSend_symbol = nullptr;
637 if (dispatch_function.might_be_reexport) {
638 msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(
639 name_const_str, eSymbolTypeReExported);
640 if (msgSend_symbol) {
641 while (msgSend_symbol->GetType() == eSymbolTypeReExported) {
642 msgSend_symbol = msgSend_symbol->ResolveReExportedSymbol(*target);
643 if (!msgSend_symbol)
644 break;
645 }
646 }
647 }
648 if (!msgSend_symbol)
649 msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(
650 name_const_str, eSymbolTypeCode);
651
652 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
653 lldb::addr_t sym_addr =
654 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
655 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
656 }
657 }
658
659 // Similarly, cache the addresses of the "optimized dispatch" function.
660 for (size_t i = 0; i != std::size(g_opt_dispatch_names); i++) {
661 ConstString name_const_str(g_opt_dispatch_names[i]);
662 const Symbol *msgSend_symbol =
663 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
665 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
666 lldb::addr_t sym_addr =
667 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
668
669 m_opt_dispatch_map.emplace(sym_addr, i);
670 }
671 }
672
673 // Build our vtable dispatch handler here:
675 std::make_unique<AppleObjCVTables>(process_sp, m_objc_module_sp);
676 if (m_vtables_up)
677 m_vtables_up->ReadRegions();
678}
679
682 ValueList &dispatch_values) {
683 ThreadSP thread_sp(thread.shared_from_this());
684 ExecutionContext exe_ctx(thread_sp);
685 Log *log = GetLog(LLDBLog::Step);
686
688 FunctionCaller *impl_function_caller = nullptr;
689
690 // Scope for mutex locker:
691 {
692 std::lock_guard<std::mutex> guard(m_impl_function_mutex);
693
694 // First stage is to make the ClangUtility to hold our injected function:
695
696 if (!m_impl_code) {
698 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
701 if (!utility_fn_or_error) {
703 log, utility_fn_or_error.takeError(),
704 "Failed to get Utility Function for implementation lookup: {0}.");
705 return args_addr;
706 }
707 m_impl_code = std::move(*utility_fn_or_error);
708 } else {
709 LLDB_LOGF(log, "No method lookup implementation code.");
711 }
712
713 // Next make the runner function for our implementation utility function.
715 thread.GetProcess()->GetTarget());
716 if (!scratch_ts_sp)
718
719 CompilerType clang_void_ptr_type =
720 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
722
723 impl_function_caller = m_impl_code->MakeFunctionCaller(
724 clang_void_ptr_type, dispatch_values, thread_sp, error);
725 if (error.Fail()) {
726 LLDB_LOGF(log,
727 "Error getting function caller for dispatch lookup: \"%s\".",
728 error.AsCString());
729 return args_addr;
730 }
731 } else {
732 impl_function_caller = m_impl_code->GetFunctionCaller();
733 }
734 }
735
736 // Now write down the argument values for this particular call.
737 // This looks like it might be a race condition if other threads
738 // were calling into here, but actually it isn't because we allocate
739 // a new args structure for this call by passing args_addr =
740 // LLDB_INVALID_ADDRESS...
741
742 DiagnosticManager diagnostics;
743 if (!impl_function_caller->WriteFunctionArguments(
744 exe_ctx, args_addr, dispatch_values, diagnostics)) {
745 if (log) {
746 LLDB_LOGF(log, "Error writing function arguments.");
747 diagnostics.Dump(log);
748 }
749 return args_addr;
750 }
751
752 return args_addr;
753}
754
757 MsgsendMap::iterator pos;
758 pos = m_msgSend_map.find(addr);
759 if (pos != m_msgSend_map.end()) {
760 return &g_dispatch_functions[(*pos).second];
761 }
762 return nullptr;
763}
764
766 std::function<void(lldb::addr_t, const DispatchFunction &)> callback) {
767 for (auto elem : m_msgSend_map) {
768 callback(elem.first, g_dispatch_functions[elem.second]);
769 }
770}
771
774 bool stop_others) {
775 ThreadPlanSP ret_plan_sp;
776 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
777
778 DispatchFunction vtable_dispatch = {"vtable", false, false, false};
779 // The selector specific stubs are a wrapper for objc_msgSend. They don't get
780 // passed a SEL, but instead the selector string is encoded in the stub
781 // name, in the form:
782 // objc_msgSend$SelectorName
783 // and the stub figures out the uniqued selector. If we find ourselves in
784 // one of these stubs, we strip off the selector string and pass that to the
785 // implementation finder function, which looks up the SEL (you have to do this
786 // in process) and passes that to the runtime lookup function.
787
788 // First step is to see if we're in a selector-specific dispatch stub.
789 // Those are of the form _objc_msgSend$<SELECTOR>, so see if the current
790 // function has that name:
791 Address func_addr;
792 Target &target = thread.GetProcess()->GetTarget();
793 llvm::StringRef sym_name;
794 const DispatchFunction *this_dispatch = nullptr;
795
796 if (target.ResolveLoadAddress(curr_pc, func_addr)) {
797 const Symbol *curr_sym = func_addr.CalculateSymbolContextSymbol();
798 if (curr_sym)
799 sym_name = curr_sym->GetName().GetStringRef();
800 }
801
802 // objc has introduced new accelerated dispatch stubs which figure out the
803 // selector and in some cases the object in one way or another, then call
804 // objc_msgSend. If we're in one of those stubs, we can use "step through
805 // direct dispatch" plan to get to the actual dispatch.
806 if (!sym_name.empty() && (sym_name.consume_front("objc_msgSend$")
807 || sym_name.consume_front("objc_msgSendClass$"))) {
808 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
809 thread, *this);
810 return ret_plan_sp;
811 }
812
813 // Second step is to look and see if we are in one of the known ObjC
814 // dispatch functions. We've already compiled a table of same, so
815 // consult it.
816
817 this_dispatch = FindDispatchFunction(curr_pc);
818
819 // Next check to see if we are in a vtable region:
820
821 if (!this_dispatch && m_vtables_up) {
822 uint32_t flags;
823 if (m_vtables_up->IsAddressInVTables(curr_pc, flags)) {
824 vtable_dispatch.stret_return =
827 this_dispatch = &vtable_dispatch;
828 }
829 }
830
831 // Since we set this_dispatch in both the vtable & sel specific stub cases
832 // this if will be used for all three of those cases.
833 if (this_dispatch) {
834 Log *log = GetLog(LLDBLog::Step);
835
836 // We are decoding a method dispatch. First job is to pull the
837 // arguments out. If we are in a regular stub, we get self & selector,
838 // but if we are in a selector-specific stub, we'll have to get that from
839 // the string sym_name.
840
841 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
842
843 const ABI *abi = nullptr;
844 ProcessSP process_sp(thread.CalculateProcess());
845 if (process_sp)
846 abi = process_sp->GetABI().get();
847 if (abi == nullptr)
848 return ret_plan_sp;
849
850 TargetSP target_sp(thread.CalculateTarget());
851
852 TypeSystemClangSP scratch_ts_sp =
854 if (!scratch_ts_sp)
855 return ret_plan_sp;
856
857 ValueList argument_values;
858 Value void_ptr_value;
859 CompilerType clang_void_ptr_type =
860 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
862 // void_ptr_value.SetContext (Value::eContextTypeClangType,
863 // clang_void_ptr_type);
864 void_ptr_value.SetCompilerType(clang_void_ptr_type);
865
866 int obj_index;
867 int sel_index;
868
869 // If this is a struct return dispatch, then the first argument is
870 // the return struct pointer, and the object is the second, and
871 // the selector is the third.
872 // Otherwise the object is the first and the selector the second.
873 if (this_dispatch->stret_return) {
874 obj_index = 1;
875 sel_index = 2;
876 argument_values.PushValue(void_ptr_value);
877 argument_values.PushValue(void_ptr_value);
878 argument_values.PushValue(void_ptr_value);
879 } else {
880 obj_index = 0;
881 sel_index = 1;
882 argument_values.PushValue(void_ptr_value);
883 argument_values.PushValue(void_ptr_value);
884 }
885
886 bool success = abi->GetArgumentValues(thread, argument_values);
887 if (!success)
888 return ret_plan_sp;
889
890 lldb::addr_t obj_addr =
891 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
892 if (obj_addr == 0x0) {
893 LLDB_LOGF(
894 log,
895 "Asked to step to dispatch to nil object, returning empty plan.");
896 return ret_plan_sp;
897 }
898
899 ExecutionContext exe_ctx(thread.shared_from_this());
900 // isa_addr will store the class pointer that the method is being
901 // dispatched to - so either the class directly or the super class
902 // if this is one of the objc_msgSendSuper flavors. That's mostly
903 // used to look up the class/selector pair in our cache.
904
907 // Get the sel address from the arguments.
908 sel_addr =
909 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
910
911 // Figure out the class this is being dispatched to and see if
912 // we've already cached this method call, If so we can push a
913 // run-to-address plan directly. Otherwise we have to figure out
914 // where the implementation lives.
915
916 if (this_dispatch->is_super) {
917 if (this_dispatch->is_super2) {
918 // In the objc_msgSendSuper2 case, we don't get the object
919 // directly, we get a structure containing the object and the
920 // class to which the super message is being sent. So we need
921 // to dig the super out of the class and use that.
922
923 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
924 super_value.GetScalar() += process_sp->GetAddressByteSize();
925 super_value.ResolveValue(&exe_ctx);
926
927 if (super_value.GetScalar().IsValid()) {
928
929 // isa_value now holds the class pointer. The second word of the
930 // class pointer is the super-class pointer:
931 super_value.GetScalar() += process_sp->GetAddressByteSize();
932 super_value.ResolveValue(&exe_ctx);
933 if (super_value.GetScalar().IsValid())
934 isa_addr = super_value.GetScalar().ULongLong();
935 else {
936 LLDB_LOGF(log, "Failed to extract the super class value from the "
937 "class in objc_super.");
938 }
939 } else {
940 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
941 }
942 } else {
943 // In the objc_msgSendSuper case, we don't get the object
944 // directly, we get a two element structure containing the
945 // object and the super class to which the super message is
946 // being sent. So the class we want is the second element of
947 // this structure.
948
949 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
950 super_value.GetScalar() += process_sp->GetAddressByteSize();
951 super_value.ResolveValue(&exe_ctx);
952
953 if (super_value.GetScalar().IsValid()) {
954 isa_addr = super_value.GetScalar().ULongLong();
955 } else {
956 LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
957 }
958 }
959 } else {
960 // In the direct dispatch case, the object->isa is the class pointer we
961 // want.
962
963 // This is a little cheesy, but since object->isa is the first field,
964 // making the object value a load address value and resolving it will get
965 // the pointer sized data pointed to by that value...
966
967 // Note, it isn't a fatal error not to be able to get the
968 // address from the object, since this might be a "tagged
969 // pointer" which isn't a real object, but rather some word
970 // length encoded dingus.
971
972 Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
973
975 isa_value.ResolveValue(&exe_ctx);
976 if (isa_value.GetScalar().IsValid()) {
977 isa_addr = isa_value.GetScalar().ULongLong();
978 } else {
979 LLDB_LOGF(log, "Failed to extract the isa value from object.");
980 }
981 }
982
983 // Okay, we've got the address of the class for which we're resolving this,
984 // let's see if it's in our cache:
986 // If this is a regular dispatch, look up the sel in our addr to sel cache:
987 if (isa_addr != LLDB_INVALID_ADDRESS) {
988 ObjCLanguageRuntime *objc_runtime =
989 ObjCLanguageRuntime::Get(*thread.GetProcess());
990 assert(objc_runtime != nullptr);
991 // We have the address in the ISA pointer of our object, but it might
992 // be a masked value, so we need to get the Pointer ISA:
993 isa_addr = objc_runtime->GetPointerISA(isa_addr);
994
995 LLDB_LOG(log, "Resolving call for class - {0} and selector - {1}",
996 isa_addr, sel_addr);
997 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
998 }
999 // If it is a selector-specific stub dispatch, look in the string cache:
1000
1001 if (impl_addr != LLDB_INVALID_ADDRESS) {
1002 // Yup, it was in the cache, so we can run to that address directly.
1003
1004 LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,
1005 impl_addr);
1006
1007 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1008 stop_others);
1009 } else {
1010 // We haven't seen this class/selector pair yet. Look it up.
1011 StreamString errors;
1012 Address impl_code_address;
1013
1014 ValueList dispatch_values;
1015
1016 // We've will inject a little function in the target that takes the
1017 // object, selector/selector string and some flags,
1018 // and figures out the implementation. Looks like:
1019 // void *__lldb_objc_find_implementation_for_selector (void *object,
1020 // void *sel,
1021 // int
1022 // is_str_ptr,
1023 // int is_stret,
1024 // int is_super,
1025 // int is_super2,
1026 // int debug)
1027 // If we don't have an actual SEL, but rather a string version of the
1028 // selector WE injected, set is_str_ptr to true, and sel to the address
1029 // of the string.
1030 // So set up the arguments for that call.
1031
1032 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1033 lldb::addr_t sel_str_addr = LLDB_INVALID_ADDRESS;
1034 // Push the selector from arguments.
1035 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1036
1037 Value flag_value;
1038 CompilerType clang_int_type =
1039 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(
1042 flag_value.SetCompilerType(clang_int_type);
1043
1044 // We are passing in a sel addr now a string pointer in all cases for now.
1045 flag_value.GetScalar() = 0;
1046 dispatch_values.PushValue(flag_value);
1047
1048 if (this_dispatch->stret_return)
1049 flag_value.GetScalar() = 1;
1050 else
1051 flag_value.GetScalar() = 0;
1052 dispatch_values.PushValue(flag_value);
1053
1054 if (this_dispatch->is_super)
1055 flag_value.GetScalar() = 1;
1056 else
1057 flag_value.GetScalar() = 0;
1058 dispatch_values.PushValue(flag_value);
1059
1060 if (this_dispatch->is_super2)
1061 flag_value.GetScalar() = 1;
1062 else
1063 flag_value.GetScalar() = 0;
1064 dispatch_values.PushValue(flag_value);
1065
1066 if (log && log->GetVerbose())
1067 flag_value.GetScalar() = 1;
1068 else
1069 flag_value.GetScalar() = 0;
1070 dispatch_values.PushValue(flag_value);
1071
1072 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1073 thread, *this, dispatch_values, isa_addr, sel_addr, sel_str_addr,
1074 sym_name);
1075 if (log) {
1076 StreamString s;
1077 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1078 LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());
1079 }
1080 }
1081 }
1082
1083 // Next, check if we have hit an "optimized dispatch" function. This will
1084 // either directly call the base implementation or dispatch an objc_msgSend
1085 // if the method has been overridden. So we just do a "step in/step out",
1086 // setting a breakpoint on objc_msgSend, and if we hit the msgSend, we
1087 // will automatically step in again. That's the job of the
1088 // AppleThreadPlanStepThroughDirectDispatch.
1089 if (!this_dispatch && !ret_plan_sp) {
1090 MsgsendMap::iterator pos;
1091 pos = m_opt_dispatch_map.find(curr_pc);
1092 if (pos != m_opt_dispatch_map.end()) {
1093 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1094 thread, *this);
1095 }
1096 }
1097
1098 return ret_plan_sp;
1099}
1100
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:586
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:370
const lldb::ABISP & GetABI()
Definition Process.cpp:1530
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1271
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:608
bool ValueIsAddress() const
Definition Symbol.cpp:192
Address & GetAddressRef()
Definition Symbol.h:78
ConstString GetName() const
Definition Symbol.cpp:615
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:536
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3638
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2793
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:2948
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:528
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
void PushValue(const Value &value)
Definition Value.cpp:699
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:703
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:324
@ 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:277
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:594
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::TypeSystem > TypeSystemSP
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