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