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