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