1 //===-- AppleGetQueuesHandler.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 "AppleGetQueuesHandler.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Core/ConstString.h"
17 #include "lldb/Core/Log.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/StreamString.h"
20 #include "lldb/Core/Value.h"
21 #include "lldb/Expression/DiagnosticManager.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 *AppleGetQueuesHandler::g_get_current_queues_function_name =
35     "__lldb_backtrace_recording_get_current_queues";
36 const char *AppleGetQueuesHandler::g_get_current_queues_function_code =
37     "                             \n\
38 extern \"C\"                                                                                                    \n\
39 {                                                                                                               \n\
40     /*                                                                                                          \n\
41      * mach defines                                                                                             \n\
42      */                                                                                                         \n\
43                                                                                                                 \n\
44     typedef unsigned int uint32_t;                                                                              \n\
45     typedef unsigned long long uint64_t;                                                                        \n\
46     typedef uint32_t mach_port_t;                                                                               \n\
47     typedef mach_port_t vm_map_t;                                                                               \n\
48     typedef int kern_return_t;                                                                                  \n\
49     typedef uint64_t mach_vm_address_t;                                                                         \n\
50     typedef uint64_t mach_vm_size_t;                                                                            \n\
51                                                                                                                 \n\
52     mach_port_t mach_task_self ();                                                                              \n\
53     kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);         \n\
54                                                                                                                 \n\
55     /*                                                                                                          \n\
56      * libBacktraceRecording defines                                                                            \n\
57      */                                                                                                         \n\
58                                                                                                                 \n\
59     typedef uint32_t queue_list_scope_t;                                                                        \n\
60     typedef void *introspection_dispatch_queue_info_t;                                                          \n\
61                                                                                                                 \n\
62     extern uint64_t __introspection_dispatch_get_queues (queue_list_scope_t scope,                              \n\
63                                                  introspection_dispatch_queue_info_t *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_current_queues_return_values                                                                     \n\
72     {                                                                                                           \n\
73         uint64_t queues_buffer_ptr;    /* the address of the queues buffer from libBacktraceRecording */        \n\
74         uint64_t queues_buffer_size;   /* the size of the queues buffer from libBacktraceRecording */           \n\
75         uint64_t count;                /* the number of queues included in the queues buffer */                 \n\
76     };                                                                                                          \n\
77                                                                                                                 \n\
78     void  __lldb_backtrace_recording_get_current_queues                                                         \n\
79                                                (struct get_current_queues_return_values *return_buffer,         \n\
80                                                 int debug,                                                      \n\
81                                                 void *page_to_free,                                             \n\
82                                                 uint64_t page_to_free_size)                                     \n\
83 {                                                                                                               \n\
84     if (debug)                                                                                                  \n\
85       printf (\"entering get_current_queues with args %p, %d, 0x%p, 0x%llx\\n\", return_buffer, debug, page_to_free, page_to_free_size); \n\
86     if (page_to_free != 0)                                                                                      \n\
87     {                                                                                                           \n\
88         mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
89     }                                                                                                           \n\
90                                                                                                                 \n\
91     return_buffer->count = __introspection_dispatch_get_queues (                                                \n\
92                                                       /* QUEUES_WITH_ANY_ITEMS */ 2,                            \n\
93                                                       (void**)&return_buffer->queues_buffer_ptr,                \n\
94                                                       &return_buffer->queues_buffer_size);                      \n\
95     if (debug)                                                                                                  \n\
96         printf(\"result was count %lld\\n\", return_buffer->count);                                             \n\
97 }                                                                                                               \n\
98 }                                                                                                               \n\
99 ";
100 
101 AppleGetQueuesHandler::AppleGetQueuesHandler(Process *process)
102     : m_process(process), m_get_queues_impl_code_up(),
103       m_get_queues_function_mutex(),
104       m_get_queues_return_buffer_addr(LLDB_INVALID_ADDRESS),
105       m_get_queues_retbuffer_mutex() {}
106 
107 AppleGetQueuesHandler::~AppleGetQueuesHandler() {}
108 
109 void AppleGetQueuesHandler::Detach() {
110 
111   if (m_process && m_process->IsAlive() &&
112       m_get_queues_return_buffer_addr != LLDB_INVALID_ADDRESS) {
113     std::unique_lock<std::mutex> lock(m_get_queues_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_queues_return_buffer_addr);
117   }
118 }
119 
120 // Construct a CompilerType for the structure that
121 // g_get_current_queues_function_code will return by value
122 // so we can extract the fields after performing the function call.
123 // i.e. we are getting this struct returned to us:
124 //
125 //    struct get_current_queues_return_values
126 //    {
127 //        introspection_dispatch_queue_info_t *queues_buffer;
128 //        uint64_t queues_buffer_size;
129 //        uint64_t count;
130 //    };
131 
132 // Compile our __lldb_backtrace_recording_get_current_queues() function (from
133 // the
134 // source above in g_get_current_queues_function_code) if we don't find that
135 // function in the inferior
136 // already with USE_BUILTIN_FUNCTION defined.  (e.g. this would be the case for
137 // testing.)
138 //
139 // Insert the __lldb_backtrace_recording_get_current_queues into the inferior
140 // process if needed.
141 //
142 // Write the get_queues_arglist into the inferior's memory space to prepare for
143 // the call.
144 //
145 // Returns the address of the arguments written down in the inferior process,
146 // which can be used to
147 // make the function call.
148 
149 lldb::addr_t
150 AppleGetQueuesHandler::SetupGetQueuesFunction(Thread &thread,
151                                               ValueList &get_queues_arglist) {
152   ThreadSP thread_sp(thread.shared_from_this());
153   ExecutionContext exe_ctx(thread_sp);
154 
155   Address impl_code_address;
156   DiagnosticManager diagnostics;
157   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
158   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
159 
160   FunctionCaller *get_queues_caller = nullptr;
161 
162   // Scope for mutex locker:
163   {
164     std::lock_guard<std::mutex> guard(m_get_queues_function_mutex);
165 
166     // First stage is to make the ClangUtility to hold our injected function:
167 
168     if (!m_get_queues_impl_code_up.get()) {
169       if (g_get_current_queues_function_code != NULL) {
170         Error error;
171         m_get_queues_impl_code_up.reset(
172             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
173                 g_get_current_queues_function_code, eLanguageTypeC,
174                 g_get_current_queues_function_name, error));
175         if (error.Fail()) {
176           if (log)
177             log->Printf(
178                 "Failed to get UtilityFunction for queues introspection: %s.",
179                 error.AsCString());
180           return args_addr;
181         }
182 
183         if (!m_get_queues_impl_code_up->Install(diagnostics, exe_ctx)) {
184           if (log) {
185             log->Printf("Failed to install queues introspection");
186             diagnostics.Dump(log);
187           }
188           m_get_queues_impl_code_up.reset();
189           return args_addr;
190         }
191       } else {
192         if (log) {
193           log->Printf("No queues introspection code found.");
194           diagnostics.Dump(log);
195         }
196         return LLDB_INVALID_ADDRESS;
197       }
198     }
199 
200     // Next make the runner function for our implementation utility function.
201     ClangASTContext *clang_ast_context =
202         thread.GetProcess()->GetTarget().GetScratchClangASTContext();
203     CompilerType get_queues_return_type =
204         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
205     Error error;
206     get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller(
207         get_queues_return_type, get_queues_arglist, thread_sp, error);
208     if (error.Fail()) {
209       if (log)
210         log->Printf(
211             "Could not get function caller for get-queues function: %s.",
212             error.AsCString());
213       return args_addr;
214     }
215   }
216 
217   diagnostics.Clear();
218 
219   // Now write down the argument values for this particular call.  This looks
220   // like it might be a race condition
221   // if other threads were calling into here, but actually it isn't because we
222   // allocate a new args structure for
223   // this call by passing args_addr = LLDB_INVALID_ADDRESS...
224 
225   if (!get_queues_caller->WriteFunctionArguments(
226           exe_ctx, args_addr, get_queues_arglist, diagnostics)) {
227     if (log) {
228       log->Printf("Error writing get-queues function arguments.");
229       diagnostics.Dump(log);
230     }
231     return args_addr;
232   }
233 
234   return args_addr;
235 }
236 
237 AppleGetQueuesHandler::GetQueuesReturnInfo
238 AppleGetQueuesHandler::GetCurrentQueues(Thread &thread, addr_t page_to_free,
239                                         uint64_t page_to_free_size,
240                                         Error &error) {
241   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
242   ProcessSP process_sp(thread.CalculateProcess());
243   TargetSP target_sp(thread.CalculateTarget());
244   ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
245   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
246 
247   GetQueuesReturnInfo return_value;
248   return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
249   return_value.queues_buffer_size = 0;
250   return_value.count = 0;
251 
252   error.Clear();
253 
254   if (thread.SafeToCallFunctions() == false) {
255     if (log)
256       log->Printf("Not safe to call functions on thread 0x%" PRIx64,
257                   thread.GetID());
258     error.SetErrorString("Not safe to call functions on this thread.");
259     return return_value;
260   }
261 
262   // Set up the arguments for a call to
263 
264   // struct get_current_queues_return_values
265   // {
266   //    uint64_t queues_buffer_ptr;    /* the address of the queues buffer from
267   //    libBacktraceRecording */
268   //    uint64_t queues_buffer_size;   /* the size of the queues buffer from
269   //    libBacktraceRecording */
270   //    uint64_t count;                /* the number of queues included in the
271   //    queues buffer */
272   // };
273   //
274   //  void
275   //    __lldb_backtrace_recording_get_current_queues
276   //                                         (struct
277   //                                         get_current_queues_return_values
278   //                                         *return_buffer,
279   //                                          void *page_to_free,
280   //                                          uint64_t page_to_free_size);
281 
282   // Where the return_buffer argument points to a 24 byte region of memory
283   // already allocated by lldb in
284   // the inferior process.
285 
286   CompilerType clang_void_ptr_type =
287       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
288   Value return_buffer_ptr_value;
289   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
290   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
291 
292   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
293   Value debug_value;
294   debug_value.SetValueType(Value::eValueTypeScalar);
295   debug_value.SetCompilerType(clang_int_type);
296 
297   Value page_to_free_value;
298   page_to_free_value.SetValueType(Value::eValueTypeScalar);
299   page_to_free_value.SetCompilerType(clang_void_ptr_type);
300 
301   CompilerType clang_uint64_type =
302       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
303   Value page_to_free_size_value;
304   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
305   page_to_free_size_value.SetCompilerType(clang_uint64_type);
306 
307   std::lock_guard<std::mutex> guard(m_get_queues_retbuffer_mutex);
308   if (m_get_queues_return_buffer_addr == LLDB_INVALID_ADDRESS) {
309     addr_t bufaddr = process_sp->AllocateMemory(
310         32, ePermissionsReadable | ePermissionsWritable, error);
311     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
312       if (log)
313         log->Printf("Failed to allocate memory for return buffer for get "
314                     "current queues func call");
315       return return_value;
316     }
317     m_get_queues_return_buffer_addr = bufaddr;
318   }
319 
320   ValueList argument_values;
321 
322   return_buffer_ptr_value.GetScalar() = m_get_queues_return_buffer_addr;
323   argument_values.PushValue(return_buffer_ptr_value);
324 
325   debug_value.GetScalar() = 0;
326   argument_values.PushValue(debug_value);
327 
328   if (page_to_free != LLDB_INVALID_ADDRESS)
329     page_to_free_value.GetScalar() = page_to_free;
330   else
331     page_to_free_value.GetScalar() = 0;
332   argument_values.PushValue(page_to_free_value);
333 
334   page_to_free_size_value.GetScalar() = page_to_free_size;
335   argument_values.PushValue(page_to_free_size_value);
336 
337   addr_t args_addr = SetupGetQueuesFunction(thread, argument_values);
338 
339   if (!m_get_queues_impl_code_up) {
340     error.SetErrorString(
341         "Unable to compile __introspection_dispatch_get_queues.");
342     return return_value;
343   }
344 
345   FunctionCaller *get_queues_caller =
346       m_get_queues_impl_code_up->GetFunctionCaller();
347 
348   if (get_queues_caller == NULL) {
349     error.SetErrorString(
350         "Unable to get caller for call __introspection_dispatch_get_queues");
351     return return_value;
352   }
353 
354   DiagnosticManager diagnostics;
355   ExecutionContext exe_ctx;
356   EvaluateExpressionOptions options;
357   options.SetUnwindOnError(true);
358   options.SetIgnoreBreakpoints(true);
359   options.SetStopOthers(true);
360   options.SetTimeoutUsec(500000);
361   options.SetTryAllThreads(false);
362   thread.CalculateExecutionContext(exe_ctx);
363 
364   ExpressionResults func_call_ret;
365   Value results;
366   func_call_ret = get_queues_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 introspection_get_dispatch_queues(), got "
371                   "ExpressionResults %d, error contains %s",
372                   func_call_ret, error.AsCString(""));
373     error.SetErrorString("Unable to call introspection_get_dispatch_queues() "
374                          "for list of queues");
375     return return_value;
376   }
377 
378   return_value.queues_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
379       m_get_queues_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
380   if (!error.Success() ||
381       return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS) {
382     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
383     return return_value;
384   }
385 
386   return_value.queues_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
387       m_get_queues_return_buffer_addr + 8, 8, 0, error);
388 
389   if (!error.Success()) {
390     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
391     return return_value;
392   }
393 
394   return_value.count = m_process->ReadUnsignedIntegerFromMemory(
395       m_get_queues_return_buffer_addr + 16, 8, 0, error);
396   if (!error.Success()) {
397     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
398     return return_value;
399   }
400 
401   if (log)
402     log->Printf("AppleGetQueuesHandler called "
403                 "__introspection_dispatch_get_queues (page_to_free == "
404                 "0x%" PRIx64 ", size = %" PRId64
405                 "), returned page is at 0x%" PRIx64 ", size %" PRId64
406                 ", count = %" PRId64,
407                 page_to_free, page_to_free_size, return_value.queues_buffer_ptr,
408                 return_value.queues_buffer_size, return_value.count);
409 
410   return return_value;
411 }
412