1 //===-- AppleGetQueuesHandler.cpp -------------------------------*- C++ -*-===//
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 
9 #include "AppleGetQueuesHandler.h"
10 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/Value.h"
13 #include "lldb/Expression/DiagnosticManager.h"
14 #include "lldb/Expression/FunctionCaller.h"
15 #include "lldb/Expression/UtilityFunction.h"
16 #include "lldb/Symbol/ClangASTContext.h"
17 #include "lldb/Symbol/Symbol.h"
18 #include "lldb/Target/ExecutionContext.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Utility/ConstString.h"
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/StreamString.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 
102 AppleGetQueuesHandler::~AppleGetQueuesHandler() {}
103 
104 void AppleGetQueuesHandler::Detach() {
105 
106   if (m_process && m_process->IsAlive() &&
107       m_get_queues_return_buffer_addr != LLDB_INVALID_ADDRESS) {
108     std::unique_lock<std::mutex> lock(m_get_queues_retbuffer_mutex,
109                                       std::defer_lock);
110     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
111     m_process->DeallocateMemory(m_get_queues_return_buffer_addr);
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 
141 lldb::addr_t
142 AppleGetQueuesHandler::SetupGetQueuesFunction(Thread &thread,
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;
149   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
150   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
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 
160     if (!m_get_queues_impl_code_up) {
161       if (g_get_current_queues_function_code != nullptr) {
162         Status error;
163         m_get_queues_impl_code_up.reset(
164             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
165                 g_get_current_queues_function_code, eLanguageTypeC,
166                 g_get_current_queues_function_name, error));
167         if (error.Fail()) {
168           LLDB_LOGF(
169               log,
170               "Failed to get UtilityFunction for queues introspection: %s.",
171               error.AsCString());
172           return args_addr;
173         }
174 
175         if (!m_get_queues_impl_code_up->Install(diagnostics, exe_ctx)) {
176           if (log) {
177             LLDB_LOGF(log, "Failed to install queues introspection");
178             diagnostics.Dump(log);
179           }
180           m_get_queues_impl_code_up.reset();
181           return args_addr;
182         }
183       } else {
184         if (log) {
185           LLDB_LOGF(log, "No queues introspection code found.");
186           diagnostics.Dump(log);
187         }
188         return LLDB_INVALID_ADDRESS;
189       }
190     }
191 
192     // Next make the runner function for our implementation utility function.
193     ClangASTContext *clang_ast_context =
194         ClangASTContext::GetScratch(thread.GetProcess()->GetTarget());
195     CompilerType get_queues_return_type =
196         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
197     Status error;
198     get_queues_caller = m_get_queues_impl_code_up->MakeFunctionCaller(
199         get_queues_return_type, get_queues_arglist, thread_sp, error);
200     if (error.Fail() || get_queues_caller == nullptr) {
201       LLDB_LOGF(log,
202                 "Could not get function caller for get-queues function: %s.",
203                 error.AsCString());
204       return args_addr;
205     }
206   }
207 
208   diagnostics.Clear();
209 
210   // Now write down the argument values for this particular call.  This looks
211   // like it might be a race condition if other threads were calling into here,
212   // but actually it isn't because we allocate a new args structure for this
213   // call by passing args_addr = LLDB_INVALID_ADDRESS...
214 
215   if (!get_queues_caller->WriteFunctionArguments(
216           exe_ctx, args_addr, get_queues_arglist, diagnostics)) {
217     if (log) {
218       LLDB_LOGF(log, "Error writing get-queues function arguments.");
219       diagnostics.Dump(log);
220     }
221     return args_addr;
222   }
223 
224   return args_addr;
225 }
226 
227 AppleGetQueuesHandler::GetQueuesReturnInfo
228 AppleGetQueuesHandler::GetCurrentQueues(Thread &thread, addr_t page_to_free,
229                                         uint64_t page_to_free_size,
230                                         Status &error) {
231   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
232   ProcessSP process_sp(thread.CalculateProcess());
233   TargetSP target_sp(thread.CalculateTarget());
234   ClangASTContext *clang_ast_context = ClangASTContext::GetScratch(*target_sp);
235   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
236 
237   GetQueuesReturnInfo return_value;
238   return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
239   return_value.queues_buffer_size = 0;
240   return_value.count = 0;
241 
242   error.Clear();
243 
244   if (!thread.SafeToCallFunctions()) {
245     LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
246               thread.GetID());
247     error.SetErrorString("Not safe to call functions on this thread.");
248     return return_value;
249   }
250 
251   // Set up the arguments for a call to
252 
253   // struct get_current_queues_return_values
254   // {
255   //    uint64_t queues_buffer_ptr;    /* the address of the queues buffer from
256   //    libBacktraceRecording */
257   //    uint64_t queues_buffer_size;   /* the size of the queues buffer from
258   //    libBacktraceRecording */
259   //    uint64_t count;                /* the number of queues included in the
260   //    queues buffer */
261   // };
262   //
263   //  void
264   //    __lldb_backtrace_recording_get_current_queues
265   //                                         (struct
266   //                                         get_current_queues_return_values
267   //                                         *return_buffer,
268   //                                          void *page_to_free,
269   //                                          uint64_t page_to_free_size);
270 
271   // Where the return_buffer argument points to a 24 byte region of memory
272   // already allocated by lldb in the inferior process.
273 
274   CompilerType clang_void_ptr_type =
275       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
276   Value return_buffer_ptr_value;
277   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
278   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
279 
280   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
281   Value debug_value;
282   debug_value.SetValueType(Value::eValueTypeScalar);
283   debug_value.SetCompilerType(clang_int_type);
284 
285   Value page_to_free_value;
286   page_to_free_value.SetValueType(Value::eValueTypeScalar);
287   page_to_free_value.SetCompilerType(clang_void_ptr_type);
288 
289   CompilerType clang_uint64_type =
290       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
291   Value page_to_free_size_value;
292   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
293   page_to_free_size_value.SetCompilerType(clang_uint64_type);
294 
295   std::lock_guard<std::mutex> guard(m_get_queues_retbuffer_mutex);
296   if (m_get_queues_return_buffer_addr == LLDB_INVALID_ADDRESS) {
297     addr_t bufaddr = process_sp->AllocateMemory(
298         32, ePermissionsReadable | ePermissionsWritable, error);
299     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
300       LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
301                      "current queues func call");
302       return return_value;
303     }
304     m_get_queues_return_buffer_addr = bufaddr;
305   }
306 
307   ValueList argument_values;
308 
309   return_buffer_ptr_value.GetScalar() = m_get_queues_return_buffer_addr;
310   argument_values.PushValue(return_buffer_ptr_value);
311 
312   debug_value.GetScalar() = 0;
313   argument_values.PushValue(debug_value);
314 
315   if (page_to_free != LLDB_INVALID_ADDRESS)
316     page_to_free_value.GetScalar() = page_to_free;
317   else
318     page_to_free_value.GetScalar() = 0;
319   argument_values.PushValue(page_to_free_value);
320 
321   page_to_free_size_value.GetScalar() = page_to_free_size;
322   argument_values.PushValue(page_to_free_size_value);
323 
324   addr_t args_addr = SetupGetQueuesFunction(thread, argument_values);
325 
326   if (!m_get_queues_impl_code_up) {
327     error.SetErrorString(
328         "Unable to compile __introspection_dispatch_get_queues.");
329     return return_value;
330   }
331 
332   FunctionCaller *get_queues_caller =
333       m_get_queues_impl_code_up->GetFunctionCaller();
334 
335   if (get_queues_caller == nullptr) {
336     error.SetErrorString(
337         "Unable to get caller for call __introspection_dispatch_get_queues");
338     return return_value;
339   }
340 
341   DiagnosticManager diagnostics;
342   ExecutionContext exe_ctx;
343   EvaluateExpressionOptions options;
344   options.SetUnwindOnError(true);
345   options.SetIgnoreBreakpoints(true);
346   options.SetStopOthers(true);
347 #if __has_feature(address_sanitizer)
348   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
349 #else
350   options.SetTimeout(std::chrono::milliseconds(500));
351 #endif
352   options.SetTryAllThreads(false);
353   options.SetIsForUtilityExpr(true);
354   thread.CalculateExecutionContext(exe_ctx);
355 
356   ExpressionResults func_call_ret;
357   Value results;
358   func_call_ret = get_queues_caller->ExecuteFunction(
359       exe_ctx, &args_addr, options, diagnostics, results);
360   if (func_call_ret != eExpressionCompleted || !error.Success()) {
361     LLDB_LOGF(log,
362               "Unable to call introspection_get_dispatch_queues(), got "
363               "ExpressionResults %d, error contains %s",
364               func_call_ret, error.AsCString(""));
365     error.SetErrorString("Unable to call introspection_get_dispatch_queues() "
366                          "for list of queues");
367     return return_value;
368   }
369 
370   return_value.queues_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
371       m_get_queues_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
372   if (!error.Success() ||
373       return_value.queues_buffer_ptr == LLDB_INVALID_ADDRESS) {
374     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
375     return return_value;
376   }
377 
378   return_value.queues_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
379       m_get_queues_return_buffer_addr + 8, 8, 0, error);
380 
381   if (!error.Success()) {
382     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
383     return return_value;
384   }
385 
386   return_value.count = m_process->ReadUnsignedIntegerFromMemory(
387       m_get_queues_return_buffer_addr + 16, 8, 0, error);
388   if (!error.Success()) {
389     return_value.queues_buffer_ptr = LLDB_INVALID_ADDRESS;
390     return return_value;
391   }
392 
393   LLDB_LOGF(log,
394             "AppleGetQueuesHandler called "
395             "__introspection_dispatch_get_queues (page_to_free == "
396             "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
397             ", size %" PRId64 ", count = %" PRId64,
398             page_to_free, page_to_free_size, return_value.queues_buffer_ptr,
399             return_value.queues_buffer_size, return_value.count);
400 
401   return return_value;
402 }
403