1 //===-- AppleGetThreadItemInfoHandler.cpp ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "AppleGetThreadItemInfoHandler.h"
10 
11 
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/Value.h"
14 #include "lldb/Expression/DiagnosticManager.h"
15 #include "lldb/Expression/Expression.h"
16 #include "lldb/Expression/FunctionCaller.h"
17 #include "lldb/Expression/UtilityFunction.h"
18 #include "lldb/Symbol/TypeSystemClang.h"
19 #include "lldb/Symbol/Symbol.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/StackFrame.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 #include "lldb/lldb-private.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 const char
34     *AppleGetThreadItemInfoHandler::g_get_thread_item_info_function_name =
35         "__lldb_backtrace_recording_get_thread_item_info";
36 const char
37     *AppleGetThreadItemInfoHandler::g_get_thread_item_info_function_code =
38         "                                  \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), m_get_thread_item_info_impl_code(),
107       m_get_thread_item_info_function_mutex(),
108       m_get_thread_item_info_return_buffer_addr(LLDB_INVALID_ADDRESS),
109       m_get_thread_item_info_retbuffer_mutex() {}
110 
111 AppleGetThreadItemInfoHandler::~AppleGetThreadItemInfoHandler() {}
112 
113 void AppleGetThreadItemInfoHandler::Detach() {
114 
115   if (m_process && m_process->IsAlive() &&
116       m_get_thread_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS) {
117     std::unique_lock<std::mutex> lock(m_get_thread_item_info_retbuffer_mutex,
118                                       std::defer_lock);
119     lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
120     m_process->DeallocateMemory(m_get_thread_item_info_return_buffer_addr);
121   }
122 }
123 
124 // Compile our __lldb_backtrace_recording_get_thread_item_info() function (from
125 // the source above in g_get_thread_item_info_function_code) if we don't find
126 // that function in the inferior already with USE_BUILTIN_FUNCTION defined.
127 // (e.g. this would be the case for testing.)
128 //
129 // Insert the __lldb_backtrace_recording_get_thread_item_info into the inferior
130 // process if needed.
131 //
132 // Write the get_thread_item_info_arglist into the inferior's memory space to
133 // prepare for the call.
134 //
135 // Returns the address of the arguments written down in the inferior process,
136 // which can be used to make the function call.
137 
138 lldb::addr_t AppleGetThreadItemInfoHandler::SetupGetThreadItemInfoFunction(
139     Thread &thread, ValueList &get_thread_item_info_arglist) {
140   ThreadSP thread_sp(thread.shared_from_this());
141   ExecutionContext exe_ctx(thread_sp);
142   Address impl_code_address;
143   DiagnosticManager diagnostics;
144   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
145   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
146   FunctionCaller *get_thread_item_info_caller = nullptr;
147 
148   // Scope for mutex locker:
149   {
150     std::lock_guard<std::mutex> guard(m_get_thread_item_info_function_mutex);
151 
152     // First stage is to make the ClangUtility to hold our injected function:
153 
154     if (!m_get_thread_item_info_impl_code) {
155       Status error;
156       if (g_get_thread_item_info_function_code != nullptr) {
157         m_get_thread_item_info_impl_code.reset(
158             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
159                 g_get_thread_item_info_function_code, eLanguageTypeC,
160                 g_get_thread_item_info_function_name, error));
161         if (error.Fail()) {
162           LLDB_LOGF(log,
163                     "Failed to get UtilityFunction for "
164                     "get-thread-item-info introspection: %s.",
165                     error.AsCString());
166           m_get_thread_item_info_impl_code.reset();
167           return args_addr;
168         }
169 
170         if (!m_get_thread_item_info_impl_code->Install(diagnostics, exe_ctx)) {
171           if (log) {
172             LLDB_LOGF(log,
173                       "Failed to install get-thread-item-info introspection.");
174             diagnostics.Dump(log);
175           }
176 
177           m_get_thread_item_info_impl_code.reset();
178           return args_addr;
179         }
180       } else {
181         LLDB_LOGF(log, "No get-thread-item-info introspection code found.");
182         return LLDB_INVALID_ADDRESS;
183       }
184 
185       // Also make the FunctionCaller for this UtilityFunction:
186 
187       TypeSystemClang *clang_ast_context =
188           TypeSystemClang::GetScratch(thread.GetProcess()->GetTarget());
189       CompilerType get_thread_item_info_return_type =
190           clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
191 
192       get_thread_item_info_caller =
193           m_get_thread_item_info_impl_code->MakeFunctionCaller(
194               get_thread_item_info_return_type, get_thread_item_info_arglist,
195               thread_sp, error);
196       if (error.Fail() || get_thread_item_info_caller == nullptr) {
197         LLDB_LOGF(log,
198                   "Failed to install get-thread-item-info introspection "
199                   "caller: %s.",
200                   error.AsCString());
201         m_get_thread_item_info_impl_code.reset();
202         return args_addr;
203       }
204 
205     } else {
206       get_thread_item_info_caller =
207           m_get_thread_item_info_impl_code->GetFunctionCaller();
208     }
209   }
210 
211   diagnostics.Clear();
212 
213   // Now write down the argument values for this particular call.  This looks
214   // like it might be a race condition if other threads were calling into here,
215   // but actually it isn't because we allocate a new args structure for this
216   // call by passing args_addr = LLDB_INVALID_ADDRESS...
217 
218   if (!get_thread_item_info_caller->WriteFunctionArguments(
219           exe_ctx, args_addr, get_thread_item_info_arglist, diagnostics)) {
220     if (log) {
221       LLDB_LOGF(log, "Error writing get-thread-item-info function arguments");
222       diagnostics.Dump(log);
223     }
224     return args_addr;
225   }
226 
227   return args_addr;
228 }
229 
230 AppleGetThreadItemInfoHandler::GetThreadItemInfoReturnInfo
231 AppleGetThreadItemInfoHandler::GetThreadItemInfo(Thread &thread,
232                                                  tid_t thread_id,
233                                                  addr_t page_to_free,
234                                                  uint64_t page_to_free_size,
235                                                  Status &error) {
236   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
237   ProcessSP process_sp(thread.CalculateProcess());
238   TargetSP target_sp(thread.CalculateTarget());
239   TypeSystemClang *clang_ast_context = TypeSystemClang::GetScratch(*target_sp);
240   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
241 
242   GetThreadItemInfoReturnInfo return_value;
243   return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
244   return_value.item_buffer_size = 0;
245 
246   error.Clear();
247 
248   if (!thread.SafeToCallFunctions()) {
249     LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
250               thread.GetID());
251     error.SetErrorString("Not safe to call functions on this thread.");
252     return return_value;
253   }
254 
255   // Set up the arguments for a call to
256 
257   // struct get_thread_item_info_return_values {
258   //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer
259   //     from libBacktraceRecording */
260   //     uint64_t item_info_buffer_size;   /* the size of the items buffer from
261   //     libBacktraceRecording */
262   // };
263   //
264   // void  __lldb_backtrace_recording_get_thread_item_info
265   //                                            (struct
266   //                                            get_thread_item_info_return_values
267   //                                            *return_buffer,
268   //                                             int debug,
269   //                                             void *page_to_free,
270   //                                             uint64_t page_to_free_size)
271 
272   // Where the return_buffer argument points to a 24 byte region of memory
273   // already allocated by lldb in the inferior process.
274 
275   CompilerType clang_void_ptr_type =
276       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
277   Value return_buffer_ptr_value;
278   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
279   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
280 
281   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
282   Value debug_value;
283   debug_value.SetValueType(Value::eValueTypeScalar);
284   debug_value.SetCompilerType(clang_int_type);
285 
286   CompilerType clang_uint64_type =
287       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
288   Value thread_id_value;
289   thread_id_value.SetValueType(Value::eValueTypeScalar);
290   thread_id_value.SetCompilerType(clang_uint64_type);
291 
292   Value page_to_free_value;
293   page_to_free_value.SetValueType(Value::eValueTypeScalar);
294   page_to_free_value.SetCompilerType(clang_void_ptr_type);
295 
296   Value page_to_free_size_value;
297   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
298   page_to_free_size_value.SetCompilerType(clang_uint64_type);
299 
300   std::lock_guard<std::mutex> guard(m_get_thread_item_info_retbuffer_mutex);
301   if (m_get_thread_item_info_return_buffer_addr == LLDB_INVALID_ADDRESS) {
302     addr_t bufaddr = process_sp->AllocateMemory(
303         32, ePermissionsReadable | ePermissionsWritable, error);
304     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
305       LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
306                      "current queues func call");
307       return return_value;
308     }
309     m_get_thread_item_info_return_buffer_addr = bufaddr;
310   }
311 
312   ValueList argument_values;
313 
314   return_buffer_ptr_value.GetScalar() =
315       m_get_thread_item_info_return_buffer_addr;
316   argument_values.PushValue(return_buffer_ptr_value);
317 
318   debug_value.GetScalar() = 0;
319   argument_values.PushValue(debug_value);
320 
321   thread_id_value.GetScalar() = thread_id;
322   argument_values.PushValue(thread_id_value);
323 
324   if (page_to_free != LLDB_INVALID_ADDRESS)
325     page_to_free_value.GetScalar() = page_to_free;
326   else
327     page_to_free_value.GetScalar() = 0;
328   argument_values.PushValue(page_to_free_value);
329 
330   page_to_free_size_value.GetScalar() = page_to_free_size;
331   argument_values.PushValue(page_to_free_size_value);
332 
333   addr_t args_addr = SetupGetThreadItemInfoFunction(thread, argument_values);
334 
335   DiagnosticManager diagnostics;
336   ExecutionContext exe_ctx;
337   EvaluateExpressionOptions options;
338   FunctionCaller *get_thread_item_info_caller = nullptr;
339 
340   options.SetUnwindOnError(true);
341   options.SetIgnoreBreakpoints(true);
342   options.SetStopOthers(true);
343 #if __has_feature(address_sanitizer)
344   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
345 #else
346   options.SetTimeout(std::chrono::milliseconds(500));
347 #endif
348   options.SetTryAllThreads(false);
349   options.SetIsForUtilityExpr(true);
350   thread.CalculateExecutionContext(exe_ctx);
351 
352   if (!m_get_thread_item_info_impl_code) {
353     error.SetErrorString("Unable to compile function to call "
354                          "__introspection_dispatch_thread_get_item_info");
355     return return_value;
356   }
357 
358   get_thread_item_info_caller =
359       m_get_thread_item_info_impl_code->GetFunctionCaller();
360 
361   if (!get_thread_item_info_caller) {
362     error.SetErrorString("Unable to compile function caller for "
363                          "__introspection_dispatch_thread_get_item_info");
364     return return_value;
365   }
366 
367   ExpressionResults func_call_ret;
368   Value results;
369   func_call_ret = get_thread_item_info_caller->ExecuteFunction(
370       exe_ctx, &args_addr, options, diagnostics, results);
371   if (func_call_ret != eExpressionCompleted || !error.Success()) {
372     LLDB_LOGF(log,
373               "Unable to call "
374               "__introspection_dispatch_thread_get_item_info(), got "
375               "ExpressionResults %d, error contains %s",
376               func_call_ret, error.AsCString(""));
377     error.SetErrorString("Unable to call "
378                          "__introspection_dispatch_thread_get_item_info() for "
379                          "list of queues");
380     return return_value;
381   }
382 
383   return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
384       m_get_thread_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS,
385       error);
386   if (!error.Success() ||
387       return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
388     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
389     return return_value;
390   }
391 
392   return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
393       m_get_thread_item_info_return_buffer_addr + 8, 8, 0, error);
394 
395   if (!error.Success()) {
396     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
397     return return_value;
398   }
399 
400   LLDB_LOGF(log,
401             "AppleGetThreadItemInfoHandler called "
402             "__introspection_dispatch_thread_get_item_info (page_to_free "
403             "== 0x%" PRIx64 ", size = %" PRId64
404             "), returned page is at 0x%" PRIx64 ", size %" PRId64,
405             page_to_free, page_to_free_size, return_value.item_buffer_ptr,
406             return_value.item_buffer_size);
407 
408   return return_value;
409 }
410