LLDB mainline
AppleGetQueuesHandler.cpp
Go to the documentation of this file.
1//===-- AppleGetQueuesHandler.cpp -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
12#include "lldb/Core/Module.h"
13#include "lldb/Core/Value.h"
17#include "lldb/Symbol/Symbol.h"
19#include "lldb/Target/Process.h"
20#include "lldb/Target/Target.h"
21#include "lldb/Target/Thread.h"
24#include "lldb/Utility/Log.h"
26
27using namespace lldb;
28using namespace lldb_private;
29
31 "__lldb_backtrace_recording_get_current_queues";
33 " \n\
34extern \"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
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
104
106
107 if (m_process && m_process->IsAlive() &&
109 std::unique_lock<std::mutex> lock(m_get_queues_retbuffer_mutex,
110 std::defer_lock);
111 (void)lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
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
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;
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
162 if (g_get_current_queues_function_code != nullptr) {
163 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
166 if (!utility_fn_or_error) {
167 LLDB_LOG_ERROR(log, utility_fn_or_error.takeError(),
168 "Failed to create UtilityFunction for queues "
169 "introspection: {0}.");
170 return args_addr;
171 }
172 m_get_queues_impl_code_up = std::move(*utility_fn_or_error);
173 } else {
174 if (log) {
175 LLDB_LOGF(log, "No queues introspection code found.");
176 diagnostics.Dump(log);
177 }
179 }
180 }
181
182 // Next make the runner function for our implementation utility function.
183 TypeSystemClangSP scratch_ts_sp =
185 CompilerType get_queues_return_type =
186 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
188 get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller(
189 get_queues_return_type, get_queues_arglist, thread_sp, error);
190 if (error.Fail() || get_queues_caller == nullptr) {
191 LLDB_LOGF(log,
192 "Could not get function caller for get-queues function: %s.",
193 error.AsCString());
194 return args_addr;
195 }
196 }
197
198 diagnostics.Clear();
199
200 // Now write down the argument values for this particular call. This looks
201 // like it might be a race condition if other threads were calling into here,
202 // but actually it isn't because we allocate a new args structure for this
203 // call by passing args_addr = LLDB_INVALID_ADDRESS...
204
205 if (!get_queues_caller->WriteFunctionArguments(
206 exe_ctx, args_addr, get_queues_arglist, diagnostics)) {
207 if (log) {
208 LLDB_LOGF(log, "Error writing get-queues function arguments.");
209 diagnostics.Dump(log);
210 }
211 return args_addr;
212 }
213
214 return args_addr;
215}
216
219 uint64_t page_to_free_size,
220 Status &error) {
221 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
222 ProcessSP process_sp(thread.CalculateProcess());
223 TargetSP target_sp(thread.CalculateTarget());
224 TypeSystemClangSP scratch_ts_sp =
227
228 GetQueuesReturnInfo return_value;
230 return_value.queues_buffer_size = 0;
231 return_value.count = 0;
232
233 error.Clear();
234
235 if (!thread.SafeToCallFunctions()) {
236 LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
237 thread.GetID());
238 error =
239 Status::FromErrorString("Not safe to call functions on this thread.");
240 return return_value;
241 }
242
243 // Set up the arguments for a call to
244
245 // struct get_current_queues_return_values
246 // {
247 // uint64_t queues_buffer_ptr; /* the address of the queues buffer from
248 // libBacktraceRecording */
249 // uint64_t queues_buffer_size; /* the size of the queues buffer from
250 // libBacktraceRecording */
251 // uint64_t count; /* the number of queues included in the
252 // queues buffer */
253 // };
254 //
255 // void
256 // __lldb_backtrace_recording_get_current_queues
257 // (struct
258 // get_current_queues_return_values
259 // *return_buffer,
260 // void *page_to_free,
261 // uint64_t page_to_free_size);
262
263 // Where the return_buffer argument points to a 24 byte region of memory
264 // already allocated by lldb in the inferior process.
265
266 CompilerType clang_void_ptr_type =
267 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
268 Value return_buffer_ptr_value;
269 return_buffer_ptr_value.SetValueType(Value::ValueType::Scalar);
270 return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
271
272 CompilerType clang_int_type = scratch_ts_sp->GetBasicType(eBasicTypeInt);
273 Value debug_value;
275 debug_value.SetCompilerType(clang_int_type);
276
277 Value page_to_free_value;
278 page_to_free_value.SetValueType(Value::ValueType::Scalar);
279 page_to_free_value.SetCompilerType(clang_void_ptr_type);
280
281 CompilerType clang_uint64_type =
282 scratch_ts_sp->GetBasicType(eBasicTypeUnsignedLongLong);
283 Value page_to_free_size_value;
284 page_to_free_size_value.SetValueType(Value::ValueType::Scalar);
285 page_to_free_size_value.SetCompilerType(clang_uint64_type);
286
287 std::lock_guard<std::mutex> guard(m_get_queues_retbuffer_mutex);
289 addr_t bufaddr = process_sp->AllocateMemory(
290 32, ePermissionsReadable | ePermissionsWritable, error);
291 if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
292 LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
293 "current queues func call");
294 return return_value;
295 }
297 }
298
299 ValueList argument_values;
300
301 return_buffer_ptr_value.GetScalar() = m_get_queues_return_buffer_addr;
302 argument_values.PushValue(return_buffer_ptr_value);
303
304 debug_value.GetScalar() = 0;
305 argument_values.PushValue(debug_value);
306
307 if (page_to_free != LLDB_INVALID_ADDRESS)
308 page_to_free_value.GetScalar() = page_to_free;
309 else
310 page_to_free_value.GetScalar() = 0;
311 argument_values.PushValue(page_to_free_value);
312
313 page_to_free_size_value.GetScalar() = page_to_free_size;
314 argument_values.PushValue(page_to_free_size_value);
315
316 addr_t args_addr = SetupGetQueuesFunction(thread, argument_values);
317
320 "Unable to compile __introspection_dispatch_get_queues.");
321 return return_value;
322 }
323
324 FunctionCaller *get_queues_caller =
325 m_get_queues_impl_code_up->GetFunctionCaller();
326
327 if (get_queues_caller == nullptr) {
329 "Unable to get caller for call __introspection_dispatch_get_queues");
330 return return_value;
331 }
332
333 DiagnosticManager diagnostics;
334 ExecutionContext exe_ctx;
336 options.SetUnwindOnError(true);
337 options.SetIgnoreBreakpoints(true);
338 options.SetStopOthers(true);
339#if __has_feature(address_sanitizer)
340 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
341#else
342 options.SetTimeout(std::chrono::milliseconds(500));
343#endif
344 options.SetTryAllThreads(false);
345 options.SetIsForUtilityExpr(true);
346 thread.CalculateExecutionContext(exe_ctx);
347
348 ExpressionResults func_call_ret;
349 Value results;
350 func_call_ret = get_queues_caller->ExecuteFunction(
351 exe_ctx, &args_addr, options, diagnostics, results);
352 if (func_call_ret != eExpressionCompleted || !error.Success()) {
353 LLDB_LOGF(log,
354 "Unable to call introspection_get_dispatch_queues(), got "
355 "ExpressionResults %d, error contains %s",
356 func_call_ret, error.AsCString(""));
358 "Unable to call introspection_get_dispatch_queues() "
359 "for list of queues");
360 return return_value;
361 }
362
365 if (!error.Success() ||
366 return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS) {
368 return return_value;
369 }
370
373
374 if (!error.Success()) {
376 return return_value;
377 }
378
381 if (!error.Success()) {
383 return return_value;
384 }
385
386 LLDB_LOGF(log,
387 "AppleGetQueuesHandler called "
388 "__introspection_dispatch_get_queues (page_to_free == "
389 "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
390 ", size %" PRId64 ", count = %" PRId64,
391 page_to_free, page_to_free_size, return_value.queues_buffer_ptr,
392 return_value.queues_buffer_size, return_value.count);
393
394 return return_value;
395}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition: Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:392
A section + offset based address class.
Definition: Address.h:62
std::unique_ptr< UtilityFunction > m_get_queues_impl_code_up
lldb::addr_t SetupGetQueuesFunction(Thread &thread, ValueList &get_queues_arglist)
static const char * g_get_current_queues_function_name
GetQueuesReturnInfo GetCurrentQueues(Thread &thread, lldb::addr_t page_to_free, uint64_t page_to_free_size, lldb_private::Status &error)
Get the list of queues that exist (with any active or pending items) via a call to introspection_get_...
AppleGetQueuesHandler(lldb_private::Process *process)
static const char * g_get_current_queues_function_code
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:359
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:392
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:380
void SetStopOthers(bool stop_others=true)
Definition: Target.h:396
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:363
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Target & GetTargetRef() const
Returns a reference to the target object.
Encapsulates a function that can be called.
lldb::ExpressionResults ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager, Value &results)
Run the function this FunctionCaller was created with.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
A plug-in interface definition class for debugging a process.
Definition: Process.h:343
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
Definition: Process.cpp:2217
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1100
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition: Process.cpp:2489
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
An error handling class.
Definition: Status.h:115
static Status FromErrorString(const char *str)
Definition: Status.h:138
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
Definition: Target.cpp:2706
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:408
virtual bool SafeToCallFunctions()
Check whether this thread is safe to run functions.
Definition: Thread.cpp:1689
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition: Thread.cpp:1422
lldb::ProcessSP CalculateProcess() override
Definition: Thread.cpp:1416
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1408
lldb::ProcessSP GetProcess() const
Definition: Thread.h:157
void PushValue(const Value &value)
Definition: Value.cpp:687
const Scalar & GetScalar() const
Definition: Value.h:112
@ Scalar
A raw scalar value.
void SetCompilerType(const CompilerType &compiler_type)
Definition: Value.cpp:268
void SetValueType(ValueType value_type)
Definition: Value.h:89
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:332
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:424
@ eBasicTypeUnsignedLongLong
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:450
@ eLanguageTypeC
Non-standardized C, such as K&R.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:389
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
Definition: lldb-forward.h:470
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:448
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47