1 //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/StringRef.h"
11 #include "CommandObjectExpression.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Expression/REPL.h"
14 #include "lldb/Expression/UserExpression.h"
15 #include "lldb/Host/OptionParser.h"
16 #include "lldb/Interpreter/CommandInterpreter.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionArgParser.h"
19 #include "lldb/Target/Language.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/StackFrame.h"
22 #include "lldb/Target/Target.h"
25 using namespace lldb_private
;
27 CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
29 CommandObjectExpression::CommandOptions::~CommandOptions() = default;
31 static constexpr OptionEnumValueElement g_description_verbosity_type
[] = {
33 eLanguageRuntimeDescriptionDisplayVerbosityCompact
,
35 "Only show the description string",
38 eLanguageRuntimeDescriptionDisplayVerbosityFull
,
40 "Show the full output, including persistent variable's name and type",
44 static constexpr OptionEnumValues
DescriptionVerbosityTypes() {
45 return OptionEnumValues(g_description_verbosity_type
);
48 #define LLDB_OPTIONS_expression
49 #include "CommandOptions.inc"
51 Status
CommandObjectExpression::CommandOptions::SetOptionValue(
52 uint32_t option_idx
, llvm::StringRef option_arg
,
53 ExecutionContext
*execution_context
) {
56 const int short_option
= GetDefinitions()[option_idx
].short_option
;
58 switch (short_option
) {
60 language
= Language::GetLanguageTypeFromString(option_arg
);
61 if (language
== eLanguageTypeUnknown
)
62 error
.SetErrorStringWithFormat(
63 "unknown language type: '%s' for expression",
64 option_arg
.str().c_str());
70 result
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
72 error
.SetErrorStringWithFormat(
73 "invalid all-threads value setting: \"%s\"",
74 option_arg
.str().c_str());
76 try_all_threads
= result
;
81 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
83 ignore_breakpoints
= tmp_value
;
85 error
.SetErrorStringWithFormat(
86 "could not convert \"%s\" to a boolean value.",
87 option_arg
.str().c_str());
93 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
95 allow_jit
= tmp_value
;
97 error
.SetErrorStringWithFormat(
98 "could not convert \"%s\" to a boolean value.",
99 option_arg
.str().c_str());
104 if (option_arg
.getAsInteger(0, timeout
)) {
106 error
.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
107 option_arg
.str().c_str());
113 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
115 unwind_on_error
= tmp_value
;
117 error
.SetErrorStringWithFormat(
118 "could not convert \"%s\" to a boolean value.",
119 option_arg
.str().c_str());
124 if (option_arg
.empty()) {
125 m_verbosity
= eLanguageRuntimeDescriptionDisplayVerbosityFull
;
128 m_verbosity
= (LanguageRuntimeDescriptionDisplayVerbosity
)
129 OptionArgParser::ToOptionEnum(
130 option_arg
, GetDefinitions()[option_idx
].enum_values
, 0, error
);
131 if (!error
.Success())
132 error
.SetErrorStringWithFormat(
133 "unrecognized value for description-verbosity '%s'",
134 option_arg
.str().c_str());
139 unwind_on_error
= false;
140 ignore_breakpoints
= false;
149 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
151 auto_apply_fixits
= tmp_value
? eLazyBoolYes
: eLazyBoolNo
;
153 error
.SetErrorStringWithFormat(
154 "could not convert \"%s\" to a boolean value.",
155 option_arg
.str().c_str());
160 llvm_unreachable("Unimplemented option");
166 void CommandObjectExpression::CommandOptions::OptionParsingStarting(
167 ExecutionContext
*execution_context
) {
169 execution_context
? execution_context
->GetProcessSP() : ProcessSP();
171 ignore_breakpoints
= process_sp
->GetIgnoreBreakpointsInExpressions();
172 unwind_on_error
= process_sp
->GetUnwindOnErrorInExpressions();
174 ignore_breakpoints
= true;
175 unwind_on_error
= true;
179 try_all_threads
= true;
182 language
= eLanguageTypeUnknown
;
183 m_verbosity
= eLanguageRuntimeDescriptionDisplayVerbosityCompact
;
184 auto_apply_fixits
= eLazyBoolCalculate
;
189 llvm::ArrayRef
<OptionDefinition
>
190 CommandObjectExpression::CommandOptions::GetDefinitions() {
191 return llvm::makeArrayRef(g_expression_options
);
194 CommandObjectExpression::CommandObjectExpression(
195 CommandInterpreter
&interpreter
)
196 : CommandObjectRaw(interpreter
, "expression",
197 "Evaluate an expression on the current "
198 "thread. Displays any returned value "
199 "with LLDB's default formatting.",
201 eCommandProcessMustBePaused
| eCommandTryTargetAPILock
),
202 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression
),
203 m_option_group(), m_format_options(eFormatDefault
),
204 m_repl_option(LLDB_OPT_SET_1
, false, "repl", 'r', "Drop into REPL", false,
206 m_command_options(), m_expr_line_count(0), m_expr_lines() {
209 Single and multi-line expressions:
212 " The expression provided on the command line must be a complete expression \
213 with no newlines. To evaluate a multi-line expression, \
214 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
215 Hit return on an empty line to end the multi-line expression."
222 " If the expression can be evaluated statically (without running code) then it will be. \
223 Otherwise, by default the expression will run on the current thread with a short timeout: \
224 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
225 and resumed with all threads running. You can use the -a option to disable retrying on all \
226 threads. You can use the -t option to set a shorter timeout."
229 User defined variables:
232 " You can define your own variables for convenience or to be used in subsequent expressions. \
233 You define them the same way you would define variables in C. If the first character of \
234 your user defined variable is a $, then the variable's value will be available in future \
235 expressions, otherwise it will just be available in the current expression."
238 Continuing evaluation after a breakpoint:
241 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
242 you are done with your investigation, you can either remove the expression execution frames \
243 from the stack with \"thread return -x\" or if you are still interested in the expression result \
244 you can issue the \"continue\" command and the expression evaluation will complete and the \
245 expression result will be available using the \"thread.completed-expression\" key in the thread \
252 expr my_struct->a = my_array[3]
253 expr -f bin -- (index * 8) + 5
254 expr unsigned int $foo = 5
255 expr char c[] = \"foo
\"; c
[0])");
257 CommandArgumentEntry arg;
258 CommandArgumentData expression_arg;
260 // Define the first (and only) variant of this arg.
261 expression_arg.arg_type = eArgTypeExpression;
262 expression_arg.arg_repetition = eArgRepeatPlain;
264 // There is only one variant this argument could be; put it into the argument
266 arg.push_back(expression_arg);
268 // Push the data for the first argument into the m_arguments vector.
269 m_arguments.push_back(arg);
271 // Add the "--format
" and "--gdb
-format
"
272 m_option_group.Append(&m_format_options,
273 OptionGroupFormat::OPTION_GROUP_FORMAT |
274 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
276 m_option_group.Append(&m_command_options);
277 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
278 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
279 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
280 m_option_group.Finalize();
283 CommandObjectExpression::~CommandObjectExpression() = default;
285 Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
287 void CommandObjectExpression::HandleCompletion(CompletionRequest &request) {
288 EvaluateExpressionOptions options;
289 options.SetCoerceToId(m_varobj_options.use_objc);
290 options.SetLanguage(m_command_options.language);
291 options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);
292 options.SetAutoApplyFixIts(false);
293 options.SetGenerateDebugInfo(false);
295 // We need a valid execution context with a frame pointer for this
296 // completion, so if we don't have one we should try to make a valid
297 // execution context.
298 if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
299 m_interpreter.UpdateExecutionContext(nullptr);
301 // This didn't work, so let's get out before we start doing things that
302 // expect a valid frame pointer.
303 if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
306 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
308 Target *target = exe_ctx.GetTargetPtr();
311 target = &GetDummyTarget();
313 unsigned cursor_pos = request.GetRawCursorPos();
314 llvm::StringRef code = request.GetRawLine();
316 const std::size_t original_code_size = code.size();
318 // Remove the first token which is 'expr' or some alias/abbreviation of that.
319 code = llvm::getToken(code).second.ltrim();
320 OptionsWithRaw args(code);
321 code = args.GetRawPart();
323 // The position where the expression starts in the command line.
324 assert(original_code_size >= code.size());
325 std::size_t raw_start = original_code_size - code.size();
327 // Check if the cursor is actually in the expression string, and if not, we
329 // FIXME: We should complete the options here.
330 if (cursor_pos < raw_start)
333 // Make the cursor_pos again relative to the start of the code string.
334 assert(cursor_pos >= raw_start);
335 cursor_pos -= raw_start;
337 auto language = exe_ctx.GetFrameRef().GetLanguage();
340 lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage(
341 code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
342 options, nullptr, error));
346 expr->Complete(exe_ctx, request, cursor_pos);
349 static lldb_private::Status
350 CanBeUsedForElementCountPrinting(ValueObject &valobj) {
351 CompilerType type(valobj.GetCompilerType());
352 CompilerType pointee;
353 if (!type.IsPointerType(&pointee))
354 return Status("as it does
not refer to a pointer
");
355 if (pointee.IsVoidType())
356 return Status("as it refers to a pointer to
void");
360 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
361 Stream *output_stream,
362 Stream *error_stream,
363 CommandReturnObject *result) {
364 // Don't use m_exe_ctx as this might be called asynchronously after the
365 // command object DoExecute has finished when doing multi-line expression
366 // that use an input reader...
367 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
369 Target *target = exe_ctx.GetTargetPtr();
372 target = &GetDummyTarget();
374 lldb::ValueObjectSP result_valobj_sp;
375 bool keep_in_memory = true;
376 StackFrame *frame = exe_ctx.GetFramePtr();
378 EvaluateExpressionOptions options;
379 options.SetCoerceToId(m_varobj_options.use_objc);
380 options.SetUnwindOnError(m_command_options.unwind_on_error);
381 options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
382 options.SetKeepInMemory(keep_in_memory);
383 options.SetUseDynamic(m_varobj_options.use_dynamic);
384 options.SetTryAllThreads(m_command_options.try_all_threads);
385 options.SetDebug(m_command_options.debug);
386 options.SetLanguage(m_command_options.language);
387 options.SetExecutionPolicy(
388 m_command_options.allow_jit
389 ? EvaluateExpressionOptions::default_execution_policy
390 : lldb_private::eExecutionPolicyNever);
392 bool auto_apply_fixits;
393 if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
394 auto_apply_fixits = target->GetEnableAutoApplyFixIts();
396 auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes;
398 options.SetAutoApplyFixIts(auto_apply_fixits);
400 if (m_command_options.top_level)
401 options.SetExecutionPolicy(eExecutionPolicyTopLevel);
403 // If there is any chance we are going to stop and want to see what went
404 // wrong with our expression, we should generate debug info
405 if (!m_command_options.ignore_breakpoints ||
406 !m_command_options.unwind_on_error)
407 options.SetGenerateDebugInfo(true);
409 if (m_command_options.timeout > 0)
410 options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
412 options.SetTimeout(llvm::None);
414 ExpressionResults success = target->EvaluateExpression(
415 expr, frame, result_valobj_sp, options, &m_fixed_expression);
417 // We only tell you about the FixIt if we applied it. The compiler errors
418 // will suggest the FixIt if it parsed.
419 if (error_stream && !m_fixed_expression.empty() &&
420 target->GetEnableNotifyAboutFixIts()) {
421 if (success == eExpressionCompleted)
422 error_stream->Printf(" Fix
-it applied
, fixed expression was
: \n %s
\n",
423 m_fixed_expression.c_str());
426 if (result_valobj_sp) {
427 Format format = m_format_options.GetFormat();
429 if (result_valobj_sp->GetError().Success()) {
430 if (format != eFormatVoid) {
431 if (format != eFormatDefault)
432 result_valobj_sp->SetFormat(format);
434 if (m_varobj_options.elem_count > 0) {
435 Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
437 result->AppendErrorWithFormat(
438 "expression cannot be used with
--element
-count
%s
\n",
439 error.AsCString(""));
440 result->SetStatus(eReturnStatusFailed);
445 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
446 m_command_options.m_verbosity, format));
447 options.SetVariableFormatDisplayLanguage(
448 result_valobj_sp->GetPreferredDisplayLanguage());
450 result_valobj_sp->Dump(*output_stream, options);
453 result->SetStatus(eReturnStatusSuccessFinishResult);
456 if (result_valobj_sp->GetError().GetError() ==
457 UserExpression::kNoResult) {
458 if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) {
459 error_stream->PutCString("(void)\n");
463 result->SetStatus(eReturnStatusSuccessFinishResult);
465 const char *error_cstr = result_valobj_sp->GetError().AsCString();
466 if (error_cstr && error_cstr[0]) {
467 const size_t error_cstr_len = strlen(error_cstr);
468 const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
469 if (strstr(error_cstr, "error
:") != error_cstr)
470 error_stream->PutCString("error
: ");
471 error_stream->Write(error_cstr, error_cstr_len);
472 if (!ends_with_newline)
475 error_stream->PutCString("error
: unknown error
\n");
479 result->SetStatus(eReturnStatusFailed);
487 void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
489 io_handler.SetIsDone(true);
490 // StreamSP output_stream =
491 // io_handler.GetDebugger().GetAsyncOutputStream();
492 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
493 StreamFileSP output_sp = io_handler.GetOutputStreamFileSP();
494 StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
496 EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
503 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
505 // An empty lines is used to indicate the end of input
506 const size_t num_lines = lines.GetSize();
507 if (num_lines > 0 && lines[num_lines - 1].empty()) {
508 // Remove the last empty line from "lines
" so it doesn't appear in our
509 // resulting input and return true to indicate we are done getting lines
516 void CommandObjectExpression::GetMultilineExpression() {
517 m_expr_lines.clear();
518 m_expr_line_count = 0;
520 Debugger &debugger = GetCommandInterpreter().GetDebugger();
521 bool color_prompt = debugger.GetUseColor();
522 const bool multiple_lines = true; // Get multiple lines
523 IOHandlerSP io_handler_sp(
524 new IOHandlerEditline(debugger, IOHandler::Type::Expression,
525 "lldb
-expr
", // Name of input reader for history
526 llvm::StringRef(), // No prompt
527 llvm::StringRef(), // Continuation prompt
528 multiple_lines, color_prompt,
529 1, // Show line numbers starting at 1
532 StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP();
534 output_sp->PutCString(
535 "Enter expressions
, then terminate with an empty line to evaluate
:\n");
538 debugger.RunIOHandlerAsync(io_handler_sp);
541 static EvaluateExpressionOptions
542 GetExprOptions(ExecutionContext &ctx,
543 CommandObjectExpression::CommandOptions command_options) {
544 command_options.OptionParsingStarting(&ctx);
546 // Default certain settings for REPL regardless of the global settings.
547 command_options.unwind_on_error = false;
548 command_options.ignore_breakpoints = false;
549 command_options.debug = false;
551 EvaluateExpressionOptions expr_options;
552 expr_options.SetUnwindOnError(command_options.unwind_on_error);
553 expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints);
554 expr_options.SetTryAllThreads(command_options.try_all_threads);
556 if (command_options.timeout > 0)
557 expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout));
559 expr_options.SetTimeout(llvm::None);
564 bool CommandObjectExpression::DoExecute(llvm::StringRef command,
565 CommandReturnObject &result) {
566 m_fixed_expression.clear();
567 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
568 m_option_group.NotifyOptionParsingStarting(&exe_ctx);
570 if (command.empty()) {
571 GetMultilineExpression();
572 return result.Succeeded();
575 OptionsWithRaw args(command);
576 llvm::StringRef expr = args.GetRawPart();
578 if (args.HasArgs()) {
579 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
582 if (m_repl_option.GetOptionValue().GetCurrentValue()) {
583 Target &target = GetSelectedOrDummyTarget();
585 m_expr_lines.clear();
586 m_expr_line_count = 0;
588 Debugger &debugger = target.GetDebugger();
590 // Check if the LLDB command interpreter is sitting on top of a REPL
591 // that launched it...
592 if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
593 IOHandler::Type::REPL)) {
594 // the LLDB command interpreter is sitting on top of a REPL that
595 // launched it, so just say the command interpreter is done and
596 // fall back to the existing REPL
597 m_interpreter.GetIOHandler(false)->SetIsDone(true);
599 // We are launching the REPL on top of the current LLDB command
600 // interpreter, so just push one
601 bool initialize = false;
603 REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language,
608 repl_sp = target.GetREPL(repl_error, m_command_options.language,
610 if (!repl_error.Success()) {
611 result.SetError(repl_error);
612 return result.Succeeded();
618 repl_sp->SetEvaluateOptions(
619 GetExprOptions(exe_ctx, m_command_options));
620 repl_sp->SetFormatOptions(m_format_options);
621 repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
624 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
625 io_handler_sp->SetIsDone(false);
626 debugger.RunIOHandlerAsync(io_handler_sp);
628 repl_error.SetErrorStringWithFormat(
629 "Couldn
't create a REPL for %s",
630 Language::GetNameForLanguageType(m_command_options.language));
631 result.SetError(repl_error);
632 return result.Succeeded();
636 // No expression following options
637 else if (expr.empty()) {
638 GetMultilineExpression();
639 return result.Succeeded();
643 Target &target = GetSelectedOrDummyTarget();
644 if (EvaluateExpression(expr, &(result.GetOutputStream()),
645 &(result.GetErrorStream()), &result)) {
647 if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
648 CommandHistory &history = m_interpreter.GetCommandHistory();
649 // FIXME: Can we figure out what the user actually typed (e.g. some alias
651 // If we can it would be nice to show that.
652 std::string fixed_command("expression ");
653 if (args.HasArgs()) {
654 // Add in any options that might have been in the original command:
655 fixed_command.append(args.GetArgStringWithDelimiter());
656 fixed_command.append(m_fixed_expression);
658 fixed_command.append(m_fixed_expression);
659 history.AppendString(fixed_command);
661 // Increment statistics to record this expression evaluation success.
662 target.IncrementStats(StatisticKind::ExpressionSuccessful);
666 // Increment statistics to record this expression evaluation failure.
667 target.IncrementStats(StatisticKind::ExpressionFailure);
668 result.SetStatus(eReturnStatusFailed);