1 //===-- AppleGetItemInfoHandler.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 "AppleGetItemInfoHandler.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 
20 #include "lldb/Core/ConstString.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Core/Value.h"
25 #include "lldb/Expression/ClangExpression.h"
26 #include "lldb/Expression/ClangFunction.h"
27 #include "lldb/Expression/ClangUtilityFunction.h"
28 #include "lldb/Symbol/ClangASTContext.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Target/ExecutionContext.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 const char *AppleGetItemInfoHandler::g_get_item_info_function_name = "__lldb_backtrace_recording_get_item_info";
39 const char *AppleGetItemInfoHandler::g_get_item_info_function_code = "                                  \n\
40 extern \"C\"                                                                                                    \n\
41 {                                                                                                               \n\
42     /*                                                                                                          \n\
43      * mach defines                                                                                             \n\
44      */                                                                                                         \n\
45                                                                                                                 \n\
46     typedef unsigned int uint32_t;                                                                              \n\
47     typedef unsigned long long uint64_t;                                                                        \n\
48     typedef uint32_t mach_port_t;                                                                               \n\
49     typedef mach_port_t vm_map_t;                                                                               \n\
50     typedef int kern_return_t;                                                                                  \n\
51     typedef uint64_t mach_vm_address_t;                                                                         \n\
52     typedef uint64_t mach_vm_size_t;                                                                            \n\
53                                                                                                                 \n\
54     mach_port_t mach_task_self ();                                                                              \n\
55     kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);         \n\
56                                                                                                                 \n\
57     /*                                                                                                          \n\
58      * libBacktraceRecording defines                                                                            \n\
59      */                                                                                                         \n\
60                                                                                                                 \n\
61     typedef uint32_t queue_list_scope_t;                                                                        \n\
62     typedef void *dispatch_queue_t;                                                                             \n\
63     typedef void *introspection_dispatch_queue_info_t;                                                          \n\
64     typedef void *introspection_dispatch_item_info_ref;                                                         \n\
65                                                                                                                 \n\
66     extern uint64_t __introspection_dispatch_queue_item_get_info (introspection_dispatch_item_info_ref item_info_ref, \n\
67                                                  introspection_dispatch_item_info_ref *returned_queues_buffer,  \n\
68                                                  uint64_t *returned_queues_buffer_size);                        \n\
69     extern int printf(const char *format, ...);                                                                 \n\
70                                                                                                                 \n\
71     /*                                                                                                          \n\
72      * return type define                                                                                       \n\
73      */                                                                                                         \n\
74                                                                                                                 \n\
75     struct get_item_info_return_values                                                                      \n\
76     {                                                                                                           \n\
77         uint64_t item_info_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */  \n\
78         uint64_t item_info_buffer_size;   /* the size of the items buffer from libBacktraceRecording */     \n\
79     };                                                                                                          \n\
80                                                                                                                 \n\
81     void  __lldb_backtrace_recording_get_item_info                                                          \n\
82                                                (struct get_item_info_return_values *return_buffer,          \n\
83                                                 int debug,                                                      \n\
84                                                 uint64_t /* introspection_dispatch_item_info_ref item_info_ref */ item, \n\
85                                                 void *page_to_free,                                             \n\
86                                                 uint64_t page_to_free_size)                                     \n\
87 {                                                                                                               \n\
88     if (debug)                                                                                                  \n\
89       printf (\"entering get_item_info with args return_buffer == %p, debug == %d, item == 0x%llx, page_to_free == %p, page_to_free_size == 0x%llx\\n\", return_buffer, debug, item, page_to_free, page_to_free_size); \n\
90     if (page_to_free != 0)                                                                                      \n\
91     {                                                                                                           \n\
92         mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
93     }                                                                                                           \n\
94                                                                                                                 \n\
95     __introspection_dispatch_queue_item_get_info ((void*) item,                                                 \n\
96                                                   (void**)&return_buffer->item_info_buffer_ptr,                 \n\
97                                                   &return_buffer->item_info_buffer_size);                       \n\
98 }                                                                                                               \n\
99 }                                                                                                               \n\
100 ";
101 
102 AppleGetItemInfoHandler::AppleGetItemInfoHandler (Process *process) :
103     m_process (process),
104     m_get_item_info_function (),
105     m_get_item_info_impl_code (),
106     m_get_item_info_function_mutex(),
107     m_get_item_info_return_buffer_addr (LLDB_INVALID_ADDRESS),
108     m_get_item_info_retbuffer_mutex()
109 {
110 }
111 
112 AppleGetItemInfoHandler::~AppleGetItemInfoHandler ()
113 {
114 }
115 
116 void
117 AppleGetItemInfoHandler::Detach ()
118 {
119 
120     if (m_process && m_process->IsAlive() && m_get_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS)
121     {
122         Mutex::Locker locker;
123         locker.TryLock (m_get_item_info_retbuffer_mutex);  // Even if we don't get the lock, deallocate the buffer
124         m_process->DeallocateMemory (m_get_item_info_return_buffer_addr);
125     }
126 }
127 
128 // Compile our __lldb_backtrace_recording_get_item_info() function (from the
129 // source above in g_get_item_info_function_code) if we don't find that function in the inferior
130 // already with USE_BUILTIN_FUNCTION defined.  (e.g. this would be the case for testing.)
131 //
132 // Insert the __lldb_backtrace_recording_get_item_info into the inferior process if needed.
133 //
134 // Write the get_item_info_arglist into the inferior's memory space to prepare for the call.
135 //
136 // Returns the address of the arguments written down in the inferior process, which can be used to
137 // make the function call.
138 
139 lldb::addr_t
140 AppleGetItemInfoHandler::SetupGetItemInfoFunction (Thread &thread, ValueList &get_item_info_arglist)
141 {
142     ExecutionContext exe_ctx (thread.shared_from_this());
143     Address impl_code_address;
144     StreamString errors;
145     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYSTEM_RUNTIME));
146     lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
147 
148     // Scope for mutex locker:
149     {
150         Mutex::Locker locker(m_get_item_info_function_mutex);
151 
152         // First stage is to make the ClangUtility to hold our injected function:
153 
154 #define USE_BUILTIN_FUNCTION 0  // Define this to 1 and we will use the get_implementation function found in the target.
155                                 // This is useful for debugging additions to the get_impl function 'cause you don't have
156                                 // to bother with string-ifying the code into g_get_item_info_function_code.
157 
158         if (USE_BUILTIN_FUNCTION)
159         {
160             ConstString our_utility_function_name("__lldb_backtrace_recording_get_item_info");
161             SymbolContextList sc_list;
162 
163             exe_ctx.GetTargetRef().GetImages().FindSymbolsWithNameAndType (our_utility_function_name, eSymbolTypeCode, sc_list);
164             if (sc_list.GetSize() == 1)
165             {
166                 SymbolContext sc;
167                 sc_list.GetContextAtIndex(0, sc);
168                 if (sc.symbol != NULL)
169                     impl_code_address = sc.symbol->GetAddress();
170 
171                 //lldb::addr_t addr = impl_code_address.GetOpcodeLoadAddress (exe_ctx.GetTargetPtr());
172                 //printf ("Getting address for our_utility_function: 0x%" PRIx64 ".\n", addr);
173             }
174             else
175             {
176                 //printf ("Could not find queues introspection function address.\n");
177                 return args_addr;
178             }
179         }
180         else if (!m_get_item_info_impl_code.get())
181         {
182             if (g_get_item_info_function_code != NULL)
183             {
184                 m_get_item_info_impl_code.reset (new ClangUtilityFunction (g_get_item_info_function_code,
185                                                              g_get_item_info_function_name));
186                 if (!m_get_item_info_impl_code->Install(errors, exe_ctx))
187                 {
188                     if (log)
189                         log->Printf ("Failed to install get-item-info introspection: %s.", errors.GetData());
190                     m_get_item_info_impl_code.reset();
191                     return args_addr;
192                 }
193             }
194             else
195             {
196                 if (log)
197                     log->Printf("No get-item-info introspection code found.");
198                 errors.Printf ("No get-item-info introspection code found.");
199                 return LLDB_INVALID_ADDRESS;
200             }
201 
202             impl_code_address.Clear();
203             impl_code_address.SetOffset(m_get_item_info_impl_code->StartAddress());
204         }
205         else
206         {
207             impl_code_address.Clear();
208             impl_code_address.SetOffset(m_get_item_info_impl_code->StartAddress());
209         }
210 
211         // Next make the runner function for our implementation utility function.
212         if (!m_get_item_info_function.get())
213         {
214             ClangASTContext *clang_ast_context = thread.GetProcess()->GetTarget().GetScratchClangASTContext();
215             ClangASTType get_item_info_return_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
216             m_get_item_info_function.reset(new ClangFunction (thread,
217                                                      get_item_info_return_type,
218                                                      impl_code_address,
219                                                      get_item_info_arglist));
220 
221             errors.Clear();
222             unsigned num_errors = m_get_item_info_function->CompileFunction(errors);
223             if (num_errors)
224             {
225                 if (log)
226                     log->Printf ("Error compiling get-item-info function: \"%s\".", errors.GetData());
227                 return args_addr;
228             }
229 
230             errors.Clear();
231             if (!m_get_item_info_function->WriteFunctionWrapper(exe_ctx, errors))
232             {
233                 if (log)
234                     log->Printf ("Error Inserting get-item-info function: \"%s\".", errors.GetData());
235                 return args_addr;
236             }
237         }
238     }
239 
240     errors.Clear();
241 
242     // Now write down the argument values for this particular call.  This looks like it might be a race condition
243     // if other threads were calling into here, but actually it isn't because we allocate a new args structure for
244     // this call by passing args_addr = LLDB_INVALID_ADDRESS...
245 
246     if (!m_get_item_info_function->WriteFunctionArguments (exe_ctx, args_addr, impl_code_address, get_item_info_arglist, errors))
247     {
248         if (log)
249             log->Printf ("Error writing get-item-info function arguments: \"%s\".", errors.GetData());
250         return args_addr;
251     }
252 
253     return args_addr;
254 }
255 
256 AppleGetItemInfoHandler::GetItemInfoReturnInfo
257 AppleGetItemInfoHandler::GetItemInfo (Thread &thread, uint64_t item, addr_t page_to_free, uint64_t page_to_free_size, Error &error)
258 {
259     lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
260     ProcessSP process_sp (thread.CalculateProcess());
261     TargetSP target_sp (thread.CalculateTarget());
262     ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
263     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYSTEM_RUNTIME));
264 
265     GetItemInfoReturnInfo return_value;
266     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
267     return_value.item_buffer_size = 0;
268 
269     error.Clear();
270 
271     // Set up the arguments for a call to
272 
273     // struct get_item_info_return_values
274     // {
275     //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */
276     //     uint64_t item_info_buffer_size;   /* the size of the items buffer from libBacktraceRecording */
277     // };
278     //
279     // void  __lldb_backtrace_recording_get_item_info
280     //                                            (struct get_item_info_return_values *return_buffer,
281     //                                             int debug,
282     //                                             uint64_t item,
283     //                                             void *page_to_free,
284     //                                             uint64_t page_to_free_size)
285 
286     // Where the return_buffer argument points to a 24 byte region of memory already allocated by lldb in
287     // the inferior process.
288 
289     ClangASTType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
290     Value return_buffer_ptr_value;
291     return_buffer_ptr_value.SetValueType (Value::eValueTypeScalar);
292     return_buffer_ptr_value.SetClangType (clang_void_ptr_type);
293 
294     ClangASTType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
295     Value debug_value;
296     debug_value.SetValueType (Value::eValueTypeScalar);
297     debug_value.SetClangType (clang_int_type);
298 
299     ClangASTType clang_uint64_type = clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
300     Value item_value;
301     item_value.SetValueType (Value::eValueTypeScalar);
302     item_value.SetClangType (clang_uint64_type);
303 
304     Value page_to_free_value;
305     page_to_free_value.SetValueType (Value::eValueTypeScalar);
306     page_to_free_value.SetClangType (clang_void_ptr_type);
307 
308     Value page_to_free_size_value;
309     page_to_free_size_value.SetValueType (Value::eValueTypeScalar);
310     page_to_free_size_value.SetClangType (clang_uint64_type);
311 
312 
313     Mutex::Locker locker(m_get_item_info_retbuffer_mutex);
314     if (m_get_item_info_return_buffer_addr == LLDB_INVALID_ADDRESS)
315     {
316         addr_t bufaddr = process_sp->AllocateMemory (32, ePermissionsReadable | ePermissionsWritable, error);
317         if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS)
318         {
319             if (log)
320                 log->Printf ("Failed to allocate memory for return buffer for get current queues func call");
321             return return_value;
322         }
323         m_get_item_info_return_buffer_addr = bufaddr;
324     }
325 
326     ValueList argument_values;
327 
328     return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr;
329     argument_values.PushValue (return_buffer_ptr_value);
330 
331     debug_value.GetScalar() = 0;
332     argument_values.PushValue (debug_value);
333 
334     item_value.GetScalar() = item;
335     argument_values.PushValue (item_value);
336 
337     if (page_to_free != LLDB_INVALID_ADDRESS)
338         page_to_free_value.GetScalar() = page_to_free;
339     else
340         page_to_free_value.GetScalar() = 0;
341     argument_values.PushValue (page_to_free_value);
342 
343     page_to_free_size_value.GetScalar() = page_to_free_size;
344     argument_values.PushValue (page_to_free_size_value);
345 
346     addr_t args_addr = SetupGetItemInfoFunction (thread, argument_values);
347 
348     StreamString errors;
349     ExecutionContext exe_ctx;
350     EvaluateExpressionOptions options;
351     options.SetUnwindOnError (true);
352     options.SetIgnoreBreakpoints (true);
353     options.SetStopOthers (true);
354     thread.CalculateExecutionContext (exe_ctx);
355 
356     if (m_get_item_info_function == NULL)
357     {
358         error.SetErrorString ("Unable to compile function to call __introspection_dispatch_queue_item_get_info");
359         return return_value;
360     }
361 
362 
363     ExecutionResults func_call_ret;
364     Value results;
365     func_call_ret =  m_get_item_info_function->ExecuteFunction (exe_ctx, &args_addr, options, errors, results);
366     if (func_call_ret != eExecutionCompleted || !error.Success())
367     {
368         if (log)
369             log->Printf ("Unable to call __introspection_dispatch_queue_item_get_info(), got ExecutionResults %d, error contains %s", func_call_ret, error.AsCString(""));
370         error.SetErrorString ("Unable to call __introspection_dispatch_queue_get_item_info() for list of queues");
371         return return_value;
372     }
373 
374     return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory (m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
375     if (!error.Success() || return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS)
376     {
377         return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
378         return return_value;
379     }
380 
381     return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory (m_get_item_info_return_buffer_addr + 8, 8, 0, error);
382 
383     if (!error.Success())
384     {
385         return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
386         return return_value;
387     }
388     if (log)
389         log->Printf ("AppleGetItemInfoHandler called __introspection_dispatch_queue_item_get_info (page_to_free == 0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64 ", size %" PRId64, page_to_free, page_to_free_size, return_value.item_buffer_ptr, return_value.item_buffer_size);
390 
391 
392     return return_value;
393 }
394