1 //===-- FunctionCaller.cpp ---------------------------------------*- C++-*-===//
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
7 //===----------------------------------------------------------------------===//
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"
30 using namespace lldb_private;
32 // FunctionCaller constructor
33 FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope,
34 const CompilerType &return_type,
35 const Address &functionAddress,
36 const ValueList &arg_value_list,
38 : Expression(exe_scope, eKindFunctionCaller), m_execution_unit_sp(),
39 m_parser(), m_jit_module_wp(), m_name(name ? name : "<unknown>"),
40 m_function_ptr(nullptr), m_function_addr(functionAddress),
41 m_function_return_type(return_type),
42 m_wrapper_function_name("__lldb_caller_function"),
43 m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
44 m_struct_valid(false), m_arg_values(arg_value_list), m_compiled(false),
46 m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
47 // Can't make a FunctionCaller without a process.
48 assert(m_jit_process_wp.lock());
52 FunctionCaller::~FunctionCaller() {
53 lldb::ProcessSP process_sp(m_jit_process_wp.lock());
55 lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
57 process_sp->GetTarget().GetImages().Remove(jit_module_sp);
61 bool FunctionCaller::WriteFunctionWrapper(
62 ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
63 Process *process = exe_ctx.GetProcessPtr();
68 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
70 if (process != jit_process_sp.get())
79 bool can_interpret = false; // should stay that way
81 Status jit_error(m_parser->PrepareForExecution(
82 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
83 can_interpret, eExecutionPolicyAlways));
85 if (!jit_error.Success()) {
86 diagnostic_manager.Printf(eDiagnosticSeverityError,
87 "Error in PrepareForExecution: %s.",
88 jit_error.AsCString());
92 if (m_parser->GetGenerateDebugInfo()) {
93 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
96 ConstString const_func_name(FunctionName());
98 jit_file.GetFilename() = const_func_name;
99 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
100 m_jit_module_wp = jit_module_sp;
101 process->GetTarget().GetImages().Append(jit_module_sp,
105 if (process && m_jit_start_addr)
106 m_jit_process_wp = process->shared_from_this();
113 bool FunctionCaller::WriteFunctionArguments(
114 ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
115 DiagnosticManager &diagnostic_manager) {
116 return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
120 // FIXME: Assure that the ValueList we were passed in is consistent with the one
121 // that defined this function.
123 bool FunctionCaller::WriteFunctionArguments(
124 ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
125 ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
126 // All the information to reconstruct the struct is provided by the
128 if (!m_struct_valid) {
129 diagnostic_manager.PutString(eDiagnosticSeverityError,
130 "Argument information was not correctly "
131 "parsed, so the function cannot be called.");
136 lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
138 Process *process = exe_ctx.GetProcessPtr();
140 if (process == nullptr)
143 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
145 if (process != jit_process_sp.get())
148 if (args_addr_ref == LLDB_INVALID_ADDRESS) {
149 args_addr_ref = process->AllocateMemory(
150 m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
152 if (args_addr_ref == LLDB_INVALID_ADDRESS)
154 m_wrapper_args_addrs.push_back(args_addr_ref);
156 // Make sure this is an address that we've already handed out.
157 if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
158 args_addr_ref) == m_wrapper_args_addrs.end()) {
163 // TODO: verify fun_addr needs to be a callable address
165 m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
166 uint64_t first_offset = m_member_offsets[0];
167 process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
168 process->GetAddressByteSize(), error);
170 // FIXME: We will need to extend this for Variadic functions.
174 size_t num_args = arg_values.GetSize();
175 if (num_args != m_arg_values.GetSize()) {
176 diagnostic_manager.Printf(
177 eDiagnosticSeverityError,
178 "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
179 (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
183 for (size_t i = 0; i < num_args; i++) {
184 // FIXME: We should sanity check sizes.
186 uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
187 Value *arg_value = arg_values.GetValueAtIndex(i);
189 // FIXME: For now just do scalars:
191 // Special case: if it's a pointer, don't do anything (the ABI supports
194 if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
195 arg_value->GetContextType() == Value::eContextTypeInvalid &&
196 arg_value->GetCompilerType().IsPointerType())
199 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
201 if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
202 arg_scalar.GetByteSize(), error))
209 bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,
210 lldb::addr_t &args_addr_ref,
211 DiagnosticManager &diagnostic_manager) {
212 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
214 if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
216 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
219 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
221 log->Printf("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
222 m_jit_start_addr, args_addr_ref);
227 lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(
228 ExecutionContext &exe_ctx, lldb::addr_t args_addr,
229 const EvaluateExpressionOptions &options,
230 DiagnosticManager &diagnostic_manager) {
231 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
235 log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
236 "thread plan to call function \"%s\" --",
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.");
248 // Okay, now run the function:
250 Address wrapper_address(m_jit_start_addr);
252 lldb::addr_t args = {args_addr};
254 lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(
255 *thread, wrapper_address, CompilerType(), args, options));
256 new_plan_sp->SetIsMasterPlan(true);
257 new_plan_sp->SetOkayToDiscard(false);
261 bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,
262 lldb::addr_t args_addr,
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
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.
271 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
275 log->Printf("-- [FunctionCaller::FetchFunctionResults] Fetching function "
276 "results for \"%s\"--",
279 Process *process = exe_ctx.GetProcessPtr();
281 if (process == nullptr)
284 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
286 if (process != jit_process_sp.get())
290 ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
291 args_addr + m_return_offset, m_return_size, 0, error);
296 ret_value.SetCompilerType(m_function_return_type);
297 ret_value.SetValueType(Value::eValueTypeScalar);
301 void FunctionCaller::DeallocateFunctionResults(ExecutionContext &exe_ctx,
302 lldb::addr_t args_addr) {
303 std::list<lldb::addr_t>::iterator pos;
304 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
306 if (pos != m_wrapper_args_addrs.end())
307 m_wrapper_args_addrs.erase(pos);
309 exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
312 lldb::ExpressionResults FunctionCaller::ExecuteFunction(
313 ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
314 const EvaluateExpressionOptions &options,
315 DiagnosticManager &diagnostic_manager, Value &results) {
316 lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
318 // FunctionCaller::ExecuteFunction execution is always just to get the
319 // result. Do make sure we ignore breakpoints, unwind on error, and don't try
321 EvaluateExpressionOptions real_options = options;
322 real_options.SetDebug(false);
323 real_options.SetUnwindOnError(true);
324 real_options.SetIgnoreBreakpoints(true);
326 lldb::addr_t args_addr;
328 if (args_addr_ptr != nullptr)
329 args_addr = *args_addr_ptr;
331 args_addr = LLDB_INVALID_ADDRESS;
333 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
334 return lldb::eExpressionSetupError;
336 if (args_addr == LLDB_INVALID_ADDRESS) {
337 if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
338 return lldb::eExpressionSetupError;
341 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
346 "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
349 lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(
350 exe_ctx, args_addr, real_options, diagnostic_manager);
352 return lldb::eExpressionSetupError;
354 // We need to make sure we record the fact that we are running an expression
355 // here otherwise this fact will fail to be recorded when fetching an
356 // Objective-C object description
357 if (exe_ctx.GetProcessPtr())
358 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
360 return_value = exe_ctx.GetProcessRef().RunThreadPlan(
361 exe_ctx, call_plan_sp, real_options, diagnostic_manager);
364 if (return_value != lldb::eExpressionCompleted) {
365 log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
366 "completed abnormally ==",
369 log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
370 "completed normally ==",
375 if (exe_ctx.GetProcessPtr())
376 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
378 if (args_addr_ptr != nullptr)
379 *args_addr_ptr = args_addr;
381 if (return_value != lldb::eExpressionCompleted)
384 FetchFunctionResults(exe_ctx, args_addr, results);
386 if (args_addr_ptr == nullptr)
387 DeallocateFunctionResults(exe_ctx, args_addr);
389 return lldb::eExpressionCompleted;