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/State.h"
31
32using namespace lldb_private;
33
35
36// FunctionCaller constructor
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) {
52 // Can't make a FunctionCaller without a process.
53 assert(m_jit_process_wp.lock());
54}
55
56// Destructor
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(jit_module_sp);
63 }
64}
65
67 ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
68 Process *process = exe_ctx.GetProcessPtr();
69
70 if (!process) {
71 diagnostic_manager.Printf(lldb::eSeverityError, "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(lldb::eSeverityError,
79 "process does not match the stored process.");
80 return false;
81 }
82
83 if (process->GetState() != lldb::eStateStopped) {
84 diagnostic_manager.Printf(lldb::eSeverityError, "process is not stopped");
85 return false;
86 }
87
88 if (!m_compiled) {
89 diagnostic_manager.Printf(lldb::eSeverityError, "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(
100 can_interpret, eExecutionPolicyAlways));
101
102 if (!jit_error.Success()) {
103 diagnostic_manager.Printf(lldb::eSeverityError,
104 "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(jit_file, ConstString());
117 m_jit_module_wp = jit_module_sp;
118 process->GetTarget().GetImages().Append(jit_module_sp,
119 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
131 ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
132 DiagnosticManager &diagnostic_manager) {
133 return WriteFunctionArguments(exe_ctx, args_addr_ref, 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
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(lldb::eSeverityError,
147 "Argument information was not correctly "
148 "parsed, so the function cannot be called.");
149 return false;
150 }
151
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 m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
168 error);
169 if (args_addr_ref == LLDB_INVALID_ADDRESS)
170 return false;
171 m_wrapper_args_addrs.push_back(args_addr_ref);
172 } else {
173 // Make sure this is an address that we've already handed out.
174 if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
175 args_addr_ref) == m_wrapper_args_addrs.end()) {
176 return false;
177 }
178 }
179
180 // TODO: verify fun_addr needs to be a callable address
181 Scalar fun_addr(
183 uint64_t first_offset = m_member_offsets[0];
184 process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
185 process->GetAddressByteSize(), error);
186
187 // FIXME: We will need to extend this for Variadic functions.
188
189 Status value_error;
190
191 size_t num_args = arg_values.GetSize();
192 if (num_args != m_arg_values.GetSize()) {
193 diagnostic_manager.Printf(
195 "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
196 (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
197 return false;
198 }
199
200 for (size_t i = 0; i < num_args; i++) {
201 // FIXME: We should sanity check sizes.
202
203 uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
204 Value *arg_value = arg_values.GetValueAtIndex(i);
205
206 // FIXME: For now just do scalars:
207
208 // Special case: if it's a pointer, don't do anything (the ABI supports
209 // passing cstrings)
210
211 if (arg_value->GetValueType() == Value::ValueType::HostAddress &&
213 arg_value->GetCompilerType().IsPointerType())
214 continue;
215
216 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
217
218 if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
219 arg_scalar.GetByteSize(), error))
220 return false;
221 }
222
223 return true;
224}
225
227 lldb::addr_t &args_addr_ref,
228 DiagnosticManager &diagnostic_manager) {
229 // Since we might need to call allocate memory and maybe call code to make
230 // the caller, we need to be stopped.
231 Process *process = exe_ctx.GetProcessPtr();
232 if (!process) {
233 diagnostic_manager.PutString(lldb::eSeverityError, "no process");
234 return false;
235 }
236 if (process->GetState() != lldb::eStateStopped) {
237 diagnostic_manager.PutString(lldb::eSeverityError, "process running");
238 return false;
239 }
240 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
241 return false;
242 if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
243 return false;
244 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
245 return false;
246
247 Log *log = GetLog(LLDBLog::Step);
248 LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
249 m_jit_start_addr, args_addr_ref);
250
251 return true;
252}
253
255 ExecutionContext &exe_ctx, lldb::addr_t args_addr,
256 const EvaluateExpressionOptions &options,
257 DiagnosticManager &diagnostic_manager) {
259
260 LLDB_LOGF(log,
261 "-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
262 "thread plan to call function \"%s\" --",
263 m_name.c_str());
264
265 // FIXME: Use the errors Stream for better error reporting.
266 Thread *thread = exe_ctx.GetThreadPtr();
267 if (thread == nullptr) {
268 diagnostic_manager.PutString(
269 lldb::eSeverityError, "Can't call a function without a valid thread.");
270 return nullptr;
271 }
272
273 // Okay, now run the function:
274
275 Address wrapper_address(m_jit_start_addr);
276
277 lldb::addr_t args = {args_addr};
278
280 *thread, wrapper_address, CompilerType(), args, options));
281 new_plan_sp->SetIsControllingPlan(true);
282 new_plan_sp->SetOkayToDiscard(false);
283 return new_plan_sp;
284}
285
287 lldb::addr_t args_addr,
288 Value &ret_value) {
289 // Read the return value - it is the last field in the struct:
290 // FIXME: How does clang tell us there's no return value? We need to handle
291 // that case.
292 // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
293 // then use GetReturnValueObject
294 // to fetch the value. That way we can fetch any values we need.
295
297
298 LLDB_LOGF(log,
299 "-- [FunctionCaller::FetchFunctionResults] Fetching function "
300 "results for \"%s\"--",
301 m_name.c_str());
302
303 Process *process = exe_ctx.GetProcessPtr();
304
305 if (process == nullptr)
306 return false;
307
308 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
309
310 if (process != jit_process_sp.get())
311 return false;
312
314 ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
315 args_addr + m_return_offset, m_return_size, 0, error);
316
317 if (error.Fail())
318 return false;
319
322 return true;
323}
324
326 lldb::addr_t args_addr) {
327 std::list<lldb::addr_t>::iterator pos;
328 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
329 args_addr);
330 if (pos != m_wrapper_args_addrs.end())
331 m_wrapper_args_addrs.erase(pos);
332
333 exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
334}
335
337 ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
338 const EvaluateExpressionOptions &options,
339 DiagnosticManager &diagnostic_manager, Value &results) {
341
342 Debugger *debugger =
343 exe_ctx.GetTargetPtr() ? &exe_ctx.GetTargetPtr()->GetDebugger() : nullptr;
344 Progress progress("Calling function", FunctionName(), {}, debugger);
345
346 // FunctionCaller::ExecuteFunction execution is always just to get the
347 // result. Unless explicitly asked for, ignore breakpoints and unwind on
348 // error.
349 const bool enable_debugging =
350 exe_ctx.GetTargetPtr() &&
352 EvaluateExpressionOptions real_options = options;
353 real_options.SetDebug(false); // This halts the expression for debugging.
354 real_options.SetGenerateDebugInfo(enable_debugging);
355 real_options.SetUnwindOnError(!enable_debugging);
356 real_options.SetIgnoreBreakpoints(!enable_debugging);
357
358 lldb::addr_t args_addr;
359
360 if (args_addr_ptr != nullptr)
361 args_addr = *args_addr_ptr;
362 else
363 args_addr = LLDB_INVALID_ADDRESS;
364
365 if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
367
368 if (args_addr == LLDB_INVALID_ADDRESS) {
369 if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
371 }
372
374
375 LLDB_LOGF(log,
376 "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
377 m_name.c_str());
378
380 exe_ctx, args_addr, real_options, diagnostic_manager);
381 if (!call_plan_sp)
383
384 // We need to make sure we record the fact that we are running an expression
385 // here otherwise this fact will fail to be recorded when fetching an
386 // Objective-C object description
387 if (exe_ctx.GetProcessPtr())
389
390 return_value = exe_ctx.GetProcessRef().RunThreadPlan(
391 exe_ctx, call_plan_sp, real_options, diagnostic_manager);
392
393 if (log) {
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
407 if (exe_ctx.GetProcessPtr())
408 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
409
410 if (args_addr_ptr != nullptr)
411 *args_addr_ptr = args_addr;
412
413 if (return_value != lldb::eExpressionCompleted)
414 return return_value;
415
416 FetchFunctionResults(exe_ctx, args_addr, results);
417
418 if (args_addr_ptr == nullptr)
419 DeallocateFunctionResults(exe_ctx, args_addr);
420
422}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition: Log.h:376
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition: Address.cpp:338
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
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:80
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:359
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:363
"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.
Encapsulates a single expression for use in lldb.
Definition: Expression.h:31
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
Definition: Expression.h:94
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:88
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition: Expression.h:91
A file utility class.
Definition: FileSpec.h:56
void SetFilename(ConstString filename)
Filename string set accessor.
Definition: FileSpec.cpp:345
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.
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.
Definition: ModuleList.cpp:247
A plug-in interface definition class for debugging a process.
Definition: Process.h:343
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition: Process.cpp:4956
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition: Process.cpp:2417
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1308
void SetRunningUserExpression(bool on)
Definition: Process.cpp:1494
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:2217
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition: Process.cpp:2489
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3615
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:2357
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1246
A Progress indicator helper class.
Definition: Progress.h:60
size_t GetByteSize() const
Definition: Scalar.cpp:132
An error handling class.
Definition: Status.h:115
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:195
bool Success() const
Test for success condition.
Definition: Status.cpp:280
bool GetDebugUtilityExpression() const
Definition: Target.cpp:5073
Debugger & GetDebugger()
Definition: Target.h:1080
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:997
Value * GetValueAtIndex(size_t idx)
Definition: Value.cpp:691
const Scalar & GetScalar() const
Definition: Value.h:112
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
@ Scalar
A raw scalar value.
ValueType GetValueType() const
Definition: Value.cpp:109
void SetCompilerType(const CompilerType &compiler_type)
Definition: Value.cpp:268
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition: Value.cpp:582
void SetValueType(ValueType value_type)
Definition: Value.h:89
ContextType GetContextType() const
Definition: Value.h:87
const CompilerType & GetCompilerType()
Definition: Value.cpp:239
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
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:332
const char * toString(AppleArm64ExceptionClass EC)
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
Definition: lldb-forward.h:453
@ 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
Definition: lldb-forward.h:389
std::weak_ptr< lldb_private::Process > ProcessWP
Definition: lldb-forward.h:392
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:373