28#include "llvm/ADT/StringSet.h"
34 llvm::StringSet<> plugin_names;
36 if (!plugin_names.insert(
language->GetPluginName()).second)
38 if (std::unique_ptr<OptionGroupLanguageExpression> options =
47#define LLDB_OPTIONS_expression
48#include "CommandOptions.inc"
51 uint32_t option_idx, llvm::StringRef option_arg,
55 const int short_option =
GetDefinitions()[option_idx].short_option;
57 switch (short_option) {
62 sstr.
Printf(
"unknown language type: '%s' for expression. "
63 "List of supported languages:\n",
64 option_arg.str().c_str());
77 "invalid all-threads value setting: \"%s\"",
78 option_arg.str().c_str());
90 "could not convert \"%s\" to a boolean value.",
91 option_arg.str().c_str());
102 "could not convert \"%s\" to a boolean value.",
103 option_arg.str().c_str());
108 if (option_arg.getAsInteger(0,
timeout)) {
111 "invalid timeout setting \"%s\"", option_arg.str().c_str());
122 "could not convert \"%s\" to a boolean value.",
123 option_arg.str().c_str());
128 if (option_arg.empty()) {
135 if (!
error.Success())
137 "unrecognized value for description-verbosity '%s'",
138 option_arg.str().c_str());
158 "could not convert \"%s\" to a boolean value.",
159 option_arg.str().c_str());
165 bool persist_result =
171 "could not convert \"%s\" to a boolean value.",
172 option_arg.str().c_str());
177 llvm_unreachable(
"Unimplemented option");
207llvm::ArrayRef<OptionDefinition>
209 return llvm::ArrayRef(g_expression_options);
227 for (
const std::unique_ptr<OptionGroupLanguageExpression> &language_options :
229 language_options->Apply(options);
268 for (
const std::unique_ptr<OptionGroupLanguageExpression> &language_options :
270 group.
Append(language_options.get());
276 "Evaluate an expression on the current "
277 "thread. Displays any returned value "
278 "with LLDB's default formatting.",
280 eCommandProcessMustBePaused | eCommandTryTargetAPILock |
281 eCommandAllowsDummyTarget),
289Single and multi-line expressions:
292 " The expression provided on the command line must be a complete expression \
293with no newlines. To evaluate a multi-line expression, \
294hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
295Hit return on an empty line to end the multi-line expression."
302 " If the expression can be evaluated statically (without running code) then it will be. \
303Otherwise, by default the expression will run on the current thread with a short timeout: \
304currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
305and resumed with all threads running. You can use the -a option to disable retrying on all \
306threads. You can use the -t option to set a shorter timeout."
309User defined variables:
312 " You can define your own variables for convenience or to be used in subsequent expressions. \
313You define them the same way you would define variables in C. If the first character of \
314your user defined variable is a $, then the variable's value will be available in future \
315expressions, otherwise it will just be available in the current expression."
318Continuing evaluation after a breakpoint:
321 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
322you are done with your investigation, you can either remove the expression execution frames \
323from the stack with \"thread return -x\" or if you are still interested in the expression result \
324you can issue the \"continue\" command and the expression evaluation will complete and the \
325expression result will be available using the \"thread.completed-expression\" key in the thread \
332 expr my_struct->a = my_array[3]
333 expr -f bin -- (index * 8) + 5
334 expr unsigned int $foo = 5
335 expr char c[] = \"foo\"; c[0])");
367 if (exe_ctx.GetFramePtr() ==
nullptr)
370 Target *exe_target = exe_ctx.GetTargetPtr();
381 const std::size_t original_code_size = code.size();
384 code = llvm::getToken(code).second.ltrim();
386 code = args.GetRawPart();
389 assert(original_code_size >= code.size());
390 std::size_t raw_start = original_code_size - code.size();
395 if (cursor_pos < raw_start)
399 assert(cursor_pos >= raw_start);
400 cursor_pos -= raw_start;
402 auto language = exe_ctx.GetFrameRef().GetLanguage();
407 options,
nullptr,
error));
411 expr->Complete(exe_ctx, request, cursor_pos);
418 if (!type.IsPointerType(&pointee))
433 Target *exe_target = exe_ctx.GetTargetPtr();
441 "Can't disable JIT compilation for top-level expressions");
445 EvaluateExpressionOptions eval_options =
457 error_stream <<
" Evaluated this expression after applying Fix-It(s):\n";
461 if (result_valobj_sp) {
466 if (result_valobj_sp->GetError().Success()) {
469 result_valobj_sp->SetFormat(format);
475 "expression cannot be used with --element-count %s",
476 error.AsCString(
""));
481 bool suppress_result =
486 options.SetHideRootName(suppress_result);
487 options.SetVariableFormatDisplayLanguage(
488 result_valobj_sp->GetPreferredDisplayLanguage());
490 if (llvm::Error
error =
491 result_valobj_sp->Dump(output_stream, options)) {
500 if (
auto result_var_sp =
502 auto language = result_valobj_sp->GetPreferredDisplayLanguage();
503 if (
auto *persistent_state =
505 persistent_state->RemovePersistentVariable(result_var_sp);
510 if (result_valobj_sp->GetError().GetError() ==
519 result.
SetError(result_valobj_sp->GetError().ToError());
523 error_stream.
PutCString(
"error: unknown error\n");
528 const bool evaluator_failed =
530 if (evaluator_failed)
532 return !evaluator_failed;
547 output_stream->Flush();
548 *error_stream << return_obj.GetErrorString();
554 const size_t num_lines = lines.
GetSize();
555 if (num_lines > 0 && lines[num_lines - 1].empty()) {
570 const bool multiple_lines =
true;
576 multiple_lines, color_prompt,
583 "Enter expressions, then terminate with an empty line to evaluate:\n");
604 if (command.empty()) {
611 OptionsWithRaw args(command);
612 llvm::StringRef expr = args.GetRawPart();
614 if (args.HasArgs()) {
620 assert(target &&
"target guaranteed by eCommandAllowsDummyTarget");
638 bool initialize =
false;
647 if (repl_error.
Fail()) {
648 result.
SetError(std::move(repl_error));
660 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
661 io_handler_sp->SetIsDone(
false);
665 "Couldn't create a REPL for %s",
667 result.
SetError(std::move(repl_error));
673 else if (expr.empty()) {
683 std::optional<uint16_t> indent;
685 if (pos != llvm::StringRef::npos)
690 assert(target &&
"target guaranteed by eCommandAllowsDummyTarget");
699 std::string fixed_command(
"expression ");
700 if (args.HasArgs()) {
702 fixed_command.append(std::string(args.GetArgStringWithDelimiter()));
static EvaluateExpressionOptions GetExprOptions()
static lldb_private::Status CanBeUsedForElementCountPrinting(ValueObject &valobj)
static llvm::raw_ostream & error(Stream &strm)
void AppendString(llvm::StringRef str, bool reject_if_dupe=true)
ExecutionContext GetExecutionContext(bool adopt_dummy_target=true) const
Returns the execution context the interpreter should run a command in.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
LazyBool auto_apply_fixits
lldb::LanguageType language
bool ShouldSuppressResult(const OptionGroupValueObjectDisplay &display_opts) const
~CommandOptions() override
LanguageRuntimeDescriptionDisplayVerbosity m_verbosity
LazyBool suppress_persistent_result
std::vector< std::unique_ptr< OptionGroupLanguageExpression > > m_language_options
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
void AppendLanguageOptions(OptionGroupOptions &group)
Appends the options that language plugins add to the commands that evaluate expressions to group.
EvaluateExpressionOptions GetEvaluateExpressionOptions(const Target &target, const OptionGroupValueObjectDisplay &display_opts)
Return the appropriate expression options used for evaluating the expression in the given target.
Options * GetOptions() override
CommandOptions m_command_options
OptionGroupOptions m_option_group
CommandObjectExpression(CommandInterpreter &interpreter)
bool IOHandlerIsInputComplete(IOHandler &io_handler, StringList &lines) override
Called to determine whether typing enter after the last line in lines should end input.
OptionGroupValueObjectDisplay m_varobj_options
void HandleCompletion(CompletionRequest &request) override
This default version handles calling option argument completions and then calls HandleArgumentComplet...
bool EvaluateExpression(llvm::StringRef expr, Stream &output_stream, Stream &error_stream, CommandReturnObject &result)
Evaluates the given expression.
void GetMultilineExpression()
uint32_t m_expr_line_count
std::string m_fixed_expression
OptionGroupBoolean m_repl_option
void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override
Called when a line or lines have been retrieved.
~CommandObjectExpression() override
OptionGroupFormat m_format_options
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
virtual void SetHelpLong(llvm::StringRef str)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
Target & GetDummyTarget()
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
std::string m_original_command
Target * GetTarget()
Get the target this command should operate on.
void AppendError(llvm::StringRef in_string)
const ValueObjectList & GetValueObjectList() const
Stream & GetErrorStream()
void SetStatus(lldb::ReturnStatus status)
void SetError(Status error)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void SetDiagnosticIndent(std::optional< uint16_t > indent)
Stream & GetOutputStream()
Generic representation of a type in a programming language.
"lldb/Utility/ArgCompletionRequest.h"
unsigned GetRawCursorPos() const
llvm::StringRef GetRawLineWithUnusedSuffix() const
Returns the full raw user input used to create this CompletionRequest.
A class to manage flag bits.
lldb::StreamUP GetAsyncErrorStream()
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
void SuggestBugReport(llvm::StringRef failure, Stream &strm)
Writes the 'bugreport' note to strm if ShouldSuggestBugReport.
bool CheckTopIOHandlerTypes(IOHandler::Type top_type, IOHandler::Type second_top_type)
lldb::StreamUP GetAsyncOutputStream()
void SetUnwindOnError(bool unwind=false)
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
void SetKeepInMemory(bool keep=true)
void SetCoerceToId(bool coerce=true)
void SetLanguage(lldb::LanguageType language_type)
void SetTryAllThreads(bool try_others=true)
void SetRetriesWithFixIts(uint64_t number_of_retries)
void SetTimeout(const Timeout< std::micro > &timeout)
static constexpr ExecutionPolicy default_execution_policy
void SetAutoApplyFixIts(bool b)
void SetSuppressPersistentResult(bool b)
void SetIgnoreBreakpoints(bool ignore=false)
void SetUseDynamic(lldb::DynamicValueType dynamic=lldb::eDynamicCanRunTarget)
void SetGenerateDebugInfo(bool b)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
IOHandlerDelegate(Completion completion=Completion::None)
static void PrintSupportedLanguagesForExpressions(Stream &s, llvm::StringRef prefix, llvm::StringRef suffix)
Prints to the specified stream 's' each language type that the current target supports for expression...
static void ForEach(llvm::function_ref< IterationAction(Language *)> callback)
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
static lldb::LanguageType GetLanguageTypeFromString(const char *string)=delete
void Append(OptionGroup *group)
Append options from a OptionGroup class.
lldb::DynamicValueType use_dynamic
A pair of an option list with a 'raw' string as a suffix.
A command line option parsing protocol class.
This base class provides an interface to stack frames.
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
bool Fail() const
Test for error condition.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
bool GetEnableNotifyAboutFixIts() const
uint64_t GetNumberOfRetriesWithFixits() const
bool GetEnableAutoApplyFixIts() const
Debugger & GetDebugger() const
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create)
UserExpression * GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, Expression::ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj, Status &error)
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
static const Status::ValueType kNoResult
ValueObject::GetError() returns this if there is no result from the expression.
void Append(const lldb::ValueObjectSP &val_obj_sp)
CompilerType GetCompilerType()
A class that represents a running process on the host machine.
@ eExecutionPolicyTopLevel
LanguageRuntimeDescriptionDisplayVerbosity
@ eLanguageRuntimeDescriptionDisplayVerbosityCompact
@ eLanguageRuntimeDescriptionDisplayVerbosityFull
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Format
Display format definitions.
@ eFormatVoid
Do not print this.
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::UserExpression > UserExpressionSP
ExpressionResults
The results of expression evaluation.
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusSuccessFinishResult
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
std::shared_ptr< lldb_private::REPL > REPLSP
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)