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