| 1 | //===-- FunctionCaller.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 "lldb/Expression/FunctionCaller.h" |
| 10 | #include "lldb/Core/Module.h" |
| 11 | #include "lldb/Core/Progress.h" |
| 12 | #include "lldb/Expression/DiagnosticManager.h" |
| 13 | #include "lldb/Expression/IRExecutionUnit.h" |
| 14 | #include "lldb/Interpreter/CommandReturnObject.h" |
| 15 | #include "lldb/Symbol/Function.h" |
| 16 | #include "lldb/Symbol/Type.h" |
| 17 | #include "lldb/Target/ExecutionContext.h" |
| 18 | #include "lldb/Target/Process.h" |
| 19 | #include "lldb/Target/RegisterContext.h" |
| 20 | #include "lldb/Target/Target.h" |
| 21 | #include "lldb/Target/Thread.h" |
| 22 | #include "lldb/Target/ThreadPlan.h" |
| 23 | #include "lldb/Target/ThreadPlanCallFunction.h" |
| 24 | #include "lldb/Utility/DataExtractor.h" |
| 25 | #include "lldb/Utility/ErrorMessages.h" |
| 26 | #include "lldb/Utility/LLDBLog.h" |
| 27 | #include "lldb/Utility/Log.h" |
| 28 | #include "lldb/Utility/State.h" |
| 29 | #include "lldb/ValueObject/ValueObject.h" |
| 30 | #include "lldb/ValueObject/ValueObjectList.h" |
| 31 | |
| 32 | using namespace lldb_private; |
| 33 | |
| 34 | char FunctionCaller::ID; |
| 35 | |
| 36 | // FunctionCaller constructor |
| 37 | FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope, |
| 38 | const CompilerType &return_type, |
| 39 | const Address &functionAddress, |
| 40 | const ValueList &arg_value_list, |
| 41 | const char *name) |
| 42 | : Expression(exe_scope), m_execution_unit_sp(), m_parser(), |
| 43 | m_jit_module_wp(), m_name(name ? name : "<unknown>" ), |
| 44 | m_function_ptr(nullptr), m_function_addr(functionAddress), |
| 45 | m_function_return_type(return_type), |
| 46 | m_wrapper_function_name("__lldb_caller_function" ), |
| 47 | m_wrapper_struct_name("__lldb_caller_struct" ), m_wrapper_args_addrs(), |
| 48 | m_struct_valid(false), m_struct_size(0), m_return_size(0), |
| 49 | m_return_offset(0), m_arg_values(arg_value_list), m_compiled(false), |
| 50 | m_JITted(false) { |
| 51 | m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess()); |
| 52 | // Can't make a FunctionCaller without a process. |
| 53 | assert(m_jit_process_wp.lock()); |
| 54 | } |
| 55 | |
| 56 | // Destructor |
| 57 | FunctionCaller::~FunctionCaller() { |
| 58 | lldb::ProcessSP process_sp(m_jit_process_wp.lock()); |
| 59 | if (process_sp) { |
| 60 | lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock()); |
| 61 | if (jit_module_sp) |
| 62 | process_sp->GetTarget().GetImages().Remove(module_sp: jit_module_sp); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | bool FunctionCaller::WriteFunctionWrapper( |
| 67 | ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) { |
| 68 | Process *process = exe_ctx.GetProcessPtr(); |
| 69 | |
| 70 | if (!process) { |
| 71 | diagnostic_manager.Printf(severity: lldb::eSeverityError, format: "no process." ); |
| 72 | return false; |
| 73 | } |
| 74 | |
| 75 | lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); |
| 76 | |
| 77 | if (process != jit_process_sp.get()) { |
| 78 | diagnostic_manager.Printf(severity: lldb::eSeverityError, |
| 79 | format: "process does not match the stored process." ); |
| 80 | return false; |
| 81 | } |
| 82 | |
| 83 | if (process->GetState() != lldb::eStateStopped) { |
| 84 | diagnostic_manager.Printf(severity: lldb::eSeverityError, format: "process is not stopped" ); |
| 85 | return false; |
| 86 | } |
| 87 | |
| 88 | if (!m_compiled) { |
| 89 | diagnostic_manager.Printf(severity: lldb::eSeverityError, format: "function not compiled" ); |
| 90 | return false; |
| 91 | } |
| 92 | |
| 93 | if (m_JITted) |
| 94 | return true; |
| 95 | |
| 96 | bool can_interpret = false; // should stay that way |
| 97 | |
| 98 | Status jit_error(m_parser->PrepareForExecution( |
| 99 | func_addr&: m_jit_start_addr, func_end&: m_jit_end_addr, execution_unit_sp&: m_execution_unit_sp, exe_ctx, |
| 100 | can_interpret, execution_policy: eExecutionPolicyAlways)); |
| 101 | |
| 102 | if (!jit_error.Success()) { |
| 103 | diagnostic_manager.Printf(severity: lldb::eSeverityError, |
| 104 | format: "Error in PrepareForExecution: %s." , |
| 105 | jit_error.AsCString()); |
| 106 | return false; |
| 107 | } |
| 108 | |
| 109 | if (m_parser->GetGenerateDebugInfo()) { |
| 110 | lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule()); |
| 111 | |
| 112 | if (jit_module_sp) { |
| 113 | ConstString const_func_name(FunctionName()); |
| 114 | FileSpec jit_file; |
| 115 | jit_file.SetFilename(const_func_name); |
| 116 | jit_module_sp->SetFileSpecAndObjectName(file: jit_file, object_name: ConstString()); |
| 117 | m_jit_module_wp = jit_module_sp; |
| 118 | process->GetTarget().GetImages().Append(module_sp: jit_module_sp, |
| 119 | notify: true /* notify */); |
| 120 | } |
| 121 | } |
| 122 | if (process && m_jit_start_addr) |
| 123 | m_jit_process_wp = process->shared_from_this(); |
| 124 | |
| 125 | m_JITted = true; |
| 126 | |
| 127 | return true; |
| 128 | } |
| 129 | |
| 130 | bool FunctionCaller::WriteFunctionArguments( |
| 131 | ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, |
| 132 | DiagnosticManager &diagnostic_manager) { |
| 133 | return WriteFunctionArguments(exe_ctx, args_addr_ref, arg_values&: m_arg_values, |
| 134 | diagnostic_manager); |
| 135 | } |
| 136 | |
| 137 | // FIXME: Assure that the ValueList we were passed in is consistent with the one |
| 138 | // that defined this function. |
| 139 | |
| 140 | bool FunctionCaller::WriteFunctionArguments( |
| 141 | ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, |
| 142 | ValueList &arg_values, DiagnosticManager &diagnostic_manager) { |
| 143 | // All the information to reconstruct the struct is provided by the |
| 144 | // StructExtractor. |
| 145 | if (!m_struct_valid) { |
| 146 | diagnostic_manager.PutString(severity: lldb::eSeverityError, |
| 147 | str: "Argument information was not correctly " |
| 148 | "parsed, so the function cannot be called." ); |
| 149 | return false; |
| 150 | } |
| 151 | |
| 152 | Status error; |
| 153 | lldb::ExpressionResults return_value = lldb::eExpressionSetupError; |
| 154 | |
| 155 | Process *process = exe_ctx.GetProcessPtr(); |
| 156 | |
| 157 | if (process == nullptr) |
| 158 | return return_value; |
| 159 | |
| 160 | lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); |
| 161 | |
| 162 | if (process != jit_process_sp.get()) |
| 163 | return false; |
| 164 | |
| 165 | if (args_addr_ref == LLDB_INVALID_ADDRESS) { |
| 166 | args_addr_ref = process->AllocateMemory( |
| 167 | size: m_struct_size, permissions: lldb::ePermissionsReadable | lldb::ePermissionsWritable, |
| 168 | error); |
| 169 | if (args_addr_ref == LLDB_INVALID_ADDRESS) |
| 170 | return false; |
| 171 | m_wrapper_args_addrs.push_back(x: args_addr_ref); |
| 172 | } else { |
| 173 | // Make sure this is an address that we've already handed out. |
| 174 | if (!llvm::is_contained(Range&: m_wrapper_args_addrs, Element: args_addr_ref)) |
| 175 | return false; |
| 176 | } |
| 177 | |
| 178 | // TODO: verify fun_addr needs to be a callable address |
| 179 | Scalar fun_addr( |
| 180 | m_function_addr.GetCallableLoadAddress(target: exe_ctx.GetTargetPtr())); |
| 181 | uint64_t first_offset = m_member_offsets[0]; |
| 182 | process->WriteScalarToMemory(vm_addr: args_addr_ref + first_offset, scalar: fun_addr, |
| 183 | size: process->GetAddressByteSize(), error); |
| 184 | |
| 185 | // FIXME: We will need to extend this for Variadic functions. |
| 186 | |
| 187 | Status value_error; |
| 188 | |
| 189 | size_t num_args = arg_values.GetSize(); |
| 190 | if (num_args != m_arg_values.GetSize()) { |
| 191 | diagnostic_manager.Printf( |
| 192 | severity: lldb::eSeverityError, |
| 193 | format: "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "" , |
| 194 | (uint64_t)num_args, (uint64_t)m_arg_values.GetSize()); |
| 195 | return false; |
| 196 | } |
| 197 | |
| 198 | for (size_t i = 0; i < num_args; i++) { |
| 199 | // FIXME: We should sanity check sizes. |
| 200 | |
| 201 | uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes. |
| 202 | Value *arg_value = arg_values.GetValueAtIndex(idx: i); |
| 203 | |
| 204 | // FIXME: For now just do scalars: |
| 205 | |
| 206 | // Special case: if it's a pointer, don't do anything (the ABI supports |
| 207 | // passing cstrings) |
| 208 | |
| 209 | if (arg_value->GetValueType() == Value::ValueType::HostAddress && |
| 210 | arg_value->GetContextType() == Value::ContextType::Invalid && |
| 211 | arg_value->GetCompilerType().IsPointerType()) |
| 212 | continue; |
| 213 | |
| 214 | const Scalar &arg_scalar = arg_value->ResolveValue(exe_ctx: &exe_ctx); |
| 215 | |
| 216 | if (!process->WriteScalarToMemory(vm_addr: args_addr_ref + offset, scalar: arg_scalar, |
| 217 | size: arg_scalar.GetByteSize(), error)) |
| 218 | return false; |
| 219 | } |
| 220 | |
| 221 | return true; |
| 222 | } |
| 223 | |
| 224 | bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx, |
| 225 | lldb::addr_t &args_addr_ref, |
| 226 | DiagnosticManager &diagnostic_manager) { |
| 227 | // Since we might need to call allocate memory and maybe call code to make |
| 228 | // the caller, we need to be stopped. |
| 229 | Process *process = exe_ctx.GetProcessPtr(); |
| 230 | if (!process) { |
| 231 | diagnostic_manager.PutString(severity: lldb::eSeverityError, str: "no process" ); |
| 232 | return false; |
| 233 | } |
| 234 | if (process->GetState() != lldb::eStateStopped) { |
| 235 | diagnostic_manager.PutString(severity: lldb::eSeverityError, str: "process running" ); |
| 236 | return false; |
| 237 | } |
| 238 | if (CompileFunction(thread_to_use_sp: exe_ctx.GetThreadSP(), diagnostic_manager) != 0) |
| 239 | return false; |
| 240 | if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager)) |
| 241 | return false; |
| 242 | if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager)) |
| 243 | return false; |
| 244 | |
| 245 | Log *log = GetLog(mask: LLDBLog::Step); |
| 246 | LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n" , |
| 247 | m_jit_start_addr, args_addr_ref); |
| 248 | |
| 249 | return true; |
| 250 | } |
| 251 | |
| 252 | lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction( |
| 253 | ExecutionContext &exe_ctx, lldb::addr_t args_addr, |
| 254 | const EvaluateExpressionOptions &options, |
| 255 | DiagnosticManager &diagnostic_manager) { |
| 256 | Log *log(GetLog(mask: LLDBLog::Expressions | LLDBLog::Step)); |
| 257 | |
| 258 | LLDB_LOGF(log, |
| 259 | "-- [FunctionCaller::GetThreadPlanToCallFunction] Creating " |
| 260 | "thread plan to call function \"%s\" --" , |
| 261 | m_name.c_str()); |
| 262 | |
| 263 | // FIXME: Use the errors Stream for better error reporting. |
| 264 | Thread *thread = exe_ctx.GetThreadPtr(); |
| 265 | if (thread == nullptr) { |
| 266 | diagnostic_manager.PutString( |
| 267 | severity: lldb::eSeverityError, str: "Can't call a function without a valid thread." ); |
| 268 | return nullptr; |
| 269 | } |
| 270 | |
| 271 | // Okay, now run the function: |
| 272 | |
| 273 | Address wrapper_address(m_jit_start_addr); |
| 274 | |
| 275 | lldb::addr_t args = {args_addr}; |
| 276 | |
| 277 | lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction( |
| 278 | *thread, wrapper_address, CompilerType(), args, options)); |
| 279 | new_plan_sp->SetIsControllingPlan(true); |
| 280 | new_plan_sp->SetOkayToDiscard(false); |
| 281 | return new_plan_sp; |
| 282 | } |
| 283 | |
| 284 | bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx, |
| 285 | lldb::addr_t args_addr, |
| 286 | Value &ret_value) { |
| 287 | // Read the return value - it is the last field in the struct: |
| 288 | // FIXME: How does clang tell us there's no return value? We need to handle |
| 289 | // that case. |
| 290 | // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and |
| 291 | // then use GetReturnValueObject |
| 292 | // to fetch the value. That way we can fetch any values we need. |
| 293 | |
| 294 | Log *log(GetLog(mask: LLDBLog::Expressions | LLDBLog::Step)); |
| 295 | |
| 296 | LLDB_LOGF(log, |
| 297 | "-- [FunctionCaller::FetchFunctionResults] Fetching function " |
| 298 | "results for \"%s\"--" , |
| 299 | m_name.c_str()); |
| 300 | |
| 301 | Process *process = exe_ctx.GetProcessPtr(); |
| 302 | |
| 303 | if (process == nullptr) |
| 304 | return false; |
| 305 | |
| 306 | lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); |
| 307 | |
| 308 | if (process != jit_process_sp.get()) |
| 309 | return false; |
| 310 | |
| 311 | Status error; |
| 312 | ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory( |
| 313 | load_addr: args_addr + m_return_offset, byte_size: m_return_size, fail_value: 0, error); |
| 314 | |
| 315 | if (error.Fail()) |
| 316 | return false; |
| 317 | |
| 318 | ret_value.SetCompilerType(m_function_return_type); |
| 319 | ret_value.SetValueType(Value::ValueType::Scalar); |
| 320 | return true; |
| 321 | } |
| 322 | |
| 323 | void FunctionCaller::DeallocateFunctionResults(ExecutionContext &exe_ctx, |
| 324 | lldb::addr_t args_addr) { |
| 325 | std::list<lldb::addr_t>::iterator pos; |
| 326 | pos = llvm::find(Range&: m_wrapper_args_addrs, Val: args_addr); |
| 327 | if (pos != m_wrapper_args_addrs.end()) |
| 328 | m_wrapper_args_addrs.erase(position: pos); |
| 329 | |
| 330 | exe_ctx.GetProcessRef().DeallocateMemory(ptr: args_addr); |
| 331 | } |
| 332 | |
| 333 | lldb::ExpressionResults FunctionCaller::ExecuteFunction( |
| 334 | ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, |
| 335 | const EvaluateExpressionOptions &options, |
| 336 | DiagnosticManager &diagnostic_manager, Value &results) { |
| 337 | lldb::ExpressionResults return_value = lldb::eExpressionSetupError; |
| 338 | |
| 339 | Debugger *debugger = |
| 340 | exe_ctx.GetTargetPtr() ? &exe_ctx.GetTargetPtr()->GetDebugger() : nullptr; |
| 341 | Progress progress("Calling function" , FunctionName(), {}, debugger); |
| 342 | |
| 343 | // FunctionCaller::ExecuteFunction execution is always just to get the |
| 344 | // result. Unless explicitly asked for, ignore breakpoints and unwind on |
| 345 | // error. |
| 346 | const bool enable_debugging = |
| 347 | exe_ctx.GetTargetPtr() && |
| 348 | exe_ctx.GetTargetPtr()->GetDebugUtilityExpression(); |
| 349 | EvaluateExpressionOptions real_options = options; |
| 350 | real_options.SetDebug(false); // This halts the expression for debugging. |
| 351 | real_options.SetGenerateDebugInfo(enable_debugging); |
| 352 | real_options.SetUnwindOnError(!enable_debugging); |
| 353 | real_options.SetIgnoreBreakpoints(!enable_debugging); |
| 354 | |
| 355 | lldb::addr_t args_addr; |
| 356 | |
| 357 | if (args_addr_ptr != nullptr) |
| 358 | args_addr = *args_addr_ptr; |
| 359 | else |
| 360 | args_addr = LLDB_INVALID_ADDRESS; |
| 361 | |
| 362 | if (CompileFunction(thread_to_use_sp: exe_ctx.GetThreadSP(), diagnostic_manager) != 0) |
| 363 | return lldb::eExpressionSetupError; |
| 364 | |
| 365 | if (args_addr == LLDB_INVALID_ADDRESS) { |
| 366 | if (!InsertFunction(exe_ctx, args_addr_ref&: args_addr, diagnostic_manager)) |
| 367 | return lldb::eExpressionSetupError; |
| 368 | } |
| 369 | |
| 370 | Log *log(GetLog(mask: LLDBLog::Expressions | LLDBLog::Step)); |
| 371 | |
| 372 | LLDB_LOGF(log, |
| 373 | "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==" , |
| 374 | m_name.c_str()); |
| 375 | |
| 376 | lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction( |
| 377 | exe_ctx, args_addr, options: real_options, diagnostic_manager); |
| 378 | if (!call_plan_sp) |
| 379 | return lldb::eExpressionSetupError; |
| 380 | |
| 381 | // We need to make sure we record the fact that we are running an expression |
| 382 | // here otherwise this fact will fail to be recorded when fetching an |
| 383 | // Objective-C object description |
| 384 | if (exe_ctx.GetProcessPtr()) |
| 385 | exe_ctx.GetProcessPtr()->SetRunningUserExpression(true); |
| 386 | |
| 387 | return_value = exe_ctx.GetProcessRef().RunThreadPlan( |
| 388 | exe_ctx, thread_plan_sp&: call_plan_sp, options: real_options, diagnostic_manager); |
| 389 | |
| 390 | if (log) { |
| 391 | if (return_value != lldb::eExpressionCompleted) { |
| 392 | LLDB_LOGF(log, |
| 393 | "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" " |
| 394 | "completed abnormally: %s ==" , |
| 395 | m_name.c_str(), toString(return_value).c_str()); |
| 396 | } else { |
| 397 | LLDB_LOGF(log, |
| 398 | "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" " |
| 399 | "completed normally ==" , |
| 400 | m_name.c_str()); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | if (exe_ctx.GetProcessPtr()) |
| 405 | exe_ctx.GetProcessPtr()->SetRunningUserExpression(false); |
| 406 | |
| 407 | if (args_addr_ptr != nullptr) |
| 408 | *args_addr_ptr = args_addr; |
| 409 | |
| 410 | if (return_value != lldb::eExpressionCompleted) |
| 411 | return return_value; |
| 412 | |
| 413 | FetchFunctionResults(exe_ctx, args_addr, ret_value&: results); |
| 414 | |
| 415 | if (args_addr_ptr == nullptr) |
| 416 | DeallocateFunctionResults(exe_ctx, args_addr); |
| 417 | |
| 418 | return lldb::eExpressionCompleted; |
| 419 | } |
| 420 | |