1 //===-- AppleGetPendingItemsHandler.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 "AppleGetPendingItemsHandler.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 *AppleGetPendingItemsHandler::g_get_pending_items_function_name = "__lldb_backtrace_recording_get_pending_items";
39 const char *AppleGetPendingItemsHandler::g_get_pending_items_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_get_pending_items (dispatch_queue_t queue,                   \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_pending_items_return_values                                                                      \n\
76     {                                                                                                           \n\
77         uint64_t pending_items_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */  \n\
78         uint64_t pending_items_buffer_size;   /* the size of the items buffer from libBacktraceRecording */     \n\
79         uint64_t count;                /* the number of items included in the queues buffer */                  \n\
80     };                                                                                                          \n\
81                                                                                                                 \n\
82     void  __lldb_backtrace_recording_get_pending_items                                                          \n\
83                                                (struct get_pending_items_return_values *return_buffer,          \n\
84                                                 int debug,                                                      \n\
85                                                 uint64_t /* dispatch_queue_t */ queue,                          \n\
86                                                 void *page_to_free,                                             \n\
87                                                 uint64_t page_to_free_size)                                     \n\
88 {                                                                                                               \n\
89     if (debug)                                                                                                  \n\
90       printf (\"entering get_pending_items with args return_buffer == %p, debug == %d, queue == 0x%llx, page_to_free == %p, page_to_free_size == 0x%llx\\n\", return_buffer, debug, queue, page_to_free, page_to_free_size); \n\
91     if (page_to_free != 0)                                                                                      \n\
92     {                                                                                                           \n\
93         mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
94     }                                                                                                           \n\
95                                                                                                                 \n\
96     return_buffer->count = __introspection_dispatch_queue_get_pending_items (                                   \n\
97                                                       (void*) queue,                                            \n\
98                                                       (void**)&return_buffer->pending_items_buffer_ptr,         \n\
99                                                       &return_buffer->pending_items_buffer_size);               \n\
100     if (debug)                                                                                                  \n\
101         printf(\"result was count %lld\\n\", return_buffer->count);                                             \n\
102 }                                                                                                               \n\
103 }                                                                                                               \n\
104 ";
105 
106 AppleGetPendingItemsHandler::AppleGetPendingItemsHandler (Process *process) :
107     m_process (process),
108     m_get_pending_items_function (),
109     m_get_pending_items_impl_code (),
110     m_get_pending_items_function_mutex(),
111     m_get_pending_items_return_buffer_addr (LLDB_INVALID_ADDRESS),
112     m_get_pending_items_retbuffer_mutex()
113 {
114 }
115 
116 AppleGetPendingItemsHandler::~AppleGetPendingItemsHandler ()
117 {
118 }
119 
120 void
121 AppleGetPendingItemsHandler::Detach ()
122 {
123 
124     if (m_process && m_process->IsAlive() && m_get_pending_items_return_buffer_addr != LLDB_INVALID_ADDRESS)
125     {
126         Mutex::Locker locker;
127         locker.TryLock (m_get_pending_items_retbuffer_mutex);  // Even if we don't get the lock, deallocate the buffer
128         m_process->DeallocateMemory (m_get_pending_items_return_buffer_addr);
129     }
130 }
131 
132 // Compile our __lldb_backtrace_recording_get_pending_items() function (from the
133 // source above in g_get_pending_items_function_code) if we don't find that function in the inferior
134 // already with USE_BUILTIN_FUNCTION defined.  (e.g. this would be the case for testing.)
135 //
136 // Insert the __lldb_backtrace_recording_get_pending_items into the inferior process if needed.
137 //
138 // Write the get_pending_items_arglist into the inferior's memory space to prepare for the call.
139 //
140 // Returns the address of the arguments written down in the inferior process, which can be used to
141 // make the function call.
142 
143 lldb::addr_t
144 AppleGetPendingItemsHandler::SetupGetPendingItemsFunction (Thread &thread, ValueList &get_pending_items_arglist)
145 {
146     ExecutionContext exe_ctx (thread.shared_from_this());
147     Address impl_code_address;
148     StreamString errors;
149     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYSTEM_RUNTIME));
150     lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
151 
152     // Scope for mutex locker:
153     {
154         Mutex::Locker locker(m_get_pending_items_function_mutex);
155 
156         // First stage is to make the ClangUtility to hold our injected function:
157 
158 #define USE_BUILTIN_FUNCTION 0  // Define this to 1 and we will use the get_implementation function found in the target.
159                                 // This is useful for debugging additions to the get_impl function 'cause you don't have
160                                 // to bother with string-ifying the code into g_get_pending_items_function_code.
161 
162         if (USE_BUILTIN_FUNCTION)
163         {
164             ConstString our_utility_function_name("__lldb_backtrace_recording_get_pending_items");
165             SymbolContextList sc_list;
166 
167             exe_ctx.GetTargetRef().GetImages().FindSymbolsWithNameAndType (our_utility_function_name, eSymbolTypeCode, sc_list);
168             if (sc_list.GetSize() == 1)
169             {
170                 SymbolContext sc;
171                 sc_list.GetContextAtIndex(0, sc);
172                 if (sc.symbol != NULL)
173                     impl_code_address = sc.symbol->GetAddress();
174 
175                 //lldb::addr_t addr = impl_code_address.GetOpcodeLoadAddress (exe_ctx.GetTargetPtr());
176                 //printf ("Getting address for our_utility_function: 0x%" PRIx64 ".\n", addr);
177             }
178             else
179             {
180                 //printf ("Could not find queues introspection function address.\n");
181                 return args_addr;
182             }
183         }
184         else if (!m_get_pending_items_impl_code.get())
185         {
186             if (g_get_pending_items_function_code != NULL)
187             {
188                 m_get_pending_items_impl_code.reset (new ClangUtilityFunction (g_get_pending_items_function_code,
189                                                              g_get_pending_items_function_name));
190                 if (!m_get_pending_items_impl_code->Install(errors, exe_ctx))
191                 {
192                     if (log)
193                         log->Printf ("Failed to install pending-items introspection: %s.", errors.GetData());
194                     m_get_pending_items_impl_code.reset();
195                     return args_addr;
196                 }
197             }
198             else
199             {
200                 if (log)
201                     log->Printf("No pending-items introspection code found.");
202                 errors.Printf ("No pending-items introspection code found.");
203                 return LLDB_INVALID_ADDRESS;
204             }
205 
206             impl_code_address.Clear();
207             impl_code_address.SetOffset(m_get_pending_items_impl_code->StartAddress());
208         }
209         else
210         {
211             impl_code_address.Clear();
212             impl_code_address.SetOffset(m_get_pending_items_impl_code->StartAddress());
213         }
214 
215         // Next make the runner function for our implementation utility function.
216         if (!m_get_pending_items_function.get())
217         {
218             ClangASTContext *clang_ast_context = thread.GetProcess()->GetTarget().GetScratchClangASTContext();
219             ClangASTType get_pending_items_return_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
220             m_get_pending_items_function.reset(new ClangFunction (thread,
221                                                      get_pending_items_return_type,
222                                                      impl_code_address,
223                                                      get_pending_items_arglist,
224                                                      "queue-pending-items"));
225 
226             errors.Clear();
227             unsigned num_errors = m_get_pending_items_function->CompileFunction(errors);
228             if (num_errors)
229             {
230                 if (log)
231                     log->Printf ("Error compiling pending-items function: \"%s\".", errors.GetData());
232                 return args_addr;
233             }
234 
235             errors.Clear();
236             if (!m_get_pending_items_function->WriteFunctionWrapper(exe_ctx, errors))
237             {
238                 if (log)
239                     log->Printf ("Error Inserting pending-items function: \"%s\".", errors.GetData());
240                 return args_addr;
241             }
242         }
243     }
244 
245     errors.Clear();
246 
247     // Now write down the argument values for this particular call.  This looks like it might be a race condition
248     // if other threads were calling into here, but actually it isn't because we allocate a new args structure for
249     // this call by passing args_addr = LLDB_INVALID_ADDRESS...
250 
251     if (!m_get_pending_items_function->WriteFunctionArguments (exe_ctx, args_addr, impl_code_address, get_pending_items_arglist, errors))
252     {
253         if (log)
254             log->Printf ("Error writing pending-items function arguments: \"%s\".", errors.GetData());
255         return args_addr;
256     }
257 
258     return args_addr;
259 }
260 
261 AppleGetPendingItemsHandler::GetPendingItemsReturnInfo
262 AppleGetPendingItemsHandler::GetPendingItems (Thread &thread, addr_t queue, addr_t page_to_free, uint64_t page_to_free_size, Error &error)
263 {
264     lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
265     ProcessSP process_sp (thread.CalculateProcess());
266     TargetSP target_sp (thread.CalculateTarget());
267     ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
268     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYSTEM_RUNTIME));
269 
270     GetPendingItemsReturnInfo return_value;
271     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
272     return_value.items_buffer_size = 0;
273     return_value.count = 0;
274 
275     error.Clear();
276 
277     if (thread.SafeToCallFunctions() == false)
278     {
279         if (log)
280             log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
281         error.SetErrorString ("Not safe to call functions on this thread.");
282         return return_value;
283     }
284 
285     // Set up the arguments for a call to
286 
287     // struct get_pending_items_return_values
288     // {
289     //     uint64_t pending_items_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */
290     //     uint64_t pending_items_buffer_size;   /* the size of the items buffer from libBacktraceRecording */
291     //     uint64_t count;                /* the number of items included in the queues buffer */
292     // };
293     //
294     // void  __lldb_backtrace_recording_get_pending_items
295     //                                            (struct get_pending_items_return_values *return_buffer,
296     //                                             int debug,
297     //                                             uint64_t /* dispatch_queue_t */ queue
298     //                                             void *page_to_free,
299     //                                             uint64_t page_to_free_size)
300 
301     // Where the return_buffer argument points to a 24 byte region of memory already allocated by lldb in
302     // the inferior process.
303 
304     ClangASTType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
305     Value return_buffer_ptr_value;
306     return_buffer_ptr_value.SetValueType (Value::eValueTypeScalar);
307     return_buffer_ptr_value.SetClangType (clang_void_ptr_type);
308 
309     ClangASTType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
310     Value debug_value;
311     debug_value.SetValueType (Value::eValueTypeScalar);
312     debug_value.SetClangType (clang_int_type);
313 
314     ClangASTType clang_uint64_type = clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
315     Value queue_value;
316     queue_value.SetValueType (Value::eValueTypeScalar);
317     queue_value.SetClangType (clang_uint64_type);
318 
319     Value page_to_free_value;
320     page_to_free_value.SetValueType (Value::eValueTypeScalar);
321     page_to_free_value.SetClangType (clang_void_ptr_type);
322 
323     Value page_to_free_size_value;
324     page_to_free_size_value.SetValueType (Value::eValueTypeScalar);
325     page_to_free_size_value.SetClangType (clang_uint64_type);
326 
327 
328     Mutex::Locker locker(m_get_pending_items_retbuffer_mutex);
329     if (m_get_pending_items_return_buffer_addr == LLDB_INVALID_ADDRESS)
330     {
331         addr_t bufaddr = process_sp->AllocateMemory (32, ePermissionsReadable | ePermissionsWritable, error);
332         if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS)
333         {
334             if (log)
335                 log->Printf ("Failed to allocate memory for return buffer for get current queues func call");
336             return return_value;
337         }
338         m_get_pending_items_return_buffer_addr = bufaddr;
339     }
340 
341     ValueList argument_values;
342 
343     return_buffer_ptr_value.GetScalar() = m_get_pending_items_return_buffer_addr;
344     argument_values.PushValue (return_buffer_ptr_value);
345 
346     debug_value.GetScalar() = 0;
347     argument_values.PushValue (debug_value);
348 
349     queue_value.GetScalar() = queue;
350     argument_values.PushValue (queue_value);
351 
352     if (page_to_free != LLDB_INVALID_ADDRESS)
353         page_to_free_value.GetScalar() = page_to_free;
354     else
355         page_to_free_value.GetScalar() = 0;
356     argument_values.PushValue (page_to_free_value);
357 
358     page_to_free_size_value.GetScalar() = page_to_free_size;
359     argument_values.PushValue (page_to_free_size_value);
360 
361     addr_t args_addr = SetupGetPendingItemsFunction (thread, argument_values);
362 
363     StreamString errors;
364     ExecutionContext exe_ctx;
365     EvaluateExpressionOptions options;
366     options.SetUnwindOnError (true);
367     options.SetIgnoreBreakpoints (true);
368     options.SetStopOthers (true);
369     options.SetTimeoutUsec(500000);
370     options.SetTryAllThreads (false);
371     thread.CalculateExecutionContext (exe_ctx);
372 
373     if (m_get_pending_items_function == NULL)
374     {
375         error.SetErrorString ("Unable to compile function to call __introspection_dispatch_queue_get_pending_items");
376     }
377 
378 
379     ExpressionResults func_call_ret;
380     Value results;
381     func_call_ret =  m_get_pending_items_function->ExecuteFunction (exe_ctx, &args_addr, options, errors, results);
382     if (func_call_ret != eExpressionCompleted || !error.Success())
383     {
384         if (log)
385             log->Printf ("Unable to call __introspection_dispatch_queue_get_pending_items(), got ExpressionResults %d, error contains %s", func_call_ret, error.AsCString(""));
386         error.SetErrorString ("Unable to call __introspection_dispatch_queue_get_pending_items() for list of queues");
387         return return_value;
388     }
389 
390     return_value.items_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory (m_get_pending_items_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
391     if (!error.Success() || return_value.items_buffer_ptr == LLDB_INVALID_ADDRESS)
392     {
393         return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
394         return return_value;
395     }
396 
397     return_value.items_buffer_size = m_process->ReadUnsignedIntegerFromMemory (m_get_pending_items_return_buffer_addr + 8, 8, 0, error);
398 
399     if (!error.Success())
400     {
401         return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
402         return return_value;
403     }
404 
405     return_value.count = m_process->ReadUnsignedIntegerFromMemory (m_get_pending_items_return_buffer_addr + 16, 8, 0, error);
406     if (!error.Success())
407     {
408         return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
409         return return_value;
410     }
411 
412     if (log)
413         log->Printf ("AppleGetPendingItemsHandler called __introspection_dispatch_queue_get_pending_items (page_to_free == 0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64 ", size %" PRId64 ", count = %" PRId64, page_to_free, page_to_free_size, return_value.items_buffer_ptr, return_value.items_buffer_size, return_value.count);
414 
415     return return_value;
416 }
417