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