blob: b2b1ed3ec3c5c12302c2e0490e465a6e3c807743 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
Eugene Zelenkoc8ecc2a2016-02-19 19:33:46 +000013#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016// Project includes
Eugene Zelenkoc8ecc2a2016-02-19 19:33:46 +000017#include "CommandObjectExpression.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h"
19#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Value.h"
Jim Ingham6c68fb42010-09-30 00:54:27 +000021#include "lldb/Core/ValueObjectVariable.h"
Enrico Granata4d93b8c2013-09-30 19:11:51 +000022#include "lldb/DataFormatters/ValueObjectPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Expression/DWARFExpression.h"
Sean Callananf2bd5c32015-10-20 00:55:21 +000024#include "lldb/Expression/REPL.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000025#include "lldb/Expression/UserExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000027#include "lldb/Host/StringConvert.h"
Greg Clayton66111032010-06-23 01:19:29 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Interpreter/CommandReturnObject.h"
30#include "lldb/Symbol/ObjectFile.h"
31#include "lldb/Symbol/Variable.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000032#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000034#include "lldb/Target/StackFrame.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
Greg Clayton7260f622011-04-18 08:33:37 +000036#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037
38using namespace lldb;
39using namespace lldb_private;
40
Kate Stoneb9c1b512016-09-06 20:57:50 +000041CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Eugene Zelenkoc8ecc2a2016-02-19 19:33:46 +000043CommandObjectExpression::CommandOptions::~CommandOptions() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Kate Stoneb9c1b512016-09-06 20:57:50 +000045static OptionEnumValueElement g_description_verbosity_type[] = {
46 {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact",
47 "Only show the description string"},
48 {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full",
49 "Show the full output, including persistent variable's name and type"},
50 {0, nullptr, nullptr}};
Enrico Granata4d93b8c2013-09-30 19:11:51 +000051
Zachary Turner1f0f5b52016-09-22 20:22:55 +000052static OptionDefinition g_expression_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000053 // clang-format off
Kate Stoneac9c3a62016-08-26 23:28:47 +000054 {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."},
55 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"},
56 {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."},
57 {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. "
58 "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
59 {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 "
60 "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
61 {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 "
62 "setting is used." },
63 {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." },
64 {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."},
65 {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 "
66 "executed."},
67 {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 "
68 "the interpreter (defaults to true)."}
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 // clang-format on
Greg Clayton1deb7962011-10-25 06:44:01 +000070};
71
Kate Stoneb9c1b512016-09-06 20:57:50 +000072Error CommandObjectExpression::CommandOptions::SetOptionValue(
73 uint32_t option_idx, const char *option_arg,
74 ExecutionContext *execution_context) {
75 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076
Zachary Turnerecbb0bb2016-09-19 17:54:06 +000077 auto option_strref = llvm::StringRef::withNullAsEmpty(option_arg);
Zachary Turner1f0f5b52016-09-22 20:22:55 +000078 const int short_option = GetDefinitions()[option_idx].short_option;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 switch (short_option) {
81 case 'l':
82 language = Language::GetLanguageTypeFromString(option_arg);
83 if (language == eLanguageTypeUnknown)
84 error.SetErrorStringWithFormat(
85 "unknown language type: '%s' for expression", option_arg);
86 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 case 'a': {
89 bool success;
90 bool result;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +000091 result = Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 if (!success)
93 error.SetErrorStringWithFormat(
94 "invalid all-threads value setting: \"%s\"", option_arg);
Jim Ingham184e9812013-01-15 02:47:48 +000095 else
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 try_all_threads = result;
97 } break;
98
99 case 'i': {
100 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000101 bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (success)
103 ignore_breakpoints = tmp_value;
104 else
105 error.SetErrorStringWithFormat(
106 "could not convert \"%s\" to a boolean value.", option_arg);
107 break;
108 }
109
110 case 'j': {
111 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000112 bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 if (success)
114 allow_jit = tmp_value;
115 else
116 error.SetErrorStringWithFormat(
117 "could not convert \"%s\" to a boolean value.", option_arg);
118 break;
119 }
120
121 case 't': {
122 bool success;
123 uint32_t result;
124 result = StringConvert::ToUInt32(option_arg, 0, 0, &success);
125 if (success)
126 timeout = result;
127 else
128 error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
129 option_arg);
130 } break;
131
132 case 'u': {
133 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000134 bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 if (success)
136 unwind_on_error = tmp_value;
137 else
138 error.SetErrorStringWithFormat(
139 "could not convert \"%s\" to a boolean value.", option_arg);
140 break;
141 }
142
143 case 'v':
144 if (!option_arg) {
145 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
146 break;
Jim Ingham184e9812013-01-15 02:47:48 +0000147 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 m_verbosity =
149 (LanguageRuntimeDescriptionDisplayVerbosity)Args::StringToOptionEnum(
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000150 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 if (!error.Success())
152 error.SetErrorStringWithFormat(
153 "unrecognized value for description-verbosity '%s'", option_arg);
154 break;
155
156 case 'g':
157 debug = true;
158 unwind_on_error = false;
159 ignore_breakpoints = false;
160 break;
161
162 case 'p':
163 top_level = true;
164 break;
165
166 case 'X': {
167 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000168 bool tmp_value = Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169 if (success)
170 auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
171 else
172 error.SetErrorStringWithFormat(
173 "could not convert \"%s\" to a boolean value.", option_arg);
174 break;
175 }
176
177 default:
178 error.SetErrorStringWithFormat("invalid short option character '%c'",
179 short_option);
180 break;
181 }
182
183 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186void CommandObjectExpression::CommandOptions::OptionParsingStarting(
187 ExecutionContext *execution_context) {
188 auto process_sp =
189 execution_context ? execution_context->GetProcessSP() : ProcessSP();
190 if (process_sp) {
191 ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
192 unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
193 } else {
194 ignore_breakpoints = true;
195 unwind_on_error = true;
196 }
197
198 show_summary = true;
199 try_all_threads = true;
200 timeout = 0;
201 debug = false;
202 language = eLanguageTypeUnknown;
203 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
204 auto_apply_fixits = eLazyBoolCalculate;
205 top_level = false;
206 allow_jit = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207}
208
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000209llvm::ArrayRef<OptionDefinition>
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210CommandObjectExpression::CommandOptions::GetDefinitions() {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000211 return g_expression_options;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212}
213
214CommandObjectExpression::CommandObjectExpression(
215 CommandInterpreter &interpreter)
Kate Stone7428a182016-07-14 22:03:10 +0000216 : CommandObjectRaw(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 interpreter, "expression", "Evaluate an expression on the current "
218 "thread. Displays any returned value "
219 "with LLDB's default formatting.",
Kate Stone7428a182016-07-14 22:03:10 +0000220 nullptr, eCommandProcessMustBePaused | eCommandTryTargetAPILock),
221 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 m_option_group(), m_format_options(eFormatDefault),
223 m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
224 true),
225 m_command_options(), m_expr_line_count(0), m_expr_lines() {
226 SetHelpLong(
227 R"(
Kate Stoneea671fb2015-07-14 05:48:36 +0000228Timeouts:
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230)"
231 " If the expression can be evaluated statically (without running code) then it will be. \
Kate Stoneea671fb2015-07-14 05:48:36 +0000232Otherwise, by default the expression will run on the current thread with a short timeout: \
233currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
234and resumed with all threads running. You can use the -a option to disable retrying on all \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235threads. You can use the -t option to set a shorter timeout."
236 R"(
Kate Stoneea671fb2015-07-14 05:48:36 +0000237
238User defined variables:
239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240)"
241 " You can define your own variables for convenience or to be used in subsequent expressions. \
Kate Stoneea671fb2015-07-14 05:48:36 +0000242You define them the same way you would define variables in C. If the first character of \
243your user defined variable is a $, then the variable's value will be available in future \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244expressions, otherwise it will just be available in the current expression."
245 R"(
Kate Stoneea671fb2015-07-14 05:48:36 +0000246
247Continuing evaluation after a breakpoint:
248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249)"
250 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
Kate Stoneea671fb2015-07-14 05:48:36 +0000251you are done with your investigation, you can either remove the expression execution frames \
252from the stack with \"thread return -x\" or if you are still interested in the expression result \
253you can issue the \"continue\" command and the expression evaluation will complete and the \
254expression result will be available using the \"thread.completed-expression\" key in the thread \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255format."
256 R"(
Kate Stoneea671fb2015-07-14 05:48:36 +0000257
258Examples:
259
260 expr my_struct->a = my_array[3]
261 expr -f bin -- (index * 8) + 5
262 expr unsigned int $foo = 5
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 expr char c[] = \"foo\"; c[0])");
Caroline Tice405fe672010-10-04 22:28:36 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 CommandArgumentEntry arg;
266 CommandArgumentData expression_arg;
Caroline Tice405fe672010-10-04 22:28:36 +0000267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 // Define the first (and only) variant of this arg.
269 expression_arg.arg_type = eArgTypeExpression;
270 expression_arg.arg_repetition = eArgRepeatPlain;
Caroline Tice405fe672010-10-04 22:28:36 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // There is only one variant this argument could be; put it into the argument
273 // entry.
274 arg.push_back(expression_arg);
Caroline Tice405fe672010-10-04 22:28:36 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 // Push the data for the first argument into the m_arguments vector.
277 m_arguments.push_back(arg);
278
279 // Add the "--format" and "--gdb-format"
280 m_option_group.Append(&m_format_options,
281 OptionGroupFormat::OPTION_GROUP_FORMAT |
282 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
283 LLDB_OPT_SET_1);
284 m_option_group.Append(&m_command_options);
285 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
286 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
287 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
288 m_option_group.Finalize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289}
290
Eugene Zelenkoc8ecc2a2016-02-19 19:33:46 +0000291CommandObjectExpression::~CommandObjectExpression() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294
Enrico Granata520a4222016-04-25 00:52:47 +0000295static lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296CanBeUsedForElementCountPrinting(ValueObject &valobj) {
297 CompilerType type(valobj.GetCompilerType());
298 CompilerType pointee;
299 if (!type.IsPointerType(&pointee))
300 return Error("as it does not refer to a pointer");
301 if (pointee.IsVoidType())
302 return Error("as it refers to a pointer to void");
303 return Error();
Enrico Granata520a4222016-04-25 00:52:47 +0000304}
305
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306bool CommandObjectExpression::EvaluateExpression(const char *expr,
307 Stream *output_stream,
308 Stream *error_stream,
309 CommandReturnObject *result) {
310 // Don't use m_exe_ctx as this might be called asynchronously
311 // after the command object DoExecute has finished when doing
312 // multi-line expression that use an input reader...
313 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
Greg Claytonba7b8e22013-01-26 23:54:29 +0000314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315 Target *target = exe_ctx.GetTargetPtr();
Enrico Granatab576bba2013-01-09 20:12:53 +0000316
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 if (!target)
318 target = GetDummyTarget();
Dawn Perchik15663c52015-07-25 00:19:39 +0000319
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 if (target) {
321 lldb::ValueObjectSP result_valobj_sp;
322 bool keep_in_memory = true;
323 StackFrame *frame = exe_ctx.GetFramePtr();
Arnaud A. de Grandmaison62e5f4d2014-03-22 20:23:26 +0000324
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 EvaluateExpressionOptions options;
326 options.SetCoerceToId(m_varobj_options.use_objc);
327 options.SetUnwindOnError(m_command_options.unwind_on_error);
328 options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
329 options.SetKeepInMemory(keep_in_memory);
330 options.SetUseDynamic(m_varobj_options.use_dynamic);
331 options.SetTryAllThreads(m_command_options.try_all_threads);
332 options.SetDebug(m_command_options.debug);
333 options.SetLanguage(m_command_options.language);
334 options.SetExecutionPolicy(
335 m_command_options.allow_jit
336 ? EvaluateExpressionOptions::default_execution_policy
337 : lldb_private::eExecutionPolicyNever);
Sean Callanan4b388c92013-07-30 19:54:09 +0000338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 bool auto_apply_fixits;
340 if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
341 auto_apply_fixits = target->GetEnableAutoApplyFixIts();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +0000342 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 auto_apply_fixits =
344 m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false;
345
346 options.SetAutoApplyFixIts(auto_apply_fixits);
347
348 if (m_command_options.top_level)
349 options.SetExecutionPolicy(eExecutionPolicyTopLevel);
350
351 // If there is any chance we are going to stop and want to see
352 // what went wrong with our expression, we should generate debug info
353 if (!m_command_options.ignore_breakpoints ||
354 !m_command_options.unwind_on_error)
355 options.SetGenerateDebugInfo(true);
356
357 if (m_command_options.timeout > 0)
358 options.SetTimeoutUsec(m_command_options.timeout);
359 else
360 options.SetTimeoutUsec(0);
361
362 ExpressionResults success = target->EvaluateExpression(
363 expr, frame, result_valobj_sp, options, &m_fixed_expression);
364
365 // We only tell you about the FixIt if we applied it. The compiler errors
366 // will suggest the FixIt if it parsed.
367 if (error_stream && !m_fixed_expression.empty() &&
368 target->GetEnableNotifyAboutFixIts()) {
369 if (success == eExpressionCompleted)
370 error_stream->Printf(
371 " Fix-it applied, fixed expression was: \n %s\n",
372 m_fixed_expression.c_str());
Sean Callananebf77072010-07-23 00:16:21 +0000373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374
375 if (result_valobj_sp) {
376 Format format = m_format_options.GetFormat();
377
378 if (result_valobj_sp->GetError().Success()) {
379 if (format != eFormatVoid) {
380 if (format != eFormatDefault)
381 result_valobj_sp->SetFormat(format);
382
383 if (m_varobj_options.elem_count > 0) {
384 Error error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
385 if (error.Fail()) {
386 result->AppendErrorWithFormat(
387 "expression cannot be used with --element-count %s\n",
388 error.AsCString(""));
389 result->SetStatus(eReturnStatusFailed);
390 return false;
391 }
392 }
393
394 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
395 m_command_options.m_verbosity, format));
396 options.SetVariableFormatDisplayLanguage(
397 result_valobj_sp->GetPreferredDisplayLanguage());
398
399 result_valobj_sp->Dump(*output_stream, options);
400
401 if (result)
402 result->SetStatus(eReturnStatusSuccessFinishResult);
403 }
404 } else {
405 if (result_valobj_sp->GetError().GetError() ==
406 UserExpression::kNoResult) {
407 if (format != eFormatVoid &&
408 m_interpreter.GetDebugger().GetNotifyVoid()) {
409 error_stream->PutCString("(void)\n");
410 }
411
412 if (result)
413 result->SetStatus(eReturnStatusSuccessFinishResult);
414 } else {
415 const char *error_cstr = result_valobj_sp->GetError().AsCString();
416 if (error_cstr && error_cstr[0]) {
417 const size_t error_cstr_len = strlen(error_cstr);
418 const bool ends_with_newline =
419 error_cstr[error_cstr_len - 1] == '\n';
420 if (strstr(error_cstr, "error:") != error_cstr)
421 error_stream->PutCString("error: ");
422 error_stream->Write(error_cstr, error_cstr_len);
423 if (!ends_with_newline)
424 error_stream->EOL();
425 } else {
426 error_stream->PutCString("error: unknown error\n");
427 }
428
429 if (result)
430 result->SetStatus(eReturnStatusFailed);
431 }
432 }
433 }
434 } else {
435 error_stream->Printf("error: invalid execution context for expression\n");
436 return false;
437 }
438
439 return true;
440}
441
442void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
443 std::string &line) {
444 io_handler.SetIsDone(true);
445 // StreamSP output_stream =
446 // io_handler.GetDebugger().GetAsyncOutputStream();
447 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
448 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
449 StreamFileSP error_sp(io_handler.GetErrorStreamFile());
450
451 EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
452 if (output_sp)
453 output_sp->Flush();
454 if (error_sp)
455 error_sp->Flush();
456}
457
458bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
459 StringList &lines) {
460 // An empty lines is used to indicate the end of input
461 const size_t num_lines = lines.GetSize();
462 if (num_lines > 0 && lines[num_lines - 1].empty()) {
463 // Remove the last empty line from "lines" so it doesn't appear
464 // in our resulting input and return true to indicate we are done
465 // getting lines
466 lines.PopBack();
Sean Callananebf77072010-07-23 00:16:21 +0000467 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 }
469 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000470}
471
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472void CommandObjectExpression::GetMultilineExpression() {
473 m_expr_lines.clear();
474 m_expr_line_count = 0;
Greg Clayton44d93782014-01-27 23:43:24 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 Debugger &debugger = GetCommandInterpreter().GetDebugger();
477 bool color_prompt = debugger.GetUseColor();
478 const bool multiple_lines = true; // Get multiple lines
479 IOHandlerSP io_handler_sp(
480 new IOHandlerEditline(debugger, IOHandler::Type::Expression,
481 "lldb-expr", // Name of input reader for history
482 nullptr, // No prompt
483 nullptr, // Continuation prompt
484 multiple_lines, color_prompt,
485 1, // Show line numbers starting at 1
486 *this));
487
488 StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
489 if (output_sp) {
490 output_sp->PutCString(
491 "Enter expressions, then terminate with an empty line to evaluate:\n");
492 output_sp->Flush();
493 }
494 debugger.PushIOHandler(io_handler_sp);
Greg Clayton44d93782014-01-27 23:43:24 +0000495}
496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497bool CommandObjectExpression::DoExecute(const char *command,
498 CommandReturnObject &result) {
499 m_fixed_expression.clear();
500 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
501 m_option_group.NotifyOptionParsingStarting(&exe_ctx);
Greg Clayton44d93782014-01-27 23:43:24 +0000502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 const char *expr = nullptr;
Greg Claytoncf28a8b2014-03-13 23:42:30 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 if (command[0] == '\0') {
506 GetMultilineExpression();
507 return result.Succeeded();
508 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000509
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 if (command[0] == '-') {
511 // We have some options and these options MUST end with --.
512 const char *end_options = nullptr;
513 const char *s = command;
514 while (s && s[0]) {
515 end_options = ::strstr(s, "--");
516 if (end_options) {
517 end_options += 2; // Get past the "--"
518 if (::isspace(end_options[0])) {
519 expr = end_options;
520 while (::isspace(*expr))
521 ++expr;
522 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 }
525 s = end_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526 }
527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 if (end_options) {
529 Args args(llvm::StringRef(command, end_options - command));
530 if (!ParseOptions(args, result))
531 return false;
532
533 Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx));
534 if (error.Fail()) {
535 result.AppendError(error.AsCString());
536 result.SetStatus(eReturnStatusFailed);
537 return false;
538 }
539
540 if (m_repl_option.GetOptionValue().GetCurrentValue()) {
Jim Inghame5ee6f02016-03-29 22:00:08 +0000541 Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 if (target) {
543 // Drop into REPL
544 m_expr_lines.clear();
545 m_expr_line_count = 0;
Johnny Chenfcd43b72010-08-13 00:42:30 +0000546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 Debugger &debugger = target->GetDebugger();
548
549 // Check if the LLDB command interpreter is sitting on top of a REPL
550 // that
551 // launched it...
552 if (debugger.CheckTopIOHandlerTypes(
553 IOHandler::Type::CommandInterpreter, IOHandler::Type::REPL)) {
554 // the LLDB command interpreter is sitting on top of a REPL that
555 // launched it,
556 // so just say the command interpreter is done and fall back to the
557 // existing REPL
558 m_interpreter.GetIOHandler(false)->SetIsDone(true);
559 } else {
560 // We are launching the REPL on top of the current LLDB command
561 // interpreter,
562 // so just push one
563 bool initialize = false;
564 Error repl_error;
565 REPLSP repl_sp(target->GetREPL(
566 repl_error, m_command_options.language, nullptr, false));
567
568 if (!repl_sp) {
569 initialize = true;
570 repl_sp = target->GetREPL(repl_error, m_command_options.language,
571 nullptr, true);
572 if (!repl_error.Success()) {
573 result.SetError(repl_error);
574 return result.Succeeded();
575 }
576 }
577
578 if (repl_sp) {
579 if (initialize) {
580 repl_sp->SetCommandOptions(m_command_options);
581 repl_sp->SetFormatOptions(m_format_options);
582 repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
583 }
584
585 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
586
587 io_handler_sp->SetIsDone(false);
588
589 debugger.PushIOHandler(io_handler_sp);
590 } else {
591 repl_error.SetErrorStringWithFormat(
592 "Couldn't create a REPL for %s",
593 Language::GetNameForLanguageType(m_command_options.language));
594 result.SetError(repl_error);
595 return result.Succeeded();
596 }
597 }
598 }
599 }
600 // No expression following options
601 else if (expr == nullptr || expr[0] == '\0') {
602 GetMultilineExpression();
603 return result.Succeeded();
604 }
605 }
606 }
607
608 if (expr == nullptr)
609 expr = command;
610
611 if (EvaluateExpression(expr, &(result.GetOutputStream()),
612 &(result.GetErrorStream()), &result)) {
613 Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
614 if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) {
615 CommandHistory &history = m_interpreter.GetCommandHistory();
616 // FIXME: Can we figure out what the user actually typed (e.g. some alias
617 // for expr???)
618 // If we can it would be nice to show that.
619 std::string fixed_command("expression ");
620 if (expr == command)
621 fixed_command.append(m_fixed_expression);
622 else {
623 // Add in any options that might have been in the original command:
624 fixed_command.append(command, expr - command);
625 fixed_command.append(m_fixed_expression);
626 }
627 history.AppendString(fixed_command);
628 }
629 return true;
630 }
631
632 result.SetStatus(eReturnStatusFailed);
633 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634}