1//===-- ClangFunction.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#include "clang/AST/ASTContext.h"
15#include "clang/AST/RecordLayout.h"
16#include "clang/CodeGen/CodeGenAction.h"
17#include "clang/CodeGen/ModuleBuilder.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Triple.h"
21#include "llvm/ExecutionEngine/ExecutionEngine.h"
22#include "llvm/IR/Module.h"
23
24// Project includes
25#include "lldb/Expression/ASTStructExtractor.h"
26#include "lldb/Expression/ClangExpressionParser.h"
27#include "lldb/Expression/ClangFunction.h"
28#include "lldb/Expression/IRExecutionUnit.h"
29#include "lldb/Symbol/Type.h"
30#include "lldb/Core/DataExtractor.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/ValueObject.h"
33#include "lldb/Core/ValueObjectList.h"
34#include "lldb/Interpreter/CommandReturnObject.h"
35#include "lldb/Symbol/ClangASTContext.h"
36#include "lldb/Symbol/Function.h"
37#include "lldb/Target/ExecutionContext.h"
38#include "lldb/Target/Process.h"
39#include "lldb/Target/RegisterContext.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Target/Thread.h"
42#include "lldb/Target/ThreadPlan.h"
43#include "lldb/Target/ThreadPlanCallFunction.h"
44#include "lldb/Core/Log.h"
45
46using namespace lldb_private;
47
48//----------------------------------------------------------------------
49// ClangFunction constructor
50//----------------------------------------------------------------------
51ClangFunction::ClangFunction
52(
53    ExecutionContextScope &exe_scope,
54    const ClangASTType &return_type,
55    const Address& functionAddress,
56    const ValueList &arg_value_list
57) :
58    m_function_ptr (NULL),
59    m_function_addr (functionAddress),
60    m_function_return_type(return_type),
61    m_wrapper_function_name ("__lldb_caller_function"),
62    m_wrapper_struct_name ("__lldb_caller_struct"),
63    m_wrapper_args_addrs (),
64    m_arg_values (arg_value_list),
65    m_compiled (false),
66    m_JITted (false)
67{
68    m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
69    // Can't make a ClangFunction without a process.
70    assert (m_jit_process_wp.lock());
71}
72
73ClangFunction::ClangFunction
74(
75    ExecutionContextScope &exe_scope,
76    Function &function,
77    ClangASTContext *ast_context,
78    const ValueList &arg_value_list
79) :
80    m_function_ptr (&function),
81    m_function_addr (),
82    m_function_return_type (),
83    m_clang_ast_context (ast_context),
84    m_wrapper_function_name ("__lldb_function_caller"),
85    m_wrapper_struct_name ("__lldb_caller_struct"),
86    m_wrapper_args_addrs (),
87    m_arg_values (arg_value_list),
88    m_compiled (false),
89    m_JITted (false)
90{
91    m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
92    // Can't make a ClangFunction without a process.
93    assert (m_jit_process_wp.lock());
94
95    m_function_addr = m_function_ptr->GetAddressRange().GetBaseAddress();
96    m_function_return_type = m_function_ptr->GetClangType().GetFunctionReturnType();
97}
98
99//----------------------------------------------------------------------
100// Destructor
101//----------------------------------------------------------------------
102ClangFunction::~ClangFunction()
103{
104}
105
106unsigned
107ClangFunction::CompileFunction (Stream &errors)
108{
109    if (m_compiled)
110        return 0;
111
112    // FIXME: How does clang tell us there's no return value?  We need to handle that case.
113    unsigned num_errors = 0;
114
115    std::string return_type_str (m_function_return_type.GetTypeName());
116
117    // Cons up the function we're going to wrap our call in, then compile it...
118    // We declare the function "extern "C"" because the compiler might be in C++
119    // mode which would mangle the name and then we couldn't find it again...
120    m_wrapper_function_text.clear();
121    m_wrapper_function_text.append ("extern \"C\" void ");
122    m_wrapper_function_text.append (m_wrapper_function_name);
123    m_wrapper_function_text.append (" (void *input)\n{\n    struct ");
124    m_wrapper_function_text.append (m_wrapper_struct_name);
125    m_wrapper_function_text.append (" \n  {\n");
126    m_wrapper_function_text.append ("    ");
127    m_wrapper_function_text.append (return_type_str);
128    m_wrapper_function_text.append (" (*fn_ptr) (");
129
130    // Get the number of arguments.  If we have a function type and it is prototyped,
131    // trust that, otherwise use the values we were given.
132
133    // FIXME: This will need to be extended to handle Variadic functions.  We'll need
134    // to pull the defined arguments out of the function, then add the types from the
135    // arguments list for the variable arguments.
136
137    uint32_t num_args = UINT32_MAX;
138    bool trust_function = false;
139    // GetArgumentCount returns -1 for an unprototyped function.
140    ClangASTType function_clang_type;
141    if (m_function_ptr)
142    {
143        function_clang_type = m_function_ptr->GetClangType();
144        if (function_clang_type)
145        {
146            int num_func_args = function_clang_type.GetFunctionArgumentCount();
147            if (num_func_args >= 0)
148            {
149                trust_function = true;
150                num_args = num_func_args;
151            }
152        }
153    }
154
155    if (num_args == UINT32_MAX)
156        num_args = m_arg_values.GetSize();
157
158    std::string args_buffer;  // This one stores the definition of all the args in "struct caller".
159    std::string args_list_buffer;  // This one stores the argument list called from the structure.
160    for (size_t i = 0; i < num_args; i++)
161    {
162        std::string type_name;
163
164        if (trust_function)
165        {
166            type_name = function_clang_type.GetFunctionArgumentTypeAtIndex(i).GetTypeName();
167        }
168        else
169        {
170            ClangASTType clang_qual_type = m_arg_values.GetValueAtIndex(i)->GetClangType ();
171            if (clang_qual_type)
172            {
173                type_name = clang_qual_type.GetTypeName();
174            }
175            else
176            {
177                errors.Printf("Could not determine type of input value %lu.", i);
178                return 1;
179            }
180        }
181
182        m_wrapper_function_text.append (type_name);
183        if (i < num_args - 1)
184            m_wrapper_function_text.append (", ");
185
186        char arg_buf[32];
187        args_buffer.append ("    ");
188        args_buffer.append (type_name);
189        snprintf(arg_buf, 31, "arg_%" PRIu64, (uint64_t)i);
190        args_buffer.push_back (' ');
191        args_buffer.append (arg_buf);
192        args_buffer.append (";\n");
193
194        args_list_buffer.append ("__lldb_fn_data->");
195        args_list_buffer.append (arg_buf);
196        if (i < num_args - 1)
197            args_list_buffer.append (", ");
198
199    }
200    m_wrapper_function_text.append (");\n"); // Close off the function calling prototype.
201
202    m_wrapper_function_text.append (args_buffer);
203
204    m_wrapper_function_text.append ("    ");
205    m_wrapper_function_text.append (return_type_str);
206    m_wrapper_function_text.append (" return_value;");
207    m_wrapper_function_text.append ("\n  };\n  struct ");
208    m_wrapper_function_text.append (m_wrapper_struct_name);
209    m_wrapper_function_text.append ("* __lldb_fn_data = (struct ");
210    m_wrapper_function_text.append (m_wrapper_struct_name);
211    m_wrapper_function_text.append (" *) input;\n");
212
213    m_wrapper_function_text.append ("  __lldb_fn_data->return_value = __lldb_fn_data->fn_ptr (");
214    m_wrapper_function_text.append (args_list_buffer);
215    m_wrapper_function_text.append (");\n}\n");
216
217    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
218    if (log)
219        log->Printf ("Expression: \n\n%s\n\n", m_wrapper_function_text.c_str());
220
221    // Okay, now compile this expression
222
223    lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
224    if (jit_process_sp)
225    {
226        m_parser.reset(new ClangExpressionParser(jit_process_sp.get(), *this));
227
228        num_errors = m_parser->Parse (errors);
229    }
230    else
231    {
232        errors.Printf("no process - unable to inject function");
233        num_errors = 1;
234    }
235
236    m_compiled = (num_errors == 0);
237
238    if (!m_compiled)
239        return num_errors;
240
241    return num_errors;
242}
243
244bool
245ClangFunction::WriteFunctionWrapper (ExecutionContext &exe_ctx, Stream &errors)
246{
247    Process *process = exe_ctx.GetProcessPtr();
248
249    if (!process)
250        return false;
251
252    lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
253
254    if (process != jit_process_sp.get())
255        return false;
256
257    if (!m_compiled)
258        return false;
259
260    if (m_JITted)
261        return true;
262
263    bool can_interpret = false; // should stay that way
264
265    Error jit_error (m_parser->PrepareForExecution (m_jit_start_addr,
266                                                    m_jit_end_addr,
267                                                    m_execution_unit_ap,
268                                                    exe_ctx,
269                                                    can_interpret,
270                                                    eExecutionPolicyAlways));
271
272    if (!jit_error.Success())
273        return false;
274
275    if (process && m_jit_start_addr)
276        m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
277
278    m_JITted = true;
279
280    return true;
281}
282
283bool
284ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
285{
286    return WriteFunctionArguments(exe_ctx, args_addr_ref, m_function_addr, m_arg_values, errors);
287}
288
289// FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function.
290
291bool
292ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx,
293                                       lldb::addr_t &args_addr_ref,
294                                       Address function_address,
295                                       ValueList &arg_values,
296                                       Stream &errors)
297{
298    // All the information to reconstruct the struct is provided by the
299    // StructExtractor.
300    if (!m_struct_valid)
301    {
302        errors.Printf("Argument information was not correctly parsed, so the function cannot be called.");
303        return false;
304    }
305
306    Error error;
307    using namespace clang;
308    ExecutionResults return_value = eExecutionSetupError;
309
310    Process *process = exe_ctx.GetProcessPtr();
311
312    if (process == NULL)
313        return return_value;
314
315    lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
316
317    if (process != jit_process_sp.get())
318        return false;
319
320    if (args_addr_ref == LLDB_INVALID_ADDRESS)
321    {
322        args_addr_ref = process->AllocateMemory(m_struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error);
323        if (args_addr_ref == LLDB_INVALID_ADDRESS)
324            return false;
325        m_wrapper_args_addrs.push_back (args_addr_ref);
326    }
327    else
328    {
329        // Make sure this is an address that we've already handed out.
330        if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end())
331        {
332            return false;
333        }
334    }
335
336    // TODO: verify fun_addr needs to be a callable address
337    Scalar fun_addr (function_address.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
338    uint64_t first_offset = m_member_offsets[0];
339    process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr, process->GetAddressByteSize(), error);
340
341    // FIXME: We will need to extend this for Variadic functions.
342
343    Error value_error;
344
345    size_t num_args = arg_values.GetSize();
346    if (num_args != m_arg_values.GetSize())
347    {
348        errors.Printf ("Wrong number of arguments - was: %lu should be: %lu", num_args, m_arg_values.GetSize());
349        return false;
350    }
351
352    for (size_t i = 0; i < num_args; i++)
353    {
354        // FIXME: We should sanity check sizes.
355
356        uint64_t offset = m_member_offsets[i+1]; // Clang sizes are in bytes.
357        Value *arg_value = arg_values.GetValueAtIndex(i);
358
359        // FIXME: For now just do scalars:
360
361        // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings)
362
363        if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
364            arg_value->GetContextType() == Value::eContextTypeInvalid &&
365            arg_value->GetClangType().IsPointerType())
366            continue;
367
368        const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
369
370        if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar, arg_scalar.GetByteSize(), error))
371            return false;
372    }
373
374    return true;
375}
376
377bool
378ClangFunction::InsertFunction (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
379{
380    using namespace clang;
381
382    if (CompileFunction(errors) != 0)
383        return false;
384    if (!WriteFunctionWrapper(exe_ctx, errors))
385        return false;
386    if (!WriteFunctionArguments(exe_ctx, args_addr_ref, errors))
387        return false;
388
389    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
390    if (log)
391        log->Printf ("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n", m_jit_start_addr, args_addr_ref);
392
393    return true;
394}
395
396ThreadPlan *
397ClangFunction::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
398                                            lldb::addr_t func_addr,
399                                            lldb::addr_t &args_addr,
400                                            Stream &errors,
401                                            bool stop_others,
402                                            bool unwind_on_error,
403                                            bool ignore_breakpoints,
404                                            lldb::addr_t *this_arg,
405                                            lldb::addr_t *cmd_arg)
406{
407    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
408
409    if (log)
410        log->Printf("-- [ClangFunction::GetThreadPlanToCallFunction] Creating thread plan to call function --");
411
412    // FIXME: Use the errors Stream for better error reporting.
413    Thread *thread = exe_ctx.GetThreadPtr();
414    if (thread == NULL)
415    {
416        errors.Printf("Can't call a function without a valid thread.");
417        return NULL;
418    }
419
420    // Okay, now run the function:
421
422    Address wrapper_address (func_addr);
423    ThreadPlan *new_plan = new ThreadPlanCallFunction (*thread,
424                                                       wrapper_address,
425                                                       ClangASTType(),
426                                                       args_addr,
427                                                       stop_others,
428                                                       unwind_on_error,
429                                                       ignore_breakpoints,
430                                                       this_arg,
431                                                       cmd_arg);
432    new_plan->SetIsMasterPlan(true);
433    new_plan->SetOkayToDiscard (false);
434    return new_plan;
435}
436
437bool
438ClangFunction::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
439{
440    // Read the return value - it is the last field in the struct:
441    // FIXME: How does clang tell us there's no return value?  We need to handle that case.
442    // FIXME: Create our ThreadPlanCallFunction with the return ClangASTType, and then use GetReturnValueObject
443    // to fetch the value.  That way we can fetch any values we need.
444
445    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
446
447    if (log)
448        log->Printf("-- [ClangFunction::FetchFunctionResults] Fetching function results --");
449
450    Process *process = exe_ctx.GetProcessPtr();
451
452    if (process == NULL)
453        return false;
454
455    lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
456
457    if (process != jit_process_sp.get())
458        return false;
459
460    Error error;
461    ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory (args_addr + m_return_offset, m_return_size, 0, error);
462
463    if (error.Fail())
464        return false;
465
466    ret_value.SetClangType(m_function_return_type);
467    ret_value.SetValueType(Value::eValueTypeScalar);
468    return true;
469}
470
471void
472ClangFunction::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr)
473{
474    std::list<lldb::addr_t>::iterator pos;
475    pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr);
476    if (pos != m_wrapper_args_addrs.end())
477        m_wrapper_args_addrs.erase(pos);
478
479    exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
480}
481
482ExecutionResults
483ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, Value &results)
484{
485    return ExecuteFunction (exe_ctx, errors, 1000, true, results);
486}
487
488ExecutionResults
489ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, bool stop_others, Value &results)
490{
491    const bool try_all_threads = false;
492    const bool unwind_on_error = true;
493    const bool ignore_breakpoints = true;
494    return ExecuteFunction (exe_ctx, NULL, errors, stop_others, 0UL, try_all_threads,
495                            unwind_on_error, ignore_breakpoints, results);
496}
497
498ExecutionResults
499ClangFunction::ExecuteFunction(
500        ExecutionContext &exe_ctx,
501        Stream &errors,
502        uint32_t timeout_usec,
503        bool try_all_threads,
504        Value &results)
505{
506    const bool stop_others = true;
507    const bool unwind_on_error = true;
508    const bool ignore_breakpoints = true;
509    return ExecuteFunction (exe_ctx, NULL, errors, stop_others, timeout_usec,
510                            try_all_threads, unwind_on_error, ignore_breakpoints, results);
511}
512
513// This is the static function
514ExecutionResults
515ClangFunction::ExecuteFunction (
516        ExecutionContext &exe_ctx,
517        lldb::addr_t function_address,
518        lldb::addr_t &void_arg,
519        bool stop_others,
520        bool try_all_threads,
521        bool unwind_on_error,
522        bool ignore_breakpoints,
523        uint32_t timeout_usec,
524        Stream &errors,
525        lldb::addr_t *this_arg)
526{
527    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
528
529    if (log)
530        log->Printf("== [ClangFunction::ExecuteFunction] Executing function ==");
531
532    lldb::ThreadPlanSP call_plan_sp (ClangFunction::GetThreadPlanToCallFunction (exe_ctx,
533                                                                                 function_address,
534                                                                                 void_arg,
535                                                                                 errors,
536                                                                                 stop_others,
537                                                                                 unwind_on_error,
538                                                                                 ignore_breakpoints,
539                                                                                 this_arg));
540    if (!call_plan_sp)
541        return eExecutionSetupError;
542
543    // <rdar://problem/12027563> we need to make sure we record the fact that we are running an expression here
544    // otherwise this fact will fail to be recorded when fetching an Objective-C object description
545    if (exe_ctx.GetProcessPtr())
546        exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
547
548    ExecutionResults results = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx, call_plan_sp,
549                                                                      stop_others,
550                                                                      try_all_threads,
551                                                                      unwind_on_error,
552                                                                      ignore_breakpoints,
553                                                                      timeout_usec,
554                                                                      errors);
555
556    if (log)
557    {
558        if (results != eExecutionCompleted)
559        {
560            log->Printf("== [ClangFunction::ExecuteFunction] Execution completed abnormally ==");
561        }
562        else
563        {
564            log->Printf("== [ClangFunction::ExecuteFunction] Execution completed normally ==");
565        }
566    }
567
568    if (exe_ctx.GetProcessPtr())
569        exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
570
571    return results;
572}
573
574ExecutionResults
575ClangFunction::ExecuteFunction(
576        ExecutionContext &exe_ctx,
577        lldb::addr_t *args_addr_ptr,
578        Stream &errors,
579        bool stop_others,
580        uint32_t timeout_usec,
581        bool try_all_threads,
582        bool unwind_on_error,
583        bool ignore_breakpoints,
584        Value &results)
585{
586    using namespace clang;
587    ExecutionResults return_value = eExecutionSetupError;
588
589    lldb::addr_t args_addr;
590
591    if (args_addr_ptr != NULL)
592        args_addr = *args_addr_ptr;
593    else
594        args_addr = LLDB_INVALID_ADDRESS;
595
596    if (CompileFunction(errors) != 0)
597        return eExecutionSetupError;
598
599    if (args_addr == LLDB_INVALID_ADDRESS)
600    {
601        if (!InsertFunction(exe_ctx, args_addr, errors))
602            return eExecutionSetupError;
603    }
604
605    return_value = ClangFunction::ExecuteFunction (exe_ctx,
606                                                   m_jit_start_addr,
607                                                   args_addr,
608                                                   stop_others,
609                                                   try_all_threads,
610                                                   unwind_on_error,
611                                                   ignore_breakpoints,
612                                                   timeout_usec,
613                                                   errors);
614
615    if (args_addr_ptr != NULL)
616        *args_addr_ptr = args_addr;
617
618    if (return_value != eExecutionCompleted)
619        return return_value;
620
621    FetchFunctionResults(exe_ctx, args_addr, results);
622
623    if (args_addr_ptr == NULL)
624        DeallocateFunctionResults(exe_ctx, args_addr);
625
626    return eExecutionCompleted;
627}
628
629clang::ASTConsumer *
630ClangFunction::ASTTransformer (clang::ASTConsumer *passthrough)
631{
632    return new ASTStructExtractor(passthrough, m_wrapper_struct_name.c_str(), *this);
633}
634