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