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