xref: /NextBSD/contrib/llvm/tools/lldb/include/lldb/Expression/ClangUserExpression.h (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
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 namespace lldb_private
34 {
35 
36 //----------------------------------------------------------------------
37 /// @class ClangUserExpression ClangUserExpression.h "lldb/Expression/ClangUserExpression.h"
38 /// @brief Encapsulates a single expression for use with Clang
39 ///
40 /// LLDB uses expressions for various purposes, notably to call functions
41 /// and as a backend for the expr command.  ClangUserExpression encapsulates
42 /// the objects needed to parse and interpret or JIT an expression.  It
43 /// uses the Clang parser to produce LLVM IR from the expression.
44 //----------------------------------------------------------------------
45 class ClangUserExpression : public ClangExpression
46 {
47 public:
48 
49     enum { kDefaultTimeout = 500000u };
50     //------------------------------------------------------------------
51     /// Constructor
52     ///
53     /// @param[in] expr
54     ///     The expression to parse.
55     ///
56     /// @param[in] expr_prefix
57     ///     If non-NULL, a C string containing translation-unit level
58     ///     definitions to be included when the expression is parsed.
59     ///
60     /// @param[in] language
61     ///     If not eLanguageTypeUnknown, a language to use when parsing
62     ///     the expression.  Currently restricted to those languages
63     ///     supported by Clang.
64     ///
65     /// @param[in] desired_type
66     ///     If not eResultTypeAny, the type to use for the expression
67     ///     result.
68     //------------------------------------------------------------------
69     ClangUserExpression (const char *expr,
70                          const char *expr_prefix,
71                          lldb::LanguageType language,
72                          ResultType desired_type);
73 
74     //------------------------------------------------------------------
75     /// Destructor
76     //------------------------------------------------------------------
77     virtual
78     ~ClangUserExpression ();
79 
80     //------------------------------------------------------------------
81     /// Parse the expression
82     ///
83     /// @param[in] error_stream
84     ///     A stream to print parse errors and warnings to.
85     ///
86     /// @param[in] exe_ctx
87     ///     The execution context to use when looking up entities that
88     ///     are needed for parsing (locations of functions, types of
89     ///     variables, persistent variables, etc.)
90     ///
91     /// @param[in] execution_policy
92     ///     Determines whether interpretation is possible or mandatory.
93     ///
94     /// @param[in] keep_result_in_memory
95     ///     True if the resulting persistent variable should reside in
96     ///     target memory, if applicable.
97     ///
98     /// @return
99     ///     True on success (no errors); false otherwise.
100     //------------------------------------------------------------------
101     bool
102     Parse (Stream &error_stream,
103            ExecutionContext &exe_ctx,
104            lldb_private::ExecutionPolicy execution_policy,
105            bool keep_result_in_memory,
106            bool generate_debug_info);
107 
108     bool
CanInterpret()109     CanInterpret ()
110     {
111         return m_can_interpret;
112     }
113 
114     bool
115     MatchesContext (ExecutionContext &exe_ctx);
116 
117     //------------------------------------------------------------------
118     /// Execute the parsed expression
119     ///
120     /// @param[in] error_stream
121     ///     A stream to print errors to.
122     ///
123     /// @param[in] exe_ctx
124     ///     The execution context to use when looking up entities that
125     ///     are needed for parsing (locations of variables, etc.)
126     ///
127     /// @param[in] options
128     ///     Expression evaluation options.
129     ///
130     /// @param[in] shared_ptr_to_me
131     ///     This is a shared pointer to this ClangUserExpression.  This is
132     ///     needed because Execute can push a thread plan that will hold onto
133     ///     the ClangUserExpression for an unbounded period of time.  So you
134     ///     need to give the thread plan a reference to this object that can
135     ///     keep it alive.
136     ///
137     /// @param[in] result
138     ///     A pointer to direct at the persistent variable in which the
139     ///     expression's result is stored.
140     ///
141     /// @return
142     ///     A Process::Execution results value.
143     //------------------------------------------------------------------
144     lldb::ExpressionResults
145     Execute (Stream &error_stream,
146              ExecutionContext &exe_ctx,
147              const EvaluateExpressionOptions& options,
148              lldb::ClangUserExpressionSP &shared_ptr_to_me,
149              lldb::ClangExpressionVariableSP &result);
150 
151     //------------------------------------------------------------------
152     /// Apply the side effects of the function to program state.
153     ///
154     /// @param[in] error_stream
155     ///     A stream to print errors to.
156     ///
157     /// @param[in] exe_ctx
158     ///     The execution context to use when looking up entities that
159     ///     are needed for parsing (locations of variables, etc.)
160     ///
161     /// @param[in] result
162     ///     A pointer to direct at the persistent variable in which the
163     ///     expression's result is stored.
164     ///
165     /// @param[in] function_stack_pointer
166     ///     A pointer to the base of the function's stack frame.  This
167     ///     is used to determine whether the expression result resides in
168     ///     memory that will still be valid, or whether it needs to be
169     ///     treated as homeless for the purpose of future expressions.
170     ///
171     /// @return
172     ///     A Process::Execution results value.
173     //------------------------------------------------------------------
174     bool
175     FinalizeJITExecution (Stream &error_stream,
176                           ExecutionContext &exe_ctx,
177                           lldb::ClangExpressionVariableSP &result,
178                           lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS,
179                           lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS);
180 
181     //------------------------------------------------------------------
182     /// Return the string that the parser should parse.  Must be a full
183     /// translation unit.
184     //------------------------------------------------------------------
185     const char *
Text()186     Text ()
187     {
188         return m_transformed_text.c_str();
189     }
190 
191     //------------------------------------------------------------------
192     /// Return the string that the user typed.
193     //------------------------------------------------------------------
194     const char *
GetUserText()195     GetUserText ()
196     {
197         return m_expr_text.c_str();
198     }
199 
200     //------------------------------------------------------------------
201     /// Return the function name that should be used for executing the
202     /// expression.  Text() should contain the definition of this
203     /// function.
204     //------------------------------------------------------------------
205     const char *
FunctionName()206     FunctionName ()
207     {
208         return "$__lldb_expr";
209     }
210 
211     //------------------------------------------------------------------
212     /// Return the language that should be used when parsing.  To use
213     /// the default, return eLanguageTypeUnknown.
214     //------------------------------------------------------------------
215     virtual lldb::LanguageType
Language()216     Language ()
217     {
218         return m_language;
219     }
220 
221     //------------------------------------------------------------------
222     /// Return the object that the parser should use when resolving external
223     /// values.  May be NULL if everything should be self-contained.
224     //------------------------------------------------------------------
225     ClangExpressionDeclMap *
DeclMap()226     DeclMap ()
227     {
228         return m_expr_decl_map.get();
229     }
230 
231     //------------------------------------------------------------------
232     /// Return the object that the parser should allow to access ASTs.
233     /// May be NULL if the ASTs do not need to be transformed.
234     ///
235     /// @param[in] passthrough
236     ///     The ASTConsumer that the returned transformer should send
237     ///     the ASTs to after transformation.
238     //------------------------------------------------------------------
239     clang::ASTConsumer *
240     ASTTransformer (clang::ASTConsumer *passthrough);
241 
242     //------------------------------------------------------------------
243     /// Return the desired result type of the function, or
244     /// eResultTypeAny if indifferent.
245     //------------------------------------------------------------------
246     virtual ResultType
DesiredResultType()247     DesiredResultType ()
248     {
249         return m_desired_type;
250     }
251 
252     //------------------------------------------------------------------
253     /// Return true if validation code should be inserted into the
254     /// expression.
255     //------------------------------------------------------------------
256     bool
NeedsValidation()257     NeedsValidation ()
258     {
259         return true;
260     }
261 
262     //------------------------------------------------------------------
263     /// Return true if external variables in the expression should be
264     /// resolved.
265     //------------------------------------------------------------------
266     bool
NeedsVariableResolution()267     NeedsVariableResolution ()
268     {
269         return true;
270     }
271 
272     //------------------------------------------------------------------
273     /// Evaluate one expression and return its result.
274     ///
275     /// @param[in] exe_ctx
276     ///     The execution context to use when evaluating the expression.
277     ///
278     /// @param[in] options
279     ///     Expression evaluation options.
280     ///
281     /// @param[in] expr_cstr
282     ///     A C string containing the expression to be evaluated.
283     ///
284     /// @param[in] expr_prefix
285     ///     If non-NULL, a C string containing translation-unit level
286     ///     definitions to be included when the expression is parsed.
287     ///
288     /// @param[in/out] result_valobj_sp
289     ///      If execution is successful, the result valobj is placed here.
290     ///
291     /// @param[out]
292     ///     Filled in with an error in case the expression evaluation
293     ///     fails to parse, run, or evaluated.
294     ///
295     /// @result
296     ///      A Process::ExpressionResults value.  eExpressionCompleted for success.
297     //------------------------------------------------------------------
298     static lldb::ExpressionResults
299     Evaluate (ExecutionContext &exe_ctx,
300               const EvaluateExpressionOptions& options,
301               const char *expr_cstr,
302               const char *expr_prefix,
303               lldb::ValueObjectSP &result_valobj_sp,
304               Error &error);
305 
306     static const Error::ValueType kNoResult = 0x1001; ///< ValueObject::GetError() returns this if there is no result from the expression.
307 private:
308     //------------------------------------------------------------------
309     /// Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
310     //------------------------------------------------------------------
311 
312     void
313     ScanContext (ExecutionContext &exe_ctx,
314                  lldb_private::Error &err);
315 
316     bool
317     PrepareToExecuteJITExpression (Stream &error_stream,
318                                    ExecutionContext &exe_ctx,
319                                    lldb::addr_t &struct_address,
320                                    lldb::addr_t &object_ptr,
321                                    lldb::addr_t &cmd_ptr);
322 
323     void
324     InstallContext (ExecutionContext &exe_ctx);
325 
326     bool
327     LockAndCheckContext (ExecutionContext &exe_ctx,
328                          lldb::TargetSP &target_sp,
329                          lldb::ProcessSP &process_sp,
330                          lldb::StackFrameSP &frame_sp);
331 
332     lldb::ProcessWP                             m_process_wp;           ///< The process used as the context for the expression.
333     Address                                     m_address;              ///< The address the process is stopped in.
334     lldb::addr_t                                m_stack_frame_bottom;   ///< The bottom of the allocated stack frame.
335     lldb::addr_t                                m_stack_frame_top;      ///< The top of the allocated stack frame.
336 
337     std::string                                 m_expr_text;            ///< The text of the expression, as typed by the user
338     std::string                                 m_expr_prefix;          ///< The text of the translation-level definitions, as provided by the user
339     lldb::LanguageType                          m_language;             ///< The language to use when parsing (eLanguageTypeUnknown means use defaults)
340     bool                                        m_allow_cxx;            ///< True if the language allows C++.
341     bool                                        m_allow_objc;           ///< True if the language allows Objective-C.
342     std::string                                 m_transformed_text;     ///< The text of the expression, as send to the parser
343     ResultType                                  m_desired_type;         ///< The type to coerce the expression's result to.  If eResultTypeAny, inferred from the expression.
344 
345     std::unique_ptr<ClangExpressionDeclMap>     m_expr_decl_map;        ///< The map to use when parsing the expression.
346     std::shared_ptr<IRExecutionUnit>            m_execution_unit_sp;    ///< The execution unit the expression is stored in.
347     std::unique_ptr<Materializer>               m_materializer_ap;      ///< The materializer to use when running the expression.
348     std::unique_ptr<ASTResultSynthesizer>       m_result_synthesizer;   ///< The result synthesizer, if one is needed.
349     lldb::ModuleWP                              m_jit_module_wp;
350     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.
351     bool                                        m_in_cplusplus_method;  ///< True if the expression is compiled as a C++ member function (true if it was parsed when exe_ctx was in a C++ method).
352     bool                                        m_in_objectivec_method; ///< 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).
353     bool                                        m_in_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).
354     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.
355     bool                                        m_const_object;         ///< True if "this" is const.
356     Target                                     *m_target;               ///< The target for storing persistent data like types and variables.
357 
358     bool                                        m_can_interpret;        ///< True if the expression could be evaluated statically; false otherwise.
359     lldb::addr_t                                m_materialized_address; ///< The address at which the arguments to the expression have been materialized.
360     Materializer::DematerializerSP              m_dematerializer_sp;    ///< The dematerializer.
361 };
362 
363 } // namespace lldb_private
364 
365 #endif  // liblldb_ClangUserExpression_h_
366