1 //===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 #include "AppleObjCTrampolineHandler.h"
11 #include "AppleThreadPlanStepThroughObjCTrampoline.h"
13 #include "lldb/Breakpoint/StoppointCallbackContext.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/StreamFile.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Expression/DiagnosticManager.h"
19 #include "lldb/Expression/FunctionCaller.h"
20 #include "lldb/Expression/UserExpression.h"
21 #include "lldb/Expression/UtilityFunction.h"
22 #include "lldb/Symbol/ClangASTContext.h"
23 #include "lldb/Symbol/Symbol.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/ThreadPlanRunToAddress.h"
31 #include "lldb/Utility/ConstString.h"
32 #include "lldb/Utility/FileSpec.h"
33 #include "lldb/Utility/Log.h"
35 #include "llvm/ADT/STLExtras.h"
37 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
42 using namespace lldb_private;
44 const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name =
45 "__lldb_objc_find_implementation_for_selector";
46 const char *AppleObjCTrampolineHandler::
47 g_lookup_implementation_with_stret_function_code =
51 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
52 extern void *class_getMethodImplementation_stret(void *objc_class, \n\
54 extern void * object_getClass (id object); \n\
55 extern void * sel_getUid(char *name); \n\
56 extern int printf(const char *format, ...); \n\
58 extern \"C\" void * __lldb_objc_find_implementation_for_selector ( \n\
68 struct __lldb_imp_return_struct \n\
75 struct __lldb_objc_class { \n\
79 struct __lldb_objc_super { \n\
81 struct __lldb_objc_class *class_ptr; \n\
83 struct __lldb_msg_ref { \n\
88 struct __lldb_imp_return_struct return_struct; \n\
91 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"\n\
92 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\
93 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);\n\
98 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;\n\
102 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;\n\
107 // This code seems a little funny, but has its reasons... \n\
109 // The call to [object class] is here because if this is a \n\
110 // class, and has not been called into yet, we need to do \n\
111 // something to force the class to initialize itself. \n\
112 // Then the call to object_getClass will actually return the \n\
113 // correct class, either the class if object is a class \n\
114 // instance, or the meta-class if it is a class pointer. \n\
115 void *class_ptr = (void *) [(id) object class]; \n\
116 return_struct.class_addr = (id) object_getClass((id) object); \n\
119 if (class_ptr == object) \n\
121 printf (\"Found a class object, need to use the meta class %p -> %p\\n\",\n\
122 class_ptr, return_struct.class_addr); \n\
126 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
127 class_ptr, return_struct.class_addr); \n\
136 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\
140 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\
141 return_struct.sel_addr = sel_getUid (sel_name); \n\
143 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
144 return_struct.sel_addr, sel_name); \n\
149 return_struct.sel_addr = sel; \n\
154 return_struct.impl_addr = \n\
155 class_getMethodImplementation_stret (return_struct.class_addr, \n\
156 return_struct.sel_addr); \n\
160 return_struct.impl_addr = \n\
161 class_getMethodImplementation (return_struct.class_addr, \n\
162 return_struct.sel_addr); \n\
165 printf (\"\\n*** Returning implementation: %p.\\n\", \n\
166 return_struct.impl_addr); \n\
168 return return_struct.impl_addr; \n\
172 AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =
176 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
177 extern void * object_getClass (id object); \n\
178 extern void * sel_getUid(char *name); \n\
179 extern int printf(const char *format, ...); \n\
181 extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object, \n\
190 struct __lldb_imp_return_struct \n\
192 void *class_addr; \n\
197 struct __lldb_objc_class { \n\
201 struct __lldb_objc_super { \n\
203 struct __lldb_objc_class *class_ptr; \n\
205 struct __lldb_msg_ref { \n\
210 struct __lldb_imp_return_struct return_struct; \n\
213 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \" \n\
214 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\
215 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed); \n\
220 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr; \n\
224 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr; \n\
229 // This code seems a little funny, but has its reasons... \n\
230 // The call to [object class] is here because if this is a class, and has not been called into \n\
231 // yet, we need to do something to force the class to initialize itself. \n\
232 // Then the call to object_getClass will actually return the correct class, either the class \n\
233 // if object is a class instance, or the meta-class if it is a class pointer. \n\
234 void *class_ptr = (void *) [(id) object class]; \n\
235 return_struct.class_addr = (id) object_getClass((id) object); \n\
238 if (class_ptr == object) \n\
240 printf (\"Found a class object, need to return the meta class %p -> %p\\n\", \n\
241 class_ptr, return_struct.class_addr); \n\
245 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
246 class_ptr, return_struct.class_addr); \n\
255 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\
259 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\
260 return_struct.sel_addr = sel_getUid (sel_name); \n\
262 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
263 return_struct.sel_addr, sel_name); \n\
268 return_struct.sel_addr = sel; \n\
271 return_struct.impl_addr = \n\
272 class_getMethodImplementation (return_struct.class_addr, \n\
273 return_struct.sel_addr); \n\
275 printf (\"\\n*** Returning implementation: 0x%p.\\n\", \n\
276 return_struct.impl_addr); \n\
278 return return_struct.impl_addr; \n\
282 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(
283 AppleObjCVTables *owner, lldb::addr_t header_addr)
284 : m_valid(true), m_owner(owner), m_header_addr(header_addr),
285 m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) {
289 AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() {}
291 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {
292 // The header looks like:
294 // uint16_t headerSize
296 // uint32_t descCount
299 // First read in the header:
301 char memory_buffer[16];
302 ProcessSP process_sp = m_owner->GetProcessSP();
305 DataExtractor data(memory_buffer, sizeof(memory_buffer),
306 process_sp->GetByteOrder(),
307 process_sp->GetAddressByteSize());
308 size_t actual_size = 8 + process_sp->GetAddressByteSize();
311 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
312 if (bytes_read != actual_size) {
317 lldb::offset_t offset = 0;
318 const uint16_t header_size = data.GetU16(&offset);
319 const uint16_t descriptor_size = data.GetU16(&offset);
320 const size_t num_descriptors = data.GetU32(&offset);
322 m_next_region = data.GetPointer(&offset);
324 // If the header size is 0, that means we've come in too early before this
326 // Set ourselves as not valid, and continue.
327 if (header_size == 0 || num_descriptors == 0) {
332 // Now read in all the descriptors:
333 // The descriptor looks like:
338 // Where offset is either 0 - in which case it is unused, or it is
339 // the offset of the vtable code from the beginning of the
340 // descriptor record. Below, we'll convert that into an absolute
341 // code address, since I don't want to have to compute it over and
344 // Ingest the whole descriptor array:
345 const lldb::addr_t desc_ptr = m_header_addr + header_size;
346 const size_t desc_array_size = num_descriptors * descriptor_size;
347 DataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
348 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
350 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
351 process_sp->GetAddressByteSize());
352 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);
353 if (bytes_read != desc_array_size) {
358 // The actual code for the vtables will be laid out consecutively, so I also
359 // compute the start and end of the whole code block.
362 m_code_start_addr = 0;
365 for (size_t i = 0; i < num_descriptors; i++) {
366 lldb::addr_t start_offset = offset;
367 uint32_t voffset = desc_extractor.GetU32(&offset);
368 uint32_t flags = desc_extractor.GetU32(&offset);
369 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
370 m_descriptors.push_back(VTableDescriptor(flags, code_addr));
372 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
373 m_code_start_addr = code_addr;
374 if (code_addr > m_code_end_addr)
375 m_code_end_addr = code_addr;
377 offset = start_offset + descriptor_size;
379 // Finally, a little bird told me that all the vtable code blocks
380 // are the same size. Let's compute the blocks and if they are all
381 // the same add the size to the code end address:
382 lldb::addr_t code_size = 0;
383 bool all_the_same = true;
384 for (size_t i = 0; i < num_descriptors - 1; i++) {
385 lldb::addr_t this_size =
386 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
388 code_size = this_size;
390 if (this_size != code_size)
391 all_the_same = false;
392 if (this_size > code_size)
393 code_size = this_size;
397 m_code_end_addr += code_size;
400 bool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::
401 AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
405 if (addr < m_code_start_addr || addr > m_code_end_addr)
408 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
409 for (pos = m_descriptors.begin(); pos != end; pos++) {
410 if (addr <= (*pos).code_start) {
411 flags = (*pos).flags;
418 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(
420 s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
421 " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
422 m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
423 size_t num_elements = m_descriptors.size();
424 for (size_t i = 0; i < num_elements; i++) {
426 s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
427 m_descriptors[i].code_start, m_descriptors[i].flags);
431 AppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables(
432 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
433 : m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS),
434 m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID),
435 m_objc_module_sp(objc_module_sp) {
437 m_process_wp = process_sp;
440 AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {
441 ProcessSP process_sp = GetProcessSP();
443 if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
444 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
448 bool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {
449 if (m_trampoline_header != LLDB_INVALID_ADDRESS)
452 ProcessSP process_sp = GetProcessSP();
454 Target &target = process_sp->GetTarget();
456 const ModuleList &target_modules = target.GetImages();
457 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
458 size_t num_modules = target_modules.GetSize();
459 if (!m_objc_module_sp) {
460 for (size_t i = 0; i < num_modules; i++) {
461 if (ObjCLanguageRuntime::Get(*process_sp)
462 ->IsModuleObjCLibrary(
463 target_modules.GetModuleAtIndexUnlocked(i))) {
464 m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i);
470 if (m_objc_module_sp) {
471 ConstString trampoline_name("gdb_objc_trampolines");
472 const Symbol *trampoline_symbol =
473 m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
475 if (trampoline_symbol != nullptr) {
476 m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
477 if (m_trampoline_header == LLDB_INVALID_ADDRESS)
480 // Next look up the "changed" symbol and set a breakpoint on that...
481 ConstString changed_name("gdb_objc_trampolines_changed");
482 const Symbol *changed_symbol =
483 m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
485 if (changed_symbol != nullptr) {
486 const Address changed_symbol_addr = changed_symbol->GetAddress();
487 if (!changed_symbol_addr.IsValid())
490 lldb::addr_t changed_addr =
491 changed_symbol_addr.GetOpcodeLoadAddress(&target);
492 if (changed_addr != LLDB_INVALID_ADDRESS) {
493 BreakpointSP trampolines_changed_bp_sp =
494 target.CreateBreakpoint(changed_addr, true, false);
495 if (trampolines_changed_bp_sp) {
496 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
497 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
499 trampolines_changed_bp_sp->SetBreakpointKind(
500 "objc-trampolines-changed");
511 bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
512 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
513 lldb::user_id_t break_loc_id) {
514 AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
515 if (vtable_handler->InitializeVTableSymbols()) {
516 // The Update function is called with the address of an added region. So we
517 // grab that address, and
518 // feed it into ReadRegions. Of course, our friend the ABI will get the
520 ExecutionContext exe_ctx(context->exe_ctx_ref);
521 Process *process = exe_ctx.GetProcessPtr();
522 const ABI *abi = process->GetABI().get();
524 ClangASTContext *clang_ast_context =
525 process->GetTarget().GetScratchClangASTContext();
526 ValueList argument_values;
528 CompilerType clang_void_ptr_type =
529 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
531 input_value.SetValueType(Value::eValueTypeScalar);
532 // input_value.SetContext (Value::eContextTypeClangType,
533 // clang_void_ptr_type);
534 input_value.SetCompilerType(clang_void_ptr_type);
535 argument_values.PushValue(input_value);
538 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
542 // Now get a pointer value from the zeroth argument.
545 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
547 lldb::offset_t offset = 0;
548 lldb::addr_t region_addr = data.GetPointer(&offset);
550 if (region_addr != 0)
551 vtable_handler->ReadRegions(region_addr);
556 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
557 // The no argument version reads the start region from the value of
558 // the gdb_regions_header, and gets started from there.
561 if (!InitializeVTableSymbols())
564 ProcessSP process_sp = GetProcessSP();
566 lldb::addr_t region_addr =
567 process_sp->ReadPointerFromMemory(m_trampoline_header, error);
569 return ReadRegions(region_addr);
574 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
575 lldb::addr_t region_addr) {
576 ProcessSP process_sp = GetProcessSP();
580 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
582 // We aren't starting at the trampoline symbol.
583 InitializeVTableSymbols();
584 lldb::addr_t next_region = region_addr;
586 // Read in the sizes of the headers.
587 while (next_region != 0) {
588 m_regions.push_back(VTableRegion(this, next_region));
589 if (!m_regions.back().IsValid()) {
595 m_regions.back().Dump(s);
596 log->Printf("Read vtable region: \n%s", s.GetData());
599 next_region = m_regions.back().GetNextRegionAddr();
605 bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
606 lldb::addr_t addr, uint32_t &flags) {
607 region_collection::iterator pos, end = m_regions.end();
608 for (pos = m_regions.begin(); pos != end; pos++) {
609 if ((*pos).AddressInRegion(addr, flags))
615 const AppleObjCTrampolineHandler::DispatchFunction
616 AppleObjCTrampolineHandler::g_dispatch_functions[] = {
617 // NAME STRET SUPER SUPER2 FIXUP TYPE
618 {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
619 {"objc_msgSend_fixup", false, false, false,
620 DispatchFunction::eFixUpToFix},
621 {"objc_msgSend_fixedup", false, false, false,
622 DispatchFunction::eFixUpFixed},
623 {"objc_msgSend_stret", true, false, false,
624 DispatchFunction::eFixUpNone},
625 {"objc_msgSend_stret_fixup", true, false, false,
626 DispatchFunction::eFixUpToFix},
627 {"objc_msgSend_stret_fixedup", true, false, false,
628 DispatchFunction::eFixUpFixed},
629 {"objc_msgSend_fpret", false, false, false,
630 DispatchFunction::eFixUpNone},
631 {"objc_msgSend_fpret_fixup", false, false, false,
632 DispatchFunction::eFixUpToFix},
633 {"objc_msgSend_fpret_fixedup", false, false, false,
634 DispatchFunction::eFixUpFixed},
635 {"objc_msgSend_fp2ret", false, false, true,
636 DispatchFunction::eFixUpNone},
637 {"objc_msgSend_fp2ret_fixup", false, false, true,
638 DispatchFunction::eFixUpToFix},
639 {"objc_msgSend_fp2ret_fixedup", false, false, true,
640 DispatchFunction::eFixUpFixed},
641 {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
642 {"objc_msgSendSuper_stret", true, true, false,
643 DispatchFunction::eFixUpNone},
644 {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
645 {"objc_msgSendSuper2_fixup", false, true, true,
646 DispatchFunction::eFixUpToFix},
647 {"objc_msgSendSuper2_fixedup", false, true, true,
648 DispatchFunction::eFixUpFixed},
649 {"objc_msgSendSuper2_stret", true, true, true,
650 DispatchFunction::eFixUpNone},
651 {"objc_msgSendSuper2_stret_fixup", true, true, true,
652 DispatchFunction::eFixUpToFix},
653 {"objc_msgSendSuper2_stret_fixedup", true, true, true,
654 DispatchFunction::eFixUpFixed},
657 AppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
658 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
659 : m_process_wp(), m_objc_module_sp(objc_module_sp),
660 m_lookup_implementation_function_code(nullptr),
661 m_impl_fn_addr(LLDB_INVALID_ADDRESS),
662 m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
663 m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
665 m_process_wp = process_sp;
666 // Look up the known resolution functions:
668 ConstString get_impl_name("class_getMethodImplementation");
669 ConstString get_impl_stret_name("class_getMethodImplementation_stret");
670 ConstString msg_forward_name("_objc_msgForward");
671 ConstString msg_forward_stret_name("_objc_msgForward_stret");
673 Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
674 const Symbol *class_getMethodImplementation =
675 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
677 const Symbol *class_getMethodImplementation_stret =
678 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
680 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
681 msg_forward_name, eSymbolTypeCode);
682 const Symbol *msg_forward_stret =
683 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
686 if (class_getMethodImplementation)
688 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
690 if (class_getMethodImplementation_stret)
691 m_impl_stret_fn_addr =
692 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
695 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
696 if (msg_forward_stret)
697 m_msg_forward_stret_addr =
698 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
700 // FIXME: Do some kind of logging here.
701 if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
702 // If we can't even find the ordinary get method implementation function,
703 // then we aren't going to be able to
704 // step through any method dispatches. Warn to that effect and get out of
706 if (process_sp->CanJIT()) {
707 process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf(
708 "Could not find implementation lookup function \"%s\""
709 " step in through ObjC method dispatch will not work.\n",
710 get_impl_name.AsCString());
713 } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
714 // It there is no stret return lookup function, assume that it is the same
715 // as the straight lookup:
716 m_impl_stret_fn_addr = m_impl_fn_addr;
717 // Also we will use the version of the lookup code that doesn't rely on the
718 // stret version of the function.
719 m_lookup_implementation_function_code =
720 g_lookup_implementation_no_stret_function_code;
722 m_lookup_implementation_function_code =
723 g_lookup_implementation_with_stret_function_code;
726 // Look up the addresses for the objc dispatch functions and cache
727 // them. For now I'm inspecting the symbol names dynamically to
728 // figure out how to dispatch to them. If it becomes more
729 // complicated than this we can turn the g_dispatch_functions char *
730 // array into a template table, and populate the DispatchFunction
733 for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
734 ConstString name_const_str(g_dispatch_functions[i].name);
735 const Symbol *msgSend_symbol =
736 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
738 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
739 // FIXME: Make g_dispatch_functions static table of
740 // DispatchFunctions, and have the map be address->index.
741 // Problem is we also need to lookup the dispatch function. For
742 // now we could have a side table of stret & non-stret dispatch
743 // functions. If that's as complex as it gets, we're fine.
745 lldb::addr_t sym_addr =
746 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
748 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
752 // Build our vtable dispatch handler here:
753 m_vtables_up.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
755 m_vtables_up->ReadRegions();
759 AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
760 ValueList &dispatch_values) {
761 ThreadSP thread_sp(thread.shared_from_this());
762 ExecutionContext exe_ctx(thread_sp);
763 DiagnosticManager diagnostics;
764 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
766 lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
767 FunctionCaller *impl_function_caller = nullptr;
769 // Scope for mutex locker:
771 std::lock_guard<std::mutex> guard(m_impl_function_mutex);
773 // First stage is to make the ClangUtility to hold our injected function:
776 if (m_lookup_implementation_function_code != nullptr) {
778 m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
779 m_lookup_implementation_function_code, eLanguageTypeObjC,
780 g_lookup_implementation_function_name, error));
784 "Failed to get Utility Function for implementation lookup: %s.",
790 if (!m_impl_code->Install(diagnostics, exe_ctx)) {
792 log->Printf("Failed to install implementation lookup.");
793 diagnostics.Dump(log);
800 log->Printf("No method lookup implementation code.");
801 return LLDB_INVALID_ADDRESS;
804 // Next make the runner function for our implementation utility function.
805 ClangASTContext *clang_ast_context =
806 thread.GetProcess()->GetTarget().GetScratchClangASTContext();
807 CompilerType clang_void_ptr_type =
808 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
811 impl_function_caller = m_impl_code->MakeFunctionCaller(
812 clang_void_ptr_type, dispatch_values, thread_sp, error);
816 "Error getting function caller for dispatch lookup: \"%s\".",
821 impl_function_caller = m_impl_code->GetFunctionCaller();
827 // Now write down the argument values for this particular call.
828 // This looks like it might be a race condition if other threads
829 // were calling into here, but actually it isn't because we allocate
830 // a new args structure for this call by passing args_addr =
831 // LLDB_INVALID_ADDRESS...
833 if (!impl_function_caller->WriteFunctionArguments(
834 exe_ctx, args_addr, dispatch_values, diagnostics)) {
836 log->Printf("Error writing function arguments.");
837 diagnostics.Dump(log);
846 AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
848 ThreadPlanSP ret_plan_sp;
849 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
851 DispatchFunction this_dispatch;
852 bool found_it = false;
854 // First step is to look and see if we are in one of the known ObjC
855 // dispatch functions. We've already compiled a table of same, so
858 MsgsendMap::iterator pos;
859 pos = m_msgSend_map.find(curr_pc);
860 if (pos != m_msgSend_map.end()) {
861 this_dispatch = g_dispatch_functions[(*pos).second];
865 // Next check to see if we are in a vtable region:
870 found_it = m_vtables_up->IsAddressInVTables(curr_pc, flags);
872 this_dispatch.name = "vtable";
873 this_dispatch.stret_return =
874 (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
875 AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
876 this_dispatch.is_super = false;
877 this_dispatch.is_super2 = false;
878 this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
884 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
886 // We are decoding a method dispatch. First job is to pull the
889 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
891 const ABI *abi = nullptr;
892 ProcessSP process_sp(thread.CalculateProcess());
894 abi = process_sp->GetABI().get();
898 TargetSP target_sp(thread.CalculateTarget());
900 ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
901 ValueList argument_values;
902 Value void_ptr_value;
903 CompilerType clang_void_ptr_type =
904 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
905 void_ptr_value.SetValueType(Value::eValueTypeScalar);
906 // void_ptr_value.SetContext (Value::eContextTypeClangType,
907 // clang_void_ptr_type);
908 void_ptr_value.SetCompilerType(clang_void_ptr_type);
913 // If this is a struct return dispatch, then the first argument is
914 // the return struct pointer, and the object is the second, and
915 // the selector is the third. Otherwise the object is the first
916 // and the selector the second.
917 if (this_dispatch.stret_return) {
920 argument_values.PushValue(void_ptr_value);
921 argument_values.PushValue(void_ptr_value);
922 argument_values.PushValue(void_ptr_value);
926 argument_values.PushValue(void_ptr_value);
927 argument_values.PushValue(void_ptr_value);
930 bool success = abi->GetArgumentValues(thread, argument_values);
934 lldb::addr_t obj_addr =
935 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
936 if (obj_addr == 0x0) {
939 "Asked to step to dispatch to nil object, returning empty plan.");
943 ExecutionContext exe_ctx(thread.shared_from_this());
944 Process *process = exe_ctx.GetProcessPtr();
945 // isa_addr will store the class pointer that the method is being
946 // dispatched to - so either the class directly or the super class
947 // if this is one of the objc_msgSendSuper flavors. That's mostly
948 // used to look up the class/selector pair in our cache.
950 lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
951 lldb::addr_t sel_addr =
952 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
954 // Figure out the class this is being dispatched to and see if
955 // we've already cached this method call, If so we can push a
956 // run-to-address plan directly. Otherwise we have to figure out
957 // where the implementation lives.
959 if (this_dispatch.is_super) {
960 if (this_dispatch.is_super2) {
961 // In the objc_msgSendSuper2 case, we don't get the object
962 // directly, we get a structure containing the object and the
963 // class to which the super message is being sent. So we need
964 // to dig the super out of the class and use that.
966 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
967 super_value.GetScalar() += process->GetAddressByteSize();
968 super_value.ResolveValue(&exe_ctx);
970 if (super_value.GetScalar().IsValid()) {
972 // isa_value now holds the class pointer. The second word of the
973 // class pointer is the super-class pointer:
974 super_value.GetScalar() += process->GetAddressByteSize();
975 super_value.ResolveValue(&exe_ctx);
976 if (super_value.GetScalar().IsValid())
977 isa_addr = super_value.GetScalar().ULongLong();
980 log->Printf("Failed to extract the super class value from the "
981 "class in objc_super.");
985 log->Printf("Failed to extract the class value from objc_super.");
988 // In the objc_msgSendSuper case, we don't get the object
989 // directly, we get a two element structure containing the
990 // object and the super class to which the super message is
991 // being sent. So the class we want is the second element of
994 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
995 super_value.GetScalar() += process->GetAddressByteSize();
996 super_value.ResolveValue(&exe_ctx);
998 if (super_value.GetScalar().IsValid()) {
999 isa_addr = super_value.GetScalar().ULongLong();
1002 log->Printf("Failed to extract the class value from objc_super.");
1006 // In the direct dispatch case, the object->isa is the class pointer we
1009 // This is a little cheesy, but since object->isa is the first field,
1010 // making the object value a load address value and resolving it will get
1011 // the pointer sized data pointed to by that value...
1013 // Note, it isn't a fatal error not to be able to get the
1014 // address from the object, since this might be a "tagged
1015 // pointer" which isn't a real object, but rather some word
1016 // length encoded dingus.
1018 Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1020 isa_value.SetValueType(Value::eValueTypeLoadAddress);
1021 isa_value.ResolveValue(&exe_ctx);
1022 if (isa_value.GetScalar().IsValid()) {
1023 isa_addr = isa_value.GetScalar().ULongLong();
1026 log->Printf("Failed to extract the isa value from object.");
1030 // Okay, we've got the address of the class for which we're resolving this,
1031 // let's see if it's in our cache:
1032 lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1034 if (isa_addr != LLDB_INVALID_ADDRESS) {
1036 log->Printf("Resolving call for class - 0x%" PRIx64
1037 " and selector - 0x%" PRIx64,
1038 isa_addr, sel_addr);
1040 ObjCLanguageRuntime *objc_runtime =
1041 ObjCLanguageRuntime::Get(*thread.GetProcess());
1042 assert(objc_runtime != nullptr);
1044 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1047 if (impl_addr != LLDB_INVALID_ADDRESS) {
1048 // Yup, it was in the cache, so we can run to that address directly.
1051 log->Printf("Found implementation address in cache: 0x%" PRIx64,
1054 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1057 // We haven't seen this class/selector pair yet. Look it up.
1058 StreamString errors;
1059 Address impl_code_address;
1061 ValueList dispatch_values;
1063 // We've will inject a little function in the target that takes the
1064 // object, selector and some flags,
1065 // and figures out the implementation. Looks like:
1066 // void *__lldb_objc_find_implementation_for_selector (void *object,
1074 // So set up the arguments for that call.
1076 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1077 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1080 CompilerType clang_int_type =
1081 clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1082 lldb::eEncodingSint, 32);
1083 flag_value.SetValueType(Value::eValueTypeScalar);
1084 // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1085 flag_value.SetCompilerType(clang_int_type);
1087 if (this_dispatch.stret_return)
1088 flag_value.GetScalar() = 1;
1090 flag_value.GetScalar() = 0;
1091 dispatch_values.PushValue(flag_value);
1093 if (this_dispatch.is_super)
1094 flag_value.GetScalar() = 1;
1096 flag_value.GetScalar() = 0;
1097 dispatch_values.PushValue(flag_value);
1099 if (this_dispatch.is_super2)
1100 flag_value.GetScalar() = 1;
1102 flag_value.GetScalar() = 0;
1103 dispatch_values.PushValue(flag_value);
1105 switch (this_dispatch.fixedup) {
1106 case DispatchFunction::eFixUpNone:
1107 flag_value.GetScalar() = 0;
1108 dispatch_values.PushValue(flag_value);
1109 dispatch_values.PushValue(flag_value);
1111 case DispatchFunction::eFixUpFixed:
1112 flag_value.GetScalar() = 1;
1113 dispatch_values.PushValue(flag_value);
1114 flag_value.GetScalar() = 1;
1115 dispatch_values.PushValue(flag_value);
1117 case DispatchFunction::eFixUpToFix:
1118 flag_value.GetScalar() = 1;
1119 dispatch_values.PushValue(flag_value);
1120 flag_value.GetScalar() = 0;
1121 dispatch_values.PushValue(flag_value);
1124 if (log && log->GetVerbose())
1125 flag_value.GetScalar() = 1;
1127 flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1128 dispatch_values.PushValue(flag_value);
1130 // The step through code might have to fill in the cache, so it
1131 // is not safe to run only one thread. So we override the
1132 // stop_others value passed in to us here:
1133 const bool trampoline_stop_others = false;
1134 ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1135 thread, this, dispatch_values, isa_addr, sel_addr,
1136 trampoline_stop_others);
1139 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1140 log->Printf("Using ObjC step plan: %s.\n", s.GetData());
1149 AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1150 return m_impl_code->GetFunctionCaller();