1 //===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++
2 //-*-===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "AppleObjCTrampolineHandler.h"
11 #include "AppleThreadPlanStepThroughObjCTrampoline.h"
12 
13 #include "lldb/Breakpoint/StoppointCallbackContext.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/StreamFile.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Expression/DiagnosticManager.h"
19 #include "lldb/Expression/FunctionCaller.h"
20 #include "lldb/Expression/UserExpression.h"
21 #include "lldb/Expression/UtilityFunction.h"
22 #include "lldb/Symbol/ClangASTContext.h"
23 #include "lldb/Symbol/Symbol.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/ThreadPlanRunToAddress.h"
31 #include "lldb/Utility/ConstString.h"
32 #include "lldb/Utility/FileSpec.h"
33 #include "lldb/Utility/Log.h"
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() {}
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.GetPointer(&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     const ModuleList &target_modules = target.GetImages();
457     std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
458     size_t num_modules = target_modules.GetSize();
459     if (!m_objc_module_sp) {
460       for (size_t i = 0; i < num_modules; i++) {
461         if (ObjCLanguageRuntime::Get(*process_sp)
462                 ->IsModuleObjCLibrary(
463                     target_modules.GetModuleAtIndexUnlocked(i))) {
464           m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i);
465           break;
466         }
467       }
468     }
469 
470     if (m_objc_module_sp) {
471       ConstString trampoline_name("gdb_objc_trampolines");
472       const Symbol *trampoline_symbol =
473           m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
474                                                            eSymbolTypeData);
475       if (trampoline_symbol != nullptr) {
476         m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
477         if (m_trampoline_header == LLDB_INVALID_ADDRESS)
478           return false;
479 
480         // Next look up the "changed" symbol and set a breakpoint on that...
481         ConstString changed_name("gdb_objc_trampolines_changed");
482         const Symbol *changed_symbol =
483             m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
484                                                              eSymbolTypeCode);
485         if (changed_symbol != nullptr) {
486           const Address changed_symbol_addr = changed_symbol->GetAddress();
487           if (!changed_symbol_addr.IsValid())
488             return false;
489 
490           lldb::addr_t changed_addr =
491               changed_symbol_addr.GetOpcodeLoadAddress(&target);
492           if (changed_addr != LLDB_INVALID_ADDRESS) {
493             BreakpointSP trampolines_changed_bp_sp =
494                 target.CreateBreakpoint(changed_addr, true, false);
495             if (trampolines_changed_bp_sp) {
496               m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
497               trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
498                                                      true);
499               trampolines_changed_bp_sp->SetBreakpointKind(
500                   "objc-trampolines-changed");
501               return true;
502             }
503           }
504         }
505       }
506     }
507   }
508   return false;
509 }
510 
511 bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
512     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
513     lldb::user_id_t break_loc_id) {
514   AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
515   if (vtable_handler->InitializeVTableSymbols()) {
516     // The Update function is called with the address of an added region.  So we
517     // grab that address, and
518     // feed it into ReadRegions.  Of course, our friend the ABI will get the
519     // values for us.
520     ExecutionContext exe_ctx(context->exe_ctx_ref);
521     Process *process = exe_ctx.GetProcessPtr();
522     const ABI *abi = process->GetABI().get();
523 
524     ClangASTContext *clang_ast_context =
525         ClangASTContext::GetScratch(process->GetTarget());
526     if (!clang_ast_context)
527       return false;
528 
529     ValueList argument_values;
530     Value input_value;
531     CompilerType clang_void_ptr_type =
532         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
533 
534     input_value.SetValueType(Value::eValueTypeScalar);
535     // input_value.SetContext (Value::eContextTypeClangType,
536     // clang_void_ptr_type);
537     input_value.SetCompilerType(clang_void_ptr_type);
538     argument_values.PushValue(input_value);
539 
540     bool success =
541         abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
542     if (!success)
543       return false;
544 
545     // Now get a pointer value from the zeroth argument.
546     Status error;
547     DataExtractor data;
548     error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
549                                                                nullptr);
550     lldb::offset_t offset = 0;
551     lldb::addr_t region_addr = data.GetPointer(&offset);
552 
553     if (region_addr != 0)
554       vtable_handler->ReadRegions(region_addr);
555   }
556   return false;
557 }
558 
559 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
560   // The no argument version reads the  start region from the value of
561   // the gdb_regions_header, and gets started from there.
562 
563   m_regions.clear();
564   if (!InitializeVTableSymbols())
565     return false;
566   Status error;
567   ProcessSP process_sp = GetProcessSP();
568   if (process_sp) {
569     lldb::addr_t region_addr =
570         process_sp->ReadPointerFromMemory(m_trampoline_header, error);
571     if (error.Success())
572       return ReadRegions(region_addr);
573   }
574   return false;
575 }
576 
577 bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
578     lldb::addr_t region_addr) {
579   ProcessSP process_sp = GetProcessSP();
580   if (!process_sp)
581     return false;
582 
583   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
584 
585   // We aren't starting at the trampoline symbol.
586   InitializeVTableSymbols();
587   lldb::addr_t next_region = region_addr;
588 
589   // Read in the sizes of the headers.
590   while (next_region != 0) {
591     m_regions.push_back(VTableRegion(this, next_region));
592     if (!m_regions.back().IsValid()) {
593       m_regions.clear();
594       return false;
595     }
596     if (log) {
597       StreamString s;
598       m_regions.back().Dump(s);
599       LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());
600     }
601 
602     next_region = m_regions.back().GetNextRegionAddr();
603   }
604 
605   return true;
606 }
607 
608 bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
609     lldb::addr_t addr, uint32_t &flags) {
610   region_collection::iterator pos, end = m_regions.end();
611   for (pos = m_regions.begin(); pos != end; pos++) {
612     if ((*pos).AddressInRegion(addr, flags))
613       return true;
614   }
615   return false;
616 }
617 
618 const AppleObjCTrampolineHandler::DispatchFunction
619     AppleObjCTrampolineHandler::g_dispatch_functions[] = {
620         // NAME                              STRET  SUPER  SUPER2  FIXUP TYPE
621         {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
622         {"objc_msgSend_fixup", false, false, false,
623          DispatchFunction::eFixUpToFix},
624         {"objc_msgSend_fixedup", false, false, false,
625          DispatchFunction::eFixUpFixed},
626         {"objc_msgSend_stret", true, false, false,
627          DispatchFunction::eFixUpNone},
628         {"objc_msgSend_stret_fixup", true, false, false,
629          DispatchFunction::eFixUpToFix},
630         {"objc_msgSend_stret_fixedup", true, false, false,
631          DispatchFunction::eFixUpFixed},
632         {"objc_msgSend_fpret", false, false, false,
633          DispatchFunction::eFixUpNone},
634         {"objc_msgSend_fpret_fixup", false, false, false,
635          DispatchFunction::eFixUpToFix},
636         {"objc_msgSend_fpret_fixedup", false, false, false,
637          DispatchFunction::eFixUpFixed},
638         {"objc_msgSend_fp2ret", false, false, true,
639          DispatchFunction::eFixUpNone},
640         {"objc_msgSend_fp2ret_fixup", false, false, true,
641          DispatchFunction::eFixUpToFix},
642         {"objc_msgSend_fp2ret_fixedup", false, false, true,
643          DispatchFunction::eFixUpFixed},
644         {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
645         {"objc_msgSendSuper_stret", true, true, false,
646          DispatchFunction::eFixUpNone},
647         {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
648         {"objc_msgSendSuper2_fixup", false, true, true,
649          DispatchFunction::eFixUpToFix},
650         {"objc_msgSendSuper2_fixedup", false, true, true,
651          DispatchFunction::eFixUpFixed},
652         {"objc_msgSendSuper2_stret", true, true, true,
653          DispatchFunction::eFixUpNone},
654         {"objc_msgSendSuper2_stret_fixup", true, true, true,
655          DispatchFunction::eFixUpToFix},
656         {"objc_msgSendSuper2_stret_fixedup", true, true, true,
657          DispatchFunction::eFixUpFixed},
658 };
659 
660 AppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
661     const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
662     : m_process_wp(), m_objc_module_sp(objc_module_sp),
663       m_lookup_implementation_function_code(nullptr),
664       m_impl_fn_addr(LLDB_INVALID_ADDRESS),
665       m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
666       m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
667   if (process_sp)
668     m_process_wp = process_sp;
669   // Look up the known resolution functions:
670 
671   ConstString get_impl_name("class_getMethodImplementation");
672   ConstString get_impl_stret_name("class_getMethodImplementation_stret");
673   ConstString msg_forward_name("_objc_msgForward");
674   ConstString msg_forward_stret_name("_objc_msgForward_stret");
675 
676   Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
677   const Symbol *class_getMethodImplementation =
678       m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
679                                                        eSymbolTypeCode);
680   const Symbol *class_getMethodImplementation_stret =
681       m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
682                                                        eSymbolTypeCode);
683   const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
684       msg_forward_name, eSymbolTypeCode);
685   const Symbol *msg_forward_stret =
686       m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
687                                                        eSymbolTypeCode);
688 
689   if (class_getMethodImplementation)
690     m_impl_fn_addr =
691         class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
692             target);
693   if (class_getMethodImplementation_stret)
694     m_impl_stret_fn_addr =
695         class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
696             target);
697   if (msg_forward)
698     m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
699   if (msg_forward_stret)
700     m_msg_forward_stret_addr =
701         msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
702 
703   // FIXME: Do some kind of logging here.
704   if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
705     // If we can't even find the ordinary get method implementation function,
706     // then we aren't going to be able to
707     // step through any method dispatches.  Warn to that effect and get out of
708     // here.
709     if (process_sp->CanJIT()) {
710       process_sp->GetTarget().GetDebugger().GetErrorStream().Printf(
711           "Could not find implementation lookup function \"%s\""
712           " step in through ObjC method dispatch will not work.\n",
713           get_impl_name.AsCString());
714     }
715     return;
716   } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
717     // It there is no stret return lookup function, assume that it is the same
718     // as the straight lookup:
719     m_impl_stret_fn_addr = m_impl_fn_addr;
720     // Also we will use the version of the lookup code that doesn't rely on the
721     // stret version of the function.
722     m_lookup_implementation_function_code =
723         g_lookup_implementation_no_stret_function_code;
724   } else {
725     m_lookup_implementation_function_code =
726         g_lookup_implementation_with_stret_function_code;
727   }
728 
729   // Look up the addresses for the objc dispatch functions and cache
730   // them.  For now I'm inspecting the symbol names dynamically to
731   // figure out how to dispatch to them.  If it becomes more
732   // complicated than this we can turn the g_dispatch_functions char *
733   // array into a template table, and populate the DispatchFunction
734   // map from there.
735 
736   for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
737     ConstString name_const_str(g_dispatch_functions[i].name);
738     const Symbol *msgSend_symbol =
739         m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
740                                                          eSymbolTypeCode);
741     if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
742       // FIXME: Make g_dispatch_functions static table of
743       // DispatchFunctions, and have the map be address->index.
744       // Problem is we also need to lookup the dispatch function.  For
745       // now we could have a side table of stret & non-stret dispatch
746       // functions.  If that's as complex as it gets, we're fine.
747 
748       lldb::addr_t sym_addr =
749           msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
750 
751       m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
752     }
753   }
754 
755   // Build our vtable dispatch handler here:
756   m_vtables_up.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
757   if (m_vtables_up)
758     m_vtables_up->ReadRegions();
759 }
760 
761 lldb::addr_t
762 AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
763                                                   ValueList &dispatch_values) {
764   ThreadSP thread_sp(thread.shared_from_this());
765   ExecutionContext exe_ctx(thread_sp);
766   DiagnosticManager diagnostics;
767   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
768 
769   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
770   FunctionCaller *impl_function_caller = nullptr;
771 
772   // Scope for mutex locker:
773   {
774     std::lock_guard<std::mutex> guard(m_impl_function_mutex);
775 
776     // First stage is to make the ClangUtility to hold our injected function:
777 
778     if (!m_impl_code) {
779       if (m_lookup_implementation_function_code != nullptr) {
780         Status error;
781         m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
782             m_lookup_implementation_function_code, eLanguageTypeObjC,
783             g_lookup_implementation_function_name, error));
784         if (error.Fail()) {
785           LLDB_LOGF(
786               log,
787               "Failed to get Utility Function for implementation lookup: %s.",
788               error.AsCString());
789           m_impl_code.reset();
790           return args_addr;
791         }
792 
793         if (!m_impl_code->Install(diagnostics, exe_ctx)) {
794           if (log) {
795             LLDB_LOGF(log, "Failed to install implementation lookup.");
796             diagnostics.Dump(log);
797           }
798           m_impl_code.reset();
799           return args_addr;
800         }
801       } else {
802         LLDB_LOGF(log, "No method lookup implementation code.");
803         return LLDB_INVALID_ADDRESS;
804       }
805 
806       // Next make the runner function for our implementation utility function.
807       ClangASTContext *clang_ast_context =
808           ClangASTContext::GetScratch(thread.GetProcess()->GetTarget());
809       if (!clang_ast_context)
810         return LLDB_INVALID_ADDRESS;
811 
812       CompilerType clang_void_ptr_type =
813           clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
814       Status error;
815 
816       impl_function_caller = m_impl_code->MakeFunctionCaller(
817           clang_void_ptr_type, dispatch_values, thread_sp, error);
818       if (error.Fail()) {
819         LLDB_LOGF(log,
820                   "Error getting function caller for dispatch lookup: \"%s\".",
821                   error.AsCString());
822         return args_addr;
823       }
824     } else {
825       impl_function_caller = m_impl_code->GetFunctionCaller();
826     }
827   }
828 
829   diagnostics.Clear();
830 
831   // Now write down the argument values for this particular call.
832   // This looks like it might be a race condition if other threads
833   // were calling into here, but actually it isn't because we allocate
834   // a new args structure for this call by passing args_addr =
835   // LLDB_INVALID_ADDRESS...
836 
837   if (!impl_function_caller->WriteFunctionArguments(
838           exe_ctx, args_addr, dispatch_values, diagnostics)) {
839     if (log) {
840       LLDB_LOGF(log, "Error writing function arguments.");
841       diagnostics.Dump(log);
842     }
843     return args_addr;
844   }
845 
846   return args_addr;
847 }
848 
849 ThreadPlanSP
850 AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
851                                                        bool stop_others) {
852   ThreadPlanSP ret_plan_sp;
853   lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
854 
855   DispatchFunction this_dispatch;
856   bool found_it = false;
857 
858   // First step is to look and see if we are in one of the known ObjC
859   // dispatch functions.  We've already compiled a table of same, so
860   // consult it.
861 
862   MsgsendMap::iterator pos;
863   pos = m_msgSend_map.find(curr_pc);
864   if (pos != m_msgSend_map.end()) {
865     this_dispatch = g_dispatch_functions[(*pos).second];
866     found_it = true;
867   }
868 
869   // Next check to see if we are in a vtable region:
870 
871   if (!found_it) {
872     uint32_t flags;
873     if (m_vtables_up) {
874       found_it = m_vtables_up->IsAddressInVTables(curr_pc, flags);
875       if (found_it) {
876         this_dispatch.name = "vtable";
877         this_dispatch.stret_return =
878             (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
879             AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
880         this_dispatch.is_super = false;
881         this_dispatch.is_super2 = false;
882         this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
883       }
884     }
885   }
886 
887   if (found_it) {
888     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
889 
890     // We are decoding a method dispatch.  First job is to pull the
891     // arguments out:
892 
893     lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
894 
895     const ABI *abi = nullptr;
896     ProcessSP process_sp(thread.CalculateProcess());
897     if (process_sp)
898       abi = process_sp->GetABI().get();
899     if (abi == nullptr)
900       return ret_plan_sp;
901 
902     TargetSP target_sp(thread.CalculateTarget());
903 
904     ClangASTContext *clang_ast_context = ClangASTContext::GetScratch(*target_sp);
905     if (!clang_ast_context)
906       return ret_plan_sp;
907 
908     ValueList argument_values;
909     Value void_ptr_value;
910     CompilerType clang_void_ptr_type =
911         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
912     void_ptr_value.SetValueType(Value::eValueTypeScalar);
913     // void_ptr_value.SetContext (Value::eContextTypeClangType,
914     // clang_void_ptr_type);
915     void_ptr_value.SetCompilerType(clang_void_ptr_type);
916 
917     int obj_index;
918     int sel_index;
919 
920     // If this is a struct return dispatch, then the first argument is
921     // the return struct pointer, and the object is the second, and
922     // the selector is the third.  Otherwise the object is the first
923     // and the selector the second.
924     if (this_dispatch.stret_return) {
925       obj_index = 1;
926       sel_index = 2;
927       argument_values.PushValue(void_ptr_value);
928       argument_values.PushValue(void_ptr_value);
929       argument_values.PushValue(void_ptr_value);
930     } else {
931       obj_index = 0;
932       sel_index = 1;
933       argument_values.PushValue(void_ptr_value);
934       argument_values.PushValue(void_ptr_value);
935     }
936 
937     bool success = abi->GetArgumentValues(thread, argument_values);
938     if (!success)
939       return ret_plan_sp;
940 
941     lldb::addr_t obj_addr =
942         argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
943     if (obj_addr == 0x0) {
944       LLDB_LOGF(
945           log,
946           "Asked to step to dispatch to nil object, returning empty plan.");
947       return ret_plan_sp;
948     }
949 
950     ExecutionContext exe_ctx(thread.shared_from_this());
951     Process *process = exe_ctx.GetProcessPtr();
952     // isa_addr will store the class pointer that the method is being
953     // dispatched to - so either the class directly or the super class
954     // if this is one of the objc_msgSendSuper flavors.  That's mostly
955     // used to look up the class/selector pair in our cache.
956 
957     lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
958     lldb::addr_t sel_addr =
959         argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
960 
961     // Figure out the class this is being dispatched to and see if
962     // we've already cached this method call, If so we can push a
963     // run-to-address plan directly.  Otherwise we have to figure out
964     // where the implementation lives.
965 
966     if (this_dispatch.is_super) {
967       if (this_dispatch.is_super2) {
968         // In the objc_msgSendSuper2 case, we don't get the object
969         // directly, we get a structure containing the object and the
970         // class to which the super message is being sent.  So we need
971         // to dig the super out of the class and use that.
972 
973         Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
974         super_value.GetScalar() += process->GetAddressByteSize();
975         super_value.ResolveValue(&exe_ctx);
976 
977         if (super_value.GetScalar().IsValid()) {
978 
979           // isa_value now holds the class pointer.  The second word of the
980           // class pointer is the super-class pointer:
981           super_value.GetScalar() += process->GetAddressByteSize();
982           super_value.ResolveValue(&exe_ctx);
983           if (super_value.GetScalar().IsValid())
984             isa_addr = super_value.GetScalar().ULongLong();
985           else {
986             LLDB_LOGF(log, "Failed to extract the super class value from the "
987                            "class in objc_super.");
988           }
989         } else {
990           LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
991         }
992       } else {
993         // In the objc_msgSendSuper case, we don't get the object
994         // directly, we get a two element structure containing the
995         // object and the super class to which the super message is
996         // being sent.  So the class we want is the second element of
997         // this structure.
998 
999         Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
1000         super_value.GetScalar() += process->GetAddressByteSize();
1001         super_value.ResolveValue(&exe_ctx);
1002 
1003         if (super_value.GetScalar().IsValid()) {
1004           isa_addr = super_value.GetScalar().ULongLong();
1005         } else {
1006           LLDB_LOGF(log, "Failed to extract the class value from objc_super.");
1007         }
1008       }
1009     } else {
1010       // In the direct dispatch case, the object->isa is the class pointer we
1011       // want.
1012 
1013       // This is a little cheesy, but since object->isa is the first field,
1014       // making the object value a load address value and resolving it will get
1015       // the pointer sized data pointed to by that value...
1016 
1017       // Note, it isn't a fatal error not to be able to get the
1018       // address from the object, since this might be a "tagged
1019       // pointer" which isn't a real object, but rather some word
1020       // length encoded dingus.
1021 
1022       Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1023 
1024       isa_value.SetValueType(Value::eValueTypeLoadAddress);
1025       isa_value.ResolveValue(&exe_ctx);
1026       if (isa_value.GetScalar().IsValid()) {
1027         isa_addr = isa_value.GetScalar().ULongLong();
1028       } else {
1029         LLDB_LOGF(log, "Failed to extract the isa value from object.");
1030       }
1031     }
1032 
1033     // Okay, we've got the address of the class for which we're resolving this,
1034     // let's see if it's in our cache:
1035     lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1036 
1037     if (isa_addr != LLDB_INVALID_ADDRESS) {
1038       if (log) {
1039         LLDB_LOGF(log,
1040                   "Resolving call for class - 0x%" PRIx64
1041                   " and selector - 0x%" PRIx64,
1042                   isa_addr, sel_addr);
1043       }
1044       ObjCLanguageRuntime *objc_runtime =
1045           ObjCLanguageRuntime::Get(*thread.GetProcess());
1046       assert(objc_runtime != nullptr);
1047 
1048       impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1049     }
1050 
1051     if (impl_addr != LLDB_INVALID_ADDRESS) {
1052       // Yup, it was in the cache, so we can run to that address directly.
1053 
1054       LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,
1055                 impl_addr);
1056 
1057       ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1058                                                              stop_others);
1059     } else {
1060       // We haven't seen this class/selector pair yet.  Look it up.
1061       StreamString errors;
1062       Address impl_code_address;
1063 
1064       ValueList dispatch_values;
1065 
1066       // We've will inject a little function in the target that takes the
1067       // object, selector and some flags,
1068       // and figures out the implementation.  Looks like:
1069       //      void *__lldb_objc_find_implementation_for_selector (void *object,
1070       //                                                          void *sel,
1071       //                                                          int is_stret,
1072       //                                                          int is_super,
1073       //                                                          int is_super2,
1074       //                                                          int is_fixup,
1075       //                                                          int is_fixed,
1076       //                                                          int debug)
1077       // So set up the arguments for that call.
1078 
1079       dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1080       dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1081 
1082       Value flag_value;
1083       CompilerType clang_int_type =
1084           clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1085               lldb::eEncodingSint, 32);
1086       flag_value.SetValueType(Value::eValueTypeScalar);
1087       // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1088       flag_value.SetCompilerType(clang_int_type);
1089 
1090       if (this_dispatch.stret_return)
1091         flag_value.GetScalar() = 1;
1092       else
1093         flag_value.GetScalar() = 0;
1094       dispatch_values.PushValue(flag_value);
1095 
1096       if (this_dispatch.is_super)
1097         flag_value.GetScalar() = 1;
1098       else
1099         flag_value.GetScalar() = 0;
1100       dispatch_values.PushValue(flag_value);
1101 
1102       if (this_dispatch.is_super2)
1103         flag_value.GetScalar() = 1;
1104       else
1105         flag_value.GetScalar() = 0;
1106       dispatch_values.PushValue(flag_value);
1107 
1108       switch (this_dispatch.fixedup) {
1109       case DispatchFunction::eFixUpNone:
1110         flag_value.GetScalar() = 0;
1111         dispatch_values.PushValue(flag_value);
1112         dispatch_values.PushValue(flag_value);
1113         break;
1114       case DispatchFunction::eFixUpFixed:
1115         flag_value.GetScalar() = 1;
1116         dispatch_values.PushValue(flag_value);
1117         flag_value.GetScalar() = 1;
1118         dispatch_values.PushValue(flag_value);
1119         break;
1120       case DispatchFunction::eFixUpToFix:
1121         flag_value.GetScalar() = 1;
1122         dispatch_values.PushValue(flag_value);
1123         flag_value.GetScalar() = 0;
1124         dispatch_values.PushValue(flag_value);
1125         break;
1126       }
1127       if (log && log->GetVerbose())
1128         flag_value.GetScalar() = 1;
1129       else
1130         flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1131       dispatch_values.PushValue(flag_value);
1132 
1133       // The step through code might have to fill in the cache, so it
1134       // is not safe to run only one thread.  So we override the
1135       // stop_others value passed in to us here:
1136       const bool trampoline_stop_others = false;
1137       ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1138           thread, this, dispatch_values, isa_addr, sel_addr,
1139           trampoline_stop_others);
1140       if (log) {
1141         StreamString s;
1142         ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1143         LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());
1144       }
1145     }
1146   }
1147 
1148   return ret_plan_sp;
1149 }
1150 
1151 FunctionCaller *
1152 AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1153   return m_impl_code->GetFunctionCaller();
1154 }
1155