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 != NULL) { 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 if (log) 154 log->Printf("Failed to get utility function: %s.", 155 error.AsCString()); 156 return args_addr; 157 } 158 159 if (!m_get_item_info_impl_code->Install(diagnostics, exe_ctx)) { 160 if (log) { 161 log->Printf("Failed to install get-item-info introspection."); 162 diagnostics.Dump(log); 163 } 164 m_get_item_info_impl_code.reset(); 165 return args_addr; 166 } 167 } else { 168 if (log) 169 log->Printf("No get-item-info introspection code found."); 170 return LLDB_INVALID_ADDRESS; 171 } 172 173 // Next make the runner function for our implementation utility function. 174 Status error; 175 176 TypeSystem *type_system = 177 thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage( 178 nullptr, eLanguageTypeC); 179 CompilerType get_item_info_return_type = 180 type_system->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType(); 181 182 get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller( 183 get_item_info_return_type, get_item_info_arglist, 184 thread.shared_from_this(), error); 185 if (error.Fail() || get_item_info_caller == nullptr) { 186 if (log) 187 log->Printf("Error Inserting get-item-info function: \"%s\".", 188 error.AsCString()); 189 return args_addr; 190 } 191 } else { 192 // If it's already made, then we can just retrieve the caller: 193 get_item_info_caller = m_get_item_info_impl_code->GetFunctionCaller(); 194 if (!get_item_info_caller) { 195 if (log) 196 log->Printf("Failed to get get-item-info introspection caller."); 197 m_get_item_info_impl_code.reset(); 198 return args_addr; 199 } 200 } 201 } 202 203 diagnostics.Clear(); 204 205 // Now write down the argument values for this particular call. This looks 206 // like it might be a race condition if other threads were calling into here, 207 // but actually it isn't because we allocate a new args structure for this 208 // call by passing args_addr = LLDB_INVALID_ADDRESS... 209 210 if (!get_item_info_caller->WriteFunctionArguments( 211 exe_ctx, args_addr, get_item_info_arglist, diagnostics)) { 212 if (log) { 213 log->Printf("Error writing get-item-info function arguments."); 214 diagnostics.Dump(log); 215 } 216 217 return args_addr; 218 } 219 220 return args_addr; 221 } 222 223 AppleGetItemInfoHandler::GetItemInfoReturnInfo 224 AppleGetItemInfoHandler::GetItemInfo(Thread &thread, uint64_t item, 225 addr_t page_to_free, 226 uint64_t page_to_free_size, 227 Status &error) { 228 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0); 229 ProcessSP process_sp(thread.CalculateProcess()); 230 TargetSP target_sp(thread.CalculateTarget()); 231 ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext(); 232 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME)); 233 234 GetItemInfoReturnInfo return_value; 235 return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS; 236 return_value.item_buffer_size = 0; 237 238 error.Clear(); 239 240 if (!thread.SafeToCallFunctions()) { 241 if (log) 242 log->Printf("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 if (log) 301 log->Printf("Failed to allocate memory for return buffer for get " 302 "current queues func call"); 303 return return_value; 304 } 305 m_get_item_info_return_buffer_addr = bufaddr; 306 } 307 308 ValueList argument_values; 309 310 return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr; 311 argument_values.PushValue(return_buffer_ptr_value); 312 313 debug_value.GetScalar() = 0; 314 argument_values.PushValue(debug_value); 315 316 item_value.GetScalar() = item; 317 argument_values.PushValue(item_value); 318 319 if (page_to_free != LLDB_INVALID_ADDRESS) 320 page_to_free_value.GetScalar() = page_to_free; 321 else 322 page_to_free_value.GetScalar() = 0; 323 argument_values.PushValue(page_to_free_value); 324 325 page_to_free_size_value.GetScalar() = page_to_free_size; 326 argument_values.PushValue(page_to_free_size_value); 327 328 addr_t args_addr = SetupGetItemInfoFunction(thread, argument_values); 329 330 DiagnosticManager diagnostics; 331 ExecutionContext exe_ctx; 332 EvaluateExpressionOptions options; 333 options.SetUnwindOnError(true); 334 options.SetIgnoreBreakpoints(true); 335 options.SetStopOthers(true); 336 options.SetTimeout(process_sp->GetUtilityExpressionTimeout()); 337 options.SetTryAllThreads(false); 338 options.SetIsForUtilityExpr(true); 339 thread.CalculateExecutionContext(exe_ctx); 340 341 if (!m_get_item_info_impl_code) { 342 error.SetErrorString("Unable to compile function to call " 343 "__introspection_dispatch_queue_item_get_info"); 344 return return_value; 345 } 346 347 ExpressionResults func_call_ret; 348 Value results; 349 FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller(); 350 if (!func_caller) { 351 if (log) 352 log->Printf("Could not retrieve function caller for " 353 "__introspection_dispatch_queue_item_get_info."); 354 error.SetErrorString("Could not retrieve function caller for " 355 "__introspection_dispatch_queue_item_get_info."); 356 return return_value; 357 } 358 359 func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options, 360 diagnostics, results); 361 if (func_call_ret != eExpressionCompleted || !error.Success()) { 362 if (log) 363 log->Printf("Unable to call " 364 "__introspection_dispatch_queue_item_get_info(), got " 365 "ExpressionResults %d, error contains %s", 366 func_call_ret, error.AsCString("")); 367 error.SetErrorString("Unable to call " 368 "__introspection_dispatch_queue_get_item_info() for " 369 "list of queues"); 370 return return_value; 371 } 372 373 return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory( 374 m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error); 375 if (!error.Success() || 376 return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) { 377 return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS; 378 return return_value; 379 } 380 381 return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory( 382 m_get_item_info_return_buffer_addr + 8, 8, 0, error); 383 384 if (!error.Success()) { 385 return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS; 386 return return_value; 387 } 388 if (log) 389 log->Printf("AppleGetItemInfoHandler called " 390 "__introspection_dispatch_queue_item_get_info (page_to_free == " 391 "0x%" PRIx64 ", size = %" PRId64 392 "), returned page is at 0x%" PRIx64 ", size %" PRId64, 393 page_to_free, page_to_free_size, return_value.item_buffer_ptr, 394 return_value.item_buffer_size); 395 396 return return_value; 397 } 398