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