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 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/Value.h"
16 #include "lldb/Expression/DiagnosticManager.h"
17 #include "lldb/Expression/FunctionCaller.h"
18 #include "lldb/Expression/UtilityFunction.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/Symbol.h"
21 #include "lldb/Target/ExecutionContext.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/ConstString.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/StreamString.h"
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
32 const char *AppleGetPendingItemsHandler::g_get_pending_items_function_name =
33     "__lldb_backtrace_recording_get_pending_items";
34 const char *AppleGetPendingItemsHandler::g_get_pending_items_function_code =
35     "                                  \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), m_get_pending_items_impl_code(),
104       m_get_pending_items_function_mutex(),
105       m_get_pending_items_return_buffer_addr(LLDB_INVALID_ADDRESS),
106       m_get_pending_items_retbuffer_mutex() {}
107 
108 AppleGetPendingItemsHandler::~AppleGetPendingItemsHandler() {}
109 
110 void AppleGetPendingItemsHandler::Detach() {
111   if (m_process && m_process->IsAlive() &&
112       m_get_pending_items_return_buffer_addr != LLDB_INVALID_ADDRESS) {
113     std::unique_lock<std::mutex> lock(m_get_pending_items_retbuffer_mutex,
114                                       std::defer_lock);
115     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
116     m_process->DeallocateMemory(m_get_pending_items_return_buffer_addr);
117   }
118 }
119 
120 // Compile our __lldb_backtrace_recording_get_pending_items() function (from
121 // the source above in g_get_pending_items_function_code) if we don't find that
122 // function in the inferior already with USE_BUILTIN_FUNCTION defined.  (e.g.
123 // this would be the case for testing.)
124 //
125 // Insert the __lldb_backtrace_recording_get_pending_items into the inferior
126 // process if needed.
127 //
128 // Write the get_pending_items_arglist into the inferior's memory space to
129 // prepare for the call.
130 //
131 // Returns the address of the arguments written down in the inferior process,
132 // which can be used to make the function call.
133 
134 lldb::addr_t AppleGetPendingItemsHandler::SetupGetPendingItemsFunction(
135     Thread &thread, ValueList &get_pending_items_arglist) {
136   ThreadSP thread_sp(thread.shared_from_this());
137   ExecutionContext exe_ctx(thread_sp);
138   DiagnosticManager diagnostics;
139   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
140 
141   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
142   FunctionCaller *get_pending_items_caller = nullptr;
143 
144   // Scope for mutex locker:
145   {
146     std::lock_guard<std::mutex> guard(m_get_pending_items_function_mutex);
147 
148     // First stage is to make the ClangUtility to hold our injected function:
149 
150     if (!m_get_pending_items_impl_code.get()) {
151       if (g_get_pending_items_function_code != NULL) {
152         Status error;
153         m_get_pending_items_impl_code.reset(
154             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
155                 g_get_pending_items_function_code, eLanguageTypeObjC,
156                 g_get_pending_items_function_name, error));
157         if (error.Fail()) {
158           if (log)
159             log->Printf("Failed to get UtilityFunction for pending-items "
160                         "introspection: %s.",
161                         error.AsCString());
162           return args_addr;
163         }
164 
165         if (!m_get_pending_items_impl_code->Install(diagnostics, exe_ctx)) {
166           if (log) {
167             log->Printf("Failed to install pending-items introspection.");
168             diagnostics.Dump(log);
169           }
170           m_get_pending_items_impl_code.reset();
171           return args_addr;
172         }
173       } else {
174         if (log)
175           log->Printf("No pending-items introspection code found.");
176         return LLDB_INVALID_ADDRESS;
177       }
178 
179       // Next make the runner function for our implementation utility function.
180       Status error;
181       ClangASTContext *clang_ast_context =
182           thread.GetProcess()->GetTarget().GetScratchClangASTContext();
183       CompilerType get_pending_items_return_type =
184           clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
185       get_pending_items_caller =
186           m_get_pending_items_impl_code->MakeFunctionCaller(
187               get_pending_items_return_type, get_pending_items_arglist,
188               thread_sp, error);
189       if (error.Fail() || get_pending_items_caller == nullptr) {
190         if (log)
191           log->Printf("Failed to install pending-items introspection function "
192                       "caller: %s.",
193                       error.AsCString());
194         m_get_pending_items_impl_code.reset();
195         return args_addr;
196       }
197     }
198   }
199 
200   diagnostics.Clear();
201 
202   if (get_pending_items_caller == nullptr) {
203     if (log)
204       log->Printf("Failed to get get_pending_items_caller.");
205     return LLDB_INVALID_ADDRESS;
206   }
207 
208   // Now write down the argument values for this particular call.  This looks
209   // like it might be a race condition if other threads were calling into here,
210   // but actually it isn't because we allocate a new args structure for this
211   // call by passing args_addr = LLDB_INVALID_ADDRESS...
212 
213   if (!get_pending_items_caller->WriteFunctionArguments(
214           exe_ctx, args_addr, get_pending_items_arglist, diagnostics)) {
215     if (log) {
216       log->Printf("Error writing pending-items function arguments.");
217       diagnostics.Dump(log);
218     }
219 
220     return args_addr;
221   }
222 
223   return args_addr;
224 }
225 
226 AppleGetPendingItemsHandler::GetPendingItemsReturnInfo
227 AppleGetPendingItemsHandler::GetPendingItems(Thread &thread, addr_t queue,
228                                              addr_t page_to_free,
229                                              uint64_t page_to_free_size,
230                                              Status &error) {
231   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
232   ProcessSP process_sp(thread.CalculateProcess());
233   TargetSP target_sp(thread.CalculateTarget());
234   ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
235   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
236 
237   GetPendingItemsReturnInfo return_value;
238   return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
239   return_value.items_buffer_size = 0;
240   return_value.count = 0;
241 
242   error.Clear();
243 
244   if (!thread.SafeToCallFunctions()) {
245     if (log)
246       log->Printf("Not safe to call functions on thread 0x%" PRIx64,
247                   thread.GetID());
248     error.SetErrorString("Not safe to call functions on this thread.");
249     return return_value;
250   }
251 
252   // Set up the arguments for a call to
253 
254   // struct get_pending_items_return_values
255   // {
256   //     uint64_t pending_items_buffer_ptr;    /* the address of the items
257   //     buffer from libBacktraceRecording */
258   //     uint64_t pending_items_buffer_size;   /* the size of the items buffer
259   //     from libBacktraceRecording */
260   //     uint64_t count;                /* the number of items included in the
261   //     queues buffer */
262   // };
263   //
264   // void  __lldb_backtrace_recording_get_pending_items
265   //                                            (struct
266   //                                            get_pending_items_return_values
267   //                                            *return_buffer,
268   //                                             int debug,
269   //                                             uint64_t /* dispatch_queue_t */
270   //                                             queue
271   //                                             void *page_to_free,
272   //                                             uint64_t page_to_free_size)
273 
274   // Where the return_buffer argument points to a 24 byte region of memory
275   // already allocated by lldb in the inferior process.
276 
277   CompilerType clang_void_ptr_type =
278       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 =
289       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
290   Value queue_value;
291   queue_value.SetValueType(Value::eValueTypeScalar);
292   queue_value.SetCompilerType(clang_uint64_type);
293 
294   Value page_to_free_value;
295   page_to_free_value.SetValueType(Value::eValueTypeScalar);
296   page_to_free_value.SetCompilerType(clang_void_ptr_type);
297 
298   Value page_to_free_size_value;
299   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
300   page_to_free_size_value.SetCompilerType(clang_uint64_type);
301 
302   std::lock_guard<std::mutex> guard(m_get_pending_items_retbuffer_mutex);
303   if (m_get_pending_items_return_buffer_addr == LLDB_INVALID_ADDRESS) {
304     addr_t bufaddr = process_sp->AllocateMemory(
305         32, ePermissionsReadable | ePermissionsWritable, error);
306     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
307       if (log)
308         log->Printf("Failed to allocate memory for return buffer for get "
309                     "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 =
340       m_get_pending_items_impl_code->GetFunctionCaller();
341 
342   EvaluateExpressionOptions options;
343   options.SetUnwindOnError(true);
344   options.SetIgnoreBreakpoints(true);
345   options.SetStopOthers(true);
346   options.SetTimeout(std::chrono::milliseconds(500));
347   options.SetTryAllThreads(false);
348   options.SetIsForUtilityExpr(true);
349   thread.CalculateExecutionContext(exe_ctx);
350 
351   if (get_pending_items_caller == NULL) {
352     error.SetErrorString("Unable to compile function to call "
353                          "__introspection_dispatch_queue_get_pending_items");
354     return return_value;
355   }
356 
357   ExpressionResults func_call_ret;
358   Value results;
359   func_call_ret = get_pending_items_caller->ExecuteFunction(
360       exe_ctx, &args_addr, options, diagnostics, results);
361   if (func_call_ret != eExpressionCompleted || !error.Success()) {
362     if (log)
363       log->Printf("Unable to call "
364                   "__introspection_dispatch_queue_get_pending_items(), got "
365                   "ExpressionResults %d, error contains %s",
366                   func_call_ret, error.AsCString(""));
367     error.SetErrorString("Unable to call "
368                          "__introspection_dispatch_queue_get_pending_items() "
369                          "for list of queues");
370     return return_value;
371   }
372 
373   return_value.items_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
374       m_get_pending_items_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
375   if (!error.Success() ||
376       return_value.items_buffer_ptr == LLDB_INVALID_ADDRESS) {
377     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
378     return return_value;
379   }
380 
381   return_value.items_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
382       m_get_pending_items_return_buffer_addr + 8, 8, 0, error);
383 
384   if (!error.Success()) {
385     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
386     return return_value;
387   }
388 
389   return_value.count = m_process->ReadUnsignedIntegerFromMemory(
390       m_get_pending_items_return_buffer_addr + 16, 8, 0, error);
391   if (!error.Success()) {
392     return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
393     return return_value;
394   }
395 
396   if (log)
397     log->Printf("AppleGetPendingItemsHandler called "
398                 "__introspection_dispatch_queue_get_pending_items "
399                 "(page_to_free == 0x%" PRIx64 ", size = %" PRId64
400                 "), returned page is at 0x%" PRIx64 ", size %" PRId64
401                 ", count = %" PRId64,
402                 page_to_free, page_to_free_size, return_value.items_buffer_ptr,
403                 return_value.items_buffer_size, return_value.count);
404 
405   return return_value;
406 }
407