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