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 <vector>
18 
19 // Other libraries and framework includes
20 // Project includes
21 
22 #include "lldb/lldb-forward.h"
23 #include "lldb/lldb-private.h"
24 #include "lldb/Core/Address.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/Materializer.h"
30 #include "lldb/Symbol/TaggedASTType.h"
31 #include "lldb/Target/ExecutionContext.h"
32 
33 #include "llvm/ExecutionEngine/JITMemoryManager.h"
34 
35 namespace 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 //----------------------------------------------------------------------
47 class ClangUserExpression : public ClangExpression
48 {
49 public:
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     bool
CanInterpret()111     CanInterpret ()
112     {
113         return m_can_interpret;
114     }
115 
116     bool
117     MatchesContext (ExecutionContext &exe_ctx);
118 
119     //------------------------------------------------------------------
120     /// Execute the parsed expression
121     ///
122     /// @param[in] error_stream
123     ///     A stream to print errors to.
124     ///
125     /// @param[in] exe_ctx
126     ///     The execution context to use when looking up entities that
127     ///     are needed for parsing (locations of variables, etc.)
128     ///
129     /// @param[in] unwind_on_error
130     ///     If true, and the execution stops before completion, we unwind the
131     ///     function call, and return the program state to what it was before the
132     ///     execution.  If false, we leave the program in the stopped state.
133     ///
134     /// @param[in] ignore_breakpoints
135     ///     If true, ignore breakpoints while executing the expression.
136     ///
137     /// @param[in] shared_ptr_to_me
138     ///     This is a shared pointer to this ClangUserExpression.  This is
139     ///     needed because Execute can push a thread plan that will hold onto
140     ///     the ClangUserExpression for an unbounded period of time.  So you
141     ///     need to give the thread plan a reference to this object that can
142     ///     keep it alive.
143     ///
144     /// @param[in] result
145     ///     A pointer to direct at the persistent variable in which the
146     ///     expression's result is stored.
147     ///
148     /// @param[in] try_all_threads
149     ///     If true, then we will try to run all threads if the function doesn't complete on
150     ///     one thread.  See timeout_usec for the interaction of this variable and
151     ///     the timeout.
152     ///
153     /// @param[in] timeout_usec
154     ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
155     ///     will try on one thread for the lesser of .25 sec and half the total timeout.
156     ///     then switch to running all threads, otherwise this will be the total timeout.
157     ///
158     ///
159     /// @return
160     ///     A Process::Execution results value.
161     //------------------------------------------------------------------
162     ExecutionResults
163     Execute (Stream &error_stream,
164              ExecutionContext &exe_ctx,
165              bool unwind_on_error,
166              bool ignore_breakpoints,
167              ClangUserExpressionSP &shared_ptr_to_me,
168              lldb::ClangExpressionVariableSP &result,
169              bool try_all_threads,
170              uint32_t timeout_usec);
171 
172     ThreadPlan *
173     GetThreadPlanToExecuteJITExpression (Stream &error_stream,
174                                          ExecutionContext &exe_ctx);
175 
176     //------------------------------------------------------------------
177     /// Apply the side effects of the function to program state.
178     ///
179     /// @param[in] error_stream
180     ///     A stream to print errors to.
181     ///
182     /// @param[in] exe_ctx
183     ///     The execution context to use when looking up entities that
184     ///     are needed for parsing (locations of variables, etc.)
185     ///
186     /// @param[in] result
187     ///     A pointer to direct at the persistent variable in which the
188     ///     expression's result is stored.
189     ///
190     /// @param[in] function_stack_pointer
191     ///     A pointer to the base of the function's stack frame.  This
192     ///     is used to determine whether the expession result resides in
193     ///     memory that will still be valid, or whether it needs to be
194     ///     treated as homeless for the purpose of future expressions.
195     ///
196     /// @return
197     ///     A Process::Execution results value.
198     //------------------------------------------------------------------
199     bool
200     FinalizeJITExecution (Stream &error_stream,
201                           ExecutionContext &exe_ctx,
202                           lldb::ClangExpressionVariableSP &result,
203                           lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS,
204                           lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS);
205 
206     //------------------------------------------------------------------
207     /// Return the string that the parser should parse.  Must be a full
208     /// translation unit.
209     //------------------------------------------------------------------
210     const char *
Text()211     Text ()
212     {
213         return m_transformed_text.c_str();
214     }
215 
216     //------------------------------------------------------------------
217     /// Return the string that the user typed.
218     //------------------------------------------------------------------
219     const char *
GetUserText()220     GetUserText ()
221     {
222         return m_expr_text.c_str();
223     }
224 
225     //------------------------------------------------------------------
226     /// Return the function name that should be used for executing the
227     /// expression.  Text() should contain the definition of this
228     /// function.
229     //------------------------------------------------------------------
230     const char *
FunctionName()231     FunctionName ()
232     {
233         return "$__lldb_expr";
234     }
235 
236     //------------------------------------------------------------------
237     /// Return the language that should be used when parsing.  To use
238     /// the default, return eLanguageTypeUnknown.
239     //------------------------------------------------------------------
240     virtual lldb::LanguageType
Language()241     Language ()
242     {
243         return m_language;
244     }
245 
246     //------------------------------------------------------------------
247     /// Return the object that the parser should use when resolving external
248     /// values.  May be NULL if everything should be self-contained.
249     //------------------------------------------------------------------
250     ClangExpressionDeclMap *
DeclMap()251     DeclMap ()
252     {
253         return m_expr_decl_map.get();
254     }
255 
256     //------------------------------------------------------------------
257     /// Return the object that the parser should allow to access ASTs.
258     /// May be NULL if the ASTs do not need to be transformed.
259     ///
260     /// @param[in] passthrough
261     ///     The ASTConsumer that the returned transformer should send
262     ///     the ASTs to after transformation.
263     //------------------------------------------------------------------
264     clang::ASTConsumer *
265     ASTTransformer (clang::ASTConsumer *passthrough);
266 
267     //------------------------------------------------------------------
268     /// Return the desired result type of the function, or
269     /// eResultTypeAny if indifferent.
270     //------------------------------------------------------------------
271     virtual ResultType
DesiredResultType()272     DesiredResultType ()
273     {
274         return m_desired_type;
275     }
276 
277     //------------------------------------------------------------------
278     /// Return true if validation code should be inserted into the
279     /// expression.
280     //------------------------------------------------------------------
281     bool
NeedsValidation()282     NeedsValidation ()
283     {
284         return true;
285     }
286 
287     //------------------------------------------------------------------
288     /// Return true if external variables in the expression should be
289     /// resolved.
290     //------------------------------------------------------------------
291     bool
NeedsVariableResolution()292     NeedsVariableResolution ()
293     {
294         return true;
295     }
296 
297     //------------------------------------------------------------------
298     /// Evaluate one expression and return its result.
299     ///
300     /// @param[in] exe_ctx
301     ///     The execution context to use when evaluating the expression.
302     ///
303     /// @param[in] execution_policy
304     ///     Determines whether or not to try using the IR interpreter to
305     ///     avoid running the expression on the parser.
306     ///
307     /// @param[in] language
308     ///     If not eLanguageTypeUnknown, a language to use when parsing
309     ///     the expression.  Currently restricted to those languages
310     ///     supported by Clang.
311     ///
312     /// @param[in] unwind_on_error
313     ///     True if the thread's state should be restored in the case
314     ///     of an error.
315     ///
316     /// @param[in] ignore_breakpoints
317     ///     If true, ignore breakpoints while executing the expression.
318     ///
319     /// @param[in] result_type
320     ///     If not eResultTypeAny, the type of the desired result.  Will
321     ///     result in parse errors if impossible.
322     ///
323     /// @param[in] expr_cstr
324     ///     A C string containing the expression to be evaluated.
325     ///
326     /// @param[in] expr_prefix
327     ///     If non-NULL, a C string containing translation-unit level
328     ///     definitions to be included when the expression is parsed.
329     ///
330     /// @param[in/out] result_valobj_sp
331     ///      If execution is successful, the result valobj is placed here.
332     ///
333     /// @param[in] try_all_threads
334     ///     If true, then we will try to run all threads if the function doesn't complete on
335     ///     one thread.  See timeout_usec for the interaction of this variable and
336     ///     the timeout.
337     ///
338     /// @param[in] timeout_usec
339     ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
340     ///     will try on one thread for the lesser of .25 sec and half the total timeout.
341     ///     then switch to running all threads, otherwise this will be the total timeout.
342     ///
343     /// @result
344     ///      A Process::ExecutionResults value.  eExecutionCompleted for success.
345     //------------------------------------------------------------------
346     static ExecutionResults
347     Evaluate (ExecutionContext &exe_ctx,
348               lldb_private::ExecutionPolicy execution_policy,
349               lldb::LanguageType language,
350               ResultType desired_type,
351               bool unwind_on_error,
352               bool ignore_breakpoints,
353               const char *expr_cstr,
354               const char *expr_prefix,
355               lldb::ValueObjectSP &result_valobj_sp,
356               bool try_all_threads,
357               uint32_t timeout_usec);
358 
359     static ExecutionResults
360     EvaluateWithError (ExecutionContext &exe_ctx,
361                        lldb_private::ExecutionPolicy execution_policy,
362                        lldb::LanguageType language,
363                        ResultType desired_type,
364                        bool unwind_on_error,
365                        bool ignore_breakpoints,
366                        const char *expr_cstr,
367                        const char *expr_prefix,
368                        lldb::ValueObjectSP &result_valobj_sp,
369                        Error &error,
370                        bool try_all_threads,
371                        uint32_t timeout_usec);
372 
373     static const Error::ValueType kNoResult = 0x1001; ///< ValueObject::GetError() returns this if there is no result from the expression.
374 private:
375     //------------------------------------------------------------------
376     /// Populate m_cplusplus and m_objetivec based on the environment.
377     //------------------------------------------------------------------
378 
379     void
380     ScanContext (ExecutionContext &exe_ctx,
381                  lldb_private::Error &err);
382 
383     bool
384     PrepareToExecuteJITExpression (Stream &error_stream,
385                                    ExecutionContext &exe_ctx,
386                                    lldb::addr_t &struct_address,
387                                    lldb::addr_t &object_ptr,
388                                    lldb::addr_t &cmd_ptr);
389 
390     void
391     InstallContext (ExecutionContext &exe_ctx);
392 
393     bool
394     LockAndCheckContext (ExecutionContext &exe_ctx,
395                          lldb::TargetSP &target_sp,
396                          lldb::ProcessSP &process_sp,
397                          lldb::StackFrameSP &frame_sp);
398 
399     lldb::ProcessWP                             m_process_wp;           ///< The process used as the context for the expression.
400     Address                                     m_address;              ///< The address the process is stopped in.
401     lldb::addr_t                                m_stack_frame_bottom;   ///< The bottom of the allocated stack frame.
402     lldb::addr_t                                m_stack_frame_top;      ///< The top of the allocated stack frame.
403 
404     std::string                                 m_expr_text;            ///< The text of the expression, as typed by the user
405     std::string                                 m_expr_prefix;          ///< The text of the translation-level definitions, as provided by the user
406     lldb::LanguageType                          m_language;             ///< The language to use when parsing (eLanguageTypeUnknown means use defaults)
407     bool                                        m_allow_cxx;            ///< True if the language allows C++.
408     bool                                        m_allow_objc;           ///< True if the language allows Objective-C.
409     std::string                                 m_transformed_text;     ///< The text of the expression, as send to the parser
410     ResultType                                  m_desired_type;         ///< The type to coerce the expression's result to.  If eResultTypeAny, inferred from the expression.
411 
412     std::unique_ptr<ClangExpressionDeclMap>      m_expr_decl_map;        ///< The map to use when parsing the expression.
413     std::unique_ptr<IRExecutionUnit>             m_execution_unit_ap;    ///< The execution unit the expression is stored in.
414     std::unique_ptr<Materializer>                m_materializer_ap;      ///< The materializer to use when running the expression.
415     std::unique_ptr<ASTResultSynthesizer>        m_result_synthesizer;   ///< The result synthesizer, if one is needed.
416 
417     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.
418     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).
419     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).
420     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).
421     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.
422     bool                                        m_const_object;         ///< True if "this" is const.
423     Target                                     *m_target;               ///< The target for storing persistent data like types and variables.
424 
425     bool                                        m_can_interpret;        ///< True if the expression could be evaluated statically; false otherwise.
426     lldb::addr_t                                m_materialized_address; ///< The address at which the arguments to the expression have been materialized.
427     Materializer::DematerializerSP              m_dematerializer_sp;    ///< The dematerializer.
428 };
429 
430 } // namespace lldb_private
431 
432 #endif  // liblldb_ClangUserExpression_h_
433