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/Expression/FunctionCaller.h"
17 #include "lldb/Core/DataExtractor.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/State.h"
21 #include "lldb/Core/ValueObject.h"
22 #include "lldb/Core/ValueObjectList.h"
23 #include "lldb/Expression/DiagnosticManager.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, DiagnosticManager &diagnostic_manager)
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,
138                                        DiagnosticManager &diagnostic_manager)
139 {
140     return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values, diagnostic_manager);
141 }
142 
143 // FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function.
144 
145 bool
146 FunctionCaller::WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, ValueList &arg_values,
147                                        DiagnosticManager &diagnostic_manager)
148 {
149     // All the information to reconstruct the struct is provided by the
150     // StructExtractor.
151     if (!m_struct_valid)
152     {
153         diagnostic_manager.PutCString(
154             eDiagnosticSeverityError,
155             "Argument information was not correctly parsed, so the function cannot be called.");
156         return false;
157     }
158 
159     Error error;
160     lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
161 
162     Process *process = exe_ctx.GetProcessPtr();
163 
164     if (process == NULL)
165         return return_value;
166 
167     lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
168 
169     if (process != jit_process_sp.get())
170         return false;
171 
172     if (args_addr_ref == LLDB_INVALID_ADDRESS)
173     {
174         args_addr_ref = process->AllocateMemory(m_struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error);
175         if (args_addr_ref == LLDB_INVALID_ADDRESS)
176             return false;
177         m_wrapper_args_addrs.push_back (args_addr_ref);
178     }
179     else
180     {
181         // Make sure this is an address that we've already handed out.
182         if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end())
183         {
184             return false;
185         }
186     }
187 
188     // TODO: verify fun_addr needs to be a callable address
189     Scalar fun_addr (m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
190     uint64_t first_offset = m_member_offsets[0];
191     process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr, process->GetAddressByteSize(), error);
192 
193     // FIXME: We will need to extend this for Variadic functions.
194 
195     Error value_error;
196 
197     size_t num_args = arg_values.GetSize();
198     if (num_args != m_arg_values.GetSize())
199     {
200         diagnostic_manager.Printf(eDiagnosticSeverityError,
201                                   "Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
202                                   (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
203         return false;
204     }
205 
206     for (size_t i = 0; i < num_args; i++)
207     {
208         // FIXME: We should sanity check sizes.
209 
210         uint64_t offset = m_member_offsets[i+1]; // Clang sizes are in bytes.
211         Value *arg_value = arg_values.GetValueAtIndex(i);
212 
213         // FIXME: For now just do scalars:
214 
215         // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings)
216 
217         if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
218             arg_value->GetContextType() == Value::eContextTypeInvalid &&
219             arg_value->GetCompilerType().IsPointerType())
220             continue;
221 
222         const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
223 
224         if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar, arg_scalar.GetByteSize(), error))
225             return false;
226     }
227 
228     return true;
229 }
230 
231 bool
232 FunctionCaller::InsertFunction(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
233                                DiagnosticManager &diagnostic_manager)
234 {
235     if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
236         return false;
237     if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
238         return false;
239     if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
240         return false;
241 
242     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
243     if (log)
244         log->Printf ("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n", m_jit_start_addr, args_addr_ref);
245 
246     return true;
247 }
248 
249 lldb::ThreadPlanSP
250 FunctionCaller::GetThreadPlanToCallFunction(ExecutionContext &exe_ctx, lldb::addr_t args_addr,
251                                             const EvaluateExpressionOptions &options,
252                                             DiagnosticManager &diagnostic_manager)
253 {
254     Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
255 
256     if (log)
257         log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating thread plan to call function \"%s\" --", m_name.c_str());
258 
259     // FIXME: Use the errors Stream for better error reporting.
260     Thread *thread = exe_ctx.GetThreadPtr();
261     if (thread == NULL)
262     {
263         diagnostic_manager.PutCString(eDiagnosticSeverityError, "Can't call a function without a valid thread.");
264         return NULL;
265     }
266 
267     // Okay, now run the function:
268 
269     Address wrapper_address (m_jit_start_addr);
270 
271     lldb::addr_t args = { args_addr };
272 
273     lldb::ThreadPlanSP new_plan_sp (new ThreadPlanCallFunction (*thread,
274                                                        wrapper_address,
275                                                        CompilerType(),
276                                                        args,
277                                                        options));
278     new_plan_sp->SetIsMasterPlan(true);
279     new_plan_sp->SetOkayToDiscard (false);
280     return new_plan_sp;
281 }
282 
283 bool
284 FunctionCaller::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
285 {
286     // Read the return value - it is the last field in the struct:
287     // FIXME: How does clang tell us there's no return value?  We need to handle that case.
288     // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and then use GetReturnValueObject
289     // to fetch the value.  That way we can fetch any values we need.
290 
291     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
292 
293     if (log)
294         log->Printf("-- [FunctionCaller::FetchFunctionResults] Fetching function results for \"%s\"--", m_name.c_str());
295 
296     Process *process = exe_ctx.GetProcessPtr();
297 
298     if (process == NULL)
299         return false;
300 
301     lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
302 
303     if (process != jit_process_sp.get())
304         return false;
305 
306     Error error;
307     ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory (args_addr + m_return_offset, m_return_size, 0, error);
308 
309     if (error.Fail())
310         return false;
311 
312     ret_value.SetCompilerType(m_function_return_type);
313     ret_value.SetValueType(Value::eValueTypeScalar);
314     return true;
315 }
316 
317 void
318 FunctionCaller::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr)
319 {
320     std::list<lldb::addr_t>::iterator pos;
321     pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr);
322     if (pos != m_wrapper_args_addrs.end())
323         m_wrapper_args_addrs.erase(pos);
324 
325     exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
326 }
327 
328 lldb::ExpressionResults
329 FunctionCaller::ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
330                                 const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager,
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(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
350         return lldb::eExpressionSetupError;
351 
352     if (args_addr == LLDB_INVALID_ADDRESS)
353     {
354         if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
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, args_addr, real_options, diagnostic_manager);
364     if (!call_plan_sp)
365         return lldb::eExpressionSetupError;
366 
367     // We need to make sure we record the fact that we are running an expression here
368     // otherwise this fact will fail to be recorded when fetching an Objective-C object description
369     if (exe_ctx.GetProcessPtr())
370         exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
371 
372     return_value = exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, real_options, diagnostic_manager);
373 
374     if (log)
375     {
376         if (return_value != lldb::eExpressionCompleted)
377         {
378             log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" completed abnormally ==", m_name.c_str());
379         }
380         else
381         {
382             log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" completed normally ==", m_name.c_str());
383         }
384     }
385 
386     if (exe_ctx.GetProcessPtr())
387         exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
388 
389     if (args_addr_ptr != NULL)
390         *args_addr_ptr = args_addr;
391 
392     if (return_value != lldb::eExpressionCompleted)
393         return return_value;
394 
395     FetchFunctionResults(exe_ctx, args_addr, results);
396 
397     if (args_addr_ptr == NULL)
398         DeallocateFunctionResults(exe_ctx, args_addr);
399 
400     return lldb::eExpressionCompleted;
401 }
402