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 
9 
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"
30 
31 using namespace lldb_private;
32 
33 char FunctionCaller::ID;
34 
35 // FunctionCaller constructor
36 FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope,
37                                const CompilerType &return_type,
38                                const Address &functionAddress,
39                                const ValueList &arg_value_list,
40                                const char *name)
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_arg_values(arg_value_list), m_compiled(false),
48       m_JITted(false) {
49   m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
50   // Can't make a FunctionCaller without a process.
51   assert(m_jit_process_wp.lock());
52 }
53 
54 // Destructor
55 FunctionCaller::~FunctionCaller() {
56   lldb::ProcessSP process_sp(m_jit_process_wp.lock());
57   if (process_sp) {
58     lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
59     if (jit_module_sp)
60       process_sp->GetTarget().GetImages().Remove(jit_module_sp);
61   }
62 }
63 
64 bool FunctionCaller::WriteFunctionWrapper(
65     ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
66   Process *process = exe_ctx.GetProcessPtr();
67 
68   if (!process)
69     return false;
70 
71   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
72 
73   if (process != jit_process_sp.get())
74     return false;
75 
76   if (!m_compiled)
77     return false;
78 
79   if (m_JITted)
80     return true;
81 
82   bool can_interpret = false; // should stay that way
83 
84   Status jit_error(m_parser->PrepareForExecution(
85       m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
86       can_interpret, eExecutionPolicyAlways));
87 
88   if (!jit_error.Success()) {
89     diagnostic_manager.Printf(eDiagnosticSeverityError,
90                               "Error in PrepareForExecution: %s.",
91                               jit_error.AsCString());
92     return false;
93   }
94 
95   if (m_parser->GetGenerateDebugInfo()) {
96     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
97 
98     if (jit_module_sp) {
99       ConstString const_func_name(FunctionName());
100       FileSpec jit_file;
101       jit_file.GetFilename() = const_func_name;
102       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
103       m_jit_module_wp = jit_module_sp;
104       process->GetTarget().GetImages().Append(jit_module_sp,
105                                               true /* notify */);
106     }
107   }
108   if (process && m_jit_start_addr)
109     m_jit_process_wp = process->shared_from_this();
110 
111   m_JITted = true;
112 
113   return true;
114 }
115 
116 bool FunctionCaller::WriteFunctionArguments(
117     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
118     DiagnosticManager &diagnostic_manager) {
119   return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
120                                 diagnostic_manager);
121 }
122 
123 // FIXME: Assure that the ValueList we were passed in is consistent with the one
124 // that defined this function.
125 
126 bool FunctionCaller::WriteFunctionArguments(
127     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
128     ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
129   // All the information to reconstruct the struct is provided by the
130   // StructExtractor.
131   if (!m_struct_valid) {
132     diagnostic_manager.PutString(eDiagnosticSeverityError,
133                                  "Argument information was not correctly "
134                                  "parsed, so the function cannot be called.");
135     return false;
136   }
137 
138   Status error;
139   lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
140 
141   Process *process = exe_ctx.GetProcessPtr();
142 
143   if (process == nullptr)
144     return return_value;
145 
146   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
147 
148   if (process != jit_process_sp.get())
149     return false;
150 
151   if (args_addr_ref == LLDB_INVALID_ADDRESS) {
152     args_addr_ref = process->AllocateMemory(
153         m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
154         error);
155     if (args_addr_ref == LLDB_INVALID_ADDRESS)
156       return false;
157     m_wrapper_args_addrs.push_back(args_addr_ref);
158   } else {
159     // Make sure this is an address that we've already handed out.
160     if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
161              args_addr_ref) == m_wrapper_args_addrs.end()) {
162       return false;
163     }
164   }
165 
166   // TODO: verify fun_addr needs to be a callable address
167   Scalar fun_addr(
168       m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
169   uint64_t first_offset = m_member_offsets[0];
170   process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
171                                process->GetAddressByteSize(), error);
172 
173   // FIXME: We will need to extend this for Variadic functions.
174 
175   Status value_error;
176 
177   size_t num_args = arg_values.GetSize();
178   if (num_args != m_arg_values.GetSize()) {
179     diagnostic_manager.Printf(
180         eDiagnosticSeverityError,
181         "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
182         (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
183     return false;
184   }
185 
186   for (size_t i = 0; i < num_args; i++) {
187     // FIXME: We should sanity check sizes.
188 
189     uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
190     Value *arg_value = arg_values.GetValueAtIndex(i);
191 
192     // FIXME: For now just do scalars:
193 
194     // Special case: if it's a pointer, don't do anything (the ABI supports
195     // passing cstrings)
196 
197     if (arg_value->GetValueType() == Value::ValueType::HostAddress &&
198         arg_value->GetContextType() == Value::ContextType::Invalid &&
199         arg_value->GetCompilerType().IsPointerType())
200       continue;
201 
202     const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
203 
204     if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
205                                       arg_scalar.GetByteSize(), error))
206       return false;
207   }
208 
209   return true;
210 }
211 
212 bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,
213                                     lldb::addr_t &args_addr_ref,
214                                     DiagnosticManager &diagnostic_manager) {
215   if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
216     return false;
217   if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
218     return false;
219   if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
220     return false;
221 
222   Log *log = GetLog(LLDBLog::Step);
223   LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
224             m_jit_start_addr, args_addr_ref);
225 
226   return true;
227 }
228 
229 lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(
230     ExecutionContext &exe_ctx, lldb::addr_t args_addr,
231     const EvaluateExpressionOptions &options,
232     DiagnosticManager &diagnostic_manager) {
233   Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
234 
235   LLDB_LOGF(log,
236             "-- [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 == nullptr) {
243     diagnostic_manager.PutString(
244         eDiagnosticSeverityError,
245         "Can't call a function without a valid thread.");
246     return nullptr;
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->SetIsControllingPlan(true);
258   new_plan_sp->SetOkayToDiscard(false);
259   return new_plan_sp;
260 }
261 
262 bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,
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 
272   Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
273 
274   LLDB_LOGF(log,
275             "-- [FunctionCaller::FetchFunctionResults] Fetching function "
276             "results for \"%s\"--",
277             m_name.c_str());
278 
279   Process *process = exe_ctx.GetProcessPtr();
280 
281   if (process == nullptr)
282     return false;
283 
284   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
285 
286   if (process != jit_process_sp.get())
287     return false;
288 
289   Status error;
290   ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
291       args_addr + m_return_offset, m_return_size, 0, error);
292 
293   if (error.Fail())
294     return false;
295 
296   ret_value.SetCompilerType(m_function_return_type);
297   ret_value.SetValueType(Value::ValueType::Scalar);
298   return true;
299 }
300 
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(),
305                   args_addr);
306   if (pos != m_wrapper_args_addrs.end())
307     m_wrapper_args_addrs.erase(pos);
308 
309   exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
310 }
311 
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;
317 
318   // FunctionCaller::ExecuteFunction execution is always just to get the
319   // result. Unless explicitly asked for, ignore breakpoints and unwind on
320   // error.
321   const bool enable_debugging =
322       exe_ctx.GetTargetPtr() &&
323       exe_ctx.GetTargetPtr()->GetDebugUtilityExpression();
324   EvaluateExpressionOptions real_options = options;
325   real_options.SetDebug(false); // This halts the expression for debugging.
326   real_options.SetGenerateDebugInfo(enable_debugging);
327   real_options.SetUnwindOnError(!enable_debugging);
328   real_options.SetIgnoreBreakpoints(!enable_debugging);
329 
330   lldb::addr_t args_addr;
331 
332   if (args_addr_ptr != nullptr)
333     args_addr = *args_addr_ptr;
334   else
335     args_addr = LLDB_INVALID_ADDRESS;
336 
337   if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
338     return lldb::eExpressionSetupError;
339 
340   if (args_addr == LLDB_INVALID_ADDRESS) {
341     if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
342       return lldb::eExpressionSetupError;
343   }
344 
345   Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
346 
347   LLDB_LOGF(log,
348             "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
349             m_name.c_str());
350 
351   lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(
352       exe_ctx, args_addr, real_options, diagnostic_manager);
353   if (!call_plan_sp)
354     return lldb::eExpressionSetupError;
355 
356   // We need to make sure we record the fact that we are running an expression
357   // here otherwise this fact will fail to be recorded when fetching an
358   // Objective-C object description
359   if (exe_ctx.GetProcessPtr())
360     exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
361 
362   return_value = exe_ctx.GetProcessRef().RunThreadPlan(
363       exe_ctx, call_plan_sp, real_options, diagnostic_manager);
364 
365   if (log) {
366     if (return_value != lldb::eExpressionCompleted) {
367       LLDB_LOGF(log,
368                 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
369                 "completed abnormally: %s ==",
370                 m_name.c_str(),
371                 Process::ExecutionResultAsCString(return_value));
372     } else {
373       LLDB_LOGF(log,
374                 "== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
375                 "completed normally ==",
376                 m_name.c_str());
377     }
378   }
379 
380   if (exe_ctx.GetProcessPtr())
381     exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
382 
383   if (args_addr_ptr != nullptr)
384     *args_addr_ptr = args_addr;
385 
386   if (return_value != lldb::eExpressionCompleted)
387     return return_value;
388 
389   FetchFunctionResults(exe_ctx, args_addr, results);
390 
391   if (args_addr_ptr == nullptr)
392     DeallocateFunctionResults(exe_ctx, args_addr);
393 
394   return lldb::eExpressionCompleted;
395 }
396