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/Module.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Expression/DiagnosticManager.h"
19 #include "lldb/Expression/FunctionCaller.h"
20 #include "lldb/Expression/UtilityFunction.h"
21 #include "lldb/Symbol/ClangASTContext.h"
22 #include "lldb/Symbol/Symbol.h"
23 #include "lldb/Target/ExecutionContext.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Utility/ConstString.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/StreamString.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 so we can extract
122 // the fields after performing the function call. i.e. we are getting this
123 // 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 source above in g_get_current_queues_function_code) if we don't find
134 // that function in the inferior already with USE_BUILTIN_FUNCTION defined.
135 // (e.g. this would be the case for testing.)
136 //
137 // Insert the __lldb_backtrace_recording_get_current_queues into the inferior
138 // process if needed.
139 //
140 // Write the get_queues_arglist into the inferior's memory space to prepare for
141 // the call.
142 //
143 // Returns the address of the arguments written down in the inferior process,
144 // which can be used to make the function call.
145 
146 lldb::addr_t
147 AppleGetQueuesHandler::SetupGetQueuesFunction(Thread &thread,
148                                               ValueList &get_queues_arglist) {
149   ThreadSP thread_sp(thread.shared_from_this());
150   ExecutionContext exe_ctx(thread_sp);
151 
152   Address impl_code_address;
153   DiagnosticManager diagnostics;
154   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
155   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
156 
157   FunctionCaller *get_queues_caller = nullptr;
158 
159   // Scope for mutex locker:
160   {
161     std::lock_guard<std::mutex> guard(m_get_queues_function_mutex);
162 
163     // First stage is to make the ClangUtility to hold our injected function:
164 
165     if (!m_get_queues_impl_code_up.get()) {
166       if (g_get_current_queues_function_code != NULL) {
167         Status error;
168         m_get_queues_impl_code_up.reset(
169             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
170                 g_get_current_queues_function_code, eLanguageTypeC,
171                 g_get_current_queues_function_name, error));
172         if (error.Fail()) {
173           if (log)
174             log->Printf(
175                 "Failed to get UtilityFunction for queues introspection: %s.",
176                 error.AsCString());
177           return args_addr;
178         }
179 
180         if (!m_get_queues_impl_code_up->Install(diagnostics, exe_ctx)) {
181           if (log) {
182             log->Printf("Failed to install queues introspection");
183             diagnostics.Dump(log);
184           }
185           m_get_queues_impl_code_up.reset();
186           return args_addr;
187         }
188       } else {
189         if (log) {
190           log->Printf("No queues introspection code found.");
191           diagnostics.Dump(log);
192         }
193         return LLDB_INVALID_ADDRESS;
194       }
195     }
196 
197     // Next make the runner function for our implementation utility function.
198     ClangASTContext *clang_ast_context =
199         thread.GetProcess()->GetTarget().GetScratchClangASTContext();
200     CompilerType get_queues_return_type =
201         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
202     Status error;
203     get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller(
204         get_queues_return_type, get_queues_arglist, thread_sp, error);
205     if (error.Fail() || get_queues_caller == nullptr) {
206       if (log)
207         log->Printf(
208             "Could not get function caller for get-queues function: %s.",
209             error.AsCString());
210       return args_addr;
211     }
212   }
213 
214   diagnostics.Clear();
215 
216   // Now write down the argument values for this particular call.  This looks
217   // like it might be a race condition if other threads were calling into here,
218   // but actually it isn't because we allocate a new args structure for this
219   // call by passing args_addr = LLDB_INVALID_ADDRESS...
220 
221   if (!get_queues_caller->WriteFunctionArguments(
222           exe_ctx, args_addr, get_queues_arglist, diagnostics)) {
223     if (log) {
224       log->Printf("Error writing get-queues function arguments.");
225       diagnostics.Dump(log);
226     }
227     return args_addr;
228   }
229 
230   return args_addr;
231 }
232 
233 AppleGetQueuesHandler::GetQueuesReturnInfo
234 AppleGetQueuesHandler::GetCurrentQueues(Thread &thread, addr_t page_to_free,
235                                         uint64_t page_to_free_size,
236                                         Status &error) {
237   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
238   ProcessSP process_sp(thread.CalculateProcess());
239   TargetSP target_sp(thread.CalculateTarget());
240   ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
241   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
242 
243   GetQueuesReturnInfo return_value;
244   return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
245   return_value.queues_buffer_size = 0;
246   return_value.count = 0;
247 
248   error.Clear();
249 
250   if (thread.SafeToCallFunctions() == false) {
251     if (log)
252       log->Printf("Not safe to call functions on thread 0x%" PRIx64,
253                   thread.GetID());
254     error.SetErrorString("Not safe to call functions on this thread.");
255     return return_value;
256   }
257 
258   // Set up the arguments for a call to
259 
260   // struct get_current_queues_return_values
261   // {
262   //    uint64_t queues_buffer_ptr;    /* the address of the queues buffer from
263   //    libBacktraceRecording */
264   //    uint64_t queues_buffer_size;   /* the size of the queues buffer from
265   //    libBacktraceRecording */
266   //    uint64_t count;                /* the number of queues included in the
267   //    queues buffer */
268   // };
269   //
270   //  void
271   //    __lldb_backtrace_recording_get_current_queues
272   //                                         (struct
273   //                                         get_current_queues_return_values
274   //                                         *return_buffer,
275   //                                          void *page_to_free,
276   //                                          uint64_t page_to_free_size);
277 
278   // Where the return_buffer argument points to a 24 byte region of memory
279   // already allocated by lldb in the inferior process.
280 
281   CompilerType clang_void_ptr_type =
282       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
283   Value return_buffer_ptr_value;
284   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
285   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
286 
287   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
288   Value debug_value;
289   debug_value.SetValueType(Value::eValueTypeScalar);
290   debug_value.SetCompilerType(clang_int_type);
291 
292   Value page_to_free_value;
293   page_to_free_value.SetValueType(Value::eValueTypeScalar);
294   page_to_free_value.SetCompilerType(clang_void_ptr_type);
295 
296   CompilerType clang_uint64_type =
297       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
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_queues_retbuffer_mutex);
303   if (m_get_queues_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_queues_return_buffer_addr = bufaddr;
313   }
314 
315   ValueList argument_values;
316 
317   return_buffer_ptr_value.GetScalar() = m_get_queues_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   if (page_to_free != LLDB_INVALID_ADDRESS)
324     page_to_free_value.GetScalar() = page_to_free;
325   else
326     page_to_free_value.GetScalar() = 0;
327   argument_values.PushValue(page_to_free_value);
328 
329   page_to_free_size_value.GetScalar() = page_to_free_size;
330   argument_values.PushValue(page_to_free_size_value);
331 
332   addr_t args_addr = SetupGetQueuesFunction(thread, argument_values);
333 
334   if (!m_get_queues_impl_code_up) {
335     error.SetErrorString(
336         "Unable to compile __introspection_dispatch_get_queues.");
337     return return_value;
338   }
339 
340   FunctionCaller *get_queues_caller =
341       m_get_queues_impl_code_up->GetFunctionCaller();
342 
343   if (get_queues_caller == NULL) {
344     error.SetErrorString(
345         "Unable to get caller for call __introspection_dispatch_get_queues");
346     return return_value;
347   }
348 
349   DiagnosticManager diagnostics;
350   ExecutionContext exe_ctx;
351   EvaluateExpressionOptions options;
352   options.SetUnwindOnError(true);
353   options.SetIgnoreBreakpoints(true);
354   options.SetStopOthers(true);
355   options.SetTimeout(std::chrono::milliseconds(500));
356   options.SetTryAllThreads(false);
357   options.SetIsForUtilityExpr(true);
358   thread.CalculateExecutionContext(exe_ctx);
359 
360   ExpressionResults func_call_ret;
361   Value results;
362   func_call_ret = get_queues_caller->ExecuteFunction(
363       exe_ctx, &args_addr, options, diagnostics, results);
364   if (func_call_ret != eExpressionCompleted || !error.Success()) {
365     if (log)
366       log->Printf("Unable to call introspection_get_dispatch_queues(), got "
367                   "ExpressionResults %d, error contains %s",
368                   func_call_ret, error.AsCString(""));
369     error.SetErrorString("Unable to call introspection_get_dispatch_queues() "
370                          "for list of queues");
371     return return_value;
372   }
373 
374   return_value.queues_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
375       m_get_queues_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
376   if (!error.Success() ||
377       return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS) {
378     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
379     return return_value;
380   }
381 
382   return_value.queues_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
383       m_get_queues_return_buffer_addr + 8, 8, 0, error);
384 
385   if (!error.Success()) {
386     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
387     return return_value;
388   }
389 
390   return_value.count = m_process->ReadUnsignedIntegerFromMemory(
391       m_get_queues_return_buffer_addr + 16, 8, 0, error);
392   if (!error.Success()) {
393     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
394     return return_value;
395   }
396 
397   if (log)
398     log->Printf("AppleGetQueuesHandler called "
399                 "__introspection_dispatch_get_queues (page_to_free == "
400                 "0x%" PRIx64 ", size = %" PRId64
401                 "), returned page is at 0x%" PRIx64 ", size %" PRId64
402                 ", count = %" PRId64,
403                 page_to_free, page_to_free_size, return_value.queues_buffer_ptr,
404                 return_value.queues_buffer_size, return_value.count);
405 
406   return return_value;
407 }
408