1 //===-- CommandObjectExpression.cpp ---------------------------------------===//
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 "CommandObjectExpression.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Expression/ExpressionVariable.h"
12 #include "lldb/Expression/REPL.h"
13 #include "lldb/Expression/UserExpression.h"
14 #include "lldb/Host/OptionParser.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/CommandOptionArgumentTable.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"
23 #include "lldb/Utility/DiagnosticsRendering.h"
24 #include "lldb/lldb-enumerations.h"
25 #include "lldb/lldb-private-enumerations.h"
28 using namespace lldb_private
;
30 CommandObjectExpression::CommandOptions::CommandOptions() = default;
32 CommandObjectExpression::CommandOptions::~CommandOptions() = default;
34 #define LLDB_OPTIONS_expression
35 #include "CommandOptions.inc"
37 Status
CommandObjectExpression::CommandOptions::SetOptionValue(
38 uint32_t option_idx
, llvm::StringRef option_arg
,
39 ExecutionContext
*execution_context
) {
42 const int short_option
= GetDefinitions()[option_idx
].short_option
;
44 switch (short_option
) {
46 language
= Language::GetLanguageTypeFromString(option_arg
);
47 if (language
== eLanguageTypeUnknown
) {
49 sstr
.Printf("unknown language type: '%s' for expression. "
50 "List of supported languages:\n",
51 option_arg
.str().c_str());
53 Language::PrintSupportedLanguagesForExpressions(sstr
, " ", "\n");
54 error
= Status(sstr
.GetString().str());
61 result
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
63 error
= Status::FromErrorStringWithFormat(
64 "invalid all-threads value setting: \"%s\"",
65 option_arg
.str().c_str());
67 try_all_threads
= result
;
72 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
74 ignore_breakpoints
= tmp_value
;
76 error
= Status::FromErrorStringWithFormat(
77 "could not convert \"%s\" to a boolean value.",
78 option_arg
.str().c_str());
84 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
86 allow_jit
= tmp_value
;
88 error
= Status::FromErrorStringWithFormat(
89 "could not convert \"%s\" to a boolean value.",
90 option_arg
.str().c_str());
95 if (option_arg
.getAsInteger(0, timeout
)) {
97 error
= Status::FromErrorStringWithFormat(
98 "invalid timeout setting \"%s\"", option_arg
.str().c_str());
104 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
106 unwind_on_error
= tmp_value
;
108 error
= Status::FromErrorStringWithFormat(
109 "could not convert \"%s\" to a boolean value.",
110 option_arg
.str().c_str());
115 if (option_arg
.empty()) {
116 m_verbosity
= eLanguageRuntimeDescriptionDisplayVerbosityFull
;
119 m_verbosity
= (LanguageRuntimeDescriptionDisplayVerbosity
)
120 OptionArgParser::ToOptionEnum(
121 option_arg
, GetDefinitions()[option_idx
].enum_values
, 0, error
);
122 if (!error
.Success())
123 error
= Status::FromErrorStringWithFormat(
124 "unrecognized value for description-verbosity '%s'",
125 option_arg
.str().c_str());
130 unwind_on_error
= false;
131 ignore_breakpoints
= false;
140 bool tmp_value
= OptionArgParser::ToBoolean(option_arg
, true, &success
);
142 auto_apply_fixits
= tmp_value
? eLazyBoolYes
: eLazyBoolNo
;
144 error
= Status::FromErrorStringWithFormat(
145 "could not convert \"%s\" to a boolean value.",
146 option_arg
.str().c_str());
152 bool persist_result
=
153 OptionArgParser::ToBoolean(option_arg
, true, &success
);
155 suppress_persistent_result
= !persist_result
? eLazyBoolYes
: eLazyBoolNo
;
157 error
= Status::FromErrorStringWithFormat(
158 "could not convert \"%s\" to a boolean value.",
159 option_arg
.str().c_str());
164 llvm_unreachable("Unimplemented option");
170 void CommandObjectExpression::CommandOptions::OptionParsingStarting(
171 ExecutionContext
*execution_context
) {
173 execution_context
? execution_context
->GetProcessSP() : ProcessSP();
175 ignore_breakpoints
= process_sp
->GetIgnoreBreakpointsInExpressions();
176 unwind_on_error
= process_sp
->GetUnwindOnErrorInExpressions();
178 ignore_breakpoints
= true;
179 unwind_on_error
= true;
183 try_all_threads
= true;
186 language
= eLanguageTypeUnknown
;
187 m_verbosity
= eLanguageRuntimeDescriptionDisplayVerbosityCompact
;
188 auto_apply_fixits
= eLazyBoolCalculate
;
191 suppress_persistent_result
= eLazyBoolCalculate
;
194 llvm::ArrayRef
<OptionDefinition
>
195 CommandObjectExpression::CommandOptions::GetDefinitions() {
196 return llvm::ArrayRef(g_expression_options
);
199 EvaluateExpressionOptions
200 CommandObjectExpression::CommandOptions::GetEvaluateExpressionOptions(
201 const Target
&target
, const OptionGroupValueObjectDisplay
&display_opts
) {
202 EvaluateExpressionOptions options
;
203 options
.SetCoerceToId(display_opts
.use_objc
);
204 options
.SetUnwindOnError(unwind_on_error
);
205 options
.SetIgnoreBreakpoints(ignore_breakpoints
);
206 options
.SetKeepInMemory(true);
207 options
.SetUseDynamic(display_opts
.use_dynamic
);
208 options
.SetTryAllThreads(try_all_threads
);
209 options
.SetDebug(debug
);
210 options
.SetLanguage(language
);
211 options
.SetExecutionPolicy(
212 allow_jit
? EvaluateExpressionOptions::default_execution_policy
213 : lldb_private::eExecutionPolicyNever
);
215 bool auto_apply_fixits
;
216 if (this->auto_apply_fixits
== eLazyBoolCalculate
)
217 auto_apply_fixits
= target
.GetEnableAutoApplyFixIts();
219 auto_apply_fixits
= this->auto_apply_fixits
== eLazyBoolYes
;
221 options
.SetAutoApplyFixIts(auto_apply_fixits
);
222 options
.SetRetriesWithFixIts(target
.GetNumberOfRetriesWithFixits());
225 options
.SetExecutionPolicy(eExecutionPolicyTopLevel
);
227 // If there is any chance we are going to stop and want to see what went
228 // wrong with our expression, we should generate debug info
229 if (!ignore_breakpoints
|| !unwind_on_error
)
230 options
.SetGenerateDebugInfo(true);
233 options
.SetTimeout(std::chrono::microseconds(timeout
));
235 options
.SetTimeout(std::nullopt
);
239 bool CommandObjectExpression::CommandOptions::ShouldSuppressResult(
240 const OptionGroupValueObjectDisplay
&display_opts
) const {
241 // Explicitly disabling persistent results takes precedence over the
242 // m_verbosity/use_objc logic.
243 if (suppress_persistent_result
!= eLazyBoolCalculate
)
244 return suppress_persistent_result
== eLazyBoolYes
;
246 return display_opts
.use_objc
&&
247 m_verbosity
== eLanguageRuntimeDescriptionDisplayVerbosityCompact
;
250 CommandObjectExpression::CommandObjectExpression(
251 CommandInterpreter
&interpreter
)
252 : CommandObjectRaw(interpreter
, "expression",
253 "Evaluate an expression on the current "
254 "thread. Displays any returned value "
255 "with LLDB's default formatting.",
257 eCommandProcessMustBePaused
| eCommandTryTargetAPILock
),
258 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression
),
259 m_format_options(eFormatDefault
),
260 m_repl_option(LLDB_OPT_SET_1
, false, "repl", 'r', "Drop into REPL", false,
262 m_expr_line_count(0) {
265 Single and multi-line expressions:
268 " The expression provided on the command line must be a complete expression \
269 with no newlines. To evaluate a multi-line expression, \
270 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
271 Hit return on an empty line to end the multi-line expression."
278 " If the expression can be evaluated statically (without running code) then it will be. \
279 Otherwise, by default the expression will run on the current thread with a short timeout: \
280 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
281 and resumed with all threads running. You can use the -a option to disable retrying on all \
282 threads. You can use the -t option to set a shorter timeout."
285 User defined variables:
288 " You can define your own variables for convenience or to be used in subsequent expressions. \
289 You define them the same way you would define variables in C. If the first character of \
290 your user defined variable is a $, then the variable's value will be available in future \
291 expressions, otherwise it will just be available in the current expression."
294 Continuing evaluation after a breakpoint:
297 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
298 you are done with your investigation, you can either remove the expression execution frames \
299 from the stack with \"thread return -x\" or if you are still interested in the expression result \
300 you can issue the \"continue\" command and the expression evaluation will complete and the \
301 expression result will be available using the \"thread.completed-expression\" key in the thread \
308 expr my_struct->a = my_array[3]
309 expr -f bin -- (index * 8) + 5
310 expr unsigned int $foo = 5
311 expr char c[] = \"foo
\"; c
[0])");
313 AddSimpleArgumentList(eArgTypeExpression);
315 // Add the "--format
" and "--gdb
-format
"
316 m_option_group.Append(&m_format_options,
317 OptionGroupFormat::OPTION_GROUP_FORMAT |
318 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
320 m_option_group.Append(&m_command_options);
321 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
322 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
323 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
324 m_option_group.Finalize();
327 CommandObjectExpression::~CommandObjectExpression() = default;
329 Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
331 void CommandObjectExpression::HandleCompletion(CompletionRequest &request) {
332 EvaluateExpressionOptions options;
333 options.SetCoerceToId(m_varobj_options.use_objc);
334 options.SetLanguage(m_command_options.language);
335 options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);
336 options.SetAutoApplyFixIts(false);
337 options.SetGenerateDebugInfo(false);
339 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
341 // Get out before we start doing things that expect a valid frame pointer.
342 if (exe_ctx.GetFramePtr() == nullptr)
345 Target *exe_target = exe_ctx.GetTargetPtr();
346 Target &target = exe_target ? *exe_target : GetDummyTarget();
348 unsigned cursor_pos = request.GetRawCursorPos();
349 // Get the full user input including the suffix. The suffix is necessary
350 // as OptionsWithRaw will use it to detect if the cursor is cursor is in the
351 // argument part of in the raw input part of the arguments. If we cut of
352 // of the suffix then "expr
-arg
[cursor
] --" would interpret the "-arg
" as
353 // the raw input (as the "--" is hidden in the suffix).
354 llvm::StringRef code = request.GetRawLineWithUnusedSuffix();
356 const std::size_t original_code_size = code.size();
358 // Remove the first token which is 'expr' or some alias/abbreviation of that.
359 code = llvm::getToken(code).second.ltrim();
360 OptionsWithRaw args(code);
361 code = args.GetRawPart();
363 // The position where the expression starts in the command line.
364 assert(original_code_size >= code.size());
365 std::size_t raw_start = original_code_size - code.size();
367 // Check if the cursor is actually in the expression string, and if not, we
369 // FIXME: We should complete the options here.
370 if (cursor_pos < raw_start)
373 // Make the cursor_pos again relative to the start of the code string.
374 assert(cursor_pos >= raw_start);
375 cursor_pos -= raw_start;
377 auto language = exe_ctx.GetFrameRef().GetLanguage();
380 lldb::UserExpressionSP expr(target.GetUserExpressionForLanguage(
381 code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
382 options, nullptr, error));
386 expr->Complete(exe_ctx, request, cursor_pos);
389 static lldb_private::Status
390 CanBeUsedForElementCountPrinting(ValueObject &valobj) {
391 CompilerType type(valobj.GetCompilerType());
392 CompilerType pointee;
393 if (!type.IsPointerType(&pointee))
394 return Status::FromErrorString("as it does
not refer to a pointer
");
395 if (pointee.IsVoidType())
396 return Status::FromErrorString("as it refers to a pointer to
void");
400 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
401 Stream &output_stream,
402 Stream &error_stream,
403 CommandReturnObject &result) {
404 // Don't use m_exe_ctx as this might be called asynchronously after the
405 // command object DoExecute has finished when doing multi-line expression
406 // that use an input reader...
407 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
408 Target *exe_target = exe_ctx.GetTargetPtr();
409 Target &target = exe_target ? *exe_target : GetDummyTarget();
411 lldb::ValueObjectSP result_valobj_sp;
412 StackFrame *frame = exe_ctx.GetFramePtr();
414 if (m_command_options.top_level && !m_command_options.allow_jit) {
415 result.AppendErrorWithFormat(
416 "Can
't disable JIT compilation for top-level expressions.\n");
420 EvaluateExpressionOptions eval_options =
421 m_command_options.GetEvaluateExpressionOptions(target, m_varobj_options);
422 // This command manually removes the result variable, make sure expression
423 // evaluation doesn't
do it first
.
424 eval_options
.SetSuppressPersistentResult(false);
426 ExpressionResults success
= target
.EvaluateExpression(
427 expr
, frame
, result_valobj_sp
, eval_options
, &m_fixed_expression
);
429 // Only mention Fix-Its if the expression evaluator applied them.
430 // Compiler errors refer to the final expression after applying Fix-It(s).
431 if (!m_fixed_expression
.empty() && target
.GetEnableNotifyAboutFixIts()) {
432 error_stream
<< " Evaluated this expression after applying Fix-It(s):\n";
433 error_stream
<< " " << m_fixed_expression
<< "\n";
436 if (result_valobj_sp
) {
437 Format format
= m_format_options
.GetFormat();
439 if (result_valobj_sp
->GetError().Success()) {
440 if (format
!= eFormatVoid
) {
441 if (format
!= eFormatDefault
)
442 result_valobj_sp
->SetFormat(format
);
444 if (m_varobj_options
.elem_count
> 0) {
445 Status
error(CanBeUsedForElementCountPrinting(*result_valobj_sp
));
447 result
.AppendErrorWithFormat(
448 "expression cannot be used with --element-count %s\n",
449 error
.AsCString(""));
454 bool suppress_result
=
455 m_command_options
.ShouldSuppressResult(m_varobj_options
);
457 DumpValueObjectOptions
options(m_varobj_options
.GetAsDumpOptions(
458 m_command_options
.m_verbosity
, format
));
459 options
.SetHideRootName(suppress_result
);
460 options
.SetVariableFormatDisplayLanguage(
461 result_valobj_sp
->GetPreferredDisplayLanguage());
463 if (llvm::Error error
=
464 result_valobj_sp
->Dump(output_stream
, options
)) {
465 result
.AppendError(toString(std::move(error
)));
470 if (auto result_var_sp
=
471 target
.GetPersistentVariable(result_valobj_sp
->GetName())) {
472 auto language
= result_valobj_sp
->GetPreferredDisplayLanguage();
473 if (auto *persistent_state
=
474 target
.GetPersistentExpressionStateForLanguage(language
))
475 persistent_state
->RemovePersistentVariable(result_var_sp
);
477 result
.SetStatus(eReturnStatusSuccessFinishResult
);
480 if (result_valobj_sp
->GetError().GetError() ==
481 UserExpression::kNoResult
) {
482 if (format
!= eFormatVoid
&& GetDebugger().GetNotifyVoid()) {
483 error_stream
.PutCString("(void)\n");
486 result
.SetStatus(eReturnStatusSuccessFinishResult
);
488 result
.SetStatus(eReturnStatusFailed
);
489 result
.SetError(result_valobj_sp
->GetError().ToError());
493 error_stream
.Printf("error: unknown error\n");
496 return (success
!= eExpressionSetupError
&&
497 success
!= eExpressionParseError
);
500 void CommandObjectExpression::IOHandlerInputComplete(IOHandler
&io_handler
,
502 io_handler
.SetIsDone(true);
503 StreamFileSP output_sp
= io_handler
.GetOutputStreamFileSP();
504 StreamFileSP error_sp
= io_handler
.GetErrorStreamFileSP();
506 CommandReturnObject
return_obj(
507 GetCommandInterpreter().GetDebugger().GetUseColor());
508 EvaluateExpression(line
.c_str(), *output_sp
, *error_sp
, return_obj
);
513 *error_sp
<< return_obj
.GetErrorString();
518 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler
&io_handler
,
520 // An empty lines is used to indicate the end of input
521 const size_t num_lines
= lines
.GetSize();
522 if (num_lines
> 0 && lines
[num_lines
- 1].empty()) {
523 // Remove the last empty line from "lines" so it doesn't appear in our
524 // resulting input and return true to indicate we are done getting lines
531 void CommandObjectExpression::GetMultilineExpression() {
532 m_expr_lines
.clear();
533 m_expr_line_count
= 0;
535 Debugger
&debugger
= GetCommandInterpreter().GetDebugger();
536 bool color_prompt
= debugger
.GetUseColor();
537 const bool multiple_lines
= true; // Get multiple lines
538 IOHandlerSP
io_handler_sp(
539 new IOHandlerEditline(debugger
, IOHandler::Type::Expression
,
540 "lldb-expr", // Name of input reader for history
541 llvm::StringRef(), // No prompt
542 llvm::StringRef(), // Continuation prompt
543 multiple_lines
, color_prompt
,
544 1, // Show line numbers starting at 1
547 StreamFileSP output_sp
= io_handler_sp
->GetOutputStreamFileSP();
549 output_sp
->PutCString(
550 "Enter expressions, then terminate with an empty line to evaluate:\n");
553 debugger
.RunIOHandlerAsync(io_handler_sp
);
556 static EvaluateExpressionOptions
557 GetExprOptions(ExecutionContext
&ctx
,
558 CommandObjectExpression::CommandOptions command_options
) {
559 command_options
.OptionParsingStarting(&ctx
);
561 // Default certain settings for REPL regardless of the global settings.
562 command_options
.unwind_on_error
= false;
563 command_options
.ignore_breakpoints
= false;
564 command_options
.debug
= false;
566 EvaluateExpressionOptions expr_options
;
567 expr_options
.SetUnwindOnError(command_options
.unwind_on_error
);
568 expr_options
.SetIgnoreBreakpoints(command_options
.ignore_breakpoints
);
569 expr_options
.SetTryAllThreads(command_options
.try_all_threads
);
571 if (command_options
.timeout
> 0)
572 expr_options
.SetTimeout(std::chrono::microseconds(command_options
.timeout
));
574 expr_options
.SetTimeout(std::nullopt
);
579 void CommandObjectExpression::DoExecute(llvm::StringRef command
,
580 CommandReturnObject
&result
) {
581 m_fixed_expression
.clear();
582 auto exe_ctx
= GetCommandInterpreter().GetExecutionContext();
583 m_option_group
.NotifyOptionParsingStarting(&exe_ctx
);
585 if (command
.empty()) {
586 GetMultilineExpression();
590 OptionsWithRaw
args(command
);
591 llvm::StringRef expr
= args
.GetRawPart();
593 if (args
.HasArgs()) {
594 if (!ParseOptionsAndNotify(args
.GetArgs(), result
, m_option_group
, exe_ctx
))
597 if (m_repl_option
.GetOptionValue().GetCurrentValue()) {
598 Target
&target
= GetTarget();
600 m_expr_lines
.clear();
601 m_expr_line_count
= 0;
603 Debugger
&debugger
= target
.GetDebugger();
605 // Check if the LLDB command interpreter is sitting on top of a REPL
606 // that launched it...
607 if (debugger
.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter
,
608 IOHandler::Type::REPL
)) {
609 // the LLDB command interpreter is sitting on top of a REPL that
610 // launched it, so just say the command interpreter is done and
611 // fall back to the existing REPL
612 m_interpreter
.GetIOHandler(false)->SetIsDone(true);
614 // We are launching the REPL on top of the current LLDB command
615 // interpreter, so just push one
616 bool initialize
= false;
618 REPLSP
repl_sp(target
.GetREPL(repl_error
, m_command_options
.language
,
623 repl_sp
= target
.GetREPL(repl_error
, m_command_options
.language
,
625 if (repl_error
.Fail()) {
626 result
.SetError(std::move(repl_error
));
633 repl_sp
->SetEvaluateOptions(
634 GetExprOptions(exe_ctx
, m_command_options
));
635 repl_sp
->SetFormatOptions(m_format_options
);
636 repl_sp
->SetValueObjectDisplayOptions(m_varobj_options
);
639 IOHandlerSP
io_handler_sp(repl_sp
->GetIOHandler());
640 io_handler_sp
->SetIsDone(false);
641 debugger
.RunIOHandlerAsync(io_handler_sp
);
643 repl_error
= Status::FromErrorStringWithFormat(
644 "Couldn't create a REPL for %s",
645 Language::GetNameForLanguageType(m_command_options
.language
));
646 result
.SetError(std::move(repl_error
));
651 // No expression following options
652 else if (expr
.empty()) {
653 GetMultilineExpression();
658 // Previously the indent was set up for diagnosing command line
659 // parsing errors. Now point it to the expression.
660 std::optional
<uint16_t> indent
;
661 size_t pos
= m_original_command
.rfind(expr
);
662 if (pos
!= llvm::StringRef::npos
)
664 result
.SetDiagnosticIndent(indent
);
666 Target
&target
= GetTarget();
667 if (EvaluateExpression(expr
, result
.GetOutputStream(),
668 result
.GetErrorStream(), result
)) {
670 if (!m_fixed_expression
.empty() && target
.GetEnableNotifyAboutFixIts()) {
671 CommandHistory
&history
= m_interpreter
.GetCommandHistory();
672 // FIXME: Can we figure out what the user actually typed (e.g. some alias
674 // If we can it would be nice to show that.
675 std::string
fixed_command("expression ");
676 if (args
.HasArgs()) {
677 // Add in any options that might have been in the original command:
678 fixed_command
.append(std::string(args
.GetArgStringWithDelimiter()));
679 fixed_command
.append(m_fixed_expression
);
681 fixed_command
.append(m_fixed_expression
);
682 history
.AppendString(fixed_command
);
686 result
.SetStatus(eReturnStatusFailed
);