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 
9 #include "AppleGetItemInfoHandler.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 *AppleGetItemInfoHandler::g_get_item_info_function_name =
31     "__lldb_backtrace_recording_get_item_info";
32 const char *AppleGetItemInfoHandler::g_get_item_info_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_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 
96 AppleGetItemInfoHandler::AppleGetItemInfoHandler(Process *process)
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 
102 AppleGetItemInfoHandler::~AppleGetItemInfoHandler() {}
103 
104 void AppleGetItemInfoHandler::Detach() {
105 
106   if (m_process && m_process->IsAlive() &&
107       m_get_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS) {
108     std::unique_lock<std::mutex> lock(m_get_item_info_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_item_info_return_buffer_addr);
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 
129 lldb::addr_t AppleGetItemInfoHandler::SetupGetItemInfoFunction(
130     Thread &thread, ValueList &get_item_info_arglist) {
131   ExecutionContext exe_ctx(thread.shared_from_this());
132   DiagnosticManager diagnostics;
133   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
134   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
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 
144     if (!m_get_item_info_impl_code) {
145       if (g_get_item_info_function_code != nullptr) {
146         Status error;
147         m_get_item_info_impl_code.reset(
148             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
149                 g_get_item_info_function_code, eLanguageTypeObjC,
150                 g_get_item_info_function_name, error));
151         if (error.Fail()) {
152           LLDB_LOGF(log, "Failed to get utility function: %s.",
153                     error.AsCString());
154           return args_addr;
155         }
156 
157         if (!m_get_item_info_impl_code->Install(diagnostics, exe_ctx)) {
158           if (log) {
159             LLDB_LOGF(log, "Failed to install get-item-info introspection.");
160             diagnostics.Dump(log);
161           }
162           m_get_item_info_impl_code.reset();
163           return args_addr;
164         }
165       } else {
166         LLDB_LOGF(log, "No get-item-info introspection code found.");
167         return LLDB_INVALID_ADDRESS;
168       }
169 
170       // Next make the runner function for our implementation utility function.
171       auto type_system_or_err =
172           thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage(
173               eLanguageTypeC);
174       if (auto err = type_system_or_err.takeError()) {
175         LLDB_LOG_ERROR(log, std::move(err),
176                        "Error inseting get-item-info function");
177         return args_addr;
178       }
179       CompilerType get_item_info_return_type =
180           type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid)
181               .GetPointerType();
182 
183       Status error;
184       get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller(
185           get_item_info_return_type, get_item_info_arglist,
186           thread.shared_from_this(), error);
187       if (error.Fail() || get_item_info_caller == nullptr) {
188         LLDB_LOGF(log, "Error Inserting get-item-info function: \"%s\".",
189                   error.AsCString());
190         return args_addr;
191       }
192     } else {
193       // If it's already made, then we can just retrieve the caller:
194       get_item_info_caller = m_get_item_info_impl_code->GetFunctionCaller();
195       if (!get_item_info_caller) {
196         LLDB_LOGF(log, "Failed to get get-item-info introspection caller.");
197         m_get_item_info_impl_code.reset();
198         return args_addr;
199       }
200     }
201   }
202 
203   diagnostics.Clear();
204 
205   // Now write down the argument values for this particular call.  This looks
206   // like it might be a race condition if other threads were calling into here,
207   // but actually it isn't because we allocate a new args structure for this
208   // call by passing args_addr = LLDB_INVALID_ADDRESS...
209 
210   if (!get_item_info_caller->WriteFunctionArguments(
211           exe_ctx, args_addr, get_item_info_arglist, diagnostics)) {
212     if (log) {
213       LLDB_LOGF(log, "Error writing get-item-info function arguments.");
214       diagnostics.Dump(log);
215     }
216 
217     return args_addr;
218   }
219 
220   return args_addr;
221 }
222 
223 AppleGetItemInfoHandler::GetItemInfoReturnInfo
224 AppleGetItemInfoHandler::GetItemInfo(Thread &thread, uint64_t item,
225                                      addr_t page_to_free,
226                                      uint64_t page_to_free_size,
227                                      Status &error) {
228   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
229   ProcessSP process_sp(thread.CalculateProcess());
230   TargetSP target_sp(thread.CalculateTarget());
231   TypeSystemClang *clang_ast_context = TypeSystemClang::GetScratch(*target_sp);
232   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
233 
234   GetItemInfoReturnInfo return_value;
235   return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
236   return_value.item_buffer_size = 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_item_info_return_values
250   // {
251   //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer
252   //     from libBacktraceRecording */
253   //     uint64_t item_info_buffer_size;   /* the size of the items buffer from
254   //     libBacktraceRecording */
255   // };
256   //
257   // void  __lldb_backtrace_recording_get_item_info
258   //                                            (struct
259   //                                            get_item_info_return_values
260   //                                            *return_buffer,
261   //                                             int debug,
262   //                                             uint64_t item,
263   //                                             void *page_to_free,
264   //                                             uint64_t page_to_free_size)
265 
266   // Where the return_buffer argument points to a 24 byte region of memory
267   // already allocated by lldb in the inferior process.
268 
269   CompilerType clang_void_ptr_type =
270       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
271   Value return_buffer_ptr_value;
272   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
273   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
274 
275   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
276   Value debug_value;
277   debug_value.SetValueType(Value::eValueTypeScalar);
278   debug_value.SetCompilerType(clang_int_type);
279 
280   CompilerType clang_uint64_type =
281       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
282   Value item_value;
283   item_value.SetValueType(Value::eValueTypeScalar);
284   item_value.SetCompilerType(clang_uint64_type);
285 
286   Value page_to_free_value;
287   page_to_free_value.SetValueType(Value::eValueTypeScalar);
288   page_to_free_value.SetCompilerType(clang_void_ptr_type);
289 
290   Value page_to_free_size_value;
291   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
292   page_to_free_size_value.SetCompilerType(clang_uint64_type);
293 
294   std::lock_guard<std::mutex> guard(m_get_item_info_retbuffer_mutex);
295   if (m_get_item_info_return_buffer_addr == LLDB_INVALID_ADDRESS) {
296     addr_t bufaddr = process_sp->AllocateMemory(
297         32, ePermissionsReadable | ePermissionsWritable, error);
298     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
299       LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
300                      "current queues func call");
301       return return_value;
302     }
303     m_get_item_info_return_buffer_addr = bufaddr;
304   }
305 
306   ValueList argument_values;
307 
308   return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr;
309   argument_values.PushValue(return_buffer_ptr_value);
310 
311   debug_value.GetScalar() = 0;
312   argument_values.PushValue(debug_value);
313 
314   item_value.GetScalar() = item;
315   argument_values.PushValue(item_value);
316 
317   if (page_to_free != LLDB_INVALID_ADDRESS)
318     page_to_free_value.GetScalar() = page_to_free;
319   else
320     page_to_free_value.GetScalar() = 0;
321   argument_values.PushValue(page_to_free_value);
322 
323   page_to_free_size_value.GetScalar() = page_to_free_size;
324   argument_values.PushValue(page_to_free_size_value);
325 
326   addr_t args_addr = SetupGetItemInfoFunction(thread, argument_values);
327 
328   DiagnosticManager diagnostics;
329   ExecutionContext exe_ctx;
330   EvaluateExpressionOptions options;
331   options.SetUnwindOnError(true);
332   options.SetIgnoreBreakpoints(true);
333   options.SetStopOthers(true);
334 #if __has_feature(address_sanitizer)
335   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
336 #else
337   options.SetTimeout(std::chrono::milliseconds(500));
338 #endif
339   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
340   options.SetTryAllThreads(false);
341   options.SetIsForUtilityExpr(true);
342   thread.CalculateExecutionContext(exe_ctx);
343 
344   if (!m_get_item_info_impl_code) {
345     error.SetErrorString("Unable to compile function to call "
346                          "__introspection_dispatch_queue_item_get_info");
347     return return_value;
348   }
349 
350   ExpressionResults func_call_ret;
351   Value results;
352   FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller();
353   if (!func_caller) {
354     LLDB_LOGF(log, "Could not retrieve function caller for "
355                    "__introspection_dispatch_queue_item_get_info.");
356     error.SetErrorString("Could not retrieve function caller for "
357                          "__introspection_dispatch_queue_item_get_info.");
358     return return_value;
359   }
360 
361   func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options,
362                                                diagnostics, results);
363   if (func_call_ret != eExpressionCompleted || !error.Success()) {
364     LLDB_LOGF(log,
365               "Unable to call "
366               "__introspection_dispatch_queue_item_get_info(), got "
367               "ExpressionResults %d, error contains %s",
368               func_call_ret, error.AsCString(""));
369     error.SetErrorString("Unable to call "
370                          "__introspection_dispatch_queue_get_item_info() for "
371                          "list of queues");
372     return return_value;
373   }
374 
375   return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
376       m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
377   if (!error.Success() ||
378       return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
379     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
380     return return_value;
381   }
382 
383   return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
384       m_get_item_info_return_buffer_addr + 8, 8, 0, error);
385 
386   if (!error.Success()) {
387     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
388     return return_value;
389   }
390   LLDB_LOGF(log,
391             "AppleGetItemInfoHandler called "
392             "__introspection_dispatch_queue_item_get_info (page_to_free == "
393             "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
394             ", size %" PRId64,
395             page_to_free, page_to_free_size, return_value.item_buffer_ptr,
396             return_value.item_buffer_size);
397 
398   return return_value;
399 }
400