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