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