LLDB mainline
FunctionCaller.cpp
Go to the documentation of this file.
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
10#include "lldb/Core/Module.h"
11#include "lldb/Core/Progress.h"
16#include "lldb/Symbol/Type.h"
18#include "lldb/Target/Process.h"
20#include "lldb/Target/Target.h"
21#include "lldb/Target/Thread.h"
27#include "lldb/Utility/Log.h"
28#include "lldb/Utility/Policy.h"
29#include "lldb/Utility/State.h"
32
33using namespace lldb_private;
34
36
37// FunctionCaller constructor
39 const CompilerType &return_type,
40 const Address &functionAddress,
41 const ValueList &arg_value_list,
42 const char *name)
43 : Expression(exe_scope), m_execution_unit_sp(), m_parser(),
44 m_jit_module_wp(), m_name(name ? name : "<unknown>"),
45 m_function_ptr(nullptr), m_function_addr(functionAddress),
46 m_function_return_type(return_type),
47 m_wrapper_function_name("__lldb_caller_function"),
48 m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
50 m_return_offset(0), m_arg_values(arg_value_list), m_compiled(false),
51 m_JITted(false) {
53 // Can't make a FunctionCaller without a process.
54 assert(m_jit_process_wp.lock());
55}
56
57// Destructor
59 lldb::ProcessSP process_sp(m_jit_process_wp.lock());
60 if (process_sp) {
61 lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
62 if (jit_module_sp)
63 process_sp->GetTarget().GetImages().Remove(jit_module_sp);
64 }
65}
66
68 ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
69 Process *process = exe_ctx.GetProcessPtr();
70
71 if (!process) {
72 diagnostic_manager.Printf(lldb::eSeverityError, "no process.");
73 return false;
74 }
75
76 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
77
78 if (process != jit_process_sp.get()) {
79 diagnostic_manager.Printf(lldb::eSeverityError,
80 "process does not match the stored process.");
81 return false;
82 }
83
84 if (process->GetState() != lldb::eStateStopped) {
85 diagnostic_manager.Printf(lldb::eSeverityError, "process is not stopped");
86 return false;
87 }
88
89 if (!m_compiled) {
90 diagnostic_manager.Printf(lldb::eSeverityError, "function not compiled");
91 return false;
92 }
93
94 if (m_JITted)
95 return true;
96
97 bool can_interpret = false; // should stay that way
98
99 Status jit_error(m_parser->PrepareForExecution(
101 can_interpret, eExecutionPolicyAlways));
102
103 if (!jit_error.Success()) {
104 diagnostic_manager.Printf(lldb::eSeverityError,
105 "Error in PrepareForExecution: %s.",
106 jit_error.AsCString());
107 return false;
108 }
109
110 if (m_parser->GetGenerateDebugInfo()) {
111 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
112
113 if (jit_module_sp) {
114 ConstString const_func_name(FunctionName());
115 FileSpec jit_file;
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,
120 true /* notify */);
121 }
122 }
123 if (process && m_jit_start_addr)
124 m_jit_process_wp = process->shared_from_this();
125
126 m_JITted = true;
127
128 return true;
129}
130
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,
135 diagnostic_manager);
136}
137
138// FIXME: Assure that the ValueList we were passed in is consistent with the one
139// that defined this function.
140
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
145 // StructExtractor.
146 if (!m_struct_valid) {
147 diagnostic_manager.PutString(lldb::eSeverityError,
148 "Argument information was not correctly "
149 "parsed, so the function cannot be called.");
150 return false;
151 }
152
155
156 Process *process = exe_ctx.GetProcessPtr();
157
158 if (process == nullptr)
159 return return_value;
160
161 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
162
163 if (process != jit_process_sp.get())
164 return false;
165
166 if (args_addr_ref == LLDB_INVALID_ADDRESS) {
167 args_addr_ref = process->AllocateMemory(
168 m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
169 error);
170 if (args_addr_ref == LLDB_INVALID_ADDRESS)
171 return false;
172 m_wrapper_args_addrs.push_back(args_addr_ref);
173 } else {
174 // Make sure this is an address that we've already handed out.
175 if (!llvm::is_contained(m_wrapper_args_addrs, args_addr_ref))
176 return false;
177 }
178
179 // TODO: verify fun_addr needs to be a callable address
180 Scalar fun_addr(
181 m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
182 uint64_t first_offset = m_member_offsets[0];
183 process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
184 process->GetAddressByteSize(), error);
185
186 // FIXME: We will need to extend this for Variadic functions.
187
188 Status value_error;
189
190 size_t num_args = arg_values.GetSize();
191 if (num_args != m_arg_values.GetSize()) {
192 diagnostic_manager.Printf(
194 "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
195 (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
196 return false;
197 }
198
199 for (size_t i = 0; i < num_args; i++) {
200 // FIXME: We should sanity check sizes.
201
202 uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
203 Value *arg_value = arg_values.GetValueAtIndex(i);
204
205 // FIXME: For now just do scalars:
206
207 // Special case: if it's a pointer, don't do anything (the ABI supports
208 // passing cstrings)
209
210 if (arg_value->GetValueType() == Value::ValueType::HostAddress &&
212 arg_value->GetCompilerType().IsPointerType())
213 continue;
214
215 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
216
217 if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
218 arg_scalar.GetByteSize(), error))
219 return false;
220 }
221
222 return true;
223}
224
226 lldb::addr_t &args_addr_ref,
227 DiagnosticManager &diagnostic_manager) {
228 // Since we might need to call allocate memory and maybe call code to make
229 // the caller, we need to be stopped.
230 Process *process = exe_ctx.GetProcessPtr();
231 if (!process) {
232 diagnostic_manager.PutString(lldb::eSeverityError, "no process");
233 return false;
234 }
235 if (process->GetState() != lldb::eStateStopped) {
236 diagnostic_manager.PutString(lldb::eSeverityError, "process running");
237 return false;
238 }
239 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
240 return false;
241 if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
242 return false;
243 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
244 return false;
245
246 Log *log = GetLog(LLDBLog::Step);
247 LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
248 m_jit_start_addr, args_addr_ref);
249
250 return true;
251}
252
254 ExecutionContext &exe_ctx, lldb::addr_t args_addr,
255 const EvaluateExpressionOptions &options,
256 DiagnosticManager &diagnostic_manager) {
258
259 LLDB_LOGF(log,
260 "-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
261 "thread plan to call function \"%s\" --",
262 m_name.c_str());
263
264 // FIXME: Use the errors Stream for better error reporting.
265 Thread *thread = exe_ctx.GetThreadPtr();
266 if (thread == nullptr) {
267 diagnostic_manager.PutString(
268 lldb::eSeverityError, "Can't call a function without a valid thread.");
269 return nullptr;
270 }
271
272 // Okay, now run the function:
273
274 Address wrapper_address(m_jit_start_addr);
275
276 lldb::addr_t args = {args_addr};
277
279 *thread, wrapper_address, CompilerType(), args, options));
280 new_plan_sp->SetIsControllingPlan(true);
281 new_plan_sp->SetOkayToDiscard(false);
282 return new_plan_sp;
283}
284
286 lldb::addr_t args_addr,
287 Value &ret_value) {
288 // Read the return value - it is the last field in the struct:
289 // FIXME: How does clang tell us there's no return value? We need to handle
290 // that case.
291 // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
292 // then use GetReturnValueObject
293 // to fetch the value. That way we can fetch any values we need.
294
296
297 LLDB_LOGF(log,
298 "-- [FunctionCaller::FetchFunctionResults] Fetching function "
299 "results for \"%s\"--",
300 m_name.c_str());
301
302 Process *process = exe_ctx.GetProcessPtr();
303
304 if (process == nullptr)
305 return false;
306
307 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
308
309 if (process != jit_process_sp.get())
310 return false;
311
313 ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
314 args_addr + m_return_offset, m_return_size, 0, error);
315
316 if (error.Fail())
317 return false;
318
321 return true;
322}
323
325 lldb::addr_t args_addr) {
326 std::list<lldb::addr_t>::iterator pos;
327 pos = llvm::find(m_wrapper_args_addrs, args_addr);
328 if (pos != m_wrapper_args_addrs.end())
329 m_wrapper_args_addrs.erase(pos);
330
331 exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
332}
333
335 ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
336 const EvaluateExpressionOptions &options,
337 DiagnosticManager &diagnostic_manager, Value &results) {
339
340 Debugger *debugger =
341 exe_ctx.GetTargetPtr() ? &exe_ctx.GetTargetPtr()->GetDebugger() : nullptr;
342 Progress progress("Calling function", FunctionName(), {}, debugger);
343
344 // FunctionCaller::ExecuteFunction execution is always just to get the
345 // result. Unless explicitly asked for, ignore breakpoints and unwind on
346 // error.
347 const bool enable_debugging =
348 exe_ctx.GetTargetPtr() &&
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);
355
356 lldb::addr_t args_addr;
357
358 if (args_addr_ptr != nullptr)
359 args_addr = *args_addr_ptr;
360 else
361 args_addr = LLDB_INVALID_ADDRESS;
362
363 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
365
366 if (args_addr == LLDB_INVALID_ADDRESS) {
367 if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
369 }
370
372
373 LLDB_LOGF(log,
374 "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
375 m_name.c_str());
376
378 exe_ctx, args_addr, real_options, diagnostic_manager);
379 if (!call_plan_sp)
381
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())
387
388 PolicyStack::Guard expr_policy_guard =
390
391 return_value = exe_ctx.GetProcessRef().RunThreadPlan(
392 exe_ctx, call_plan_sp, real_options, diagnostic_manager);
393
394 if (return_value != lldb::eExpressionCompleted) {
395 LLDB_LOGF(log,
396 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
397 "completed abnormally: %s ==",
398 m_name.c_str(), toString(return_value).c_str());
399 } else {
400 LLDB_LOGF(log,
401 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
402 "completed normally ==",
403 m_name.c_str());
404 }
405
406 if (exe_ctx.GetProcessPtr())
407 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
408
409 if (args_addr_ptr != nullptr)
410 *args_addr_ptr = args_addr;
411
412 if (return_value != lldb::eExpressionCompleted)
413 return return_value;
414
415 FetchFunctionResults(exe_ctx, args_addr, results);
416
417 if (args_addr_ptr == nullptr)
418 DeallocateFunctionResults(exe_ctx, args_addr);
419
421}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:390
A section + offset based address class.
Definition Address.h:62
Generic representation of a type in a programming language.
bool IsPointerType(CompilerType *pointee_type=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:100
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
size_t Printf(lldb::Severity severity, const char *format,...) __attribute__((format(printf
void SetUnwindOnError(bool unwind=false)
Definition Target.h:396
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:400
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual lldb::ProcessSP CalculateProcess()=0
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Process & GetProcessRef() const
Returns a reference to the process object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
Definition Expression.h:95
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition Expression.h:89
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition Expression.h:92
Expression(Target &target)
A file utility class.
Definition FileSpec.h:57
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:359
std::string m_wrapper_struct_name
The name of the struct that contains the target function address, arguments, and result.
Function * m_function_ptr
The function we're going to call.
std::list< lldb::addr_t > m_wrapper_args_addrs
The addresses of the arguments to the wrapper function.
FunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name)
Constructor.
~FunctionCaller() override
Destructor.
Address m_function_addr
If we don't have the FunctionSP, we at least need the address & return type.
size_t m_struct_size
These values are populated by the ASTStructExtractor.
void DeallocateFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Deallocate the arguments structure.
uint64_t m_return_offset
The offset of the result variable in the struct, in bytes.
bool m_struct_valid
True if the ASTStructExtractor has populated the variables below.
bool InsertFunction(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function wrapper and its default argument struct.
ValueList m_arg_values
The default values of the arguments.
std::string m_wrapper_function_name
The name of the wrapper function.
lldb::ExpressionResults ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager, Value &results)
Run the function this FunctionCaller was created with.
lldb::ThreadPlanSP GetThreadPlanToCallFunction(ExecutionContext &exe_ctx, lldb::addr_t args_addr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Get a thread plan to run the function this FunctionCaller was created with.
virtual unsigned CompileFunction(lldb::ThreadSP thread_to_use_sp, DiagnosticManager &diagnostic_manager)=0
Compile the wrapper function.
bool FetchFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
Get the result of the function from its struct.
CompilerType m_function_return_type
The opaque clang qual type for the function return type.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
uint64_t m_return_size
The size of the result variable, in bytes.
bool m_compiled
True if the wrapper function has already been parsed.
std::string m_name
The name of this clang function - for debugging purposes.
bool m_JITted
True if the wrapper function has already been JIT-compiled.
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
std::unique_ptr< ExpressionParser > m_parser
The parser responsible for compiling the function.
const char * FunctionName() override
Return the function name that should be used for executing the expression.
std::vector< uint64_t > m_member_offsets
The offset of each member in the struct, in bytes.
bool WriteFunctionWrapper(ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager)
Insert the default function wrapper (using the JIT)
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
RAII guard that pops a policy on destruction.
Definition Policy.h:110
Guard PushPublicStateRunningExpression()
Definition Policy.h:138
static PolicyStack & Get()
Definition Policy.cpp:21
A plug-in interface definition class for debugging a process.
Definition Process.h:359
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:5172
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2701
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1282
void SetRunningUserExpression(bool on)
Definition Process.cpp:1482
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
Definition Process.cpp:2456
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2764
uint32_t GetAddressByteSize() const
Definition Process.cpp:3930
size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, size_t size, Status &error)
Write all or part of a scalar value to memory.
Definition Process.cpp:2640
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
A Progress indicator helper class.
Definition Progress.h:60
size_t GetByteSize() const
Definition Scalar.cpp:162
An error handling class.
Definition Status.h:118
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
bool Success() const
Test for success condition.
Definition Status.cpp:303
bool GetDebugUtilityExpression() const
Definition Target.cpp:5880
Debugger & GetDebugger() const
Definition Target.h:1326
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1243
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:698
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
Definition Value.h:53
@ Scalar
A raw scalar value.
Definition Value.h:46
ValueType GetValueType() const
Definition Value.cpp:111
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:589
void SetValueType(ValueType value_type)
Definition Value.h:90
ContextType GetContextType() const
Definition Value.h:88
const CompilerType & GetCompilerType()
Definition Value.cpp:247
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:339
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
@ eStateStopped
Process or thread is stopped and can be examined.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
std::weak_ptr< lldb_private::Process > ProcessWP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP