AppleObjCTrampolineHandler.cpp revision 309124
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/DiagnosticManager.h"
26#include "lldb/Expression/FunctionCaller.h"
27#include "lldb/Expression/UserExpression.h"
28#include "lldb/Expression/UtilityFunction.h"
29#include "lldb/Host/FileSpec.h"
30#include "lldb/Symbol/ClangASTContext.h"
31#include "lldb/Symbol/Symbol.h"
32#include "lldb/Target/ABI.h"
33#include "lldb/Target/ExecutionContext.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
35#include "lldb/Target/Process.h"
36#include "lldb/Target/RegisterContext.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadPlanRunToAddress.h"
40
41#include "llvm/ADT/STLExtras.h"
42
43using namespace lldb;
44using namespace lldb_private;
45
46const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name = "__lldb_objc_find_implementation_for_selector";
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        std::lock_guard<std::recursive_mutex> guard(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_lookup_implementation_function_code(nullptr),
661    m_impl_fn_addr (LLDB_INVALID_ADDRESS),
662    m_impl_stret_fn_addr (LLDB_INVALID_ADDRESS),
663    m_msg_forward_addr (LLDB_INVALID_ADDRESS)
664{
665    if (process_sp)
666        m_process_wp = process_sp;
667    // Look up the known resolution functions:
668
669    ConstString get_impl_name("class_getMethodImplementation");
670    ConstString get_impl_stret_name("class_getMethodImplementation_stret");
671    ConstString msg_forward_name("_objc_msgForward");
672    ConstString msg_forward_stret_name("_objc_msgForward_stret");
673
674    Target *target = process_sp ? &process_sp->GetTarget() : NULL;
675    const Symbol *class_getMethodImplementation = m_objc_module_sp->FindFirstSymbolWithNameAndType (get_impl_name, eSymbolTypeCode);
676    const Symbol *class_getMethodImplementation_stret = m_objc_module_sp->FindFirstSymbolWithNameAndType (get_impl_stret_name, eSymbolTypeCode);
677    const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType (msg_forward_name, eSymbolTypeCode);
678    const Symbol *msg_forward_stret = m_objc_module_sp->FindFirstSymbolWithNameAndType (msg_forward_stret_name, eSymbolTypeCode);
679
680    if (class_getMethodImplementation)
681        m_impl_fn_addr = class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress (target);
682    if  (class_getMethodImplementation_stret)
683        m_impl_stret_fn_addr = class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress (target);
684    if (msg_forward)
685        m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);
686    if  (msg_forward_stret)
687        m_msg_forward_stret_addr = msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);
688
689    // FIXME: Do some kind of logging here.
690    if (m_impl_fn_addr == LLDB_INVALID_ADDRESS)
691    {
692        // If we can't even find the ordinary get method implementation function, then we aren't going to be able to
693        // step through any method dispatches.  Warn to that effect and get out of here.
694        if (process_sp->CanJIT())
695        {
696            process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf ("Could not find implementation lookup function \"%s\""
697                                                                          " step in through ObjC method dispatch will not work.\n",
698                                                                          get_impl_name.AsCString());
699        }
700        return;
701    }
702    else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS)
703    {
704        // It there is no stret return lookup function, assume that it is the same as the straight lookup:
705        m_impl_stret_fn_addr = m_impl_fn_addr;
706        // Also we will use the version of the lookup code that doesn't rely on the stret version of the function.
707        m_lookup_implementation_function_code = g_lookup_implementation_no_stret_function_code;
708    }
709    else
710    {
711        m_lookup_implementation_function_code = g_lookup_implementation_with_stret_function_code;
712    }
713
714    // Look up the addresses for the objc dispatch functions and cache them.  For now I'm inspecting the symbol
715    // names dynamically to figure out how to dispatch to them.  If it becomes more complicated than this we can
716    // turn the g_dispatch_functions char * array into a template table, and populate the DispatchFunction map
717    // from there.
718
719    for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++)
720    {
721        ConstString name_const_str(g_dispatch_functions[i].name);
722        const Symbol *msgSend_symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType (name_const_str, eSymbolTypeCode);
723        if (msgSend_symbol && msgSend_symbol->ValueIsAddress())
724        {
725            // FixMe: Make g_dispatch_functions static table of DispatchFunctions, and have the map be address->index.
726            // Problem is we also need to lookup the dispatch function.  For now we could have a side table of stret & non-stret
727            // dispatch functions.  If that's as complex as it gets, we're fine.
728
729            lldb::addr_t sym_addr = msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);
730
731            m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));
732        }
733    }
734
735    // Build our vtable dispatch handler here:
736    m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp));
737    if (m_vtables_ap.get())
738        m_vtables_ap->ReadRegions();
739}
740
741lldb::addr_t
742AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread, ValueList &dispatch_values)
743{
744    ThreadSP thread_sp(thread.shared_from_this());
745    ExecutionContext exe_ctx (thread_sp);
746    DiagnosticManager diagnostics;
747    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
748
749    lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
750    FunctionCaller *impl_function_caller = nullptr;
751
752    // Scope for mutex locker:
753    {
754        std::lock_guard<std::mutex> guard(m_impl_function_mutex);
755
756        // First stage is to make the ClangUtility to hold our injected function:
757
758        if (!m_impl_code.get())
759        {
760            if (m_lookup_implementation_function_code != NULL)
761            {
762                Error error;
763                m_impl_code.reset (exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage (m_lookup_implementation_function_code,
764                                                                                         eLanguageTypeObjC,
765                                                                                         g_lookup_implementation_function_name,
766                                                                                         error));
767                if (error.Fail())
768                {
769                    if (log)
770                        log->Printf ("Failed to get Utility Function for implementation lookup: %s.", error.AsCString());
771                    m_impl_code.reset();
772                    return args_addr;
773                }
774
775                if (!m_impl_code->Install(diagnostics, exe_ctx))
776                {
777                    if (log)
778                    {
779                        log->Printf("Failed to install implementation lookup.");
780                        diagnostics.Dump(log);
781                    }
782                    m_impl_code.reset();
783                    return args_addr;
784                }
785            }
786            else
787            {
788                if (log)
789                    log->Printf("No method lookup implementation code.");
790                return LLDB_INVALID_ADDRESS;
791            }
792
793            // Next make the runner function for our implementation utility function.
794            ClangASTContext *clang_ast_context = thread.GetProcess()->GetTarget().GetScratchClangASTContext();
795            CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
796            Error error;
797
798            impl_function_caller = m_impl_code->MakeFunctionCaller(clang_void_ptr_type,
799                                                                   dispatch_values,
800                                                                   thread_sp,
801                                                                   error);
802            if (error.Fail())
803            {
804                if (log)
805                    log->Printf ("Error getting function caller for dispatch lookup: \"%s\".", error.AsCString());
806                return args_addr;
807            }
808        }
809        else
810        {
811            impl_function_caller = m_impl_code->GetFunctionCaller();
812        }
813    }
814
815    diagnostics.Clear();
816
817    // Now write down the argument values for this particular call.  This looks like it might be a race condition
818    // if other threads were calling into here, but actually it isn't because we allocate a new args structure for
819    // this call by passing args_addr = LLDB_INVALID_ADDRESS...
820
821    if (!impl_function_caller->WriteFunctionArguments(exe_ctx, args_addr, dispatch_values, diagnostics))
822    {
823        if (log)
824        {
825            log->Printf("Error writing function arguments.");
826            diagnostics.Dump(log);
827        }
828        return args_addr;
829    }
830
831    return args_addr;
832}
833
834ThreadPlanSP
835AppleObjCTrampolineHandler::GetStepThroughDispatchPlan (Thread &thread, bool stop_others)
836{
837    ThreadPlanSP ret_plan_sp;
838    lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
839
840    DispatchFunction this_dispatch;
841    bool found_it = false;
842
843    // First step is to look and see if we are in one of the known ObjC dispatch functions.  We've already compiled
844    // a table of same, so consult it.
845
846    MsgsendMap::iterator pos;
847    pos = m_msgSend_map.find (curr_pc);
848    if (pos != m_msgSend_map.end())
849    {
850        this_dispatch = g_dispatch_functions[(*pos).second];
851        found_it = true;
852    }
853
854    // Next check to see if we are in a vtable region:
855
856    if (!found_it)
857    {
858        uint32_t flags;
859        if (m_vtables_ap.get())
860        {
861            found_it = m_vtables_ap->IsAddressInVTables (curr_pc, flags);
862            if (found_it)
863            {
864                this_dispatch.name = "vtable";
865                this_dispatch.stret_return
866                        = (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) == AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;
867                this_dispatch.is_super = false;
868                this_dispatch.is_super2 = false;
869                this_dispatch.fixedup = DispatchFunction::eFixUpFixed;
870            }
871        }
872    }
873
874    if (found_it)
875    {
876        Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
877
878        // We are decoding a method dispatch.
879        // First job is to pull the arguments out:
880
881        lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
882
883        const ABI *abi = NULL;
884        ProcessSP process_sp (thread.CalculateProcess());
885        if (process_sp)
886            abi = process_sp->GetABI().get();
887        if (abi == NULL)
888            return ret_plan_sp;
889
890        TargetSP target_sp (thread.CalculateTarget());
891
892        ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
893        ValueList argument_values;
894        Value void_ptr_value;
895        CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
896        void_ptr_value.SetValueType (Value::eValueTypeScalar);
897        //void_ptr_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
898        void_ptr_value.SetCompilerType (clang_void_ptr_type);
899
900        int obj_index;
901        int sel_index;
902
903        // If this is a struct return dispatch, then the first argument is the
904        // return struct pointer, and the object is the second, and the selector is the third.
905        // Otherwise the object is the first and the selector the second.
906        if (this_dispatch.stret_return)
907        {
908            obj_index = 1;
909            sel_index = 2;
910            argument_values.PushValue(void_ptr_value);
911            argument_values.PushValue(void_ptr_value);
912            argument_values.PushValue(void_ptr_value);
913        }
914        else
915        {
916            obj_index = 0;
917            sel_index = 1;
918            argument_values.PushValue(void_ptr_value);
919            argument_values.PushValue(void_ptr_value);
920        }
921
922
923        bool success = abi->GetArgumentValues (thread, argument_values);
924        if (!success)
925            return ret_plan_sp;
926
927        lldb::addr_t obj_addr = argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();
928        if (obj_addr == 0x0)
929        {
930            if (log)
931                log->Printf("Asked to step to dispatch to nil object, returning empty plan.");
932            return ret_plan_sp;
933        }
934
935        ExecutionContext exe_ctx (thread.shared_from_this());
936        Process *process = exe_ctx.GetProcessPtr();
937        // isa_addr will store the class pointer that the method is being dispatched to - so either the class
938        // directly or the super class if this is one of the objc_msgSendSuper flavors.  That's mostly used to
939        // look up the class/selector pair in our cache.
940
941        lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;
942        lldb::addr_t sel_addr = argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();
943
944        // Figure out the class this is being dispatched to and see if we've already cached this method call,
945        // If so we can push a run-to-address plan directly.  Otherwise we have to figure out where
946        // the implementation lives.
947
948        if (this_dispatch.is_super)
949        {
950            if (this_dispatch.is_super2)
951            {
952               // In the objc_msgSendSuper2 case, we don't get the object directly, we get a structure containing
953               // the object and the class to which the super message is being sent.  So we need to dig the super
954               // out of the class and use that.
955
956                Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
957                super_value.GetScalar() += process->GetAddressByteSize();
958                super_value.ResolveValue (&exe_ctx);
959
960                if (super_value.GetScalar().IsValid())
961                {
962
963                    // isa_value now holds the class pointer.  The second word of the class pointer is the super-class pointer:
964                    super_value.GetScalar() += process->GetAddressByteSize();
965                    super_value.ResolveValue (&exe_ctx);
966                    if (super_value.GetScalar().IsValid())
967                        isa_addr = super_value.GetScalar().ULongLong();
968                    else
969                    {
970                       if (log)
971                        log->Printf("Failed to extract the super class value from the class in objc_super.");
972                    }
973                }
974                else
975                {
976                   if (log)
977                    log->Printf("Failed to extract the class value from objc_super.");
978                }
979            }
980            else
981            {
982               // In the objc_msgSendSuper case, we don't get the object directly, we get a two element structure containing
983               // the object and the super class to which the super message is being sent.  So the class we want is
984               // the second element of this structure.
985
986                Value super_value(*(argument_values.GetValueAtIndex(obj_index)));
987                super_value.GetScalar() += process->GetAddressByteSize();
988                super_value.ResolveValue (&exe_ctx);
989
990                if (super_value.GetScalar().IsValid())
991                {
992                    isa_addr = super_value.GetScalar().ULongLong();
993                }
994                else
995                {
996                   if (log)
997                    log->Printf("Failed to extract the class value from objc_super.");
998                }
999            }
1000        }
1001        else
1002        {
1003            // In the direct dispatch case, the object->isa is the class pointer we want.
1004
1005            // This is a little cheesy, but since object->isa is the first field,
1006            // making the object value a load address value and resolving it will get
1007            // the pointer sized data pointed to by that value...
1008
1009            // Note, it isn't a fatal error not to be able to get the address from the object, since this might
1010            // be a "tagged pointer" which isn't a real object, but rather some word length encoded dingus.
1011
1012            Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));
1013
1014            isa_value.SetValueType(Value::eValueTypeLoadAddress);
1015            isa_value.ResolveValue(&exe_ctx);
1016            if (isa_value.GetScalar().IsValid())
1017            {
1018                isa_addr = isa_value.GetScalar().ULongLong();
1019            }
1020            else
1021            {
1022               if (log)
1023                log->Printf("Failed to extract the isa value from object.");
1024            }
1025
1026        }
1027
1028        // Okay, we've got the address of the class for which we're resolving this, let's see if it's in our cache:
1029        lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;
1030
1031        if (isa_addr != LLDB_INVALID_ADDRESS)
1032        {
1033            if (log)
1034            {
1035                log->Printf("Resolving call for class - 0x%" PRIx64 " and selector - 0x%" PRIx64,
1036                            isa_addr, sel_addr);
1037            }
1038            ObjCLanguageRuntime *objc_runtime = thread.GetProcess()->GetObjCLanguageRuntime ();
1039            assert(objc_runtime != NULL);
1040
1041            impl_addr = objc_runtime->LookupInMethodCache (isa_addr, sel_addr);
1042        }
1043
1044        if (impl_addr != LLDB_INVALID_ADDRESS)
1045        {
1046            // Yup, it was in the cache, so we can run to that address directly.
1047
1048            if (log)
1049                log->Printf ("Found implementation address in cache: 0x%" PRIx64, impl_addr);
1050
1051            ret_plan_sp.reset (new ThreadPlanRunToAddress (thread, impl_addr, stop_others));
1052        }
1053        else
1054        {
1055            // We haven't seen this class/selector pair yet.  Look it up.
1056            StreamString errors;
1057            Address impl_code_address;
1058
1059            ValueList dispatch_values;
1060
1061            // We've will inject a little function in the target that takes the object, selector and some flags,
1062            // and figures out the implementation.  Looks like:
1063            //      void *__lldb_objc_find_implementation_for_selector (void *object,
1064            //                                                          void *sel,
1065            //                                                          int is_stret,
1066            //                                                          int is_super,
1067            //                                                          int is_super2,
1068            //                                                          int is_fixup,
1069            //                                                          int is_fixed,
1070            //                                                          int debug)
1071            // So set up the arguments for that call.
1072
1073            dispatch_values.PushValue (*(argument_values.GetValueAtIndex(obj_index)));
1074            dispatch_values.PushValue (*(argument_values.GetValueAtIndex(sel_index)));
1075
1076            Value flag_value;
1077            CompilerType clang_int_type = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingSint, 32);
1078            flag_value.SetValueType (Value::eValueTypeScalar);
1079            //flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);
1080            flag_value.SetCompilerType (clang_int_type);
1081
1082            if (this_dispatch.stret_return)
1083                flag_value.GetScalar() = 1;
1084            else
1085                flag_value.GetScalar() = 0;
1086            dispatch_values.PushValue (flag_value);
1087
1088            if (this_dispatch.is_super)
1089                flag_value.GetScalar() = 1;
1090            else
1091                flag_value.GetScalar() = 0;
1092            dispatch_values.PushValue (flag_value);
1093
1094            if (this_dispatch.is_super2)
1095                flag_value.GetScalar() = 1;
1096            else
1097                flag_value.GetScalar() = 0;
1098            dispatch_values.PushValue (flag_value);
1099
1100            switch (this_dispatch.fixedup)
1101            {
1102              case DispatchFunction::eFixUpNone:
1103                 flag_value.GetScalar() = 0;
1104                 dispatch_values.PushValue (flag_value);
1105                 dispatch_values.PushValue (flag_value);
1106                 break;
1107              case DispatchFunction::eFixUpFixed:
1108                 flag_value.GetScalar() = 1;
1109                 dispatch_values.PushValue (flag_value);
1110                 flag_value.GetScalar() = 1;
1111                 dispatch_values.PushValue (flag_value);
1112                 break;
1113              case DispatchFunction::eFixUpToFix:
1114                 flag_value.GetScalar() = 1;
1115                 dispatch_values.PushValue (flag_value);
1116                 flag_value.GetScalar() = 0;
1117                 dispatch_values.PushValue (flag_value);
1118                 break;
1119            }
1120            if (log && log->GetVerbose())
1121                flag_value.GetScalar() = 1;
1122            else
1123                flag_value.GetScalar() = 0;  // FIXME - Set to 0 when debugging is done.
1124            dispatch_values.PushValue (flag_value);
1125
1126
1127            // The step through code might have to fill in the cache, so it is not safe to run only one thread.
1128            // So we override the stop_others value passed in to us here:
1129            const bool trampoline_stop_others = false;
1130            ret_plan_sp.reset (new AppleThreadPlanStepThroughObjCTrampoline (thread,
1131                                                                             this,
1132                                                                             dispatch_values,
1133                                                                             isa_addr,
1134                                                                             sel_addr,
1135                                                                             trampoline_stop_others));
1136            if (log)
1137            {
1138                StreamString s;
1139                ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);
1140                log->Printf("Using ObjC step plan: %s.\n", s.GetData());
1141            }
1142        }
1143    }
1144
1145    return ret_plan_sp;
1146}
1147
1148FunctionCaller *
1149AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller ()
1150{
1151    return m_impl_code->GetFunctionCaller();
1152}
1153