1 //===-- FunctionCaller.cpp ------------------------------------------------===//
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/LLDBLog.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/State.h"
31 using namespace lldb_private
;
33 char FunctionCaller::ID
;
35 // FunctionCaller constructor
36 FunctionCaller::FunctionCaller(ExecutionContextScope
&exe_scope
,
37 const CompilerType
&return_type
,
38 const Address
&functionAddress
,
39 const ValueList
&arg_value_list
,
41 : Expression(exe_scope
), m_execution_unit_sp(), m_parser(),
42 m_jit_module_wp(), m_name(name
? name
: "<unknown>"),
43 m_function_ptr(nullptr), m_function_addr(functionAddress
),
44 m_function_return_type(return_type
),
45 m_wrapper_function_name("__lldb_caller_function"),
46 m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
47 m_struct_valid(false), m_struct_size(0), m_return_size(0),
48 m_return_offset(0), m_arg_values(arg_value_list
), m_compiled(false),
50 m_jit_process_wp
= lldb::ProcessWP(exe_scope
.CalculateProcess());
51 // Can't make a FunctionCaller without a process.
52 assert(m_jit_process_wp
.lock());
56 FunctionCaller::~FunctionCaller() {
57 lldb::ProcessSP
process_sp(m_jit_process_wp
.lock());
59 lldb::ModuleSP
jit_module_sp(m_jit_module_wp
.lock());
61 process_sp
->GetTarget().GetImages().Remove(jit_module_sp
);
65 bool FunctionCaller::WriteFunctionWrapper(
66 ExecutionContext
&exe_ctx
, DiagnosticManager
&diagnostic_manager
) {
67 Process
*process
= exe_ctx
.GetProcessPtr();
70 diagnostic_manager
.Printf(eDiagnosticSeverityError
, "no process.");
74 lldb::ProcessSP
jit_process_sp(m_jit_process_wp
.lock());
76 if (process
!= jit_process_sp
.get()) {
77 diagnostic_manager
.Printf(eDiagnosticSeverityError
,
78 "process does not match the stored process.");
82 if (process
->GetState() != lldb::eStateStopped
) {
83 diagnostic_manager
.Printf(eDiagnosticSeverityError
,
84 "process is not stopped");
89 diagnostic_manager
.Printf(eDiagnosticSeverityError
,
90 "function not compiled");
97 bool can_interpret
= false; // should stay that way
99 Status
jit_error(m_parser
->PrepareForExecution(
100 m_jit_start_addr
, m_jit_end_addr
, m_execution_unit_sp
, exe_ctx
,
101 can_interpret
, eExecutionPolicyAlways
));
103 if (!jit_error
.Success()) {
104 diagnostic_manager
.Printf(eDiagnosticSeverityError
,
105 "Error in PrepareForExecution: %s.",
106 jit_error
.AsCString());
110 if (m_parser
->GetGenerateDebugInfo()) {
111 lldb::ModuleSP
jit_module_sp(m_execution_unit_sp
->GetJITModule());
114 ConstString
const_func_name(FunctionName());
116 jit_file
.SetFilename(const_func_name
);
117 jit_module_sp
->SetFileSpecAndObjectName(jit_file
, ConstString());
118 m_jit_module_wp
= jit_module_sp
;
119 process
->GetTarget().GetImages().Append(jit_module_sp
,
123 if (process
&& m_jit_start_addr
)
124 m_jit_process_wp
= process
->shared_from_this();
131 bool FunctionCaller::WriteFunctionArguments(
132 ExecutionContext
&exe_ctx
, lldb::addr_t
&args_addr_ref
,
133 DiagnosticManager
&diagnostic_manager
) {
134 return WriteFunctionArguments(exe_ctx
, args_addr_ref
, m_arg_values
,
138 // FIXME: Assure that the ValueList we were passed in is consistent with the one
139 // that defined this function.
141 bool FunctionCaller::WriteFunctionArguments(
142 ExecutionContext
&exe_ctx
, lldb::addr_t
&args_addr_ref
,
143 ValueList
&arg_values
, DiagnosticManager
&diagnostic_manager
) {
144 // All the information to reconstruct the struct is provided by the
146 if (!m_struct_valid
) {
147 diagnostic_manager
.PutString(eDiagnosticSeverityError
,
148 "Argument information was not correctly "
149 "parsed, so the function cannot be called.");
154 lldb::ExpressionResults return_value
= lldb::eExpressionSetupError
;
156 Process
*process
= exe_ctx
.GetProcessPtr();
158 if (process
== nullptr)
161 lldb::ProcessSP
jit_process_sp(m_jit_process_wp
.lock());
163 if (process
!= jit_process_sp
.get())
166 if (args_addr_ref
== LLDB_INVALID_ADDRESS
) {
167 args_addr_ref
= process
->AllocateMemory(
168 m_struct_size
, lldb::ePermissionsReadable
| lldb::ePermissionsWritable
,
170 if (args_addr_ref
== LLDB_INVALID_ADDRESS
)
172 m_wrapper_args_addrs
.push_back(args_addr_ref
);
174 // Make sure this is an address that we've already handed out.
175 if (find(m_wrapper_args_addrs
.begin(), m_wrapper_args_addrs
.end(),
176 args_addr_ref
) == m_wrapper_args_addrs
.end()) {
181 // TODO: verify fun_addr needs to be a callable address
183 m_function_addr
.GetCallableLoadAddress(exe_ctx
.GetTargetPtr()));
184 uint64_t first_offset
= m_member_offsets
[0];
185 process
->WriteScalarToMemory(args_addr_ref
+ first_offset
, fun_addr
,
186 process
->GetAddressByteSize(), error
);
188 // FIXME: We will need to extend this for Variadic functions.
192 size_t num_args
= arg_values
.GetSize();
193 if (num_args
!= m_arg_values
.GetSize()) {
194 diagnostic_manager
.Printf(
195 eDiagnosticSeverityError
,
196 "Wrong number of arguments - was: %" PRIu64
" should be: %" PRIu64
"",
197 (uint64_t)num_args
, (uint64_t)m_arg_values
.GetSize());
201 for (size_t i
= 0; i
< num_args
; i
++) {
202 // FIXME: We should sanity check sizes.
204 uint64_t offset
= m_member_offsets
[i
+ 1]; // Clang sizes are in bytes.
205 Value
*arg_value
= arg_values
.GetValueAtIndex(i
);
207 // FIXME: For now just do scalars:
209 // Special case: if it's a pointer, don't do anything (the ABI supports
212 if (arg_value
->GetValueType() == Value::ValueType::HostAddress
&&
213 arg_value
->GetContextType() == Value::ContextType::Invalid
&&
214 arg_value
->GetCompilerType().IsPointerType())
217 const Scalar
&arg_scalar
= arg_value
->ResolveValue(&exe_ctx
);
219 if (!process
->WriteScalarToMemory(args_addr_ref
+ offset
, arg_scalar
,
220 arg_scalar
.GetByteSize(), error
))
227 bool FunctionCaller::InsertFunction(ExecutionContext
&exe_ctx
,
228 lldb::addr_t
&args_addr_ref
,
229 DiagnosticManager
&diagnostic_manager
) {
230 // Since we might need to call allocate memory and maybe call code to make
231 // the caller, we need to be stopped.
232 Process
*process
= exe_ctx
.GetProcessPtr();
234 diagnostic_manager
.PutString(eDiagnosticSeverityError
, "no process");
237 if (process
->GetState() != lldb::eStateStopped
) {
238 diagnostic_manager
.PutString(eDiagnosticSeverityError
, "process running");
241 if (CompileFunction(exe_ctx
.GetThreadSP(), diagnostic_manager
) != 0)
243 if (!WriteFunctionWrapper(exe_ctx
, diagnostic_manager
))
245 if (!WriteFunctionArguments(exe_ctx
, args_addr_ref
, diagnostic_manager
))
248 Log
*log
= GetLog(LLDBLog::Step
);
249 LLDB_LOGF(log
, "Call Address: 0x%" PRIx64
" Struct Address: 0x%" PRIx64
".\n",
250 m_jit_start_addr
, args_addr_ref
);
255 lldb::ThreadPlanSP
FunctionCaller::GetThreadPlanToCallFunction(
256 ExecutionContext
&exe_ctx
, lldb::addr_t args_addr
,
257 const EvaluateExpressionOptions
&options
,
258 DiagnosticManager
&diagnostic_manager
) {
259 Log
*log(GetLog(LLDBLog::Expressions
| LLDBLog::Step
));
262 "-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
263 "thread plan to call function \"%s\" --",
266 // FIXME: Use the errors Stream for better error reporting.
267 Thread
*thread
= exe_ctx
.GetThreadPtr();
268 if (thread
== nullptr) {
269 diagnostic_manager
.PutString(
270 eDiagnosticSeverityError
,
271 "Can't call a function without a valid thread.");
275 // Okay, now run the function:
277 Address
wrapper_address(m_jit_start_addr
);
279 lldb::addr_t args
= {args_addr
};
281 lldb::ThreadPlanSP
new_plan_sp(new ThreadPlanCallFunction(
282 *thread
, wrapper_address
, CompilerType(), args
, options
));
283 new_plan_sp
->SetIsControllingPlan(true);
284 new_plan_sp
->SetOkayToDiscard(false);
288 bool FunctionCaller::FetchFunctionResults(ExecutionContext
&exe_ctx
,
289 lldb::addr_t args_addr
,
291 // Read the return value - it is the last field in the struct:
292 // FIXME: How does clang tell us there's no return value? We need to handle
294 // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
295 // then use GetReturnValueObject
296 // to fetch the value. That way we can fetch any values we need.
298 Log
*log(GetLog(LLDBLog::Expressions
| LLDBLog::Step
));
301 "-- [FunctionCaller::FetchFunctionResults] Fetching function "
302 "results for \"%s\"--",
305 Process
*process
= exe_ctx
.GetProcessPtr();
307 if (process
== nullptr)
310 lldb::ProcessSP
jit_process_sp(m_jit_process_wp
.lock());
312 if (process
!= jit_process_sp
.get())
316 ret_value
.GetScalar() = process
->ReadUnsignedIntegerFromMemory(
317 args_addr
+ m_return_offset
, m_return_size
, 0, error
);
322 ret_value
.SetCompilerType(m_function_return_type
);
323 ret_value
.SetValueType(Value::ValueType::Scalar
);
327 void FunctionCaller::DeallocateFunctionResults(ExecutionContext
&exe_ctx
,
328 lldb::addr_t args_addr
) {
329 std::list
<lldb::addr_t
>::iterator pos
;
330 pos
= std::find(m_wrapper_args_addrs
.begin(), m_wrapper_args_addrs
.end(),
332 if (pos
!= m_wrapper_args_addrs
.end())
333 m_wrapper_args_addrs
.erase(pos
);
335 exe_ctx
.GetProcessRef().DeallocateMemory(args_addr
);
338 lldb::ExpressionResults
FunctionCaller::ExecuteFunction(
339 ExecutionContext
&exe_ctx
, lldb::addr_t
*args_addr_ptr
,
340 const EvaluateExpressionOptions
&options
,
341 DiagnosticManager
&diagnostic_manager
, Value
&results
) {
342 lldb::ExpressionResults return_value
= lldb::eExpressionSetupError
;
344 // FunctionCaller::ExecuteFunction execution is always just to get the
345 // result. Unless explicitly asked for, ignore breakpoints and unwind on
347 const bool enable_debugging
=
348 exe_ctx
.GetTargetPtr() &&
349 exe_ctx
.GetTargetPtr()->GetDebugUtilityExpression();
350 EvaluateExpressionOptions real_options
= options
;
351 real_options
.SetDebug(false); // This halts the expression for debugging.
352 real_options
.SetGenerateDebugInfo(enable_debugging
);
353 real_options
.SetUnwindOnError(!enable_debugging
);
354 real_options
.SetIgnoreBreakpoints(!enable_debugging
);
356 lldb::addr_t args_addr
;
358 if (args_addr_ptr
!= nullptr)
359 args_addr
= *args_addr_ptr
;
361 args_addr
= LLDB_INVALID_ADDRESS
;
363 if (CompileFunction(exe_ctx
.GetThreadSP(), diagnostic_manager
) != 0)
364 return lldb::eExpressionSetupError
;
366 if (args_addr
== LLDB_INVALID_ADDRESS
) {
367 if (!InsertFunction(exe_ctx
, args_addr
, diagnostic_manager
))
368 return lldb::eExpressionSetupError
;
371 Log
*log(GetLog(LLDBLog::Expressions
| LLDBLog::Step
));
374 "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
377 lldb::ThreadPlanSP call_plan_sp
= GetThreadPlanToCallFunction(
378 exe_ctx
, args_addr
, real_options
, diagnostic_manager
);
380 return lldb::eExpressionSetupError
;
382 // We need to make sure we record the fact that we are running an expression
383 // here otherwise this fact will fail to be recorded when fetching an
384 // Objective-C object description
385 if (exe_ctx
.GetProcessPtr())
386 exe_ctx
.GetProcessPtr()->SetRunningUserExpression(true);
388 return_value
= exe_ctx
.GetProcessRef().RunThreadPlan(
389 exe_ctx
, call_plan_sp
, real_options
, diagnostic_manager
);
392 if (return_value
!= lldb::eExpressionCompleted
) {
394 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
395 "completed abnormally: %s ==",
397 Process::ExecutionResultAsCString(return_value
));
400 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
401 "completed normally ==",
406 if (exe_ctx
.GetProcessPtr())
407 exe_ctx
.GetProcessPtr()->SetRunningUserExpression(false);
409 if (args_addr_ptr
!= nullptr)
410 *args_addr_ptr
= args_addr
;
412 if (return_value
!= lldb::eExpressionCompleted
)
415 FetchFunctionResults(exe_ctx
, args_addr
, results
);
417 if (args_addr_ptr
== nullptr)
418 DeallocateFunctionResults(exe_ctx
, args_addr
);
420 return lldb::eExpressionCompleted
;