1 //===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 #include "AppleObjCTrampolineHandler.h"
15 // Other libraries and framework includes
17 #include "AppleThreadPlanStepThroughObjCTrampoline.h"
19 #include "lldb/Breakpoint/StoppointCallbackContext.h"
20 #include "lldb/Core/ConstString.h"
21 #include "lldb/Core/Debugger.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/StreamFile.h"
25 #include "lldb/Core/Value.h"
26 #include "lldb/Expression/DiagnosticManager.h"
27 #include "lldb/Expression/FunctionCaller.h"
28 #include "lldb/Expression/UserExpression.h"
29 #include "lldb/Expression/UtilityFunction.h"
30 #include "lldb/Host/FileSpec.h"
31 #include "lldb/Symbol/ClangASTContext.h"
32 #include "lldb/Symbol/Symbol.h"
33 #include "lldb/Target/ABI.h"
34 #include "lldb/Target/ExecutionContext.h"
35 #include "lldb/Target/ObjCLanguageRuntime.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/RegisterContext.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Thread.h"
40 #include "lldb/Target/ThreadPlanRunToAddress.h"
42 #include "llvm/ADT/STLExtras.h"
45 using namespace lldb_private;
47 const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name =
48 "__lldb_objc_find_implementation_for_selector";
49 const char *AppleObjCTrampolineHandler::
50 g_lookup_implementation_with_stret_function_code =
54 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
55 extern void *class_getMethodImplementation_stret(void *objc_class, void *sel); \n\
56 extern void * object_getClass (id object); \n\
57 extern void * sel_getUid(char *name); \n\
58 extern int printf(const char *format, ...); \n\
60 extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object, \n\
69 struct __lldb_imp_return_struct \n\
76 struct __lldb_objc_class { \n\
80 struct __lldb_objc_super { \n\
82 struct __lldb_objc_class *class_ptr; \n\
84 struct __lldb_msg_ref { \n\
89 struct __lldb_imp_return_struct return_struct; \n\
92 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \" \n\
93 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\
94 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed); \n\
99 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr; \n\
103 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr; \n\
108 // This code seems a little funny, but has its reasons... \n\
109 // The call to [object class] is here because if this is a class, and has not been called into \n\
110 // yet, we need to do something to force the class to initialize itself. \n\
111 // Then the call to object_getClass will actually return the correct class, either the class \n\
112 // if object is a class instance, or the meta-class if it is a class pointer. \n\
113 void *class_ptr = (void *) [(id) object class]; \n\
114 return_struct.class_addr = (id) object_getClass((id) object); \n\
117 if (class_ptr == object) \n\
119 printf (\"Found a class object, need to use the meta class %p -> %p\\n\", \n\
120 class_ptr, return_struct.class_addr); \n\
124 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
125 class_ptr, return_struct.class_addr); \n\
134 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\
138 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\
139 return_struct.sel_addr = sel_getUid (sel_name); \n\
141 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\", \n\
142 return_struct.sel_addr, sel_name); \n\
147 return_struct.sel_addr = sel; \n\
152 return_struct.impl_addr = class_getMethodImplementation_stret (return_struct.class_addr, \n\
153 return_struct.sel_addr); \n\
157 return_struct.impl_addr = class_getMethodImplementation (return_struct.class_addr, \n\
158 return_struct.sel_addr); \n\
161 printf (\"\\n*** Returning implementation: %p.\\n\", return_struct.impl_addr); \n\
163 return return_struct.impl_addr; \n\
167 AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =
171 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
172 extern void * object_getClass (id object); \n\
173 extern void * sel_getUid(char *name); \n\
174 extern int printf(const char *format, ...); \n\
176 extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object, \n\
185 struct __lldb_imp_return_struct \n\
187 void *class_addr; \n\
192 struct __lldb_objc_class { \n\
196 struct __lldb_objc_super { \n\
198 struct __lldb_objc_class *class_ptr; \n\
200 struct __lldb_msg_ref { \n\
205 struct __lldb_imp_return_struct return_struct; \n\
208 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \" \n\
209 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\
210 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed); \n\
215 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr; \n\
219 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr; \n\
224 // This code seems a little funny, but has its reasons... \n\
225 // The call to [object class] is here because if this is a class, and has not been called into \n\
226 // yet, we need to do something to force the class to initialize itself. \n\
227 // Then the call to object_getClass will actually return the correct class, either the class \n\
228 // if object is a class instance, or the meta-class if it is a class pointer. \n\
229 void *class_ptr = (void *) [(id) object class]; \n\
230 return_struct.class_addr = (id) object_getClass((id) object); \n\
233 if (class_ptr == object) \n\
235 printf (\"Found a class object, need to return the meta class %p -> %p\\n\", \n\
236 class_ptr, return_struct.class_addr); \n\
240 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
241 class_ptr, return_struct.class_addr); \n\
250 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\
254 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\
255 return_struct.sel_addr = sel_getUid (sel_name); \n\
257 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\", \n\
258 return_struct.sel_addr, sel_name); \n\
263 return_struct.sel_addr = sel; \n\
266 return_struct.impl_addr = class_getMethodImplementation (return_struct.class_addr, \n\
267 return_struct.sel_addr); \n\
269 printf (\"\\n*** Returning implementation: 0x%p.\\n\", return_struct.impl_addr); \n\
271 return return_struct.impl_addr; \n\
275 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(
276 AppleObjCVTables *owner, lldb::addr_t header_addr)
277 : m_valid(true), m_owner(owner), m_header_addr(header_addr),
278 m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) {
282 AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() {}
284 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {
285 // The header looks like:
287 // uint16_t headerSize
289 // uint32_t descCount
292 // First read in the header:
294 char memory_buffer[16];
295 ProcessSP process_sp = m_owner->GetProcessSP();
298 DataExtractor data(memory_buffer, sizeof(memory_buffer),
299 process_sp->GetByteOrder(),
300 process_sp->GetAddressByteSize());
301 size_t actual_size = 8 + process_sp->GetAddressByteSize();
304 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
305 if (bytes_read != actual_size) {
310 lldb::offset_t offset = 0;
311 const uint16_t header_size = data.GetU16(&offset);
312 const uint16_t descriptor_size = data.GetU16(&offset);
313 const size_t num_descriptors = data.GetU32(&offset);
315 m_next_region = data.GetPointer(&offset);
317 // If the header size is 0, that means we've come in too early before this
319 // Set ourselves as not valid, and continue.
320 if (header_size == 0 || num_descriptors == 0) {
325 // Now read in all the descriptors:
326 // The descriptor looks like:
331 // Where offset is either 0 - in which case it is unused, or
332 // it is the offset of the vtable code from the beginning of the descriptor
334 // Below, we'll convert that into an absolute code address, since I don't want
336 // to compute it over and over.
338 // Ingest the whole descriptor array:
339 const lldb::addr_t desc_ptr = m_header_addr + header_size;
340 const size_t desc_array_size = num_descriptors * descriptor_size;
341 DataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
342 uint8_t *dst = (uint8_t *)data_sp->GetBytes();
344 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
345 process_sp->GetAddressByteSize());
346 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);
347 if (bytes_read != desc_array_size) {
352 // The actual code for the vtables will be laid out consecutively, so I also
353 // compute the start and end of the whole code block.
356 m_code_start_addr = 0;
359 for (size_t i = 0; i < num_descriptors; i++) {
360 lldb::addr_t start_offset = offset;
361 uint32_t voffset = desc_extractor.GetU32(&offset);
362 uint32_t flags = desc_extractor.GetU32(&offset);
363 lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
364 m_descriptors.push_back(VTableDescriptor(flags, code_addr));
366 if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
367 m_code_start_addr = code_addr;
368 if (code_addr > m_code_end_addr)
369 m_code_end_addr = code_addr;
371 offset = start_offset + descriptor_size;
373 // Finally, a little bird told me that all the vtable code blocks are the same
375 // Let's compute the blocks and if they are all the same add the size to the
377 lldb::addr_t code_size = 0;
378 bool all_the_same = true;
379 for (size_t i = 0; i < num_descriptors - 1; i++) {
380 lldb::addr_t this_size =
381 m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
383 code_size = this_size;
385 if (this_size != code_size)
386 all_the_same = false;
387 if (this_size > code_size)
388 code_size = this_size;
392 m_code_end_addr += code_size;
395 bool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::
396 AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
400 if (addr < m_code_start_addr || addr > m_code_end_addr)
403 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
404 for (pos = m_descriptors.begin(); pos != end; pos++) {
405 if (addr <= (*pos).code_start) {
406 flags = (*pos).flags;
413 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(
415 s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
416 " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
417 m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
418 size_t num_elements = m_descriptors.size();
419 for (size_t i = 0; i < num_elements; i++) {
421 s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
422 m_descriptors[i].code_start, m_descriptors[i].flags);
426 AppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables(
427 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
428 : m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS),
429 m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID),
430 m_objc_module_sp(objc_module_sp) {
432 m_process_wp = process_sp;
435 AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {
436 ProcessSP process_sp = GetProcessSP();
438 if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
439 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
443 bool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {
444 if (m_trampoline_header != LLDB_INVALID_ADDRESS)
447 ProcessSP process_sp = GetProcessSP();
449 Target &target = process_sp->GetTarget();
451 const ModuleList &target_modules = target.GetImages();
452 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
453 size_t num_modules = target_modules.GetSize();
454 if (!m_objc_module_sp) {
455 for (size_t i = 0; i < num_modules; i++) {
456 if (process_sp->GetObjCLanguageRuntime()->IsModuleObjCLibrary(
457 target_modules.GetModuleAtIndexUnlocked(i))) {
458 m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i);
464 if (m_objc_module_sp) {
465 ConstString trampoline_name("gdb_objc_trampolines");
466 const Symbol *trampoline_symbol =
467 m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
469 if (trampoline_symbol != NULL) {
470 m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
471 if (m_trampoline_header == LLDB_INVALID_ADDRESS)
474 // Next look up the "changed" symbol and set a breakpoint on that...
475 ConstString changed_name("gdb_objc_trampolines_changed");
476 const Symbol *changed_symbol =
477 m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
479 if (changed_symbol != NULL) {
480 const Address changed_symbol_addr = changed_symbol->GetAddress();
481 if (!changed_symbol_addr.IsValid())
484 lldb::addr_t changed_addr =
485 changed_symbol_addr.GetOpcodeLoadAddress(&target);
486 if (changed_addr != LLDB_INVALID_ADDRESS) {
487 BreakpointSP trampolines_changed_bp_sp =
488 target.CreateBreakpoint(changed_addr, true, false);
489 if (trampolines_changed_bp_sp) {
490 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
491 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
493 trampolines_changed_bp_sp->SetBreakpointKind(
494 "objc-trampolines-changed");
505 bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
506 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
507 lldb::user_id_t break_loc_id) {
508 AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
509 if (vtable_handler->InitializeVTableSymbols()) {
510 // The Update function is called with the address of an added region. So we
511 // grab that address, and
512 // feed it into ReadRegions. Of course, our friend the ABI will get the
514 ExecutionContext exe_ctx(context->exe_ctx_ref);
515 Process *process = exe_ctx.GetProcessPtr();
516 const ABI *abi = process->GetABI().get();
518 ClangASTContext *clang_ast_context =
519 process->GetTarget().GetScratchClangASTContext();
520 ValueList argument_values;
522 CompilerType clang_void_ptr_type =
523 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
525 input_value.SetValueType(Value::eValueTypeScalar);
526 // input_value.SetContext (Value::eContextTypeClangType,
527 // clang_void_ptr_type);
528 input_value.SetCompilerType(clang_void_ptr_type);
529 argument_values.PushValue(input_value);
532 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
536 // Now get a pointer value from the zeroth argument.
539 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
541 lldb::offset_t offset = 0;
542 lldb::addr_t region_addr = data.GetPointer(&offset);
544 if (region_addr != 0)
545 vtable_handler->ReadRegions(region_addr);
550 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
551 // The no argument version reads the start region from the value of the
552 // gdb_regions_header, and
553 // gets started from there.
556 if (!InitializeVTableSymbols())
559 ProcessSP process_sp = GetProcessSP();
561 lldb::addr_t region_addr =
562 process_sp->ReadPointerFromMemory(m_trampoline_header, error);
564 return ReadRegions(region_addr);
569 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
570 lldb::addr_t region_addr) {
571 ProcessSP process_sp = GetProcessSP();
575 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
577 // We aren't starting at the trampoline symbol.
578 InitializeVTableSymbols();
579 lldb::addr_t next_region = region_addr;
581 // Read in the sizes of the headers.
582 while (next_region != 0) {
583 m_regions.push_back(VTableRegion(this, next_region));
584 if (!m_regions.back().IsValid()) {
590 m_regions.back().Dump(s);
591 log->Printf("Read vtable region: \n%s", s.GetData());
594 next_region = m_regions.back().GetNextRegionAddr();
600 bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
601 lldb::addr_t addr, uint32_t &flags) {
602 region_collection::iterator pos, end = m_regions.end();
603 for (pos = m_regions.begin(); pos != end; pos++) {
604 if ((*pos).AddressInRegion(addr, flags))
610 const AppleObjCTrampolineHandler::DispatchFunction
611 AppleObjCTrampolineHandler::g_dispatch_functions[] = {
612 // NAME STRET SUPER SUPER2 FIXUP TYPE
613 {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
614 {"objc_msgSend_fixup", false, false, false,
615 DispatchFunction::eFixUpToFix},
616 {"objc_msgSend_fixedup", false, false, false,
617 DispatchFunction::eFixUpFixed},
618 {"objc_msgSend_stret", true, false, false,
619 DispatchFunction::eFixUpNone},
620 {"objc_msgSend_stret_fixup", true, false, false,
621 DispatchFunction::eFixUpToFix},
622 {"objc_msgSend_stret_fixedup", true, false, false,
623 DispatchFunction::eFixUpFixed},
624 {"objc_msgSend_fpret", false, false, false,
625 DispatchFunction::eFixUpNone},
626 {"objc_msgSend_fpret_fixup", false, false, false,
627 DispatchFunction::eFixUpToFix},
628 {"objc_msgSend_fpret_fixedup", false, false, false,
629 DispatchFunction::eFixUpFixed},
630 {"objc_msgSend_fp2ret", false, false, true,
631 DispatchFunction::eFixUpNone},
632 {"objc_msgSend_fp2ret_fixup", false, false, true,
633 DispatchFunction::eFixUpToFix},
634 {"objc_msgSend_fp2ret_fixedup", false, false, true,
635 DispatchFunction::eFixUpFixed},
636 {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
637 {"objc_msgSendSuper_stret", true, true, false,
638 DispatchFunction::eFixUpNone},
639 {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
640 {"objc_msgSendSuper2_fixup", false, true, true,
641 DispatchFunction::eFixUpToFix},
642 {"objc_msgSendSuper2_fixedup", false, true, true,
643 DispatchFunction::eFixUpFixed},
644 {"objc_msgSendSuper2_stret", true, true, true,
645 DispatchFunction::eFixUpNone},
646 {"objc_msgSendSuper2_stret_fixup", true, true, true,
647 DispatchFunction::eFixUpToFix},
648 {"objc_msgSendSuper2_stret_fixedup", true, true, true,
649 DispatchFunction::eFixUpFixed},
652 AppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
653 const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
654 : m_process_wp(), m_objc_module_sp(objc_module_sp),
655 m_lookup_implementation_function_code(nullptr),
656 m_impl_fn_addr(LLDB_INVALID_ADDRESS),
657 m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
658 m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
660 m_process_wp = process_sp;
661 // Look up the known resolution functions:
663 ConstString get_impl_name("class_getMethodImplementation");
664 ConstString get_impl_stret_name("class_getMethodImplementation_stret");
665 ConstString msg_forward_name("_objc_msgForward");
666 ConstString msg_forward_stret_name("_objc_msgForward_stret");
668 Target *target = process_sp ? &process_sp->GetTarget() : NULL;
669 const Symbol *class_getMethodImplementation =
670 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
672 const Symbol *class_getMethodImplementation_stret =
673 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
675 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
676 msg_forward_name, eSymbolTypeCode);
677 const Symbol *msg_forward_stret =
678 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
681 if (class_getMethodImplementation)
683 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
685 if (class_getMethodImplementation_stret)
686 m_impl_stret_fn_addr =
687 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
690 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
691 if (msg_forward_stret)
692 m_msg_forward_stret_addr =
693 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
695 // FIXME: Do some kind of logging here.
696 if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
697 // If we can't even find the ordinary get method implementation function,
698 // then we aren't going to be able to
699 // step through any method dispatches. Warn to that effect and get out of
701 if (process_sp->CanJIT()) {
702 process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf(
703 "Could not find implementation lookup function \"%s\""
704 " step in through ObjC method dispatch will not work.\n",
705 get_impl_name.AsCString());
708 } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
709 // It there is no stret return lookup function, assume that it is the same
710 // as the straight lookup:
711 m_impl_stret_fn_addr = m_impl_fn_addr;
712 // Also we will use the version of the lookup code that doesn't rely on the
713 // stret version of the function.
714 m_lookup_implementation_function_code =
715 g_lookup_implementation_no_stret_function_code;
717 m_lookup_implementation_function_code =
718 g_lookup_implementation_with_stret_function_code;
721 // Look up the addresses for the objc dispatch functions and cache them. For
722 // now I'm inspecting the symbol
723 // names dynamically to figure out how to dispatch to them. If it becomes
724 // more complicated than this we can
725 // turn the g_dispatch_functions char * array into a template table, and
726 // populate the DispatchFunction map
729 for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
730 ConstString name_const_str(g_dispatch_functions[i].name);
731 const Symbol *msgSend_symbol =
732 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
734 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
735 // FixMe: Make g_dispatch_functions static table of DispatchFunctions, and
736 // have the map be address->index.
737 // Problem is we also need to lookup the dispatch function. For now we
738 // could have a side table of stret & non-stret
739 // dispatch functions. If that's as complex as it gets, we're fine.
741 lldb::addr_t sym_addr =
742 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
744 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
748 // Build our vtable dispatch handler here:
749 m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
750 if (m_vtables_ap.get())
751 m_vtables_ap->ReadRegions();
755 AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
756 ValueList &dispatch_values) {
757 ThreadSP thread_sp(thread.shared_from_this());
758 ExecutionContext exe_ctx(thread_sp);
759 DiagnosticManager diagnostics;
760 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
762 lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
763 FunctionCaller *impl_function_caller = nullptr;
765 // Scope for mutex locker:
767 std::lock_guard<std::mutex> guard(m_impl_function_mutex);
769 // First stage is to make the ClangUtility to hold our injected function:
771 if (!m_impl_code.get()) {
772 if (m_lookup_implementation_function_code != NULL) {
774 m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
775 m_lookup_implementation_function_code, eLanguageTypeObjC,
776 g_lookup_implementation_function_name, error));
780 "Failed to get Utility Function for implementation lookup: %s.",
786 if (!m_impl_code->Install(diagnostics, exe_ctx)) {
788 log->Printf("Failed to install implementation lookup.");
789 diagnostics.Dump(log);
796 log->Printf("No method lookup implementation code.");
797 return LLDB_INVALID_ADDRESS;
800 // Next make the runner function for our implementation utility function.
801 ClangASTContext *clang_ast_context =
802 thread.GetProcess()->GetTarget().GetScratchClangASTContext();
803 CompilerType clang_void_ptr_type =
804 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
807 impl_function_caller = m_impl_code->MakeFunctionCaller(
808 clang_void_ptr_type, dispatch_values, thread_sp, error);
812 "Error getting function caller for dispatch lookup: \"%s\".",
817 impl_function_caller = m_impl_code->GetFunctionCaller();
823 // Now write down the argument values for this particular call. This looks
824 // like it might be a race condition
825 // if other threads were calling into here, but actually it isn't because we
826 // allocate a new args structure for
827 // this call by passing args_addr = LLDB_INVALID_ADDRESS...
829 if (!impl_function_caller->WriteFunctionArguments(
830 exe_ctx, args_addr, dispatch_values, diagnostics)) {
832 log->Printf("Error writing function arguments.");
833 diagnostics.Dump(log);
842 AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
844 ThreadPlanSP ret_plan_sp;
845 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
847 DispatchFunction this_dispatch;
848 bool found_it = false;
850 // First step is to look and see if we are in one of the known ObjC dispatch
851 // functions. We've already compiled
852 // a table of same, so consult it.
854 MsgsendMap::iterator pos;
855 pos = m_msgSend_map.find(curr_pc);
856 if (pos != m_msgSend_map.end()) {
857 this_dispatch = g_dispatch_functions[(*pos).second];
861 // Next check to see if we are in a vtable region:
865 if (m_vtables_ap.get()) {
866 found_it = m_vtables_ap->IsAddressInVTables(curr_pc, flags);
868 this_dispatch.name = "vtable";
869 this_dispatch.stret_return =
870 (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
871 AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
872 this_dispatch.is_super = false;
873 this_dispatch.is_super2 = false;
874 this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
880 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
882 // We are decoding a method dispatch.
883 // First job is to pull the arguments out:
885 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
887 const ABI *abi = NULL;
888 ProcessSP process_sp(thread.CalculateProcess());
890 abi = process_sp->GetABI().get();
894 TargetSP target_sp(thread.CalculateTarget());
896 ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
897 ValueList argument_values;
898 Value void_ptr_value;
899 CompilerType clang_void_ptr_type =
900 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
901 void_ptr_value.SetValueType(Value::eValueTypeScalar);
902 // void_ptr_value.SetContext (Value::eContextTypeClangType,
903 // clang_void_ptr_type);
904 void_ptr_value.SetCompilerType(clang_void_ptr_type);
909 // If this is a struct return dispatch, then the first argument is the
910 // return struct pointer, and the object is the second, and the selector is
912 // Otherwise the object is the first and the selector the second.
913 if (this_dispatch.stret_return) {
916 argument_values.PushValue(void_ptr_value);
917 argument_values.PushValue(void_ptr_value);
918 argument_values.PushValue(void_ptr_value);
922 argument_values.PushValue(void_ptr_value);
923 argument_values.PushValue(void_ptr_value);
926 bool success = abi->GetArgumentValues(thread, argument_values);
930 lldb::addr_t obj_addr =
931 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
932 if (obj_addr == 0x0) {
935 "Asked to step to dispatch to nil object, returning empty plan.");
939 ExecutionContext exe_ctx(thread.shared_from_this());
940 Process *process = exe_ctx.GetProcessPtr();
941 // isa_addr will store the class pointer that the method is being dispatched
942 // to - so either the class
943 // directly or the super class if this is one of the objc_msgSendSuper
944 // flavors. That's mostly used to
945 // look up the class/selector pair in our cache.
947 lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
948 lldb::addr_t sel_addr =
949 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
951 // Figure out the class this is being dispatched to and see if we've already
952 // cached this method call,
953 // If so we can push a run-to-address plan directly. Otherwise we have to
955 // the implementation lives.
957 if (this_dispatch.is_super) {
958 if (this_dispatch.is_super2) {
959 // In the objc_msgSendSuper2 case, we don't get the object directly, we
960 // get a structure containing
961 // the object and the class to which the super message is being sent.
962 // So we need to dig the super
963 // out of the class and use that.
965 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
966 super_value.GetScalar() += process->GetAddressByteSize();
967 super_value.ResolveValue(&exe_ctx);
969 if (super_value.GetScalar().IsValid()) {
971 // isa_value now holds the class pointer. The second word of the
972 // class pointer is the super-class pointer:
973 super_value.GetScalar() += process->GetAddressByteSize();
974 super_value.ResolveValue(&exe_ctx);
975 if (super_value.GetScalar().IsValid())
976 isa_addr = super_value.GetScalar().ULongLong();
979 log->Printf("Failed to extract the super class value from the "
980 "class in objc_super.");
984 log->Printf("Failed to extract the class value from objc_super.");
987 // In the objc_msgSendSuper case, we don't get the object directly, we
988 // get a two element structure containing
989 // the object and the super class to which the super message is being
990 // sent. So the class we want is
991 // the second element of this structure.
993 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
994 super_value.GetScalar() += process->GetAddressByteSize();
995 super_value.ResolveValue(&exe_ctx);
997 if (super_value.GetScalar().IsValid()) {
998 isa_addr = super_value.GetScalar().ULongLong();
1001 log->Printf("Failed to extract the class value from objc_super.");
1005 // In the direct dispatch case, the object->isa is the class pointer we
1008 // This is a little cheesy, but since object->isa is the first field,
1009 // making the object value a load address value and resolving it will get
1010 // the pointer sized data pointed to by that value...
1012 // Note, it isn't a fatal error not to be able to get the address from the
1013 // object, since this might
1014 // be a "tagged pointer" which isn't a real object, but rather some word
1015 // length encoded dingus.
1017 Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1019 isa_value.SetValueType(Value::eValueTypeLoadAddress);
1020 isa_value.ResolveValue(&exe_ctx);
1021 if (isa_value.GetScalar().IsValid()) {
1022 isa_addr = isa_value.GetScalar().ULongLong();
1025 log->Printf("Failed to extract the isa value from object.");
1029 // Okay, we've got the address of the class for which we're resolving this,
1030 // let's see if it's in our cache:
1031 lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1033 if (isa_addr != LLDB_INVALID_ADDRESS) {
1035 log->Printf("Resolving call for class - 0x%" PRIx64
1036 " and selector - 0x%" PRIx64,
1037 isa_addr, sel_addr);
1039 ObjCLanguageRuntime *objc_runtime =
1040 thread.GetProcess()->GetObjCLanguageRuntime();
1041 assert(objc_runtime != NULL);
1043 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1046 if (impl_addr != LLDB_INVALID_ADDRESS) {
1047 // Yup, it was in the cache, so we can run to that address directly.
1050 log->Printf("Found implementation address in cache: 0x%" PRIx64,
1054 new ThreadPlanRunToAddress(thread, impl_addr, stop_others));
1056 // We haven't seen this class/selector pair yet. Look it up.
1057 StreamString errors;
1058 Address impl_code_address;
1060 ValueList dispatch_values;
1062 // We've will inject a little function in the target that takes the
1063 // object, selector and some flags,
1064 // and figures out the implementation. Looks like:
1065 // void *__lldb_objc_find_implementation_for_selector (void *object,
1073 // So set up the arguments for that call.
1075 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1076 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1079 CompilerType clang_int_type =
1080 clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1081 lldb::eEncodingSint, 32);
1082 flag_value.SetValueType(Value::eValueTypeScalar);
1083 // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1084 flag_value.SetCompilerType(clang_int_type);
1086 if (this_dispatch.stret_return)
1087 flag_value.GetScalar() = 1;
1089 flag_value.GetScalar() = 0;
1090 dispatch_values.PushValue(flag_value);
1092 if (this_dispatch.is_super)
1093 flag_value.GetScalar() = 1;
1095 flag_value.GetScalar() = 0;
1096 dispatch_values.PushValue(flag_value);
1098 if (this_dispatch.is_super2)
1099 flag_value.GetScalar() = 1;
1101 flag_value.GetScalar() = 0;
1102 dispatch_values.PushValue(flag_value);
1104 switch (this_dispatch.fixedup) {
1105 case DispatchFunction::eFixUpNone:
1106 flag_value.GetScalar() = 0;
1107 dispatch_values.PushValue(flag_value);
1108 dispatch_values.PushValue(flag_value);
1110 case DispatchFunction::eFixUpFixed:
1111 flag_value.GetScalar() = 1;
1112 dispatch_values.PushValue(flag_value);
1113 flag_value.GetScalar() = 1;
1114 dispatch_values.PushValue(flag_value);
1116 case DispatchFunction::eFixUpToFix:
1117 flag_value.GetScalar() = 1;
1118 dispatch_values.PushValue(flag_value);
1119 flag_value.GetScalar() = 0;
1120 dispatch_values.PushValue(flag_value);
1123 if (log && log->GetVerbose())
1124 flag_value.GetScalar() = 1;
1126 flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1127 dispatch_values.PushValue(flag_value);
1129 // The step through code might have to fill in the cache, so it is not
1130 // safe to run only one thread.
1131 // So we override the stop_others value passed in to us here:
1132 const bool trampoline_stop_others = false;
1133 ret_plan_sp.reset(new AppleThreadPlanStepThroughObjCTrampoline(
1134 thread, this, dispatch_values, isa_addr, sel_addr,
1135 trampoline_stop_others));
1138 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1139 log->Printf("Using ObjC step plan: %s.\n", s.GetData());
1148 AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1149 return m_impl_code->GetFunctionCaller();