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