1dda28197Spatrick //===-- AppleGetPendingItemsHandler.cpp -----------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "AppleGetPendingItemsHandler.h"
10061da546Spatrick
11dda28197Spatrick #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12061da546Spatrick #include "lldb/Core/Module.h"
13061da546Spatrick #include "lldb/Core/Value.h"
14061da546Spatrick #include "lldb/Expression/DiagnosticManager.h"
15061da546Spatrick #include "lldb/Expression/FunctionCaller.h"
16061da546Spatrick #include "lldb/Expression/UtilityFunction.h"
17061da546Spatrick #include "lldb/Symbol/Symbol.h"
18061da546Spatrick #include "lldb/Target/ExecutionContext.h"
19061da546Spatrick #include "lldb/Target/Process.h"
20061da546Spatrick #include "lldb/Target/Target.h"
21061da546Spatrick #include "lldb/Target/Thread.h"
22061da546Spatrick #include "lldb/Utility/ConstString.h"
23*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
24061da546Spatrick #include "lldb/Utility/Log.h"
25061da546Spatrick #include "lldb/Utility/StreamString.h"
26061da546Spatrick
27061da546Spatrick using namespace lldb;
28061da546Spatrick using namespace lldb_private;
29061da546Spatrick
30061da546Spatrick const char *AppleGetPendingItemsHandler::g_get_pending_items_function_name =
31061da546Spatrick "__lldb_backtrace_recording_get_pending_items";
32061da546Spatrick const char *AppleGetPendingItemsHandler::g_get_pending_items_function_code =
33061da546Spatrick " \n\
34061da546Spatrick extern \"C\" \n\
35061da546Spatrick { \n\
36061da546Spatrick /* \n\
37061da546Spatrick * mach defines \n\
38061da546Spatrick */ \n\
39061da546Spatrick \n\
40061da546Spatrick typedef unsigned int uint32_t; \n\
41061da546Spatrick typedef unsigned long long uint64_t; \n\
42061da546Spatrick typedef uint32_t mach_port_t; \n\
43061da546Spatrick typedef mach_port_t vm_map_t; \n\
44061da546Spatrick typedef int kern_return_t; \n\
45061da546Spatrick typedef uint64_t mach_vm_address_t; \n\
46061da546Spatrick typedef uint64_t mach_vm_size_t; \n\
47061da546Spatrick \n\
48061da546Spatrick mach_port_t mach_task_self (); \n\
49061da546Spatrick kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size); \n\
50061da546Spatrick \n\
51061da546Spatrick /* \n\
52061da546Spatrick * libBacktraceRecording defines \n\
53061da546Spatrick */ \n\
54061da546Spatrick \n\
55061da546Spatrick typedef uint32_t queue_list_scope_t; \n\
56061da546Spatrick typedef void *dispatch_queue_t; \n\
57061da546Spatrick typedef void *introspection_dispatch_queue_info_t; \n\
58061da546Spatrick typedef void *introspection_dispatch_item_info_ref; \n\
59061da546Spatrick \n\
60061da546Spatrick extern uint64_t __introspection_dispatch_queue_get_pending_items (dispatch_queue_t queue, \n\
61061da546Spatrick introspection_dispatch_item_info_ref *returned_queues_buffer, \n\
62061da546Spatrick uint64_t *returned_queues_buffer_size); \n\
63061da546Spatrick extern int printf(const char *format, ...); \n\
64061da546Spatrick \n\
65061da546Spatrick /* \n\
66061da546Spatrick * return type define \n\
67061da546Spatrick */ \n\
68061da546Spatrick \n\
69061da546Spatrick struct get_pending_items_return_values \n\
70061da546Spatrick { \n\
71061da546Spatrick uint64_t pending_items_buffer_ptr; /* the address of the items buffer from libBacktraceRecording */ \n\
72061da546Spatrick uint64_t pending_items_buffer_size; /* the size of the items buffer from libBacktraceRecording */ \n\
73061da546Spatrick uint64_t count; /* the number of items included in the queues buffer */ \n\
74061da546Spatrick }; \n\
75061da546Spatrick \n\
76061da546Spatrick void __lldb_backtrace_recording_get_pending_items \n\
77061da546Spatrick (struct get_pending_items_return_values *return_buffer, \n\
78061da546Spatrick int debug, \n\
79061da546Spatrick uint64_t /* dispatch_queue_t */ queue, \n\
80061da546Spatrick void *page_to_free, \n\
81061da546Spatrick uint64_t page_to_free_size) \n\
82061da546Spatrick { \n\
83061da546Spatrick if (debug) \n\
84061da546Spatrick printf (\"entering get_pending_items with args return_buffer == %p, debug == %d, queue == 0x%llx, page_to_free == %p, page_to_free_size == 0x%llx\\n\", return_buffer, debug, queue, page_to_free, page_to_free_size); \n\
85061da546Spatrick if (page_to_free != 0) \n\
86061da546Spatrick { \n\
87061da546Spatrick mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
88061da546Spatrick } \n\
89061da546Spatrick \n\
90061da546Spatrick return_buffer->count = __introspection_dispatch_queue_get_pending_items ( \n\
91061da546Spatrick (void*) queue, \n\
92061da546Spatrick (void**)&return_buffer->pending_items_buffer_ptr, \n\
93061da546Spatrick &return_buffer->pending_items_buffer_size); \n\
94061da546Spatrick if (debug) \n\
95061da546Spatrick printf(\"result was count %lld\\n\", return_buffer->count); \n\
96061da546Spatrick } \n\
97061da546Spatrick } \n\
98061da546Spatrick ";
99061da546Spatrick
AppleGetPendingItemsHandler(Process * process)100061da546Spatrick AppleGetPendingItemsHandler::AppleGetPendingItemsHandler(Process *process)
101061da546Spatrick : m_process(process), m_get_pending_items_impl_code(),
102061da546Spatrick m_get_pending_items_function_mutex(),
103061da546Spatrick m_get_pending_items_return_buffer_addr(LLDB_INVALID_ADDRESS),
104061da546Spatrick m_get_pending_items_retbuffer_mutex() {}
105061da546Spatrick
106be691f3bSpatrick AppleGetPendingItemsHandler::~AppleGetPendingItemsHandler() = default;
107061da546Spatrick
Detach()108061da546Spatrick void AppleGetPendingItemsHandler::Detach() {
109061da546Spatrick if (m_process && m_process->IsAlive() &&
110061da546Spatrick m_get_pending_items_return_buffer_addr != LLDB_INVALID_ADDRESS) {
111061da546Spatrick std::unique_lock<std::mutex> lock(m_get_pending_items_retbuffer_mutex,
112061da546Spatrick std::defer_lock);
113dda28197Spatrick (void)lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
114061da546Spatrick m_process->DeallocateMemory(m_get_pending_items_return_buffer_addr);
115061da546Spatrick }
116061da546Spatrick }
117061da546Spatrick
118061da546Spatrick // Compile our __lldb_backtrace_recording_get_pending_items() function (from
119061da546Spatrick // the source above in g_get_pending_items_function_code) if we don't find that
120061da546Spatrick // function in the inferior already with USE_BUILTIN_FUNCTION defined. (e.g.
121061da546Spatrick // this would be the case for testing.)
122061da546Spatrick //
123061da546Spatrick // Insert the __lldb_backtrace_recording_get_pending_items into the inferior
124061da546Spatrick // process if needed.
125061da546Spatrick //
126061da546Spatrick // Write the get_pending_items_arglist into the inferior's memory space to
127061da546Spatrick // prepare for the call.
128061da546Spatrick //
129061da546Spatrick // Returns the address of the arguments written down in the inferior process,
130061da546Spatrick // which can be used to make the function call.
131061da546Spatrick
SetupGetPendingItemsFunction(Thread & thread,ValueList & get_pending_items_arglist)132061da546Spatrick lldb::addr_t AppleGetPendingItemsHandler::SetupGetPendingItemsFunction(
133061da546Spatrick Thread &thread, ValueList &get_pending_items_arglist) {
134061da546Spatrick ThreadSP thread_sp(thread.shared_from_this());
135061da546Spatrick ExecutionContext exe_ctx(thread_sp);
136061da546Spatrick DiagnosticManager diagnostics;
137*f6aab3d8Srobert Log *log = GetLog(LLDBLog::SystemRuntime);
138061da546Spatrick
139061da546Spatrick lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
140061da546Spatrick FunctionCaller *get_pending_items_caller = nullptr;
141061da546Spatrick
142061da546Spatrick // Scope for mutex locker:
143061da546Spatrick {
144061da546Spatrick std::lock_guard<std::mutex> guard(m_get_pending_items_function_mutex);
145061da546Spatrick
146061da546Spatrick // First stage is to make the ClangUtility to hold our injected function:
147061da546Spatrick
148061da546Spatrick if (!m_get_pending_items_impl_code) {
149061da546Spatrick if (g_get_pending_items_function_code != nullptr) {
150be691f3bSpatrick auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
151be691f3bSpatrick g_get_pending_items_function_code,
152be691f3bSpatrick g_get_pending_items_function_name, eLanguageTypeC, exe_ctx);
153be691f3bSpatrick if (!utility_fn_or_error) {
154be691f3bSpatrick LLDB_LOG_ERROR(log, utility_fn_or_error.takeError(),
155be691f3bSpatrick "Failed to create UtilityFunction for pending-items "
156be691f3bSpatrick "introspection: {0}.");
157061da546Spatrick return args_addr;
158061da546Spatrick }
159be691f3bSpatrick m_get_pending_items_impl_code = std::move(*utility_fn_or_error);
160061da546Spatrick } else {
161061da546Spatrick LLDB_LOGF(log, "No pending-items introspection code found.");
162061da546Spatrick return LLDB_INVALID_ADDRESS;
163061da546Spatrick }
164061da546Spatrick
165061da546Spatrick // Next make the runner function for our implementation utility function.
166061da546Spatrick Status error;
167*f6aab3d8Srobert TypeSystemClangSP scratch_ts_sp = ScratchTypeSystemClang::GetForTarget(
168be691f3bSpatrick thread.GetProcess()->GetTarget());
169061da546Spatrick CompilerType get_pending_items_return_type =
170*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
171061da546Spatrick get_pending_items_caller =
172061da546Spatrick m_get_pending_items_impl_code->MakeFunctionCaller(
173061da546Spatrick get_pending_items_return_type, get_pending_items_arglist,
174061da546Spatrick thread_sp, error);
175061da546Spatrick if (error.Fail() || get_pending_items_caller == nullptr) {
176061da546Spatrick LLDB_LOGF(log,
177061da546Spatrick "Failed to install pending-items introspection function "
178061da546Spatrick "caller: %s.",
179061da546Spatrick error.AsCString());
180061da546Spatrick m_get_pending_items_impl_code.reset();
181061da546Spatrick return args_addr;
182061da546Spatrick }
183061da546Spatrick }
184061da546Spatrick }
185061da546Spatrick
186061da546Spatrick diagnostics.Clear();
187061da546Spatrick
188061da546Spatrick if (get_pending_items_caller == nullptr) {
189061da546Spatrick LLDB_LOGF(log, "Failed to get get_pending_items_caller.");
190061da546Spatrick return LLDB_INVALID_ADDRESS;
191061da546Spatrick }
192061da546Spatrick
193061da546Spatrick // Now write down the argument values for this particular call. This looks
194061da546Spatrick // like it might be a race condition if other threads were calling into here,
195061da546Spatrick // but actually it isn't because we allocate a new args structure for this
196061da546Spatrick // call by passing args_addr = LLDB_INVALID_ADDRESS...
197061da546Spatrick
198061da546Spatrick if (!get_pending_items_caller->WriteFunctionArguments(
199061da546Spatrick exe_ctx, args_addr, get_pending_items_arglist, diagnostics)) {
200061da546Spatrick if (log) {
201061da546Spatrick LLDB_LOGF(log, "Error writing pending-items function arguments.");
202061da546Spatrick diagnostics.Dump(log);
203061da546Spatrick }
204061da546Spatrick
205061da546Spatrick return args_addr;
206061da546Spatrick }
207061da546Spatrick
208061da546Spatrick return args_addr;
209061da546Spatrick }
210061da546Spatrick
211061da546Spatrick AppleGetPendingItemsHandler::GetPendingItemsReturnInfo
GetPendingItems(Thread & thread,addr_t queue,addr_t page_to_free,uint64_t page_to_free_size,Status & error)212061da546Spatrick AppleGetPendingItemsHandler::GetPendingItems(Thread &thread, addr_t queue,
213061da546Spatrick addr_t page_to_free,
214061da546Spatrick uint64_t page_to_free_size,
215061da546Spatrick Status &error) {
216061da546Spatrick lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
217061da546Spatrick ProcessSP process_sp(thread.CalculateProcess());
218061da546Spatrick TargetSP target_sp(thread.CalculateTarget());
219*f6aab3d8Srobert TypeSystemClangSP scratch_ts_sp =
220be691f3bSpatrick ScratchTypeSystemClang::GetForTarget(*target_sp);
221*f6aab3d8Srobert Log *log = GetLog(LLDBLog::SystemRuntime);
222061da546Spatrick
223061da546Spatrick GetPendingItemsReturnInfo return_value;
224061da546Spatrick return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
225061da546Spatrick return_value.items_buffer_size = 0;
226061da546Spatrick return_value.count = 0;
227061da546Spatrick
228061da546Spatrick error.Clear();
229061da546Spatrick
230061da546Spatrick if (!thread.SafeToCallFunctions()) {
231061da546Spatrick LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
232061da546Spatrick thread.GetID());
233061da546Spatrick error.SetErrorString("Not safe to call functions on this thread.");
234061da546Spatrick return return_value;
235061da546Spatrick }
236061da546Spatrick
237061da546Spatrick // Set up the arguments for a call to
238061da546Spatrick
239061da546Spatrick // struct get_pending_items_return_values
240061da546Spatrick // {
241061da546Spatrick // uint64_t pending_items_buffer_ptr; /* the address of the items
242061da546Spatrick // buffer from libBacktraceRecording */
243061da546Spatrick // uint64_t pending_items_buffer_size; /* the size of the items buffer
244061da546Spatrick // from libBacktraceRecording */
245061da546Spatrick // uint64_t count; /* the number of items included in the
246061da546Spatrick // queues buffer */
247061da546Spatrick // };
248061da546Spatrick //
249061da546Spatrick // void __lldb_backtrace_recording_get_pending_items
250061da546Spatrick // (struct
251061da546Spatrick // get_pending_items_return_values
252061da546Spatrick // *return_buffer,
253061da546Spatrick // int debug,
254061da546Spatrick // uint64_t /* dispatch_queue_t */
255061da546Spatrick // queue
256061da546Spatrick // void *page_to_free,
257061da546Spatrick // uint64_t page_to_free_size)
258061da546Spatrick
259061da546Spatrick // Where the return_buffer argument points to a 24 byte region of memory
260061da546Spatrick // already allocated by lldb in the inferior process.
261061da546Spatrick
262061da546Spatrick CompilerType clang_void_ptr_type =
263*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
264061da546Spatrick Value return_buffer_ptr_value;
265be691f3bSpatrick return_buffer_ptr_value.SetValueType(Value::ValueType::Scalar);
266061da546Spatrick return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
267061da546Spatrick
268*f6aab3d8Srobert CompilerType clang_int_type = scratch_ts_sp->GetBasicType(eBasicTypeInt);
269061da546Spatrick Value debug_value;
270be691f3bSpatrick debug_value.SetValueType(Value::ValueType::Scalar);
271061da546Spatrick debug_value.SetCompilerType(clang_int_type);
272061da546Spatrick
273061da546Spatrick CompilerType clang_uint64_type =
274*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeUnsignedLongLong);
275061da546Spatrick Value queue_value;
276be691f3bSpatrick queue_value.SetValueType(Value::ValueType::Scalar);
277061da546Spatrick queue_value.SetCompilerType(clang_uint64_type);
278061da546Spatrick
279061da546Spatrick Value page_to_free_value;
280be691f3bSpatrick page_to_free_value.SetValueType(Value::ValueType::Scalar);
281061da546Spatrick page_to_free_value.SetCompilerType(clang_void_ptr_type);
282061da546Spatrick
283061da546Spatrick Value page_to_free_size_value;
284be691f3bSpatrick page_to_free_size_value.SetValueType(Value::ValueType::Scalar);
285061da546Spatrick page_to_free_size_value.SetCompilerType(clang_uint64_type);
286061da546Spatrick
287061da546Spatrick std::lock_guard<std::mutex> guard(m_get_pending_items_retbuffer_mutex);
288061da546Spatrick if (m_get_pending_items_return_buffer_addr == LLDB_INVALID_ADDRESS) {
289061da546Spatrick addr_t bufaddr = process_sp->AllocateMemory(
290061da546Spatrick 32, ePermissionsReadable | ePermissionsWritable, error);
291061da546Spatrick if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
292061da546Spatrick LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
293061da546Spatrick "current queues func call");
294061da546Spatrick return return_value;
295061da546Spatrick }
296061da546Spatrick m_get_pending_items_return_buffer_addr = bufaddr;
297061da546Spatrick }
298061da546Spatrick
299061da546Spatrick ValueList argument_values;
300061da546Spatrick
301061da546Spatrick return_buffer_ptr_value.GetScalar() = m_get_pending_items_return_buffer_addr;
302061da546Spatrick argument_values.PushValue(return_buffer_ptr_value);
303061da546Spatrick
304061da546Spatrick debug_value.GetScalar() = 0;
305061da546Spatrick argument_values.PushValue(debug_value);
306061da546Spatrick
307061da546Spatrick queue_value.GetScalar() = queue;
308061da546Spatrick argument_values.PushValue(queue_value);
309061da546Spatrick
310061da546Spatrick if (page_to_free != LLDB_INVALID_ADDRESS)
311061da546Spatrick page_to_free_value.GetScalar() = page_to_free;
312061da546Spatrick else
313061da546Spatrick page_to_free_value.GetScalar() = 0;
314061da546Spatrick argument_values.PushValue(page_to_free_value);
315061da546Spatrick
316061da546Spatrick page_to_free_size_value.GetScalar() = page_to_free_size;
317061da546Spatrick argument_values.PushValue(page_to_free_size_value);
318061da546Spatrick
319061da546Spatrick addr_t args_addr = SetupGetPendingItemsFunction(thread, argument_values);
320061da546Spatrick
321061da546Spatrick DiagnosticManager diagnostics;
322061da546Spatrick ExecutionContext exe_ctx;
323061da546Spatrick FunctionCaller *get_pending_items_caller =
324061da546Spatrick m_get_pending_items_impl_code->GetFunctionCaller();
325061da546Spatrick
326061da546Spatrick EvaluateExpressionOptions options;
327061da546Spatrick options.SetUnwindOnError(true);
328061da546Spatrick options.SetIgnoreBreakpoints(true);
329061da546Spatrick options.SetStopOthers(true);
330061da546Spatrick #if __has_feature(address_sanitizer)
331061da546Spatrick options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
332061da546Spatrick #else
333061da546Spatrick options.SetTimeout(std::chrono::milliseconds(500));
334061da546Spatrick #endif
335061da546Spatrick options.SetTryAllThreads(false);
336061da546Spatrick options.SetIsForUtilityExpr(true);
337061da546Spatrick thread.CalculateExecutionContext(exe_ctx);
338061da546Spatrick
339061da546Spatrick if (get_pending_items_caller == nullptr) {
340061da546Spatrick error.SetErrorString("Unable to compile function to call "
341061da546Spatrick "__introspection_dispatch_queue_get_pending_items");
342061da546Spatrick return return_value;
343061da546Spatrick }
344061da546Spatrick
345061da546Spatrick ExpressionResults func_call_ret;
346061da546Spatrick Value results;
347061da546Spatrick func_call_ret = get_pending_items_caller->ExecuteFunction(
348061da546Spatrick exe_ctx, &args_addr, options, diagnostics, results);
349061da546Spatrick if (func_call_ret != eExpressionCompleted || !error.Success()) {
350061da546Spatrick LLDB_LOGF(log,
351061da546Spatrick "Unable to call "
352061da546Spatrick "__introspection_dispatch_queue_get_pending_items(), got "
353061da546Spatrick "ExpressionResults %d, error contains %s",
354061da546Spatrick func_call_ret, error.AsCString(""));
355061da546Spatrick error.SetErrorString("Unable to call "
356061da546Spatrick "__introspection_dispatch_queue_get_pending_items() "
357061da546Spatrick "for list of queues");
358061da546Spatrick return return_value;
359061da546Spatrick }
360061da546Spatrick
361061da546Spatrick return_value.items_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
362061da546Spatrick m_get_pending_items_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
363061da546Spatrick if (!error.Success() ||
364061da546Spatrick return_value.items_buffer_ptr == LLDB_INVALID_ADDRESS) {
365061da546Spatrick return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
366061da546Spatrick return return_value;
367061da546Spatrick }
368061da546Spatrick
369061da546Spatrick return_value.items_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
370061da546Spatrick m_get_pending_items_return_buffer_addr + 8, 8, 0, error);
371061da546Spatrick
372061da546Spatrick if (!error.Success()) {
373061da546Spatrick return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
374061da546Spatrick return return_value;
375061da546Spatrick }
376061da546Spatrick
377061da546Spatrick return_value.count = m_process->ReadUnsignedIntegerFromMemory(
378061da546Spatrick m_get_pending_items_return_buffer_addr + 16, 8, 0, error);
379061da546Spatrick if (!error.Success()) {
380061da546Spatrick return_value.items_buffer_ptr = LLDB_INVALID_ADDRESS;
381061da546Spatrick return return_value;
382061da546Spatrick }
383061da546Spatrick
384061da546Spatrick LLDB_LOGF(log,
385061da546Spatrick "AppleGetPendingItemsHandler called "
386061da546Spatrick "__introspection_dispatch_queue_get_pending_items "
387061da546Spatrick "(page_to_free == 0x%" PRIx64 ", size = %" PRId64
388061da546Spatrick "), returned page is at 0x%" PRIx64 ", size %" PRId64
389061da546Spatrick ", count = %" PRId64,
390061da546Spatrick page_to_free, page_to_free_size, return_value.items_buffer_ptr,
391061da546Spatrick return_value.items_buffer_size, return_value.count);
392061da546Spatrick
393061da546Spatrick return return_value;
394061da546Spatrick }
395