AppleObjCTrampolineHandler.cpp revision 353358
1314564Sdim//===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++
2314564Sdim//-*-===//
3293116Semaste//
4353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5353358Sdim// See https://llvm.org/LICENSE.txt for license information.
6353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7293116Semaste//
8293116Semaste//===----------------------------------------------------------------------===//
9293116Semaste
10293116Semaste#include "AppleObjCTrampolineHandler.h"
11293116Semaste#include "AppleThreadPlanStepThroughObjCTrampoline.h"
12293116Semaste
13293116Semaste#include "lldb/Breakpoint/StoppointCallbackContext.h"
14293116Semaste#include "lldb/Core/Debugger.h"
15293116Semaste#include "lldb/Core/Module.h"
16293116Semaste#include "lldb/Core/StreamFile.h"
17293116Semaste#include "lldb/Core/Value.h"
18309124Sdim#include "lldb/Expression/DiagnosticManager.h"
19309124Sdim#include "lldb/Expression/FunctionCaller.h"
20293116Semaste#include "lldb/Expression/UserExpression.h"
21293116Semaste#include "lldb/Expression/UtilityFunction.h"
22293116Semaste#include "lldb/Symbol/ClangASTContext.h"
23293116Semaste#include "lldb/Symbol/Symbol.h"
24293116Semaste#include "lldb/Target/ABI.h"
25309124Sdim#include "lldb/Target/ExecutionContext.h"
26293116Semaste#include "lldb/Target/Process.h"
27293116Semaste#include "lldb/Target/RegisterContext.h"
28293116Semaste#include "lldb/Target/Target.h"
29293116Semaste#include "lldb/Target/Thread.h"
30293116Semaste#include "lldb/Target/ThreadPlanRunToAddress.h"
31321369Sdim#include "lldb/Utility/ConstString.h"
32321369Sdim#include "lldb/Utility/FileSpec.h"
33321369Sdim#include "lldb/Utility/Log.h"
34293116Semaste
35293116Semaste#include "llvm/ADT/STLExtras.h"
36293116Semaste
37353358Sdim#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
38353358Sdim
39353358Sdim#include <memory>
40353358Sdim
41293116Semasteusing namespace lldb;
42293116Semasteusing namespace lldb_private;
43293116Semaste
44314564Sdimconst char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name =
45314564Sdim    "__lldb_objc_find_implementation_for_selector";
46314564Sdimconst char *AppleObjCTrampolineHandler::
47314564Sdim    g_lookup_implementation_with_stret_function_code =
48314564Sdim        "                               \n\
49341825Sdimextern \"C\"                                                                 \n\
50341825Sdim{                                                                            \n\
51341825Sdim    extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
52341825Sdim    extern void *class_getMethodImplementation_stret(void *objc_class,       \n\
53341825Sdim                                                     void *sel);             \n\
54341825Sdim    extern void * object_getClass (id object);                               \n\
55341825Sdim    extern void * sel_getUid(char *name);                                    \n\
56341825Sdim    extern int printf(const char *format, ...);                              \n\
57341825Sdim}                                                                            \n\
58341825Sdimextern \"C\" void * __lldb_objc_find_implementation_for_selector (           \n\
59341825Sdim                                                    void *object,            \n\
60341825Sdim                                                    void *sel,               \n\
61341825Sdim                                                    int is_stret,            \n\
62341825Sdim                                                    int is_super,            \n\
63341825Sdim                                                    int is_super2,           \n\
64341825Sdim                                                    int is_fixup,            \n\
65341825Sdim                                                    int is_fixed,            \n\
66341825Sdim                                                    int debug)               \n\
67341825Sdim{                                                                            \n\
68341825Sdim    struct __lldb_imp_return_struct                                          \n\
69341825Sdim    {                                                                        \n\
70341825Sdim        void *class_addr;                                                    \n\
71341825Sdim        void *sel_addr;                                                      \n\
72341825Sdim        void *impl_addr;                                                     \n\
73341825Sdim    };                                                                       \n\
74341825Sdim                                                                             \n\
75341825Sdim    struct __lldb_objc_class {                                               \n\
76341825Sdim        void *isa;                                                           \n\
77341825Sdim        void *super_ptr;                                                     \n\
78341825Sdim    };                                                                       \n\
79341825Sdim    struct __lldb_objc_super {                                               \n\
80344779Sdim        void *receiver;                                                      \n\
81341825Sdim        struct __lldb_objc_class *class_ptr;                                 \n\
82341825Sdim    };                                                                       \n\
83341825Sdim    struct __lldb_msg_ref {                                                  \n\
84341825Sdim        void *dont_know;                                                     \n\
85341825Sdim        void *sel;                                                           \n\
86341825Sdim    };                                                                       \n\
87341825Sdim                                                                             \n\
88341825Sdim    struct __lldb_imp_return_struct return_struct;                           \n\
89341825Sdim                                                                             \n\
90341825Sdim    if (debug)                                                               \n\
91341825Sdim        printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"\n\
92341825Sdim                \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\",            \n\
93341825Sdim                 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);\n\
94341825Sdim    if (is_super)                                                            \n\
95341825Sdim    {                                                                        \n\
96341825Sdim        if (is_super2)                                                       \n\
97341825Sdim        {                                                                    \n\
98341825Sdim            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;\n\
99341825Sdim        }                                                                    \n\
100341825Sdim        else                                                                 \n\
101341825Sdim        {                                                                    \n\
102341825Sdim            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;\n\
103341825Sdim        }                                                                    \n\
104341825Sdim    }                                                                        \n\
105341825Sdim    else                                                                     \n\
106341825Sdim    {                                                                        \n\
107341825Sdim        // This code seems a little funny, but has its reasons...            \n\
108341825Sdim                                                                             \n\
109341825Sdim        // The call to [object class] is here because if this is a           \n\
110341825Sdim        // class, and has not been called into yet, we need to do            \n\
111341825Sdim        // something to force the class to initialize itself.                \n\
112341825Sdim        // Then the call to object_getClass will actually return the         \n\
113341825Sdim        // correct class, either the class if object is a class              \n\
114341825Sdim        // instance, or the meta-class if it is a class pointer.             \n\
115341825Sdim        void *class_ptr = (void *) [(id) object class];                      \n\
116341825Sdim        return_struct.class_addr = (id)  object_getClass((id) object);       \n\
117341825Sdim        if (debug)                                                           \n\
118341825Sdim        {                                                                    \n\
119341825Sdim            if (class_ptr == object)                                         \n\
120341825Sdim            {                                                                \n\
121341825Sdim                printf (\"Found a class object, need to use the meta class %p -> %p\\n\",\n\
122341825Sdim                        class_ptr, return_struct.class_addr);                \n\
123341825Sdim            }                                                                \n\
124341825Sdim            else                                                             \n\
125341825Sdim            {                                                                \n\
126341825Sdim                 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\
127341825Sdim                 class_ptr, return_struct.class_addr);                       \n\
128341825Sdim            }                                                                \n\
129341825Sdim        }                                                                    \n\
130341825Sdim    }                                                                        \n\
131341825Sdim                                                                             \n\
132341825Sdim    if (is_fixup)                                                            \n\
133341825Sdim    {                                                                        \n\
134341825Sdim        if (is_fixed)                                                        \n\
135341825Sdim        {                                                                    \n\
136341825Sdim            return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
137341825Sdim        }                                                                    \n\
138341825Sdim        else                                                                 \n\
139341825Sdim        {                                                                    \n\
140341825Sdim            char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
141341825Sdim            return_struct.sel_addr = sel_getUid (sel_name);                  \n\
142341825Sdim            if (debug)                                                       \n\
143341825Sdim                printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
144341825Sdim                        return_struct.sel_addr, sel_name);                   \n\
145341825Sdim        }                                                                    \n\
146341825Sdim    }                                                                        \n\
147341825Sdim    else                                                                     \n\
148341825Sdim    {                                                                        \n\
149341825Sdim        return_struct.sel_addr = sel;                                        \n\
150341825Sdim    }                                                                        \n\
151341825Sdim                                                                             \n\
152341825Sdim    if (is_stret)                                                            \n\
153341825Sdim    {                                                                        \n\
154341825Sdim        return_struct.impl_addr =                                            \n\
155341825Sdim          class_getMethodImplementation_stret (return_struct.class_addr,     \n\
156341825Sdim                                               return_struct.sel_addr);      \n\
157341825Sdim    }                                                                        \n\
158341825Sdim    else                                                                     \n\
159341825Sdim    {                                                                        \n\
160341825Sdim        return_struct.impl_addr =                                            \n\
161341825Sdim            class_getMethodImplementation (return_struct.class_addr,         \n\
162341825Sdim                                           return_struct.sel_addr);          \n\
163341825Sdim    }                                                                        \n\
164341825Sdim    if (debug)                                                               \n\
165341825Sdim        printf (\"\\n*** Returning implementation: %p.\\n\",                 \n\
166341825Sdim                          return_struct.impl_addr);                          \n\
167341825Sdim                                                                             \n\
168341825Sdim    return return_struct.impl_addr;                                          \n\
169341825Sdim}                                                                            \n\
170293116Semaste";
171314564Sdimconst char *
172314564Sdim    AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =
173314564Sdim        "                      \n\
174341825Sdimextern \"C\"                                                                 \n\
175341825Sdim{                                                                            \n\
176341825Sdim    extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\
177341825Sdim    extern void * object_getClass (id object);                               \n\
178341825Sdim    extern void * sel_getUid(char *name);                                    \n\
179341825Sdim    extern int printf(const char *format, ...);                              \n\
180341825Sdim}                                                                            \n\
181293116Semasteextern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object,                                 \n\
182341825Sdim                                                    void *sel,               \n\
183341825Sdim                                                    int is_stret,            \n\
184341825Sdim                                                    int is_super,            \n\
185341825Sdim                                                    int is_super2,           \n\
186341825Sdim                                                    int is_fixup,            \n\
187341825Sdim                                                    int is_fixed,            \n\
188341825Sdim                                                    int debug)               \n\
189341825Sdim{                                                                            \n\
190341825Sdim    struct __lldb_imp_return_struct                                          \n\
191341825Sdim    {                                                                        \n\
192341825Sdim        void *class_addr;                                                    \n\
193341825Sdim        void *sel_addr;                                                      \n\
194341825Sdim        void *impl_addr;                                                     \n\
195341825Sdim    };                                                                       \n\
196341825Sdim                                                                             \n\
197341825Sdim    struct __lldb_objc_class {                                               \n\
198341825Sdim        void *isa;                                                           \n\
199341825Sdim        void *super_ptr;                                                     \n\
200341825Sdim    };                                                                       \n\
201341825Sdim    struct __lldb_objc_super {                                               \n\
202344779Sdim        void *receiver;                                                      \n\
203341825Sdim        struct __lldb_objc_class *class_ptr;                                 \n\
204341825Sdim    };                                                                       \n\
205341825Sdim    struct __lldb_msg_ref {                                                  \n\
206341825Sdim        void *dont_know;                                                     \n\
207341825Sdim        void *sel;                                                           \n\
208341825Sdim    };                                                                       \n\
209341825Sdim                                                                             \n\
210341825Sdim    struct __lldb_imp_return_struct return_struct;                           \n\
211341825Sdim                                                                             \n\
212341825Sdim    if (debug)                                                               \n\
213293116Semaste        printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \"                          \n\
214341825Sdim                \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\",            \n\
215293116Semaste                 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed);                               \n\
216341825Sdim    if (is_super)                                                            \n\
217341825Sdim    {                                                                        \n\
218341825Sdim        if (is_super2)                                                       \n\
219341825Sdim        {                                                                    \n\
220293116Semaste            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr;                    \n\
221341825Sdim        }                                                                    \n\
222341825Sdim        else                                                                 \n\
223341825Sdim        {                                                                    \n\
224293116Semaste            return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;                               \n\
225341825Sdim        }                                                                    \n\
226341825Sdim    }                                                                        \n\
227341825Sdim    else                                                                     \n\
228341825Sdim    {                                                                        \n\
229341825Sdim        // This code seems a little funny, but has its reasons...            \n\
230293116Semaste        // The call to [object class] is here because if this is a class, and has not been called into          \n\
231293116Semaste        // yet, we need to do something to force the class to initialize itself.                                \n\
232293116Semaste        // Then the call to object_getClass will actually return the correct class, either the class            \n\
233293116Semaste        // if object is a class instance, or the meta-class if it is a class pointer.                           \n\
234341825Sdim        void *class_ptr = (void *) [(id) object class];                      \n\
235341825Sdim        return_struct.class_addr = (id)  object_getClass((id) object);       \n\
236341825Sdim        if (debug)                                                           \n\
237341825Sdim        {                                                                    \n\
238341825Sdim            if (class_ptr == object)                                         \n\
239341825Sdim            {                                                                \n\
240293116Semaste                printf (\"Found a class object, need to return the meta class %p -> %p\\n\",                    \n\
241341825Sdim                        class_ptr, return_struct.class_addr);                \n\
242341825Sdim            }                                                                \n\
243341825Sdim            else                                                             \n\
244341825Sdim            {                                                                \n\
245293116Semaste                 printf (\"[object class] returned: %p object_getClass: %p.\\n\",                               \n\
246341825Sdim                 class_ptr, return_struct.class_addr);                       \n\
247341825Sdim            }                                                                \n\
248341825Sdim        }                                                                    \n\
249341825Sdim    }                                                                        \n\
250341825Sdim                                                                             \n\
251341825Sdim    if (is_fixup)                                                            \n\
252341825Sdim    {                                                                        \n\
253341825Sdim        if (is_fixed)                                                        \n\
254341825Sdim        {                                                                    \n\
255341825Sdim            return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;          \n\
256341825Sdim        }                                                                    \n\
257341825Sdim        else                                                                 \n\
258341825Sdim        {                                                                    \n\
259341825Sdim            char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;         \n\
260341825Sdim            return_struct.sel_addr = sel_getUid (sel_name);                  \n\
261341825Sdim            if (debug)                                                       \n\
262341825Sdim                printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\",\n\
263341825Sdim                        return_struct.sel_addr, sel_name);                   \n\
264341825Sdim        }                                                                    \n\
265341825Sdim    }                                                                        \n\
266341825Sdim    else                                                                     \n\
267341825Sdim    {                                                                        \n\
268341825Sdim        return_struct.sel_addr = sel;                                        \n\
269341825Sdim    }                                                                        \n\
270341825Sdim                                                                             \n\
271341825Sdim    return_struct.impl_addr =                                                \n\
272341825Sdim      class_getMethodImplementation (return_struct.class_addr,               \n\
273341825Sdim                                     return_struct.sel_addr);                \n\
274341825Sdim    if (debug)                                                               \n\
275341825Sdim        printf (\"\\n*** Returning implementation: 0x%p.\\n\",               \n\
276341825Sdim          return_struct.impl_addr);                                          \n\
277341825Sdim                                                                             \n\
278341825Sdim    return return_struct.impl_addr;                                          \n\
279341825Sdim}                                                                            \n\
280293116Semaste";
281293116Semaste
282314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(
283314564Sdim    AppleObjCVTables *owner, lldb::addr_t header_addr)
284314564Sdim    : m_valid(true), m_owner(owner), m_header_addr(header_addr),
285314564Sdim      m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) {
286314564Sdim  SetUpRegion();
287293116Semaste}
288293116Semaste
289314564SdimAppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() {}
290293116Semaste
291314564Sdimvoid AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {
292314564Sdim  // The header looks like:
293314564Sdim  //
294314564Sdim  //   uint16_t headerSize
295314564Sdim  //   uint16_t descSize
296314564Sdim  //   uint32_t descCount
297314564Sdim  //   void * next
298314564Sdim  //
299314564Sdim  // First read in the header:
300293116Semaste
301314564Sdim  char memory_buffer[16];
302314564Sdim  ProcessSP process_sp = m_owner->GetProcessSP();
303314564Sdim  if (!process_sp)
304314564Sdim    return;
305314564Sdim  DataExtractor data(memory_buffer, sizeof(memory_buffer),
306314564Sdim                     process_sp->GetByteOrder(),
307314564Sdim                     process_sp->GetAddressByteSize());
308314564Sdim  size_t actual_size = 8 + process_sp->GetAddressByteSize();
309321369Sdim  Status error;
310314564Sdim  size_t bytes_read =
311314564Sdim      process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);
312314564Sdim  if (bytes_read != actual_size) {
313314564Sdim    m_valid = false;
314314564Sdim    return;
315314564Sdim  }
316293116Semaste
317314564Sdim  lldb::offset_t offset = 0;
318314564Sdim  const uint16_t header_size = data.GetU16(&offset);
319314564Sdim  const uint16_t descriptor_size = data.GetU16(&offset);
320314564Sdim  const size_t num_descriptors = data.GetU32(&offset);
321293116Semaste
322314564Sdim  m_next_region = data.GetPointer(&offset);
323314564Sdim
324314564Sdim  // If the header size is 0, that means we've come in too early before this
325314564Sdim  // data is set up.
326314564Sdim  // Set ourselves as not valid, and continue.
327314564Sdim  if (header_size == 0 || num_descriptors == 0) {
328314564Sdim    m_valid = false;
329314564Sdim    return;
330314564Sdim  }
331314564Sdim
332314564Sdim  // Now read in all the descriptors:
333314564Sdim  // The descriptor looks like:
334314564Sdim  //
335314564Sdim  // uint32_t offset
336314564Sdim  // uint32_t flags
337314564Sdim  //
338341825Sdim  // Where offset is either 0 - in which case it is unused, or it is
339341825Sdim  // the offset of the vtable code from the beginning of the
340341825Sdim  // descriptor record.  Below, we'll convert that into an absolute
341341825Sdim  // code address, since I don't want to have to compute it over and
342341825Sdim  // over.
343314564Sdim
344314564Sdim  // Ingest the whole descriptor array:
345314564Sdim  const lldb::addr_t desc_ptr = m_header_addr + header_size;
346314564Sdim  const size_t desc_array_size = num_descriptors * descriptor_size;
347314564Sdim  DataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));
348314564Sdim  uint8_t *dst = (uint8_t *)data_sp->GetBytes();
349314564Sdim
350314564Sdim  DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),
351314564Sdim                               process_sp->GetAddressByteSize());
352314564Sdim  bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);
353314564Sdim  if (bytes_read != desc_array_size) {
354314564Sdim    m_valid = false;
355314564Sdim    return;
356314564Sdim  }
357314564Sdim
358314564Sdim  // The actual code for the vtables will be laid out consecutively, so I also
359314564Sdim  // compute the start and end of the whole code block.
360314564Sdim
361314564Sdim  offset = 0;
362314564Sdim  m_code_start_addr = 0;
363314564Sdim  m_code_end_addr = 0;
364314564Sdim
365314564Sdim  for (size_t i = 0; i < num_descriptors; i++) {
366314564Sdim    lldb::addr_t start_offset = offset;
367314564Sdim    uint32_t voffset = desc_extractor.GetU32(&offset);
368314564Sdim    uint32_t flags = desc_extractor.GetU32(&offset);
369314564Sdim    lldb::addr_t code_addr = desc_ptr + start_offset + voffset;
370314564Sdim    m_descriptors.push_back(VTableDescriptor(flags, code_addr));
371314564Sdim
372314564Sdim    if (m_code_start_addr == 0 || code_addr < m_code_start_addr)
373314564Sdim      m_code_start_addr = code_addr;
374314564Sdim    if (code_addr > m_code_end_addr)
375314564Sdim      m_code_end_addr = code_addr;
376314564Sdim
377314564Sdim    offset = start_offset + descriptor_size;
378314564Sdim  }
379341825Sdim  // Finally, a little bird told me that all the vtable code blocks
380341825Sdim  // are the same size.  Let's compute the blocks and if they are all
381341825Sdim  // the same add the size to the code end address:
382314564Sdim  lldb::addr_t code_size = 0;
383314564Sdim  bool all_the_same = true;
384314564Sdim  for (size_t i = 0; i < num_descriptors - 1; i++) {
385314564Sdim    lldb::addr_t this_size =
386314564Sdim        m_descriptors[i + 1].code_start - m_descriptors[i].code_start;
387314564Sdim    if (code_size == 0)
388314564Sdim      code_size = this_size;
389314564Sdim    else {
390314564Sdim      if (this_size != code_size)
391314564Sdim        all_the_same = false;
392314564Sdim      if (this_size > code_size)
393314564Sdim        code_size = this_size;
394293116Semaste    }
395314564Sdim  }
396314564Sdim  if (all_the_same)
397314564Sdim    m_code_end_addr += code_size;
398293116Semaste}
399293116Semaste
400314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::
401314564Sdim    AddressInRegion(lldb::addr_t addr, uint32_t &flags) {
402314564Sdim  if (!IsValid())
403293116Semaste    return false;
404293116Semaste
405314564Sdim  if (addr < m_code_start_addr || addr > m_code_end_addr)
406314564Sdim    return false;
407314564Sdim
408314564Sdim  std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();
409314564Sdim  for (pos = m_descriptors.begin(); pos != end; pos++) {
410314564Sdim    if (addr <= (*pos).code_start) {
411314564Sdim      flags = (*pos).flags;
412314564Sdim      return true;
413293116Semaste    }
414314564Sdim  }
415314564Sdim  return false;
416293116Semaste}
417314564Sdim
418314564Sdimvoid AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(
419314564Sdim    Stream &s) {
420314564Sdim  s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64
421314564Sdim           " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",
422314564Sdim           m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);
423314564Sdim  size_t num_elements = m_descriptors.size();
424314564Sdim  for (size_t i = 0; i < num_elements; i++) {
425314564Sdim    s.Indent();
426314564Sdim    s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",
427314564Sdim             m_descriptors[i].code_start, m_descriptors[i].flags);
428314564Sdim  }
429293116Semaste}
430293116Semaste
431314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables(
432314564Sdim    const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
433314564Sdim    : m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS),
434314564Sdim      m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID),
435314564Sdim      m_objc_module_sp(objc_module_sp) {
436314564Sdim  if (process_sp)
437314564Sdim    m_process_wp = process_sp;
438293116Semaste}
439293116Semaste
440314564SdimAppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {
441314564Sdim  ProcessSP process_sp = GetProcessSP();
442314564Sdim  if (process_sp) {
443314564Sdim    if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)
444314564Sdim      process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);
445314564Sdim  }
446314564Sdim}
447293116Semaste
448314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {
449314564Sdim  if (m_trampoline_header != LLDB_INVALID_ADDRESS)
450314564Sdim    return true;
451314564Sdim
452314564Sdim  ProcessSP process_sp = GetProcessSP();
453314564Sdim  if (process_sp) {
454314564Sdim    Target &target = process_sp->GetTarget();
455314564Sdim
456314564Sdim    const ModuleList &target_modules = target.GetImages();
457314564Sdim    std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
458314564Sdim    size_t num_modules = target_modules.GetSize();
459314564Sdim    if (!m_objc_module_sp) {
460314564Sdim      for (size_t i = 0; i < num_modules; i++) {
461353358Sdim        if (ObjCLanguageRuntime::Get(*process_sp)
462353358Sdim                ->IsModuleObjCLibrary(
463353358Sdim                    target_modules.GetModuleAtIndexUnlocked(i))) {
464314564Sdim          m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i);
465314564Sdim          break;
466293116Semaste        }
467314564Sdim      }
468314564Sdim    }
469314564Sdim
470314564Sdim    if (m_objc_module_sp) {
471314564Sdim      ConstString trampoline_name("gdb_objc_trampolines");
472314564Sdim      const Symbol *trampoline_symbol =
473314564Sdim          m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,
474314564Sdim                                                           eSymbolTypeData);
475353358Sdim      if (trampoline_symbol != nullptr) {
476314564Sdim        m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);
477314564Sdim        if (m_trampoline_header == LLDB_INVALID_ADDRESS)
478314564Sdim          return false;
479314564Sdim
480314564Sdim        // Next look up the "changed" symbol and set a breakpoint on that...
481314564Sdim        ConstString changed_name("gdb_objc_trampolines_changed");
482314564Sdim        const Symbol *changed_symbol =
483314564Sdim            m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,
484314564Sdim                                                             eSymbolTypeCode);
485353358Sdim        if (changed_symbol != nullptr) {
486314564Sdim          const Address changed_symbol_addr = changed_symbol->GetAddress();
487314564Sdim          if (!changed_symbol_addr.IsValid())
488314564Sdim            return false;
489314564Sdim
490314564Sdim          lldb::addr_t changed_addr =
491314564Sdim              changed_symbol_addr.GetOpcodeLoadAddress(&target);
492314564Sdim          if (changed_addr != LLDB_INVALID_ADDRESS) {
493314564Sdim            BreakpointSP trampolines_changed_bp_sp =
494314564Sdim                target.CreateBreakpoint(changed_addr, true, false);
495314564Sdim            if (trampolines_changed_bp_sp) {
496314564Sdim              m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();
497314564Sdim              trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,
498314564Sdim                                                     true);
499314564Sdim              trampolines_changed_bp_sp->SetBreakpointKind(
500314564Sdim                  "objc-trampolines-changed");
501314564Sdim              return true;
502293116Semaste            }
503314564Sdim          }
504293116Semaste        }
505314564Sdim      }
506293116Semaste    }
507314564Sdim  }
508314564Sdim  return false;
509293116Semaste}
510293116Semaste
511314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(
512314564Sdim    void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
513314564Sdim    lldb::user_id_t break_loc_id) {
514314564Sdim  AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;
515314564Sdim  if (vtable_handler->InitializeVTableSymbols()) {
516314564Sdim    // The Update function is called with the address of an added region.  So we
517314564Sdim    // grab that address, and
518314564Sdim    // feed it into ReadRegions.  Of course, our friend the ABI will get the
519314564Sdim    // values for us.
520314564Sdim    ExecutionContext exe_ctx(context->exe_ctx_ref);
521314564Sdim    Process *process = exe_ctx.GetProcessPtr();
522314564Sdim    const ABI *abi = process->GetABI().get();
523314564Sdim
524314564Sdim    ClangASTContext *clang_ast_context =
525314564Sdim        process->GetTarget().GetScratchClangASTContext();
526314564Sdim    ValueList argument_values;
527314564Sdim    Value input_value;
528314564Sdim    CompilerType clang_void_ptr_type =
529314564Sdim        clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
530314564Sdim
531314564Sdim    input_value.SetValueType(Value::eValueTypeScalar);
532314564Sdim    // input_value.SetContext (Value::eContextTypeClangType,
533314564Sdim    // clang_void_ptr_type);
534314564Sdim    input_value.SetCompilerType(clang_void_ptr_type);
535314564Sdim    argument_values.PushValue(input_value);
536314564Sdim
537314564Sdim    bool success =
538314564Sdim        abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);
539314564Sdim    if (!success)
540314564Sdim      return false;
541314564Sdim
542314564Sdim    // Now get a pointer value from the zeroth argument.
543321369Sdim    Status error;
544314564Sdim    DataExtractor data;
545314564Sdim    error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,
546353358Sdim                                                               0, nullptr);
547314564Sdim    lldb::offset_t offset = 0;
548314564Sdim    lldb::addr_t region_addr = data.GetPointer(&offset);
549314564Sdim
550314564Sdim    if (region_addr != 0)
551314564Sdim      vtable_handler->ReadRegions(region_addr);
552314564Sdim  }
553314564Sdim  return false;
554293116Semaste}
555293116Semaste
556314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {
557341825Sdim  // The no argument version reads the  start region from the value of
558341825Sdim  // the gdb_regions_header, and gets started from there.
559314564Sdim
560314564Sdim  m_regions.clear();
561314564Sdim  if (!InitializeVTableSymbols())
562293116Semaste    return false;
563321369Sdim  Status error;
564314564Sdim  ProcessSP process_sp = GetProcessSP();
565314564Sdim  if (process_sp) {
566314564Sdim    lldb::addr_t region_addr =
567314564Sdim        process_sp->ReadPointerFromMemory(m_trampoline_header, error);
568314564Sdim    if (error.Success())
569314564Sdim      return ReadRegions(region_addr);
570314564Sdim  }
571314564Sdim  return false;
572293116Semaste}
573293116Semaste
574314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(
575314564Sdim    lldb::addr_t region_addr) {
576314564Sdim  ProcessSP process_sp = GetProcessSP();
577314564Sdim  if (!process_sp)
578314564Sdim    return false;
579314564Sdim
580314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
581314564Sdim
582314564Sdim  // We aren't starting at the trampoline symbol.
583314564Sdim  InitializeVTableSymbols();
584314564Sdim  lldb::addr_t next_region = region_addr;
585314564Sdim
586314564Sdim  // Read in the sizes of the headers.
587314564Sdim  while (next_region != 0) {
588314564Sdim    m_regions.push_back(VTableRegion(this, next_region));
589314564Sdim    if (!m_regions.back().IsValid()) {
590314564Sdim      m_regions.clear();
591314564Sdim      return false;
592293116Semaste    }
593314564Sdim    if (log) {
594314564Sdim      StreamString s;
595314564Sdim      m_regions.back().Dump(s);
596314564Sdim      log->Printf("Read vtable region: \n%s", s.GetData());
597293116Semaste    }
598314564Sdim
599314564Sdim    next_region = m_regions.back().GetNextRegionAddr();
600314564Sdim  }
601314564Sdim
602314564Sdim  return true;
603293116Semaste}
604293116Semaste
605314564Sdimbool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(
606314564Sdim    lldb::addr_t addr, uint32_t &flags) {
607314564Sdim  region_collection::iterator pos, end = m_regions.end();
608314564Sdim  for (pos = m_regions.begin(); pos != end; pos++) {
609314564Sdim    if ((*pos).AddressInRegion(addr, flags))
610314564Sdim      return true;
611314564Sdim  }
612314564Sdim  return false;
613314564Sdim}
614314564Sdim
615293116Semasteconst AppleObjCTrampolineHandler::DispatchFunction
616314564Sdim    AppleObjCTrampolineHandler::g_dispatch_functions[] = {
617314564Sdim        // NAME                              STRET  SUPER  SUPER2  FIXUP TYPE
618314564Sdim        {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},
619314564Sdim        {"objc_msgSend_fixup", false, false, false,
620314564Sdim         DispatchFunction::eFixUpToFix},
621314564Sdim        {"objc_msgSend_fixedup", false, false, false,
622314564Sdim         DispatchFunction::eFixUpFixed},
623314564Sdim        {"objc_msgSend_stret", true, false, false,
624314564Sdim         DispatchFunction::eFixUpNone},
625314564Sdim        {"objc_msgSend_stret_fixup", true, false, false,
626314564Sdim         DispatchFunction::eFixUpToFix},
627314564Sdim        {"objc_msgSend_stret_fixedup", true, false, false,
628314564Sdim         DispatchFunction::eFixUpFixed},
629314564Sdim        {"objc_msgSend_fpret", false, false, false,
630314564Sdim         DispatchFunction::eFixUpNone},
631314564Sdim        {"objc_msgSend_fpret_fixup", false, false, false,
632314564Sdim         DispatchFunction::eFixUpToFix},
633314564Sdim        {"objc_msgSend_fpret_fixedup", false, false, false,
634314564Sdim         DispatchFunction::eFixUpFixed},
635314564Sdim        {"objc_msgSend_fp2ret", false, false, true,
636314564Sdim         DispatchFunction::eFixUpNone},
637314564Sdim        {"objc_msgSend_fp2ret_fixup", false, false, true,
638314564Sdim         DispatchFunction::eFixUpToFix},
639314564Sdim        {"objc_msgSend_fp2ret_fixedup", false, false, true,
640314564Sdim         DispatchFunction::eFixUpFixed},
641314564Sdim        {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},
642314564Sdim        {"objc_msgSendSuper_stret", true, true, false,
643314564Sdim         DispatchFunction::eFixUpNone},
644314564Sdim        {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},
645314564Sdim        {"objc_msgSendSuper2_fixup", false, true, true,
646314564Sdim         DispatchFunction::eFixUpToFix},
647314564Sdim        {"objc_msgSendSuper2_fixedup", false, true, true,
648314564Sdim         DispatchFunction::eFixUpFixed},
649314564Sdim        {"objc_msgSendSuper2_stret", true, true, true,
650314564Sdim         DispatchFunction::eFixUpNone},
651314564Sdim        {"objc_msgSendSuper2_stret_fixup", true, true, true,
652314564Sdim         DispatchFunction::eFixUpToFix},
653314564Sdim        {"objc_msgSendSuper2_stret_fixedup", true, true, true,
654314564Sdim         DispatchFunction::eFixUpFixed},
655293116Semaste};
656293116Semaste
657314564SdimAppleObjCTrampolineHandler::AppleObjCTrampolineHandler(
658314564Sdim    const ProcessSP &process_sp, const ModuleSP &objc_module_sp)
659314564Sdim    : m_process_wp(), m_objc_module_sp(objc_module_sp),
660314564Sdim      m_lookup_implementation_function_code(nullptr),
661314564Sdim      m_impl_fn_addr(LLDB_INVALID_ADDRESS),
662314564Sdim      m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),
663314564Sdim      m_msg_forward_addr(LLDB_INVALID_ADDRESS) {
664314564Sdim  if (process_sp)
665314564Sdim    m_process_wp = process_sp;
666314564Sdim  // Look up the known resolution functions:
667314564Sdim
668314564Sdim  ConstString get_impl_name("class_getMethodImplementation");
669314564Sdim  ConstString get_impl_stret_name("class_getMethodImplementation_stret");
670314564Sdim  ConstString msg_forward_name("_objc_msgForward");
671314564Sdim  ConstString msg_forward_stret_name("_objc_msgForward_stret");
672314564Sdim
673353358Sdim  Target *target = process_sp ? &process_sp->GetTarget() : nullptr;
674314564Sdim  const Symbol *class_getMethodImplementation =
675314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,
676314564Sdim                                                       eSymbolTypeCode);
677314564Sdim  const Symbol *class_getMethodImplementation_stret =
678314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,
679314564Sdim                                                       eSymbolTypeCode);
680314564Sdim  const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(
681314564Sdim      msg_forward_name, eSymbolTypeCode);
682314564Sdim  const Symbol *msg_forward_stret =
683314564Sdim      m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,
684314564Sdim                                                       eSymbolTypeCode);
685314564Sdim
686314564Sdim  if (class_getMethodImplementation)
687314564Sdim    m_impl_fn_addr =
688314564Sdim        class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(
689314564Sdim            target);
690314564Sdim  if (class_getMethodImplementation_stret)
691314564Sdim    m_impl_stret_fn_addr =
692314564Sdim        class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(
693314564Sdim            target);
694314564Sdim  if (msg_forward)
695314564Sdim    m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
696314564Sdim  if (msg_forward_stret)
697314564Sdim    m_msg_forward_stret_addr =
698314564Sdim        msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
699314564Sdim
700314564Sdim  // FIXME: Do some kind of logging here.
701314564Sdim  if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {
702314564Sdim    // If we can't even find the ordinary get method implementation function,
703314564Sdim    // then we aren't going to be able to
704314564Sdim    // step through any method dispatches.  Warn to that effect and get out of
705314564Sdim    // here.
706314564Sdim    if (process_sp->CanJIT()) {
707314564Sdim      process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf(
708314564Sdim          "Could not find implementation lookup function \"%s\""
709314564Sdim          " step in through ObjC method dispatch will not work.\n",
710314564Sdim          get_impl_name.AsCString());
711293116Semaste    }
712314564Sdim    return;
713314564Sdim  } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {
714314564Sdim    // It there is no stret return lookup function, assume that it is the same
715314564Sdim    // as the straight lookup:
716314564Sdim    m_impl_stret_fn_addr = m_impl_fn_addr;
717314564Sdim    // Also we will use the version of the lookup code that doesn't rely on the
718314564Sdim    // stret version of the function.
719314564Sdim    m_lookup_implementation_function_code =
720314564Sdim        g_lookup_implementation_no_stret_function_code;
721314564Sdim  } else {
722314564Sdim    m_lookup_implementation_function_code =
723314564Sdim        g_lookup_implementation_with_stret_function_code;
724314564Sdim  }
725314564Sdim
726341825Sdim  // Look up the addresses for the objc dispatch functions and cache
727341825Sdim  // them.  For now I'm inspecting the symbol names dynamically to
728341825Sdim  // figure out how to dispatch to them.  If it becomes more
729341825Sdim  // complicated than this we can turn the g_dispatch_functions char *
730341825Sdim  // array into a template table, and populate the DispatchFunction
731341825Sdim  // map from there.
732314564Sdim
733314564Sdim  for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) {
734314564Sdim    ConstString name_const_str(g_dispatch_functions[i].name);
735314564Sdim    const Symbol *msgSend_symbol =
736314564Sdim        m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,
737314564Sdim                                                         eSymbolTypeCode);
738314564Sdim    if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {
739341825Sdim      // FIXME: Make g_dispatch_functions static table of
740341825Sdim      // DispatchFunctions, and have the map be address->index.
741341825Sdim      // Problem is we also need to lookup the dispatch function.  For
742341825Sdim      // now we could have a side table of stret & non-stret dispatch
743341825Sdim      // functions.  If that's as complex as it gets, we're fine.
744314564Sdim
745314564Sdim      lldb::addr_t sym_addr =
746314564Sdim          msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
747314564Sdim
748314564Sdim      m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
749293116Semaste    }
750314564Sdim  }
751293116Semaste
752314564Sdim  // Build our vtable dispatch handler here:
753353358Sdim  m_vtables_up.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
754353358Sdim  if (m_vtables_up)
755353358Sdim    m_vtables_up->ReadRegions();
756293116Semaste}
757293116Semaste
758293116Semastelldb::addr_t
759314564SdimAppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,
760314564Sdim                                                  ValueList &dispatch_values) {
761314564Sdim  ThreadSP thread_sp(thread.shared_from_this());
762314564Sdim  ExecutionContext exe_ctx(thread_sp);
763314564Sdim  DiagnosticManager diagnostics;
764314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
765309124Sdim
766314564Sdim  lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
767314564Sdim  FunctionCaller *impl_function_caller = nullptr;
768293116Semaste
769314564Sdim  // Scope for mutex locker:
770314564Sdim  {
771314564Sdim    std::lock_guard<std::mutex> guard(m_impl_function_mutex);
772309124Sdim
773314564Sdim    // First stage is to make the ClangUtility to hold our injected function:
774293116Semaste
775353358Sdim    if (!m_impl_code) {
776353358Sdim      if (m_lookup_implementation_function_code != nullptr) {
777321369Sdim        Status error;
778314564Sdim        m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
779314564Sdim            m_lookup_implementation_function_code, eLanguageTypeObjC,
780314564Sdim            g_lookup_implementation_function_name, error));
781314564Sdim        if (error.Fail()) {
782314564Sdim          if (log)
783314564Sdim            log->Printf(
784314564Sdim                "Failed to get Utility Function for implementation lookup: %s.",
785314564Sdim                error.AsCString());
786314564Sdim          m_impl_code.reset();
787314564Sdim          return args_addr;
788314564Sdim        }
789309124Sdim
790314564Sdim        if (!m_impl_code->Install(diagnostics, exe_ctx)) {
791314564Sdim          if (log) {
792314564Sdim            log->Printf("Failed to install implementation lookup.");
793314564Sdim            diagnostics.Dump(log);
794314564Sdim          }
795314564Sdim          m_impl_code.reset();
796314564Sdim          return args_addr;
797293116Semaste        }
798314564Sdim      } else {
799314564Sdim        if (log)
800314564Sdim          log->Printf("No method lookup implementation code.");
801314564Sdim        return LLDB_INVALID_ADDRESS;
802314564Sdim      }
803309124Sdim
804314564Sdim      // Next make the runner function for our implementation utility function.
805314564Sdim      ClangASTContext *clang_ast_context =
806314564Sdim          thread.GetProcess()->GetTarget().GetScratchClangASTContext();
807314564Sdim      CompilerType clang_void_ptr_type =
808314564Sdim          clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
809321369Sdim      Status error;
810309124Sdim
811314564Sdim      impl_function_caller = m_impl_code->MakeFunctionCaller(
812314564Sdim          clang_void_ptr_type, dispatch_values, thread_sp, error);
813314564Sdim      if (error.Fail()) {
814293116Semaste        if (log)
815314564Sdim          log->Printf(
816314564Sdim              "Error getting function caller for dispatch lookup: \"%s\".",
817314564Sdim              error.AsCString());
818293116Semaste        return args_addr;
819314564Sdim      }
820314564Sdim    } else {
821314564Sdim      impl_function_caller = m_impl_code->GetFunctionCaller();
822293116Semaste    }
823314564Sdim  }
824309124Sdim
825314564Sdim  diagnostics.Clear();
826314564Sdim
827341825Sdim  // Now write down the argument values for this particular call.
828341825Sdim  // This looks like it might be a race condition if other threads
829341825Sdim  // were calling into here, but actually it isn't because we allocate
830341825Sdim  // a new args structure for this call by passing args_addr =
831341825Sdim  // LLDB_INVALID_ADDRESS...
832314564Sdim
833314564Sdim  if (!impl_function_caller->WriteFunctionArguments(
834314564Sdim          exe_ctx, args_addr, dispatch_values, diagnostics)) {
835314564Sdim    if (log) {
836314564Sdim      log->Printf("Error writing function arguments.");
837314564Sdim      diagnostics.Dump(log);
838314564Sdim    }
839293116Semaste    return args_addr;
840314564Sdim  }
841314564Sdim
842314564Sdim  return args_addr;
843293116Semaste}
844293116Semaste
845293116SemasteThreadPlanSP
846314564SdimAppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,
847314564Sdim                                                       bool stop_others) {
848314564Sdim  ThreadPlanSP ret_plan_sp;
849314564Sdim  lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
850314564Sdim
851314564Sdim  DispatchFunction this_dispatch;
852314564Sdim  bool found_it = false;
853314564Sdim
854341825Sdim  // First step is to look and see if we are in one of the known ObjC
855341825Sdim  // dispatch functions.  We've already compiled a table of same, so
856341825Sdim  // consult it.
857314564Sdim
858314564Sdim  MsgsendMap::iterator pos;
859314564Sdim  pos = m_msgSend_map.find(curr_pc);
860314564Sdim  if (pos != m_msgSend_map.end()) {
861314564Sdim    this_dispatch = g_dispatch_functions[(*pos).second];
862314564Sdim    found_it = true;
863314564Sdim  }
864314564Sdim
865314564Sdim  // Next check to see if we are in a vtable region:
866314564Sdim
867314564Sdim  if (!found_it) {
868314564Sdim    uint32_t flags;
869353358Sdim    if (m_vtables_up) {
870353358Sdim      found_it = m_vtables_up->IsAddressInVTables(curr_pc, flags);
871314564Sdim      if (found_it) {
872314564Sdim        this_dispatch.name = "vtable";
873314564Sdim        this_dispatch.stret_return =
874314564Sdim            (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==
875314564Sdim            AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
876314564Sdim        this_dispatch.is_super = false;
877314564Sdim        this_dispatch.is_super2 = false;
878314564Sdim        this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
879314564Sdim      }
880293116Semaste    }
881314564Sdim  }
882314564Sdim
883314564Sdim  if (found_it) {
884314564Sdim    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
885314564Sdim
886341825Sdim    // We are decoding a method dispatch.  First job is to pull the
887341825Sdim    // arguments out:
888314564Sdim
889314564Sdim    lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
890314564Sdim
891353358Sdim    const ABI *abi = nullptr;
892314564Sdim    ProcessSP process_sp(thread.CalculateProcess());
893314564Sdim    if (process_sp)
894314564Sdim      abi = process_sp->GetABI().get();
895353358Sdim    if (abi == nullptr)
896314564Sdim      return ret_plan_sp;
897314564Sdim
898314564Sdim    TargetSP target_sp(thread.CalculateTarget());
899314564Sdim
900314564Sdim    ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
901314564Sdim    ValueList argument_values;
902314564Sdim    Value void_ptr_value;
903314564Sdim    CompilerType clang_void_ptr_type =
904314564Sdim        clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
905314564Sdim    void_ptr_value.SetValueType(Value::eValueTypeScalar);
906314564Sdim    // void_ptr_value.SetContext (Value::eContextTypeClangType,
907314564Sdim    // clang_void_ptr_type);
908314564Sdim    void_ptr_value.SetCompilerType(clang_void_ptr_type);
909314564Sdim
910314564Sdim    int obj_index;
911314564Sdim    int sel_index;
912314564Sdim
913341825Sdim    // If this is a struct return dispatch, then the first argument is
914341825Sdim    // the return struct pointer, and the object is the second, and
915341825Sdim    // the selector is the third.  Otherwise the object is the first
916341825Sdim    // and the selector the second.
917314564Sdim    if (this_dispatch.stret_return) {
918314564Sdim      obj_index = 1;
919314564Sdim      sel_index = 2;
920314564Sdim      argument_values.PushValue(void_ptr_value);
921314564Sdim      argument_values.PushValue(void_ptr_value);
922314564Sdim      argument_values.PushValue(void_ptr_value);
923314564Sdim    } else {
924314564Sdim      obj_index = 0;
925314564Sdim      sel_index = 1;
926314564Sdim      argument_values.PushValue(void_ptr_value);
927314564Sdim      argument_values.PushValue(void_ptr_value);
928293116Semaste    }
929293116Semaste
930314564Sdim    bool success = abi->GetArgumentValues(thread, argument_values);
931314564Sdim    if (!success)
932314564Sdim      return ret_plan_sp;
933293116Semaste
934314564Sdim    lldb::addr_t obj_addr =
935314564Sdim        argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
936314564Sdim    if (obj_addr == 0x0) {
937314564Sdim      if (log)
938314564Sdim        log->Printf(
939314564Sdim            "Asked to step to dispatch to nil object, returning empty plan.");
940314564Sdim      return ret_plan_sp;
941314564Sdim    }
942314564Sdim
943314564Sdim    ExecutionContext exe_ctx(thread.shared_from_this());
944314564Sdim    Process *process = exe_ctx.GetProcessPtr();
945341825Sdim    // isa_addr will store the class pointer that the method is being
946341825Sdim    // dispatched to - so either the class directly or the super class
947341825Sdim    // if this is one of the objc_msgSendSuper flavors.  That's mostly
948341825Sdim    // used to look up the class/selector pair in our cache.
949314564Sdim
950314564Sdim    lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
951314564Sdim    lldb::addr_t sel_addr =
952314564Sdim        argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
953314564Sdim
954341825Sdim    // Figure out the class this is being dispatched to and see if
955341825Sdim    // we've already cached this method call, If so we can push a
956341825Sdim    // run-to-address plan directly.  Otherwise we have to figure out
957341825Sdim    // where the implementation lives.
958314564Sdim
959314564Sdim    if (this_dispatch.is_super) {
960314564Sdim      if (this_dispatch.is_super2) {
961341825Sdim        // In the objc_msgSendSuper2 case, we don't get the object
962341825Sdim        // directly, we get a structure containing the object and the
963341825Sdim        // class to which the super message is being sent.  So we need
964341825Sdim        // to dig the super out of the class and use that.
965314564Sdim
966314564Sdim        Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
967314564Sdim        super_value.GetScalar() += process->GetAddressByteSize();
968314564Sdim        super_value.ResolveValue(&exe_ctx);
969314564Sdim
970314564Sdim        if (super_value.GetScalar().IsValid()) {
971314564Sdim
972314564Sdim          // isa_value now holds the class pointer.  The second word of the
973314564Sdim          // class pointer is the super-class pointer:
974314564Sdim          super_value.GetScalar() += process->GetAddressByteSize();
975314564Sdim          super_value.ResolveValue(&exe_ctx);
976314564Sdim          if (super_value.GetScalar().IsValid())
977314564Sdim            isa_addr = super_value.GetScalar().ULongLong();
978314564Sdim          else {
979293116Semaste            if (log)
980314564Sdim              log->Printf("Failed to extract the super class value from the "
981314564Sdim                          "class in objc_super.");
982314564Sdim          }
983314564Sdim        } else {
984314564Sdim          if (log)
985314564Sdim            log->Printf("Failed to extract the class value from objc_super.");
986293116Semaste        }
987314564Sdim      } else {
988341825Sdim        // In the objc_msgSendSuper case, we don't get the object
989341825Sdim        // directly, we get a two element structure containing the
990341825Sdim        // object and the super class to which the super message is
991341825Sdim        // being sent.  So the class we want is the second element of
992341825Sdim        // this structure.
993293116Semaste
994314564Sdim        Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
995314564Sdim        super_value.GetScalar() += process->GetAddressByteSize();
996314564Sdim        super_value.ResolveValue(&exe_ctx);
997314564Sdim
998314564Sdim        if (super_value.GetScalar().IsValid()) {
999314564Sdim          isa_addr = super_value.GetScalar().ULongLong();
1000314564Sdim        } else {
1001314564Sdim          if (log)
1002314564Sdim            log->Printf("Failed to extract the class value from objc_super.");
1003293116Semaste        }
1004314564Sdim      }
1005314564Sdim    } else {
1006314564Sdim      // In the direct dispatch case, the object->isa is the class pointer we
1007314564Sdim      // want.
1008293116Semaste
1009314564Sdim      // This is a little cheesy, but since object->isa is the first field,
1010314564Sdim      // making the object value a load address value and resolving it will get
1011314564Sdim      // the pointer sized data pointed to by that value...
1012293116Semaste
1013341825Sdim      // Note, it isn't a fatal error not to be able to get the
1014341825Sdim      // address from the object, since this might be a "tagged
1015341825Sdim      // pointer" which isn't a real object, but rather some word
1016314564Sdim      // length encoded dingus.
1017314564Sdim
1018314564Sdim      Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1019314564Sdim
1020314564Sdim      isa_value.SetValueType(Value::eValueTypeLoadAddress);
1021314564Sdim      isa_value.ResolveValue(&exe_ctx);
1022314564Sdim      if (isa_value.GetScalar().IsValid()) {
1023314564Sdim        isa_addr = isa_value.GetScalar().ULongLong();
1024314564Sdim      } else {
1025314564Sdim        if (log)
1026314564Sdim          log->Printf("Failed to extract the isa value from object.");
1027314564Sdim      }
1028293116Semaste    }
1029314564Sdim
1030314564Sdim    // Okay, we've got the address of the class for which we're resolving this,
1031314564Sdim    // let's see if it's in our cache:
1032314564Sdim    lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1033314564Sdim
1034314564Sdim    if (isa_addr != LLDB_INVALID_ADDRESS) {
1035314564Sdim      if (log) {
1036314564Sdim        log->Printf("Resolving call for class - 0x%" PRIx64
1037314564Sdim                    " and selector - 0x%" PRIx64,
1038314564Sdim                    isa_addr, sel_addr);
1039314564Sdim      }
1040314564Sdim      ObjCLanguageRuntime *objc_runtime =
1041353358Sdim          ObjCLanguageRuntime::Get(*thread.GetProcess());
1042353358Sdim      assert(objc_runtime != nullptr);
1043314564Sdim
1044314564Sdim      impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);
1045314564Sdim    }
1046314564Sdim
1047314564Sdim    if (impl_addr != LLDB_INVALID_ADDRESS) {
1048314564Sdim      // Yup, it was in the cache, so we can run to that address directly.
1049314564Sdim
1050314564Sdim      if (log)
1051314564Sdim        log->Printf("Found implementation address in cache: 0x%" PRIx64,
1052314564Sdim                    impl_addr);
1053314564Sdim
1054353358Sdim      ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,
1055353358Sdim                                                             stop_others);
1056314564Sdim    } else {
1057314564Sdim      // We haven't seen this class/selector pair yet.  Look it up.
1058314564Sdim      StreamString errors;
1059314564Sdim      Address impl_code_address;
1060314564Sdim
1061314564Sdim      ValueList dispatch_values;
1062314564Sdim
1063314564Sdim      // We've will inject a little function in the target that takes the
1064314564Sdim      // object, selector and some flags,
1065314564Sdim      // and figures out the implementation.  Looks like:
1066314564Sdim      //      void *__lldb_objc_find_implementation_for_selector (void *object,
1067314564Sdim      //                                                          void *sel,
1068314564Sdim      //                                                          int is_stret,
1069314564Sdim      //                                                          int is_super,
1070314564Sdim      //                                                          int is_super2,
1071314564Sdim      //                                                          int is_fixup,
1072314564Sdim      //                                                          int is_fixed,
1073314564Sdim      //                                                          int debug)
1074314564Sdim      // So set up the arguments for that call.
1075314564Sdim
1076314564Sdim      dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));
1077314564Sdim      dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index)));
1078314564Sdim
1079314564Sdim      Value flag_value;
1080314564Sdim      CompilerType clang_int_type =
1081314564Sdim          clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1082314564Sdim              lldb::eEncodingSint, 32);
1083314564Sdim      flag_value.SetValueType(Value::eValueTypeScalar);
1084314564Sdim      // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1085314564Sdim      flag_value.SetCompilerType(clang_int_type);
1086314564Sdim
1087314564Sdim      if (this_dispatch.stret_return)
1088314564Sdim        flag_value.GetScalar() = 1;
1089314564Sdim      else
1090314564Sdim        flag_value.GetScalar() = 0;
1091314564Sdim      dispatch_values.PushValue(flag_value);
1092314564Sdim
1093314564Sdim      if (this_dispatch.is_super)
1094314564Sdim        flag_value.GetScalar() = 1;
1095314564Sdim      else
1096314564Sdim        flag_value.GetScalar() = 0;
1097314564Sdim      dispatch_values.PushValue(flag_value);
1098314564Sdim
1099314564Sdim      if (this_dispatch.is_super2)
1100314564Sdim        flag_value.GetScalar() = 1;
1101314564Sdim      else
1102314564Sdim        flag_value.GetScalar() = 0;
1103314564Sdim      dispatch_values.PushValue(flag_value);
1104314564Sdim
1105314564Sdim      switch (this_dispatch.fixedup) {
1106314564Sdim      case DispatchFunction::eFixUpNone:
1107314564Sdim        flag_value.GetScalar() = 0;
1108314564Sdim        dispatch_values.PushValue(flag_value);
1109314564Sdim        dispatch_values.PushValue(flag_value);
1110314564Sdim        break;
1111314564Sdim      case DispatchFunction::eFixUpFixed:
1112314564Sdim        flag_value.GetScalar() = 1;
1113314564Sdim        dispatch_values.PushValue(flag_value);
1114314564Sdim        flag_value.GetScalar() = 1;
1115314564Sdim        dispatch_values.PushValue(flag_value);
1116314564Sdim        break;
1117314564Sdim      case DispatchFunction::eFixUpToFix:
1118314564Sdim        flag_value.GetScalar() = 1;
1119314564Sdim        dispatch_values.PushValue(flag_value);
1120314564Sdim        flag_value.GetScalar() = 0;
1121314564Sdim        dispatch_values.PushValue(flag_value);
1122314564Sdim        break;
1123314564Sdim      }
1124314564Sdim      if (log && log->GetVerbose())
1125314564Sdim        flag_value.GetScalar() = 1;
1126314564Sdim      else
1127314564Sdim        flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.
1128314564Sdim      dispatch_values.PushValue(flag_value);
1129314564Sdim
1130341825Sdim      // The step through code might have to fill in the cache, so it
1131341825Sdim      // is not safe to run only one thread.  So we override the
1132341825Sdim      // stop_others value passed in to us here:
1133314564Sdim      const bool trampoline_stop_others = false;
1134353358Sdim      ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(
1135314564Sdim          thread, this, dispatch_values, isa_addr, sel_addr,
1136353358Sdim          trampoline_stop_others);
1137314564Sdim      if (log) {
1138314564Sdim        StreamString s;
1139314564Sdim        ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1140314564Sdim        log->Printf("Using ObjC step plan: %s.\n", s.GetData());
1141314564Sdim      }
1142314564Sdim    }
1143314564Sdim  }
1144314564Sdim
1145314564Sdim  return ret_plan_sp;
1146293116Semaste}
1147293116Semaste
1148293116SemasteFunctionCaller *
1149314564SdimAppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {
1150314564Sdim  return m_impl_code->GetFunctionCaller();
1151293116Semaste}
1152