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