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