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