ClangUserExpression.h revision 34507e41794909465d168af4048ebd07ee7819e8
1//===-- ClangUserExpression.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 liblldb_ClangUserExpression_h_
11#define liblldb_ClangUserExpression_h_
12
13// C Includes
14// C++ Includes
15#include <string>
16#include <map>
17#include <memory>
18#include <vector>
19
20// Other libraries and framework includes
21// Project includes
22
23#include "lldb/lldb-forward.h"
24#include "lldb/lldb-private.h"
25#include "lldb/Core/ClangForward.h"
26#include "lldb/Expression/ClangExpression.h"
27#include "lldb/Expression/ClangExpressionVariable.h"
28#include "lldb/Expression/IRForTarget.h"
29#include "lldb/Expression/ProcessDataAllocator.h"
30#include "lldb/Symbol/TaggedASTType.h"
31#include "lldb/Target/ExecutionContext.h"
32
33#include "llvm/ExecutionEngine/JITMemoryManager.h"
34
35namespace lldb_private
36{
37
38//----------------------------------------------------------------------
39/// @class ClangUserExpression ClangUserExpression.h "lldb/Expression/ClangUserExpression.h"
40/// @brief Encapsulates a single expression for use with Clang
41///
42/// LLDB uses expressions for various purposes, notably to call functions
43/// and as a backend for the expr command.  ClangUserExpression encapsulates
44/// the objects needed to parse and interpret or JIT an expression.  It
45/// uses the Clang parser to produce LLVM IR from the expression.
46//----------------------------------------------------------------------
47class ClangUserExpression : public ClangExpression
48{
49public:
50    typedef STD_SHARED_PTR(ClangUserExpression) ClangUserExpressionSP;
51
52    enum { kDefaultTimeout = 500000u };
53    //------------------------------------------------------------------
54    /// Constructor
55    ///
56    /// @param[in] expr
57    ///     The expression to parse.
58    ///
59    /// @param[in] expr_prefix
60    ///     If non-NULL, a C string containing translation-unit level
61    ///     definitions to be included when the expression is parsed.
62    ///
63    /// @param[in] language
64    ///     If not eLanguageTypeUnknown, a language to use when parsing
65    ///     the expression.  Currently restricted to those languages
66    ///     supported by Clang.
67    ///
68    /// @param[in] desired_type
69    ///     If not eResultTypeAny, the type to use for the expression
70    ///     result.
71    //------------------------------------------------------------------
72    ClangUserExpression (const char *expr,
73                         const char *expr_prefix,
74                         lldb::LanguageType language,
75                         ResultType desired_type);
76
77    //------------------------------------------------------------------
78    /// Destructor
79    //------------------------------------------------------------------
80    virtual
81    ~ClangUserExpression ();
82
83    //------------------------------------------------------------------
84    /// Parse the expression
85    ///
86    /// @param[in] error_stream
87    ///     A stream to print parse errors and warnings to.
88    ///
89    /// @param[in] exe_ctx
90    ///     The execution context to use when looking up entities that
91    ///     are needed for parsing (locations of functions, types of
92    ///     variables, persistent variables, etc.)
93    ///
94    /// @param[in] execution_policy
95    ///     Determines whether interpretation is possible or mandatory.
96    ///
97    /// @param[in] keep_result_in_memory
98    ///     True if the resulting persistent variable should reside in
99    ///     target memory, if applicable.
100    ///
101    /// @return
102    ///     True on success (no errors); false otherwise.
103    //------------------------------------------------------------------
104    bool
105    Parse (Stream &error_stream,
106           ExecutionContext &exe_ctx,
107           lldb_private::ExecutionPolicy execution_policy,
108           bool keep_result_in_memory);
109
110    //------------------------------------------------------------------
111    /// Execute the parsed expression
112    ///
113    /// @param[in] error_stream
114    ///     A stream to print errors to.
115    ///
116    /// @param[in] exe_ctx
117    ///     The execution context to use when looking up entities that
118    ///     are needed for parsing (locations of variables, etc.)
119    ///
120    /// @param[in] discard_on_error
121    ///     If true, and the execution stops before completion, we unwind the
122    ///     function call, and return the program state to what it was before the
123    ///     execution.  If false, we leave the program in the stopped state.
124    ///
125    /// @param[in] shared_ptr_to_me
126    ///     This is a shared pointer to this ClangUserExpression.  This is
127    ///     needed because Execute can push a thread plan that will hold onto
128    ///     the ClangUserExpression for an unbounded period of time.  So you
129    ///     need to give the thread plan a reference to this object that can
130    ///     keep it alive.
131    ///
132    /// @param[in] result
133    ///     A pointer to direct at the persistent variable in which the
134    ///     expression's result is stored.
135    ///
136    /// @param[in] try_all_threads
137    ///     If true, then we will try to run all threads if the function doesn't complete on
138    ///     one thread.  See timeout_usec for the interaction of this variable and
139    ///     the timeout.
140    ///
141    /// @param[in] timeout_usec
142    ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
143    ///     will try on one thread for the lesser of .25 sec and half the total timeout.
144    ///     then switch to running all threads, otherwise this will be the total timeout.
145    ///
146    ///
147    /// @return
148    ///     A Process::Execution results value.
149    //------------------------------------------------------------------
150    ExecutionResults
151    Execute (Stream &error_stream,
152             ExecutionContext &exe_ctx,
153             bool discard_on_error,
154             ClangUserExpressionSP &shared_ptr_to_me,
155             lldb::ClangExpressionVariableSP &result,
156             bool try_all_threads,
157             uint32_t timeout_usec);
158
159    ThreadPlan *
160    GetThreadPlanToExecuteJITExpression (Stream &error_stream,
161                                         ExecutionContext &exe_ctx);
162
163    //------------------------------------------------------------------
164    /// Apply the side effects of the function to program state.
165    ///
166    /// @param[in] error_stream
167    ///     A stream to print errors to.
168    ///
169    /// @param[in] exe_ctx
170    ///     The execution context to use when looking up entities that
171    ///     are needed for parsing (locations of variables, etc.)
172    ///
173    /// @param[in] result
174    ///     A pointer to direct at the persistent variable in which the
175    ///     expression's result is stored.
176    ///
177    /// @param[in] function_stack_pointer
178    ///     A pointer to the base of the function's stack frame.  This
179    ///     is used to determine whether the expession result resides in
180    ///     memory that will still be valid, or whether it needs to be
181    ///     treated as homeless for the purpose of future expressions.
182    ///
183    /// @return
184    ///     A Process::Execution results value.
185    //------------------------------------------------------------------
186    bool
187    FinalizeJITExecution (Stream &error_stream,
188                          ExecutionContext &exe_ctx,
189                          lldb::ClangExpressionVariableSP &result,
190                          lldb::addr_t function_stack_pointer = LLDB_INVALID_ADDRESS);
191
192    //------------------------------------------------------------------
193    /// Return the string that the parser should parse.  Must be a full
194    /// translation unit.
195    //------------------------------------------------------------------
196    const char *
197    Text ()
198    {
199        return m_transformed_text.c_str();
200    }
201
202    //------------------------------------------------------------------
203    /// Return the string that the user typed.
204    //------------------------------------------------------------------
205    const char *
206    GetUserText ()
207    {
208        return m_expr_text.c_str();
209    }
210
211    //------------------------------------------------------------------
212    /// Return the function name that should be used for executing the
213    /// expression.  Text() should contain the definition of this
214    /// function.
215    //------------------------------------------------------------------
216    const char *
217    FunctionName ()
218    {
219        return "$__lldb_expr";
220    }
221
222    //------------------------------------------------------------------
223    /// Return the language that should be used when parsing.  To use
224    /// the default, return eLanguageTypeUnknown.
225    //------------------------------------------------------------------
226    virtual lldb::LanguageType
227    Language ()
228    {
229        return m_language;
230    }
231
232    //------------------------------------------------------------------
233    /// Return the object that the parser should use when resolving external
234    /// values.  May be NULL if everything should be self-contained.
235    //------------------------------------------------------------------
236    ClangExpressionDeclMap *
237    DeclMap ()
238    {
239        return m_expr_decl_map.get();
240    }
241
242    //------------------------------------------------------------------
243    /// Return the object that the parser should use when registering
244    /// local variables.  May be NULL if the Expression doesn't care.
245    //------------------------------------------------------------------
246    ClangExpressionVariableList *
247    LocalVariables ()
248    {
249        return m_local_variables.get();
250    }
251
252    //------------------------------------------------------------------
253    /// Return the object that the parser should allow to access ASTs.
254    /// May be NULL if the ASTs do not need to be transformed.
255    ///
256    /// @param[in] passthrough
257    ///     The ASTConsumer that the returned transformer should send
258    ///     the ASTs to after transformation.
259    //------------------------------------------------------------------
260    clang::ASTConsumer *
261    ASTTransformer (clang::ASTConsumer *passthrough);
262
263    //------------------------------------------------------------------
264    /// Return the desired result type of the function, or
265    /// eResultTypeAny if indifferent.
266    //------------------------------------------------------------------
267    virtual ResultType
268    DesiredResultType ()
269    {
270        return m_desired_type;
271    }
272
273    //------------------------------------------------------------------
274    /// Return true if validation code should be inserted into the
275    /// expression.
276    //------------------------------------------------------------------
277    bool
278    NeedsValidation ()
279    {
280        return true;
281    }
282
283    //------------------------------------------------------------------
284    /// Return true if external variables in the expression should be
285    /// resolved.
286    //------------------------------------------------------------------
287    bool
288    NeedsVariableResolution ()
289    {
290        return true;
291    }
292
293    //------------------------------------------------------------------
294    /// Evaluate one expression and return its result.
295    ///
296    /// @param[in] exe_ctx
297    ///     The execution context to use when evaluating the expression.
298    ///
299    /// @param[in] execution_policy
300    ///     Determines whether or not to try using the IR interpreter to
301    ///     avoid running the expression on the parser.
302    ///
303    /// @param[in] language
304    ///     If not eLanguageTypeUnknown, a language to use when parsing
305    ///     the expression.  Currently restricted to those languages
306    ///     supported by Clang.
307    ///
308    /// @param[in] discard_on_error
309    ///     True if the thread's state should be restored in the case
310    ///     of an error.
311    ///
312    /// @param[in] result_type
313    ///     If not eResultTypeAny, the type of the desired result.  Will
314    ///     result in parse errors if impossible.
315    ///
316    /// @param[in] expr_cstr
317    ///     A C string containing the expression to be evaluated.
318    ///
319    /// @param[in] expr_prefix
320    ///     If non-NULL, a C string containing translation-unit level
321    ///     definitions to be included when the expression is parsed.
322    ///
323    /// @param[in/out] result_valobj_sp
324    ///      If execution is successful, the result valobj is placed here.
325    ///
326    /// @param[in] try_all_threads
327    ///     If true, then we will try to run all threads if the function doesn't complete on
328    ///     one thread.  See timeout_usec for the interaction of this variable and
329    ///     the timeout.
330    ///
331    /// @param[in] timeout_usec
332    ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
333    ///     will try on one thread for the lesser of .25 sec and half the total timeout.
334    ///     then switch to running all threads, otherwise this will be the total timeout.
335    ///
336    /// @result
337    ///      A Process::ExecutionResults value.  eExecutionCompleted for success.
338    //------------------------------------------------------------------
339    static ExecutionResults
340    Evaluate (ExecutionContext &exe_ctx,
341              lldb_private::ExecutionPolicy execution_policy,
342              lldb::LanguageType language,
343              ResultType desired_type,
344              bool discard_on_error,
345              const char *expr_cstr,
346              const char *expr_prefix,
347              lldb::ValueObjectSP &result_valobj_sp,
348              bool try_all_threads,
349              uint32_t timeout_usec);
350
351    static ExecutionResults
352    EvaluateWithError (ExecutionContext &exe_ctx,
353                       lldb_private::ExecutionPolicy execution_policy,
354                       lldb::LanguageType language,
355                       ResultType desired_type,
356                       bool discard_on_error,
357                       const char *expr_cstr,
358                       const char *expr_prefix,
359                       lldb::ValueObjectSP &result_valobj_sp,
360                       Error &error,
361                       bool try_all_threads,
362                       uint32_t timeout_usec);
363
364    static const Error::ValueType kNoResult = 0x1001; ///< ValueObject::GetError() returns this if there is no result from the expression.
365private:
366    //------------------------------------------------------------------
367    /// Populate m_cplusplus and m_objetivec based on the environment.
368    //------------------------------------------------------------------
369
370    void
371    ScanContext (ExecutionContext &exe_ctx,
372                 lldb_private::Error &err);
373
374    bool
375    PrepareToExecuteJITExpression (Stream &error_stream,
376                                   ExecutionContext &exe_ctx,
377                                   lldb::addr_t &struct_address,
378                                   lldb::addr_t &object_ptr,
379                                   lldb::addr_t &cmd_ptr);
380
381    bool
382    EvaluatedStatically ()
383    {
384        return m_evaluated_statically;
385    }
386
387    void
388    InstallContext (ExecutionContext &exe_ctx)
389    {
390        m_process_wp = exe_ctx.GetProcessSP();
391        m_target_wp = exe_ctx.GetTargetSP();
392        m_frame_wp = exe_ctx.GetFrameSP();
393    }
394
395    bool
396    LockAndCheckContext (ExecutionContext &exe_ctx,
397                         lldb::TargetSP &target_sp,
398                         lldb::ProcessSP &process_sp,
399                         lldb::StackFrameSP &frame_sp)
400    {
401        target_sp = m_target_wp.lock();
402        process_sp = m_process_wp.lock();
403        frame_sp = m_frame_wp.lock();
404
405        if ((target_sp && target_sp.get() != exe_ctx.GetTargetPtr()) ||
406            (process_sp && process_sp.get() != exe_ctx.GetProcessPtr()) ||
407            (frame_sp && frame_sp.get() != exe_ctx.GetFramePtr()))
408            return false;
409
410        return true;
411    }
412
413    lldb::TargetWP                              m_target_wp;            ///< The target used as the context for the expression.
414    lldb::ProcessWP                             m_process_wp;           ///< The process used as the context for the expression.
415    lldb::StackFrameWP                          m_frame_wp;             ///< The stack frame used as context for the expression.
416
417    std::string                                 m_expr_text;            ///< The text of the expression, as typed by the user
418    std::string                                 m_expr_prefix;          ///< The text of the translation-level definitions, as provided by the user
419    lldb::LanguageType                          m_language;             ///< The language to use when parsing (eLanguageTypeUnknown means use defaults)
420    bool                                        m_allow_cxx;            ///< True if the language allows C++.
421    bool                                        m_allow_objc;           ///< True if the language allows Objective-C.
422    std::string                                 m_transformed_text;     ///< The text of the expression, as send to the parser
423    ResultType                                  m_desired_type;         ///< The type to coerce the expression's result to.  If eResultTypeAny, inferred from the expression.
424
425    std::auto_ptr<ClangExpressionDeclMap>       m_expr_decl_map;        ///< The map to use when parsing and materializing the expression.
426    std::auto_ptr<ClangExpressionVariableList>  m_local_variables;      ///< The local expression variables, if the expression is DWARF.
427    std::auto_ptr<ProcessDataAllocator>         m_data_allocator;       ///< The allocator that the parser uses to place strings for use by JIT-compiled code.
428
429    std::auto_ptr<ASTResultSynthesizer>         m_result_synthesizer;   ///< The result synthesizer, if one is needed.
430
431    bool                                        m_enforce_valid_object; ///< True if the expression parser should enforce the presence of a valid class pointer in order to generate the expression as a method.
432    bool                                        m_cplusplus;            ///< True if the expression is compiled as a C++ member function (true if it was parsed when exe_ctx was in a C++ method).
433    bool                                        m_objectivec;           ///< True if the expression is compiled as an Objective-C method (true if it was parsed when exe_ctx was in an Objective-C method).
434    bool                                        m_static_method;        ///< True if the expression is compiled as a static (or class) method (currently true if it was parsed when exe_ctx was in an Objective-C class method).
435    bool                                        m_needs_object_ptr;     ///< True if "this" or "self" must be looked up and passed in.  False if the expression doesn't really use them and they can be NULL.
436    bool                                        m_const_object;         ///< True if "this" is const.
437    Target                                     *m_target;               ///< The target for storing persistent data like types and variables.
438
439    bool                                        m_evaluated_statically; ///< True if the expression could be evaluated statically; false otherwise.
440    lldb::ClangExpressionVariableSP             m_const_result;         ///< The statically-computed result of the expression.  NULL if it could not be computed statically or the expression has side effects.
441};
442
443} // namespace lldb_private
444
445#endif  // liblldb_ClangUserExpression_h_
446