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 //===----------------------------------------------------------------------===//
10 #include "CommandObjectExpression.h"
14 // Other libraries and framework includes
16 #include "lldb/Core/Value.h"
17 #include "lldb/Core/ValueObjectVariable.h"
18 #include "lldb/DataFormatters/ValueObjectPrinter.h"
19 #include "lldb/Expression/ClangExpressionVariable.h"
20 #include "lldb/Expression/ClangUserExpression.h"
21 #include "lldb/Expression/ClangFunction.h"
22 #include "lldb/Expression/DWARFExpression.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Host/StringConvert.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Interpreter/CommandReturnObject.h"
28 #include "lldb/Target/ObjCLanguageRuntime.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Symbol/Variable.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Target/StackFrame.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringRef.h"
39 using namespace lldb_private;
41 CommandObjectExpression::CommandOptions::CommandOptions () :
47 CommandObjectExpression::CommandOptions::~CommandOptions ()
51 static OptionEnumValueElement g_description_verbosity_type[] =
53 { eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", "Only show the description string"},
54 { eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", "Show the full output, including persistent variable's name and type"},
59 CommandObjectExpression::CommandOptions::g_option_table[] =
61 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."},
62 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"},
63 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."},
64 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error", 'u', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, or raises a signal. Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
65 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug", 'g', OptionParser::eNoArgument , NULL, NULL, 0, eArgTypeNone, "When specified, debug the JIT code by setting a breakpoint on the first instruction and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
66 { LLDB_OPT_SET_1, false, "description-verbosity", 'v', OptionParser::eOptionalArgument, NULL, g_description_verbosity_type, 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."},
71 CommandObjectExpression::CommandOptions::GetNumDefinitions ()
73 return llvm::array_lengthof(g_option_table);
77 CommandObjectExpression::CommandOptions::SetOptionValue (CommandInterpreter &interpreter,
79 const char *option_arg)
83 const int short_option = g_option_table[option_idx].short_option;
88 //if (language.SetLanguageFromCString (option_arg) == false)
90 // error.SetErrorStringWithFormat("invalid language option argument '%s'", option_arg);
98 result = Args::StringToBoolean(option_arg, true, &success);
100 error.SetErrorStringWithFormat("invalid all-threads value setting: \"%s\"", option_arg);
102 try_all_threads = result;
109 bool tmp_value = Args::StringToBoolean(option_arg, true, &success);
111 ignore_breakpoints = tmp_value;
113 error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg);
120 result = StringConvert::ToUInt32(option_arg, 0, 0, &success);
124 error.SetErrorStringWithFormat ("invalid timeout setting \"%s\"", option_arg);
131 bool tmp_value = Args::StringToBoolean(option_arg, true, &success);
133 unwind_on_error = tmp_value;
135 error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg);
142 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
145 m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
146 if (!error.Success())
147 error.SetErrorStringWithFormat ("unrecognized value for description-verbosity '%s'", option_arg);
152 unwind_on_error = false;
153 ignore_breakpoints = false;
157 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
165 CommandObjectExpression::CommandOptions::OptionParsingStarting (CommandInterpreter &interpreter)
167 Process *process = interpreter.GetExecutionContext().GetProcessPtr();
170 ignore_breakpoints = process->GetIgnoreBreakpointsInExpressions();
171 unwind_on_error = process->GetUnwindOnErrorInExpressions();
175 ignore_breakpoints = true;
176 unwind_on_error = true;
180 try_all_threads = true;
183 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
186 const OptionDefinition*
187 CommandObjectExpression::CommandOptions::GetDefinitions ()
189 return g_option_table;
192 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) :
193 CommandObjectRaw (interpreter,
195 "Evaluate a C/ObjC/C++ expression in the current program context, using user defined variables and variables currently in scope.",
197 eCommandProcessMustBePaused | eCommandTryTargetAPILock),
198 IOHandlerDelegate (IOHandlerDelegate::Completion::Expression),
199 m_option_group (interpreter),
200 m_format_options (eFormatDefault),
201 m_command_options (),
202 m_expr_line_count (0),
209 )" " If the expression can be evaluated statically (without running code) then it will be. \
210 Otherwise, by default the expression will run on the current thread with a short timeout: \
211 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \
212 and resumed with all threads running. You can use the -a option to disable retrying on all \
213 threads. You can use the -t option to set a shorter timeout." R"(
215 User defined variables:
217 )" " You can define your own variables for convenience or to be used in subsequent expressions. \
218 You define them the same way you would define variables in C. If the first character of \
219 your user defined variable is a $, then the variable's value will be available in future \
220 expressions, otherwise it will just be available in the current expression." R"(
222 Continuing evaluation after a breakpoint:
224 )" " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
225 you are done with your investigation, you can either remove the expression execution frames \
226 from the stack with \"thread return -x\" or if you are still interested in the expression result \
227 you can issue the \"continue\" command and the expression evaluation will complete and the \
228 expression result will be available using the \"thread.completed-expression\" key in the thread \
233 expr my_struct->a = my_array[3]
234 expr -f bin -- (index * 8) + 5
235 expr unsigned int $foo = 5
236 expr char c[] = \"foo\"; c[0])"
239 CommandArgumentEntry arg;
240 CommandArgumentData expression_arg;
242 // Define the first (and only) variant of this arg.
243 expression_arg.arg_type = eArgTypeExpression;
244 expression_arg.arg_repetition = eArgRepeatPlain;
246 // There is only one variant this argument could be; put it into the argument entry.
247 arg.push_back (expression_arg);
249 // Push the data for the first argument into the m_arguments vector.
250 m_arguments.push_back (arg);
252 // Add the "--format" and "--gdb-format"
253 m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1);
254 m_option_group.Append (&m_command_options);
255 m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
256 m_option_group.Finalize();
259 CommandObjectExpression::~CommandObjectExpression ()
264 CommandObjectExpression::GetOptions ()
266 return &m_option_group;
270 CommandObjectExpression::EvaluateExpression
273 Stream *output_stream,
274 Stream *error_stream,
275 CommandReturnObject *result
278 // Don't use m_exe_ctx as this might be called asynchronously
279 // after the command object DoExecute has finished when doing
280 // multi-line expression that use an input reader...
281 ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
283 Target *target = exe_ctx.GetTargetPtr();
286 target = GetDummyTarget();
290 lldb::ValueObjectSP result_valobj_sp;
292 bool keep_in_memory = true;
294 EvaluateExpressionOptions options;
295 options.SetCoerceToId(m_varobj_options.use_objc);
296 options.SetUnwindOnError(m_command_options.unwind_on_error);
297 options.SetIgnoreBreakpoints (m_command_options.ignore_breakpoints);
298 options.SetKeepInMemory(keep_in_memory);
299 options.SetUseDynamic(m_varobj_options.use_dynamic);
300 options.SetTryAllThreads(m_command_options.try_all_threads);
301 options.SetDebug(m_command_options.debug);
303 // If there is any chance we are going to stop and want to see
304 // what went wrong with our expression, we should generate debug info
305 if (!m_command_options.ignore_breakpoints ||
306 !m_command_options.unwind_on_error)
307 options.SetGenerateDebugInfo(true);
309 if (m_command_options.timeout > 0)
310 options.SetTimeoutUsec(m_command_options.timeout);
312 options.SetTimeoutUsec(0);
314 target->EvaluateExpression(expr, exe_ctx.GetFramePtr(),
315 result_valobj_sp, options);
317 if (result_valobj_sp)
319 Format format = m_format_options.GetFormat();
321 if (result_valobj_sp->GetError().Success())
323 if (format != eFormatVoid)
325 if (format != eFormatDefault)
326 result_valobj_sp->SetFormat (format);
328 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(m_command_options.m_verbosity,format));
330 result_valobj_sp->Dump(*output_stream,options);
333 result->SetStatus (eReturnStatusSuccessFinishResult);
338 if (result_valobj_sp->GetError().GetError() == ClangUserExpression::kNoResult)
340 if (format != eFormatVoid && m_interpreter.GetDebugger().GetNotifyVoid())
342 error_stream->PutCString("(void)\n");
346 result->SetStatus (eReturnStatusSuccessFinishResult);
350 const char *error_cstr = result_valobj_sp->GetError().AsCString();
351 if (error_cstr && error_cstr[0])
353 const size_t error_cstr_len = strlen (error_cstr);
354 const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
355 if (strstr(error_cstr, "error:") != error_cstr)
356 error_stream->PutCString ("error: ");
357 error_stream->Write(error_cstr, error_cstr_len);
358 if (!ends_with_newline)
363 error_stream->PutCString ("error: unknown error\n");
367 result->SetStatus (eReturnStatusFailed);
374 error_stream->Printf ("error: invalid execution context for expression\n");
382 CommandObjectExpression::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
384 io_handler.SetIsDone(true);
385 // StreamSP output_stream = io_handler.GetDebugger().GetAsyncOutputStream();
386 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
387 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
388 StreamFileSP error_sp(io_handler.GetErrorStreamFile());
390 EvaluateExpression (line.c_str(),
400 CommandObjectExpression::IOHandlerLinesUpdated (IOHandler &io_handler,
405 if (line_idx == UINT32_MAX)
407 // Remove the last line from "lines" so it doesn't appear
408 // in our final expression
411 return LineStatus::Done;
413 else if (line_idx + 1 == lines.GetSize())
415 // The last line was edited, if this line is empty, then we are done
416 // getting our multiple lines.
417 if (lines[line_idx].empty())
418 return LineStatus::Done;
420 return LineStatus::Success;
424 CommandObjectExpression::GetMultilineExpression ()
426 m_expr_lines.clear();
427 m_expr_line_count = 0;
429 Debugger &debugger = GetCommandInterpreter().GetDebugger();
430 bool color_prompt = debugger.GetUseColor();
431 const bool multiple_lines = true; // Get multiple lines
432 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
433 IOHandler::Type::Expression,
434 "lldb-expr", // Name of input reader for history
436 NULL, // Continuation prompt
439 1, // Show line numbers starting at 1
442 StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
445 output_sp->PutCString("Enter expressions, then terminate with an empty line to evaluate:\n");
448 debugger.PushIOHandler(io_handler_sp);
452 CommandObjectExpression::DoExecute
455 CommandReturnObject &result
458 m_option_group.NotifyOptionParsingStarting();
460 const char * expr = NULL;
462 if (command[0] == '\0')
464 GetMultilineExpression ();
465 return result.Succeeded();
468 if (command[0] == '-')
470 // We have some options and these options MUST end with --.
471 const char *end_options = NULL;
472 const char *s = command;
475 end_options = ::strstr (s, "--");
478 end_options += 2; // Get past the "--"
479 if (::isspace (end_options[0]))
482 while (::isspace (*expr))
492 Args args (llvm::StringRef(command, end_options - command));
493 if (!ParseOptions (args, result))
496 Error error (m_option_group.NotifyOptionParsingFinished());
499 result.AppendError (error.AsCString());
500 result.SetStatus (eReturnStatusFailed);
504 // No expression following options
505 if (expr == NULL || expr[0] == '\0')
507 GetMultilineExpression ();
508 return result.Succeeded();
516 if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result))
519 result.SetStatus (eReturnStatusFailed);