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