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 
9 #include "AppleObjCTrampolineHandler.h"
10 #include "AppleThreadPlanStepThroughObjCTrampoline.h"
11 
12 #include "Plugins/TypeSystem/Clang/TypeSystemClang.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/Symbol.h"
23 #include "lldb/Target/ABI.h"
24 #include "lldb/Target/ExecutionContext.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/ThreadPlanRunToAddress.h"
30 #include "lldb/Utility/ConstString.h"
31 #include "lldb/Utility/FileSpec.h"
32 #include "lldb/Utility/LLDBLog.h"
33 #include "lldb/Utility/Log.h"
34 
35 #include "llvm/ADT/STLExtras.h"
36 
37 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
38 
39 #include <memory>
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
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 =
48         "                               \n\
49 extern \"C\"                                                                 \n\
50 {                                                                            \n\
51     extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
52     extern void *class_getMethodImplementation_stret(void *objc_class,       \n\
53                                                      void *sel);             \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\
57 }                                                                            \n\
58 extern \"C\" void * __lldb_objc_find_implementation_for_selector (           \n\
59                                                     void *object,            \n\
60                                                     void *sel,               \n\
61                                                     int is_stret,            \n\
62                                                     int is_super,            \n\
63                                                     int is_super2,           \n\
64                                                     int is_fixup,            \n\
65                                                     int is_fixed,            \n\
66                                                     int debug)               \n\
67 {                                                                            \n\
68     struct __lldb_imp_return_struct                                          \n\
69     {                                                                        \n\
70         void *class_addr;                                                    \n\
71         void *sel_addr;                                                      \n\
72         void *impl_addr;                                                     \n\
73     };                                                                       \n\
74                                                                              \n\
75     struct __lldb_objc_class {                                               \n\
76         void *isa;                                                           \n\
77         void *super_ptr;                                                     \n\
78     };                                                                       \n\
79     struct __lldb_objc_super {                                               \n\
80         void *receiver;                                                      \n\
81         struct __lldb_objc_class *class_ptr;                                 \n\
82     };                                                                       \n\
83     struct __lldb_msg_ref {                                                  \n\
84         void *dont_know;                                                     \n\
85         void *sel;                                                           \n\
86     };                                                                       \n\
87                                                                              \n\
88     struct __lldb_imp_return_struct return_struct;                           \n\
89                                                                              \n\
90     if (debug)                                                               \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\
94     if (is_super)                                                            \n\
95     {                                                                        \n\
96         if (is_super2)                                                       \n\
97         {                                                                    \n\
98             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;\n\
99         }                                                                    \n\
100         else                                                                 \n\
101         {                                                                    \n\
102             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;\n\
103         }                                                                    \n\
104     }                                                                        \n\
105     else                                                                     \n\
106     {                                                                        \n\
107         // This code seems a little funny, but has its reasons...            \n\
108                                                                              \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\
117         if (debug)                                                           \n\
118         {                                                                    \n\
119             if (class_ptr == object)                                         \n\
120             {                                                                \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\
123             }                                                                \n\
124             else                                                             \n\
125             {                                                                \n\
126                  printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
127                  class_ptr, return_struct.class_addr);                       \n\
128             }                                                                \n\
129         }                                                                    \n\
130     }                                                                        \n\
131                                                                              \n\
132     if (is_fixup)                                                            \n\
133     {                                                                        \n\
134         if (is_fixed)                                                        \n\
135         {                                                                    \n\
136             return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
137         }                                                                    \n\
138         else                                                                 \n\
139         {                                                                    \n\
140             char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
141             return_struct.sel_addr = sel_getUid (sel_name);                  \n\
142             if (debug)                                                       \n\
143                 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
144                         return_struct.sel_addr, sel_name);                   \n\
145         }                                                                    \n\
146     }                                                                        \n\
147     else                                                                     \n\
148     {                                                                        \n\
149         return_struct.sel_addr = sel;                                        \n\
150     }                                                                        \n\
151                                                                              \n\
152     if (is_stret)                                                            \n\
153     {                                                                        \n\
154         return_struct.impl_addr =                                            \n\
155           class_getMethodImplementation_stret (return_struct.class_addr,     \n\
156                                                return_struct.sel_addr);      \n\
157     }                                                                        \n\
158     else                                                                     \n\
159     {                                                                        \n\
160         return_struct.impl_addr =                                            \n\
161             class_getMethodImplementation (return_struct.class_addr,         \n\
162                                            return_struct.sel_addr);          \n\
163     }                                                                        \n\
164     if (debug)                                                               \n\
165         printf (\"\\n*** Returning implementation: %p.\\n\",                 \n\
166                           return_struct.impl_addr);                          \n\
167                                                                              \n\
168     return return_struct.impl_addr;                                          \n\
169 }                                                                            \n\
170 ";
171 const char *
172     AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =
173         "                      \n\
174 extern \"C\"                                                                 \n\
175 {                                                                            \n\
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\
180 }                                                                            \n\
181 extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object,                                 \n\
182                                                     void *sel,               \n\
183                                                     int is_stret,            \n\
184                                                     int is_super,            \n\
185                                                     int is_super2,           \n\
186                                                     int is_fixup,            \n\
187                                                     int is_fixed,            \n\
188                                                     int debug)               \n\
189 {                                                                            \n\
190     struct __lldb_imp_return_struct                                          \n\
191     {                                                                        \n\
192         void *class_addr;                                                    \n\
193         void *sel_addr;                                                      \n\
194         void *impl_addr;                                                     \n\
195     };                                                                       \n\
196                                                                              \n\
197     struct __lldb_objc_class {                                               \n\
198         void *isa;                                                           \n\
199         void *super_ptr;                                                     \n\
200     };                                                                       \n\
201     struct __lldb_objc_super {                                               \n\
202         void *receiver;                                                      \n\
203         struct __lldb_objc_class *class_ptr;                                 \n\
204     };                                                                       \n\
205     struct __lldb_msg_ref {                                                  \n\
206         void *dont_know;                                                     \n\
207         void *sel;                                                           \n\
208     };                                                                       \n\
209                                                                              \n\
210     struct __lldb_imp_return_struct return_struct;                           \n\
211                                                                              \n\
212     if (debug)                                                               \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\
216     if (is_super)                                                            \n\
217     {                                                                        \n\
218         if (is_super2)                                                       \n\
219         {                                                                    \n\
220             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;                    \n\
221         }                                                                    \n\
222         else                                                                 \n\
223         {                                                                    \n\
224             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;                               \n\
225         }                                                                    \n\
226     }                                                                        \n\
227     else                                                                     \n\
228     {                                                                        \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\
236         if (debug)                                                           \n\
237         {                                                                    \n\
238             if (class_ptr == object)                                         \n\
239             {                                                                \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\
242             }                                                                \n\
243             else                                                             \n\
244             {                                                                \n\
245                  printf (\"[object class] returned: %p object_getClass: %p.\\n\",                               \n\
246                  class_ptr, return_struct.class_addr);                       \n\
247             }                                                                \n\
248         }                                                                    \n\
249     }                                                                        \n\
250                                                                              \n\
251     if (is_fixup)                                                            \n\
252     {                                                                        \n\
253         if (is_fixed)                                                        \n\
254         {                                                                    \n\
255             return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
256         }                                                                    \n\
257         else                                                                 \n\
258         {                                                                    \n\
259             char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
260             return_struct.sel_addr = sel_getUid (sel_name);                  \n\
261             if (debug)                                                       \n\
262                 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
263                         return_struct.sel_addr, sel_name);                   \n\
264         }                                                                    \n\
265     }                                                                        \n\
266     else                                                                     \n\
267     {                                                                        \n\
268         return_struct.sel_addr = sel;                                        \n\
269     }                                                                        \n\
270                                                                              \n\
271     return_struct.impl_addr =                                                \n\
272       class_getMethodImplementation (return_struct.class_addr,               \n\
273                                      return_struct.sel_addr);                \n\
274     if (debug)                                                               \n\
275         printf (\"\\n*** Returning implementation: 0x%p.\\n\",               \n\
276           return_struct.impl_addr);                                          \n\
277                                                                              \n\
278     return return_struct.impl_addr;                                          \n\
279 }                                                                            \n\
280 ";
281 
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) {
286   SetUpRegion();
287 }
288 
289 AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() = default;
290 
291 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {
292   // The header looks like:
293   //
294   //   uint16_t headerSize
295   //   uint16_t descSize
296   //   uint32_t descCount
297   //   void * next
298   //
299   // First read in the header:
300 
301   char memory_buffer[16];
302   ProcessSP process_sp = m_owner->GetProcessSP();
303   if (!process_sp)
304     return;
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();
309   Status error;
310   size_t bytes_read =
311       process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
312   if (bytes_read != actual_size) {
313     m_valid = false;
314     return;
315   }
316 
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);
321 
322   m_next_region = data.GetAddress(&offset);
323 
324   // If the header size is 0, that means we've come in too early before this
325   // data is set up.
326   // Set ourselves as not valid, and continue.
327   if (header_size == 0 || num_descriptors == 0) {
328     m_valid = false;
329     return;
330   }
331 
332   // Now read in all the descriptors:
333   // The descriptor looks like:
334   //
335   // uint32_t offset
336   // uint32_t flags
337   //
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
342   // over.
343 
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();
349 
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) {
354     m_valid = false;
355     return;
356   }
357 
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.
360 
361   offset = 0;
362   m_code_start_addr = 0;
363   m_code_end_addr = 0;
364 
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));
371 
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;
376 
377     offset = start_offset + descriptor_size;
378   }
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;
387     if (code_size == 0)
388       code_size = this_size;
389     else {
390       if (this_size != code_size)
391         all_the_same = false;
392       if (this_size > code_size)
393         code_size = this_size;
394     }
395   }
396   if (all_the_same)
397     m_code_end_addr += code_size;
398 }
399 
400 bool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::
401     AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
402   if (!IsValid())
403     return false;
404 
405   if (addr < m_code_start_addr || addr > m_code_end_addr)
406     return false;
407 
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;
412       return true;
413     }
414   }
415   return false;
416 }
417 
418 void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(
419     Stream &s) {
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++) {
425     s.Indent();
426     s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
427              m_descriptors[i].code_start, m_descriptors[i].flags);
428   }
429 }
430 
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) {
436   if (process_sp)
437     m_process_wp = process_sp;
438 }
439 
440 AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {
441   ProcessSP process_sp = GetProcessSP();
442   if (process_sp) {
443     if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
444       process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
445   }
446 }
447 
448 bool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {
449   if (m_trampoline_header != LLDB_INVALID_ADDRESS)
450     return true;
451 
452   ProcessSP process_sp = GetProcessSP();
453   if (process_sp) {
454     Target &target = process_sp->GetTarget();
455 
456     if (!m_objc_module_sp) {
457       for (ModuleSP module_sp : target.GetImages().Modules()) {
458         if (ObjCLanguageRuntime::Get(*process_sp)
459                 ->IsModuleObjCLibrary(module_sp)) {
460           m_objc_module_sp = module_sp;
461           break;
462         }
463       }
464     }
465 
466     if (m_objc_module_sp) {
467       ConstString trampoline_name("gdb_objc_trampolines");
468       const Symbol *trampoline_symbol =
469           m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
470                                                            eSymbolTypeData);
471       if (trampoline_symbol != nullptr) {
472         m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
473         if (m_trampoline_header == LLDB_INVALID_ADDRESS)
474           return false;
475 
476         // Next look up the "changed" symbol and set a breakpoint on that...
477         ConstString changed_name("gdb_objc_trampolines_changed");
478         const Symbol *changed_symbol =
479             m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
480                                                              eSymbolTypeCode);
481         if (changed_symbol != nullptr) {
482           const Address changed_symbol_addr = changed_symbol->GetAddress();
483           if (!changed_symbol_addr.IsValid())
484             return false;
485 
486           lldb::addr_t changed_addr =
487               changed_symbol_addr.GetOpcodeLoadAddress(&target);
488           if (changed_addr != LLDB_INVALID_ADDRESS) {
489             BreakpointSP trampolines_changed_bp_sp =
490                 target.CreateBreakpoint(changed_addr, true, false);
491             if (trampolines_changed_bp_sp) {
492               m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
493               trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
494                                                      true);
495               trampolines_changed_bp_sp->SetBreakpointKind(
496                   "objc-trampolines-changed");
497               return true;
498             }
499           }
500         }
501       }
502     }
503   }
504   return false;
505 }
506 
507 bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
508     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
509     lldb::user_id_t break_loc_id) {
510   AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
511   if (vtable_handler->InitializeVTableSymbols()) {
512     // The Update function is called with the address of an added region.  So we
513     // grab that address, and
514     // feed it into ReadRegions.  Of course, our friend the ABI will get the
515     // values for us.
516     ExecutionContext exe_ctx(context->exe_ctx_ref);
517     Process *process = exe_ctx.GetProcessPtr();
518     const ABI *abi = process->GetABI().get();
519 
520     TypeSystemClang *clang_ast_context =
521         ScratchTypeSystemClang::GetForTarget(process->GetTarget());
522     if (!clang_ast_context)
523       return false;
524 
525     ValueList argument_values;
526     Value input_value;
527     CompilerType clang_void_ptr_type =
528         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
529 
530     input_value.SetValueType(Value::ValueType::Scalar);
531     // input_value.SetContext (Value::eContextTypeClangType,
532     // clang_void_ptr_type);
533     input_value.SetCompilerType(clang_void_ptr_type);
534     argument_values.PushValue(input_value);
535 
536     bool success =
537         abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
538     if (!success)
539       return false;
540 
541     // Now get a pointer value from the zeroth argument.
542     Status error;
543     DataExtractor data;
544     error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
545                                                                nullptr);
546     lldb::offset_t offset = 0;
547     lldb::addr_t region_addr = data.GetAddress(&offset);
548 
549     if (region_addr != 0)
550       vtable_handler->ReadRegions(region_addr);
551   }
552   return false;
553 }
554 
555 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
556   // The no argument version reads the  start region from the value of
557   // the gdb_regions_header, and gets started from there.
558 
559   m_regions.clear();
560   if (!InitializeVTableSymbols())
561     return false;
562   Status error;
563   ProcessSP process_sp = GetProcessSP();
564   if (process_sp) {
565     lldb::addr_t region_addr =
566         process_sp->ReadPointerFromMemory(m_trampoline_header, error);
567     if (error.Success())
568       return ReadRegions(region_addr);
569   }
570   return false;
571 }
572 
573 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
574     lldb::addr_t region_addr) {
575   ProcessSP process_sp = GetProcessSP();
576   if (!process_sp)
577     return false;
578 
579   Log *log = GetLog(LLDBLog::Step);
580 
581   // We aren't starting at the trampoline symbol.
582   InitializeVTableSymbols();
583   lldb::addr_t next_region = region_addr;
584 
585   // Read in the sizes of the headers.
586   while (next_region != 0) {
587     m_regions.push_back(VTableRegion(this, next_region));
588     if (!m_regions.back().IsValid()) {
589       m_regions.clear();
590       return false;
591     }
592     if (log) {
593       StreamString s;
594       m_regions.back().Dump(s);
595       LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());
596     }
597 
598     next_region = m_regions.back().GetNextRegionAddr();
599   }
600 
601   return true;
602 }
603 
604 bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
605     lldb::addr_t addr, uint32_t &flags) {
606   region_collection::iterator pos, end = m_regions.end();
607   for (pos = m_regions.begin(); pos != end; pos++) {
608     if ((*pos).AddressInRegion(addr, flags))
609       return true;
610   }
611   return false;
612 }
613 
614 const AppleObjCTrampolineHandler::DispatchFunction
615     AppleObjCTrampolineHandler::g_dispatch_functions[] = {
616         // NAME                              STRET  SUPER  SUPER2  FIXUP TYPE
617         {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
618         {"objc_msgSend_fixup", false, false, false,
619          DispatchFunction::eFixUpToFix},
620         {"objc_msgSend_fixedup", false, false, false,
621          DispatchFunction::eFixUpFixed},
622         {"objc_msgSend_stret", true, false, false,
623          DispatchFunction::eFixUpNone},
624         {"objc_msgSend_stret_fixup", true, false, false,
625          DispatchFunction::eFixUpToFix},
626         {"objc_msgSend_stret_fixedup", true, false, false,
627          DispatchFunction::eFixUpFixed},
628         {"objc_msgSend_fpret", false, false, false,
629          DispatchFunction::eFixUpNone},
630         {"objc_msgSend_fpret_fixup", false, false, false,
631          DispatchFunction::eFixUpToFix},
632         {"objc_msgSend_fpret_fixedup", false, false, false,
633          DispatchFunction::eFixUpFixed},
634         {"objc_msgSend_fp2ret", false, false, true,
635          DispatchFunction::eFixUpNone},
636         {"objc_msgSend_fp2ret_fixup", false, false, true,
637          DispatchFunction::eFixUpToFix},
638         {"objc_msgSend_fp2ret_fixedup", false, false, true,
639          DispatchFunction::eFixUpFixed},
640         {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
641         {"objc_msgSendSuper_stret", true, true, false,
642          DispatchFunction::eFixUpNone},
643         {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
644         {"objc_msgSendSuper2_fixup", false, true, true,
645          DispatchFunction::eFixUpToFix},
646         {"objc_msgSendSuper2_fixedup", false, true, true,
647          DispatchFunction::eFixUpFixed},
648         {"objc_msgSendSuper2_stret", true, true, true,
649          DispatchFunction::eFixUpNone},
650         {"objc_msgSendSuper2_stret_fixup", true, true, true,
651          DispatchFunction::eFixUpToFix},
652         {"objc_msgSendSuper2_stret_fixedup", true, true, true,
653          DispatchFunction::eFixUpFixed},
654 };
655 
656 // This is the table of ObjC "accelerated dispatch" functions.  They are a set
657 // of objc methods that are "seldom overridden" and so the compiler replaces the
658 // objc_msgSend with a call to one of the dispatch functions.  That will check
659 // whether the method has been overridden, and directly call the Foundation
660 // implementation if not.
661 // This table is supposed to be complete.  If ones get added in the future, we
662 // will have to add them to the table.
663 const char *AppleObjCTrampolineHandler::g_opt_dispatch_names[] = {
664     "objc_alloc",
665     "objc_autorelease",
666     "objc_release",
667     "objc_retain",
668     "objc_alloc_init",
669     "objc_allocWithZone",
670     "objc_opt_class",
671     "objc_opt_isKindOfClass",
672     "objc_opt_new",
673     "objc_opt_respondsToSelector",
674     "objc_opt_self",
675 };
676 
677 AppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
678     const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
679     : m_process_wp(), m_objc_module_sp(objc_module_sp),
680       m_lookup_implementation_function_code(nullptr),
681       m_impl_fn_addr(LLDB_INVALID_ADDRESS),
682       m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
683       m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
684   if (process_sp)
685     m_process_wp = process_sp;
686   // Look up the known resolution functions:
687 
688   ConstString get_impl_name("class_getMethodImplementation");
689   ConstString get_impl_stret_name("class_getMethodImplementation_stret");
690   ConstString msg_forward_name("_objc_msgForward");
691   ConstString msg_forward_stret_name("_objc_msgForward_stret");
692 
693   Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
694   const Symbol *class_getMethodImplementation =
695       m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
696                                                        eSymbolTypeCode);
697   const Symbol *class_getMethodImplementation_stret =
698       m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
699                                                        eSymbolTypeCode);
700   const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
701       msg_forward_name, eSymbolTypeCode);
702   const Symbol *msg_forward_stret =
703       m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
704                                                        eSymbolTypeCode);
705 
706   if (class_getMethodImplementation)
707     m_impl_fn_addr =
708         class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
709             target);
710   if (class_getMethodImplementation_stret)
711     m_impl_stret_fn_addr =
712         class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
713             target);
714   if (msg_forward)
715     m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
716   if (msg_forward_stret)
717     m_msg_forward_stret_addr =
718         msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
719 
720   // FIXME: Do some kind of logging here.
721   if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
722     // If we can't even find the ordinary get method implementation function,
723     // then we aren't going to be able to
724     // step through any method dispatches.  Warn to that effect and get out of
725     // here.
726     if (process_sp->CanJIT()) {
727       process_sp->GetTarget().GetDebugger().GetErrorStream().Printf(
728           "Could not find implementation lookup function \"%s\""
729           " step in through ObjC method dispatch will not work.\n",
730           get_impl_name.AsCString());
731     }
732     return;
733   } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
734     // It there is no stret return lookup function, assume that it is the same
735     // as the straight lookup:
736     m_impl_stret_fn_addr = m_impl_fn_addr;
737     // Also we will use the version of the lookup code that doesn't rely on the
738     // stret version of the function.
739     m_lookup_implementation_function_code =
740         g_lookup_implementation_no_stret_function_code;
741   } else {
742     m_lookup_implementation_function_code =
743         g_lookup_implementation_with_stret_function_code;
744   }
745 
746   // Look up the addresses for the objc dispatch functions and cache
747   // them.  For now I'm inspecting the symbol names dynamically to
748   // figure out how to dispatch to them.  If it becomes more
749   // complicated than this we can turn the g_dispatch_functions char *
750   // array into a template table, and populate the DispatchFunction
751   // map from there.
752 
753   for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
754     ConstString name_const_str(g_dispatch_functions[i].name);
755     const Symbol *msgSend_symbol =
756         m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
757                                                          eSymbolTypeCode);
758     if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
759       // FIXME: Make g_dispatch_functions static table of
760       // DispatchFunctions, and have the map be address->index.
761       // Problem is we also need to lookup the dispatch function.  For
762       // now we could have a side table of stret & non-stret dispatch
763       // functions.  If that's as complex as it gets, we're fine.
764 
765       lldb::addr_t sym_addr =
766           msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
767 
768       m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
769     }
770   }
771 
772   // Similarly, cache the addresses of the "optimized dispatch" function.
773   for (size_t i = 0; i != llvm::array_lengthof(g_opt_dispatch_names); i++) {
774     ConstString name_const_str(g_opt_dispatch_names[i]);
775     const Symbol *msgSend_symbol =
776         m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
777                                                          eSymbolTypeCode);
778     if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
779       lldb::addr_t sym_addr =
780           msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
781 
782       m_opt_dispatch_map.emplace(sym_addr, i);
783     }
784   }
785 
786   // Build our vtable dispatch handler here:
787   m_vtables_up =
788       std::make_unique<AppleObjCVTables>(process_sp, m_objc_module_sp);
789   if (m_vtables_up)
790     m_vtables_up->ReadRegions();
791 }
792 
793 lldb::addr_t
794 AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
795                                                   ValueList &dispatch_values) {
796   ThreadSP thread_sp(thread.shared_from_this());
797   ExecutionContext exe_ctx(thread_sp);
798   Log *log = GetLog(LLDBLog::Step);
799 
800   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
801   FunctionCaller *impl_function_caller = nullptr;
802 
803   // Scope for mutex locker:
804   {
805     std::lock_guard<std::mutex> guard(m_impl_function_mutex);
806 
807     // First stage is to make the ClangUtility to hold our injected function:
808 
809     if (!m_impl_code) {
810       if (m_lookup_implementation_function_code != nullptr) {
811         auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
812             m_lookup_implementation_function_code,
813             g_lookup_implementation_function_name, eLanguageTypeC, exe_ctx);
814         if (!utility_fn_or_error) {
815           LLDB_LOG_ERROR(
816               log, utility_fn_or_error.takeError(),
817               "Failed to get Utility Function for implementation lookup: {0}.");
818           return args_addr;
819         }
820         m_impl_code = std::move(*utility_fn_or_error);
821       } else {
822         LLDB_LOGF(log, "No method lookup implementation code.");
823         return LLDB_INVALID_ADDRESS;
824       }
825 
826       // Next make the runner function for our implementation utility function.
827       TypeSystemClang *clang_ast_context = ScratchTypeSystemClang::GetForTarget(
828           thread.GetProcess()->GetTarget());
829       if (!clang_ast_context)
830         return LLDB_INVALID_ADDRESS;
831 
832       CompilerType clang_void_ptr_type =
833           clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
834       Status error;
835 
836       impl_function_caller = m_impl_code->MakeFunctionCaller(
837           clang_void_ptr_type, dispatch_values, thread_sp, error);
838       if (error.Fail()) {
839         LLDB_LOGF(log,
840                   "Error getting function caller for dispatch lookup: \"%s\".",
841                   error.AsCString());
842         return args_addr;
843       }
844     } else {
845       impl_function_caller = m_impl_code->GetFunctionCaller();
846     }
847   }
848 
849   // Now write down the argument values for this particular call.
850   // This looks like it might be a race condition if other threads
851   // were calling into here, but actually it isn't because we allocate
852   // a new args structure for this call by passing args_addr =
853   // LLDB_INVALID_ADDRESS...
854 
855   DiagnosticManager diagnostics;
856   if (!impl_function_caller->WriteFunctionArguments(
857           exe_ctx, args_addr, dispatch_values, diagnostics)) {
858     if (log) {
859       LLDB_LOGF(log, "Error writing function arguments.");
860       diagnostics.Dump(log);
861     }
862     return args_addr;
863   }
864 
865   return args_addr;
866 }
867 
868 const AppleObjCTrampolineHandler::DispatchFunction *
869 AppleObjCTrampolineHandler::FindDispatchFunction(lldb::addr_t addr) {
870   MsgsendMap::iterator pos;
871   pos = m_msgSend_map.find(addr);
872   if (pos != m_msgSend_map.end()) {
873     return &g_dispatch_functions[(*pos).second];
874   }
875   return nullptr;
876 }
877 
878 void
879 AppleObjCTrampolineHandler::ForEachDispatchFunction(
880     std::function<void(lldb::addr_t,
881                        const DispatchFunction &)> callback) {
882   for (auto elem : m_msgSend_map) {
883     callback(elem.first, g_dispatch_functions[elem.second]);
884   }
885 }
886 
887 ThreadPlanSP
888 AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
889                                                        bool stop_others) {
890   ThreadPlanSP ret_plan_sp;
891   lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
892 
893   DispatchFunction vtable_dispatch = {"vtable", false, false, false,
894                                       DispatchFunction::eFixUpFixed};
895 
896   // First step is to look and see if we are in one of the known ObjC
897   // dispatch functions.  We've already compiled a table of same, so
898   // consult it.
899 
900   const DispatchFunction *this_dispatch = FindDispatchFunction(curr_pc);
901 
902   // Next check to see if we are in a vtable region:
903 
904   if (!this_dispatch && m_vtables_up) {
905     uint32_t flags;
906     if (m_vtables_up->IsAddressInVTables(curr_pc, flags)) {
907       vtable_dispatch.stret_return =
908           (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
909           AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
910       this_dispatch = &vtable_dispatch;
911     }
912   }
913 
914   if (this_dispatch) {
915     Log *log = GetLog(LLDBLog::Step);
916 
917     // We are decoding a method dispatch.  First job is to pull the
918     // arguments out:
919 
920     lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
921 
922     const ABI *abi = nullptr;
923     ProcessSP process_sp(thread.CalculateProcess());
924     if (process_sp)
925       abi = process_sp->GetABI().get();
926     if (abi == nullptr)
927       return ret_plan_sp;
928 
929     TargetSP target_sp(thread.CalculateTarget());
930 
931     TypeSystemClang *clang_ast_context =
932         ScratchTypeSystemClang::GetForTarget(*target_sp);
933     if (!clang_ast_context)
934       return ret_plan_sp;
935 
936     ValueList argument_values;
937     Value void_ptr_value;
938     CompilerType clang_void_ptr_type =
939         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
940     void_ptr_value.SetValueType(Value::ValueType::Scalar);
941     // void_ptr_value.SetContext (Value::eContextTypeClangType,
942     // clang_void_ptr_type);
943     void_ptr_value.SetCompilerType(clang_void_ptr_type);
944 
945     int obj_index;
946     int sel_index;
947 
948     // If this is a struct return dispatch, then the first argument is
949     // the return struct pointer, and the object is the second, and
950     // the selector is the third.  Otherwise the object is the first
951     // and the selector the second.
952     if (this_dispatch->stret_return) {
953       obj_index = 1;
954       sel_index = 2;
955       argument_values.PushValue(void_ptr_value);
956       argument_values.PushValue(void_ptr_value);
957       argument_values.PushValue(void_ptr_value);
958     } else {
959       obj_index = 0;
960       sel_index = 1;
961       argument_values.PushValue(void_ptr_value);
962       argument_values.PushValue(void_ptr_value);
963     }
964 
965     bool success = abi->GetArgumentValues(thread, argument_values);
966     if (!success)
967       return ret_plan_sp;
968 
969     lldb::addr_t obj_addr =
970         argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
971     if (obj_addr == 0x0) {
972       LLDB_LOGF(
973           log,
974           "Asked to step to dispatch to nil object, returning empty plan.");
975       return ret_plan_sp;
976     }
977 
978     ExecutionContext exe_ctx(thread.shared_from_this());
979     Process *process = exe_ctx.GetProcessPtr();
980     // isa_addr will store the class pointer that the method is being
981     // dispatched to - so either the class directly or the super class
982     // if this is one of the objc_msgSendSuper flavors.  That's mostly
983     // used to look up the class/selector pair in our cache.
984 
985     lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
986     lldb::addr_t sel_addr =
987         argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
988 
989     // Figure out the class this is being dispatched to and see if
990     // we've already cached this method call, If so we can push a
991     // run-to-address plan directly.  Otherwise we have to figure out
992     // where the implementation lives.
993 
994     if (this_dispatch->is_super) {
995       if (this_dispatch->is_super2) {
996         // In the objc_msgSendSuper2 case, we don't get the object
997         // directly, we get a structure containing the object and the
998         // class to which the super message is being sent.  So we need
999         // to dig the super out of the class and use that.
1000 
1001         Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
1002         super_value.GetScalar() += process->GetAddressByteSize();
1003         super_value.ResolveValue(&exe_ctx);
1004 
1005         if (super_value.GetScalar().IsValid()) {
1006 
1007           // isa_value now holds the class pointer.  The second word of the
1008           // class pointer is the super-class pointer:
1009           super_value.GetScalar() += process->GetAddressByteSize();
1010           super_value.ResolveValue(&exe_ctx);
1011           if (super_value.GetScalar().IsValid())
1012             isa_addr = super_value.GetScalar().ULongLong();
1013           else {
1014             LLDB_LOGF(log, "Failed to extract the super class value from the "
1015                            "class in objc_super.");
1016           }
1017         } else {
1018           LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
1019         }
1020       } else {
1021         // In the objc_msgSendSuper case, we don't get the object
1022         // directly, we get a two element structure containing the
1023         // object and the super class to which the super message is
1024         // being sent.  So the class we want is the second element of
1025         // this structure.
1026 
1027         Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
1028         super_value.GetScalar() += process->GetAddressByteSize();
1029         super_value.ResolveValue(&exe_ctx);
1030 
1031         if (super_value.GetScalar().IsValid()) {
1032           isa_addr = super_value.GetScalar().ULongLong();
1033         } else {
1034           LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
1035         }
1036       }
1037     } else {
1038       // In the direct dispatch case, the object->isa is the class pointer we
1039       // want.
1040 
1041       // This is a little cheesy, but since object->isa is the first field,
1042       // making the object value a load address value and resolving it will get
1043       // the pointer sized data pointed to by that value...
1044 
1045       // Note, it isn't a fatal error not to be able to get the
1046       // address from the object, since this might be a "tagged
1047       // pointer" which isn't a real object, but rather some word
1048       // length encoded dingus.
1049 
1050       Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1051 
1052       isa_value.SetValueType(Value::ValueType::LoadAddress);
1053       isa_value.ResolveValue(&exe_ctx);
1054       if (isa_value.GetScalar().IsValid()) {
1055         isa_addr = isa_value.GetScalar().ULongLong();
1056       } else {
1057         LLDB_LOGF(log, "Failed to extract the isa value from object.");
1058       }
1059     }
1060 
1061     // Okay, we've got the address of the class for which we're resolving this,
1062     // let's see if it's in our cache:
1063     lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1064 
1065     if (isa_addr != LLDB_INVALID_ADDRESS) {
1066       if (log) {
1067         LLDB_LOGF(log,
1068                   "Resolving call for class - 0x%" PRIx64
1069                   " and selector - 0x%" PRIx64,
1070                   isa_addr, sel_addr);
1071       }
1072       ObjCLanguageRuntime *objc_runtime =
1073           ObjCLanguageRuntime::Get(*thread.GetProcess());
1074       assert(objc_runtime != nullptr);
1075 
1076       impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1077     }
1078 
1079     if (impl_addr != LLDB_INVALID_ADDRESS) {
1080       // Yup, it was in the cache, so we can run to that address directly.
1081 
1082       LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,
1083                 impl_addr);
1084 
1085       ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1086                                                              stop_others);
1087     } else {
1088       // We haven't seen this class/selector pair yet.  Look it up.
1089       StreamString errors;
1090       Address impl_code_address;
1091 
1092       ValueList dispatch_values;
1093 
1094       // We've will inject a little function in the target that takes the
1095       // object, selector and some flags,
1096       // and figures out the implementation.  Looks like:
1097       //      void *__lldb_objc_find_implementation_for_selector (void *object,
1098       //                                                          void *sel,
1099       //                                                          int is_stret,
1100       //                                                          int is_super,
1101       //                                                          int is_super2,
1102       //                                                          int is_fixup,
1103       //                                                          int is_fixed,
1104       //                                                          int debug)
1105       // So set up the arguments for that call.
1106 
1107       dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1108       dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1109 
1110       Value flag_value;
1111       CompilerType clang_int_type =
1112           clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1113               lldb::eEncodingSint, 32);
1114       flag_value.SetValueType(Value::ValueType::Scalar);
1115       // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1116       flag_value.SetCompilerType(clang_int_type);
1117 
1118       if (this_dispatch->stret_return)
1119         flag_value.GetScalar() = 1;
1120       else
1121         flag_value.GetScalar() = 0;
1122       dispatch_values.PushValue(flag_value);
1123 
1124       if (this_dispatch->is_super)
1125         flag_value.GetScalar() = 1;
1126       else
1127         flag_value.GetScalar() = 0;
1128       dispatch_values.PushValue(flag_value);
1129 
1130       if (this_dispatch->is_super2)
1131         flag_value.GetScalar() = 1;
1132       else
1133         flag_value.GetScalar() = 0;
1134       dispatch_values.PushValue(flag_value);
1135 
1136       switch (this_dispatch->fixedup) {
1137       case DispatchFunction::eFixUpNone:
1138         flag_value.GetScalar() = 0;
1139         dispatch_values.PushValue(flag_value);
1140         dispatch_values.PushValue(flag_value);
1141         break;
1142       case DispatchFunction::eFixUpFixed:
1143         flag_value.GetScalar() = 1;
1144         dispatch_values.PushValue(flag_value);
1145         flag_value.GetScalar() = 1;
1146         dispatch_values.PushValue(flag_value);
1147         break;
1148       case DispatchFunction::eFixUpToFix:
1149         flag_value.GetScalar() = 1;
1150         dispatch_values.PushValue(flag_value);
1151         flag_value.GetScalar() = 0;
1152         dispatch_values.PushValue(flag_value);
1153         break;
1154       }
1155       if (log && log->GetVerbose())
1156         flag_value.GetScalar() = 1;
1157       else
1158         flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1159       dispatch_values.PushValue(flag_value);
1160 
1161       ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1162           thread, *this, dispatch_values, isa_addr, sel_addr);
1163       if (log) {
1164         StreamString s;
1165         ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1166         LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());
1167       }
1168     }
1169   }
1170 
1171   // Finally, check if we have hit an "optimized dispatch" function.  This will
1172   // either directly call the base implementation or dispatch an objc_msgSend
1173   // if the method has been overridden.  So we just do a "step in/step out",
1174   // setting a breakpoint on objc_msgSend, and if we hit the msgSend, we
1175   // will automatically step in again.  That's the job of the
1176   // AppleThreadPlanStepThroughDirectDispatch.
1177   if (!this_dispatch && !ret_plan_sp) {
1178     MsgsendMap::iterator pos;
1179     pos = m_opt_dispatch_map.find(curr_pc);
1180     if (pos != m_opt_dispatch_map.end()) {
1181       const char *opt_name = g_opt_dispatch_names[(*pos).second];
1182       ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(
1183           thread, *this, opt_name);
1184     }
1185   }
1186 
1187   return ret_plan_sp;
1188 }
1189 
1190 FunctionCaller *
1191 AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1192   return m_impl_code->GetFunctionCaller();
1193 }
1194