1 //===-- AppleGetQueuesHandler.cpp -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "AppleGetQueuesHandler.h"
14 // Other libraries and framework 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"
32 using namespace lldb_private;
34 const char *AppleGetQueuesHandler::g_get_current_queues_function_name = "__lldb_backtrace_recording_get_current_queues";
35 const char *AppleGetQueuesHandler::g_get_current_queues_function_code = " \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\
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\
54 * libBacktraceRecording defines \n\
57 typedef uint32_t queue_list_scope_t; \n\
58 typedef void *introspection_dispatch_queue_info_t; \n\
60 extern uint64_t __introspection_dispatch_get_queues (queue_list_scope_t scope, \n\
61 introspection_dispatch_queue_info_t *returned_queues_buffer, \n\
62 uint64_t *returned_queues_buffer_size); \n\
63 extern int printf(const char *format, ...); \n\
66 * return type define \n\
69 struct get_current_queues_return_values \n\
71 uint64_t queues_buffer_ptr; /* the address of the queues buffer from libBacktraceRecording */ \n\
72 uint64_t queues_buffer_size; /* the size of the queues buffer from libBacktraceRecording */ \n\
73 uint64_t count; /* the number of queues included in the queues buffer */ \n\
76 void __lldb_backtrace_recording_get_current_queues \n\
77 (struct get_current_queues_return_values *return_buffer, \n\
79 void *page_to_free, \n\
80 uint64_t page_to_free_size) \n\
83 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\
84 if (page_to_free != 0) \n\
86 mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
89 return_buffer->count = __introspection_dispatch_get_queues ( \n\
90 /* QUEUES_WITH_ANY_ITEMS */ 2, \n\
91 (void**)&return_buffer->queues_buffer_ptr, \n\
92 &return_buffer->queues_buffer_size); \n\
94 printf(\"result was count %lld\\n\", return_buffer->count); \n\
99 AppleGetQueuesHandler::AppleGetQueuesHandler(Process *process)
100 : m_process(process),
101 m_get_queues_impl_code_up(),
102 m_get_queues_function_mutex(),
103 m_get_queues_return_buffer_addr(LLDB_INVALID_ADDRESS),
104 m_get_queues_retbuffer_mutex()
108 AppleGetQueuesHandler::~AppleGetQueuesHandler ()
113 AppleGetQueuesHandler::Detach()
116 if (m_process && m_process->IsAlive() && m_get_queues_return_buffer_addr != LLDB_INVALID_ADDRESS)
118 std::unique_lock<std::mutex> lock(m_get_queues_retbuffer_mutex, std::defer_lock);
119 lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
120 m_process->DeallocateMemory(m_get_queues_return_buffer_addr);
124 // Construct a CompilerType for the structure that g_get_current_queues_function_code will return by value
125 // so we can extract the fields after performing the function call.
126 // i.e. we are getting this struct returned to us:
128 // struct get_current_queues_return_values
130 // introspection_dispatch_queue_info_t *queues_buffer;
131 // uint64_t queues_buffer_size;
136 // Compile our __lldb_backtrace_recording_get_current_queues() function (from the
137 // source above in g_get_current_queues_function_code) if we don't find that function in the inferior
138 // already with USE_BUILTIN_FUNCTION defined. (e.g. this would be the case for testing.)
140 // Insert the __lldb_backtrace_recording_get_current_queues into the inferior process if needed.
142 // Write the get_queues_arglist into the inferior's memory space to prepare for the call.
144 // Returns the address of the arguments written down in the inferior process, which can be used to
145 // make the function call.
148 AppleGetQueuesHandler::SetupGetQueuesFunction (Thread &thread, ValueList &get_queues_arglist)
150 ThreadSP thread_sp(thread.shared_from_this());
151 ExecutionContext exe_ctx (thread_sp);
153 Address impl_code_address;
154 DiagnosticManager diagnostics;
155 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
156 lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
158 FunctionCaller *get_queues_caller = nullptr;
160 // Scope for mutex locker:
162 std::lock_guard<std::mutex> guard(m_get_queues_function_mutex);
164 // First stage is to make the ClangUtility to hold our injected function:
166 if (!m_get_queues_impl_code_up.get())
168 if (g_get_current_queues_function_code != NULL)
171 m_get_queues_impl_code_up.reset (exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(g_get_current_queues_function_code,
173 g_get_current_queues_function_name,
178 log->Printf ("Failed to get UtilityFunction for queues introspection: %s.", error.AsCString());
182 if (!m_get_queues_impl_code_up->Install(diagnostics, exe_ctx))
186 log->Printf("Failed to install queues introspection");
187 diagnostics.Dump(log);
189 m_get_queues_impl_code_up.reset();
197 log->Printf("No queues introspection code found.");
198 diagnostics.Dump(log);
200 return LLDB_INVALID_ADDRESS;
204 // Next make the runner function for our implementation utility function.
205 ClangASTContext *clang_ast_context = thread.GetProcess()->GetTarget().GetScratchClangASTContext();
206 CompilerType get_queues_return_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
208 get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller (get_queues_return_type,
215 log->Printf ("Could not get function caller for get-queues function: %s.", error.AsCString());
222 // Now write down the argument values for this particular call. This looks like it might be a race condition
223 // if other threads were calling into here, but actually it isn't because we allocate a new args structure for
224 // this call by passing args_addr = LLDB_INVALID_ADDRESS...
226 if (!get_queues_caller->WriteFunctionArguments(exe_ctx, args_addr, get_queues_arglist, diagnostics))
230 log->Printf("Error writing get-queues function arguments.");
231 diagnostics.Dump(log);
239 AppleGetQueuesHandler::GetQueuesReturnInfo
240 AppleGetQueuesHandler::GetCurrentQueues (Thread &thread, addr_t page_to_free, uint64_t page_to_free_size, Error &error)
242 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
243 ProcessSP process_sp (thread.CalculateProcess());
244 TargetSP target_sp (thread.CalculateTarget());
245 ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
246 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYSTEM_RUNTIME));
248 GetQueuesReturnInfo return_value;
249 return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
250 return_value.queues_buffer_size = 0;
251 return_value.count = 0;
255 if (thread.SafeToCallFunctions() == false)
258 log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
259 error.SetErrorString ("Not safe to call functions on this thread.");
263 // Set up the arguments for a call to
265 // struct get_current_queues_return_values
267 // uint64_t queues_buffer_ptr; /* the address of the queues buffer from libBacktraceRecording */
268 // uint64_t queues_buffer_size; /* the size of the queues buffer from libBacktraceRecording */
269 // uint64_t count; /* the number of queues included in the queues buffer */
273 // __lldb_backtrace_recording_get_current_queues
274 // (struct get_current_queues_return_values *return_buffer,
275 // void *page_to_free,
276 // uint64_t page_to_free_size);
278 // Where the return_buffer argument points to a 24 byte region of memory already allocated by lldb in
279 // the inferior process.
281 CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
282 Value return_buffer_ptr_value;
283 return_buffer_ptr_value.SetValueType (Value::eValueTypeScalar);
284 return_buffer_ptr_value.SetCompilerType (clang_void_ptr_type);
286 CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
288 debug_value.SetValueType (Value::eValueTypeScalar);
289 debug_value.SetCompilerType (clang_int_type);
291 Value page_to_free_value;
292 page_to_free_value.SetValueType (Value::eValueTypeScalar);
293 page_to_free_value.SetCompilerType (clang_void_ptr_type);
295 CompilerType clang_uint64_type = clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
296 Value page_to_free_size_value;
297 page_to_free_size_value.SetValueType (Value::eValueTypeScalar);
298 page_to_free_size_value.SetCompilerType (clang_uint64_type);
300 std::lock_guard<std::mutex> guard(m_get_queues_retbuffer_mutex);
301 if (m_get_queues_return_buffer_addr == LLDB_INVALID_ADDRESS)
303 addr_t bufaddr = process_sp->AllocateMemory (32, ePermissionsReadable | ePermissionsWritable, error);
304 if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS)
307 log->Printf ("Failed to allocate memory for return buffer for get current queues func call");
310 m_get_queues_return_buffer_addr = bufaddr;
313 ValueList argument_values;
315 return_buffer_ptr_value.GetScalar() = m_get_queues_return_buffer_addr;
316 argument_values.PushValue (return_buffer_ptr_value);
318 debug_value.GetScalar() = 0;
319 argument_values.PushValue (debug_value);
321 if (page_to_free != LLDB_INVALID_ADDRESS)
322 page_to_free_value.GetScalar() = page_to_free;
324 page_to_free_value.GetScalar() = 0;
325 argument_values.PushValue (page_to_free_value);
327 page_to_free_size_value.GetScalar() = page_to_free_size;
328 argument_values.PushValue (page_to_free_size_value);
330 addr_t args_addr = SetupGetQueuesFunction (thread, argument_values);
332 if (!m_get_queues_impl_code_up)
334 error.SetErrorString ("Unable to compile __introspection_dispatch_get_queues.");
338 FunctionCaller *get_queues_caller = m_get_queues_impl_code_up->GetFunctionCaller();
340 if (get_queues_caller == NULL)
342 error.SetErrorString ("Unable to get caller for call __introspection_dispatch_get_queues");
346 DiagnosticManager diagnostics;
347 ExecutionContext exe_ctx;
348 EvaluateExpressionOptions options;
349 options.SetUnwindOnError(true);
350 options.SetIgnoreBreakpoints (true);
351 options.SetStopOthers (true);
352 options.SetTimeoutUsec(500000);
353 options.SetTryAllThreads (false);
354 thread.CalculateExecutionContext (exe_ctx);
356 ExpressionResults func_call_ret;
358 func_call_ret = get_queues_caller->ExecuteFunction(exe_ctx, &args_addr, options, diagnostics, results);
359 if (func_call_ret != eExpressionCompleted || !error.Success())
362 log->Printf ("Unable to call introspection_get_dispatch_queues(), got ExpressionResults %d, error contains %s", func_call_ret, error.AsCString(""));
363 error.SetErrorString ("Unable to call introspection_get_dispatch_queues() for list of queues");
367 return_value.queues_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory (m_get_queues_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
368 if (!error.Success() || return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS)
370 return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
374 return_value.queues_buffer_size = m_process->ReadUnsignedIntegerFromMemory (m_get_queues_return_buffer_addr + 8, 8, 0, error);
376 if (!error.Success())
378 return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
382 return_value.count = m_process->ReadUnsignedIntegerFromMemory (m_get_queues_return_buffer_addr + 16, 8, 0, error);
383 if (!error.Success())
385 return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
390 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);