1 //===-- AppleGetItemInfoHandler.cpp -------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include "AppleGetItemInfoHandler.h"
12 
13 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/Value.h"
16 #include "lldb/Expression/DiagnosticManager.h"
17 #include "lldb/Expression/FunctionCaller.h"
18 #include "lldb/Expression/UtilityFunction.h"
19 #include "lldb/Symbol/ClangASTContext.h"
20 #include "lldb/Symbol/Symbol.h"
21 #include "lldb/Target/ExecutionContext.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/ConstString.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/StreamString.h"
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
32 const char *AppleGetItemInfoHandler::g_get_item_info_function_name =
33     "__lldb_backtrace_recording_get_item_info";
34 const char *AppleGetItemInfoHandler::g_get_item_info_function_code =
35     "                                  \n\
36 extern \"C\"                                                                                                    \n\
37 {                                                                                                               \n\
38     /*                                                                                                          \n\
39      * mach defines                                                                                             \n\
40      */                                                                                                         \n\
41                                                                                                                 \n\
42     typedef unsigned int uint32_t;                                                                              \n\
43     typedef unsigned long long uint64_t;                                                                        \n\
44     typedef uint32_t mach_port_t;                                                                               \n\
45     typedef mach_port_t vm_map_t;                                                                               \n\
46     typedef int kern_return_t;                                                                                  \n\
47     typedef uint64_t mach_vm_address_t;                                                                         \n\
48     typedef uint64_t mach_vm_size_t;                                                                            \n\
49                                                                                                                 \n\
50     mach_port_t mach_task_self ();                                                                              \n\
51     kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);         \n\
52                                                                                                                 \n\
53     /*                                                                                                          \n\
54      * libBacktraceRecording defines                                                                            \n\
55      */                                                                                                         \n\
56                                                                                                                 \n\
57     typedef uint32_t queue_list_scope_t;                                                                        \n\
58     typedef void *dispatch_queue_t;                                                                             \n\
59     typedef void *introspection_dispatch_queue_info_t;                                                          \n\
60     typedef void *introspection_dispatch_item_info_ref;                                                         \n\
61                                                                                                                 \n\
62     extern uint64_t __introspection_dispatch_queue_item_get_info (introspection_dispatch_item_info_ref item_info_ref, \n\
63                                                  introspection_dispatch_item_info_ref *returned_queues_buffer,  \n\
64                                                  uint64_t *returned_queues_buffer_size);                        \n\
65     extern int printf(const char *format, ...);                                                                 \n\
66                                                                                                                 \n\
67     /*                                                                                                          \n\
68      * return type define                                                                                       \n\
69      */                                                                                                         \n\
70                                                                                                                 \n\
71     struct get_item_info_return_values                                                                      \n\
72     {                                                                                                           \n\
73         uint64_t item_info_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */  \n\
74         uint64_t item_info_buffer_size;   /* the size of the items buffer from libBacktraceRecording */     \n\
75     };                                                                                                          \n\
76                                                                                                                 \n\
77     void  __lldb_backtrace_recording_get_item_info                                                          \n\
78                                                (struct get_item_info_return_values *return_buffer,          \n\
79                                                 int debug,                                                      \n\
80                                                 uint64_t /* introspection_dispatch_item_info_ref item_info_ref */ item, \n\
81                                                 void *page_to_free,                                             \n\
82                                                 uint64_t page_to_free_size)                                     \n\
83 {                                                                                                               \n\
84     if (debug)                                                                                                  \n\
85       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\
86     if (page_to_free != 0)                                                                                      \n\
87     {                                                                                                           \n\
88         mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
89     }                                                                                                           \n\
90                                                                                                                 \n\
91     __introspection_dispatch_queue_item_get_info ((void*) item,                                                 \n\
92                                                   (void**)&return_buffer->item_info_buffer_ptr,                 \n\
93                                                   &return_buffer->item_info_buffer_size);                       \n\
94 }                                                                                                               \n\
95 }                                                                                                               \n\
96 ";
97 
98 AppleGetItemInfoHandler::AppleGetItemInfoHandler(Process *process)
99     : m_process(process), m_get_item_info_impl_code(),
100       m_get_item_info_function_mutex(),
101       m_get_item_info_return_buffer_addr(LLDB_INVALID_ADDRESS),
102       m_get_item_info_retbuffer_mutex() {}
103 
104 AppleGetItemInfoHandler::~AppleGetItemInfoHandler() {}
105 
106 void AppleGetItemInfoHandler::Detach() {
107 
108   if (m_process && m_process->IsAlive() &&
109       m_get_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS) {
110     std::unique_lock<std::mutex> lock(m_get_item_info_retbuffer_mutex,
111                                       std::defer_lock);
112     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
113     m_process->DeallocateMemory(m_get_item_info_return_buffer_addr);
114   }
115 }
116 
117 // Compile our __lldb_backtrace_recording_get_item_info() function (from the
118 // source above in g_get_item_info_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_item_info into the inferior
123 // process if needed.
124 //
125 // Write the get_item_info_arglist into the inferior's memory space to prepare
126 // 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 AppleGetItemInfoHandler::SetupGetItemInfoFunction(
132     Thread &thread, ValueList &get_item_info_arglist) {
133   ExecutionContext exe_ctx(thread.shared_from_this());
134   DiagnosticManager diagnostics;
135   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
136   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
137   FunctionCaller *get_item_info_caller = nullptr;
138 
139   // Scope for mutex locker:
140   {
141     std::lock_guard<std::mutex> guard(m_get_item_info_function_mutex);
142 
143     // First stage is to make the UtilityFunction to hold our injected
144     // function:
145 
146     if (!m_get_item_info_impl_code.get()) {
147       if (g_get_item_info_function_code != NULL) {
148         Status error;
149         m_get_item_info_impl_code.reset(
150             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
151                 g_get_item_info_function_code, eLanguageTypeObjC,
152                 g_get_item_info_function_name, error));
153         if (error.Fail()) {
154           if (log)
155             log->Printf("Failed to get utility function: %s.",
156                         error.AsCString());
157           return args_addr;
158         }
159 
160         if (!m_get_item_info_impl_code->Install(diagnostics, exe_ctx)) {
161           if (log) {
162             log->Printf("Failed to install get-item-info introspection.");
163             diagnostics.Dump(log);
164           }
165           m_get_item_info_impl_code.reset();
166           return args_addr;
167         }
168       } else {
169         if (log)
170           log->Printf("No get-item-info introspection code found.");
171         return LLDB_INVALID_ADDRESS;
172       }
173 
174       // Next make the runner function for our implementation utility function.
175       Status error;
176 
177       TypeSystem *type_system =
178           thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage(
179               nullptr, eLanguageTypeC);
180       CompilerType get_item_info_return_type =
181           type_system->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
182 
183       get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller(
184           get_item_info_return_type, get_item_info_arglist,
185           thread.shared_from_this(), error);
186       if (error.Fail() || get_item_info_caller == nullptr) {
187         if (log)
188           log->Printf("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         if (log)
197           log->Printf("Failed to get get-item-info introspection caller.");
198         m_get_item_info_impl_code.reset();
199         return args_addr;
200       }
201     }
202   }
203 
204   diagnostics.Clear();
205 
206   // Now write down the argument values for this particular call.  This looks
207   // like it might be a race condition if other threads were calling into here,
208   // but actually it isn't because we allocate a new args structure for this
209   // call by passing args_addr = LLDB_INVALID_ADDRESS...
210 
211   if (!get_item_info_caller->WriteFunctionArguments(
212           exe_ctx, args_addr, get_item_info_arglist, diagnostics)) {
213     if (log) {
214       log->Printf("Error writing get-item-info function arguments.");
215       diagnostics.Dump(log);
216     }
217 
218     return args_addr;
219   }
220 
221   return args_addr;
222 }
223 
224 AppleGetItemInfoHandler::GetItemInfoReturnInfo
225 AppleGetItemInfoHandler::GetItemInfo(Thread &thread, uint64_t item,
226                                      addr_t page_to_free,
227                                      uint64_t page_to_free_size,
228                                      Status &error) {
229   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
230   ProcessSP process_sp(thread.CalculateProcess());
231   TargetSP target_sp(thread.CalculateTarget());
232   ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext();
233   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
234 
235   GetItemInfoReturnInfo return_value;
236   return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
237   return_value.item_buffer_size = 0;
238 
239   error.Clear();
240 
241   if (!thread.SafeToCallFunctions()) {
242     if (log)
243       log->Printf("Not safe to call functions on thread 0x%" PRIx64,
244                   thread.GetID());
245     error.SetErrorString("Not safe to call functions on this thread.");
246     return return_value;
247   }
248 
249   // Set up the arguments for a call to
250 
251   // struct get_item_info_return_values
252   // {
253   //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer
254   //     from libBacktraceRecording */
255   //     uint64_t item_info_buffer_size;   /* the size of the items buffer from
256   //     libBacktraceRecording */
257   // };
258   //
259   // void  __lldb_backtrace_recording_get_item_info
260   //                                            (struct
261   //                                            get_item_info_return_values
262   //                                            *return_buffer,
263   //                                             int debug,
264   //                                             uint64_t item,
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 item_value;
285   item_value.SetValueType(Value::eValueTypeScalar);
286   item_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_item_info_retbuffer_mutex);
297   if (m_get_item_info_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       if (log)
302         log->Printf("Failed to allocate memory for return buffer for get "
303                     "current queues func call");
304       return return_value;
305     }
306     m_get_item_info_return_buffer_addr = bufaddr;
307   }
308 
309   ValueList argument_values;
310 
311   return_buffer_ptr_value.GetScalar() = m_get_item_info_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   item_value.GetScalar() = item;
318   argument_values.PushValue(item_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 = SetupGetItemInfoFunction(thread, argument_values);
330 
331   DiagnosticManager diagnostics;
332   ExecutionContext exe_ctx;
333   EvaluateExpressionOptions options;
334   options.SetUnwindOnError(true);
335   options.SetIgnoreBreakpoints(true);
336   options.SetStopOthers(true);
337   options.SetTimeout(std::chrono::milliseconds(500));
338   options.SetTryAllThreads(false);
339   options.SetIsForUtilityExpr(true);
340   thread.CalculateExecutionContext(exe_ctx);
341 
342   if (!m_get_item_info_impl_code) {
343     error.SetErrorString("Unable to compile function to call "
344                          "__introspection_dispatch_queue_item_get_info");
345     return return_value;
346   }
347 
348   ExpressionResults func_call_ret;
349   Value results;
350   FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller();
351   if (!func_caller) {
352     if (log)
353       log->Printf("Could not retrieve function caller for "
354                   "__introspection_dispatch_queue_item_get_info.");
355     error.SetErrorString("Could not retrieve function caller for "
356                          "__introspection_dispatch_queue_item_get_info.");
357     return return_value;
358   }
359 
360   func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options,
361                                                diagnostics, results);
362   if (func_call_ret != eExpressionCompleted || !error.Success()) {
363     if (log)
364       log->Printf("Unable to call "
365                   "__introspection_dispatch_queue_item_get_info(), got "
366                   "ExpressionResults %d, error contains %s",
367                   func_call_ret, error.AsCString(""));
368     error.SetErrorString("Unable to call "
369                          "__introspection_dispatch_queue_get_item_info() for "
370                          "list of queues");
371     return return_value;
372   }
373 
374   return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
375       m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
376   if (!error.Success() ||
377       return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
378     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
379     return return_value;
380   }
381 
382   return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
383       m_get_item_info_return_buffer_addr + 8, 8, 0, error);
384 
385   if (!error.Success()) {
386     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
387     return return_value;
388   }
389   if (log)
390     log->Printf("AppleGetItemInfoHandler called "
391                 "__introspection_dispatch_queue_item_get_info (page_to_free == "
392                 "0x%" PRIx64 ", size = %" PRId64
393                 "), returned page is at 0x%" PRIx64 ", size %" PRId64,
394                 page_to_free, page_to_free_size, return_value.item_buffer_ptr,
395                 return_value.item_buffer_size);
396 
397   return return_value;
398 }
399