ClangFunction.h revision 6a5aa8ab240a13f397e3e09f2ca1ea3f16b451c2
1//===-- ClangFunction.h -----------------------------------------*- 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#ifndef lldb_ClangFunction_h_
11#define lldb_ClangFunction_h_
12
13// C Includes
14// C++ Includes
15#include <vector>
16#include <list>
17// Other libraries and framework includes
18// Project includes
19#include "lldb/Core/ClangForward.h"
20#include "lldb/Core/Address.h"
21#include "lldb/Core/Value.h"
22#include "lldb/Core/ValueObjectList.h"
23#include "lldb/Expression/ClangExpression.h"
24
25// Right now, this is just a toy.  It calls a set function, with fixed
26// values.
27
28namespace lldb_private
29{
30
31class ASTStructExtractor;
32class ClangExpressionParser;
33
34//----------------------------------------------------------------------
35/// @class ClangFunction ClangFunction.h "lldb/Expression/ClangFunction.h"
36/// @brief Encapsulates a function that can be called.
37///
38/// A given ClangFunction object can handle a single function signature.
39/// Once constructed, it can set up any number of concurrent calls to
40/// functions with that signature.
41///
42/// It performs the call by synthesizing a structure that contains the pointer
43/// to the function and the arguments that should be passed to that function,
44/// and producing a special-purpose JIT-compiled function that accepts a void*
45/// pointing to this struct as its only argument and calls the function in the
46/// struct with the written arguments.  This method lets Clang handle the
47/// vagaries of function calling conventions.
48///
49/// The simplest use of the ClangFunction is to construct it with a
50/// function representative of the signature you want to use, then call
51/// ExecuteFunction(ExecutionContext &, Stream &, Value &).
52///
53/// If you need to reuse the arguments for several calls, you can call
54/// InsertFunction() followed by WriteFunctionArguments(), which will return
55/// the location of the args struct for the wrapper function in args_addr_ref.
56///
57/// If you need to call the function on the thread plan stack, you can also
58/// call InsertFunction() followed by GetThreadPlanToCallFunction().
59///
60/// Any of the methods that take arg_addr_ptr or arg_addr_ref can be passed
61/// a pointer set to LLDB_INVALID_ADDRESS and new structure will be allocated
62/// and its address returned in that variable.
63///
64/// Any of the methods that take arg_addr_ptr can be passed NULL, and the
65/// argument space will be managed for you.
66//----------------------------------------------------------------------
67class ClangFunction : public ClangExpression
68{
69    friend class ASTStructExtractor;
70public:
71    enum ExecutionResults
72    {
73        eExecutionSetupError,
74        eExecutionCompleted,
75        eExecutionDiscarded,
76        eExecutionInterrupted,
77        eExecutionTimedOut
78    };
79
80	//------------------------------------------------------------------
81	/// Constructor
82    ///
83    /// @param[in] target_triple
84    ///     The LLVM-style target triple for the target in which the
85    ///     function is to be executed.
86    ///
87    /// @param[in] function_ptr
88    ///     The default function to be called.  Can be overridden using
89    ///     WriteFunctionArguments().
90    ///
91    /// @param[in] ast_context
92    ///     The AST context to evaluate argument types in.
93    ///
94    /// @param[in] arg_value_list
95    ///     The default values to use when calling this function.  Can
96    ///     be overridden using WriteFunctionArguments().
97	//------------------------------------------------------------------
98	ClangFunction(const char *target_triple,
99                  Function &function_ptr,
100                  ClangASTContext *ast_context,
101                  const ValueList &arg_value_list);
102
103    //------------------------------------------------------------------
104	/// Constructor
105    ///
106    /// @param[in] target_triple
107    ///     The LLVM-style target triple for the target in which the
108    ///     function is to be executed.
109    ///
110    /// @param[in] ast_context
111    ///     The AST context to evaluate argument types in.
112    ///
113    /// @param[in] return_qualtype
114    ///     An opaque Clang QualType for the function result.  Should be
115    ///     defined in ast_context.
116    ///
117    /// @param[in] function_address
118    ///     The address of the function to call.
119    ///
120    /// @param[in] arg_value_list
121    ///     The default values to use when calling this function.  Can
122    ///     be overridden using WriteFunctionArguments().
123	//------------------------------------------------------------------
124	ClangFunction(const char *target_triple,
125                  ClangASTContext *ast_context,
126                  void *return_qualtype,
127                  const Address& function_address,
128                  const ValueList &arg_value_list);
129
130    //------------------------------------------------------------------
131	/// Destructor
132	//------------------------------------------------------------------
133	virtual
134    ~ClangFunction();
135
136    //------------------------------------------------------------------
137	/// Compile the wrapper function
138    ///
139    /// @param[in] errors
140    ///     The stream to print parser errors to.
141    ///
142    /// @return
143    ///     The number of errors.
144	//------------------------------------------------------------------
145    unsigned CompileFunction (Stream &errors);
146
147    //------------------------------------------------------------------
148	/// Insert the default function wrapper and its default argument struct
149    ///
150    /// @param[in] exe_ctx
151    ///     The execution context to insert the function and its arguments
152    ///     into.
153    ///
154    /// @param[in,out] args_addr_ref
155    ///     The address of the structure to write the arguments into.  May
156    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
157    ///     and args_addr_ref is pointed to it.
158    ///
159    /// @param[in] errors
160    ///     The stream to write errors to.
161    ///
162    /// @return
163    ///     True on success; false otherwise.
164	//------------------------------------------------------------------
165    bool InsertFunction (ExecutionContext &exe_ctx,
166                         lldb::addr_t &args_addr_ref,
167                         Stream &errors);
168
169    //------------------------------------------------------------------
170	/// Insert the default function wrapper (using the JIT)
171    ///
172    /// @param[in] exe_ctx
173    ///     The execution context to insert the function and its arguments
174    ///     into.
175    ///
176    /// @param[in] errors
177    ///     The stream to write errors to.
178    ///
179    /// @return
180    ///     True on success; false otherwise.
181	//------------------------------------------------------------------
182    bool WriteFunctionWrapper (ExecutionContext &exe_ctx,
183                               Stream &errors);
184
185    //------------------------------------------------------------------
186	/// Insert the default function argument struct
187    ///
188    /// @param[in] exe_ctx
189    ///     The execution context to insert the function and its arguments
190    ///     into.
191    ///
192    /// @param[in,out] args_addr_ref
193    ///     The address of the structure to write the arguments into.  May
194    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
195    ///     and args_addr_ref is pointed to it.
196    ///
197    /// @param[in] errors
198    ///     The stream to write errors to.
199    ///
200    /// @return
201    ///     True on success; false otherwise.
202	//------------------------------------------------------------------
203    bool WriteFunctionArguments (ExecutionContext &exe_ctx,
204                                 lldb::addr_t &args_addr_ref,
205                                 Stream &errors);
206
207    //------------------------------------------------------------------
208	/// Insert an argument struct with a non-default function address and
209    /// non-default argument values
210    ///
211    /// @param[in] exe_ctx
212    ///     The execution context to insert the function and its arguments
213    ///     into.
214    ///
215    /// @param[in,out] args_addr_ref
216    ///     The address of the structure to write the arguments into.  May
217    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
218    ///     and args_addr_ref is pointed to it.
219    ///
220    /// @param[in] function_address
221    ///     The address of the function to call.
222    ///
223    /// @param[in] arg_values
224    ///     The values of the function's arguments.
225    ///
226    /// @param[in] errors
227    ///     The stream to write errors to.
228    ///
229    /// @return
230    ///     True on success; false otherwise.
231	//------------------------------------------------------------------
232    bool WriteFunctionArguments (ExecutionContext &exe_ctx,
233                                 lldb::addr_t &args_addr_ref,
234                                 Address function_address,
235                                 ValueList &arg_values,
236                                 Stream &errors);
237
238    //------------------------------------------------------------------
239	/// [Static] Execute a function, passing it a single void* parameter.
240    /// ClangFunction uses this to call the wrapper function.
241    ///
242    /// @param[in] exe_ctx
243    ///     The execution context to insert the function and its arguments
244    ///     into.
245    ///
246    /// @param[in] function_address
247    ///     The address of the function in the target process.
248    ///
249    /// @param[in] void_arg
250    ///     The value of the void* parameter.
251    ///
252    /// @param[in] stop_others
253    ///     True if other threads should pause during execution.
254    ///
255    /// @param[in] try_all_threads
256    ///     If the timeout expires, true if other threads should run.  If
257    ///     the function may try to take locks, this is useful.
258    ///
259    /// @param[in] single_thread_timeout_usec
260    ///     If stop_others is true, the length of time to wait before
261    ///     concluding that the system is deadlocked.
262    ///
263    /// @param[in] errors
264    ///     The stream to write errors to.
265    ///
266    /// @param[in] this_arg
267    ///     If non-NULL, the function is invoked like a C++ method, with the
268    ///     value pointed to by the pointer as its 'this' argument.
269    ///
270    /// @return
271    ///     Returns one of the ExecutionResults enum indicating function call status.
272	//------------------------------------------------------------------
273    static ExecutionResults ExecuteFunction (ExecutionContext &exe_ctx,
274                                             lldb::addr_t function_address,
275                                             lldb::addr_t &void_arg,
276                                             bool stop_others,
277                                             bool try_all_threads,
278                                             uint32_t single_thread_timeout_usec,
279                                             Stream &errors,
280                                             lldb::addr_t* this_arg = 0);
281
282    //------------------------------------------------------------------
283    /// Run the function this ClangFunction was created with.
284    ///
285    /// This simple version will run the function stopping other threads
286    /// for a fixed timeout period (1000 usec) and if it does not complete,
287    /// we halt the process and try with all threads running.
288    ///
289    /// @param[in] exe_ctx
290    ///     The thread & process in which this function will run.
291    ///
292    /// @param[in] errors
293    ///     Errors will be written here if there are any.
294    ///
295    /// @param[out] results
296    ///     The result value will be put here after running the function.
297    ///
298    /// @return
299    ///     Returns one of the ExecutionResults enum indicating function call status.
300    //------------------------------------------------------------------
301    ExecutionResults ExecuteFunction(ExecutionContext &exe_ctx,
302                                     Stream &errors,
303                                     Value &results);
304
305    //------------------------------------------------------------------
306    /// Run the function this ClangFunction was created with.
307    ///
308    /// This simple version will run the function obeying the stop_others
309    /// argument.  There is no timeout.
310    ///
311    /// @param[in] exe_ctx
312    ///     The thread & process in which this function will run.
313    ///
314    /// @param[in] errors
315    ///     Errors will be written here if there are any.
316    ///
317    /// @param[in] stop_others
318    ///     If \b true, run only this thread, if \b false let all threads run.
319    ///
320    /// @param[out] results
321    ///     The result value will be put here after running the function.
322    ///
323    /// @return
324    ///     Returns one of the ExecutionResults enum indicating function call status.
325    //------------------------------------------------------------------
326    ExecutionResults ExecuteFunction(ExecutionContext &exe_ctx,
327                                     Stream &errors, bool stop_others,
328                                     Value &results);
329
330    //------------------------------------------------------------------
331    /// Run the function this ClangFunction was created with.
332    ///
333    /// This simple version will run the function on one thread.  If \a single_thread_timeout_usec
334    /// is not zero, we time out after that timeout.  If \a try_all_threads is true, then we will
335    /// resume with all threads on, otherwise we halt the process, and eExecutionInterrupted will be returned.
336    ///
337    /// @param[in] exe_ctx
338    ///     The thread & process in which this function will run.
339    ///
340    /// @param[in] errors
341    ///     Errors will be written here if there are any.
342    ///
343    /// @param[in] single_thread_timeout_usec
344    ///     If \b true, run only this thread, if \b false let all threads run.
345    ///
346    /// @param[in] try_all_threads
347    ///     If \b true, run only this thread, if \b false let all threads run.
348    ///
349    /// @param[out] results
350    ///     The result value will be put here after running the function.
351    ///
352    /// @return
353    ///     Returns one of the ExecutionResults enum indicating function call status.
354    //------------------------------------------------------------------
355    ExecutionResults ExecuteFunction(ExecutionContext &exe_ctx,
356                                     Stream &errors,
357                                     uint32_t single_thread_timeout_usec,
358                                     bool try_all_threads,
359                                     Value &results);
360
361    //------------------------------------------------------------------
362    /// Run the function this ClangFunction was created with.
363    ///
364    /// This is the full version.
365    ///
366    /// @param[in] exe_ctx
367    ///     The thread & process in which this function will run.
368    ///
369    /// @param[in] args_addr_ptr
370    ///     If NULL, the function will take care of allocating & deallocating the wrapper
371    ///     args structure.  Otherwise, if set to LLDB_INVALID_ADDRESS, a new structure
372    ///     will be allocated, filled and the address returned to you.  You are responsible
373    ///     for deallocating it.  And if passed in with a value other than LLDB_INVALID_ADDRESS,
374    ///     this should point to an already allocated structure with the values already written.
375    ///
376    /// @param[in] errors
377    ///     Errors will be written here if there are any.
378    ///
379    /// @param[in] stop_others
380    ///     If \b true, run only this thread, if \b false let all threads run.
381    ///
382    /// @param[in] single_thread_timeout_usec
383    ///     If \b true, run only this thread, if \b false let all threads run.
384    ///
385    /// @param[in] try_all_threads
386    ///     If \b true, run only this thread, if \b false let all threads run.
387    ///
388    /// @param[out] results
389    ///     The result value will be put here after running the function.
390    ///
391    /// @return
392    ///     Returns one of the ExecutionResults enum indicating function call status.
393    //------------------------------------------------------------------
394    ExecutionResults ExecuteFunction(ExecutionContext &exe_ctx,
395                                     lldb::addr_t *args_addr_ptr,
396                                     Stream &errors,
397                                     bool stop_others,
398                                     uint32_t single_thread_timeout_usec,
399                                     bool try_all_threads,
400                                     Value &results);
401
402    //------------------------------------------------------------------
403    /// [static] Get a thread plan to run a function.
404    ///
405    /// @param[in] exe_ctx
406    ///     The execution context to insert the function and its arguments
407    ///     into.
408    ///
409    /// @param[in] func_addr
410    ///     The address of the function in the target process.
411    ///
412    /// @param[in] args_addr_ref
413    ///     The value of the void* parameter.
414    ///
415    /// @param[in] errors
416    ///     The stream to write errors to.
417    ///
418    /// @param[in] stop_others
419    ///     True if other threads should pause during execution.
420    ///
421    /// @param[in] discard_on_error
422    ///     True if the thread plan may simply be discarded if an error occurs.
423    ///
424    /// @param[in] this_arg
425    ///     If non-NULL, the function is invoked like a C++ method, with the
426    ///     value pointed to by the pointer as its 'this' argument.
427    ///
428    /// @return
429    ///     A ThreadPlan for executing the function.
430	//------------------------------------------------------------------
431    static ThreadPlan *
432    GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
433                                 lldb::addr_t func_addr,
434                                 lldb::addr_t &args_addr_ref,
435                                 Stream &errors,
436                                 bool stop_others,
437                                 bool discard_on_error = true,
438                                 lldb::addr_t *this_arg = 0);
439
440    //------------------------------------------------------------------
441    /// Get a thread plan to run the function this ClangFunction was created with.
442    ///
443    /// @param[in] exe_ctx
444    ///     The execution context to insert the function and its arguments
445    ///     into.
446    ///
447    /// @param[in] func_addr
448    ///     The address of the function in the target process.
449    ///
450    /// @param[in] args_addr_ref
451    ///     The value of the void* parameter.
452    ///
453    /// @param[in] errors
454    ///     The stream to write errors to.
455    ///
456    /// @param[in] stop_others
457    ///     True if other threads should pause during execution.
458    ///
459    /// @param[in] discard_on_error
460    ///     True if the thread plan may simply be discarded if an error occurs.
461    ///
462    /// @return
463    ///     A ThreadPlan for executing the function.
464	//------------------------------------------------------------------
465    ThreadPlan *
466    GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
467                                 lldb::addr_t &args_addr_ref,
468                                 Stream &errors,
469                                 bool stop_others,
470                                 bool discard_on_error = true)
471    {
472        return ClangFunction::GetThreadPlanToCallFunction (exe_ctx,
473                                                           m_wrapper_function_addr,
474                                                           args_addr_ref,
475                                                           errors,
476                                                           stop_others,
477                                                           discard_on_error);
478    }
479
480    //------------------------------------------------------------------
481    /// Get the result of the function from its struct
482    ///
483    /// @param[in] exe_ctx
484    ///     The execution context to retrieve the result from.
485    ///
486    /// @param[in] args_addr
487    ///     The address of the argument struct.
488    ///
489    /// @param[in] ret_value
490    ///     The value returned by the function.
491    ///
492    /// @return
493    ///     True on success; false otherwise.
494	//------------------------------------------------------------------
495    bool FetchFunctionResults (ExecutionContext &exe_ctx,
496                               lldb::addr_t args_addr,
497                               Value &ret_value);
498
499    //------------------------------------------------------------------
500    /// Deallocate the arguments structure
501    ///
502    /// @param[in] exe_ctx
503    ///     The execution context to insert the function and its arguments
504    ///     into.
505    ///
506    /// @param[in] args_addr
507    ///     The address of the argument struct.
508	//------------------------------------------------------------------
509    void DeallocateFunctionResults (ExecutionContext &exe_ctx,
510                                    lldb::addr_t args_addr);
511
512    //------------------------------------------------------------------
513    /// Interface for ClangExpression
514    //------------------------------------------------------------------
515
516    //------------------------------------------------------------------
517    /// Return the string that the parser should parse.  Must be a full
518    /// translation unit.
519    //------------------------------------------------------------------
520    const char *
521    Text ()
522    {
523        return m_wrapper_function_text.c_str();
524    }
525
526    //------------------------------------------------------------------
527    /// Return the function name that should be used for executing the
528    /// expression.  Text() should contain the definition of this
529    /// function.
530    //------------------------------------------------------------------
531    const char *
532    FunctionName ()
533    {
534        return m_wrapper_function_name.c_str();
535    }
536
537    //------------------------------------------------------------------
538    /// Return the object that the parser should use when resolving external
539    /// values.  May be NULL if everything should be self-contained.
540    //------------------------------------------------------------------
541    ClangExpressionDeclMap *
542    DeclMap ()
543    {
544        return NULL;
545    }
546
547    //------------------------------------------------------------------
548    /// Return the object that the parser should use when registering
549    /// local variables.  May be NULL if the Expression doesn't care.
550    //------------------------------------------------------------------
551    ClangExpressionVariableStore *
552    LocalVariables ()
553    {
554        return NULL;
555    }
556
557    //------------------------------------------------------------------
558    /// Return the object that the parser should allow to access ASTs.
559    /// May be NULL if the ASTs do not need to be transformed.
560    ///
561    /// @param[in] passthrough
562    ///     The ASTConsumer that the returned transformer should send
563    ///     the ASTs to after transformation.
564    //------------------------------------------------------------------
565    clang::ASTConsumer *
566    ASTTransformer (clang::ASTConsumer *passthrough);
567
568    //------------------------------------------------------------------
569    /// Return the stream that the parser should use to write DWARF
570    /// opcodes.
571    //------------------------------------------------------------------
572    StreamString &
573    DwarfOpcodeStream ()
574    {
575        return *((StreamString*)0);
576    }
577
578    //------------------------------------------------------------------
579    /// Return true if validation code should be inserted into the
580    /// expression.
581    //------------------------------------------------------------------
582    bool
583    NeedsValidation ()
584    {
585        return false;
586    }
587
588    //------------------------------------------------------------------
589    /// Return true if external variables in the expression should be
590    /// resolved.
591    //------------------------------------------------------------------
592    bool
593    NeedsVariableResolution ()
594    {
595        return false;
596    }
597
598private:
599	//------------------------------------------------------------------
600	// For ClangFunction only
601	//------------------------------------------------------------------
602
603    std::auto_ptr<ClangExpressionParser>    m_parser;               ///< The parser responsible for compiling the function.
604
605    Function                       *m_function_ptr;                 ///< The function we're going to call.  May be NULL if we don't have debug info for the function.
606    Address                         m_function_addr;                ///< If we don't have the FunctionSP, we at least need the address & return type.
607    void                           *m_function_return_qual_type;    ///< The opaque clang qual type for the function return type.
608    ClangASTContext                *m_clang_ast_context;            ///< This is the clang_ast_context that we're getting types from the and value, and the function return the function pointer is NULL.
609    std::string                     m_target_triple;                ///< The target triple to compile the wrapper function for.
610
611    std::string                     m_wrapper_function_name;        ///< The name of the wrapper function.
612    std::string                     m_wrapper_function_text;        ///< The contents of the wrapper function.
613    std::string                     m_wrapper_struct_name;          ///< The name of the struct that contains the target function address, arguments, and result.
614    lldb::addr_t                    m_wrapper_function_addr;        ///< The address of the wrapper function.
615    std::list<lldb::addr_t>         m_wrapper_args_addrs;           ///< The addresses of the arguments to the wrapper function.
616
617    bool                            m_struct_valid;                 ///< True if the ASTStructExtractor has populated the variables below.
618
619	//------------------------------------------------------------------
620	/// These values are populated by the ASTStructExtractor
621    size_t                          m_struct_size;                  ///< The size of the argument struct, in bytes.
622    std::vector<uint64_t>           m_member_offsets;               ///< The offset of each member in the struct, in bytes.
623    uint64_t                        m_return_size;                  ///< The size of the result variable, in bytes.
624    uint64_t                        m_return_offset;                ///< The offset of the result variable in the struct, in bytes.
625    //------------------------------------------------------------------
626
627    ValueList                       m_arg_values;                   ///< The default values of the arguments.
628
629    bool                            m_compiled;                     ///< True if the wrapper function has already been parsed.
630    bool                            m_JITted;                       ///< True if the wrapper function has already been JIT-compiled.
631};
632
633} // Namespace lldb_private
634
635#endif  // lldb_ClangFunction_h_
636