1 //===-- AppleGetPendingItemsHandler.cpp -------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include "AppleGetPendingItemsHandler.h"
12 
13 // C Includes
14 // C++ Includes
15 // Other libraries and framework includes
16 // Project includes
17 
18 #include "lldb/Core/ConstString.h"
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Core/Value.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/FunctionCaller.h"
25 #include "lldb/Expression/UtilityFunction.h"
26 #include "lldb/Symbol/ClangASTContext.h"
27 #include "lldb/Symbol/Symbol.h"
28 #include "lldb/Target/ExecutionContext.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 
36 const char *AppleGetPendingItemsHandler::g_get_pending_items_function_name =
37     "__lldb_backtrace_recording_get_pending_items";
38 const char *AppleGetPendingItemsHandler::g_get_pending_items_function_code =
39     "                                  \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), m_get_pending_items_impl_code(),
108       m_get_pending_items_function_mutex(),
109       m_get_pending_items_return_buffer_addr(LLDB_INVALID_ADDRESS),
110       m_get_pending_items_retbuffer_mutex() {}
111 
112 AppleGetPendingItemsHandler::~AppleGetPendingItemsHandler() {}
113 
114 void AppleGetPendingItemsHandler::Detach() {
115   if (m_process && m_process->IsAlive() &&
116       m_get_pending_items_return_buffer_addr != LLDB_INVALID_ADDRESS) {
117     std::unique_lock<std::mutex> lock(m_get_pending_items_retbuffer_mutex,
118                                       std::defer_lock);
119     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
120     m_process->DeallocateMemory(m_get_pending_items_return_buffer_addr);
121   }
122 }
123 
124 // Compile our __lldb_backtrace_recording_get_pending_items() function (from the
125 // source above in g_get_pending_items_function_code) if we don't find that
126 // function in the inferior
127 // already with USE_BUILTIN_FUNCTION defined.  (e.g. this would be the case for
128 // testing.)
129 //
130 // Insert the __lldb_backtrace_recording_get_pending_items into the inferior
131 // process if needed.
132 //
133 // Write the get_pending_items_arglist into the inferior's memory space to
134 // prepare for the call.
135 //
136 // Returns the address of the arguments written down in the inferior process,
137 // which can be used to
138 // make the function call.
139 
140 lldb::addr_t AppleGetPendingItemsHandler::SetupGetPendingItemsFunction(
141     Thread &thread, ValueList &get_pending_items_arglist) {
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     std::lock_guard<std::mutex> guard(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       if (g_get_pending_items_function_code != NULL) {
158         Error error;
159         m_get_pending_items_impl_code.reset(
160             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
161                 g_get_pending_items_function_code, eLanguageTypeObjC,
162                 g_get_pending_items_function_name, error));
163         if (error.Fail()) {
164           if (log)
165             log->Printf("Failed to get UtilityFunction for pending-items "
166                         "introspection: %s.",
167                         error.AsCString());
168           return args_addr;
169         }
170 
171         if (!m_get_pending_items_impl_code->Install(diagnostics, exe_ctx)) {
172           if (log) {
173             log->Printf("Failed to install pending-items introspection.");
174             diagnostics.Dump(log);
175           }
176           m_get_pending_items_impl_code.reset();
177           return args_addr;
178         }
179       } else {
180         if (log)
181           log->Printf("No pending-items introspection code found.");
182         return LLDB_INVALID_ADDRESS;
183       }
184 
185       // Next make the runner function for our implementation utility function.
186       Error error;
187       ClangASTContext *clang_ast_context =
188           thread.GetProcess()->GetTarget().GetScratchClangASTContext();
189       CompilerType get_pending_items_return_type =
190           clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
191       get_pending_items_caller =
192           m_get_pending_items_impl_code->MakeFunctionCaller(
193               get_pending_items_return_type, get_pending_items_arglist,
194               thread_sp, error);
195       if (error.Fail()) {
196         if (log)
197           log->Printf("Failed to install pending-items introspection function "
198                       "caller: %s.",
199                       error.AsCString());
200         m_get_pending_items_impl_code.reset();
201         return args_addr;
202       }
203     }
204   }
205 
206   diagnostics.Clear();
207 
208   if (get_pending_items_caller == nullptr) {
209     if (log)
210       log->Printf("Failed to get get_pending_items_caller.");
211     return LLDB_INVALID_ADDRESS;
212   }
213 
214   // Now write down the argument values for this particular call.  This looks
215   // like it might be a race condition
216   // if other threads were calling into here, but actually it isn't because we
217   // allocate a new args structure for
218   // this call by passing args_addr = LLDB_INVALID_ADDRESS...
219 
220   if (!get_pending_items_caller->WriteFunctionArguments(
221           exe_ctx, args_addr, get_pending_items_arglist, diagnostics)) {
222     if (log) {
223       log->Printf("Error writing pending-items function arguments.");
224       diagnostics.Dump(log);
225     }
226 
227     return args_addr;
228   }
229 
230   return args_addr;
231 }
232 
233 AppleGetPendingItemsHandler::GetPendingItemsReturnInfo
234 AppleGetPendingItemsHandler::GetPendingItems(Thread &thread, addr_t queue,
235                                              addr_t page_to_free,
236                                              uint64_t page_to_free_size,
237                                              Error &error) {
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     if (log)
253       log->Printf("Not safe to call functions on thread 0x%" PRIx64,
254                   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
264   //     buffer from libBacktraceRecording */
265   //     uint64_t pending_items_buffer_size;   /* the size of the items buffer
266   //     from libBacktraceRecording */
267   //     uint64_t count;                /* the number of items included in the
268   //     queues buffer */
269   // };
270   //
271   // void  __lldb_backtrace_recording_get_pending_items
272   //                                            (struct
273   //                                            get_pending_items_return_values
274   //                                            *return_buffer,
275   //                                             int debug,
276   //                                             uint64_t /* dispatch_queue_t */
277   //                                             queue
278   //                                             void *page_to_free,
279   //                                             uint64_t page_to_free_size)
280 
281   // Where the return_buffer argument points to a 24 byte region of memory
282   // already allocated by lldb in
283   // the inferior process.
284 
285   CompilerType clang_void_ptr_type =
286       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
287   Value return_buffer_ptr_value;
288   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
289   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
290 
291   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
292   Value debug_value;
293   debug_value.SetValueType(Value::eValueTypeScalar);
294   debug_value.SetCompilerType(clang_int_type);
295 
296   CompilerType clang_uint64_type =
297       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
298   Value queue_value;
299   queue_value.SetValueType(Value::eValueTypeScalar);
300   queue_value.SetCompilerType(clang_uint64_type);
301 
302   Value page_to_free_value;
303   page_to_free_value.SetValueType(Value::eValueTypeScalar);
304   page_to_free_value.SetCompilerType(clang_void_ptr_type);
305 
306   Value page_to_free_size_value;
307   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
308   page_to_free_size_value.SetCompilerType(clang_uint64_type);
309 
310   std::lock_guard<std::mutex> guard(m_get_pending_items_retbuffer_mutex);
311   if (m_get_pending_items_return_buffer_addr == LLDB_INVALID_ADDRESS) {
312     addr_t bufaddr = process_sp->AllocateMemory(
313         32, ePermissionsReadable | ePermissionsWritable, error);
314     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
315       if (log)
316         log->Printf("Failed to allocate memory for return buffer for get "
317                     "current queues func call");
318       return return_value;
319     }
320     m_get_pending_items_return_buffer_addr = bufaddr;
321   }
322 
323   ValueList argument_values;
324 
325   return_buffer_ptr_value.GetScalar() = m_get_pending_items_return_buffer_addr;
326   argument_values.PushValue(return_buffer_ptr_value);
327 
328   debug_value.GetScalar() = 0;
329   argument_values.PushValue(debug_value);
330 
331   queue_value.GetScalar() = queue;
332   argument_values.PushValue(queue_value);
333 
334   if (page_to_free != LLDB_INVALID_ADDRESS)
335     page_to_free_value.GetScalar() = page_to_free;
336   else
337     page_to_free_value.GetScalar() = 0;
338   argument_values.PushValue(page_to_free_value);
339 
340   page_to_free_size_value.GetScalar() = page_to_free_size;
341   argument_values.PushValue(page_to_free_size_value);
342 
343   addr_t args_addr = SetupGetPendingItemsFunction(thread, argument_values);
344 
345   DiagnosticManager diagnostics;
346   ExecutionContext exe_ctx;
347   FunctionCaller *get_pending_items_caller =
348       m_get_pending_items_impl_code->GetFunctionCaller();
349 
350   EvaluateExpressionOptions options;
351   options.SetUnwindOnError(true);
352   options.SetIgnoreBreakpoints(true);
353   options.SetStopOthers(true);
354   options.SetTimeoutUsec(500000);
355   options.SetTryAllThreads(false);
356   thread.CalculateExecutionContext(exe_ctx);
357 
358   if (get_pending_items_caller == NULL) {
359     error.SetErrorString("Unable to compile function to call "
360                          "__introspection_dispatch_queue_get_pending_items");
361     return return_value;
362   }
363 
364   ExpressionResults func_call_ret;
365   Value results;
366   func_call_ret = get_pending_items_caller->ExecuteFunction(
367       exe_ctx, &args_addr, options, diagnostics, results);
368   if (func_call_ret != eExpressionCompleted || !error.Success()) {
369     if (log)
370       log->Printf("Unable to call "
371                   "__introspection_dispatch_queue_get_pending_items(), got "
372                   "ExpressionResults %d, error contains %s",
373                   func_call_ret, error.AsCString(""));
374     error.SetErrorString("Unable to call "
375                          "__introspection_dispatch_queue_get_pending_items() "
376                          "for list of queues");
377     return return_value;
378   }
379 
380   return_value.items_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
381       m_get_pending_items_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
382   if (!error.Success() ||
383       return_value.items_buffer_ptr == LLDB_INVALID_ADDRESS) {
384     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
385     return return_value;
386   }
387 
388   return_value.items_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
389       m_get_pending_items_return_buffer_addr + 8, 8, 0, error);
390 
391   if (!error.Success()) {
392     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
393     return return_value;
394   }
395 
396   return_value.count = m_process->ReadUnsignedIntegerFromMemory(
397       m_get_pending_items_return_buffer_addr + 16, 8, 0, error);
398   if (!error.Success()) {
399     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
400     return return_value;
401   }
402 
403   if (log)
404     log->Printf("AppleGetPendingItemsHandler called "
405                 "__introspection_dispatch_queue_get_pending_items "
406                 "(page_to_free == 0x%" PRIx64 ", size = %" PRId64
407                 "), returned page is at 0x%" PRIx64 ", size %" PRId64
408                 ", count = %" PRId64,
409                 page_to_free, page_to_free_size, return_value.items_buffer_ptr,
410                 return_value.items_buffer_size, return_value.count);
411 
412   return return_value;
413 }
414