LLDB mainline
AppleGetPendingItemsHandler.cpp
Go to the documentation of this file.
1//===-- AppleGetPendingItemsHandler.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_pending_items";
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 *dispatch_queue_t; \n\
57 typedef void *introspection_dispatch_queue_info_t; \n\
58 typedef void *introspection_dispatch_item_info_ref; \n\
59 \n\
60 extern uint64_t __introspection_dispatch_queue_get_pending_items (dispatch_queue_t queue, \n\
61 introspection_dispatch_item_info_ref *returned_queues_buffer, \n\
62 uint64_t *returned_queues_buffer_size); \n\
63 extern int printf(const char *format, ...); \n\
64 \n\
65 /* \n\
66 * return type define \n\
67 */ \n\
68 \n\
69 struct get_pending_items_return_values \n\
70 { \n\
71 uint64_t pending_items_buffer_ptr; /* the address of the items buffer from libBacktraceRecording */ \n\
72 uint64_t pending_items_buffer_size; /* the size of the items buffer from libBacktraceRecording */ \n\
73 uint64_t count; /* the number of items included in the queues buffer */ \n\
74 }; \n\
75 \n\
76 void __lldb_backtrace_recording_get_pending_items \n\
77 (struct get_pending_items_return_values *return_buffer, \n\
78 int debug, \n\
79 uint64_t /* dispatch_queue_t */ queue, \n\
80 void *page_to_free, \n\
81 uint64_t page_to_free_size) \n\
82{ \n\
83 if (debug) \n\
84 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\
85 if (page_to_free != 0) \n\
86 { \n\
87 mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
88 } \n\
89 \n\
90 return_buffer->count = __introspection_dispatch_queue_get_pending_items ( \n\
91 (void*) queue, \n\
92 (void**)&return_buffer->pending_items_buffer_ptr, \n\
93 &return_buffer->pending_items_buffer_size); \n\
94 if (debug) \n\
95 printf(\"result was count %lld\\n\", return_buffer->count); \n\
96} \n\
97} \n\
98";
99
101 : m_process(process), m_get_pending_items_impl_code(),
102 m_get_pending_items_function_mutex(),
103 m_get_pending_items_return_buffer_addr(LLDB_INVALID_ADDRESS),
104 m_get_pending_items_retbuffer_mutex() {}
105
107
109 if (m_process && m_process->IsAlive() &&
111 std::unique_lock<std::mutex> lock(m_get_pending_items_retbuffer_mutex,
112 std::defer_lock);
113 (void)lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
115 }
116}
117
118// Compile our __lldb_backtrace_recording_get_pending_items() function (from
119// the source above in g_get_pending_items_function_code) if we don't find that
120// function in the inferior already with USE_BUILTIN_FUNCTION defined. (e.g.
121// this would be the case for testing.)
122//
123// Insert the __lldb_backtrace_recording_get_pending_items into the inferior
124// process if needed.
125//
126// Write the get_pending_items_arglist into the inferior's memory space to
127// prepare for the call.
128//
129// Returns the address of the arguments written down in the inferior process,
130// which can be used to make the function call.
131
133 Thread &thread, ValueList &get_pending_items_arglist) {
134 ThreadSP thread_sp(thread.shared_from_this());
135 ExecutionContext exe_ctx(thread_sp);
136 DiagnosticManager diagnostics;
138
140 FunctionCaller *get_pending_items_caller = nullptr;
141
142 // Scope for mutex locker:
143 {
144 std::lock_guard<std::mutex> guard(m_get_pending_items_function_mutex);
145
146 // First stage is to make the ClangUtility to hold our injected function:
147
149 if (g_get_pending_items_function_code != nullptr) {
150 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
153 if (!utility_fn_or_error) {
154 LLDB_LOG_ERROR(log, utility_fn_or_error.takeError(),
155 "Failed to create UtilityFunction for pending-items "
156 "introspection: {0}.");
157 return args_addr;
158 }
159 m_get_pending_items_impl_code = std::move(*utility_fn_or_error);
160 } else {
161 LLDB_LOGF(log, "No pending-items introspection code found.");
163 }
164
165 // Next make the runner function for our implementation utility function.
168 thread.GetProcess()->GetTarget());
169 CompilerType get_pending_items_return_type =
170 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
171 get_pending_items_caller =
172 m_get_pending_items_impl_code->MakeFunctionCaller(
173 get_pending_items_return_type, get_pending_items_arglist,
174 thread_sp, error);
175 if (error.Fail() || get_pending_items_caller == nullptr) {
176 LLDB_LOGF(log,
177 "Failed to install pending-items introspection function "
178 "caller: %s.",
179 error.AsCString());
181 return args_addr;
182 }
183 }
184 }
185
186 diagnostics.Clear();
187
188 if (get_pending_items_caller == nullptr) {
189 LLDB_LOGF(log, "Failed to get get_pending_items_caller.");
191 }
192
193 // Now write down the argument values for this particular call. This looks
194 // like it might be a race condition if other threads were calling into here,
195 // but actually it isn't because we allocate a new args structure for this
196 // call by passing args_addr = LLDB_INVALID_ADDRESS...
197
198 if (!get_pending_items_caller->WriteFunctionArguments(
199 exe_ctx, args_addr, get_pending_items_arglist, diagnostics)) {
200 if (log) {
201 LLDB_LOGF(log, "Error writing pending-items function arguments.");
202 diagnostics.Dump(log);
203 }
204
205 return args_addr;
206 }
207
208 return args_addr;
209}
210
213 addr_t page_to_free,
214 uint64_t page_to_free_size,
215 Status &error) {
216 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
217 ProcessSP process_sp(thread.CalculateProcess());
218 TargetSP target_sp(thread.CalculateTarget());
219 TypeSystemClangSP scratch_ts_sp =
222
223 GetPendingItemsReturnInfo return_value;
225 return_value.items_buffer_size = 0;
226 return_value.count = 0;
227
228 error.Clear();
229
230 if (!thread.SafeToCallFunctions()) {
231 LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
232 thread.GetID());
233 error =
234 Status::FromErrorString("Not safe to call functions on this thread.");
235 return return_value;
236 }
237
238 // Set up the arguments for a call to
239
240 // struct get_pending_items_return_values
241 // {
242 // uint64_t pending_items_buffer_ptr; /* the address of the items
243 // buffer from libBacktraceRecording */
244 // uint64_t pending_items_buffer_size; /* the size of the items buffer
245 // from libBacktraceRecording */
246 // uint64_t count; /* the number of items included in the
247 // queues buffer */
248 // };
249 //
250 // void __lldb_backtrace_recording_get_pending_items
251 // (struct
252 // get_pending_items_return_values
253 // *return_buffer,
254 // int debug,
255 // uint64_t /* dispatch_queue_t */
256 // queue
257 // void *page_to_free,
258 // uint64_t page_to_free_size)
259
260 // Where the return_buffer argument points to a 24 byte region of memory
261 // already allocated by lldb in the inferior process.
262
263 CompilerType clang_void_ptr_type =
264 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
265 Value return_buffer_ptr_value;
266 return_buffer_ptr_value.SetValueType(Value::ValueType::Scalar);
267 return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
268
269 CompilerType clang_int_type = scratch_ts_sp->GetBasicType(eBasicTypeInt);
270 Value debug_value;
272 debug_value.SetCompilerType(clang_int_type);
273
274 CompilerType clang_uint64_type =
275 scratch_ts_sp->GetBasicType(eBasicTypeUnsignedLongLong);
276 Value queue_value;
278 queue_value.SetCompilerType(clang_uint64_type);
279
280 Value page_to_free_value;
281 page_to_free_value.SetValueType(Value::ValueType::Scalar);
282 page_to_free_value.SetCompilerType(clang_void_ptr_type);
283
284 Value page_to_free_size_value;
285 page_to_free_size_value.SetValueType(Value::ValueType::Scalar);
286 page_to_free_size_value.SetCompilerType(clang_uint64_type);
287
288 std::lock_guard<std::mutex> guard(m_get_pending_items_retbuffer_mutex);
290 addr_t bufaddr = process_sp->AllocateMemory(
291 32, ePermissionsReadable | ePermissionsWritable, error);
292 if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
293 LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
294 "current queues func call");
295 return return_value;
296 }
298 }
299
300 ValueList argument_values;
301
302 return_buffer_ptr_value.GetScalar() = m_get_pending_items_return_buffer_addr;
303 argument_values.PushValue(return_buffer_ptr_value);
304
305 debug_value.GetScalar() = 0;
306 argument_values.PushValue(debug_value);
307
308 queue_value.GetScalar() = queue;
309 argument_values.PushValue(queue_value);
310
311 if (page_to_free != LLDB_INVALID_ADDRESS)
312 page_to_free_value.GetScalar() = page_to_free;
313 else
314 page_to_free_value.GetScalar() = 0;
315 argument_values.PushValue(page_to_free_value);
316
317 page_to_free_size_value.GetScalar() = page_to_free_size;
318 argument_values.PushValue(page_to_free_size_value);
319
320 addr_t args_addr = SetupGetPendingItemsFunction(thread, argument_values);
321
322 DiagnosticManager diagnostics;
323 ExecutionContext exe_ctx;
324 FunctionCaller *get_pending_items_caller =
325 m_get_pending_items_impl_code->GetFunctionCaller();
326
328 options.SetUnwindOnError(true);
329 options.SetIgnoreBreakpoints(true);
330 options.SetStopOthers(true);
331#if __has_feature(address_sanitizer)
332 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
333#else
334 options.SetTimeout(std::chrono::milliseconds(500));
335#endif
336 options.SetTryAllThreads(false);
337 options.SetIsForUtilityExpr(true);
338 thread.CalculateExecutionContext(exe_ctx);
339
340 if (get_pending_items_caller == nullptr) {
342 "Unable to compile function to call "
343 "__introspection_dispatch_queue_get_pending_items");
344 return return_value;
345 }
346
347 ExpressionResults func_call_ret;
348 Value results;
349 func_call_ret = get_pending_items_caller->ExecuteFunction(
350 exe_ctx, &args_addr, options, diagnostics, results);
351 if (func_call_ret != eExpressionCompleted || !error.Success()) {
352 LLDB_LOGF(log,
353 "Unable to call "
354 "__introspection_dispatch_queue_get_pending_items(), got "
355 "ExpressionResults %d, error contains %s",
356 func_call_ret, error.AsCString(""));
358 "Unable to call "
359 "__introspection_dispatch_queue_get_pending_items() "
360 "for list of queues");
361 return return_value;
362 }
363
366 if (!error.Success() ||
367 return_value.items_buffer_ptr == LLDB_INVALID_ADDRESS) {
369 return return_value;
370 }
371
374
375 if (!error.Success()) {
377 return return_value;
378 }
379
382 if (!error.Success()) {
384 return return_value;
385 }
386
387 LLDB_LOGF(log,
388 "AppleGetPendingItemsHandler called "
389 "__introspection_dispatch_queue_get_pending_items "
390 "(page_to_free == 0x%" PRIx64 ", size = %" PRId64
391 "), returned page is at 0x%" PRIx64 ", size %" PRId64
392 ", count = %" PRId64,
393 page_to_free, page_to_free_size, return_value.items_buffer_ptr,
394 return_value.items_buffer_size, return_value.count);
395
396 return return_value;
397}
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
lldb::addr_t SetupGetPendingItemsFunction(Thread &thread, ValueList &get_pending_items_arglist)
AppleGetPendingItemsHandler(lldb_private::Process *process)
std::unique_ptr< UtilityFunction > m_get_pending_items_impl_code
GetPendingItemsReturnInfo GetPendingItems(Thread &thread, lldb::addr_t queue, lldb::addr_t page_to_free, uint64_t page_to_free_size, lldb_private::Status &error)
Get the list of pending items for a given queue via a call to __introspection_dispatch_queue_get_pend...
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:118
static Status FromErrorString(const char *str)
Definition: Status.h:141
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