Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:42:48

0001 //===-- UserExpression.h ----------------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLDB_EXPRESSION_USEREXPRESSION_H
0010 #define LLDB_EXPRESSION_USEREXPRESSION_H
0011 
0012 #include <memory>
0013 #include <string>
0014 #include <vector>
0015 
0016 #include "lldb/Core/Address.h"
0017 #include "lldb/Expression/Expression.h"
0018 #include "lldb/Expression/Materializer.h"
0019 #include "lldb/Target/ExecutionContext.h"
0020 #include "lldb/Target/Target.h"
0021 #include "lldb/lldb-forward.h"
0022 #include "lldb/lldb-private.h"
0023 
0024 namespace lldb_private {
0025 
0026 /// \class UserExpression UserExpression.h "lldb/Expression/UserExpression.h"
0027 /// Encapsulates a one-time expression for use in lldb.
0028 ///
0029 /// LLDB uses expressions for various purposes, notably to call functions
0030 /// and as a backend for the expr command.  UserExpression is a virtual base
0031 /// class that encapsulates the objects needed to parse and interpret or
0032 /// JIT an expression.  The actual parsing part will be provided by the specific
0033 /// implementations of UserExpression - which will be vended through the
0034 /// appropriate TypeSystem.
0035 class UserExpression : public Expression {
0036   /// LLVM RTTI support.
0037   static char ID;
0038 
0039 public:
0040   bool isA(const void *ClassID) const override { return ClassID == &ID; }
0041   static bool classof(const Expression *obj) { return obj->isA(&ID); }
0042 
0043   enum { kDefaultTimeout = 500000u };
0044 
0045   /// Constructor
0046   ///
0047   /// \param[in] expr
0048   ///     The expression to parse.
0049   ///
0050   /// \param[in] language
0051   ///     If not eLanguageTypeUnknown, a language to use when parsing
0052   ///     the expression.  Currently restricted to those languages
0053   ///     supported by Clang.
0054   ///
0055   /// \param[in] desired_type
0056   ///     If not eResultTypeAny, the type to use for the expression
0057   ///     result.
0058   UserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr,
0059                  llvm::StringRef prefix, SourceLanguage language,
0060                  ResultType desired_type,
0061                  const EvaluateExpressionOptions &options);
0062 
0063   /// Destructor
0064   ~UserExpression() override;
0065 
0066   /// Parse the expression
0067   ///
0068   /// \param[in] diagnostic_manager
0069   ///     A diagnostic manager to report parse errors and warnings to.
0070   ///
0071   /// \param[in] exe_ctx
0072   ///     The execution context to use when looking up entities that
0073   ///     are needed for parsing (locations of functions, types of
0074   ///     variables, persistent variables, etc.)
0075   ///
0076   /// \param[in] execution_policy
0077   ///     Determines whether interpretation is possible or mandatory.
0078   ///
0079   /// \param[in] keep_result_in_memory
0080   ///     True if the resulting persistent variable should reside in
0081   ///     target memory, if applicable.
0082   ///
0083   /// \return
0084   ///     True on success (no errors); false otherwise.
0085   virtual bool Parse(DiagnosticManager &diagnostic_manager,
0086                      ExecutionContext &exe_ctx,
0087                      lldb_private::ExecutionPolicy execution_policy,
0088                      bool keep_result_in_memory, bool generate_debug_info) = 0;
0089 
0090   /// Attempts to find possible command line completions for the given
0091   /// (possible incomplete) user expression.
0092   ///
0093   /// \param[in] exe_ctx
0094   ///     The execution context to use when looking up entities that
0095   ///     are needed for parsing and completing (locations of functions, types
0096   ///     of variables, persistent variables, etc.)
0097   ///
0098   /// \param[out] request
0099   ///     The completion request to fill out. The completion should be a string
0100   ///     that would complete the current token at the cursor position.
0101   ///     Note that the string in the list replaces the current token
0102   ///     in the command line.
0103   ///
0104   /// \param[in] complete_pos
0105   ///     The position of the cursor inside the user expression string.
0106   ///     The completion process starts on the token that the cursor is in.
0107   ///
0108   /// \return
0109   ///     True if we added any completion results to the output;
0110   ///     false otherwise.
0111   virtual bool Complete(ExecutionContext &exe_ctx, CompletionRequest &request,
0112                         unsigned complete_pos) {
0113     return false;
0114   }
0115 
0116   virtual bool CanInterpret() = 0;
0117 
0118   bool MatchesContext(ExecutionContext &exe_ctx);
0119 
0120   /// Execute the parsed expression by callinng the derived class's DoExecute
0121   /// method.
0122   ///
0123   /// \param[in] diagnostic_manager
0124   ///     A diagnostic manager to report errors to.
0125   ///
0126   /// \param[in] exe_ctx
0127   ///     The execution context to use when looking up entities that
0128   ///     are needed for parsing (locations of variables, etc.)
0129   ///
0130   /// \param[in] options
0131   ///     Expression evaluation options.
0132   ///
0133   /// \param[in] shared_ptr_to_me
0134   ///     This is a shared pointer to this UserExpression.  This is
0135   ///     needed because Execute can push a thread plan that will hold onto
0136   ///     the UserExpression for an unbounded period of time.  So you
0137   ///     need to give the thread plan a reference to this object that can
0138   ///     keep it alive.
0139   ///
0140   /// \param[in] result
0141   ///     A pointer to direct at the persistent variable in which the
0142   ///     expression's result is stored.
0143   ///
0144   /// \return
0145   ///     A Process::Execution results value.
0146   lldb::ExpressionResults Execute(DiagnosticManager &diagnostic_manager,
0147                                   ExecutionContext &exe_ctx,
0148                                   const EvaluateExpressionOptions &options,
0149                                   lldb::UserExpressionSP &shared_ptr_to_me,
0150                                   lldb::ExpressionVariableSP &result);
0151 
0152   /// Apply the side effects of the function to program state.
0153   ///
0154   /// \param[in] diagnostic_manager
0155   ///     A diagnostic manager to report errors to.
0156   ///
0157   /// \param[in] exe_ctx
0158   ///     The execution context to use when looking up entities that
0159   ///     are needed for parsing (locations of variables, etc.)
0160   ///
0161   /// \param[in] result
0162   ///     A pointer to direct at the persistent variable in which the
0163   ///     expression's result is stored.
0164   ///
0165   /// \param[in] function_stack_bottom
0166   ///     A pointer to the bottom of the function's stack frame.  This
0167   ///     is used to determine whether the expression result resides in
0168   ///     memory that will still be valid, or whether it needs to be
0169   ///     treated as homeless for the purpose of future expressions.
0170   ///
0171   /// \param[in] function_stack_top
0172   ///     A pointer to the top of the function's stack frame.  This
0173   ///     is used to determine whether the expression result resides in
0174   ///     memory that will still be valid, or whether it needs to be
0175   ///     treated as homeless for the purpose of future expressions.
0176   ///
0177   /// \return
0178   ///     A Process::Execution results value.
0179   virtual bool FinalizeJITExecution(
0180       DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
0181       lldb::ExpressionVariableSP &result,
0182       lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS,
0183       lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS) = 0;
0184 
0185   /// Return the string that the parser should parse.
0186   const char *Text() override { return m_expr_text.c_str(); }
0187 
0188   /// Return the string that the user typed.
0189   const char *GetUserText() { return m_expr_text.c_str(); }
0190 
0191   /// Return the function name that should be used for executing the
0192   /// expression.  Text() should contain the definition of this function.
0193   const char *FunctionName() override { return "$__lldb_expr"; }
0194 
0195   /// Returns whether the call to Parse on this user expression is cacheable.
0196   /// This function exists to provide an escape hatch for supporting languages
0197   /// where parsing an expression in the exact same context is unsafe. For
0198   /// example, languages where generic functions aren't monomorphized, but
0199   /// implement some other mechanism to represent generic values, may be unsafe
0200   /// to cache, as the concrete type substitution may be different in every
0201   /// expression evaluation.
0202   virtual bool IsParseCacheable() { return true; }
0203   /// Return the language that should be used when parsing.  To use the
0204   /// default, return eLanguageTypeUnknown.
0205   SourceLanguage Language() const override { return m_language; }
0206 
0207   /// Return the desired result type of the function, or eResultTypeAny if
0208   /// indifferent.
0209   ResultType DesiredResultType() const override { return m_desired_type; }
0210 
0211   /// Return true if validation code should be inserted into the expression.
0212   bool NeedsValidation() override { return true; }
0213 
0214   /// Return true if external variables in the expression should be resolved.
0215   bool NeedsVariableResolution() override { return true; }
0216 
0217   EvaluateExpressionOptions *GetOptions() override { return &m_options; }
0218 
0219   virtual lldb::ExpressionVariableSP
0220   GetResultAfterDematerialization(ExecutionContextScope *exe_scope) {
0221     return lldb::ExpressionVariableSP();
0222   }
0223 
0224   /// Evaluate one expression in the scratch context of the target passed in
0225   /// the exe_ctx and return its result.
0226   ///
0227   /// \param[in] exe_ctx
0228   ///     The execution context to use when evaluating the expression.
0229   ///
0230   /// \param[in] options
0231   ///     Expression evaluation options.  N.B. The language in the
0232   ///     evaluation options will be used to determine the language used for
0233   ///     expression evaluation.
0234   ///
0235   /// \param[in] expr_cstr
0236   ///     A C string containing the expression to be evaluated.
0237   ///
0238   /// \param[in] expr_prefix
0239   ///     If non-nullptr, a C string containing translation-unit level
0240   ///     definitions to be included when the expression is parsed.
0241   ///
0242   /// \param[in,out] result_valobj_sp
0243   ///      If execution is successful, the result valobj is placed
0244   ///      here. Otherwise its Error will contain an ExpressionError
0245   ///      with details about the failure mode.
0246   ///
0247   /// \param[out] fixed_expression
0248   ///     If non-nullptr, the fixed expression is copied into the provided
0249   ///     string.
0250   ///
0251   /// \param[in] ctx_obj
0252   ///     If specified, then the expression will be evaluated in the context of
0253   ///     this object. It means that the context object's address will be
0254   ///     treated as `this` for the expression (the expression will be
0255   ///     evaluated as if it was inside of a method of the context object's
0256   ///     class, and its `this` parameter were pointing to the context object).
0257   ///     The parameter makes sense for class and union types only.
0258   ///     Currently there is a limitation: the context object must be located
0259   ///     in the debuggee process' memory (and have the load address).
0260   ///
0261   /// \result
0262   ///      A Process::ExpressionResults value.  eExpressionCompleted for
0263   ///      success.
0264   static lldb::ExpressionResults
0265   Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
0266            llvm::StringRef expr_cstr, llvm::StringRef expr_prefix,
0267            lldb::ValueObjectSP &result_valobj_sp,
0268            std::string *fixed_expression = nullptr,
0269            ValueObject *ctx_obj = nullptr);
0270 
0271   static const Status::ValueType kNoResult =
0272       0x1001; ///< ValueObject::GetError() returns this if there is no result
0273               /// from the expression.
0274 
0275   llvm::StringRef GetFixedText() {
0276     return m_fixed_text;
0277   }
0278 
0279 protected:
0280   virtual lldb::ExpressionResults
0281   DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
0282             const EvaluateExpressionOptions &options,
0283             lldb::UserExpressionSP &shared_ptr_to_me,
0284             lldb::ExpressionVariableSP &result) = 0;
0285 
0286   static lldb::addr_t GetObjectPointer(lldb::StackFrameSP frame_sp,
0287                                        llvm::StringRef object_name,
0288                                        Status &err);
0289 
0290   /// Return ValueObject for a given variable name in the current stack frame
0291   ///
0292   /// \param[in] frame Current stack frame. When passed a 'nullptr', this
0293   ///                  function returns an empty ValueObjectSP.
0294   ///
0295   /// \param[in] object_name Name of the variable in the current stack frame
0296   ///                        for which we want the ValueObjectSP.
0297   ///
0298   /// \param[out] err Status object which will get set on error.
0299   ///
0300   /// \returns On success returns a ValueObjectSP corresponding to the variable
0301   ///          with 'object_name' in the current 'frame'. Otherwise, returns
0302   ///          'nullptr' (and sets the error status parameter 'err').
0303   static lldb::ValueObjectSP
0304   GetObjectPointerValueObject(lldb::StackFrameSP frame,
0305                               llvm::StringRef object_name, Status &err);
0306 
0307   /// Populate m_in_cplusplus_method and m_in_objectivec_method based on the
0308   /// environment.
0309 
0310   void InstallContext(ExecutionContext &exe_ctx);
0311 
0312   bool LockAndCheckContext(ExecutionContext &exe_ctx, lldb::TargetSP &target_sp,
0313                            lldb::ProcessSP &process_sp,
0314                            lldb::StackFrameSP &frame_sp);
0315 
0316   /// The address the process is stopped in.
0317   Address m_address;
0318   /// The text of the expression, as typed by the user.
0319   std::string m_expr_text;
0320   /// The text of the translation-level definitions, as provided by the user.
0321   std::string m_expr_prefix;
0322   /// The text of the expression with fix-its applied this won't be set if the
0323   /// fixed text doesn't parse.
0324   std::string m_fixed_text;
0325   /// The language to use when parsing (unknown means use defaults).
0326   SourceLanguage m_language;
0327   /// The type to coerce the expression's result to. If eResultTypeAny, inferred
0328   /// from the expression.
0329   ResultType m_desired_type;
0330   /// Additional options provided by the user.
0331   EvaluateExpressionOptions m_options;
0332 };
0333 
0334 } // namespace lldb_private
0335 
0336 #endif // LLDB_EXPRESSION_USEREXPRESSION_H