]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Expression / FunctionCaller.cpp
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
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/Log.h"
28 #include "lldb/Utility/State.h"
29
30 using namespace lldb_private;
31
32 // FunctionCaller constructor
33 FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope,
34                                const CompilerType &return_type,
35                                const Address &functionAddress,
36                                const ValueList &arg_value_list,
37                                const char *name)
38     : Expression(exe_scope, eKindFunctionCaller), m_execution_unit_sp(),
39       m_parser(), m_jit_module_wp(), m_name(name ? name : "<unknown>"),
40       m_function_ptr(nullptr), m_function_addr(functionAddress),
41       m_function_return_type(return_type),
42       m_wrapper_function_name("__lldb_caller_function"),
43       m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
44       m_struct_valid(false), m_arg_values(arg_value_list), m_compiled(false),
45       m_JITted(false) {
46   m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
47   // Can't make a FunctionCaller without a process.
48   assert(m_jit_process_wp.lock());
49 }
50
51 // Destructor
52 FunctionCaller::~FunctionCaller() {
53   lldb::ProcessSP process_sp(m_jit_process_wp.lock());
54   if (process_sp) {
55     lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
56     if (jit_module_sp)
57       process_sp->GetTarget().GetImages().Remove(jit_module_sp);
58   }
59 }
60
61 bool FunctionCaller::WriteFunctionWrapper(
62     ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
63   Process *process = exe_ctx.GetProcessPtr();
64
65   if (!process)
66     return false;
67
68   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
69
70   if (process != jit_process_sp.get())
71     return false;
72
73   if (!m_compiled)
74     return false;
75
76   if (m_JITted)
77     return true;
78
79   bool can_interpret = false; // should stay that way
80
81   Status jit_error(m_parser->PrepareForExecution(
82       m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
83       can_interpret, eExecutionPolicyAlways));
84
85   if (!jit_error.Success()) {
86     diagnostic_manager.Printf(eDiagnosticSeverityError,
87                               "Error in PrepareForExecution: %s.",
88                               jit_error.AsCString());
89     return false;
90   }
91
92   if (m_parser->GetGenerateDebugInfo()) {
93     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
94
95     if (jit_module_sp) {
96       ConstString const_func_name(FunctionName());
97       FileSpec jit_file;
98       jit_file.GetFilename() = const_func_name;
99       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
100       m_jit_module_wp = jit_module_sp;
101       process->GetTarget().GetImages().Append(jit_module_sp, 
102                                               true /* notify */);
103     }
104   }
105   if (process && m_jit_start_addr)
106     m_jit_process_wp = process->shared_from_this();
107
108   m_JITted = true;
109
110   return true;
111 }
112
113 bool FunctionCaller::WriteFunctionArguments(
114     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
115     DiagnosticManager &diagnostic_manager) {
116   return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
117                                 diagnostic_manager);
118 }
119
120 // FIXME: Assure that the ValueList we were passed in is consistent with the one
121 // that defined this function.
122
123 bool FunctionCaller::WriteFunctionArguments(
124     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
125     ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
126   // All the information to reconstruct the struct is provided by the
127   // StructExtractor.
128   if (!m_struct_valid) {
129     diagnostic_manager.PutString(eDiagnosticSeverityError,
130                                  "Argument information was not correctly "
131                                  "parsed, so the function cannot be called.");
132     return false;
133   }
134
135   Status error;
136   lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
137
138   Process *process = exe_ctx.GetProcessPtr();
139
140   if (process == nullptr)
141     return return_value;
142
143   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
144
145   if (process != jit_process_sp.get())
146     return false;
147
148   if (args_addr_ref == LLDB_INVALID_ADDRESS) {
149     args_addr_ref = process->AllocateMemory(
150         m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
151         error);
152     if (args_addr_ref == LLDB_INVALID_ADDRESS)
153       return false;
154     m_wrapper_args_addrs.push_back(args_addr_ref);
155   } else {
156     // Make sure this is an address that we've already handed out.
157     if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
158              args_addr_ref) == m_wrapper_args_addrs.end()) {
159       return false;
160     }
161   }
162
163   // TODO: verify fun_addr needs to be a callable address
164   Scalar fun_addr(
165       m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
166   uint64_t first_offset = m_member_offsets[0];
167   process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
168                                process->GetAddressByteSize(), error);
169
170   // FIXME: We will need to extend this for Variadic functions.
171
172   Status value_error;
173
174   size_t num_args = arg_values.GetSize();
175   if (num_args != m_arg_values.GetSize()) {
176     diagnostic_manager.Printf(
177         eDiagnosticSeverityError,
178         "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
179         (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
180     return false;
181   }
182
183   for (size_t i = 0; i < num_args; i++) {
184     // FIXME: We should sanity check sizes.
185
186     uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
187     Value *arg_value = arg_values.GetValueAtIndex(i);
188
189     // FIXME: For now just do scalars:
190
191     // Special case: if it's a pointer, don't do anything (the ABI supports
192     // passing cstrings)
193
194     if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
195         arg_value->GetContextType() == Value::eContextTypeInvalid &&
196         arg_value->GetCompilerType().IsPointerType())
197       continue;
198
199     const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
200
201     if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
202                                       arg_scalar.GetByteSize(), error))
203       return false;
204   }
205
206   return true;
207 }
208
209 bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,
210                                     lldb::addr_t &args_addr_ref,
211                                     DiagnosticManager &diagnostic_manager) {
212   if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
213     return false;
214   if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
215     return false;
216   if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
217     return false;
218
219   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
220   if (log)
221     log->Printf("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
222                 m_jit_start_addr, args_addr_ref);
223
224   return true;
225 }
226
227 lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(
228     ExecutionContext &exe_ctx, lldb::addr_t args_addr,
229     const EvaluateExpressionOptions &options,
230     DiagnosticManager &diagnostic_manager) {
231   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
232                                                   LIBLLDB_LOG_STEP));
233
234   if (log)
235     log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
236                 "thread plan to call function \"%s\" --",
237                 m_name.c_str());
238
239   // FIXME: Use the errors Stream for better error reporting.
240   Thread *thread = exe_ctx.GetThreadPtr();
241   if (thread == nullptr) {
242     diagnostic_manager.PutString(
243         eDiagnosticSeverityError,
244         "Can't call a function without a valid thread.");
245     return nullptr;
246   }
247
248   // Okay, now run the function:
249
250   Address wrapper_address(m_jit_start_addr);
251
252   lldb::addr_t args = {args_addr};
253
254   lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(
255       *thread, wrapper_address, CompilerType(), args, options));
256   new_plan_sp->SetIsMasterPlan(true);
257   new_plan_sp->SetOkayToDiscard(false);
258   return new_plan_sp;
259 }
260
261 bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,
262                                           lldb::addr_t args_addr,
263                                           Value &ret_value) {
264   // Read the return value - it is the last field in the struct:
265   // FIXME: How does clang tell us there's no return value?  We need to handle
266   // that case.
267   // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
268   // then use GetReturnValueObject
269   // to fetch the value.  That way we can fetch any values we need.
270
271   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
272                                                   LIBLLDB_LOG_STEP));
273
274   if (log)
275     log->Printf("-- [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::eValueTypeScalar);
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. Do make sure we ignore breakpoints, unwind on error, and don't try
320   // to debug it.
321   EvaluateExpressionOptions real_options = options;
322   real_options.SetDebug(false);
323   real_options.SetUnwindOnError(true);
324   real_options.SetIgnoreBreakpoints(true);
325
326   lldb::addr_t args_addr;
327
328   if (args_addr_ptr != nullptr)
329     args_addr = *args_addr_ptr;
330   else
331     args_addr = LLDB_INVALID_ADDRESS;
332
333   if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
334     return lldb::eExpressionSetupError;
335
336   if (args_addr == LLDB_INVALID_ADDRESS) {
337     if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
338       return lldb::eExpressionSetupError;
339   }
340
341   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
342                                                   LIBLLDB_LOG_STEP));
343
344   if (log)
345     log->Printf(
346         "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
347         m_name.c_str());
348
349   lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(
350       exe_ctx, args_addr, real_options, diagnostic_manager);
351   if (!call_plan_sp)
352     return lldb::eExpressionSetupError;
353
354   // We need to make sure we record the fact that we are running an expression
355   // here otherwise this fact will fail to be recorded when fetching an
356   // Objective-C object description
357   if (exe_ctx.GetProcessPtr())
358     exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
359
360   return_value = exe_ctx.GetProcessRef().RunThreadPlan(
361       exe_ctx, call_plan_sp, real_options, diagnostic_manager);
362
363   if (log) {
364     if (return_value != lldb::eExpressionCompleted) {
365       log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
366                   "completed abnormally ==",
367                   m_name.c_str());
368     } else {
369       log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
370                   "completed normally ==",
371                   m_name.c_str());
372     }
373   }
374
375   if (exe_ctx.GetProcessPtr())
376     exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
377
378   if (args_addr_ptr != nullptr)
379     *args_addr_ptr = args_addr;
380
381   if (return_value != lldb::eExpressionCompleted)
382     return return_value;
383
384   FetchFunctionResults(exe_ctx, args_addr, results);
385
386   if (args_addr_ptr == nullptr)
387     DeallocateFunctionResults(exe_ctx, args_addr);
388
389   return lldb::eExpressionCompleted;
390 }