LLDB mainline
AppleGetItemInfoHandler.cpp
Go to the documentation of this file.
1//===-- AppleGetItemInfoHandler.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_item_info";
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_item_get_info (introspection_dispatch_item_info_ref item_info_ref, \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_item_info_return_values \n\
70 { \n\
71 uint64_t item_info_buffer_ptr; /* the address of the items buffer from libBacktraceRecording */ \n\
72 uint64_t item_info_buffer_size; /* the size of the items buffer from libBacktraceRecording */ \n\
73 }; \n\
74 \n\
75 void __lldb_backtrace_recording_get_item_info \n\
76 (struct get_item_info_return_values *return_buffer, \n\
77 int debug, \n\
78 uint64_t /* introspection_dispatch_item_info_ref item_info_ref */ item, \n\
79 void *page_to_free, \n\
80 uint64_t page_to_free_size) \n\
81{ \n\
82 if (debug) \n\
83 printf (\"entering get_item_info with args return_buffer == %p, debug == %d, item == 0x%llx, page_to_free == %p, page_to_free_size == 0x%llx\\n\", return_buffer, debug, item, page_to_free, page_to_free_size); \n\
84 if (page_to_free != 0) \n\
85 { \n\
86 mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
87 } \n\
88 \n\
89 __introspection_dispatch_queue_item_get_info ((void*) item, \n\
90 (void**)&return_buffer->item_info_buffer_ptr, \n\
91 &return_buffer->item_info_buffer_size); \n\
92} \n\
93} \n\
94";
95
97 : m_process(process), m_get_item_info_impl_code(),
98 m_get_item_info_function_mutex(),
99 m_get_item_info_return_buffer_addr(LLDB_INVALID_ADDRESS),
100 m_get_item_info_retbuffer_mutex() {}
101
103
105
106 if (m_process && m_process->IsAlive() &&
108 std::unique_lock<std::mutex> lock(m_get_item_info_retbuffer_mutex,
109 std::defer_lock);
110 (void)lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
112 }
113}
114
115// Compile our __lldb_backtrace_recording_get_item_info() function (from the
116// source above in g_get_item_info_function_code) if we don't find that
117// function in the inferior already with USE_BUILTIN_FUNCTION defined. (e.g.
118// this would be the case for testing.)
119//
120// Insert the __lldb_backtrace_recording_get_item_info into the inferior
121// process if needed.
122//
123// Write the get_item_info_arglist into the inferior's memory space to prepare
124// for the call.
125//
126// Returns the address of the arguments written down in the inferior process,
127// which can be used to make the function call.
128
130 Thread &thread, ValueList &get_item_info_arglist) {
131 ExecutionContext exe_ctx(thread.shared_from_this());
132 DiagnosticManager diagnostics;
135 FunctionCaller *get_item_info_caller = nullptr;
136
137 // Scope for mutex locker:
138 {
139 std::lock_guard<std::mutex> guard(m_get_item_info_function_mutex);
140
141 // First stage is to make the UtilityFunction to hold our injected
142 // function:
143
145 if (g_get_item_info_function_code != nullptr) {
146 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
148 eLanguageTypeObjC, exe_ctx);
149 if (!utility_fn_or_error) {
150 LLDB_LOG_ERROR(log, utility_fn_or_error.takeError(),
151 "Failed to create utility function: {0}");
152 }
153 m_get_item_info_impl_code = std::move(*utility_fn_or_error);
154 } else {
155 LLDB_LOGF(log, "No get-item-info introspection code found.");
157 }
158
159 // Next make the runner function for our implementation utility function.
160 auto type_system_or_err =
161 thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage(
163 if (auto err = type_system_or_err.takeError()) {
164 LLDB_LOG_ERROR(log, std::move(err),
165 "Error inserting get-item-info function: {0}");
166 return args_addr;
167 }
168 auto ts = *type_system_or_err;
169 if (!ts)
170 return args_addr;
171
172 CompilerType get_item_info_return_type =
175
177 get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller(
178 get_item_info_return_type, get_item_info_arglist,
179 thread.shared_from_this(), error);
180 if (error.Fail() || get_item_info_caller == nullptr) {
181 LLDB_LOGF(log, "Error inserting get-item-info function: \"%s\".",
182 error.AsCString());
183 return args_addr;
184 }
185 } else {
186 // If it's already made, then we can just retrieve the caller:
187 get_item_info_caller = m_get_item_info_impl_code->GetFunctionCaller();
188 if (!get_item_info_caller) {
189 LLDB_LOGF(log, "Failed to get get-item-info introspection caller.");
191 return args_addr;
192 }
193 }
194 }
195
196 diagnostics.Clear();
197
198 // Now write down the argument values for this particular call. This looks
199 // like it might be a race condition if other threads were calling into here,
200 // but actually it isn't because we allocate a new args structure for this
201 // call by passing args_addr = LLDB_INVALID_ADDRESS...
202
203 if (!get_item_info_caller->WriteFunctionArguments(
204 exe_ctx, args_addr, get_item_info_arglist, diagnostics)) {
205 if (log) {
206 LLDB_LOGF(log, "Error writing get-item-info function arguments.");
207 diagnostics.Dump(log);
208 }
209
210 return args_addr;
211 }
212
213 return args_addr;
214}
215
218 addr_t page_to_free,
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 GetItemInfoReturnInfo return_value;
230 return_value.item_buffer_size = 0;
231
232 error.Clear();
233
234 if (!thread.SafeToCallFunctions()) {
235 LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
236 thread.GetID());
237 error =
238 Status::FromErrorString("Not safe to call functions on this thread.");
239 return return_value;
240 }
241
242 // Set up the arguments for a call to
243
244 // struct get_item_info_return_values
245 // {
246 // uint64_t item_info_buffer_ptr; /* the address of the items buffer
247 // from libBacktraceRecording */
248 // uint64_t item_info_buffer_size; /* the size of the items buffer from
249 // libBacktraceRecording */
250 // };
251 //
252 // void __lldb_backtrace_recording_get_item_info
253 // (struct
254 // get_item_info_return_values
255 // *return_buffer,
256 // int debug,
257 // uint64_t item,
258 // void *page_to_free,
259 // uint64_t page_to_free_size)
260
261 // Where the return_buffer argument points to a 24 byte region of memory
262 // already allocated by lldb in the inferior process.
263
264 CompilerType clang_void_ptr_type =
265 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
266 Value return_buffer_ptr_value;
267 return_buffer_ptr_value.SetValueType(Value::ValueType::Scalar);
268 return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
269
270 CompilerType clang_int_type = scratch_ts_sp->GetBasicType(eBasicTypeInt);
271 Value debug_value;
273 debug_value.SetCompilerType(clang_int_type);
274
275 CompilerType clang_uint64_type =
276 scratch_ts_sp->GetBasicType(eBasicTypeUnsignedLongLong);
277 Value item_value;
279 item_value.SetCompilerType(clang_uint64_type);
280
281 Value page_to_free_value;
282 page_to_free_value.SetValueType(Value::ValueType::Scalar);
283 page_to_free_value.SetCompilerType(clang_void_ptr_type);
284
285 Value page_to_free_size_value;
286 page_to_free_size_value.SetValueType(Value::ValueType::Scalar);
287 page_to_free_size_value.SetCompilerType(clang_uint64_type);
288
289 std::lock_guard<std::mutex> guard(m_get_item_info_retbuffer_mutex);
291 addr_t bufaddr = process_sp->AllocateMemory(
292 32, ePermissionsReadable | ePermissionsWritable, error);
293 if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
294 LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
295 "current queues func call");
296 return return_value;
297 }
299 }
300
301 ValueList argument_values;
302
303 return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr;
304 argument_values.PushValue(return_buffer_ptr_value);
305
306 debug_value.GetScalar() = 0;
307 argument_values.PushValue(debug_value);
308
309 item_value.GetScalar() = item;
310 argument_values.PushValue(item_value);
311
312 if (page_to_free != LLDB_INVALID_ADDRESS)
313 page_to_free_value.GetScalar() = page_to_free;
314 else
315 page_to_free_value.GetScalar() = 0;
316 argument_values.PushValue(page_to_free_value);
317
318 page_to_free_size_value.GetScalar() = page_to_free_size;
319 argument_values.PushValue(page_to_free_size_value);
320
321 addr_t args_addr = SetupGetItemInfoFunction(thread, argument_values);
322
323 DiagnosticManager diagnostics;
324 ExecutionContext exe_ctx;
326 options.SetUnwindOnError(true);
327 options.SetIgnoreBreakpoints(true);
328 options.SetStopOthers(true);
329#if __has_feature(address_sanitizer)
330 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
331#else
332 options.SetTimeout(std::chrono::milliseconds(500));
333#endif
334 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
335 options.SetTryAllThreads(false);
336 options.SetIsForUtilityExpr(true);
337 thread.CalculateExecutionContext(exe_ctx);
338
340 error =
341 Status::FromErrorString("Unable to compile function to call "
342 "__introspection_dispatch_queue_item_get_info");
343 return return_value;
344 }
345
346 ExpressionResults func_call_ret;
347 Value results;
348 FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller();
349 if (!func_caller) {
350 LLDB_LOGF(log, "Could not retrieve function caller for "
351 "__introspection_dispatch_queue_item_get_info.");
353 "Could not retrieve function caller for "
354 "__introspection_dispatch_queue_item_get_info.");
355 return return_value;
356 }
357
358 func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options,
359 diagnostics, results);
360 if (func_call_ret != eExpressionCompleted || !error.Success()) {
361 LLDB_LOGF(log,
362 "Unable to call "
363 "__introspection_dispatch_queue_item_get_info(), got "
364 "ExpressionResults %d, error contains %s",
365 func_call_ret, error.AsCString(""));
367 "Unable to call "
368 "__introspection_dispatch_queue_get_item_info() for "
369 "list of queues");
370 return return_value;
371 }
372
375 if (!error.Success() ||
376 return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
378 return return_value;
379 }
380
383
384 if (!error.Success()) {
386 return return_value;
387 }
388 LLDB_LOGF(log,
389 "AppleGetItemInfoHandler called "
390 "__introspection_dispatch_queue_item_get_info (page_to_free == "
391 "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
392 ", size %" PRId64,
393 page_to_free, page_to_free_size, return_value.item_buffer_ptr,
394 return_value.item_buffer_size);
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
AppleGetItemInfoHandler(lldb_private::Process *process)
GetItemInfoReturnInfo GetItemInfo(Thread &thread, lldb::addr_t item, lldb::addr_t page_to_free, uint64_t page_to_free_size, lldb_private::Status &error)
Get the information about a work item by calling __introspection_dispatch_queue_item_get_info.
std::unique_ptr< UtilityFunction > m_get_item_info_impl_code
lldb::addr_t SetupGetItemInfoFunction(Thread &thread, ValueList &get_item_info_arglist)
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) const
Create related types using the current type's AST.
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
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
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