]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp
MFV r348535: 9677 panic from zio_write_gang_block() when creating dump device on...
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Expression / FunctionCaller.cpp
1 //===-- FunctionCaller.cpp ---------------------------------------*- C++-*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10
11 #include "lldb/Expression/FunctionCaller.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ValueObject.h"
14 #include "lldb/Core/ValueObjectList.h"
15 #include "lldb/Expression/DiagnosticManager.h"
16 #include "lldb/Expression/IRExecutionUnit.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Symbol/Function.h"
19 #include "lldb/Symbol/Type.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/RegisterContext.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Target/ThreadPlan.h"
26 #include "lldb/Target/ThreadPlanCallFunction.h"
27 #include "lldb/Utility/DataExtractor.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/State.h"
30
31 using namespace lldb_private;
32
33 //----------------------------------------------------------------------
34 // FunctionCaller constructor
35 //----------------------------------------------------------------------
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(NULL), 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 //----------------------------------------------------------------------
55 // Destructor
56 //----------------------------------------------------------------------
57 FunctionCaller::~FunctionCaller() {
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
66 bool FunctionCaller::WriteFunctionWrapper(
67     ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
68   Process *process = exe_ctx.GetProcessPtr();
69
70   if (!process)
71     return false;
72
73   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
74
75   if (process != jit_process_sp.get())
76     return false;
77
78   if (!m_compiled)
79     return false;
80
81   if (m_JITted)
82     return true;
83
84   bool can_interpret = false; // should stay that way
85
86   Status jit_error(m_parser->PrepareForExecution(
87       m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
88       can_interpret, eExecutionPolicyAlways));
89
90   if (!jit_error.Success()) {
91     diagnostic_manager.Printf(eDiagnosticSeverityError,
92                               "Error in PrepareForExecution: %s.",
93                               jit_error.AsCString());
94     return false;
95   }
96
97   if (m_parser->GetGenerateDebugInfo()) {
98     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
99
100     if (jit_module_sp) {
101       ConstString const_func_name(FunctionName());
102       FileSpec jit_file;
103       jit_file.GetFilename() = const_func_name;
104       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
105       m_jit_module_wp = jit_module_sp;
106       process->GetTarget().GetImages().Append(jit_module_sp);
107     }
108   }
109   if (process && m_jit_start_addr)
110     m_jit_process_wp = process->shared_from_this();
111
112   m_JITted = true;
113
114   return true;
115 }
116
117 bool FunctionCaller::WriteFunctionArguments(
118     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
119     DiagnosticManager &diagnostic_manager) {
120   return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
121                                 diagnostic_manager);
122 }
123
124 // FIXME: Assure that the ValueList we were passed in is consistent with the one
125 // that defined this function.
126
127 bool FunctionCaller::WriteFunctionArguments(
128     ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
129     ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
130   // All the information to reconstruct the struct is provided by the
131   // StructExtractor.
132   if (!m_struct_valid) {
133     diagnostic_manager.PutString(eDiagnosticSeverityError,
134                                  "Argument information was not correctly "
135                                  "parsed, so the function cannot be called.");
136     return false;
137   }
138
139   Status error;
140   lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
141
142   Process *process = exe_ctx.GetProcessPtr();
143
144   if (process == NULL)
145     return return_value;
146
147   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
148
149   if (process != jit_process_sp.get())
150     return false;
151
152   if (args_addr_ref == LLDB_INVALID_ADDRESS) {
153     args_addr_ref = process->AllocateMemory(
154         m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
155         error);
156     if (args_addr_ref == LLDB_INVALID_ADDRESS)
157       return false;
158     m_wrapper_args_addrs.push_back(args_addr_ref);
159   } else {
160     // Make sure this is an address that we've already handed out.
161     if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
162              args_addr_ref) == m_wrapper_args_addrs.end()) {
163       return false;
164     }
165   }
166
167   // TODO: verify fun_addr needs to be a callable address
168   Scalar fun_addr(
169       m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
170   uint64_t first_offset = m_member_offsets[0];
171   process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
172                                process->GetAddressByteSize(), error);
173
174   // FIXME: We will need to extend this for Variadic functions.
175
176   Status value_error;
177
178   size_t num_args = arg_values.GetSize();
179   if (num_args != m_arg_values.GetSize()) {
180     diagnostic_manager.Printf(
181         eDiagnosticSeverityError,
182         "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
183         (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
184     return false;
185   }
186
187   for (size_t i = 0; i < num_args; i++) {
188     // FIXME: We should sanity check sizes.
189
190     uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
191     Value *arg_value = arg_values.GetValueAtIndex(i);
192
193     // FIXME: For now just do scalars:
194
195     // Special case: if it's a pointer, don't do anything (the ABI supports
196     // passing cstrings)
197
198     if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
199         arg_value->GetContextType() == Value::eContextTypeInvalid &&
200         arg_value->GetCompilerType().IsPointerType())
201       continue;
202
203     const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
204
205     if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
206                                       arg_scalar.GetByteSize(), error))
207       return false;
208   }
209
210   return true;
211 }
212
213 bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,
214                                     lldb::addr_t &args_addr_ref,
215                                     DiagnosticManager &diagnostic_manager) {
216   if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
217     return false;
218   if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
219     return false;
220   if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
221     return false;
222
223   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
224   if (log)
225     log->Printf("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
226                 m_jit_start_addr, args_addr_ref);
227
228   return true;
229 }
230
231 lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(
232     ExecutionContext &exe_ctx, lldb::addr_t args_addr,
233     const EvaluateExpressionOptions &options,
234     DiagnosticManager &diagnostic_manager) {
235   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
236                                                   LIBLLDB_LOG_STEP));
237
238   if (log)
239     log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
240                 "thread plan to call function \"%s\" --",
241                 m_name.c_str());
242
243   // FIXME: Use the errors Stream for better error reporting.
244   Thread *thread = exe_ctx.GetThreadPtr();
245   if (thread == NULL) {
246     diagnostic_manager.PutString(
247         eDiagnosticSeverityError,
248         "Can't call a function without a valid thread.");
249     return NULL;
250   }
251
252   // Okay, now run the function:
253
254   Address wrapper_address(m_jit_start_addr);
255
256   lldb::addr_t args = {args_addr};
257
258   lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(
259       *thread, wrapper_address, CompilerType(), args, options));
260   new_plan_sp->SetIsMasterPlan(true);
261   new_plan_sp->SetOkayToDiscard(false);
262   return new_plan_sp;
263 }
264
265 bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,
266                                           lldb::addr_t args_addr,
267                                           Value &ret_value) {
268   // Read the return value - it is the last field in the struct:
269   // FIXME: How does clang tell us there's no return value?  We need to handle
270   // that case.
271   // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
272   // then use GetReturnValueObject
273   // to fetch the value.  That way we can fetch any values we need.
274
275   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
276                                                   LIBLLDB_LOG_STEP));
277
278   if (log)
279     log->Printf("-- [FunctionCaller::FetchFunctionResults] Fetching function "
280                 "results for \"%s\"--",
281                 m_name.c_str());
282
283   Process *process = exe_ctx.GetProcessPtr();
284
285   if (process == NULL)
286     return false;
287
288   lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
289
290   if (process != jit_process_sp.get())
291     return false;
292
293   Status error;
294   ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
295       args_addr + m_return_offset, m_return_size, 0, error);
296
297   if (error.Fail())
298     return false;
299
300   ret_value.SetCompilerType(m_function_return_type);
301   ret_value.SetValueType(Value::eValueTypeScalar);
302   return true;
303 }
304
305 void FunctionCaller::DeallocateFunctionResults(ExecutionContext &exe_ctx,
306                                                lldb::addr_t args_addr) {
307   std::list<lldb::addr_t>::iterator pos;
308   pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
309                   args_addr);
310   if (pos != m_wrapper_args_addrs.end())
311     m_wrapper_args_addrs.erase(pos);
312
313   exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
314 }
315
316 lldb::ExpressionResults FunctionCaller::ExecuteFunction(
317     ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
318     const EvaluateExpressionOptions &options,
319     DiagnosticManager &diagnostic_manager, Value &results) {
320   lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
321
322   // FunctionCaller::ExecuteFunction execution is always just to get the
323   // result. Do make sure we ignore breakpoints, unwind on error, and don't try
324   // to debug it.
325   EvaluateExpressionOptions real_options = options;
326   real_options.SetDebug(false);
327   real_options.SetUnwindOnError(true);
328   real_options.SetIgnoreBreakpoints(true);
329
330   lldb::addr_t args_addr;
331
332   if (args_addr_ptr != NULL)
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(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
346                                                   LIBLLDB_LOG_STEP));
347
348   if (log)
349     log->Printf(
350         "== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
351         m_name.c_str());
352
353   lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(
354       exe_ctx, args_addr, real_options, diagnostic_manager);
355   if (!call_plan_sp)
356     return lldb::eExpressionSetupError;
357
358   // We need to make sure we record the fact that we are running an expression
359   // here otherwise this fact will fail to be recorded when fetching an
360   // Objective-C object description
361   if (exe_ctx.GetProcessPtr())
362     exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
363
364   return_value = exe_ctx.GetProcessRef().RunThreadPlan(
365       exe_ctx, call_plan_sp, real_options, diagnostic_manager);
366
367   if (log) {
368     if (return_value != lldb::eExpressionCompleted) {
369       log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
370                   "completed abnormally ==",
371                   m_name.c_str());
372     } else {
373       log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
374                   "completed normally ==",
375                   m_name.c_str());
376     }
377   }
378
379   if (exe_ctx.GetProcessPtr())
380     exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
381
382   if (args_addr_ptr != NULL)
383     *args_addr_ptr = args_addr;
384
385   if (return_value != lldb::eExpressionCompleted)
386     return return_value;
387
388   FetchFunctionResults(exe_ctx, args_addr, results);
389
390   if (args_addr_ptr == NULL)
391     DeallocateFunctionResults(exe_ctx, args_addr);
392
393   return lldb::eExpressionCompleted;
394 }