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