1 //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/StringRef.h"
17 #include "CommandObjectExpression.h"
18 #include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Value.h"
21 #include "lldb/Core/ValueObjectVariable.h"
22 #include "lldb/DataFormatters/ValueObjectPrinter.h"
23 #include "lldb/Expression/DWARFExpression.h"
24 #include "lldb/Expression/REPL.h"
25 #include "lldb/Expression/UserExpression.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Host/OptionParser.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Interpreter/CommandReturnObject.h"
30 #include "lldb/Interpreter/OptionArgParser.h"
31 #include "lldb/Symbol/ObjectFile.h"
32 #include "lldb/Symbol/Variable.h"
33 #include "lldb/Target/Language.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/StackFrame.h"
36 #include "lldb/Target/Target.h"
37 #include "lldb/Target/Thread.h"
40 using namespace lldb_private;
42 CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
44 CommandObjectExpression::CommandOptions::~CommandOptions() = default;
46 static OptionEnumValueElement g_description_verbosity_type[] = {
47 {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact",
48 "Only show the description string"},
49 {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full",
50 "Show the full output, including persistent variable's name and type"},
51 {0, nullptr, nullptr}};
53 static OptionDefinition g_expression_options[] = {
55 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."},
56 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"},
57 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."},
58 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error", 'u', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, or raises a signal. "
59 "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
60 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug", 'g', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "When specified, debug the JIT code by setting a breakpoint on the first instruction "
61 "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
62 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Specifies the Language to use when parsing the expression. If not set the target.language "
64 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "apply-fixits", 'X', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "If true, simple fix-it hints will be automatically applied to the expression." },
65 {LLDB_OPT_SET_1, false, "description-verbosity", 'v', OptionParser::eOptionalArgument, nullptr, g_description_verbosity_type, 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."},
66 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "top-level", 'p', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Interpret the expression as a complete translation unit, without injecting it into the local "
67 "context. Allows declaration of persistent, top-level entities without a $ prefix."},
68 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "allow-jit", 'j', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Controls whether the expression can fall back to being JITted if it's not supported by "
69 "the interpreter (defaults to true)."}
73 Status CommandObjectExpression::CommandOptions::SetOptionValue(
74 uint32_t option_idx, llvm::StringRef option_arg,
75 ExecutionContext *execution_context) {
78 const int short_option = GetDefinitions()[option_idx].short_option;
80 switch (short_option) {
82 language = Language::GetLanguageTypeFromString(option_arg);
83 if (language == eLanguageTypeUnknown)
84 error.SetErrorStringWithFormat(
85 "unknown language type: '%s' for expression",
86 option_arg.str().c_str());
92 result = OptionArgParser::ToBoolean(option_arg, true, &success);
94 error.SetErrorStringWithFormat(
95 "invalid all-threads value setting: \"%s\"",
96 option_arg.str().c_str());
98 try_all_threads = result;
103 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
105 ignore_breakpoints = tmp_value;
107 error.SetErrorStringWithFormat(
108 "could not convert \"%s\" to a boolean value.",
109 option_arg.str().c_str());
115 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
117 allow_jit = tmp_value;
119 error.SetErrorStringWithFormat(
120 "could not convert \"%s\" to a boolean value.",
121 option_arg.str().c_str());
126 if (option_arg.getAsInteger(0, timeout)) {
128 error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
129 option_arg.str().c_str());
135 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
137 unwind_on_error = tmp_value;
139 error.SetErrorStringWithFormat(
140 "could not convert \"%s\" to a boolean value.",
141 option_arg.str().c_str());
146 if (option_arg.empty()) {
147 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
150 m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity)
151 OptionArgParser::ToOptionEnum(
152 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
153 if (!error.Success())
154 error.SetErrorStringWithFormat(
155 "unrecognized value for description-verbosity '%s'",
156 option_arg.str().c_str());
161 unwind_on_error = false;
162 ignore_breakpoints = false;
171 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
173 auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
175 error.SetErrorStringWithFormat(
176 "could not convert \"%s\" to a boolean value.",
177 option_arg.str().c_str());
182 error.SetErrorStringWithFormat("invalid short option character '%c'",
190 void CommandObjectExpression::CommandOptions::OptionParsingStarting(
191 ExecutionContext *execution_context) {
193 execution_context ? execution_context->GetProcessSP() : ProcessSP();
195 ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
196 unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
198 ignore_breakpoints = true;
199 unwind_on_error = true;
203 try_all_threads = true;
206 language = eLanguageTypeUnknown;
207 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
208 auto_apply_fixits = eLazyBoolCalculate;
213 llvm::ArrayRef<OptionDefinition>
214 CommandObjectExpression::CommandOptions::GetDefinitions() {
215 return llvm::makeArrayRef(g_expression_options);
218 CommandObjectExpression::CommandObjectExpression(
219 CommandInterpreter &interpreter)
221 interpreter, "expression", "Evaluate an expression on the current "
222 "thread. Displays any returned value "
223 "with LLDB's default formatting.",
224 "", eCommandProcessMustBePaused | eCommandTryTargetAPILock),
225 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
226 m_option_group(), m_format_options(eFormatDefault),
227 m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
229 m_command_options(), m_expr_line_count(0), m_expr_lines() {
232 Single and multi-line expressions:
235 " The expression provided on the command line must be a complete expression \
236 with no newlines. To evaluate a multi-line expression, \
237 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
238 Hit return on an empty line to end the multi-line expression."
245 " If the expression can be evaluated statically (without running code) then it will be. \
246 Otherwise, by default the expression will run on the current thread with a short timeout: \
247 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
248 and resumed with all threads running. You can use the -a option to disable retrying on all \
249 threads. You can use the -t option to set a shorter timeout."
252 User defined variables:
255 " You can define your own variables for convenience or to be used in subsequent expressions. \
256 You define them the same way you would define variables in C. If the first character of \
257 your user defined variable is a $, then the variable's value will be available in future \
258 expressions, otherwise it will just be available in the current expression."
261 Continuing evaluation after a breakpoint:
264 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
265 you are done with your investigation, you can either remove the expression execution frames \
266 from the stack with \"thread return -x\" or if you are still interested in the expression result \
267 you can issue the \"continue\" command and the expression evaluation will complete and the \
268 expression result will be available using the \"thread.completed-expression\" key in the thread \
275 expr my_struct->a = my_array[3]
276 expr -f bin -- (index * 8) + 5
277 expr unsigned int $foo = 5
278 expr char c[] = \"foo\"; c[0])");
280 CommandArgumentEntry arg;
281 CommandArgumentData expression_arg;
283 // Define the first (and only) variant of this arg.
284 expression_arg.arg_type = eArgTypeExpression;
285 expression_arg.arg_repetition = eArgRepeatPlain;
287 // There is only one variant this argument could be; put it into the argument
289 arg.push_back(expression_arg);
291 // Push the data for the first argument into the m_arguments vector.
292 m_arguments.push_back(arg);
294 // Add the "--format" and "--gdb-format"
295 m_option_group.Append(&m_format_options,
296 OptionGroupFormat::OPTION_GROUP_FORMAT |
297 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
299 m_option_group.Append(&m_command_options);
300 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
301 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
302 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
303 m_option_group.Finalize();
306 CommandObjectExpression::~CommandObjectExpression() = default;
308 Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
310 static lldb_private::Status
311 CanBeUsedForElementCountPrinting(ValueObject &valobj) {
312 CompilerType type(valobj.GetCompilerType());
313 CompilerType pointee;
314 if (!type.IsPointerType(&pointee))
315 return Status("as it does not refer to a pointer");
316 if (pointee.IsVoidType())
317 return Status("as it refers to a pointer to void");
321 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
322 Stream *output_stream,
323 Stream *error_stream,
324 CommandReturnObject *result) {
325 // Don't use m_exe_ctx as this might be called asynchronously after the
326 // command object DoExecute has finished when doing multi-line expression
327 // that use an input reader...
328 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
330 Target *target = exe_ctx.GetTargetPtr();
333 target = GetDummyTarget();
336 lldb::ValueObjectSP result_valobj_sp;
337 bool keep_in_memory = true;
338 StackFrame *frame = exe_ctx.GetFramePtr();
340 EvaluateExpressionOptions options;
341 options.SetCoerceToId(m_varobj_options.use_objc);
342 options.SetUnwindOnError(m_command_options.unwind_on_error);
343 options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
344 options.SetKeepInMemory(keep_in_memory);
345 options.SetUseDynamic(m_varobj_options.use_dynamic);
346 options.SetTryAllThreads(m_command_options.try_all_threads);
347 options.SetDebug(m_command_options.debug);
348 options.SetLanguage(m_command_options.language);
349 options.SetExecutionPolicy(
350 m_command_options.allow_jit
351 ? EvaluateExpressionOptions::default_execution_policy
352 : lldb_private::eExecutionPolicyNever);
354 bool auto_apply_fixits;
355 if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
356 auto_apply_fixits = target->GetEnableAutoApplyFixIts();
359 m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false;
361 options.SetAutoApplyFixIts(auto_apply_fixits);
363 if (m_command_options.top_level)
364 options.SetExecutionPolicy(eExecutionPolicyTopLevel);
366 // If there is any chance we are going to stop and want to see what went
367 // wrong with our expression, we should generate debug info
368 if (!m_command_options.ignore_breakpoints ||
369 !m_command_options.unwind_on_error)
370 options.SetGenerateDebugInfo(true);
372 if (m_command_options.timeout > 0)
373 options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
375 options.SetTimeout(llvm::None);
377 ExpressionResults success = target->EvaluateExpression(
378 expr, frame, result_valobj_sp, options, &m_fixed_expression);
380 // We only tell you about the FixIt if we applied it. The compiler errors
381 // will suggest the FixIt if it parsed.
382 if (error_stream && !m_fixed_expression.empty() &&
383 target->GetEnableNotifyAboutFixIts()) {
384 if (success == eExpressionCompleted)
385 error_stream->Printf(
386 " Fix-it applied, fixed expression was: \n %s\n",
387 m_fixed_expression.c_str());
390 if (result_valobj_sp) {
391 Format format = m_format_options.GetFormat();
393 if (result_valobj_sp->GetError().Success()) {
394 if (format != eFormatVoid) {
395 if (format != eFormatDefault)
396 result_valobj_sp->SetFormat(format);
398 if (m_varobj_options.elem_count > 0) {
399 Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
401 result->AppendErrorWithFormat(
402 "expression cannot be used with --element-count %s\n",
403 error.AsCString(""));
404 result->SetStatus(eReturnStatusFailed);
409 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
410 m_command_options.m_verbosity, format));
411 options.SetVariableFormatDisplayLanguage(
412 result_valobj_sp->GetPreferredDisplayLanguage());
414 result_valobj_sp->Dump(*output_stream, options);
417 result->SetStatus(eReturnStatusSuccessFinishResult);
420 if (result_valobj_sp->GetError().GetError() ==
421 UserExpression::kNoResult) {
422 if (format != eFormatVoid &&
423 m_interpreter.GetDebugger().GetNotifyVoid()) {
424 error_stream->PutCString("(void)\n");
428 result->SetStatus(eReturnStatusSuccessFinishResult);
430 const char *error_cstr = result_valobj_sp->GetError().AsCString();
431 if (error_cstr && error_cstr[0]) {
432 const size_t error_cstr_len = strlen(error_cstr);
433 const bool ends_with_newline =
434 error_cstr[error_cstr_len - 1] == '\n';
435 if (strstr(error_cstr, "error:") != error_cstr)
436 error_stream->PutCString("error: ");
437 error_stream->Write(error_cstr, error_cstr_len);
438 if (!ends_with_newline)
441 error_stream->PutCString("error: unknown error\n");
445 result->SetStatus(eReturnStatusFailed);
450 error_stream->Printf("error: invalid execution context for expression\n");
457 void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
459 io_handler.SetIsDone(true);
460 // StreamSP output_stream =
461 // io_handler.GetDebugger().GetAsyncOutputStream();
462 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
463 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
464 StreamFileSP error_sp(io_handler.GetErrorStreamFile());
466 EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
473 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
475 // An empty lines is used to indicate the end of input
476 const size_t num_lines = lines.GetSize();
477 if (num_lines > 0 && lines[num_lines - 1].empty()) {
478 // Remove the last empty line from "lines" so it doesn't appear in our
479 // resulting input and return true to indicate we are done getting lines
486 void CommandObjectExpression::GetMultilineExpression() {
487 m_expr_lines.clear();
488 m_expr_line_count = 0;
490 Debugger &debugger = GetCommandInterpreter().GetDebugger();
491 bool color_prompt = debugger.GetUseColor();
492 const bool multiple_lines = true; // Get multiple lines
493 IOHandlerSP io_handler_sp(
494 new IOHandlerEditline(debugger, IOHandler::Type::Expression,
495 "lldb-expr", // Name of input reader for history
496 llvm::StringRef(), // No prompt
497 llvm::StringRef(), // Continuation prompt
498 multiple_lines, color_prompt,
499 1, // Show line numbers starting at 1
502 StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
504 output_sp->PutCString(
505 "Enter expressions, then terminate with an empty line to evaluate:\n");
508 debugger.PushIOHandler(io_handler_sp);
511 bool CommandObjectExpression::DoExecute(llvm::StringRef command,
512 CommandReturnObject &result) {
513 m_fixed_expression.clear();
514 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
515 m_option_group.NotifyOptionParsingStarting(&exe_ctx);
517 if (command.empty()) {
518 GetMultilineExpression();
519 return result.Succeeded();
522 OptionsWithRaw args(command);
523 llvm::StringRef expr = args.GetRawPart();
525 if (args.HasArgs()) {
526 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
529 if (m_repl_option.GetOptionValue().GetCurrentValue()) {
530 Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
533 m_expr_lines.clear();
534 m_expr_line_count = 0;
536 Debugger &debugger = target->GetDebugger();
538 // Check if the LLDB command interpreter is sitting on top of a REPL
539 // that launched it...
540 if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
541 IOHandler::Type::REPL)) {
542 // the LLDB command interpreter is sitting on top of a REPL that
543 // launched it, so just say the command interpreter is done and
544 // fall back to the existing REPL
545 m_interpreter.GetIOHandler(false)->SetIsDone(true);
547 // We are launching the REPL on top of the current LLDB command
548 // interpreter, so just push one
549 bool initialize = false;
551 REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language,
556 repl_sp = target->GetREPL(repl_error, m_command_options.language,
558 if (!repl_error.Success()) {
559 result.SetError(repl_error);
560 return result.Succeeded();
566 repl_sp->SetCommandOptions(m_command_options);
567 repl_sp->SetFormatOptions(m_format_options);
568 repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
571 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
573 io_handler_sp->SetIsDone(false);
575 debugger.PushIOHandler(io_handler_sp);
577 repl_error.SetErrorStringWithFormat(
578 "Couldn't create a REPL for %s",
579 Language::GetNameForLanguageType(m_command_options.language));
580 result.SetError(repl_error);
581 return result.Succeeded();
586 // No expression following options
587 else if (expr.empty()) {
588 GetMultilineExpression();
589 return result.Succeeded();
593 Target *target = GetSelectedOrDummyTarget();
594 if (EvaluateExpression(expr, &(result.GetOutputStream()),
595 &(result.GetErrorStream()), &result)) {
597 if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) {
598 CommandHistory &history = m_interpreter.GetCommandHistory();
599 // FIXME: Can we figure out what the user actually typed (e.g. some alias
601 // If we can it would be nice to show that.
602 std::string fixed_command("expression ");
603 if (args.HasArgs()) {
604 // Add in any options that might have been in the original command:
605 fixed_command.append(args.GetArgStringWithDelimiter());
606 fixed_command.append(m_fixed_expression);
608 fixed_command.append(m_fixed_expression);
609 history.AppendString(fixed_command);
611 // Increment statistics to record this expression evaluation success.
612 target->IncrementStats(StatisticKind::ExpressionSuccessful);
616 // Increment statistics to record this expression evaluation failure.
617 target->IncrementStats(StatisticKind::ExpressionFailure);
618 result.SetStatus(eReturnStatusFailed);