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