LLDB  mainline
FunctionCaller.cpp
Go to the documentation of this file.
1 //===-- FunctionCaller.cpp ---------------------------------------*- C++-*-===//
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 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ValueObject.h"
17 #include "lldb/Symbol/Function.h"
18 #include "lldb/Symbol/Type.h"
20 #include "lldb/Target/Process.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Target/ThreadPlan.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/State.h"
29 
30 using namespace lldb_private;
31 
32 // FunctionCaller constructor
34  const CompilerType &return_type,
35  const Address &functionAddress,
36  const ValueList &arg_value_list,
37  const char *name)
38  : Expression(exe_scope, eKindFunctionCaller),
39  m_execution_unit_sp(), m_parser(),
40  m_jit_module_wp(), m_name(name ? name : "<unknown>"),
41  m_function_ptr(NULL), m_function_addr(functionAddress),
42  m_function_return_type(return_type),
43  m_wrapper_function_name("__lldb_caller_function"),
44  m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
45  m_struct_valid(false), m_arg_values(arg_value_list), m_compiled(false),
46  m_JITted(false) {
47  m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
48  // Can't make a FunctionCaller without a process.
49  assert(m_jit_process_wp.lock());
50 }
51 
52 // Destructor
54  lldb::ProcessSP process_sp(m_jit_process_wp.lock());
55  if (process_sp) {
56  lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
57  if (jit_module_sp)
58  process_sp->GetTarget().GetImages().Remove(jit_module_sp);
59  }
60 }
61 
63  ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
64  Process *process = exe_ctx.GetProcessPtr();
65 
66  if (!process)
67  return false;
68 
69  lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
70 
71  if (process != jit_process_sp.get())
72  return false;
73 
74  if (!m_compiled)
75  return false;
76 
77  if (m_JITted)
78  return true;
79 
80  bool can_interpret = false; // should stay that way
81 
82  Status jit_error(m_parser->PrepareForExecution(
84  can_interpret, eExecutionPolicyAlways));
85 
86  if (!jit_error.Success()) {
87  diagnostic_manager.Printf(eDiagnosticSeverityError,
88  "Error in PrepareForExecution: %s.",
89  jit_error.AsCString());
90  return false;
91  }
92 
93  if (m_parser->GetGenerateDebugInfo()) {
94  lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
95 
96  if (jit_module_sp) {
97  ConstString const_func_name(FunctionName());
98  FileSpec jit_file;
99  jit_file.GetFilename() = const_func_name;
100  jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
101  m_jit_module_wp = jit_module_sp;
102  process->GetTarget().GetImages().Append(jit_module_sp,
103  true /* notify */);
104  }
105  }
106  if (process && m_jit_start_addr)
107  m_jit_process_wp = process->shared_from_this();
108 
109  m_JITted = true;
110 
111  return true;
112 }
113 
115  ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
116  DiagnosticManager &diagnostic_manager) {
117  return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
118  diagnostic_manager);
119 }
120 
121 // FIXME: Assure that the ValueList we were passed in is consistent with the one
122 // that defined this function.
123 
125  ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
126  ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
127  // All the information to reconstruct the struct is provided by the
128  // StructExtractor.
129  if (!m_struct_valid) {
130  diagnostic_manager.PutString(eDiagnosticSeverityError,
131  "Argument information was not correctly "
132  "parsed, so the function cannot be called.");
133  return false;
134  }
135 
136  Status error;
138 
139  Process *process = exe_ctx.GetProcessPtr();
140 
141  if (process == NULL)
142  return return_value;
143 
144  lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
145 
146  if (process != jit_process_sp.get())
147  return false;
148 
149  if (args_addr_ref == LLDB_INVALID_ADDRESS) {
150  args_addr_ref = process->AllocateMemory(
151  m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
152  error);
153  if (args_addr_ref == LLDB_INVALID_ADDRESS)
154  return false;
155  m_wrapper_args_addrs.push_back(args_addr_ref);
156  } else {
157  // Make sure this is an address that we've already handed out.
158  if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
159  args_addr_ref) == m_wrapper_args_addrs.end()) {
160  return false;
161  }
162  }
163 
164  // TODO: verify fun_addr needs to be a callable address
165  Scalar fun_addr(
167  uint64_t first_offset = m_member_offsets[0];
168  process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
169  process->GetAddressByteSize(), error);
170 
171  // FIXME: We will need to extend this for Variadic functions.
172 
173  Status value_error;
174 
175  size_t num_args = arg_values.GetSize();
176  if (num_args != m_arg_values.GetSize()) {
177  diagnostic_manager.Printf(
179  "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
180  (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
181  return false;
182  }
183 
184  for (size_t i = 0; i < num_args; i++) {
185  // FIXME: We should sanity check sizes.
186 
187  uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
188  Value *arg_value = arg_values.GetValueAtIndex(i);
189 
190  // FIXME: For now just do scalars:
191 
192  // Special case: if it's a pointer, don't do anything (the ABI supports
193  // passing cstrings)
194 
195  if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
196  arg_value->GetContextType() == Value::eContextTypeInvalid &&
197  arg_value->GetCompilerType().IsPointerType())
198  continue;
199 
200  const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
201 
202  if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
203  arg_scalar.GetByteSize(), error))
204  return false;
205  }
206 
207  return true;
208 }
209 
211  lldb::addr_t &args_addr_ref,
212  DiagnosticManager &diagnostic_manager) {
213  if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
214  return false;
215  if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
216  return false;
217  if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
218  return false;
219 
221  if (log)
222  log->Printf("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
223  m_jit_start_addr, args_addr_ref);
224 
225  return true;
226 }
227 
229  ExecutionContext &exe_ctx, lldb::addr_t args_addr,
230  const EvaluateExpressionOptions &options,
231  DiagnosticManager &diagnostic_manager) {
234 
235  if (log)
236  log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
237  "thread plan to call function \"%s\" --",
238  m_name.c_str());
239 
240  // FIXME: Use the errors Stream for better error reporting.
241  Thread *thread = exe_ctx.GetThreadPtr();
242  if (thread == NULL) {
243  diagnostic_manager.PutString(
245  "Can't call a function without a valid thread.");
246  return NULL;
247  }
248 
249  // Okay, now run the function:
250 
251  Address wrapper_address(m_jit_start_addr);
252 
253  lldb::addr_t args = {args_addr};
254 
255  lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(
256  *thread, wrapper_address, CompilerType(), args, options));
257  new_plan_sp->SetIsMasterPlan(true);
258  new_plan_sp->SetOkayToDiscard(false);
259  return new_plan_sp;
260 }
261 
263  lldb::addr_t args_addr,
264  Value &ret_value) {
265  // Read the return value - it is the last field in the struct:
266  // FIXME: How does clang tell us there's no return value? We need to handle
267  // that case.
268  // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
269  // then use GetReturnValueObject
270  // to fetch the value. That way we can fetch any values we need.
271 
274 
275  if (log)
276  log->Printf("-- [FunctionCaller::FetchFunctionResults] Fetching function "
277  "results for \"%s\"--",
278  m_name.c_str());
279 
280  Process *process = exe_ctx.GetProcessPtr();
281 
282  if (process == NULL)
283  return false;
284 
285  lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
286 
287  if (process != jit_process_sp.get())
288  return false;
289 
290  Status error;
291  ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
292  args_addr + m_return_offset, m_return_size, 0, error);
293 
294  if (error.Fail())
295  return false;
296 
299  return true;
300 }
301 
303  lldb::addr_t args_addr) {
304  std::list<lldb::addr_t>::iterator pos;
305  pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
306  args_addr);
307  if (pos != m_wrapper_args_addrs.end())
308  m_wrapper_args_addrs.erase(pos);
309 
310  exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
311 }
312 
314  ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
315  const EvaluateExpressionOptions &options,
316  DiagnosticManager &diagnostic_manager, Value &results) {
318 
319  // FunctionCaller::ExecuteFunction execution is always just to get the
320  // result. Do make sure we ignore breakpoints, unwind on error, and don't try
321  // to debug it.
322  EvaluateExpressionOptions real_options = options;
323  real_options.SetDebug(false);
324  real_options.SetUnwindOnError(true);
325  real_options.SetIgnoreBreakpoints(true);
326 
327  lldb::addr_t args_addr;
328 
329  if (args_addr_ptr != NULL)
330  args_addr = *args_addr_ptr;
331  else
332  args_addr = LLDB_INVALID_ADDRESS;
333 
334  if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
336 
337  if (args_addr == LLDB_INVALID_ADDRESS) {
338  if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
340  }
341 
344 
345  if (log)
346  log->Printf(
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)
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  log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
367  "completed abnormally ==",
368  m_name.c_str());
369  } else {
370  log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
371  "completed normally ==",
372  m_name.c_str());
373  }
374  }
375 
376  if (exe_ctx.GetProcessPtr())
377  exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
378 
379  if (args_addr_ptr != NULL)
380  *args_addr_ptr = args_addr;
381 
382  if (return_value != lldb::eExpressionCompleted)
383  return return_value;
384 
385  FetchFunctionResults(exe_ctx, args_addr, results);
386 
387  if (args_addr_ptr == NULL)
388  DeallocateFunctionResults(exe_ctx, args_addr);
389 
391 }
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.
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:289
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition: Address.cpp:317
ConstString & GetFilename()
Filename string get accessor.
Definition: FileSpec.cpp:369
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn&#39;t need to (e.g.
Definition: Expression.h:104
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
void DeallocateFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Deallocate the arguments structure.
size_t m_struct_size
These values are populated by the ASTStructExtractor.
size_t GetByteSize() const
Definition: Scalar.cpp:187
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition: Process.cpp:4648
~FunctionCaller() override
Destructor.
std::unique_ptr< ExpressionParser > m_parser
The parser responsible for compiling the function.
bool m_compiled
True if the wrapper function has already been parsed.
bool m_JITted
True if the wrapper function has already been JIT-compiled.
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:285
A file utility class.
Definition: FileSpec.h:55
virtual lldb::ProcessSP CalculateProcess()=0
Encapsulates a single expression for use in lldb.
Definition: Expression.h:33
Value * GetValueAtIndex(size_t idx)
Definition: Value.cpp:701
void SetValueType(ValueType value_type)
Definition: Value.h:154
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
bool FetchFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
Get the result of the function from its struct.
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
const char * FunctionName() override
Return the function name that should be used for executing the expression.
bool IsPointerType(CompilerType *pointee_type=nullptr) const
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition: Process.cpp:2344
ValueType GetValueType() const
Definition: Value.cpp:114
Target * GetTargetPtr() const
Returns a pointer to the target object.
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition: Process.cpp:2415
void SetRunningUserExpression(bool on)
Definition: Process.cpp:1531
bool WriteFunctionWrapper(ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager)
Insert the default function wrapper (using the JIT)
std::list< lldb::addr_t > m_wrapper_args_addrs
The addresses of the arguments to the wrapper function.
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3370
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
ContextType GetContextType() const
Definition: Value.h:152
FunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name)
Constructor.
A plug-in interface definition class for debugging a process.
Definition: Process.h:353
Process * GetProcessPtr() const
Returns a pointer to the process object.
size_t size_t PutString(DiagnosticSeverity severity, llvm::StringRef str)
lldb::ProcessWP m_jit_process_wp
Expression&#39;s always have to have a target...
Definition: Expression.h:101
uint64_t m_return_size
The size of the result variable, in bytes.
const CompilerType & GetCompilerType()
Definition: Value.cpp:239
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.
A section + offset based address class.
Definition: Address.h:80
Address m_function_addr
If we don&#39;t have the FunctionSP, we at least need the address & return type.
bool InsertFunction(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function wrapper and its default argument struct.
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:899
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
Definition: Expression.h:107
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1194
std::vector< uint64_t > m_member_offsets
The offset of each member in the struct, in bytes.
uint64_t addr_t
Definition: lldb-types.h:83
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
A uniqued constant string class.
Definition: ConstString.h:38
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
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:2284
Log * GetLogIfAnyCategoriesSet(uint32_t mask)
Definition: Logging.cpp:61
void SetCompilerType(const CompilerType &compiler_type)
Definition: Value.cpp:268
#define LIBLLDB_LOG_EXPRESSIONS
Definition: Logging.h:22
virtual unsigned CompileFunction(lldb::ThreadSP thread_to_use_sp, DiagnosticManager &diagnostic_manager)=0
Compile the wrapper function.
const Scalar & GetScalar() const
Definition: Value.h:178
ValueList m_arg_values
The default values of the arguments.
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:2150
Process & GetProcessRef() const
Returns a reference to the process object.
Scalar & ResolveValue(ExecutionContext *exe_ctx)
Definition: Value.cpp:585
#define LIBLLDB_LOG_STEP
Definition: Logging.h:21
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
std::string m_name
The name of this clang function - for debugging purposes.
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.
An error handling class.
Definition: Status.h:44
CompilerType m_function_return_type
The opaque clang qual type for the function return type.