1 //===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "AppleObjCTrampolineHandler.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "AppleThreadPlanStepThroughObjCTrampoline.h"
17 
18 #include "lldb/Breakpoint/StoppointCallbackContext.h"
19 #include "lldb/Core/ConstString.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Host/FileSpec.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/Value.h"
25 #include "lldb/Expression/ClangExpression.h"
26 #include "lldb/Expression/ClangFunction.h"
27 #include "lldb/Expression/ClangUtilityFunction.h"
28 
29 #include "lldb/Symbol/ClangASTContext.h"
30 #include "lldb/Target/ObjCLanguageRuntime.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Target/RegisterContext.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/ThreadPlanRunToAddress.h"
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name = "__lldb_objc_find_implementation_for_selector";
42 const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_code = "                               \n\
43 extern \"C\"                                                                                                    \n\
44 {                                                                                                               \n\
45     extern void *class_getMethodImplementation(void *objc_class, void *sel);                                    \n\
46     extern void *class_getMethodImplementation_stret(void *objc_class, void *sel);                              \n\
47     extern void * sel_getUid(char *name);                                                                       \n\
48     extern int printf(const char *format, ...);                                                                 \n\
49 }                                                                                                               \n\
50 extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object,                                 \n\
51                                                     void *sel,                                                  \n\
52                                                     int is_stret,                                               \n\
53                                                     int is_super,                                               \n\
54                                                     int is_super2,                                              \n\
55                                                     int is_fixup,                                               \n\
56                                                     int is_fixed,                                               \n\
57                                                     int debug)                                                  \n\
58 {                                                                                                               \n\
59     struct __lldb_imp_return_struct                                                                             \n\
60     {                                                                                                           \n\
61         void *class_addr;                                                                                       \n\
62         void *sel_addr;                                                                                         \n\
63         void *impl_addr;                                                                                        \n\
64     };                                                                                                          \n\
65                                                                                                                 \n\
66     struct __lldb_objc_class {                                                                                  \n\
67         void *isa;                                                                                              \n\
68         void *super_ptr;                                                                                        \n\
69     };                                                                                                          \n\
70     struct __lldb_objc_super {                                                                                  \n\
71         void *reciever;                                                                                         \n\
72         struct __lldb_objc_class *class_ptr;                                                                    \n\
73     };                                                                                                          \n\
74     struct __lldb_msg_ref {                                                                                     \n\
75         void *dont_know;                                                                                        \n\
76         void *sel;                                                                                              \n\
77     };                                                                                                          \n\
78                                                                                                                 \n\
79     struct __lldb_imp_return_struct return_struct;                                                              \n\
80                                                                                                                 \n\
81     if (debug)                                                                                                  \n\
82         printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"                          \n\
83                 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\",                                               \n\
84                  object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);                               \n\
85     if (is_super)                                                                                               \n\
86     {                                                                                                           \n\
87         if (is_super2)                                                                                          \n\
88         {                                                                                                       \n\
89             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;                    \n\
90         }                                                                                                       \n\
91         else                                                                                                    \n\
92         {                                                                                                       \n\
93             return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;                               \n\
94         }                                                                                                       \n\
95     }                                                                                                           \n\
96     else                                                                                                        \n\
97     {                                                                                                           \n\
98         void *class_ptr = (void *) [(id) object class];                                                         \n\
99         if (class_ptr == object)                                                                                \n\
100         {                                                                                                       \n\
101             struct __lldb_objc_class *class_as_class_struct = (struct __lldb_objc_class *) class_ptr;           \n\
102             if (debug)                                                                                          \n\
103                 printf (\"Found a class object, need to return the meta class 0x%p -> 0x%p\\n\",                \n\
104                         class_ptr, class_as_class_struct->isa);                                                 \n\
105             return_struct.class_addr = class_as_class_struct->isa;                                              \n\
106         }                                                                                                       \n\
107         else                                                                                                    \n\
108         {                                                                                                       \n\
109             if (debug)                                                                                          \n\
110                 printf (\"[object class] returned: 0x%p.\\n\", class_ptr);                                      \n\
111             return_struct.class_addr = class_ptr;                                                               \n\
112         }                                                                                                       \n\
113     }                                                                                                           \n\
114                                                                                                                 \n\
115     if (is_fixup)                                                                                               \n\
116     {                                                                                                           \n\
117         if (is_fixed)                                                                                           \n\
118         {                                                                                                       \n\
119             return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;                                             \n\
120         }                                                                                                       \n\
121         else                                                                                                    \n\
122         {                                                                                                       \n\
123             char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;                                            \n\
124             return_struct.sel_addr = sel_getUid (sel_name);                                                     \n\
125             if (debug)                                                                                          \n\
126                 printf (\"\\n*** Got fixed up selector: 0x%p for name %s.\\n\",                                 \n\
127                         return_struct.sel_addr, sel_name);                                                      \n\
128         }                                                                                                       \n\
129     }                                                                                                           \n\
130     else                                                                                                        \n\
131     {                                                                                                           \n\
132         return_struct.sel_addr = sel;                                                                           \n\
133     }                                                                                                           \n\
134                                                                                                                 \n\
135     if (is_stret)                                                                                               \n\
136     {                                                                                                           \n\
137         return_struct.impl_addr = class_getMethodImplementation_stret (return_struct.class_addr,                \n\
138                                                                        return_struct.sel_addr);                 \n\
139     }                                                                                                           \n\
140     else                                                                                                        \n\
141     {                                                                                                           \n\
142         return_struct.impl_addr = class_getMethodImplementation (return_struct.class_addr,                      \n\
143                                                                        return_struct.sel_addr);                 \n\
144     }                                                                                                           \n\
145     if (debug)                                                                                                  \n\
146         printf (\"\\n*** Returning implementation: 0x%p.\\n\", return_struct.impl_addr);                        \n\
147                                                                                                                 \n\
148     return return_struct.impl_addr;                                                                             \n\
149 }                                                                                                               \n\
150 ";
151 
152 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(AppleObjCVTables *owner, lldb::addr_t header_addr) :
153     m_valid (true),
154     m_owner(owner),
155     m_header_addr (header_addr),
156     m_code_start_addr(0),
157     m_code_end_addr (0),
158     m_next_region (0)
159 {
160     SetUpRegion ();
161 }
162 
163 AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler()
164 {
165 }
166 
167 void
168 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion()
169 {
170     // The header looks like:
171     //
172     //   uint16_t headerSize
173     //   uint16_t descSize
174     //   uint32_t descCount
175     //   void * next
176     //
177     // First read in the header:
178 
179     char memory_buffer[16];
180     Process *process = m_owner->GetProcess();
181     DataExtractor data(memory_buffer, sizeof(memory_buffer),
182                        process->GetByteOrder(),
183                        process->GetAddressByteSize());
184     size_t actual_size = 8 + process->GetAddressByteSize();
185     Error error;
186     size_t bytes_read = process->ReadMemory (m_header_addr, memory_buffer, actual_size, error);
187     if (bytes_read != actual_size)
188     {
189         m_valid = false;
190         return;
191     }
192 
193     uint32_t offset_ptr = 0;
194     const uint16_t header_size = data.GetU16(&offset_ptr);
195     const uint16_t descriptor_size = data.GetU16(&offset_ptr);
196     const size_t num_descriptors = data.GetU32(&offset_ptr);
197 
198     m_next_region = data.GetPointer(&offset_ptr);
199 
200     // If the header size is 0, that means we've come in too early before this data is set up.
201     // Set ourselves as not valid, and continue.
202     if (header_size == 0 || num_descriptors == 0)
203     {
204         m_valid = false;
205         return;
206     }
207 
208     // Now read in all the descriptors:
209     // The descriptor looks like:
210     //
211     // uint32_t offset
212     // uint32_t flags
213     //
214     // Where offset is either 0 - in which case it is unused, or
215     // it is the offset of the vtable code from the beginning of the descriptor record.
216     // Below, we'll convert that into an absolute code address, since I don't want to have
217     // to compute it over and over.
218 
219     // Ingest the whole descriptor array:
220     const lldb::addr_t desc_ptr = m_header_addr + header_size;
221     const size_t desc_array_size = num_descriptors * descriptor_size;
222     DataBufferSP data_sp(new DataBufferHeap (desc_array_size, '\0'));
223     uint8_t* dst = (uint8_t*)data_sp->GetBytes();
224 
225     DataExtractor desc_extractor (dst, desc_array_size,
226                                   process->GetByteOrder(),
227                                   process->GetAddressByteSize());
228     bytes_read = process->ReadMemory(desc_ptr, dst, desc_array_size, error);
229     if (bytes_read != desc_array_size)
230     {
231         m_valid = false;
232         return;
233     }
234 
235     // The actual code for the vtables will be laid out consecutively, so I also
236     // compute the start and end of the whole code block.
237 
238     offset_ptr = 0;
239     m_code_start_addr = 0;
240     m_code_end_addr = 0;
241 
242     for (int i = 0; i < num_descriptors; i++)
243     {
244         lldb::addr_t start_offset = offset_ptr;
245         uint32_t offset = desc_extractor.GetU32 (&offset_ptr);
246         uint32_t flags  = desc_extractor.GetU32 (&offset_ptr);
247         lldb:addr_t code_addr = desc_ptr + start_offset + offset;
248         m_descriptors.push_back (VTableDescriptor(flags, code_addr));
249 
250         if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
251             m_code_start_addr = code_addr;
252         if (code_addr > m_code_end_addr)
253             m_code_end_addr = code_addr;
254 
255         offset_ptr = start_offset + descriptor_size;
256     }
257     // Finally, a little bird told me that all the vtable code blocks are the same size.
258     // Let's compute the blocks and if they are all the same add the size to the code end address:
259     lldb::addr_t code_size = 0;
260     bool all_the_same = true;
261     for (int i = 0; i < num_descriptors - 1; i++)
262     {
263         lldb::addr_t this_size = m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
264         if (code_size == 0)
265             code_size = this_size;
266         else
267         {
268             if (this_size != code_size)
269                 all_the_same = false;
270             if (this_size > code_size)
271                 code_size = this_size;
272         }
273     }
274     if (all_the_same)
275         m_code_end_addr += code_size;
276 }
277 
278 bool
279 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::AddressInRegion (lldb::addr_t addr, uint32_t &flags)
280 {
281     if (!IsValid())
282         return false;
283 
284     if (addr < m_code_start_addr || addr > m_code_end_addr)
285         return false;
286 
287     std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
288     for (pos = m_descriptors.begin(); pos != end; pos++)
289     {
290         if (addr <= (*pos).code_start)
291         {
292             flags = (*pos).flags;
293             return true;
294         }
295     }
296     return false;
297 }
298 
299 void
300 AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump (Stream &s)
301 {
302     s.Printf ("Header addr: 0x%llx Code start: 0x%llx Code End: 0x%llx Next: 0x%llx\n",
303               m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
304     size_t num_elements = m_descriptors.size();
305     for (size_t i = 0; i < num_elements; i++)
306     {
307         s.Indent();
308         s.Printf ("Code start: 0x%llx Flags: %d\n", m_descriptors[i].code_start, m_descriptors[i].flags);
309     }
310 }
311 
312 AppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables (const ProcessSP &process_sp,
313                                                                 const ModuleSP &objc_module_sp) :
314     m_process_sp (process_sp),
315     m_trampoline_header (LLDB_INVALID_ADDRESS),
316     m_trampolines_changed_bp_id (LLDB_INVALID_BREAK_ID),
317     m_objc_module_sp (objc_module_sp)
318 {
319 
320 }
321 
322 AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables()
323 {
324     if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
325         m_process_sp->GetTarget().RemoveBreakpointByID (m_trampolines_changed_bp_id);
326 }
327 
328 bool
329 AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols ()
330 {
331     if (m_trampoline_header != LLDB_INVALID_ADDRESS)
332         return true;
333     Target &target = m_process_sp->GetTarget();
334 
335     ModuleList &modules = target.GetImages();
336     size_t num_modules = modules.GetSize();
337     if (!m_objc_module_sp)
338     {
339         for (size_t i = 0; i < num_modules; i++)
340         {
341             if (m_process_sp->GetObjCLanguageRuntime()->IsModuleObjCLibrary (modules.GetModuleAtIndex(i)))
342             {
343                 m_objc_module_sp = modules.GetModuleAtIndex(i);
344                 break;
345             }
346         }
347     }
348 
349     if (m_objc_module_sp)
350     {
351         ConstString trampoline_name ("gdb_objc_trampolines");
352         const Symbol *trampoline_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType (trampoline_name,
353                                                                                             eSymbolTypeData);
354         if (trampoline_symbol != NULL)
355         {
356             if (!trampoline_symbol->GetValue().IsValid())
357                 return false;
358 
359             m_trampoline_header = trampoline_symbol->GetValue().GetLoadAddress(&target);
360             if (m_trampoline_header == LLDB_INVALID_ADDRESS)
361                 return false;
362 
363             // Next look up the "changed" symbol and set a breakpoint on that...
364             ConstString changed_name ("gdb_objc_trampolines_changed");
365             const Symbol *changed_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType (changed_name,
366                                                                                              eSymbolTypeCode);
367             if (changed_symbol != NULL)
368             {
369                 if (!changed_symbol->GetValue().IsValid())
370                     return false;
371 
372                 lldb::addr_t changed_addr = changed_symbol->GetValue().GetOpcodeLoadAddress (&target);
373                 if (changed_addr != LLDB_INVALID_ADDRESS)
374                 {
375                     BreakpointSP trampolines_changed_bp_sp = target.CreateBreakpoint (changed_addr, true);
376                     if (trampolines_changed_bp_sp)
377                     {
378                         m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
379                         trampolines_changed_bp_sp->SetCallback (RefreshTrampolines, this, true);
380                         return true;
381                     }
382                 }
383             }
384         }
385     }
386 
387     return false;
388 }
389 
390 bool
391 AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines (void *baton,
392                                                                   StoppointCallbackContext *context,
393                                                                   lldb::user_id_t break_id,
394                                                                   lldb::user_id_t break_loc_id)
395 {
396     AppleObjCVTables *vtable_handler = (AppleObjCVTables *) baton;
397     if (vtable_handler->InitializeVTableSymbols())
398     {
399         // The Update function is called with the address of an added region.  So we grab that address, and
400         // feed it into ReadRegions.  Of course, our friend the ABI will get the values for us.
401         Process *process = context->exe_ctx.GetProcessPtr();
402         const ABI *abi = process->GetABI().get();
403 
404         ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext();
405         ValueList argument_values;
406         Value input_value;
407         void *clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
408         input_value.SetValueType (Value::eValueTypeScalar);
409         input_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
410         argument_values.PushValue(input_value);
411 
412         bool success = abi->GetArgumentValues (context->exe_ctx.GetThreadRef(), argument_values);
413         if (!success)
414             return false;
415 
416         // Now get a pointer value from the zeroth argument.
417         Error error;
418         DataExtractor data;
419         error = argument_values.GetValueAtIndex(0)->GetValueAsData (&(context->exe_ctx),
420                                                                     clang_ast_context->getASTContext(),
421                                                                     data,
422                                                                     0,
423                                                                     NULL);
424         uint32_t offset_ptr = 0;
425         lldb::addr_t region_addr = data.GetPointer(&offset_ptr);
426 
427         if (region_addr != 0)
428             vtable_handler->ReadRegions(region_addr);
429     }
430     return false;
431 }
432 
433 bool
434 AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions ()
435 {
436     // The no argument version reads the start region from the value of the gdb_regions_header, and
437     // gets started from there.
438 
439     m_regions.clear();
440     if (!InitializeVTableSymbols())
441         return false;
442     Error error;
443     lldb::addr_t region_addr = m_process_sp->ReadPointerFromMemory (m_trampoline_header, error);
444     if (error.Success())
445         return ReadRegions (region_addr);
446     return false;
447 }
448 
449 bool
450 AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions (lldb::addr_t region_addr)
451 {
452     if (!m_process_sp)
453         return false;
454 
455     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
456 
457     // We aren't starting at the trampoline symbol.
458     InitializeVTableSymbols ();
459     lldb::addr_t next_region = region_addr;
460 
461     // Read in the sizes of the headers.
462     while (next_region != 0)
463     {
464         m_regions.push_back (VTableRegion(this, next_region));
465         if (!m_regions.back().IsValid())
466         {
467             m_regions.clear();
468             return false;
469         }
470         if (log)
471         {
472             StreamString s;
473             m_regions.back().Dump(s);
474             log->Printf("Read vtable region: \n%s", s.GetData());
475         }
476 
477         next_region = m_regions.back().GetNextRegionAddr();
478     }
479 
480     return true;
481 }
482 
483 bool
484 AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables (lldb::addr_t addr, uint32_t &flags)
485 {
486     region_collection::iterator pos, end = m_regions.end();
487     for (pos = m_regions.begin(); pos != end; pos++)
488     {
489         if ((*pos).AddressInRegion (addr, flags))
490             return true;
491     }
492     return false;
493 }
494 
495 const AppleObjCTrampolineHandler::DispatchFunction
496 AppleObjCTrampolineHandler::g_dispatch_functions[] =
497 {
498     // NAME                              STRET  SUPER  SUPER2  FIXUP TYPE
499     {"objc_msgSend",                     false, false, false, DispatchFunction::eFixUpNone    },
500     {"objc_msgSend_fixup",               false, false, false, DispatchFunction::eFixUpToFix   },
501     {"objc_msgSend_fixedup",             false, false, false, DispatchFunction::eFixUpFixed   },
502     {"objc_msgSend_stret",               true,  false, false, DispatchFunction::eFixUpNone    },
503     {"objc_msgSend_stret_fixup",         true,  false, false, DispatchFunction::eFixUpToFix   },
504     {"objc_msgSend_stret_fixedup",       true,  false, false, DispatchFunction::eFixUpFixed   },
505     {"objc_msgSend_fpret",               false, false, false, DispatchFunction::eFixUpNone    },
506     {"objc_msgSend_fpret_fixup",         false, false, false, DispatchFunction::eFixUpToFix   },
507     {"objc_msgSend_fpret_fixedup",       false, false, false, DispatchFunction::eFixUpFixed   },
508     {"objc_msgSend_fp2ret",              false, false,  true, DispatchFunction::eFixUpNone    },
509     {"objc_msgSend_fp2ret_fixup",        false, false,  true, DispatchFunction::eFixUpToFix   },
510     {"objc_msgSend_fp2ret_fixedup",      false, false,  true, DispatchFunction::eFixUpFixed   },
511     {"objc_msgSendSuper",                false, true,  false, DispatchFunction::eFixUpNone    },
512     {"objc_msgSendSuper_stret",          true,  true,  false, DispatchFunction::eFixUpNone    },
513     {"objc_msgSendSuper2",               false, true,   true, DispatchFunction::eFixUpNone    },
514     {"objc_msgSendSuper2_fixup",         false, true,   true, DispatchFunction::eFixUpToFix   },
515     {"objc_msgSendSuper2_fixedup",       false, true,   true, DispatchFunction::eFixUpFixed   },
516     {"objc_msgSendSuper2_stret",         true,  true,   true, DispatchFunction::eFixUpNone    },
517     {"objc_msgSendSuper2_stret_fixup",   true,  true,   true, DispatchFunction::eFixUpToFix   },
518     {"objc_msgSendSuper2_stret_fixedup", true,  true,   true, DispatchFunction::eFixUpFixed   },
519     {NULL}
520 };
521 
522 AppleObjCTrampolineHandler::AppleObjCTrampolineHandler (const ProcessSP &process_sp,
523                                                         const ModuleSP &objc_module_sp) :
524     m_process_sp (process_sp),
525     m_objc_module_sp (objc_module_sp),
526     m_impl_fn_addr (LLDB_INVALID_ADDRESS),
527     m_impl_stret_fn_addr (LLDB_INVALID_ADDRESS),
528     m_msg_forward_addr (LLDB_INVALID_ADDRESS)
529 {
530     // Look up the known resolution functions:
531 
532     ConstString get_impl_name("class_getMethodImplementation");
533     ConstString get_impl_stret_name("class_getMethodImplementation_stret");
534     ConstString msg_forward_name("_objc_msgForward");
535     ConstString msg_forward_stret_name("_objc_msgForward_stret");
536 
537     Target *target = m_process_sp ? &m_process_sp->GetTarget() : NULL;
538     const Symbol *class_getMethodImplementation = m_objc_module_sp->FindFirstSymbolWithNameAndType (get_impl_name, eSymbolTypeCode);
539     const Symbol *class_getMethodImplementation_stret = m_objc_module_sp->FindFirstSymbolWithNameAndType (get_impl_stret_name, eSymbolTypeCode);
540     const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType (msg_forward_name, eSymbolTypeCode);
541     const Symbol *msg_forward_stret = m_objc_module_sp->FindFirstSymbolWithNameAndType (msg_forward_stret_name, eSymbolTypeCode);
542 
543     if (class_getMethodImplementation)
544         m_impl_fn_addr = class_getMethodImplementation->GetValue().GetOpcodeLoadAddress (target);
545     if  (class_getMethodImplementation_stret)
546         m_impl_stret_fn_addr = class_getMethodImplementation_stret->GetValue().GetOpcodeLoadAddress (target);
547     if (msg_forward)
548         m_msg_forward_addr = msg_forward->GetValue().GetOpcodeLoadAddress(target);
549     if  (msg_forward_stret)
550         m_msg_forward_stret_addr = msg_forward_stret->GetValue().GetOpcodeLoadAddress(target);
551 
552     // FIXME: Do some kind of logging here.
553     if (m_impl_fn_addr == LLDB_INVALID_ADDRESS || m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS)
554         return;
555 
556     // Look up the addresses for the objc dispatch functions and cache them.  For now I'm inspecting the symbol
557     // names dynamically to figure out how to dispatch to them.  If it becomes more complicated than this we can
558     // turn the g_dispatch_functions char * array into a template table, and populate the DispatchFunction map
559     // from there.
560 
561     for (int i = 0; g_dispatch_functions[i].name != NULL; i++)
562     {
563         ConstString name_const_str(g_dispatch_functions[i].name);
564         const Symbol *msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType (name_const_str, eSymbolTypeCode);
565         if (msgSend_symbol)
566         {
567             // FixMe: Make g_dispatch_functions static table of DispatchFunctions, and have the map be address->index.
568             // Problem is we also need to lookup the dispatch function.  For now we could have a side table of stret & non-stret
569             // dispatch functions.  If that's as complex as it gets, we're fine.
570 
571             lldb::addr_t sym_addr = msgSend_symbol->GetValue().GetOpcodeLoadAddress(target);
572 
573             m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
574         }
575     }
576 
577     // Build our vtable dispatch handler here:
578     m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
579     if (m_vtables_ap.get())
580         m_vtables_ap->ReadRegions();
581 }
582 
583 ThreadPlanSP
584 AppleObjCTrampolineHandler::GetStepThroughDispatchPlan (Thread &thread, bool stop_others)
585 {
586     ThreadPlanSP ret_plan_sp;
587     lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
588 
589     DispatchFunction this_dispatch;
590     bool found_it = false;
591 
592     // First step is to look and see if we are in one of the known ObjC dispatch functions.  We've already compiled
593     // a table of same, so consult it.
594 
595     MsgsendMap::iterator pos;
596     pos = m_msgSend_map.find (curr_pc);
597     if (pos != m_msgSend_map.end())
598     {
599         this_dispatch = g_dispatch_functions[(*pos).second];
600         found_it = true;
601     }
602 
603     // Next check to see if we are in a vtable region:
604 
605     if (!found_it)
606     {
607         uint32_t flags;
608         if (m_vtables_ap.get())
609         {
610             found_it = m_vtables_ap->IsAddressInVTables (curr_pc, flags);
611             if (found_it)
612             {
613                 this_dispatch.name = "vtable";
614                 this_dispatch.stret_return
615                         = (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) == AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
616                 this_dispatch.is_super = false;
617                 this_dispatch.is_super2 = false;
618                 this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
619             }
620         }
621     }
622 
623     if (found_it)
624     {
625         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
626 
627         // We are decoding a method dispatch.
628         // First job is to pull the arguments out:
629 
630         lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
631 
632         Process *process = thread.CalculateProcess();
633         const ABI *abi = process->GetABI().get();
634         if (abi == NULL)
635             return ret_plan_sp;
636 
637         Target *target = thread.CalculateTarget();
638 
639         ClangASTContext *clang_ast_context = target->GetScratchClangASTContext();
640         ValueList argument_values;
641         Value void_ptr_value;
642         lldb::clang_type_t clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
643         void_ptr_value.SetValueType (Value::eValueTypeScalar);
644         void_ptr_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
645 
646         int obj_index;
647         int sel_index;
648 
649         // If this is a struct return dispatch, then the first argument is the
650         // return struct pointer, and the object is the second, and the selector is the third.
651         // Otherwise the object is the first and the selector the second.
652         if (this_dispatch.stret_return)
653         {
654             obj_index = 1;
655             sel_index = 2;
656             argument_values.PushValue(void_ptr_value);
657             argument_values.PushValue(void_ptr_value);
658             argument_values.PushValue(void_ptr_value);
659         }
660         else
661         {
662             obj_index = 0;
663             sel_index = 1;
664             argument_values.PushValue(void_ptr_value);
665             argument_values.PushValue(void_ptr_value);
666         }
667 
668 
669         bool success = abi->GetArgumentValues (thread, argument_values);
670         if (!success)
671             return ret_plan_sp;
672 
673         ExecutionContext exe_ctx;
674         thread.CalculateExecutionContext (exe_ctx);
675 
676         // isa_addr will store the class pointer that the method is being dispatched to - so either the class
677         // directly or the super class if this is one of the objc_msgSendSuper flavors.  That's mostly used to
678         // look up the class/selector pair in our cache.
679 
680         lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
681         lldb::addr_t sel_addr = argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
682 
683         // Figure out the class this is being dispatched to and see if we've already cached this method call,
684         // If so we can push a run-to-address plan directly.  Otherwise we have to figure out where
685         // the implementation lives.
686 
687         if (this_dispatch.is_super)
688         {
689             if (this_dispatch.is_super2)
690             {
691                // In the objc_msgSendSuper2 case, we don't get the object directly, we get a structure containing
692                // the object and the class to which the super message is being sent.  So we need to dig the super
693                // out of the class and use that.
694 
695                 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
696                 super_value.GetScalar() += process->GetAddressByteSize();
697                 super_value.ResolveValue (&exe_ctx, clang_ast_context->getASTContext());
698 
699                 if (super_value.GetScalar().IsValid())
700                 {
701 
702                     // isa_value now holds the class pointer.  The second word of the class pointer is the super-class pointer:
703                     super_value.GetScalar() += process->GetAddressByteSize();
704                     super_value.ResolveValue (&exe_ctx, clang_ast_context->getASTContext());
705                     if (super_value.GetScalar().IsValid())
706                         isa_addr = super_value.GetScalar().ULongLong();
707                     else
708                     {
709                        if (log)
710                         log->Printf("Failed to extract the super class value from the class in objc_super.");
711                     }
712                 }
713                 else
714                 {
715                    if (log)
716                     log->Printf("Failed to extract the class value from objc_super.");
717                 }
718             }
719             else
720             {
721                // In the objc_msgSendSuper case, we don't get the object directly, we get a two element structure containing
722                // the object and the super class to which the super message is being sent.  So the class we want is
723                // the second element of this structure.
724 
725                 Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
726                 super_value.GetScalar() += process->GetAddressByteSize();
727                 super_value.ResolveValue (&exe_ctx, clang_ast_context->getASTContext());
728 
729                 if (super_value.GetScalar().IsValid())
730                 {
731                     isa_addr = super_value.GetScalar().ULongLong();
732                 }
733                 else
734                 {
735                    if (log)
736                     log->Printf("Failed to extract the class value from objc_super.");
737                 }
738             }
739         }
740         else
741         {
742             // In the direct dispatch case, the object->isa is the class pointer we want.
743 
744             // This is a little cheesy, but since object->isa is the first field,
745             // making the object value a load address value and resolving it will get
746             // the pointer sized data pointed to by that value...
747 
748             // Note, it isn't a fatal error not to be able to get the address from the object, since this might
749             // be a "tagged pointer" which isn't a real object, but rather some word length encoded dingus.
750 
751             Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
752 
753             isa_value.SetValueType(Value::eValueTypeLoadAddress);
754             isa_value.ResolveValue(&exe_ctx, clang_ast_context->getASTContext());
755             if (isa_value.GetScalar().IsValid())
756             {
757                 isa_addr = isa_value.GetScalar().ULongLong();
758             }
759             else
760             {
761                if (log)
762                 log->Printf("Failed to extract the isa value from object.");
763             }
764 
765         }
766 
767         // Okay, we've got the address of the class for which we're resolving this, let's see if it's in our cache:
768         lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
769 
770         if (isa_addr != LLDB_INVALID_ADDRESS)
771         {
772             if (log)
773             {
774                 log->Printf("Resolving call for class - 0x%llx and selector - 0x%llx",
775                             isa_addr, sel_addr);
776             }
777             ObjCLanguageRuntime *objc_runtime = m_process_sp->GetObjCLanguageRuntime ();
778             assert(objc_runtime != NULL);
779 
780             impl_addr = objc_runtime->LookupInMethodCache (isa_addr, sel_addr);
781         }
782 
783         if (impl_addr != LLDB_INVALID_ADDRESS)
784         {
785             // Yup, it was in the cache, so we can run to that address directly.
786 
787             if (log)
788                 log->Printf ("Found implementation address in cache: 0x%llx", impl_addr);
789 
790             ret_plan_sp.reset (new ThreadPlanRunToAddress (thread, impl_addr, stop_others));
791         }
792         else
793         {
794             // We haven't seen this class/selector pair yet.  Look it up.
795             StreamString errors;
796             Address impl_code_address;
797 
798             ValueList dispatch_values;
799 
800             // We've will inject a little function in the target that takes the object, selector and some flags,
801             // and figures out the implementation.  Looks like:
802             //      void *__lldb_objc_find_implementation_for_selector (void *object,
803             //                                                          void *sel,
804             //                                                          int is_stret,
805             //                                                          int is_super,
806             //                                                          int is_super2,
807             //                                                          int is_fixup,
808             //                                                          int is_fixed,
809             //                                                          int debug)
810             // So set up the arguments for that call.
811 
812             dispatch_values.PushValue (*(argument_values.GetValueAtIndex(obj_index)));
813             dispatch_values.PushValue (*(argument_values.GetValueAtIndex(sel_index)));
814 
815             Value flag_value;
816             lldb::clang_type_t clang_int_type
817                     = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingSint, 32);
818             flag_value.SetValueType (Value::eValueTypeScalar);
819             flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
820 
821             if (this_dispatch.stret_return)
822                 flag_value.GetScalar() = 1;
823             else
824                 flag_value.GetScalar() = 0;
825             dispatch_values.PushValue (flag_value);
826 
827             if (this_dispatch.is_super)
828                 flag_value.GetScalar() = 1;
829             else
830                 flag_value.GetScalar() = 0;
831             dispatch_values.PushValue (flag_value);
832 
833             if (this_dispatch.is_super2)
834                 flag_value.GetScalar() = 1;
835             else
836                 flag_value.GetScalar() = 0;
837             dispatch_values.PushValue (flag_value);
838 
839             switch (this_dispatch.fixedup)
840             {
841               case DispatchFunction::eFixUpNone:
842                  flag_value.GetScalar() = 0;
843                  dispatch_values.PushValue (flag_value);
844                  dispatch_values.PushValue (flag_value);
845                  break;
846               case DispatchFunction::eFixUpFixed:
847                  flag_value.GetScalar() = 1;
848                  dispatch_values.PushValue (flag_value);
849                  flag_value.GetScalar() = 1;
850                  dispatch_values.PushValue (flag_value);
851                  break;
852               case DispatchFunction::eFixUpToFix:
853                  flag_value.GetScalar() = 1;
854                  dispatch_values.PushValue (flag_value);
855                  flag_value.GetScalar() = 0;
856                  dispatch_values.PushValue (flag_value);
857                  break;
858             }
859             if (log)
860                 flag_value.GetScalar() = 1;
861             else
862                 flag_value.GetScalar() = 0;  // FIXME - Set to 0 when debugging is done.
863             dispatch_values.PushValue (flag_value);
864 
865             // Now, if we haven't already, make and insert the function as a ClangUtilityFunction, and make and insert
866             // it's runner ClangFunction.
867             {
868                 // Scope for mutex locker:
869                 Mutex::Locker locker(m_impl_function_mutex);
870 
871                 // First stage is to make the ClangUtility to hold our injected function:
872 
873 #define USE_BUILTIN_FUNCTION 0  // Define this to 1 and we will use the get_implementation function found in the target.
874                                 // This is useful for debugging additions to the get_impl function 'cause you don't have
875                                 // to bother with string-ifying the code into g_lookup_implementation_function_code.
876 
877                 if (USE_BUILTIN_FUNCTION)
878                 {
879                     ConstString our_utility_function_name("__lldb_objc_find_implementation_for_selector");
880                     SymbolContextList sc_list;
881 
882                     exe_ctx.GetTargetRef().GetImages().FindSymbolsWithNameAndType (our_utility_function_name, eSymbolTypeCode, sc_list);
883                     if (sc_list.GetSize() == 1)
884                     {
885                         SymbolContext sc;
886                         sc_list.GetContextAtIndex(0, sc);
887                         if (sc.symbol != NULL)
888                             impl_code_address = sc.symbol->GetValue();
889 
890                         //lldb::addr_t addr = impl_code_address.GetOpcodeLoadAddress (exe_ctx.GetTargetPtr());
891                         //printf ("Getting address for our_utility_function: 0x%llx.\n", addr);
892                     }
893                     else
894                     {
895                         //printf ("Could not find implementation function address.\n");
896                         return ret_plan_sp;
897                     }
898                 }
899                 else if (!m_impl_code.get())
900                 {
901                     m_impl_code.reset (new ClangUtilityFunction (g_lookup_implementation_function_code,
902                                                                  g_lookup_implementation_function_name));
903                     if (!m_impl_code->Install(errors, exe_ctx))
904                     {
905                         if (log)
906                             log->Printf ("Failed to install implementation lookup: %s.", errors.GetData());
907                         m_impl_code.reset();
908                         return ret_plan_sp;
909                     }
910                     impl_code_address.Clear();
911                     impl_code_address.SetOffset(m_impl_code->StartAddress());
912                 }
913                 else
914                 {
915                     impl_code_address.Clear();
916                     impl_code_address.SetOffset(m_impl_code->StartAddress());
917                 }
918 
919                 // Next make the runner function for our implementation utility function.
920                 if (!m_impl_function.get())
921                 {
922                      m_impl_function.reset(new ClangFunction (thread,
923                                                               clang_ast_context,
924                                                               clang_void_ptr_type,
925                                                               impl_code_address,
926                                                               dispatch_values));
927 
928                     errors.Clear();
929                     unsigned num_errors = m_impl_function->CompileFunction(errors);
930                     if (num_errors)
931                     {
932                         if (log)
933                             log->Printf ("Error compiling function: \"%s\".", errors.GetData());
934                         return ret_plan_sp;
935                     }
936 
937                     errors.Clear();
938                     if (!m_impl_function->WriteFunctionWrapper(exe_ctx, errors))
939                     {
940                         if (log)
941                             log->Printf ("Error Inserting function: \"%s\".", errors.GetData());
942                         return ret_plan_sp;
943                     }
944                 }
945 
946             }
947 
948             errors.Clear();
949 
950             // Now write down the argument values for this particular call.  This looks like it might be a race condition
951             // if other threads were calling into here, but actually it isn't because we allocate a new args structure for
952             // this call by passing args_addr = LLDB_INVALID_ADDRESS...
953 
954             lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
955             if (!m_impl_function->WriteFunctionArguments (exe_ctx, args_addr, impl_code_address, dispatch_values, errors))
956                 return ret_plan_sp;
957 
958             ret_plan_sp.reset (new AppleThreadPlanStepThroughObjCTrampoline (thread, this, args_addr,
959                                                                         dispatch_values.GetValueAtIndex(0)->GetScalar().ULongLong(),
960                                                                         isa_addr, sel_addr,
961                                                                         stop_others));
962             if (log)
963             {
964                 StreamString s;
965                 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
966                 log->Printf("Using ObjC step plan: %s.\n", s.GetData());
967             }
968         }
969     }
970 
971     return ret_plan_sp;
972 }
973 
974 ClangFunction *
975 AppleObjCTrampolineHandler::GetLookupImplementationWrapperFunction ()
976 {
977     return m_impl_function.get();
978 }
979