AppleObjCTrampolineHandler.cpp revision 344779
1314564Sdim//===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++
2314564Sdim//-*-===//
3293116Semaste//
4293116Semaste//                     The LLVM Compiler Infrastructure
5293116Semaste//
6293116Semaste// This file is distributed under the University of Illinois Open Source
7293116Semaste// License. See LICENSE.TXT for details.
8293116Semaste//
9293116Semaste//===----------------------------------------------------------------------===//
10293116Semaste
11293116Semaste#include "AppleObjCTrampolineHandler.h"
12293116Semaste
13293116Semaste#include "AppleThreadPlanStepThroughObjCTrampoline.h"
14293116Semaste
15293116Semaste#include "lldb/Breakpoint/StoppointCallbackContext.h"
16293116Semaste#include "lldb/Core/Debugger.h"
17293116Semaste#include "lldb/Core/Module.h"
18293116Semaste#include "lldb/Core/StreamFile.h"
19293116Semaste#include "lldb/Core/Value.h"
20309124Sdim#include "lldb/Expression/DiagnosticManager.h"
21309124Sdim#include "lldb/Expression/FunctionCaller.h"
22293116Semaste#include "lldb/Expression/UserExpression.h"
23293116Semaste#include "lldb/Expression/UtilityFunction.h"
24293116Semaste#include "lldb/Symbol/ClangASTContext.h"
25293116Semaste#include "lldb/Symbol/Symbol.h"
26293116Semaste#include "lldb/Target/ABI.h"
27309124Sdim#include "lldb/Target/ExecutionContext.h"
28293116Semaste#include "lldb/Target/ObjCLanguageRuntime.h"
29293116Semaste#include "lldb/Target/Process.h"
30293116Semaste#include "lldb/Target/RegisterContext.h"
31293116Semaste#include "lldb/Target/Target.h"
32293116Semaste#include "lldb/Target/Thread.h"
33293116Semaste#include "lldb/Target/ThreadPlanRunToAddress.h"
34321369Sdim#include "lldb/Utility/ConstString.h"
35321369Sdim#include "lldb/Utility/FileSpec.h"
36321369Sdim#include "lldb/Utility/Log.h"
37293116Semaste
38293116Semaste#include "llvm/ADT/STLExtras.h"
39293116Semaste
40293116Semasteusing namespace lldb;
41293116Semasteusing namespace lldb_private;
42293116Semaste
43314564Sdimconst char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name =
44314564Sdim    "__lldb_objc_find_implementation_for_selector";
45314564Sdimconst char *AppleObjCTrampolineHandler::
46314564Sdim    g_lookup_implementation_with_stret_function_code =
47314564Sdim        "                               \n\
48341825Sdimextern \"C\"                                                                 \n\
49341825Sdim{                                                                            \n\
50341825Sdim    extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
51341825Sdim    extern void *class_getMethodImplementation_stret(void *objc_class,       \n\
52341825Sdim                                                     void *sel);             \n\
53341825Sdim    extern void * object_getClass (id object);                               \n\
54341825Sdim    extern void * sel_getUid(char *name);                                    \n\
55341825Sdim    extern int printf(const char *format, ...);                              \n\
56341825Sdim}                                                                            \n\
57341825Sdimextern \"C\" void * __lldb_objc_find_implementation_for_selector (           \n\
58341825Sdim                                                    void *object,            \n\
59341825Sdim                                                    void *sel,               \n\
60341825Sdim                                                    int is_stret,            \n\
61341825Sdim                                                    int is_super,            \n\
62341825Sdim                                                    int is_super2,           \n\
63341825Sdim                                                    int is_fixup,            \n\
64341825Sdim                                                    int is_fixed,            \n\
65341825Sdim                                                    int debug)               \n\
66341825Sdim{                                                                            \n\
67341825Sdim    struct __lldb_imp_return_struct                                          \n\
68341825Sdim    {                                                                        \n\
69341825Sdim        void *class_addr;                                                    \n\
70341825Sdim        void *sel_addr;                                                      \n\
71341825Sdim        void *impl_addr;                                                     \n\
72341825Sdim    };                                                                       \n\
73341825Sdim                                                                             \n\
74341825Sdim    struct __lldb_objc_class {                                               \n\
75341825Sdim        void *isa;                                                           \n\
76341825Sdim        void *super_ptr;                                                     \n\
77341825Sdim    };                                                                       \n\
78341825Sdim    struct __lldb_objc_super {                                               \n\
79344779Sdim        void *receiver;                                                      \n\
80341825Sdim        struct __lldb_objc_class *class_ptr;                                 \n\
81341825Sdim    };                                                                       \n\
82341825Sdim    struct __lldb_msg_ref {                                                  \n\
83341825Sdim        void *dont_know;                                                     \n\
84341825Sdim        void *sel;                                                           \n\
85341825Sdim    };                                                                       \n\
86341825Sdim                                                                             \n\
87341825Sdim    struct __lldb_imp_return_struct return_struct;                           \n\
88341825Sdim                                                                             \n\
89341825Sdim    if (debug)                                                               \n\
90341825Sdim        printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"\n\
91341825Sdim                \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\",            \n\
92341825Sdim                 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);\n\
93341825Sdim    if (is_super)                                                            \n\
94341825Sdim    {                                                                        \n\
95341825Sdim        if (is_super2)                                                       \n\
96341825Sdim        {                                                                    \n\
97341825Sdim            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;\n\
98341825Sdim        }                                                                    \n\
99341825Sdim        else                                                                 \n\
100341825Sdim        {                                                                    \n\
101341825Sdim            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;\n\
102341825Sdim        }                                                                    \n\
103341825Sdim    }                                                                        \n\
104341825Sdim    else                                                                     \n\
105341825Sdim    {                                                                        \n\
106341825Sdim        // This code seems a little funny, but has its reasons...            \n\
107341825Sdim                                                                             \n\
108341825Sdim        // The call to [object class] is here because if this is a           \n\
109341825Sdim        // class, and has not been called into yet, we need to do            \n\
110341825Sdim        // something to force the class to initialize itself.                \n\
111341825Sdim        // Then the call to object_getClass will actually return the         \n\
112341825Sdim        // correct class, either the class if object is a class              \n\
113341825Sdim        // instance, or the meta-class if it is a class pointer.             \n\
114341825Sdim        void *class_ptr = (void *) [(id) object class];                      \n\
115341825Sdim        return_struct.class_addr = (id)  object_getClass((id) object);       \n\
116341825Sdim        if (debug)                                                           \n\
117341825Sdim        {                                                                    \n\
118341825Sdim            if (class_ptr == object)                                         \n\
119341825Sdim            {                                                                \n\
120341825Sdim                printf (\"Found a class object, need to use the meta class %p -> %p\\n\",\n\
121341825Sdim                        class_ptr, return_struct.class_addr);                \n\
122341825Sdim            }                                                                \n\
123341825Sdim            else                                                             \n\
124341825Sdim            {                                                                \n\
125341825Sdim                 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
126341825Sdim                 class_ptr, return_struct.class_addr);                       \n\
127341825Sdim            }                                                                \n\
128341825Sdim        }                                                                    \n\
129341825Sdim    }                                                                        \n\
130341825Sdim                                                                             \n\
131341825Sdim    if (is_fixup)                                                            \n\
132341825Sdim    {                                                                        \n\
133341825Sdim        if (is_fixed)                                                        \n\
134341825Sdim        {                                                                    \n\
135341825Sdim            return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
136341825Sdim        }                                                                    \n\
137341825Sdim        else                                                                 \n\
138341825Sdim        {                                                                    \n\
139341825Sdim            char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
140341825Sdim            return_struct.sel_addr = sel_getUid (sel_name);                  \n\
141341825Sdim            if (debug)                                                       \n\
142341825Sdim                printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
143341825Sdim                        return_struct.sel_addr, sel_name);                   \n\
144341825Sdim        }                                                                    \n\
145341825Sdim    }                                                                        \n\
146341825Sdim    else                                                                     \n\
147341825Sdim    {                                                                        \n\
148341825Sdim        return_struct.sel_addr = sel;                                        \n\
149341825Sdim    }                                                                        \n\
150341825Sdim                                                                             \n\
151341825Sdim    if (is_stret)                                                            \n\
152341825Sdim    {                                                                        \n\
153341825Sdim        return_struct.impl_addr =                                            \n\
154341825Sdim          class_getMethodImplementation_stret (return_struct.class_addr,     \n\
155341825Sdim                                               return_struct.sel_addr);      \n\
156341825Sdim    }                                                                        \n\
157341825Sdim    else                                                                     \n\
158341825Sdim    {                                                                        \n\
159341825Sdim        return_struct.impl_addr =                                            \n\
160341825Sdim            class_getMethodImplementation (return_struct.class_addr,         \n\
161341825Sdim                                           return_struct.sel_addr);          \n\
162341825Sdim    }                                                                        \n\
163341825Sdim    if (debug)                                                               \n\
164341825Sdim        printf (\"\\n*** Returning implementation: %p.\\n\",                 \n\
165341825Sdim                          return_struct.impl_addr);                          \n\
166341825Sdim                                                                             \n\
167341825Sdim    return return_struct.impl_addr;                                          \n\
168341825Sdim}                                                                            \n\
169293116Semaste";
170314564Sdimconst char *
171314564Sdim    AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =
172314564Sdim        "                      \n\
173341825Sdimextern \"C\"                                                                 \n\
174341825Sdim{                                                                            \n\
175341825Sdim    extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
176341825Sdim    extern void * object_getClass (id object);                               \n\
177341825Sdim    extern void * sel_getUid(char *name);                                    \n\
178341825Sdim    extern int printf(const char *format, ...);                              \n\
179341825Sdim}                                                                            \n\
180293116Semasteextern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object,                                 \n\
181341825Sdim                                                    void *sel,               \n\
182341825Sdim                                                    int is_stret,            \n\
183341825Sdim                                                    int is_super,            \n\
184341825Sdim                                                    int is_super2,           \n\
185341825Sdim                                                    int is_fixup,            \n\
186341825Sdim                                                    int is_fixed,            \n\
187341825Sdim                                                    int debug)               \n\
188341825Sdim{                                                                            \n\
189341825Sdim    struct __lldb_imp_return_struct                                          \n\
190341825Sdim    {                                                                        \n\
191341825Sdim        void *class_addr;                                                    \n\
192341825Sdim        void *sel_addr;                                                      \n\
193341825Sdim        void *impl_addr;                                                     \n\
194341825Sdim    };                                                                       \n\
195341825Sdim                                                                             \n\
196341825Sdim    struct __lldb_objc_class {                                               \n\
197341825Sdim        void *isa;                                                           \n\
198341825Sdim        void *super_ptr;                                                     \n\
199341825Sdim    };                                                                       \n\
200341825Sdim    struct __lldb_objc_super {                                               \n\
201344779Sdim        void *receiver;                                                      \n\
202341825Sdim        struct __lldb_objc_class *class_ptr;                                 \n\
203341825Sdim    };                                                                       \n\
204341825Sdim    struct __lldb_msg_ref {                                                  \n\
205341825Sdim        void *dont_know;                                                     \n\
206341825Sdim        void *sel;                                                           \n\
207341825Sdim    };                                                                       \n\
208341825Sdim                                                                             \n\
209341825Sdim    struct __lldb_imp_return_struct return_struct;                           \n\
210341825Sdim                                                                             \n\
211341825Sdim    if (debug)                                                               \n\
212293116Semaste        printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"                          \n\
213341825Sdim                \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\",            \n\
214293116Semaste                 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);                               \n\
215341825Sdim    if (is_super)                                                            \n\
216341825Sdim    {                                                                        \n\
217341825Sdim        if (is_super2)                                                       \n\
218341825Sdim        {                                                                    \n\
219293116Semaste            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;                    \n\
220341825Sdim        }                                                                    \n\
221341825Sdim        else                                                                 \n\
222341825Sdim        {                                                                    \n\
223293116Semaste            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;                               \n\
224341825Sdim        }                                                                    \n\
225341825Sdim    }                                                                        \n\
226341825Sdim    else                                                                     \n\
227341825Sdim    {                                                                        \n\
228341825Sdim        // This code seems a little funny, but has its reasons...            \n\
229293116Semaste        // The call to [object class] is here because if this is a class, and has not been called into          \n\
230293116Semaste        // yet, we need to do something to force the class to initialize itself.                                \n\
231293116Semaste        // Then the call to object_getClass will actually return the correct class, either the class            \n\
232293116Semaste        // if object is a class instance, or the meta-class if it is a class pointer.                           \n\
233341825Sdim        void *class_ptr = (void *) [(id) object class];                      \n\
234341825Sdim        return_struct.class_addr = (id)  object_getClass((id) object);       \n\
235341825Sdim        if (debug)                                                           \n\
236341825Sdim        {                                                                    \n\
237341825Sdim            if (class_ptr == object)                                         \n\
238341825Sdim            {                                                                \n\
239293116Semaste                printf (\"Found a class object, need to return the meta class %p -> %p\\n\",                    \n\
240341825Sdim                        class_ptr, return_struct.class_addr);                \n\
241341825Sdim            }                                                                \n\
242341825Sdim            else                                                             \n\
243341825Sdim            {                                                                \n\
244293116Semaste                 printf (\"[object class] returned: %p object_getClass: %p.\\n\",                               \n\
245341825Sdim                 class_ptr, return_struct.class_addr);                       \n\
246341825Sdim            }                                                                \n\
247341825Sdim        }                                                                    \n\
248341825Sdim    }                                                                        \n\
249341825Sdim                                                                             \n\
250341825Sdim    if (is_fixup)                                                            \n\
251341825Sdim    {                                                                        \n\
252341825Sdim        if (is_fixed)                                                        \n\
253341825Sdim        {                                                                    \n\
254341825Sdim            return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
255341825Sdim        }                                                                    \n\
256341825Sdim        else                                                                 \n\
257341825Sdim        {                                                                    \n\
258341825Sdim            char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
259341825Sdim            return_struct.sel_addr = sel_getUid (sel_name);                  \n\
260341825Sdim            if (debug)                                                       \n\
261341825Sdim                printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
262341825Sdim                        return_struct.sel_addr, sel_name);                   \n\
263341825Sdim        }                                                                    \n\
264341825Sdim    }                                                                        \n\
265341825Sdim    else                                                                     \n\
266341825Sdim    {                                                                        \n\
267341825Sdim        return_struct.sel_addr = sel;                                        \n\
268341825Sdim    }                                                                        \n\
269341825Sdim                                                                             \n\
270341825Sdim    return_struct.impl_addr =                                                \n\
271341825Sdim      class_getMethodImplementation (return_struct.class_addr,               \n\
272341825Sdim                                     return_struct.sel_addr);                \n\
273341825Sdim    if (debug)                                                               \n\
274341825Sdim        printf (\"\\n*** Returning implementation: 0x%p.\\n\",               \n\
275341825Sdim          return_struct.impl_addr);                                          \n\
276341825Sdim                                                                             \n\
277341825Sdim    return return_struct.impl_addr;                                          \n\
278341825Sdim}                                                                            \n\
279293116Semaste";
280293116Semaste
281314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(
282314564Sdim    AppleObjCVTables *owner, lldb::addr_t header_addr)
283314564Sdim    : m_valid(true), m_owner(owner), m_header_addr(header_addr),
284314564Sdim      m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) {
285314564Sdim  SetUpRegion();
286293116Semaste}
287293116Semaste
288314564SdimAppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() {}
289293116Semaste
290314564Sdimvoid AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {
291314564Sdim  // The header looks like:
292314564Sdim  //
293314564Sdim  //   uint16_t headerSize
294314564Sdim  //   uint16_t descSize
295314564Sdim  //   uint32_t descCount
296314564Sdim  //   void * next
297314564Sdim  //
298314564Sdim  // First read in the header:
299293116Semaste
300314564Sdim  char memory_buffer[16];
301314564Sdim  ProcessSP process_sp = m_owner->GetProcessSP();
302314564Sdim  if (!process_sp)
303314564Sdim    return;
304314564Sdim  DataExtractor data(memory_buffer, sizeof(memory_buffer),
305314564Sdim                     process_sp->GetByteOrder(),
306314564Sdim                     process_sp->GetAddressByteSize());
307314564Sdim  size_t actual_size = 8 + process_sp->GetAddressByteSize();
308321369Sdim  Status error;
309314564Sdim  size_t bytes_read =
310314564Sdim      process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
311314564Sdim  if (bytes_read != actual_size) {
312314564Sdim    m_valid = false;
313314564Sdim    return;
314314564Sdim  }
315293116Semaste
316314564Sdim  lldb::offset_t offset = 0;
317314564Sdim  const uint16_t header_size = data.GetU16(&offset);
318314564Sdim  const uint16_t descriptor_size = data.GetU16(&offset);
319314564Sdim  const size_t num_descriptors = data.GetU32(&offset);
320293116Semaste
321314564Sdim  m_next_region = data.GetPointer(&offset);
322314564Sdim
323314564Sdim  // If the header size is 0, that means we've come in too early before this
324314564Sdim  // data is set up.
325314564Sdim  // Set ourselves as not valid, and continue.
326314564Sdim  if (header_size == 0 || num_descriptors == 0) {
327314564Sdim    m_valid = false;
328314564Sdim    return;
329314564Sdim  }
330314564Sdim
331314564Sdim  // Now read in all the descriptors:
332314564Sdim  // The descriptor looks like:
333314564Sdim  //
334314564Sdim  // uint32_t offset
335314564Sdim  // uint32_t flags
336314564Sdim  //
337341825Sdim  // Where offset is either 0 - in which case it is unused, or it is
338341825Sdim  // the offset of the vtable code from the beginning of the
339341825Sdim  // descriptor record.  Below, we'll convert that into an absolute
340341825Sdim  // code address, since I don't want to have to compute it over and
341341825Sdim  // over.
342314564Sdim
343314564Sdim  // Ingest the whole descriptor array:
344314564Sdim  const lldb::addr_t desc_ptr = m_header_addr + header_size;
345314564Sdim  const size_t desc_array_size = num_descriptors * descriptor_size;
346314564Sdim  DataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
347314564Sdim  uint8_t *dst = (uint8_t *)data_sp->GetBytes();
348314564Sdim
349314564Sdim  DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
350314564Sdim                               process_sp->GetAddressByteSize());
351314564Sdim  bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);
352314564Sdim  if (bytes_read != desc_array_size) {
353314564Sdim    m_valid = false;
354314564Sdim    return;
355314564Sdim  }
356314564Sdim
357314564Sdim  // The actual code for the vtables will be laid out consecutively, so I also
358314564Sdim  // compute the start and end of the whole code block.
359314564Sdim
360314564Sdim  offset = 0;
361314564Sdim  m_code_start_addr = 0;
362314564Sdim  m_code_end_addr = 0;
363314564Sdim
364314564Sdim  for (size_t i = 0; i < num_descriptors; i++) {
365314564Sdim    lldb::addr_t start_offset = offset;
366314564Sdim    uint32_t voffset = desc_extractor.GetU32(&offset);
367314564Sdim    uint32_t flags = desc_extractor.GetU32(&offset);
368314564Sdim    lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
369314564Sdim    m_descriptors.push_back(VTableDescriptor(flags, code_addr));
370314564Sdim
371314564Sdim    if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
372314564Sdim      m_code_start_addr = code_addr;
373314564Sdim    if (code_addr > m_code_end_addr)
374314564Sdim      m_code_end_addr = code_addr;
375314564Sdim
376314564Sdim    offset = start_offset + descriptor_size;
377314564Sdim  }
378341825Sdim  // Finally, a little bird told me that all the vtable code blocks
379341825Sdim  // are the same size.  Let's compute the blocks and if they are all
380341825Sdim  // the same add the size to the code end address:
381314564Sdim  lldb::addr_t code_size = 0;
382314564Sdim  bool all_the_same = true;
383314564Sdim  for (size_t i = 0; i < num_descriptors - 1; i++) {
384314564Sdim    lldb::addr_t this_size =
385314564Sdim        m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
386314564Sdim    if (code_size == 0)
387314564Sdim      code_size = this_size;
388314564Sdim    else {
389314564Sdim      if (this_size != code_size)
390314564Sdim        all_the_same = false;
391314564Sdim      if (this_size > code_size)
392314564Sdim        code_size = this_size;
393293116Semaste    }
394314564Sdim  }
395314564Sdim  if (all_the_same)
396314564Sdim    m_code_end_addr += code_size;
397293116Semaste}
398293116Semaste
399314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::
400314564Sdim    AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
401314564Sdim  if (!IsValid())
402293116Semaste    return false;
403293116Semaste
404314564Sdim  if (addr < m_code_start_addr || addr > m_code_end_addr)
405314564Sdim    return false;
406314564Sdim
407314564Sdim  std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
408314564Sdim  for (pos = m_descriptors.begin(); pos != end; pos++) {
409314564Sdim    if (addr <= (*pos).code_start) {
410314564Sdim      flags = (*pos).flags;
411314564Sdim      return true;
412293116Semaste    }
413314564Sdim  }
414314564Sdim  return false;
415293116Semaste}
416314564Sdim
417314564Sdimvoid AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(
418314564Sdim    Stream &s) {
419314564Sdim  s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
420314564Sdim           " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
421314564Sdim           m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
422314564Sdim  size_t num_elements = m_descriptors.size();
423314564Sdim  for (size_t i = 0; i < num_elements; i++) {
424314564Sdim    s.Indent();
425314564Sdim    s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
426314564Sdim             m_descriptors[i].code_start, m_descriptors[i].flags);
427314564Sdim  }
428293116Semaste}
429293116Semaste
430314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables(
431314564Sdim    const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
432314564Sdim    : m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS),
433314564Sdim      m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID),
434314564Sdim      m_objc_module_sp(objc_module_sp) {
435314564Sdim  if (process_sp)
436314564Sdim    m_process_wp = process_sp;
437293116Semaste}
438293116Semaste
439314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {
440314564Sdim  ProcessSP process_sp = GetProcessSP();
441314564Sdim  if (process_sp) {
442314564Sdim    if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
443314564Sdim      process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
444314564Sdim  }
445314564Sdim}
446293116Semaste
447314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {
448314564Sdim  if (m_trampoline_header != LLDB_INVALID_ADDRESS)
449314564Sdim    return true;
450314564Sdim
451314564Sdim  ProcessSP process_sp = GetProcessSP();
452314564Sdim  if (process_sp) {
453314564Sdim    Target &target = process_sp->GetTarget();
454314564Sdim
455314564Sdim    const ModuleList &target_modules = target.GetImages();
456314564Sdim    std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
457314564Sdim    size_t num_modules = target_modules.GetSize();
458314564Sdim    if (!m_objc_module_sp) {
459314564Sdim      for (size_t i = 0; i < num_modules; i++) {
460314564Sdim        if (process_sp->GetObjCLanguageRuntime()->IsModuleObjCLibrary(
461314564Sdim                target_modules.GetModuleAtIndexUnlocked(i))) {
462314564Sdim          m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i);
463314564Sdim          break;
464293116Semaste        }
465314564Sdim      }
466314564Sdim    }
467314564Sdim
468314564Sdim    if (m_objc_module_sp) {
469314564Sdim      ConstString trampoline_name("gdb_objc_trampolines");
470314564Sdim      const Symbol *trampoline_symbol =
471314564Sdim          m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
472314564Sdim                                                           eSymbolTypeData);
473314564Sdim      if (trampoline_symbol != NULL) {
474314564Sdim        m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
475314564Sdim        if (m_trampoline_header == LLDB_INVALID_ADDRESS)
476314564Sdim          return false;
477314564Sdim
478314564Sdim        // Next look up the "changed" symbol and set a breakpoint on that...
479314564Sdim        ConstString changed_name("gdb_objc_trampolines_changed");
480314564Sdim        const Symbol *changed_symbol =
481314564Sdim            m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
482314564Sdim                                                             eSymbolTypeCode);
483314564Sdim        if (changed_symbol != NULL) {
484314564Sdim          const Address changed_symbol_addr = changed_symbol->GetAddress();
485314564Sdim          if (!changed_symbol_addr.IsValid())
486314564Sdim            return false;
487314564Sdim
488314564Sdim          lldb::addr_t changed_addr =
489314564Sdim              changed_symbol_addr.GetOpcodeLoadAddress(&target);
490314564Sdim          if (changed_addr != LLDB_INVALID_ADDRESS) {
491314564Sdim            BreakpointSP trampolines_changed_bp_sp =
492314564Sdim                target.CreateBreakpoint(changed_addr, true, false);
493314564Sdim            if (trampolines_changed_bp_sp) {
494314564Sdim              m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
495314564Sdim              trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
496314564Sdim                                                     true);
497314564Sdim              trampolines_changed_bp_sp->SetBreakpointKind(
498314564Sdim                  "objc-trampolines-changed");
499314564Sdim              return true;
500293116Semaste            }
501314564Sdim          }
502293116Semaste        }
503314564Sdim      }
504293116Semaste    }
505314564Sdim  }
506314564Sdim  return false;
507293116Semaste}
508293116Semaste
509314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
510314564Sdim    void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
511314564Sdim    lldb::user_id_t break_loc_id) {
512314564Sdim  AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
513314564Sdim  if (vtable_handler->InitializeVTableSymbols()) {
514314564Sdim    // The Update function is called with the address of an added region.  So we
515314564Sdim    // grab that address, and
516314564Sdim    // feed it into ReadRegions.  Of course, our friend the ABI will get the
517314564Sdim    // values for us.
518314564Sdim    ExecutionContext exe_ctx(context->exe_ctx_ref);
519314564Sdim    Process *process = exe_ctx.GetProcessPtr();
520314564Sdim    const ABI *abi = process->GetABI().get();
521314564Sdim
522314564Sdim    ClangASTContext *clang_ast_context =
523314564Sdim        process->GetTarget().GetScratchClangASTContext();
524314564Sdim    ValueList argument_values;
525314564Sdim    Value input_value;
526314564Sdim    CompilerType clang_void_ptr_type =
527314564Sdim        clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
528314564Sdim
529314564Sdim    input_value.SetValueType(Value::eValueTypeScalar);
530314564Sdim    // input_value.SetContext (Value::eContextTypeClangType,
531314564Sdim    // clang_void_ptr_type);
532314564Sdim    input_value.SetCompilerType(clang_void_ptr_type);
533314564Sdim    argument_values.PushValue(input_value);
534314564Sdim
535314564Sdim    bool success =
536314564Sdim        abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
537314564Sdim    if (!success)
538314564Sdim      return false;
539314564Sdim
540314564Sdim    // Now get a pointer value from the zeroth argument.
541321369Sdim    Status error;
542314564Sdim    DataExtractor data;
543314564Sdim    error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
544314564Sdim                                                               0, NULL);
545314564Sdim    lldb::offset_t offset = 0;
546314564Sdim    lldb::addr_t region_addr = data.GetPointer(&offset);
547314564Sdim
548314564Sdim    if (region_addr != 0)
549314564Sdim      vtable_handler->ReadRegions(region_addr);
550314564Sdim  }
551314564Sdim  return false;
552293116Semaste}
553293116Semaste
554314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
555341825Sdim  // The no argument version reads the  start region from the value of
556341825Sdim  // the gdb_regions_header, and gets started from there.
557314564Sdim
558314564Sdim  m_regions.clear();
559314564Sdim  if (!InitializeVTableSymbols())
560293116Semaste    return false;
561321369Sdim  Status error;
562314564Sdim  ProcessSP process_sp = GetProcessSP();
563314564Sdim  if (process_sp) {
564314564Sdim    lldb::addr_t region_addr =
565314564Sdim        process_sp->ReadPointerFromMemory(m_trampoline_header, error);
566314564Sdim    if (error.Success())
567314564Sdim      return ReadRegions(region_addr);
568314564Sdim  }
569314564Sdim  return false;
570293116Semaste}
571293116Semaste
572314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
573314564Sdim    lldb::addr_t region_addr) {
574314564Sdim  ProcessSP process_sp = GetProcessSP();
575314564Sdim  if (!process_sp)
576314564Sdim    return false;
577314564Sdim
578314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
579314564Sdim
580314564Sdim  // We aren't starting at the trampoline symbol.
581314564Sdim  InitializeVTableSymbols();
582314564Sdim  lldb::addr_t next_region = region_addr;
583314564Sdim
584314564Sdim  // Read in the sizes of the headers.
585314564Sdim  while (next_region != 0) {
586314564Sdim    m_regions.push_back(VTableRegion(this, next_region));
587314564Sdim    if (!m_regions.back().IsValid()) {
588314564Sdim      m_regions.clear();
589314564Sdim      return false;
590293116Semaste    }
591314564Sdim    if (log) {
592314564Sdim      StreamString s;
593314564Sdim      m_regions.back().Dump(s);
594314564Sdim      log->Printf("Read vtable region: \n%s", s.GetData());
595293116Semaste    }
596314564Sdim
597314564Sdim    next_region = m_regions.back().GetNextRegionAddr();
598314564Sdim  }
599314564Sdim
600314564Sdim  return true;
601293116Semaste}
602293116Semaste
603314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
604314564Sdim    lldb::addr_t addr, uint32_t &flags) {
605314564Sdim  region_collection::iterator pos, end = m_regions.end();
606314564Sdim  for (pos = m_regions.begin(); pos != end; pos++) {
607314564Sdim    if ((*pos).AddressInRegion(addr, flags))
608314564Sdim      return true;
609314564Sdim  }
610314564Sdim  return false;
611314564Sdim}
612314564Sdim
613293116Semasteconst AppleObjCTrampolineHandler::DispatchFunction
614314564Sdim    AppleObjCTrampolineHandler::g_dispatch_functions[] = {
615314564Sdim        // NAME                              STRET  SUPER  SUPER2  FIXUP TYPE
616314564Sdim        {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
617314564Sdim        {"objc_msgSend_fixup", false, false, false,
618314564Sdim         DispatchFunction::eFixUpToFix},
619314564Sdim        {"objc_msgSend_fixedup", false, false, false,
620314564Sdim         DispatchFunction::eFixUpFixed},
621314564Sdim        {"objc_msgSend_stret", true, false, false,
622314564Sdim         DispatchFunction::eFixUpNone},
623314564Sdim        {"objc_msgSend_stret_fixup", true, false, false,
624314564Sdim         DispatchFunction::eFixUpToFix},
625314564Sdim        {"objc_msgSend_stret_fixedup", true, false, false,
626314564Sdim         DispatchFunction::eFixUpFixed},
627314564Sdim        {"objc_msgSend_fpret", false, false, false,
628314564Sdim         DispatchFunction::eFixUpNone},
629314564Sdim        {"objc_msgSend_fpret_fixup", false, false, false,
630314564Sdim         DispatchFunction::eFixUpToFix},
631314564Sdim        {"objc_msgSend_fpret_fixedup", false, false, false,
632314564Sdim         DispatchFunction::eFixUpFixed},
633314564Sdim        {"objc_msgSend_fp2ret", false, false, true,
634314564Sdim         DispatchFunction::eFixUpNone},
635314564Sdim        {"objc_msgSend_fp2ret_fixup", false, false, true,
636314564Sdim         DispatchFunction::eFixUpToFix},
637314564Sdim        {"objc_msgSend_fp2ret_fixedup", false, false, true,
638314564Sdim         DispatchFunction::eFixUpFixed},
639314564Sdim        {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
640314564Sdim        {"objc_msgSendSuper_stret", true, true, false,
641314564Sdim         DispatchFunction::eFixUpNone},
642314564Sdim        {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
643314564Sdim        {"objc_msgSendSuper2_fixup", false, true, true,
644314564Sdim         DispatchFunction::eFixUpToFix},
645314564Sdim        {"objc_msgSendSuper2_fixedup", false, true, true,
646314564Sdim         DispatchFunction::eFixUpFixed},
647314564Sdim        {"objc_msgSendSuper2_stret", true, true, true,
648314564Sdim         DispatchFunction::eFixUpNone},
649314564Sdim        {"objc_msgSendSuper2_stret_fixup", true, true, true,
650314564Sdim         DispatchFunction::eFixUpToFix},
651314564Sdim        {"objc_msgSendSuper2_stret_fixedup", true, true, true,
652314564Sdim         DispatchFunction::eFixUpFixed},
653293116Semaste};
654293116Semaste
655314564SdimAppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
656314564Sdim    const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
657314564Sdim    : m_process_wp(), m_objc_module_sp(objc_module_sp),
658314564Sdim      m_lookup_implementation_function_code(nullptr),
659314564Sdim      m_impl_fn_addr(LLDB_INVALID_ADDRESS),
660314564Sdim      m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
661314564Sdim      m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
662314564Sdim  if (process_sp)
663314564Sdim    m_process_wp = process_sp;
664314564Sdim  // Look up the known resolution functions:
665314564Sdim
666314564Sdim  ConstString get_impl_name("class_getMethodImplementation");
667314564Sdim  ConstString get_impl_stret_name("class_getMethodImplementation_stret");
668314564Sdim  ConstString msg_forward_name("_objc_msgForward");
669314564Sdim  ConstString msg_forward_stret_name("_objc_msgForward_stret");
670314564Sdim
671314564Sdim  Target *target = process_sp ? &process_sp->GetTarget() : NULL;
672314564Sdim  const Symbol *class_getMethodImplementation =
673314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
674314564Sdim                                                       eSymbolTypeCode);
675314564Sdim  const Symbol *class_getMethodImplementation_stret =
676314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
677314564Sdim                                                       eSymbolTypeCode);
678314564Sdim  const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
679314564Sdim      msg_forward_name, eSymbolTypeCode);
680314564Sdim  const Symbol *msg_forward_stret =
681314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
682314564Sdim                                                       eSymbolTypeCode);
683314564Sdim
684314564Sdim  if (class_getMethodImplementation)
685314564Sdim    m_impl_fn_addr =
686314564Sdim        class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
687314564Sdim            target);
688314564Sdim  if (class_getMethodImplementation_stret)
689314564Sdim    m_impl_stret_fn_addr =
690314564Sdim        class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
691314564Sdim            target);
692314564Sdim  if (msg_forward)
693314564Sdim    m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
694314564Sdim  if (msg_forward_stret)
695314564Sdim    m_msg_forward_stret_addr =
696314564Sdim        msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
697314564Sdim
698314564Sdim  // FIXME: Do some kind of logging here.
699314564Sdim  if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
700314564Sdim    // If we can't even find the ordinary get method implementation function,
701314564Sdim    // then we aren't going to be able to
702314564Sdim    // step through any method dispatches.  Warn to that effect and get out of
703314564Sdim    // here.
704314564Sdim    if (process_sp->CanJIT()) {
705314564Sdim      process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf(
706314564Sdim          "Could not find implementation lookup function \"%s\""
707314564Sdim          " step in through ObjC method dispatch will not work.\n",
708314564Sdim          get_impl_name.AsCString());
709293116Semaste    }
710314564Sdim    return;
711314564Sdim  } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
712314564Sdim    // It there is no stret return lookup function, assume that it is the same
713314564Sdim    // as the straight lookup:
714314564Sdim    m_impl_stret_fn_addr = m_impl_fn_addr;
715314564Sdim    // Also we will use the version of the lookup code that doesn't rely on the
716314564Sdim    // stret version of the function.
717314564Sdim    m_lookup_implementation_function_code =
718314564Sdim        g_lookup_implementation_no_stret_function_code;
719314564Sdim  } else {
720314564Sdim    m_lookup_implementation_function_code =
721314564Sdim        g_lookup_implementation_with_stret_function_code;
722314564Sdim  }
723314564Sdim
724341825Sdim  // Look up the addresses for the objc dispatch functions and cache
725341825Sdim  // them.  For now I'm inspecting the symbol names dynamically to
726341825Sdim  // figure out how to dispatch to them.  If it becomes more
727341825Sdim  // complicated than this we can turn the g_dispatch_functions char *
728341825Sdim  // array into a template table, and populate the DispatchFunction
729341825Sdim  // map from there.
730314564Sdim
731314564Sdim  for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
732314564Sdim    ConstString name_const_str(g_dispatch_functions[i].name);
733314564Sdim    const Symbol *msgSend_symbol =
734314564Sdim        m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
735314564Sdim                                                         eSymbolTypeCode);
736314564Sdim    if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
737341825Sdim      // FIXME: Make g_dispatch_functions static table of
738341825Sdim      // DispatchFunctions, and have the map be address->index.
739341825Sdim      // Problem is we also need to lookup the dispatch function.  For
740341825Sdim      // now we could have a side table of stret & non-stret dispatch
741341825Sdim      // functions.  If that's as complex as it gets, we're fine.
742314564Sdim
743314564Sdim      lldb::addr_t sym_addr =
744314564Sdim          msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
745314564Sdim
746314564Sdim      m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
747293116Semaste    }
748314564Sdim  }
749293116Semaste
750314564Sdim  // Build our vtable dispatch handler here:
751314564Sdim  m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
752314564Sdim  if (m_vtables_ap.get())
753314564Sdim    m_vtables_ap->ReadRegions();
754293116Semaste}
755293116Semaste
756293116Semastelldb::addr_t
757314564SdimAppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
758314564Sdim                                                  ValueList &dispatch_values) {
759314564Sdim  ThreadSP thread_sp(thread.shared_from_this());
760314564Sdim  ExecutionContext exe_ctx(thread_sp);
761314564Sdim  DiagnosticManager diagnostics;
762314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
763309124Sdim
764314564Sdim  lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
765314564Sdim  FunctionCaller *impl_function_caller = nullptr;
766293116Semaste
767314564Sdim  // Scope for mutex locker:
768314564Sdim  {
769314564Sdim    std::lock_guard<std::mutex> guard(m_impl_function_mutex);
770309124Sdim
771314564Sdim    // First stage is to make the ClangUtility to hold our injected function:
772293116Semaste
773314564Sdim    if (!m_impl_code.get()) {
774314564Sdim      if (m_lookup_implementation_function_code != NULL) {
775321369Sdim        Status error;
776314564Sdim        m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
777314564Sdim            m_lookup_implementation_function_code, eLanguageTypeObjC,
778314564Sdim            g_lookup_implementation_function_name, error));
779314564Sdim        if (error.Fail()) {
780314564Sdim          if (log)
781314564Sdim            log->Printf(
782314564Sdim                "Failed to get Utility Function for implementation lookup: %s.",
783314564Sdim                error.AsCString());
784314564Sdim          m_impl_code.reset();
785314564Sdim          return args_addr;
786314564Sdim        }
787309124Sdim
788314564Sdim        if (!m_impl_code->Install(diagnostics, exe_ctx)) {
789314564Sdim          if (log) {
790314564Sdim            log->Printf("Failed to install implementation lookup.");
791314564Sdim            diagnostics.Dump(log);
792314564Sdim          }
793314564Sdim          m_impl_code.reset();
794314564Sdim          return args_addr;
795293116Semaste        }
796314564Sdim      } else {
797314564Sdim        if (log)
798314564Sdim          log->Printf("No method lookup implementation code.");
799314564Sdim        return LLDB_INVALID_ADDRESS;
800314564Sdim      }
801309124Sdim
802314564Sdim      // Next make the runner function for our implementation utility function.
803314564Sdim      ClangASTContext *clang_ast_context =
804314564Sdim          thread.GetProcess()->GetTarget().GetScratchClangASTContext();
805314564Sdim      CompilerType clang_void_ptr_type =
806314564Sdim          clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
807321369Sdim      Status error;
808309124Sdim
809314564Sdim      impl_function_caller = m_impl_code->MakeFunctionCaller(
810314564Sdim          clang_void_ptr_type, dispatch_values, thread_sp, error);
811314564Sdim      if (error.Fail()) {
812293116Semaste        if (log)
813314564Sdim          log->Printf(
814314564Sdim              "Error getting function caller for dispatch lookup: \"%s\".",
815314564Sdim              error.AsCString());
816293116Semaste        return args_addr;
817314564Sdim      }
818314564Sdim    } else {
819314564Sdim      impl_function_caller = m_impl_code->GetFunctionCaller();
820293116Semaste    }
821314564Sdim  }
822309124Sdim
823314564Sdim  diagnostics.Clear();
824314564Sdim
825341825Sdim  // Now write down the argument values for this particular call.
826341825Sdim  // This looks like it might be a race condition if other threads
827341825Sdim  // were calling into here, but actually it isn't because we allocate
828341825Sdim  // a new args structure for this call by passing args_addr =
829341825Sdim  // LLDB_INVALID_ADDRESS...
830314564Sdim
831314564Sdim  if (!impl_function_caller->WriteFunctionArguments(
832314564Sdim          exe_ctx, args_addr, dispatch_values, diagnostics)) {
833314564Sdim    if (log) {
834314564Sdim      log->Printf("Error writing function arguments.");
835314564Sdim      diagnostics.Dump(log);
836314564Sdim    }
837293116Semaste    return args_addr;
838314564Sdim  }
839314564Sdim
840314564Sdim  return args_addr;
841293116Semaste}
842293116Semaste
843293116SemasteThreadPlanSP
844314564SdimAppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
845314564Sdim                                                       bool stop_others) {
846314564Sdim  ThreadPlanSP ret_plan_sp;
847314564Sdim  lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
848314564Sdim
849314564Sdim  DispatchFunction this_dispatch;
850314564Sdim  bool found_it = false;
851314564Sdim
852341825Sdim  // First step is to look and see if we are in one of the known ObjC
853341825Sdim  // dispatch functions.  We've already compiled a table of same, so
854341825Sdim  // consult it.
855314564Sdim
856314564Sdim  MsgsendMap::iterator pos;
857314564Sdim  pos = m_msgSend_map.find(curr_pc);
858314564Sdim  if (pos != m_msgSend_map.end()) {
859314564Sdim    this_dispatch = g_dispatch_functions[(*pos).second];
860314564Sdim    found_it = true;
861314564Sdim  }
862314564Sdim
863314564Sdim  // Next check to see if we are in a vtable region:
864314564Sdim
865314564Sdim  if (!found_it) {
866314564Sdim    uint32_t flags;
867314564Sdim    if (m_vtables_ap.get()) {
868314564Sdim      found_it = m_vtables_ap->IsAddressInVTables(curr_pc, flags);
869314564Sdim      if (found_it) {
870314564Sdim        this_dispatch.name = "vtable";
871314564Sdim        this_dispatch.stret_return =
872314564Sdim            (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
873314564Sdim            AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
874314564Sdim        this_dispatch.is_super = false;
875314564Sdim        this_dispatch.is_super2 = false;
876314564Sdim        this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
877314564Sdim      }
878293116Semaste    }
879314564Sdim  }
880314564Sdim
881314564Sdim  if (found_it) {
882314564Sdim    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
883314564Sdim
884341825Sdim    // We are decoding a method dispatch.  First job is to pull the
885341825Sdim    // arguments out:
886314564Sdim
887314564Sdim    lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
888314564Sdim
889314564Sdim    const ABI *abi = NULL;
890314564Sdim    ProcessSP process_sp(thread.CalculateProcess());
891314564Sdim    if (process_sp)
892314564Sdim      abi = process_sp->GetABI().get();
893314564Sdim    if (abi == NULL)
894314564Sdim      return ret_plan_sp;
895314564Sdim
896314564Sdim    TargetSP target_sp(thread.CalculateTarget());
897314564Sdim
898314564Sdim    ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
899314564Sdim    ValueList argument_values;
900314564Sdim    Value void_ptr_value;
901314564Sdim    CompilerType clang_void_ptr_type =
902314564Sdim        clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
903314564Sdim    void_ptr_value.SetValueType(Value::eValueTypeScalar);
904314564Sdim    // void_ptr_value.SetContext (Value::eContextTypeClangType,
905314564Sdim    // clang_void_ptr_type);
906314564Sdim    void_ptr_value.SetCompilerType(clang_void_ptr_type);
907314564Sdim
908314564Sdim    int obj_index;
909314564Sdim    int sel_index;
910314564Sdim
911341825Sdim    // If this is a struct return dispatch, then the first argument is
912341825Sdim    // the return struct pointer, and the object is the second, and
913341825Sdim    // the selector is the third.  Otherwise the object is the first
914341825Sdim    // and the selector the second.
915314564Sdim    if (this_dispatch.stret_return) {
916314564Sdim      obj_index = 1;
917314564Sdim      sel_index = 2;
918314564Sdim      argument_values.PushValue(void_ptr_value);
919314564Sdim      argument_values.PushValue(void_ptr_value);
920314564Sdim      argument_values.PushValue(void_ptr_value);
921314564Sdim    } else {
922314564Sdim      obj_index = 0;
923314564Sdim      sel_index = 1;
924314564Sdim      argument_values.PushValue(void_ptr_value);
925314564Sdim      argument_values.PushValue(void_ptr_value);
926293116Semaste    }
927293116Semaste
928314564Sdim    bool success = abi->GetArgumentValues(thread, argument_values);
929314564Sdim    if (!success)
930314564Sdim      return ret_plan_sp;
931293116Semaste
932314564Sdim    lldb::addr_t obj_addr =
933314564Sdim        argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
934314564Sdim    if (obj_addr == 0x0) {
935314564Sdim      if (log)
936314564Sdim        log->Printf(
937314564Sdim            "Asked to step to dispatch to nil object, returning empty plan.");
938314564Sdim      return ret_plan_sp;
939314564Sdim    }
940314564Sdim
941314564Sdim    ExecutionContext exe_ctx(thread.shared_from_this());
942314564Sdim    Process *process = exe_ctx.GetProcessPtr();
943341825Sdim    // isa_addr will store the class pointer that the method is being
944341825Sdim    // dispatched to - so either the class directly or the super class
945341825Sdim    // if this is one of the objc_msgSendSuper flavors.  That's mostly
946341825Sdim    // used to look up the class/selector pair in our cache.
947314564Sdim
948314564Sdim    lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
949314564Sdim    lldb::addr_t sel_addr =
950314564Sdim        argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
951314564Sdim
952341825Sdim    // Figure out the class this is being dispatched to and see if
953341825Sdim    // we've already cached this method call, If so we can push a
954341825Sdim    // run-to-address plan directly.  Otherwise we have to figure out
955341825Sdim    // where the implementation lives.
956314564Sdim
957314564Sdim    if (this_dispatch.is_super) {
958314564Sdim      if (this_dispatch.is_super2) {
959341825Sdim        // In the objc_msgSendSuper2 case, we don't get the object
960341825Sdim        // directly, we get a structure containing the object and the
961341825Sdim        // class to which the super message is being sent.  So we need
962341825Sdim        // to dig the super out of the class and use that.
963314564Sdim
964314564Sdim        Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
965314564Sdim        super_value.GetScalar() += process->GetAddressByteSize();
966314564Sdim        super_value.ResolveValue(&exe_ctx);
967314564Sdim
968314564Sdim        if (super_value.GetScalar().IsValid()) {
969314564Sdim
970314564Sdim          // isa_value now holds the class pointer.  The second word of the
971314564Sdim          // class pointer is the super-class pointer:
972314564Sdim          super_value.GetScalar() += process->GetAddressByteSize();
973314564Sdim          super_value.ResolveValue(&exe_ctx);
974314564Sdim          if (super_value.GetScalar().IsValid())
975314564Sdim            isa_addr = super_value.GetScalar().ULongLong();
976314564Sdim          else {
977293116Semaste            if (log)
978314564Sdim              log->Printf("Failed to extract the super class value from the "
979314564Sdim                          "class in objc_super.");
980314564Sdim          }
981314564Sdim        } else {
982314564Sdim          if (log)
983314564Sdim            log->Printf("Failed to extract the class value from objc_super.");
984293116Semaste        }
985314564Sdim      } else {
986341825Sdim        // In the objc_msgSendSuper case, we don't get the object
987341825Sdim        // directly, we get a two element structure containing the
988341825Sdim        // object and the super class to which the super message is
989341825Sdim        // being sent.  So the class we want is the second element of
990341825Sdim        // this structure.
991293116Semaste
992314564Sdim        Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
993314564Sdim        super_value.GetScalar() += process->GetAddressByteSize();
994314564Sdim        super_value.ResolveValue(&exe_ctx);
995314564Sdim
996314564Sdim        if (super_value.GetScalar().IsValid()) {
997314564Sdim          isa_addr = super_value.GetScalar().ULongLong();
998314564Sdim        } else {
999314564Sdim          if (log)
1000314564Sdim            log->Printf("Failed to extract the class value from objc_super.");
1001293116Semaste        }
1002314564Sdim      }
1003314564Sdim    } else {
1004314564Sdim      // In the direct dispatch case, the object->isa is the class pointer we
1005314564Sdim      // want.
1006293116Semaste
1007314564Sdim      // This is a little cheesy, but since object->isa is the first field,
1008314564Sdim      // making the object value a load address value and resolving it will get
1009314564Sdim      // the pointer sized data pointed to by that value...
1010293116Semaste
1011341825Sdim      // Note, it isn't a fatal error not to be able to get the
1012341825Sdim      // address from the object, since this might be a "tagged
1013341825Sdim      // pointer" which isn't a real object, but rather some word
1014314564Sdim      // length encoded dingus.
1015314564Sdim
1016314564Sdim      Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1017314564Sdim
1018314564Sdim      isa_value.SetValueType(Value::eValueTypeLoadAddress);
1019314564Sdim      isa_value.ResolveValue(&exe_ctx);
1020314564Sdim      if (isa_value.GetScalar().IsValid()) {
1021314564Sdim        isa_addr = isa_value.GetScalar().ULongLong();
1022314564Sdim      } else {
1023314564Sdim        if (log)
1024314564Sdim          log->Printf("Failed to extract the isa value from object.");
1025314564Sdim      }
1026293116Semaste    }
1027314564Sdim
1028314564Sdim    // Okay, we've got the address of the class for which we're resolving this,
1029314564Sdim    // let's see if it's in our cache:
1030314564Sdim    lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1031314564Sdim
1032314564Sdim    if (isa_addr != LLDB_INVALID_ADDRESS) {
1033314564Sdim      if (log) {
1034314564Sdim        log->Printf("Resolving call for class - 0x%" PRIx64
1035314564Sdim                    " and selector - 0x%" PRIx64,
1036314564Sdim                    isa_addr, sel_addr);
1037314564Sdim      }
1038314564Sdim      ObjCLanguageRuntime *objc_runtime =
1039314564Sdim          thread.GetProcess()->GetObjCLanguageRuntime();
1040314564Sdim      assert(objc_runtime != NULL);
1041314564Sdim
1042314564Sdim      impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1043314564Sdim    }
1044314564Sdim
1045314564Sdim    if (impl_addr != LLDB_INVALID_ADDRESS) {
1046314564Sdim      // Yup, it was in the cache, so we can run to that address directly.
1047314564Sdim
1048314564Sdim      if (log)
1049314564Sdim        log->Printf("Found implementation address in cache: 0x%" PRIx64,
1050314564Sdim                    impl_addr);
1051314564Sdim
1052314564Sdim      ret_plan_sp.reset(
1053314564Sdim          new ThreadPlanRunToAddress(thread, impl_addr, stop_others));
1054314564Sdim    } else {
1055314564Sdim      // We haven't seen this class/selector pair yet.  Look it up.
1056314564Sdim      StreamString errors;
1057314564Sdim      Address impl_code_address;
1058314564Sdim
1059314564Sdim      ValueList dispatch_values;
1060314564Sdim
1061314564Sdim      // We've will inject a little function in the target that takes the
1062314564Sdim      // object, selector and some flags,
1063314564Sdim      // and figures out the implementation.  Looks like:
1064314564Sdim      //      void *__lldb_objc_find_implementation_for_selector (void *object,
1065314564Sdim      //                                                          void *sel,
1066314564Sdim      //                                                          int is_stret,
1067314564Sdim      //                                                          int is_super,
1068314564Sdim      //                                                          int is_super2,
1069314564Sdim      //                                                          int is_fixup,
1070314564Sdim      //                                                          int is_fixed,
1071314564Sdim      //                                                          int debug)
1072314564Sdim      // So set up the arguments for that call.
1073314564Sdim
1074314564Sdim      dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1075314564Sdim      dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1076314564Sdim
1077314564Sdim      Value flag_value;
1078314564Sdim      CompilerType clang_int_type =
1079314564Sdim          clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1080314564Sdim              lldb::eEncodingSint, 32);
1081314564Sdim      flag_value.SetValueType(Value::eValueTypeScalar);
1082314564Sdim      // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1083314564Sdim      flag_value.SetCompilerType(clang_int_type);
1084314564Sdim
1085314564Sdim      if (this_dispatch.stret_return)
1086314564Sdim        flag_value.GetScalar() = 1;
1087314564Sdim      else
1088314564Sdim        flag_value.GetScalar() = 0;
1089314564Sdim      dispatch_values.PushValue(flag_value);
1090314564Sdim
1091314564Sdim      if (this_dispatch.is_super)
1092314564Sdim        flag_value.GetScalar() = 1;
1093314564Sdim      else
1094314564Sdim        flag_value.GetScalar() = 0;
1095314564Sdim      dispatch_values.PushValue(flag_value);
1096314564Sdim
1097314564Sdim      if (this_dispatch.is_super2)
1098314564Sdim        flag_value.GetScalar() = 1;
1099314564Sdim      else
1100314564Sdim        flag_value.GetScalar() = 0;
1101314564Sdim      dispatch_values.PushValue(flag_value);
1102314564Sdim
1103314564Sdim      switch (this_dispatch.fixedup) {
1104314564Sdim      case DispatchFunction::eFixUpNone:
1105314564Sdim        flag_value.GetScalar() = 0;
1106314564Sdim        dispatch_values.PushValue(flag_value);
1107314564Sdim        dispatch_values.PushValue(flag_value);
1108314564Sdim        break;
1109314564Sdim      case DispatchFunction::eFixUpFixed:
1110314564Sdim        flag_value.GetScalar() = 1;
1111314564Sdim        dispatch_values.PushValue(flag_value);
1112314564Sdim        flag_value.GetScalar() = 1;
1113314564Sdim        dispatch_values.PushValue(flag_value);
1114314564Sdim        break;
1115314564Sdim      case DispatchFunction::eFixUpToFix:
1116314564Sdim        flag_value.GetScalar() = 1;
1117314564Sdim        dispatch_values.PushValue(flag_value);
1118314564Sdim        flag_value.GetScalar() = 0;
1119314564Sdim        dispatch_values.PushValue(flag_value);
1120314564Sdim        break;
1121314564Sdim      }
1122314564Sdim      if (log && log->GetVerbose())
1123314564Sdim        flag_value.GetScalar() = 1;
1124314564Sdim      else
1125314564Sdim        flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1126314564Sdim      dispatch_values.PushValue(flag_value);
1127314564Sdim
1128341825Sdim      // The step through code might have to fill in the cache, so it
1129341825Sdim      // is not safe to run only one thread.  So we override the
1130341825Sdim      // stop_others value passed in to us here:
1131314564Sdim      const bool trampoline_stop_others = false;
1132314564Sdim      ret_plan_sp.reset(new AppleThreadPlanStepThroughObjCTrampoline(
1133314564Sdim          thread, this, dispatch_values, isa_addr, sel_addr,
1134314564Sdim          trampoline_stop_others));
1135314564Sdim      if (log) {
1136314564Sdim        StreamString s;
1137314564Sdim        ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1138314564Sdim        log->Printf("Using ObjC step plan: %s.\n", s.GetData());
1139314564Sdim      }
1140314564Sdim    }
1141314564Sdim  }
1142314564Sdim
1143314564Sdim  return ret_plan_sp;
1144293116Semaste}
1145293116Semaste
1146293116SemasteFunctionCaller *
1147314564SdimAppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1148314564Sdim  return m_impl_code->GetFunctionCaller();
1149293116Semaste}
1150