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