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