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"
23 #include "lldb/Utility/Log.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 const char *AppleGetQueuesHandler::g_get_current_queues_function_name =
30  "__lldb_backtrace_recording_get_current_queues";
31 const char *AppleGetQueuesHandler::g_get_current_queues_function_code =
32  " \n\
33 extern \"C\" \n\
34 { \n\
35  /* \n\
36  * mach defines \n\
37  */ \n\
38  \n\
39  typedef unsigned int uint32_t; \n\
40  typedef unsigned long long uint64_t; \n\
41  typedef uint32_t mach_port_t; \n\
42  typedef mach_port_t vm_map_t; \n\
43  typedef int kern_return_t; \n\
44  typedef uint64_t mach_vm_address_t; \n\
45  typedef uint64_t mach_vm_size_t; \n\
46  \n\
47  mach_port_t mach_task_self (); \n\
48  kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size); \n\
49  \n\
50  /* \n\
51  * libBacktraceRecording defines \n\
52  */ \n\
53  \n\
54  typedef uint32_t queue_list_scope_t; \n\
55  typedef void *introspection_dispatch_queue_info_t; \n\
56  \n\
57  extern uint64_t __introspection_dispatch_get_queues (queue_list_scope_t scope, \n\
58  introspection_dispatch_queue_info_t *returned_queues_buffer, \n\
59  uint64_t *returned_queues_buffer_size); \n\
60  extern int printf(const char *format, ...); \n\
61  \n\
62  /* \n\
63  * return type define \n\
64  */ \n\
65  \n\
66  struct get_current_queues_return_values \n\
67  { \n\
68  uint64_t queues_buffer_ptr; /* the address of the queues buffer from libBacktraceRecording */ \n\
69  uint64_t queues_buffer_size; /* the size of the queues buffer from libBacktraceRecording */ \n\
70  uint64_t count; /* the number of queues included in the queues buffer */ \n\
71  }; \n\
72  \n\
73  void __lldb_backtrace_recording_get_current_queues \n\
74  (struct get_current_queues_return_values *return_buffer, \n\
75  int debug, \n\
76  void *page_to_free, \n\
77  uint64_t page_to_free_size) \n\
78 { \n\
79  if (debug) \n\
80  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\
81  if (page_to_free != 0) \n\
82  { \n\
83  mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
84  } \n\
85  \n\
86  return_buffer->count = __introspection_dispatch_get_queues ( \n\
87  /* QUEUES_WITH_ANY_ITEMS */ 2, \n\
88  (void**)&return_buffer->queues_buffer_ptr, \n\
89  &return_buffer->queues_buffer_size); \n\
90  if (debug) \n\
91  printf(\"result was count %lld\\n\", return_buffer->count); \n\
92 } \n\
93 } \n\
94 ";
95 
96 AppleGetQueuesHandler::AppleGetQueuesHandler(Process *process)
97  : m_process(process), m_get_queues_impl_code_up(),
98  m_get_queues_function_mutex(),
99  m_get_queues_return_buffer_addr(LLDB_INVALID_ADDRESS),
100  m_get_queues_retbuffer_mutex() {}
101 
103 
105 
106  if (m_process && m_process->IsAlive() &&
108  std::unique_lock<std::mutex> lock(m_get_queues_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 // Construct a CompilerType for the structure that
116 // g_get_current_queues_function_code will return by value so we can extract
117 // the fields after performing the function call. i.e. we are getting this
118 // struct returned to us:
119 //
120 // struct get_current_queues_return_values
121 // {
122 // introspection_dispatch_queue_info_t *queues_buffer;
123 // uint64_t queues_buffer_size;
124 // uint64_t count;
125 // };
126 
127 // Compile our __lldb_backtrace_recording_get_current_queues() function (from
128 // the source above in g_get_current_queues_function_code) if we don't find
129 // that function in the inferior already with USE_BUILTIN_FUNCTION defined.
130 // (e.g. this would be the case for testing.)
131 //
132 // Insert the __lldb_backtrace_recording_get_current_queues into the inferior
133 // process if needed.
134 //
135 // Write the get_queues_arglist into the inferior's memory space to prepare for
136 // the call.
137 //
138 // Returns the address of the arguments written down in the inferior process,
139 // which can be used to make the function call.
140 
143  ValueList &get_queues_arglist) {
144  ThreadSP thread_sp(thread.shared_from_this());
145  ExecutionContext exe_ctx(thread_sp);
146 
147  Address impl_code_address;
148  DiagnosticManager diagnostics;
151 
152  FunctionCaller *get_queues_caller = nullptr;
153 
154  // Scope for mutex locker:
155  {
156  std::lock_guard<std::mutex> guard(m_get_queues_function_mutex);
157 
158  // First stage is to make the ClangUtility to hold our injected function:
159 
161  if (g_get_current_queues_function_code != nullptr) {
162  auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
165  if (!utility_fn_or_error) {
166  LLDB_LOG_ERROR(log, utility_fn_or_error.takeError(),
167  "Failed to create UtilityFunction for queues "
168  "introspection: {0}.");
169  return args_addr;
170  }
171  m_get_queues_impl_code_up = std::move(*utility_fn_or_error);
172  } else {
173  if (log) {
174  LLDB_LOGF(log, "No queues introspection code found.");
175  diagnostics.Dump(log);
176  }
177  return LLDB_INVALID_ADDRESS;
178  }
179  }
180 
181  // Next make the runner function for our implementation utility function.
182  TypeSystemClang *clang_ast_context =
183  ScratchTypeSystemClang::GetForTarget(thread.GetProcess()->GetTarget());
184  CompilerType get_queues_return_type =
185  clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
186  Status error;
187  get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller(
188  get_queues_return_type, get_queues_arglist, thread_sp, error);
189  if (error.Fail() || get_queues_caller == nullptr) {
190  LLDB_LOGF(log,
191  "Could not get function caller for get-queues function: %s.",
192  error.AsCString());
193  return args_addr;
194  }
195  }
196 
197  diagnostics.Clear();
198 
199  // Now write down the argument values for this particular call. This looks
200  // like it might be a race condition if other threads were calling into here,
201  // but actually it isn't because we allocate a new args structure for this
202  // call by passing args_addr = LLDB_INVALID_ADDRESS...
203 
204  if (!get_queues_caller->WriteFunctionArguments(
205  exe_ctx, args_addr, get_queues_arglist, diagnostics)) {
206  if (log) {
207  LLDB_LOGF(log, "Error writing get-queues function arguments.");
208  diagnostics.Dump(log);
209  }
210  return args_addr;
211  }
212 
213  return args_addr;
214 }
215 
218  uint64_t page_to_free_size,
219  Status &error) {
220  lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
221  ProcessSP process_sp(thread.CalculateProcess());
222  TargetSP target_sp(thread.CalculateTarget());
223  TypeSystemClang *clang_ast_context =
226 
227  GetQueuesReturnInfo return_value;
229  return_value.queues_buffer_size = 0;
230  return_value.count = 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.SetErrorString("Not safe to call functions on this thread.");
238  return return_value;
239  }
240 
241  // Set up the arguments for a call to
242 
243  // struct get_current_queues_return_values
244  // {
245  // uint64_t queues_buffer_ptr; /* the address of the queues buffer from
246  // libBacktraceRecording */
247  // uint64_t queues_buffer_size; /* the size of the queues buffer from
248  // libBacktraceRecording */
249  // uint64_t count; /* the number of queues included in the
250  // queues buffer */
251  // };
252  //
253  // void
254  // __lldb_backtrace_recording_get_current_queues
255  // (struct
256  // get_current_queues_return_values
257  // *return_buffer,
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  clang_ast_context->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 = clang_ast_context->GetBasicType(eBasicTypeInt);
271  Value debug_value;
273  debug_value.SetCompilerType(clang_int_type);
274 
275  Value page_to_free_value;
276  page_to_free_value.SetValueType(Value::ValueType::Scalar);
277  page_to_free_value.SetCompilerType(clang_void_ptr_type);
278 
279  CompilerType clang_uint64_type =
280  clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
281  Value page_to_free_size_value;
282  page_to_free_size_value.SetValueType(Value::ValueType::Scalar);
283  page_to_free_size_value.SetCompilerType(clang_uint64_type);
284 
285  std::lock_guard<std::mutex> guard(m_get_queues_retbuffer_mutex);
287  addr_t bufaddr = process_sp->AllocateMemory(
288  32, ePermissionsReadable | ePermissionsWritable, error);
289  if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
290  LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
291  "current queues func call");
292  return return_value;
293  }
295  }
296 
297  ValueList argument_values;
298 
299  return_buffer_ptr_value.GetScalar() = m_get_queues_return_buffer_addr;
300  argument_values.PushValue(return_buffer_ptr_value);
301 
302  debug_value.GetScalar() = 0;
303  argument_values.PushValue(debug_value);
304 
305  if (page_to_free != LLDB_INVALID_ADDRESS)
306  page_to_free_value.GetScalar() = page_to_free;
307  else
308  page_to_free_value.GetScalar() = 0;
309  argument_values.PushValue(page_to_free_value);
310 
311  page_to_free_size_value.GetScalar() = page_to_free_size;
312  argument_values.PushValue(page_to_free_size_value);
313 
314  addr_t args_addr = SetupGetQueuesFunction(thread, argument_values);
315 
317  error.SetErrorString(
318  "Unable to compile __introspection_dispatch_get_queues.");
319  return return_value;
320  }
321 
322  FunctionCaller *get_queues_caller =
323  m_get_queues_impl_code_up->GetFunctionCaller();
324 
325  if (get_queues_caller == nullptr) {
326  error.SetErrorString(
327  "Unable to get caller for call __introspection_dispatch_get_queues");
328  return return_value;
329  }
330 
331  DiagnosticManager diagnostics;
332  ExecutionContext exe_ctx;
334  options.SetUnwindOnError(true);
335  options.SetIgnoreBreakpoints(true);
336  options.SetStopOthers(true);
337 #if __has_feature(address_sanitizer)
338  options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
339 #else
340  options.SetTimeout(std::chrono::milliseconds(500));
341 #endif
342  options.SetTryAllThreads(false);
343  options.SetIsForUtilityExpr(true);
344  thread.CalculateExecutionContext(exe_ctx);
345 
346  ExpressionResults func_call_ret;
347  Value results;
348  func_call_ret = get_queues_caller->ExecuteFunction(
349  exe_ctx, &args_addr, options, diagnostics, results);
350  if (func_call_ret != eExpressionCompleted || !error.Success()) {
351  LLDB_LOGF(log,
352  "Unable to call introspection_get_dispatch_queues(), got "
353  "ExpressionResults %d, error contains %s",
354  func_call_ret, error.AsCString(""));
355  error.SetErrorString("Unable to call introspection_get_dispatch_queues() "
356  "for list of queues");
357  return return_value;
358  }
359 
362  if (!error.Success() ||
363  return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS) {
365  return return_value;
366  }
367 
370 
371  if (!error.Success()) {
373  return return_value;
374  }
375 
378  if (!error.Success()) {
380  return return_value;
381  }
382 
383  LLDB_LOGF(log,
384  "AppleGetQueuesHandler called "
385  "__introspection_dispatch_get_queues (page_to_free == "
386  "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
387  ", size %" PRId64 ", count = %" PRId64,
388  page_to_free, page_to_free_size, return_value.queues_buffer_ptr,
389  return_value.queues_buffer_size, return_value.count);
390 
391  return return_value;
392 }
lldb_private::Value::ValueType::Scalar
@ Scalar
A raw scalar value.
lldb_private::ExecutionContext
Definition: ExecutionContext.h:292
lldb_private::Process::DeallocateMemory
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition: Process.cpp:2380
lldb_private::AppleGetQueuesHandler::GetCurrentQueues
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_...
Definition: AppleGetQueuesHandler.cpp:217
FunctionCaller.h
lldb_private::EvaluateExpressionOptions::SetTimeout
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:327
lldb_private::Value
Definition: Value.h:38
lldb_private::Value::SetValueType
void SetValueType(ValueType value_type)
Definition: Value.h:89
lldb_private::DiagnosticManager::Dump
void Dump(Log *log)
Definition: DiagnosticManager.cpp:18
lldb_private::AppleGetQueuesHandler::m_get_queues_return_buffer_addr
lldb::addr_t m_get_queues_return_buffer_addr
Definition: AppleGetQueuesHandler.h:102
lldb::ExpressionResults
ExpressionResults
The results of expression evaluation.
Definition: lldb-enumerations.h:270
LLDB_LOGF
#define LLDB_LOGF(log,...)
Definition: Log.h:249
lldb_private::Process
Definition: Process.h:341
lldb_private::Thread::CalculateTarget
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1389
lldb_private::EvaluateExpressionOptions::SetIsForUtilityExpr
void SetIsForUtilityExpr(bool b)
Definition: Target.h:414
Module.h
lldb_private::EvaluateExpressionOptions
Definition: Target.h:259
lldb_private::ValueList
Definition: Value.h:157
LIBLLDB_LOG_SYSTEM_RUNTIME
#define LIBLLDB_LOG_SYSTEM_RUNTIME
Definition: Logging.h:40
lldb_private::Process::IsAlive
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1085
lldb::addr_t
uint64_t addr_t
Definition: lldb-types.h:83
lldb_private::Thread::SafeToCallFunctions
virtual bool SafeToCallFunctions()
Check whether this thread is safe to run functions.
Definition: Thread.cpp:1647
Process.h
lldb_private::Value::SetCompilerType
void SetCompilerType(const CompilerType &compiler_type)
Definition: Value.cpp:254
Target.h
lldb_private::Value::GetScalar
const Scalar & GetScalar() const
Definition: Value.h:112
lldb_private::Thread::GetProcess
lldb::ProcessSP GetProcess() const
Definition: Thread.h:152
lldb_private::AppleGetQueuesHandler::m_get_queues_retbuffer_mutex
std::mutex m_get_queues_retbuffer_mutex
Definition: AppleGetQueuesHandler.h:103
error
static llvm::raw_ostream & error(Stream &strm)
Definition: CommandReturnObject.cpp:17
lldb_private::ValueList::PushValue
void PushValue(const Value &value)
Definition: Value.cpp:675
lldb_private::Thread::CalculateProcess
lldb::ProcessSP CalculateProcess() override
Definition: Thread.cpp:1397
lldb_private::AppleGetQueuesHandler::~AppleGetQueuesHandler
~AppleGetQueuesHandler()
lldb_private::FunctionCaller::WriteFunctionArguments
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
Definition: FunctionCaller.cpp:115
Log.h
TypeSystemClang.h
lldb_private::Thread
Definition: Thread.h:60
lldb::eExpressionCompleted
@ eExpressionCompleted
Definition: lldb-enumerations.h:271
StreamString.h
lldb::eBasicTypeInt
@ eBasicTypeInt
Definition: lldb-enumerations.h:754
lldb_private::AppleGetQueuesHandler::g_get_current_queues_function_code
static const char * g_get_current_queues_function_code
Definition: AppleGetQueuesHandler.h:96
lldb_private::AppleGetQueuesHandler::m_process
lldb_private::Process * m_process
Definition: AppleGetQueuesHandler.h:98
lldb_private::Target::CreateUtilityFunction
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:2320
lldb_private::EvaluateExpressionOptions::SetTryAllThreads
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:339
lldb_private::GetLogIfAllCategoriesSet
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:58
lldb::eBasicTypeVoid
@ eBasicTypeVoid
Definition: lldb-enumerations.h:743
lldb_private::AppleGetQueuesHandler::Detach
void Detach()
Definition: AppleGetQueuesHandler.cpp:104
lldb::eBasicTypeUnsignedLongLong
@ eBasicTypeUnsignedLongLong
Definition: lldb-enumerations.h:759
lldb_private::AppleGetQueuesHandler::SetupGetQueuesFunction
lldb::addr_t SetupGetQueuesFunction(Thread &thread, ValueList &get_queues_arglist)
Definition: AppleGetQueuesHandler.cpp:142
lldb_private::EvaluateExpressionOptions::SetUnwindOnError
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:306
Thread.h
lldb_private::AppleGetQueuesHandler::GetQueuesReturnInfo::queues_buffer_ptr
lldb::addr_t queues_buffer_ptr
Definition: AppleGetQueuesHandler.h:48
lldb_private::UserID::GetID
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47
lldb_private::Thread::CalculateExecutionContext
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition: Thread.cpp:1403
UtilityFunction.h
lldb_private::EvaluateExpressionOptions::SetIgnoreBreakpoints
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:310
Symbol.h
lldb_private::Status
Definition: Status.h:44
lldb_private::CompilerType::GetPointerType
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
Definition: CompilerType.cpp:407
lldb_private::AppleGetQueuesHandler::GetQueuesReturnInfo::queues_buffer_size
lldb::addr_t queues_buffer_size
Definition: AppleGetQueuesHandler.h:51
lldb_private::Address
Definition: Address.h:59
lldb_private::DiagnosticManager
Definition: DiagnosticManager.h:93
lldb_private::ScratchTypeSystemClang::GetForTarget
static TypeSystemClang * GetForTarget(Target &target, llvm::Optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
Definition: TypeSystemClang.cpp:9729
LLDB_INVALID_ADDRESS
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:86
lldb_private::CompilerType
Generic representation of a type in a programming language.
Definition: CompilerType.h:33
DiagnosticManager.h
lldb_private::DiagnosticManager::Clear
void Clear()
Definition: DiagnosticManager.h:95
lldb_private::ExecutionContext::GetTargetRef
Target & GetTargetRef() const
Returns a reference to the target object.
Definition: ExecutionContext.cpp:226
lldb_private::AppleGetQueuesHandler::GetQueuesReturnInfo
Definition: AppleGetQueuesHandler.h:47
lldb::eLanguageTypeC
@ eLanguageTypeC
Non-standardized C, such as K&R.
Definition: lldb-enumerations.h:439
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::FunctionCaller::ExecuteFunction
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.
Definition: FunctionCaller.cpp:313
lldb_private::TypeSystemClang::GetBasicType
CompilerType GetBasicType(lldb::BasicType type)
Definition: TypeSystemClang.cpp:934
lldb_private::TypeSystemClang
A TypeSystem implementation based on Clang.
Definition: TypeSystemClang.h:106
ConstString.h
lldb_private::Process::ReadUnsignedIntegerFromMemory
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:2112
lldb_private::Log
Definition: Log.h:49
lldb_private::EvaluateExpressionOptions::SetStopOthers
void SetStopOthers(bool stop_others=true)
Definition: Target.h:343
lldb_private::Thread::GetStackFrameAtIndex
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:397
AppleGetQueuesHandler.h
lldb_private::AppleGetQueuesHandler::g_get_current_queues_function_name
static const char * g_get_current_queues_function_name
Definition: AppleGetQueuesHandler.h:95
lldb_private::AppleGetQueuesHandler::GetQueuesReturnInfo::count
uint64_t count
Definition: AppleGetQueuesHandler.h:53
lldb
Definition: SBAddress.h:15
LLDB_LOG_ERROR
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:265
Value.h
lldb_private::AppleGetQueuesHandler::m_get_queues_impl_code_up
std::unique_ptr< UtilityFunction > m_get_queues_impl_code_up
Definition: AppleGetQueuesHandler.h:99
ExecutionContext.h
lldb_private::AppleGetQueuesHandler::m_get_queues_function_mutex
std::mutex m_get_queues_function_mutex
Definition: AppleGetQueuesHandler.h:100
lldb_private::FunctionCaller
Definition: FunctionCaller.h:56