130fdc8d8SChris Lattner //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
230fdc8d8SChris Lattner //
330fdc8d8SChris Lattner //                     The LLVM Compiler Infrastructure
430fdc8d8SChris Lattner //
530fdc8d8SChris Lattner // This file is distributed under the University of Illinois Open Source
630fdc8d8SChris Lattner // License. See LICENSE.TXT for details.
730fdc8d8SChris Lattner //
830fdc8d8SChris Lattner //===----------------------------------------------------------------------===//
930fdc8d8SChris Lattner 
1030fdc8d8SChris Lattner // C Includes
1130fdc8d8SChris Lattner // C++ Includes
1230fdc8d8SChris Lattner // Other libraries and framework includes
13c8ecc2a9SEugene Zelenko #include "llvm/ADT/STLExtras.h"
14c8ecc2a9SEugene Zelenko #include "llvm/ADT/StringRef.h"
15c8ecc2a9SEugene Zelenko 
1630fdc8d8SChris Lattner // Project includes
17c8ecc2a9SEugene Zelenko #include "CommandObjectExpression.h"
18b9c1b51eSKate Stone #include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h"
19b9c1b51eSKate Stone #include "lldb/Core/Debugger.h"
2030fdc8d8SChris Lattner #include "lldb/Core/Value.h"
216c68fb45SJim Ingham #include "lldb/Core/ValueObjectVariable.h"
224d93b8cdSEnrico Granata #include "lldb/DataFormatters/ValueObjectPrinter.h"
2330fdc8d8SChris Lattner #include "lldb/Expression/DWARFExpression.h"
24f2bd5c3eSSean Callanan #include "lldb/Expression/REPL.h"
25b9c1b51eSKate Stone #include "lldb/Expression/UserExpression.h"
2630fdc8d8SChris Lattner #include "lldb/Host/Host.h"
275275aaa0SVince Harron #include "lldb/Host/StringConvert.h"
286611103cSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h"
2930fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h"
3030fdc8d8SChris Lattner #include "lldb/Symbol/ObjectFile.h"
3130fdc8d8SChris Lattner #include "lldb/Symbol/Variable.h"
32b9c1b51eSKate Stone #include "lldb/Target/Language.h"
3330fdc8d8SChris Lattner #include "lldb/Target/Process.h"
34b57e4a1bSJason Molenda #include "lldb/Target/StackFrame.h"
3530fdc8d8SChris Lattner #include "lldb/Target/Target.h"
367260f620SGreg Clayton #include "lldb/Target/Thread.h"
3730fdc8d8SChris Lattner 
3830fdc8d8SChris Lattner using namespace lldb;
3930fdc8d8SChris Lattner using namespace lldb_private;
4030fdc8d8SChris Lattner 
41b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
4230fdc8d8SChris Lattner 
43c8ecc2a9SEugene Zelenko CommandObjectExpression::CommandOptions::~CommandOptions() = default;
4430fdc8d8SChris Lattner 
45b9c1b51eSKate Stone static OptionEnumValueElement g_description_verbosity_type[] = {
46b9c1b51eSKate Stone     {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact",
47b9c1b51eSKate Stone      "Only show the description string"},
48b9c1b51eSKate Stone     {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full",
49b9c1b51eSKate Stone      "Show the full output, including persistent variable's name and type"},
50b9c1b51eSKate Stone     {0, nullptr, nullptr}};
514d93b8cdSEnrico Granata 
52*1f0f5b5bSZachary Turner static OptionDefinition g_expression_options[] = {
53ac9c3a62SKate Stone     // clang-format off
54c8ecc2a9SEugene Zelenko   {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."},
55c8ecc2a9SEugene Zelenko   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints",    'i', OptionParser::eRequiredArgument, nullptr, nullptr,                      0, eArgTypeBoolean,              "Ignore breakpoint hits while running expressions"},
56c8ecc2a9SEugene Zelenko   {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."},
57ac9c3a62SKate Stone   {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.  "
58ac9c3a62SKate Stone                                                                                                                                                                                   "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
59ac9c3a62SKate Stone   {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 "
60ac9c3a62SKate Stone                                                                                                                                                                                   "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
61ac9c3a62SKate Stone   {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 "
62ac9c3a62SKate Stone                                                                                                                                                                                   "setting is used." },
63279b2e88SJim Ingham   {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." },
64c8ecc2a9SEugene Zelenko   {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."},
65ac9c3a62SKate Stone   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "top-level",             'p', OptionParser::eNoArgument,       nullptr, nullptr,                      0, eArgTypeNone,                 "Interpret the expression as top-level definitions rather than code to be immediately "
66ac9c3a62SKate Stone                                                                                                                                                                                   "executed."},
67ac9c3a62SKate Stone   {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 "
68ac9c3a62SKate Stone                                                                                                                                                                                   "the interpreter (defaults to true)."}
69ac9c3a62SKate Stone     // clang-format on
701deb7962SGreg Clayton };
711deb7962SGreg Clayton 
72b9c1b51eSKate Stone Error CommandObjectExpression::CommandOptions::SetOptionValue(
73b9c1b51eSKate Stone     uint32_t option_idx, const char *option_arg,
74b9c1b51eSKate Stone     ExecutionContext *execution_context) {
7530fdc8d8SChris Lattner   Error error;
7630fdc8d8SChris Lattner 
77ecbb0bb1SZachary Turner   auto option_strref = llvm::StringRef::withNullAsEmpty(option_arg);
78*1f0f5b5bSZachary Turner   const int short_option = GetDefinitions()[option_idx].short_option;
7930fdc8d8SChris Lattner 
80b9c1b51eSKate Stone   switch (short_option) {
8115663c53SDawn Perchik   case 'l':
820e0984eeSJim Ingham     language = Language::GetLanguageTypeFromString(option_arg);
8315663c53SDawn Perchik     if (language == eLanguageTypeUnknown)
84b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
85b9c1b51eSKate Stone           "unknown language type: '%s' for expression", option_arg);
8615663c53SDawn Perchik     break;
8730fdc8d8SChris Lattner 
88b9c1b51eSKate Stone   case 'a': {
8935e1bda6SJim Ingham     bool success;
9035e1bda6SJim Ingham     bool result;
91ecbb0bb1SZachary Turner     result = Args::StringToBoolean(option_strref, true, &success);
9235e1bda6SJim Ingham     if (!success)
93b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
94b9c1b51eSKate Stone           "invalid all-threads value setting: \"%s\"", option_arg);
9535e1bda6SJim Ingham     else
9635e1bda6SJim Ingham       try_all_threads = result;
97b9c1b51eSKate Stone   } break;
986c68fb45SJim Ingham 
99b9c1b51eSKate Stone   case 'i': {
100184e9811SJim Ingham     bool success;
101ecbb0bb1SZachary Turner     bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
102184e9811SJim Ingham     if (success)
103184e9811SJim Ingham       ignore_breakpoints = tmp_value;
104184e9811SJim Ingham     else
105b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
106b9c1b51eSKate Stone           "could not convert \"%s\" to a boolean value.", option_arg);
107184e9811SJim Ingham     break;
108184e9811SJim Ingham   }
1093fe71581SMarianne Mailhot-Sarrasin 
110b9c1b51eSKate Stone   case 'j': {
1113fe71581SMarianne Mailhot-Sarrasin     bool success;
112ecbb0bb1SZachary Turner     bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
1133fe71581SMarianne Mailhot-Sarrasin     if (success)
1143fe71581SMarianne Mailhot-Sarrasin       allow_jit = tmp_value;
1153fe71581SMarianne Mailhot-Sarrasin     else
116b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
117b9c1b51eSKate Stone           "could not convert \"%s\" to a boolean value.", option_arg);
1183fe71581SMarianne Mailhot-Sarrasin     break;
1193fe71581SMarianne Mailhot-Sarrasin   }
1203fe71581SMarianne Mailhot-Sarrasin 
121b9c1b51eSKate Stone   case 't': {
12235e1bda6SJim Ingham     bool success;
12335e1bda6SJim Ingham     uint32_t result;
1245275aaa0SVince Harron     result = StringConvert::ToUInt32(option_arg, 0, 0, &success);
12535e1bda6SJim Ingham     if (success)
12635e1bda6SJim Ingham       timeout = result;
12735e1bda6SJim Ingham     else
128b9c1b51eSKate Stone       error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
129b9c1b51eSKate Stone                                      option_arg);
130b9c1b51eSKate Stone   } break;
13135e1bda6SJim Ingham 
132b9c1b51eSKate Stone   case 'u': {
133399f1cafSJim Ingham     bool success;
134ecbb0bb1SZachary Turner     bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
135184e9811SJim Ingham     if (success)
136184e9811SJim Ingham       unwind_on_error = tmp_value;
137184e9811SJim Ingham     else
138b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
139b9c1b51eSKate Stone           "could not convert \"%s\" to a boolean value.", option_arg);
140399f1cafSJim Ingham     break;
1413bfdaa2aSSean Callanan   }
1424d93b8cdSEnrico Granata 
1434d93b8cdSEnrico Granata   case 'v':
144b9c1b51eSKate Stone     if (!option_arg) {
1454d93b8cdSEnrico Granata       m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
1464d93b8cdSEnrico Granata       break;
1474d93b8cdSEnrico Granata     }
148b9c1b51eSKate Stone     m_verbosity =
149b9c1b51eSKate Stone         (LanguageRuntimeDescriptionDisplayVerbosity)Args::StringToOptionEnum(
150*1f0f5b5bSZachary Turner             option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
1514d93b8cdSEnrico Granata     if (!error.Success())
152b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
153b9c1b51eSKate Stone           "unrecognized value for description-verbosity '%s'", option_arg);
1544d93b8cdSEnrico Granata     break;
1554d93b8cdSEnrico Granata 
15662afb9f6SGreg Clayton   case 'g':
15762afb9f6SGreg Clayton     debug = true;
15862afb9f6SGreg Clayton     unwind_on_error = false;
15962afb9f6SGreg Clayton     ignore_breakpoints = false;
16062afb9f6SGreg Clayton     break;
16162afb9f6SGreg Clayton 
162863fab69SSean Callanan   case 'p':
163863fab69SSean Callanan     top_level = true;
164863fab69SSean Callanan     break;
165863fab69SSean Callanan 
166b9c1b51eSKate Stone   case 'X': {
167a1e541bfSJim Ingham     bool success;
168ecbb0bb1SZachary Turner     bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
169a1e541bfSJim Ingham     if (success)
170a1e541bfSJim Ingham       auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
171a1e541bfSJim Ingham     else
172b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
173b9c1b51eSKate Stone           "could not convert \"%s\" to a boolean value.", option_arg);
174a1e541bfSJim Ingham     break;
175a1e541bfSJim Ingham   }
176a1e541bfSJim Ingham 
17730fdc8d8SChris Lattner   default:
178b9c1b51eSKate Stone     error.SetErrorStringWithFormat("invalid short option character '%c'",
179b9c1b51eSKate Stone                                    short_option);
18030fdc8d8SChris Lattner     break;
18130fdc8d8SChris Lattner   }
18230fdc8d8SChris Lattner 
18330fdc8d8SChris Lattner   return error;
18430fdc8d8SChris Lattner }
18530fdc8d8SChris Lattner 
186b9c1b51eSKate Stone void CommandObjectExpression::CommandOptions::OptionParsingStarting(
187b9c1b51eSKate Stone     ExecutionContext *execution_context) {
188e1cfbc79STodd Fiala   auto process_sp =
189e1cfbc79STodd Fiala       execution_context ? execution_context->GetProcessSP() : ProcessSP();
190b9c1b51eSKate Stone   if (process_sp) {
191e1cfbc79STodd Fiala     ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
192e1cfbc79STodd Fiala     unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
193b9c1b51eSKate Stone   } else {
194fc03f8fcSGreg Clayton     ignore_breakpoints = true;
195399f1cafSJim Ingham     unwind_on_error = true;
196184e9811SJim Ingham   }
197184e9811SJim Ingham 
19830fdc8d8SChris Lattner   show_summary = true;
19935e1bda6SJim Ingham   try_all_threads = true;
20035e1bda6SJim Ingham   timeout = 0;
20162afb9f6SGreg Clayton   debug = false;
20215663c53SDawn Perchik   language = eLanguageTypeUnknown;
2034d93b8cdSEnrico Granata   m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
204a1e541bfSJim Ingham   auto_apply_fixits = eLazyBoolCalculate;
205863fab69SSean Callanan   top_level = false;
2063fe71581SMarianne Mailhot-Sarrasin   allow_jit = true;
20730fdc8d8SChris Lattner }
20830fdc8d8SChris Lattner 
209*1f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition>
210b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::GetDefinitions() {
211*1f0f5b5bSZachary Turner   return g_expression_options;
21230fdc8d8SChris Lattner }
21330fdc8d8SChris Lattner 
214b9c1b51eSKate Stone CommandObjectExpression::CommandObjectExpression(
215b9c1b51eSKate Stone     CommandInterpreter &interpreter)
2167428a18cSKate Stone     : CommandObjectRaw(
217b9c1b51eSKate Stone           interpreter, "expression", "Evaluate an expression on the current "
218b9c1b51eSKate Stone                                      "thread.  Displays any returned value "
219b9c1b51eSKate Stone                                      "with LLDB's default formatting.",
2207428a18cSKate Stone           nullptr, eCommandProcessMustBePaused | eCommandTryTargetAPILock),
22144d93782SGreg Clayton       IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
222b9c1b51eSKate Stone       m_option_group(), m_format_options(eFormatDefault),
223b9c1b51eSKate Stone       m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
224b9c1b51eSKate Stone                     true),
225b9c1b51eSKate Stone       m_command_options(), m_expr_line_count(0), m_expr_lines() {
22630fdc8d8SChris Lattner   SetHelpLong(
227ea671fbdSKate Stone       R"(
228ea671fbdSKate Stone Timeouts:
229ea671fbdSKate Stone 
230b9c1b51eSKate Stone )"
231b9c1b51eSKate Stone       "    If the expression can be evaluated statically (without running code) then it will be.  \
232ea671fbdSKate Stone Otherwise, by default the expression will run on the current thread with a short timeout: \
233ea671fbdSKate Stone currently .25 seconds.  If it doesn't return in that time, the evaluation will be interrupted \
234ea671fbdSKate Stone and resumed with all threads running.  You can use the -a option to disable retrying on all \
235b9c1b51eSKate Stone threads.  You can use the -t option to set a shorter timeout."
236b9c1b51eSKate Stone       R"(
237ea671fbdSKate Stone 
238ea671fbdSKate Stone User defined variables:
239ea671fbdSKate Stone 
240b9c1b51eSKate Stone )"
241b9c1b51eSKate Stone       "    You can define your own variables for convenience or to be used in subsequent expressions.  \
242ea671fbdSKate Stone You define them the same way you would define variables in C.  If the first character of \
243ea671fbdSKate Stone your user defined variable is a $, then the variable's value will be available in future \
244b9c1b51eSKate Stone expressions, otherwise it will just be available in the current expression."
245b9c1b51eSKate Stone       R"(
246ea671fbdSKate Stone 
247ea671fbdSKate Stone Continuing evaluation after a breakpoint:
248ea671fbdSKate Stone 
249b9c1b51eSKate Stone )"
250b9c1b51eSKate Stone       "    If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
251ea671fbdSKate Stone you are done with your investigation, you can either remove the expression execution frames \
252ea671fbdSKate Stone from the stack with \"thread return -x\" or if you are still interested in the expression result \
253ea671fbdSKate Stone you can issue the \"continue\" command and the expression evaluation will complete and the \
254ea671fbdSKate Stone expression result will be available using the \"thread.completed-expression\" key in the thread \
255b9c1b51eSKate Stone format."
256b9c1b51eSKate Stone       R"(
257ea671fbdSKate Stone 
258ea671fbdSKate Stone Examples:
259ea671fbdSKate Stone 
260ea671fbdSKate Stone     expr my_struct->a = my_array[3]
261ea671fbdSKate Stone     expr -f bin -- (index * 8) + 5
262ea671fbdSKate Stone     expr unsigned int $foo = 5
263b9c1b51eSKate Stone     expr char c[] = \"foo\"; c[0])");
264405fe67fSCaroline Tice 
265405fe67fSCaroline Tice   CommandArgumentEntry arg;
266405fe67fSCaroline Tice   CommandArgumentData expression_arg;
267405fe67fSCaroline Tice 
268405fe67fSCaroline Tice   // Define the first (and only) variant of this arg.
269405fe67fSCaroline Tice   expression_arg.arg_type = eArgTypeExpression;
270405fe67fSCaroline Tice   expression_arg.arg_repetition = eArgRepeatPlain;
271405fe67fSCaroline Tice 
272b9c1b51eSKate Stone   // There is only one variant this argument could be; put it into the argument
273b9c1b51eSKate Stone   // entry.
274405fe67fSCaroline Tice   arg.push_back(expression_arg);
275405fe67fSCaroline Tice 
276405fe67fSCaroline Tice   // Push the data for the first argument into the m_arguments vector.
277405fe67fSCaroline Tice   m_arguments.push_back(arg);
2781deb7962SGreg Clayton 
2795009f9d5SGreg Clayton   // Add the "--format" and "--gdb-format"
280b9c1b51eSKate Stone   m_option_group.Append(&m_format_options,
281b9c1b51eSKate Stone                         OptionGroupFormat::OPTION_GROUP_FORMAT |
282b9c1b51eSKate Stone                             OptionGroupFormat::OPTION_GROUP_GDB_FMT,
283b9c1b51eSKate Stone                         LLDB_OPT_SET_1);
2841deb7962SGreg Clayton   m_option_group.Append(&m_command_options);
285b9c1b51eSKate Stone   m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
286b9c1b51eSKate Stone                         LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
287f2bd5c3eSSean Callanan   m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
2881deb7962SGreg Clayton   m_option_group.Finalize();
28930fdc8d8SChris Lattner }
29030fdc8d8SChris Lattner 
291c8ecc2a9SEugene Zelenko CommandObjectExpression::~CommandObjectExpression() = default;
29230fdc8d8SChris Lattner 
293b9c1b51eSKate Stone Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
29430fdc8d8SChris Lattner 
295520a422bSEnrico Granata static lldb_private::Error
296b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) {
297520a422bSEnrico Granata   CompilerType type(valobj.GetCompilerType());
298520a422bSEnrico Granata   CompilerType pointee;
299520a422bSEnrico Granata   if (!type.IsPointerType(&pointee))
300520a422bSEnrico Granata     return Error("as it does not refer to a pointer");
301520a422bSEnrico Granata   if (pointee.IsVoidType())
302520a422bSEnrico Granata     return Error("as it refers to a pointer to void");
303520a422bSEnrico Granata   return Error();
304520a422bSEnrico Granata }
305520a422bSEnrico Granata 
306b9c1b51eSKate Stone bool CommandObjectExpression::EvaluateExpression(const char *expr,
3076e8dc334SCaroline Tice                                                  Stream *output_stream,
3086e8dc334SCaroline Tice                                                  Stream *error_stream,
309b9c1b51eSKate Stone                                                  CommandReturnObject *result) {
310ba7b8e2cSGreg Clayton   // Don't use m_exe_ctx as this might be called asynchronously
311ba7b8e2cSGreg Clayton   // after the command object DoExecute has finished when doing
312ba7b8e2cSGreg Clayton   // multi-line expression that use an input reader...
313ba7b8e2cSGreg Clayton   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
314ba7b8e2cSGreg Clayton 
315ba7b8e2cSGreg Clayton   Target *target = exe_ctx.GetTargetPtr();
316c0a6e061SSean Callanan 
317c0a6e061SSean Callanan   if (!target)
318893c932aSJim Ingham     target = GetDummyTarget();
319c0a6e061SSean Callanan 
320b9c1b51eSKate Stone   if (target) {
3218b2fe6dcSGreg Clayton     lldb::ValueObjectSP result_valobj_sp;
32292adcac9SSean Callanan     bool keep_in_memory = true;
323009d110dSDawn Perchik     StackFrame *frame = exe_ctx.GetFramePtr();
32492adcac9SSean Callanan 
32535e1bda6SJim Ingham     EvaluateExpressionOptions options;
3266fbc48bcSJim Ingham     options.SetCoerceToId(m_varobj_options.use_objc);
3276fbc48bcSJim Ingham     options.SetUnwindOnError(m_command_options.unwind_on_error);
3286fbc48bcSJim Ingham     options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
3296fbc48bcSJim Ingham     options.SetKeepInMemory(keep_in_memory);
3306fbc48bcSJim Ingham     options.SetUseDynamic(m_varobj_options.use_dynamic);
3316fbc48bcSJim Ingham     options.SetTryAllThreads(m_command_options.try_all_threads);
3326fbc48bcSJim Ingham     options.SetDebug(m_command_options.debug);
33315663c53SDawn Perchik     options.SetLanguage(m_command_options.language);
334b9c1b51eSKate Stone     options.SetExecutionPolicy(
335b9c1b51eSKate Stone         m_command_options.allow_jit
336b9c1b51eSKate Stone             ? EvaluateExpressionOptions::default_execution_policy
337b9c1b51eSKate Stone             : lldb_private::eExecutionPolicyNever);
33815663c53SDawn Perchik 
339a1e541bfSJim Ingham     bool auto_apply_fixits;
340a1e541bfSJim Ingham     if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
341a1e541bfSJim Ingham       auto_apply_fixits = target->GetEnableAutoApplyFixIts();
342a1e541bfSJim Ingham     else
343b9c1b51eSKate Stone       auto_apply_fixits =
344b9c1b51eSKate Stone           m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false;
345a1e541bfSJim Ingham 
346a1e541bfSJim Ingham     options.SetAutoApplyFixIts(auto_apply_fixits);
347a1e541bfSJim Ingham 
348863fab69SSean Callanan     if (m_command_options.top_level)
349863fab69SSean Callanan       options.SetExecutionPolicy(eExecutionPolicyTopLevel);
350863fab69SSean Callanan 
35123f8c95aSGreg Clayton     // If there is any chance we are going to stop and want to see
35223f8c95aSGreg Clayton     // what went wrong with our expression, we should generate debug info
35323f8c95aSGreg Clayton     if (!m_command_options.ignore_breakpoints ||
35423f8c95aSGreg Clayton         !m_command_options.unwind_on_error)
35523f8c95aSGreg Clayton       options.SetGenerateDebugInfo(true);
35623f8c95aSGreg Clayton 
35762afb9f6SGreg Clayton     if (m_command_options.timeout > 0)
35862afb9f6SGreg Clayton       options.SetTimeoutUsec(m_command_options.timeout);
3596f78f386SJim Ingham     else
3606f78f386SJim Ingham       options.SetTimeoutUsec(0);
361d4439aa9SEnrico Granata 
362b9c1b51eSKate Stone     ExpressionResults success = target->EvaluateExpression(
363b9c1b51eSKate Stone         expr, frame, result_valobj_sp, options, &m_fixed_expression);
364e5ee6f04SJim Ingham 
365b9c1b51eSKate Stone     // We only tell you about the FixIt if we applied it.  The compiler errors
366b9c1b51eSKate Stone     // will suggest the FixIt if it parsed.
367b9c1b51eSKate Stone     if (error_stream && !m_fixed_expression.empty() &&
368b9c1b51eSKate Stone         target->GetEnableNotifyAboutFixIts()) {
369e5ee6f04SJim Ingham       if (success == eExpressionCompleted)
370b9c1b51eSKate Stone         error_stream->Printf(
371b9c1b51eSKate Stone             "  Fix-it applied, fixed expression was: \n    %s\n",
372b9c1b51eSKate Stone             m_fixed_expression.c_str());
373e5ee6f04SJim Ingham     }
3748b2fe6dcSGreg Clayton 
375b9c1b51eSKate Stone     if (result_valobj_sp) {
376bf154daeSSean Callanan       Format format = m_format_options.GetFormat();
377bf154daeSSean Callanan 
378b9c1b51eSKate Stone       if (result_valobj_sp->GetError().Success()) {
379b9c1b51eSKate Stone         if (format != eFormatVoid) {
3801deb7962SGreg Clayton           if (format != eFormatDefault)
3811deb7962SGreg Clayton             result_valobj_sp->SetFormat(format);
38232c4085bSGreg Clayton 
383b9c1b51eSKate Stone           if (m_varobj_options.elem_count > 0) {
384520a422bSEnrico Granata             Error error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
385b9c1b51eSKate Stone             if (error.Fail()) {
386b9c1b51eSKate Stone               result->AppendErrorWithFormat(
387b9c1b51eSKate Stone                   "expression cannot be used with --element-count %s\n",
388b9c1b51eSKate Stone                   error.AsCString(""));
389520a422bSEnrico Granata               result->SetStatus(eReturnStatusFailed);
390520a422bSEnrico Granata               return false;
391520a422bSEnrico Granata             }
392520a422bSEnrico Granata           }
393520a422bSEnrico Granata 
394b9c1b51eSKate Stone           DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
395b9c1b51eSKate Stone               m_command_options.m_verbosity, format));
396b9c1b51eSKate Stone           options.SetVariableFormatDisplayLanguage(
397b9c1b51eSKate Stone               result_valobj_sp->GetPreferredDisplayLanguage());
398770eb05aSEnrico Granata 
3994d93b8cdSEnrico Granata           result_valobj_sp->Dump(*output_stream, options);
4004d93b8cdSEnrico Granata 
401fcd43b71SJohnny Chen           if (result)
402fcd43b71SJohnny Chen             result->SetStatus(eReturnStatusSuccessFinishResult);
40330fdc8d8SChris Lattner         }
404b9c1b51eSKate Stone       } else {
405b9c1b51eSKate Stone         if (result_valobj_sp->GetError().GetError() ==
406b9c1b51eSKate Stone             UserExpression::kNoResult) {
407b9c1b51eSKate Stone           if (format != eFormatVoid &&
408b9c1b51eSKate Stone               m_interpreter.GetDebugger().GetNotifyVoid()) {
409bcf897faSSean Callanan             error_stream->PutCString("(void)\n");
410bcf897faSSean Callanan           }
411bccce813SSean Callanan 
412bccce813SSean Callanan           if (result)
413bccce813SSean Callanan             result->SetStatus(eReturnStatusSuccessFinishResult);
414b9c1b51eSKate Stone         } else {
4155fd05903SGreg Clayton           const char *error_cstr = result_valobj_sp->GetError().AsCString();
416b9c1b51eSKate Stone           if (error_cstr && error_cstr[0]) {
417c7bece56SGreg Clayton             const size_t error_cstr_len = strlen(error_cstr);
418b9c1b51eSKate Stone             const bool ends_with_newline =
419b9c1b51eSKate Stone                 error_cstr[error_cstr_len - 1] == '\n';
4205fd05903SGreg Clayton             if (strstr(error_cstr, "error:") != error_cstr)
4215fd05903SGreg Clayton               error_stream->PutCString("error: ");
4225fd05903SGreg Clayton             error_stream->Write(error_cstr, error_cstr_len);
4235fd05903SGreg Clayton             if (!ends_with_newline)
4245fd05903SGreg Clayton               error_stream->EOL();
425b9c1b51eSKate Stone           } else {
4265fd05903SGreg Clayton             error_stream->PutCString("error: unknown error\n");
4275fd05903SGreg Clayton           }
4285fd05903SGreg Clayton 
429fcd43b71SJohnny Chen           if (result)
430b71f3844SGreg Clayton             result->SetStatus(eReturnStatusFailed);
43130fdc8d8SChris Lattner         }
4328b2fe6dcSGreg Clayton       }
4338b2fe6dcSGreg Clayton     }
434b9c1b51eSKate Stone   } else {
4356e8dc334SCaroline Tice     error_stream->Printf("error: invalid execution context for expression\n");
4368b2fe6dcSGreg Clayton     return false;
4378b2fe6dcSGreg Clayton   }
43830fdc8d8SChris Lattner 
43916ad5faeSSean Callanan   return true;
44030fdc8d8SChris Lattner }
44130fdc8d8SChris Lattner 
442b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
443b9c1b51eSKate Stone                                                      std::string &line) {
44444d93782SGreg Clayton   io_handler.SetIsDone(true);
445b9c1b51eSKate Stone   //    StreamSP output_stream =
446b9c1b51eSKate Stone   //    io_handler.GetDebugger().GetAsyncOutputStream();
44744d93782SGreg Clayton   //    StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
44844d93782SGreg Clayton   StreamFileSP output_sp(io_handler.GetOutputStreamFile());
44944d93782SGreg Clayton   StreamFileSP error_sp(io_handler.GetErrorStreamFile());
45044d93782SGreg Clayton 
451b9c1b51eSKate Stone   EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
45244d93782SGreg Clayton   if (output_sp)
45344d93782SGreg Clayton     output_sp->Flush();
45444d93782SGreg Clayton   if (error_sp)
45544d93782SGreg Clayton     error_sp->Flush();
45644d93782SGreg Clayton }
45744d93782SGreg Clayton 
458b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
459b9c1b51eSKate Stone                                                        StringList &lines) {
460f52c40c5SSean Callanan   // An empty lines is used to indicate the end of input
461f52c40c5SSean Callanan   const size_t num_lines = lines.GetSize();
462b9c1b51eSKate Stone   if (num_lines > 0 && lines[num_lines - 1].empty()) {
463f52c40c5SSean Callanan     // Remove the last empty line from "lines" so it doesn't appear
464f52c40c5SSean Callanan     // in our resulting input and return true to indicate we are done
465f52c40c5SSean Callanan     // getting lines
46644d93782SGreg Clayton     lines.PopBack();
467f52c40c5SSean Callanan     return true;
46844d93782SGreg Clayton   }
469f52c40c5SSean Callanan   return false;
47044d93782SGreg Clayton }
47144d93782SGreg Clayton 
472b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() {
47330fdc8d8SChris Lattner   m_expr_lines.clear();
47430fdc8d8SChris Lattner   m_expr_line_count = 0;
47530fdc8d8SChris Lattner 
47644d93782SGreg Clayton   Debugger &debugger = GetCommandInterpreter().GetDebugger();
477e30f11d9SKate Stone   bool color_prompt = debugger.GetUseColor();
47844d93782SGreg Clayton   const bool multiple_lines = true; // Get multiple lines
479b9c1b51eSKate Stone   IOHandlerSP io_handler_sp(
480b9c1b51eSKate Stone       new IOHandlerEditline(debugger, IOHandler::Type::Expression,
48144d93782SGreg Clayton                             "lldb-expr", // Name of input reader for history
482c8ecc2a9SEugene Zelenko                             nullptr,     // No prompt
483c8ecc2a9SEugene Zelenko                             nullptr,     // Continuation prompt
484b9c1b51eSKate Stone                             multiple_lines, color_prompt,
485f6913cd7SGreg Clayton                             1, // Show line numbers starting at 1
48644d93782SGreg Clayton                             *this));
487b6892508SGreg Clayton 
488b6892508SGreg Clayton   StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
489b9c1b51eSKate Stone   if (output_sp) {
490b9c1b51eSKate Stone     output_sp->PutCString(
491b9c1b51eSKate Stone         "Enter expressions, then terminate with an empty line to evaluate:\n");
492b6892508SGreg Clayton     output_sp->Flush();
493b6892508SGreg Clayton   }
49444d93782SGreg Clayton   debugger.PushIOHandler(io_handler_sp);
495cf28a8b7SGreg Clayton }
496cf28a8b7SGreg Clayton 
497b9c1b51eSKate Stone bool CommandObjectExpression::DoExecute(const char *command,
498b9c1b51eSKate Stone                                         CommandReturnObject &result) {
499e5ee6f04SJim Ingham   m_fixed_expression.clear();
500e1cfbc79STodd Fiala   auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
501e1cfbc79STodd Fiala   m_option_group.NotifyOptionParsingStarting(&exe_ctx);
502cf28a8b7SGreg Clayton 
503c8ecc2a9SEugene Zelenko   const char *expr = nullptr;
504cf28a8b7SGreg Clayton 
505b9c1b51eSKate Stone   if (command[0] == '\0') {
506cf28a8b7SGreg Clayton     GetMultilineExpression();
50730fdc8d8SChris Lattner     return result.Succeeded();
50830fdc8d8SChris Lattner   }
50930fdc8d8SChris Lattner 
510b9c1b51eSKate Stone   if (command[0] == '-') {
51130fdc8d8SChris Lattner     // We have some options and these options MUST end with --.
512c8ecc2a9SEugene Zelenko     const char *end_options = nullptr;
51330fdc8d8SChris Lattner     const char *s = command;
514b9c1b51eSKate Stone     while (s && s[0]) {
51530fdc8d8SChris Lattner       end_options = ::strstr(s, "--");
516b9c1b51eSKate Stone       if (end_options) {
51730fdc8d8SChris Lattner         end_options += 2; // Get past the "--"
518b9c1b51eSKate Stone         if (::isspace(end_options[0])) {
51930fdc8d8SChris Lattner           expr = end_options;
52030fdc8d8SChris Lattner           while (::isspace(*expr))
52130fdc8d8SChris Lattner             ++expr;
52230fdc8d8SChris Lattner           break;
52330fdc8d8SChris Lattner         }
52430fdc8d8SChris Lattner       }
52530fdc8d8SChris Lattner       s = end_options;
52630fdc8d8SChris Lattner     }
52730fdc8d8SChris Lattner 
528b9c1b51eSKate Stone     if (end_options) {
52900b7f95bSPavel Labath       Args args(llvm::StringRef(command, end_options - command));
530a7015092SGreg Clayton       if (!ParseOptions(args, result))
53130fdc8d8SChris Lattner         return false;
532f6b8b581SGreg Clayton 
533e1cfbc79STodd Fiala       Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx));
534b9c1b51eSKate Stone       if (error.Fail()) {
535f6b8b581SGreg Clayton         result.AppendError(error.AsCString());
536f6b8b581SGreg Clayton         result.SetStatus(eReturnStatusFailed);
537f6b8b581SGreg Clayton         return false;
538f6b8b581SGreg Clayton       }
539cf28a8b7SGreg Clayton 
540b9c1b51eSKate Stone       if (m_repl_option.GetOptionValue().GetCurrentValue()) {
541f2bd5c3eSSean Callanan         Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
542b9c1b51eSKate Stone         if (target) {
543f2bd5c3eSSean Callanan           // Drop into REPL
544f2bd5c3eSSean Callanan           m_expr_lines.clear();
545f2bd5c3eSSean Callanan           m_expr_line_count = 0;
546f2bd5c3eSSean Callanan 
547f2bd5c3eSSean Callanan           Debugger &debugger = target->GetDebugger();
548f2bd5c3eSSean Callanan 
549b9c1b51eSKate Stone           // Check if the LLDB command interpreter is sitting on top of a REPL
550b9c1b51eSKate Stone           // that
551f2bd5c3eSSean Callanan           // launched it...
552b9c1b51eSKate Stone           if (debugger.CheckTopIOHandlerTypes(
553b9c1b51eSKate Stone                   IOHandler::Type::CommandInterpreter, IOHandler::Type::REPL)) {
554b9c1b51eSKate Stone             // the LLDB command interpreter is sitting on top of a REPL that
555b9c1b51eSKate Stone             // launched it,
556b9c1b51eSKate Stone             // so just say the command interpreter is done and fall back to the
557b9c1b51eSKate Stone             // existing REPL
558f2bd5c3eSSean Callanan             m_interpreter.GetIOHandler(false)->SetIsDone(true);
559b9c1b51eSKate Stone           } else {
560b9c1b51eSKate Stone             // We are launching the REPL on top of the current LLDB command
561b9c1b51eSKate Stone             // interpreter,
562f2bd5c3eSSean Callanan             // so just push one
563f2bd5c3eSSean Callanan             bool initialize = false;
564f2bd5c3eSSean Callanan             Error repl_error;
565b9c1b51eSKate Stone             REPLSP repl_sp(target->GetREPL(
566b9c1b51eSKate Stone                 repl_error, m_command_options.language, nullptr, false));
567f2bd5c3eSSean Callanan 
568b9c1b51eSKate Stone             if (!repl_sp) {
569f2bd5c3eSSean Callanan               initialize = true;
570b9c1b51eSKate Stone               repl_sp = target->GetREPL(repl_error, m_command_options.language,
571b9c1b51eSKate Stone                                         nullptr, true);
572b9c1b51eSKate Stone               if (!repl_error.Success()) {
573f2bd5c3eSSean Callanan                 result.SetError(repl_error);
574f2bd5c3eSSean Callanan                 return result.Succeeded();
575f2bd5c3eSSean Callanan               }
576f2bd5c3eSSean Callanan             }
577f2bd5c3eSSean Callanan 
578b9c1b51eSKate Stone             if (repl_sp) {
579b9c1b51eSKate Stone               if (initialize) {
580f2bd5c3eSSean Callanan                 repl_sp->SetCommandOptions(m_command_options);
581f2bd5c3eSSean Callanan                 repl_sp->SetFormatOptions(m_format_options);
582f2bd5c3eSSean Callanan                 repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
583f2bd5c3eSSean Callanan               }
584f2bd5c3eSSean Callanan 
585f2bd5c3eSSean Callanan               IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
586f2bd5c3eSSean Callanan 
587f2bd5c3eSSean Callanan               io_handler_sp->SetIsDone(false);
588f2bd5c3eSSean Callanan 
589f2bd5c3eSSean Callanan               debugger.PushIOHandler(io_handler_sp);
590b9c1b51eSKate Stone             } else {
591b9c1b51eSKate Stone               repl_error.SetErrorStringWithFormat(
592b9c1b51eSKate Stone                   "Couldn't create a REPL for %s",
593b9c1b51eSKate Stone                   Language::GetNameForLanguageType(m_command_options.language));
594f2bd5c3eSSean Callanan               result.SetError(repl_error);
595f2bd5c3eSSean Callanan               return result.Succeeded();
596f2bd5c3eSSean Callanan             }
597f2bd5c3eSSean Callanan           }
598f2bd5c3eSSean Callanan         }
599f2bd5c3eSSean Callanan       }
600cf28a8b7SGreg Clayton       // No expression following options
601b9c1b51eSKate Stone       else if (expr == nullptr || expr[0] == '\0') {
602cf28a8b7SGreg Clayton         GetMultilineExpression();
603cf28a8b7SGreg Clayton         return result.Succeeded();
604cf28a8b7SGreg Clayton       }
60530fdc8d8SChris Lattner     }
60630fdc8d8SChris Lattner   }
60730fdc8d8SChris Lattner 
608c8ecc2a9SEugene Zelenko   if (expr == nullptr)
60930fdc8d8SChris Lattner     expr = command;
61030fdc8d8SChris Lattner 
611b9c1b51eSKate Stone   if (EvaluateExpression(expr, &(result.GetOutputStream()),
612b9c1b51eSKate Stone                          &(result.GetErrorStream()), &result)) {
613e5ee6f04SJim Ingham     Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
614b9c1b51eSKate Stone     if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) {
615e5ee6f04SJim Ingham       CommandHistory &history = m_interpreter.GetCommandHistory();
616b9c1b51eSKate Stone       // FIXME: Can we figure out what the user actually typed (e.g. some alias
617b9c1b51eSKate Stone       // for expr???)
618e5ee6f04SJim Ingham       // If we can it would be nice to show that.
619e5ee6f04SJim Ingham       std::string fixed_command("expression ");
620e5ee6f04SJim Ingham       if (expr == command)
621e5ee6f04SJim Ingham         fixed_command.append(m_fixed_expression);
622b9c1b51eSKate Stone       else {
623e5ee6f04SJim Ingham         // Add in any options that might have been in the original command:
624e5ee6f04SJim Ingham         fixed_command.append(command, expr - command);
625e5ee6f04SJim Ingham         fixed_command.append(m_fixed_expression);
626e5ee6f04SJim Ingham       }
627e5ee6f04SJim Ingham       history.AppendString(fixed_command);
628e5ee6f04SJim Ingham     }
629fcd43b71SJohnny Chen     return true;
630e5ee6f04SJim Ingham   }
631fcd43b71SJohnny Chen 
632fcd43b71SJohnny Chen   result.SetStatus(eReturnStatusFailed);
633fcd43b71SJohnny Chen   return false;
63430fdc8d8SChris Lattner }
635