1 //===-- AppleGetItemInfoHandler.cpp -------------------------------*- C++
2 //-*-===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "AppleGetItemInfoHandler.h"
11 
12 
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/Value.h"
15 #include "lldb/Expression/DiagnosticManager.h"
16 #include "lldb/Expression/FunctionCaller.h"
17 #include "lldb/Expression/UtilityFunction.h"
18 #include "lldb/Symbol/ClangASTContext.h"
19 #include "lldb/Symbol/Symbol.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Utility/ConstString.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/StreamString.h"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 const char *AppleGetItemInfoHandler::g_get_item_info_function_name =
32     "__lldb_backtrace_recording_get_item_info";
33 const char *AppleGetItemInfoHandler::g_get_item_info_function_code =
34     "                                  \n\
35 extern \"C\"                                                                                                    \n\
36 {                                                                                                               \n\
37     /*                                                                                                          \n\
38      * mach defines                                                                                             \n\
39      */                                                                                                         \n\
40                                                                                                                 \n\
41     typedef unsigned int uint32_t;                                                                              \n\
42     typedef unsigned long long uint64_t;                                                                        \n\
43     typedef uint32_t mach_port_t;                                                                               \n\
44     typedef mach_port_t vm_map_t;                                                                               \n\
45     typedef int kern_return_t;                                                                                  \n\
46     typedef uint64_t mach_vm_address_t;                                                                         \n\
47     typedef uint64_t mach_vm_size_t;                                                                            \n\
48                                                                                                                 \n\
49     mach_port_t mach_task_self ();                                                                              \n\
50     kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);         \n\
51                                                                                                                 \n\
52     /*                                                                                                          \n\
53      * libBacktraceRecording defines                                                                            \n\
54      */                                                                                                         \n\
55                                                                                                                 \n\
56     typedef uint32_t queue_list_scope_t;                                                                        \n\
57     typedef void *dispatch_queue_t;                                                                             \n\
58     typedef void *introspection_dispatch_queue_info_t;                                                          \n\
59     typedef void *introspection_dispatch_item_info_ref;                                                         \n\
60                                                                                                                 \n\
61     extern uint64_t __introspection_dispatch_queue_item_get_info (introspection_dispatch_item_info_ref item_info_ref, \n\
62                                                  introspection_dispatch_item_info_ref *returned_queues_buffer,  \n\
63                                                  uint64_t *returned_queues_buffer_size);                        \n\
64     extern int printf(const char *format, ...);                                                                 \n\
65                                                                                                                 \n\
66     /*                                                                                                          \n\
67      * return type define                                                                                       \n\
68      */                                                                                                         \n\
69                                                                                                                 \n\
70     struct get_item_info_return_values                                                                      \n\
71     {                                                                                                           \n\
72         uint64_t item_info_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */  \n\
73         uint64_t item_info_buffer_size;   /* the size of the items buffer from libBacktraceRecording */     \n\
74     };                                                                                                          \n\
75                                                                                                                 \n\
76     void  __lldb_backtrace_recording_get_item_info                                                          \n\
77                                                (struct get_item_info_return_values *return_buffer,          \n\
78                                                 int debug,                                                      \n\
79                                                 uint64_t /* introspection_dispatch_item_info_ref item_info_ref */ item, \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_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\
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     __introspection_dispatch_queue_item_get_info ((void*) item,                                                 \n\
91                                                   (void**)&return_buffer->item_info_buffer_ptr,                 \n\
92                                                   &return_buffer->item_info_buffer_size);                       \n\
93 }                                                                                                               \n\
94 }                                                                                                               \n\
95 ";
96 
97 AppleGetItemInfoHandler::AppleGetItemInfoHandler(Process *process)
98     : m_process(process), m_get_item_info_impl_code(),
99       m_get_item_info_function_mutex(),
100       m_get_item_info_return_buffer_addr(LLDB_INVALID_ADDRESS),
101       m_get_item_info_retbuffer_mutex() {}
102 
103 AppleGetItemInfoHandler::~AppleGetItemInfoHandler() {}
104 
105 void AppleGetItemInfoHandler::Detach() {
106 
107   if (m_process && m_process->IsAlive() &&
108       m_get_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS) {
109     std::unique_lock<std::mutex> lock(m_get_item_info_retbuffer_mutex,
110                                       std::defer_lock);
111     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
112     m_process->DeallocateMemory(m_get_item_info_return_buffer_addr);
113   }
114 }
115 
116 // Compile our __lldb_backtrace_recording_get_item_info() function (from the
117 // source above in g_get_item_info_function_code) if we don't find that
118 // function in the inferior already with USE_BUILTIN_FUNCTION defined.  (e.g.
119 // this would be the case for testing.)
120 //
121 // Insert the __lldb_backtrace_recording_get_item_info into the inferior
122 // process if needed.
123 //
124 // Write the get_item_info_arglist into the inferior's memory space to prepare
125 // for the call.
126 //
127 // Returns the address of the arguments written down in the inferior process,
128 // which can be used to make the function call.
129 
130 lldb::addr_t AppleGetItemInfoHandler::SetupGetItemInfoFunction(
131     Thread &thread, ValueList &get_item_info_arglist) {
132   ExecutionContext exe_ctx(thread.shared_from_this());
133   DiagnosticManager diagnostics;
134   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
135   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
136   FunctionCaller *get_item_info_caller = nullptr;
137 
138   // Scope for mutex locker:
139   {
140     std::lock_guard<std::mutex> guard(m_get_item_info_function_mutex);
141 
142     // First stage is to make the UtilityFunction to hold our injected
143     // function:
144 
145     if (!m_get_item_info_impl_code) {
146       if (g_get_item_info_function_code != nullptr) {
147         Status error;
148         m_get_item_info_impl_code.reset(
149             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
150                 g_get_item_info_function_code, eLanguageTypeObjC,
151                 g_get_item_info_function_name, error));
152         if (error.Fail()) {
153           LLDB_LOGF(log, "Failed to get utility function: %s.",
154                     error.AsCString());
155           return args_addr;
156         }
157 
158         if (!m_get_item_info_impl_code->Install(diagnostics, exe_ctx)) {
159           if (log) {
160             LLDB_LOGF(log, "Failed to install get-item-info introspection.");
161             diagnostics.Dump(log);
162           }
163           m_get_item_info_impl_code.reset();
164           return args_addr;
165         }
166       } else {
167         LLDB_LOGF(log, "No get-item-info introspection code found.");
168         return LLDB_INVALID_ADDRESS;
169       }
170 
171       // Next make the runner function for our implementation utility function.
172       Status error;
173 
174       TypeSystem *type_system =
175           thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage(
176               nullptr, eLanguageTypeC);
177       CompilerType get_item_info_return_type =
178           type_system->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
179 
180       get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller(
181           get_item_info_return_type, get_item_info_arglist,
182           thread.shared_from_this(), error);
183       if (error.Fail() || get_item_info_caller == nullptr) {
184         LLDB_LOGF(log, "Error Inserting get-item-info function: \"%s\".",
185                   error.AsCString());
186         return args_addr;
187       }
188     } else {
189       // If it's already made, then we can just retrieve the caller:
190       get_item_info_caller = m_get_item_info_impl_code->GetFunctionCaller();
191       if (!get_item_info_caller) {
192         LLDB_LOGF(log, "Failed to get get-item-info introspection caller.");
193         m_get_item_info_impl_code.reset();
194         return args_addr;
195       }
196     }
197   }
198 
199   diagnostics.Clear();
200 
201   // Now write down the argument values for this particular call.  This looks
202   // like it might be a race condition if other threads were calling into here,
203   // but actually it isn't because we allocate a new args structure for this
204   // call by passing args_addr = LLDB_INVALID_ADDRESS...
205 
206   if (!get_item_info_caller->WriteFunctionArguments(
207           exe_ctx, args_addr, get_item_info_arglist, diagnostics)) {
208     if (log) {
209       LLDB_LOGF(log, "Error writing get-item-info function arguments.");
210       diagnostics.Dump(log);
211     }
212 
213     return args_addr;
214   }
215 
216   return args_addr;
217 }
218 
219 AppleGetItemInfoHandler::GetItemInfoReturnInfo
220 AppleGetItemInfoHandler::GetItemInfo(Thread &thread, uint64_t item,
221                                      addr_t page_to_free,
222                                      uint64_t page_to_free_size,
223                                      Status &error) {
224   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
225   ProcessSP process_sp(thread.CalculateProcess());
226   TargetSP target_sp(thread.CalculateTarget());
227   ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
228   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
229 
230   GetItemInfoReturnInfo return_value;
231   return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
232   return_value.item_buffer_size = 0;
233 
234   error.Clear();
235 
236   if (!thread.SafeToCallFunctions()) {
237     LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
238               thread.GetID());
239     error.SetErrorString("Not safe to call functions on this thread.");
240     return return_value;
241   }
242 
243   // Set up the arguments for a call to
244 
245   // struct get_item_info_return_values
246   // {
247   //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer
248   //     from libBacktraceRecording */
249   //     uint64_t item_info_buffer_size;   /* the size of the items buffer from
250   //     libBacktraceRecording */
251   // };
252   //
253   // void  __lldb_backtrace_recording_get_item_info
254   //                                            (struct
255   //                                            get_item_info_return_values
256   //                                            *return_buffer,
257   //                                             int debug,
258   //                                             uint64_t item,
259   //                                             void *page_to_free,
260   //                                             uint64_t page_to_free_size)
261 
262   // Where the return_buffer argument points to a 24 byte region of memory
263   // already allocated by lldb in the inferior process.
264 
265   CompilerType clang_void_ptr_type =
266       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
267   Value return_buffer_ptr_value;
268   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
269   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
270 
271   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
272   Value debug_value;
273   debug_value.SetValueType(Value::eValueTypeScalar);
274   debug_value.SetCompilerType(clang_int_type);
275 
276   CompilerType clang_uint64_type =
277       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
278   Value item_value;
279   item_value.SetValueType(Value::eValueTypeScalar);
280   item_value.SetCompilerType(clang_uint64_type);
281 
282   Value page_to_free_value;
283   page_to_free_value.SetValueType(Value::eValueTypeScalar);
284   page_to_free_value.SetCompilerType(clang_void_ptr_type);
285 
286   Value page_to_free_size_value;
287   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
288   page_to_free_size_value.SetCompilerType(clang_uint64_type);
289 
290   std::lock_guard<std::mutex> guard(m_get_item_info_retbuffer_mutex);
291   if (m_get_item_info_return_buffer_addr == LLDB_INVALID_ADDRESS) {
292     addr_t bufaddr = process_sp->AllocateMemory(
293         32, ePermissionsReadable | ePermissionsWritable, error);
294     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
295       LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
296                      "current queues func call");
297       return return_value;
298     }
299     m_get_item_info_return_buffer_addr = bufaddr;
300   }
301 
302   ValueList argument_values;
303 
304   return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr;
305   argument_values.PushValue(return_buffer_ptr_value);
306 
307   debug_value.GetScalar() = 0;
308   argument_values.PushValue(debug_value);
309 
310   item_value.GetScalar() = item;
311   argument_values.PushValue(item_value);
312 
313   if (page_to_free != LLDB_INVALID_ADDRESS)
314     page_to_free_value.GetScalar() = page_to_free;
315   else
316     page_to_free_value.GetScalar() = 0;
317   argument_values.PushValue(page_to_free_value);
318 
319   page_to_free_size_value.GetScalar() = page_to_free_size;
320   argument_values.PushValue(page_to_free_size_value);
321 
322   addr_t args_addr = SetupGetItemInfoFunction(thread, argument_values);
323 
324   DiagnosticManager diagnostics;
325   ExecutionContext exe_ctx;
326   EvaluateExpressionOptions options;
327   options.SetUnwindOnError(true);
328   options.SetIgnoreBreakpoints(true);
329   options.SetStopOthers(true);
330   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
331   options.SetTryAllThreads(false);
332   options.SetIsForUtilityExpr(true);
333   thread.CalculateExecutionContext(exe_ctx);
334 
335   if (!m_get_item_info_impl_code) {
336     error.SetErrorString("Unable to compile function to call "
337                          "__introspection_dispatch_queue_item_get_info");
338     return return_value;
339   }
340 
341   ExpressionResults func_call_ret;
342   Value results;
343   FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller();
344   if (!func_caller) {
345     LLDB_LOGF(log, "Could not retrieve function caller for "
346                    "__introspection_dispatch_queue_item_get_info.");
347     error.SetErrorString("Could not retrieve function caller for "
348                          "__introspection_dispatch_queue_item_get_info.");
349     return return_value;
350   }
351 
352   func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options,
353                                                diagnostics, results);
354   if (func_call_ret != eExpressionCompleted || !error.Success()) {
355     LLDB_LOGF(log,
356               "Unable to call "
357               "__introspection_dispatch_queue_item_get_info(), got "
358               "ExpressionResults %d, error contains %s",
359               func_call_ret, error.AsCString(""));
360     error.SetErrorString("Unable to call "
361                          "__introspection_dispatch_queue_get_item_info() for "
362                          "list of queues");
363     return return_value;
364   }
365 
366   return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
367       m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
368   if (!error.Success() ||
369       return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
370     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
371     return return_value;
372   }
373 
374   return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
375       m_get_item_info_return_buffer_addr + 8, 8, 0, error);
376 
377   if (!error.Success()) {
378     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
379     return return_value;
380   }
381   LLDB_LOGF(log,
382             "AppleGetItemInfoHandler called "
383             "__introspection_dispatch_queue_item_get_info (page_to_free == "
384             "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
385             ", size %" PRId64,
386             page_to_free, page_to_free_size, return_value.item_buffer_ptr,
387             return_value.item_buffer_size);
388 
389   return return_value;
390 }
391