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" 273eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h" 286611103cSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h" 2930fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h" 3047cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h" 3130fdc8d8SChris Lattner #include "lldb/Symbol/ObjectFile.h" 3230fdc8d8SChris Lattner #include "lldb/Symbol/Variable.h" 33b9c1b51eSKate Stone #include "lldb/Target/Language.h" 3430fdc8d8SChris Lattner #include "lldb/Target/Process.h" 35b57e4a1bSJason Molenda #include "lldb/Target/StackFrame.h" 3630fdc8d8SChris Lattner #include "lldb/Target/Target.h" 377260f620SGreg Clayton #include "lldb/Target/Thread.h" 3830fdc8d8SChris Lattner 3930fdc8d8SChris Lattner using namespace lldb; 4030fdc8d8SChris Lattner using namespace lldb_private; 4130fdc8d8SChris Lattner 42b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {} 4330fdc8d8SChris Lattner 44c8ecc2a9SEugene Zelenko CommandObjectExpression::CommandOptions::~CommandOptions() = default; 4530fdc8d8SChris Lattner 46*8fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_description_verbosity_type[] = { 47b9c1b51eSKate Stone {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", 48b9c1b51eSKate Stone "Only show the description string"}, 49b9c1b51eSKate Stone {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", 50*8fe53c49STatyana Krasnukha "Show the full output, including persistent variable's name and type"} }; 514d93b8cdSEnrico Granata 52*8fe53c49STatyana Krasnukha static constexpr OptionEnumValues DescriptionVerbosityTypes() { 53*8fe53c49STatyana Krasnukha return OptionEnumValues(g_description_verbosity_type); 54*8fe53c49STatyana Krasnukha } 55*8fe53c49STatyana Krasnukha 56*8fe53c49STatyana Krasnukha static constexpr OptionDefinition g_expression_options[] = { 57ac9c3a62SKate Stone // clang-format off 58*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."}, 59*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"}, 60*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."}, 61*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error", 'u', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, or raises a signal. " 62ac9c3a62SKate Stone "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."}, 63*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug", 'g', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "When specified, debug the JIT code by setting a breakpoint on the first instruction " 64ac9c3a62SKate Stone "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."}, 65*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "Specifies the Language to use when parsing the expression. If not set the target.language " 66ac9c3a62SKate Stone "setting is used." }, 67*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "apply-fixits", 'X', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "If true, simple fix-it hints will be automatically applied to the expression." }, 68*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1, false, "description-verbosity", 'v', OptionParser::eOptionalArgument, nullptr, DescriptionVerbosityTypes(), 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."}, 69*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "top-level", 'p', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Interpret the expression as a complete translation unit, without injecting it into the local " 700354a688SSean Callanan "context. Allows declaration of persistent, top-level entities without a $ prefix."}, 71*8fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "allow-jit", 'j', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Controls whether the expression can fall back to being JITted if it's not supported by " 72ac9c3a62SKate Stone "the interpreter (defaults to true)."} 73ac9c3a62SKate Stone // clang-format on 741deb7962SGreg Clayton }; 751deb7962SGreg Clayton 7697206d57SZachary Turner Status CommandObjectExpression::CommandOptions::SetOptionValue( 778cef4b0bSZachary Turner uint32_t option_idx, llvm::StringRef option_arg, 78b9c1b51eSKate Stone ExecutionContext *execution_context) { 7997206d57SZachary Turner Status error; 8030fdc8d8SChris Lattner 811f0f5b5bSZachary Turner const int short_option = GetDefinitions()[option_idx].short_option; 8230fdc8d8SChris Lattner 83b9c1b51eSKate Stone switch (short_option) { 8415663c53SDawn Perchik case 'l': 850e0984eeSJim Ingham language = Language::GetLanguageTypeFromString(option_arg); 8615663c53SDawn Perchik if (language == eLanguageTypeUnknown) 87b9c1b51eSKate Stone error.SetErrorStringWithFormat( 888cef4b0bSZachary Turner "unknown language type: '%s' for expression", 898cef4b0bSZachary Turner option_arg.str().c_str()); 9015663c53SDawn Perchik break; 9130fdc8d8SChris Lattner 92b9c1b51eSKate Stone case 'a': { 9335e1bda6SJim Ingham bool success; 9435e1bda6SJim Ingham bool result; 9547cbf4a0SPavel Labath result = OptionArgParser::ToBoolean(option_arg, true, &success); 9635e1bda6SJim Ingham if (!success) 97b9c1b51eSKate Stone error.SetErrorStringWithFormat( 988cef4b0bSZachary Turner "invalid all-threads value setting: \"%s\"", 998cef4b0bSZachary Turner option_arg.str().c_str()); 10035e1bda6SJim Ingham else 10135e1bda6SJim Ingham try_all_threads = result; 102b9c1b51eSKate Stone } break; 1036c68fb45SJim Ingham 104b9c1b51eSKate Stone case 'i': { 105184e9811SJim Ingham bool success; 10647cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 107184e9811SJim Ingham if (success) 108184e9811SJim Ingham ignore_breakpoints = tmp_value; 109184e9811SJim Ingham else 110b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1118cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1128cef4b0bSZachary Turner option_arg.str().c_str()); 113184e9811SJim Ingham break; 114184e9811SJim Ingham } 1153fe71581SMarianne Mailhot-Sarrasin 116b9c1b51eSKate Stone case 'j': { 1173fe71581SMarianne Mailhot-Sarrasin bool success; 11847cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 1193fe71581SMarianne Mailhot-Sarrasin if (success) 1203fe71581SMarianne Mailhot-Sarrasin allow_jit = tmp_value; 1213fe71581SMarianne Mailhot-Sarrasin else 122b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1238cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1248cef4b0bSZachary Turner option_arg.str().c_str()); 1253fe71581SMarianne Mailhot-Sarrasin break; 1263fe71581SMarianne Mailhot-Sarrasin } 1273fe71581SMarianne Mailhot-Sarrasin 1288cef4b0bSZachary Turner case 't': 1298cef4b0bSZachary Turner if (option_arg.getAsInteger(0, timeout)) { 1308cef4b0bSZachary Turner timeout = 0; 131b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid timeout setting \"%s\"", 1328cef4b0bSZachary Turner option_arg.str().c_str()); 1338cef4b0bSZachary Turner } 1348cef4b0bSZachary Turner break; 13535e1bda6SJim Ingham 136b9c1b51eSKate Stone case 'u': { 137399f1cafSJim Ingham bool success; 13847cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 139184e9811SJim Ingham if (success) 140184e9811SJim Ingham unwind_on_error = tmp_value; 141184e9811SJim Ingham else 142b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1438cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1448cef4b0bSZachary Turner option_arg.str().c_str()); 145399f1cafSJim Ingham break; 1463bfdaa2aSSean Callanan } 1474d93b8cdSEnrico Granata 1484d93b8cdSEnrico Granata case 'v': 149543a26e9SEnrico Granata if (option_arg.empty()) { 1504d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 1514d93b8cdSEnrico Granata break; 1524d93b8cdSEnrico Granata } 15347cbf4a0SPavel Labath m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) 15447cbf4a0SPavel Labath OptionArgParser::ToOptionEnum( 1551f0f5b5bSZachary Turner option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 1564d93b8cdSEnrico Granata if (!error.Success()) 157b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1588cef4b0bSZachary Turner "unrecognized value for description-verbosity '%s'", 1598cef4b0bSZachary Turner option_arg.str().c_str()); 1604d93b8cdSEnrico Granata break; 1614d93b8cdSEnrico Granata 16262afb9f6SGreg Clayton case 'g': 16362afb9f6SGreg Clayton debug = true; 16462afb9f6SGreg Clayton unwind_on_error = false; 16562afb9f6SGreg Clayton ignore_breakpoints = false; 16662afb9f6SGreg Clayton break; 16762afb9f6SGreg Clayton 168863fab69SSean Callanan case 'p': 169863fab69SSean Callanan top_level = true; 170863fab69SSean Callanan break; 171863fab69SSean Callanan 172b9c1b51eSKate Stone case 'X': { 173a1e541bfSJim Ingham bool success; 17447cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 175a1e541bfSJim Ingham if (success) 176a1e541bfSJim Ingham auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; 177a1e541bfSJim Ingham else 178b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1798cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1808cef4b0bSZachary Turner option_arg.str().c_str()); 181a1e541bfSJim Ingham break; 182a1e541bfSJim Ingham } 183a1e541bfSJim Ingham 18430fdc8d8SChris Lattner default: 185b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid short option character '%c'", 186b9c1b51eSKate Stone short_option); 18730fdc8d8SChris Lattner break; 18830fdc8d8SChris Lattner } 18930fdc8d8SChris Lattner 19030fdc8d8SChris Lattner return error; 19130fdc8d8SChris Lattner } 19230fdc8d8SChris Lattner 193b9c1b51eSKate Stone void CommandObjectExpression::CommandOptions::OptionParsingStarting( 194b9c1b51eSKate Stone ExecutionContext *execution_context) { 195e1cfbc79STodd Fiala auto process_sp = 196e1cfbc79STodd Fiala execution_context ? execution_context->GetProcessSP() : ProcessSP(); 197b9c1b51eSKate Stone if (process_sp) { 198e1cfbc79STodd Fiala ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); 199e1cfbc79STodd Fiala unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); 200b9c1b51eSKate Stone } else { 201fc03f8fcSGreg Clayton ignore_breakpoints = true; 202399f1cafSJim Ingham unwind_on_error = true; 203184e9811SJim Ingham } 204184e9811SJim Ingham 20530fdc8d8SChris Lattner show_summary = true; 20635e1bda6SJim Ingham try_all_threads = true; 20735e1bda6SJim Ingham timeout = 0; 20862afb9f6SGreg Clayton debug = false; 20915663c53SDawn Perchik language = eLanguageTypeUnknown; 2104d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 211a1e541bfSJim Ingham auto_apply_fixits = eLazyBoolCalculate; 212863fab69SSean Callanan top_level = false; 2133fe71581SMarianne Mailhot-Sarrasin allow_jit = true; 21430fdc8d8SChris Lattner } 21530fdc8d8SChris Lattner 2161f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> 217b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::GetDefinitions() { 21870602439SZachary Turner return llvm::makeArrayRef(g_expression_options); 21930fdc8d8SChris Lattner } 22030fdc8d8SChris Lattner 221b9c1b51eSKate Stone CommandObjectExpression::CommandObjectExpression( 222b9c1b51eSKate Stone CommandInterpreter &interpreter) 2237428a18cSKate Stone : CommandObjectRaw( 224b9c1b51eSKate Stone interpreter, "expression", "Evaluate an expression on the current " 225b9c1b51eSKate Stone "thread. Displays any returned value " 226b9c1b51eSKate Stone "with LLDB's default formatting.", 227a449698cSZachary Turner "", eCommandProcessMustBePaused | eCommandTryTargetAPILock), 22844d93782SGreg Clayton IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), 229b9c1b51eSKate Stone m_option_group(), m_format_options(eFormatDefault), 230b9c1b51eSKate Stone m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, 231b9c1b51eSKate Stone true), 232b9c1b51eSKate Stone m_command_options(), m_expr_line_count(0), m_expr_lines() { 23330fdc8d8SChris Lattner SetHelpLong( 234ea671fbdSKate Stone R"( 235d0309916SJim Ingham Single and multi-line expressions: 236d0309916SJim Ingham 237d0309916SJim Ingham )" 238d0309916SJim Ingham " The expression provided on the command line must be a complete expression \ 239d0309916SJim Ingham with no newlines. To evaluate a multi-line expression, \ 240d0309916SJim Ingham hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ 241d0309916SJim Ingham Hit return on an empty line to end the multi-line expression." 242d0309916SJim Ingham 243d0309916SJim Ingham R"( 244d0309916SJim Ingham 245ea671fbdSKate Stone Timeouts: 246ea671fbdSKate Stone 247b9c1b51eSKate Stone )" 248b9c1b51eSKate Stone " If the expression can be evaluated statically (without running code) then it will be. \ 249ea671fbdSKate Stone Otherwise, by default the expression will run on the current thread with a short timeout: \ 250ea671fbdSKate Stone currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 251ea671fbdSKate Stone and resumed with all threads running. You can use the -a option to disable retrying on all \ 252b9c1b51eSKate Stone threads. You can use the -t option to set a shorter timeout." 253b9c1b51eSKate Stone R"( 254ea671fbdSKate Stone 255ea671fbdSKate Stone User defined variables: 256ea671fbdSKate Stone 257b9c1b51eSKate Stone )" 258b9c1b51eSKate Stone " You can define your own variables for convenience or to be used in subsequent expressions. \ 259ea671fbdSKate Stone You define them the same way you would define variables in C. If the first character of \ 260ea671fbdSKate Stone your user defined variable is a $, then the variable's value will be available in future \ 261b9c1b51eSKate Stone expressions, otherwise it will just be available in the current expression." 262b9c1b51eSKate Stone R"( 263ea671fbdSKate Stone 264ea671fbdSKate Stone Continuing evaluation after a breakpoint: 265ea671fbdSKate Stone 266b9c1b51eSKate Stone )" 267b9c1b51eSKate Stone " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 268ea671fbdSKate Stone you are done with your investigation, you can either remove the expression execution frames \ 269ea671fbdSKate Stone from the stack with \"thread return -x\" or if you are still interested in the expression result \ 270ea671fbdSKate Stone you can issue the \"continue\" command and the expression evaluation will complete and the \ 271ea671fbdSKate Stone expression result will be available using the \"thread.completed-expression\" key in the thread \ 272b9c1b51eSKate Stone format." 273d0309916SJim Ingham 274b9c1b51eSKate Stone R"( 275ea671fbdSKate Stone 276ea671fbdSKate Stone Examples: 277ea671fbdSKate Stone 278ea671fbdSKate Stone expr my_struct->a = my_array[3] 279ea671fbdSKate Stone expr -f bin -- (index * 8) + 5 280ea671fbdSKate Stone expr unsigned int $foo = 5 281b9c1b51eSKate Stone expr char c[] = \"foo\"; c[0])"); 282405fe67fSCaroline Tice 283405fe67fSCaroline Tice CommandArgumentEntry arg; 284405fe67fSCaroline Tice CommandArgumentData expression_arg; 285405fe67fSCaroline Tice 286405fe67fSCaroline Tice // Define the first (and only) variant of this arg. 287405fe67fSCaroline Tice expression_arg.arg_type = eArgTypeExpression; 288405fe67fSCaroline Tice expression_arg.arg_repetition = eArgRepeatPlain; 289405fe67fSCaroline Tice 290b9c1b51eSKate Stone // There is only one variant this argument could be; put it into the argument 291b9c1b51eSKate Stone // entry. 292405fe67fSCaroline Tice arg.push_back(expression_arg); 293405fe67fSCaroline Tice 294405fe67fSCaroline Tice // Push the data for the first argument into the m_arguments vector. 295405fe67fSCaroline Tice m_arguments.push_back(arg); 2961deb7962SGreg Clayton 2975009f9d5SGreg Clayton // Add the "--format" and "--gdb-format" 298b9c1b51eSKate Stone m_option_group.Append(&m_format_options, 299b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_FORMAT | 300b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_GDB_FMT, 301b9c1b51eSKate Stone LLDB_OPT_SET_1); 3021deb7962SGreg Clayton m_option_group.Append(&m_command_options); 303b9c1b51eSKate Stone m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, 304b9c1b51eSKate Stone LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 305f2bd5c3eSSean Callanan m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 3061deb7962SGreg Clayton m_option_group.Finalize(); 30730fdc8d8SChris Lattner } 30830fdc8d8SChris Lattner 309c8ecc2a9SEugene Zelenko CommandObjectExpression::~CommandObjectExpression() = default; 31030fdc8d8SChris Lattner 311b9c1b51eSKate Stone Options *CommandObjectExpression::GetOptions() { return &m_option_group; } 31230fdc8d8SChris Lattner 31374829734SRaphael Isemann int CommandObjectExpression::HandleCompletion(CompletionRequest &request) { 31474829734SRaphael Isemann EvaluateExpressionOptions options; 31574829734SRaphael Isemann options.SetCoerceToId(m_varobj_options.use_objc); 31674829734SRaphael Isemann options.SetLanguage(m_command_options.language); 31774829734SRaphael Isemann options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever); 31874829734SRaphael Isemann options.SetAutoApplyFixIts(false); 31974829734SRaphael Isemann options.SetGenerateDebugInfo(false); 32074829734SRaphael Isemann 32174829734SRaphael Isemann // We need a valid execution context with a frame pointer for this 32274829734SRaphael Isemann // completion, so if we don't have one we should try to make a valid 32374829734SRaphael Isemann // execution context. 32474829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 32574829734SRaphael Isemann m_interpreter.UpdateExecutionContext(nullptr); 32674829734SRaphael Isemann 32774829734SRaphael Isemann // This didn't work, so let's get out before we start doing things that 32874829734SRaphael Isemann // expect a valid frame pointer. 32974829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 33074829734SRaphael Isemann return 0; 33174829734SRaphael Isemann 33274829734SRaphael Isemann ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 33374829734SRaphael Isemann 33474829734SRaphael Isemann Target *target = exe_ctx.GetTargetPtr(); 33574829734SRaphael Isemann 33674829734SRaphael Isemann if (!target) 33774829734SRaphael Isemann target = GetDummyTarget(); 33874829734SRaphael Isemann 33974829734SRaphael Isemann if (!target) 34074829734SRaphael Isemann return 0; 34174829734SRaphael Isemann 34274829734SRaphael Isemann unsigned cursor_pos = request.GetRawCursorPos(); 34374829734SRaphael Isemann llvm::StringRef code = request.GetRawLine(); 34474829734SRaphael Isemann 34574829734SRaphael Isemann const std::size_t original_code_size = code.size(); 34674829734SRaphael Isemann 34774829734SRaphael Isemann // Remove the first token which is 'expr' or some alias/abbreviation of that. 34874829734SRaphael Isemann code = llvm::getToken(code).second.ltrim(); 34974829734SRaphael Isemann OptionsWithRaw args(code); 35074829734SRaphael Isemann code = args.GetRawPart(); 35174829734SRaphael Isemann 35274829734SRaphael Isemann // The position where the expression starts in the command line. 35374829734SRaphael Isemann assert(original_code_size >= code.size()); 35474829734SRaphael Isemann std::size_t raw_start = original_code_size - code.size(); 35574829734SRaphael Isemann 35674829734SRaphael Isemann // Check if the cursor is actually in the expression string, and if not, we 35774829734SRaphael Isemann // exit. 35874829734SRaphael Isemann // FIXME: We should complete the options here. 35974829734SRaphael Isemann if (cursor_pos < raw_start) 36074829734SRaphael Isemann return 0; 36174829734SRaphael Isemann 36274829734SRaphael Isemann // Make the cursor_pos again relative to the start of the code string. 36374829734SRaphael Isemann assert(cursor_pos >= raw_start); 36474829734SRaphael Isemann cursor_pos -= raw_start; 36574829734SRaphael Isemann 36674829734SRaphael Isemann auto language = exe_ctx.GetFrameRef().GetLanguage(); 36774829734SRaphael Isemann 36874829734SRaphael Isemann Status error; 36974829734SRaphael Isemann lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage( 37074829734SRaphael Isemann code, llvm::StringRef(), language, UserExpression::eResultTypeAny, 37174829734SRaphael Isemann options, error)); 37274829734SRaphael Isemann if (error.Fail()) 37374829734SRaphael Isemann return 0; 37474829734SRaphael Isemann 375c11a780eSRaphael Isemann expr->Complete(exe_ctx, request, cursor_pos); 37674829734SRaphael Isemann return request.GetNumberOfMatches(); 37774829734SRaphael Isemann } 37874829734SRaphael Isemann 37997206d57SZachary Turner static lldb_private::Status 380b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) { 381520a422bSEnrico Granata CompilerType type(valobj.GetCompilerType()); 382520a422bSEnrico Granata CompilerType pointee; 383520a422bSEnrico Granata if (!type.IsPointerType(&pointee)) 38497206d57SZachary Turner return Status("as it does not refer to a pointer"); 385520a422bSEnrico Granata if (pointee.IsVoidType()) 38697206d57SZachary Turner return Status("as it refers to a pointer to void"); 38797206d57SZachary Turner return Status(); 388520a422bSEnrico Granata } 389520a422bSEnrico Granata 3904d51a902SRaphael Isemann bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr, 3916e8dc334SCaroline Tice Stream *output_stream, 3926e8dc334SCaroline Tice Stream *error_stream, 393b9c1b51eSKate Stone CommandReturnObject *result) { 39405097246SAdrian Prantl // Don't use m_exe_ctx as this might be called asynchronously after the 39505097246SAdrian Prantl // command object DoExecute has finished when doing multi-line expression 39605097246SAdrian Prantl // that use an input reader... 397ba7b8e2cSGreg Clayton ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 398ba7b8e2cSGreg Clayton 399ba7b8e2cSGreg Clayton Target *target = exe_ctx.GetTargetPtr(); 400c0a6e061SSean Callanan 401c0a6e061SSean Callanan if (!target) 402893c932aSJim Ingham target = GetDummyTarget(); 403c0a6e061SSean Callanan 404b9c1b51eSKate Stone if (target) { 4058b2fe6dcSGreg Clayton lldb::ValueObjectSP result_valobj_sp; 40692adcac9SSean Callanan bool keep_in_memory = true; 407009d110dSDawn Perchik StackFrame *frame = exe_ctx.GetFramePtr(); 40892adcac9SSean Callanan 40935e1bda6SJim Ingham EvaluateExpressionOptions options; 4106fbc48bcSJim Ingham options.SetCoerceToId(m_varobj_options.use_objc); 4116fbc48bcSJim Ingham options.SetUnwindOnError(m_command_options.unwind_on_error); 4126fbc48bcSJim Ingham options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); 4136fbc48bcSJim Ingham options.SetKeepInMemory(keep_in_memory); 4146fbc48bcSJim Ingham options.SetUseDynamic(m_varobj_options.use_dynamic); 4156fbc48bcSJim Ingham options.SetTryAllThreads(m_command_options.try_all_threads); 4166fbc48bcSJim Ingham options.SetDebug(m_command_options.debug); 41715663c53SDawn Perchik options.SetLanguage(m_command_options.language); 418b9c1b51eSKate Stone options.SetExecutionPolicy( 419b9c1b51eSKate Stone m_command_options.allow_jit 420b9c1b51eSKate Stone ? EvaluateExpressionOptions::default_execution_policy 421b9c1b51eSKate Stone : lldb_private::eExecutionPolicyNever); 42215663c53SDawn Perchik 423a1e541bfSJim Ingham bool auto_apply_fixits; 424a1e541bfSJim Ingham if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) 425a1e541bfSJim Ingham auto_apply_fixits = target->GetEnableAutoApplyFixIts(); 426a1e541bfSJim Ingham else 427b9c1b51eSKate Stone auto_apply_fixits = 428b9c1b51eSKate Stone m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false; 429a1e541bfSJim Ingham 430a1e541bfSJim Ingham options.SetAutoApplyFixIts(auto_apply_fixits); 431a1e541bfSJim Ingham 432863fab69SSean Callanan if (m_command_options.top_level) 433863fab69SSean Callanan options.SetExecutionPolicy(eExecutionPolicyTopLevel); 434863fab69SSean Callanan 43505097246SAdrian Prantl // If there is any chance we are going to stop and want to see what went 43605097246SAdrian Prantl // wrong with our expression, we should generate debug info 43723f8c95aSGreg Clayton if (!m_command_options.ignore_breakpoints || 43823f8c95aSGreg Clayton !m_command_options.unwind_on_error) 43923f8c95aSGreg Clayton options.SetGenerateDebugInfo(true); 44023f8c95aSGreg Clayton 44162afb9f6SGreg Clayton if (m_command_options.timeout > 0) 44243d35418SPavel Labath options.SetTimeout(std::chrono::microseconds(m_command_options.timeout)); 4436f78f386SJim Ingham else 44443d35418SPavel Labath options.SetTimeout(llvm::None); 445d4439aa9SEnrico Granata 446b9c1b51eSKate Stone ExpressionResults success = target->EvaluateExpression( 447b9c1b51eSKate Stone expr, frame, result_valobj_sp, options, &m_fixed_expression); 448e5ee6f04SJim Ingham 449b9c1b51eSKate Stone // We only tell you about the FixIt if we applied it. The compiler errors 450b9c1b51eSKate Stone // will suggest the FixIt if it parsed. 451b9c1b51eSKate Stone if (error_stream && !m_fixed_expression.empty() && 452b9c1b51eSKate Stone target->GetEnableNotifyAboutFixIts()) { 453e5ee6f04SJim Ingham if (success == eExpressionCompleted) 454b9c1b51eSKate Stone error_stream->Printf( 455b9c1b51eSKate Stone " Fix-it applied, fixed expression was: \n %s\n", 456b9c1b51eSKate Stone m_fixed_expression.c_str()); 457e5ee6f04SJim Ingham } 4588b2fe6dcSGreg Clayton 459b9c1b51eSKate Stone if (result_valobj_sp) { 460bf154daeSSean Callanan Format format = m_format_options.GetFormat(); 461bf154daeSSean Callanan 462b9c1b51eSKate Stone if (result_valobj_sp->GetError().Success()) { 463b9c1b51eSKate Stone if (format != eFormatVoid) { 4641deb7962SGreg Clayton if (format != eFormatDefault) 4651deb7962SGreg Clayton result_valobj_sp->SetFormat(format); 46632c4085bSGreg Clayton 467b9c1b51eSKate Stone if (m_varobj_options.elem_count > 0) { 46897206d57SZachary Turner Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); 469b9c1b51eSKate Stone if (error.Fail()) { 470b9c1b51eSKate Stone result->AppendErrorWithFormat( 471b9c1b51eSKate Stone "expression cannot be used with --element-count %s\n", 472b9c1b51eSKate Stone error.AsCString("")); 473520a422bSEnrico Granata result->SetStatus(eReturnStatusFailed); 474520a422bSEnrico Granata return false; 475520a422bSEnrico Granata } 476520a422bSEnrico Granata } 477520a422bSEnrico Granata 478b9c1b51eSKate Stone DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 479b9c1b51eSKate Stone m_command_options.m_verbosity, format)); 480b9c1b51eSKate Stone options.SetVariableFormatDisplayLanguage( 481b9c1b51eSKate Stone result_valobj_sp->GetPreferredDisplayLanguage()); 482770eb05aSEnrico Granata 4834d93b8cdSEnrico Granata result_valobj_sp->Dump(*output_stream, options); 4844d93b8cdSEnrico Granata 485fcd43b71SJohnny Chen if (result) 486fcd43b71SJohnny Chen result->SetStatus(eReturnStatusSuccessFinishResult); 48730fdc8d8SChris Lattner } 488b9c1b51eSKate Stone } else { 489b9c1b51eSKate Stone if (result_valobj_sp->GetError().GetError() == 490b9c1b51eSKate Stone UserExpression::kNoResult) { 491b9c1b51eSKate Stone if (format != eFormatVoid && 492b9c1b51eSKate Stone m_interpreter.GetDebugger().GetNotifyVoid()) { 493bcf897faSSean Callanan error_stream->PutCString("(void)\n"); 494bcf897faSSean Callanan } 495bccce813SSean Callanan 496bccce813SSean Callanan if (result) 497bccce813SSean Callanan result->SetStatus(eReturnStatusSuccessFinishResult); 498b9c1b51eSKate Stone } else { 4995fd05903SGreg Clayton const char *error_cstr = result_valobj_sp->GetError().AsCString(); 500b9c1b51eSKate Stone if (error_cstr && error_cstr[0]) { 501c7bece56SGreg Clayton const size_t error_cstr_len = strlen(error_cstr); 502b9c1b51eSKate Stone const bool ends_with_newline = 503b9c1b51eSKate Stone error_cstr[error_cstr_len - 1] == '\n'; 5045fd05903SGreg Clayton if (strstr(error_cstr, "error:") != error_cstr) 5055fd05903SGreg Clayton error_stream->PutCString("error: "); 5065fd05903SGreg Clayton error_stream->Write(error_cstr, error_cstr_len); 5075fd05903SGreg Clayton if (!ends_with_newline) 5085fd05903SGreg Clayton error_stream->EOL(); 509b9c1b51eSKate Stone } else { 5105fd05903SGreg Clayton error_stream->PutCString("error: unknown error\n"); 5115fd05903SGreg Clayton } 5125fd05903SGreg Clayton 513fcd43b71SJohnny Chen if (result) 514b71f3844SGreg Clayton result->SetStatus(eReturnStatusFailed); 51530fdc8d8SChris Lattner } 5168b2fe6dcSGreg Clayton } 5178b2fe6dcSGreg Clayton } 518b9c1b51eSKate Stone } else { 5196e8dc334SCaroline Tice error_stream->Printf("error: invalid execution context for expression\n"); 5208b2fe6dcSGreg Clayton return false; 5218b2fe6dcSGreg Clayton } 52230fdc8d8SChris Lattner 52316ad5faeSSean Callanan return true; 52430fdc8d8SChris Lattner } 52530fdc8d8SChris Lattner 526b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, 527b9c1b51eSKate Stone std::string &line) { 52844d93782SGreg Clayton io_handler.SetIsDone(true); 529b9c1b51eSKate Stone // StreamSP output_stream = 530b9c1b51eSKate Stone // io_handler.GetDebugger().GetAsyncOutputStream(); 53144d93782SGreg Clayton // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); 53244d93782SGreg Clayton StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 53344d93782SGreg Clayton StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 53444d93782SGreg Clayton 535b9c1b51eSKate Stone EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get()); 53644d93782SGreg Clayton if (output_sp) 53744d93782SGreg Clayton output_sp->Flush(); 53844d93782SGreg Clayton if (error_sp) 53944d93782SGreg Clayton error_sp->Flush(); 54044d93782SGreg Clayton } 54144d93782SGreg Clayton 542b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, 543b9c1b51eSKate Stone StringList &lines) { 544f52c40c5SSean Callanan // An empty lines is used to indicate the end of input 545f52c40c5SSean Callanan const size_t num_lines = lines.GetSize(); 546b9c1b51eSKate Stone if (num_lines > 0 && lines[num_lines - 1].empty()) { 54705097246SAdrian Prantl // Remove the last empty line from "lines" so it doesn't appear in our 54805097246SAdrian Prantl // resulting input and return true to indicate we are done getting lines 54944d93782SGreg Clayton lines.PopBack(); 550f52c40c5SSean Callanan return true; 55144d93782SGreg Clayton } 552f52c40c5SSean Callanan return false; 55344d93782SGreg Clayton } 55444d93782SGreg Clayton 555b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() { 55630fdc8d8SChris Lattner m_expr_lines.clear(); 55730fdc8d8SChris Lattner m_expr_line_count = 0; 55830fdc8d8SChris Lattner 55944d93782SGreg Clayton Debugger &debugger = GetCommandInterpreter().GetDebugger(); 560e30f11d9SKate Stone bool color_prompt = debugger.GetUseColor(); 56144d93782SGreg Clayton const bool multiple_lines = true; // Get multiple lines 562b9c1b51eSKate Stone IOHandlerSP io_handler_sp( 563b9c1b51eSKate Stone new IOHandlerEditline(debugger, IOHandler::Type::Expression, 56444d93782SGreg Clayton "lldb-expr", // Name of input reader for history 565514d8cd8SZachary Turner llvm::StringRef(), // No prompt 566514d8cd8SZachary Turner llvm::StringRef(), // Continuation prompt 567b9c1b51eSKate Stone multiple_lines, color_prompt, 568f6913cd7SGreg Clayton 1, // Show line numbers starting at 1 56944d93782SGreg Clayton *this)); 570b6892508SGreg Clayton 571b6892508SGreg Clayton StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); 572b9c1b51eSKate Stone if (output_sp) { 573b9c1b51eSKate Stone output_sp->PutCString( 574b9c1b51eSKate Stone "Enter expressions, then terminate with an empty line to evaluate:\n"); 575b6892508SGreg Clayton output_sp->Flush(); 576b6892508SGreg Clayton } 57744d93782SGreg Clayton debugger.PushIOHandler(io_handler_sp); 578cf28a8b7SGreg Clayton } 579cf28a8b7SGreg Clayton 5804d51a902SRaphael Isemann bool CommandObjectExpression::DoExecute(llvm::StringRef command, 581b9c1b51eSKate Stone CommandReturnObject &result) { 582e5ee6f04SJim Ingham m_fixed_expression.clear(); 583e1cfbc79STodd Fiala auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); 584e1cfbc79STodd Fiala m_option_group.NotifyOptionParsingStarting(&exe_ctx); 585cf28a8b7SGreg Clayton 5864d51a902SRaphael Isemann if (command.empty()) { 587cf28a8b7SGreg Clayton GetMultilineExpression(); 58830fdc8d8SChris Lattner return result.Succeeded(); 58930fdc8d8SChris Lattner } 59030fdc8d8SChris Lattner 5913a0e1270SRaphael Isemann OptionsWithRaw args(command); 5924d51a902SRaphael Isemann llvm::StringRef expr = args.GetRawPart(); 59330fdc8d8SChris Lattner 5943a0e1270SRaphael Isemann if (args.HasArgs()) { 5953a0e1270SRaphael Isemann if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx)) 59630fdc8d8SChris Lattner return false; 597f6b8b581SGreg Clayton 598b9c1b51eSKate Stone if (m_repl_option.GetOptionValue().GetCurrentValue()) { 599f2bd5c3eSSean Callanan Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); 600b9c1b51eSKate Stone if (target) { 601f2bd5c3eSSean Callanan // Drop into REPL 602f2bd5c3eSSean Callanan m_expr_lines.clear(); 603f2bd5c3eSSean Callanan m_expr_line_count = 0; 604f2bd5c3eSSean Callanan 605f2bd5c3eSSean Callanan Debugger &debugger = target->GetDebugger(); 606f2bd5c3eSSean Callanan 607b9c1b51eSKate Stone // Check if the LLDB command interpreter is sitting on top of a REPL 60805097246SAdrian Prantl // that launched it... 6093a0e1270SRaphael Isemann if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, 6103a0e1270SRaphael Isemann IOHandler::Type::REPL)) { 611b9c1b51eSKate Stone // the LLDB command interpreter is sitting on top of a REPL that 61205097246SAdrian Prantl // launched it, so just say the command interpreter is done and 61305097246SAdrian Prantl // fall back to the existing REPL 614f2bd5c3eSSean Callanan m_interpreter.GetIOHandler(false)->SetIsDone(true); 615b9c1b51eSKate Stone } else { 616b9c1b51eSKate Stone // We are launching the REPL on top of the current LLDB command 61705097246SAdrian Prantl // interpreter, so just push one 618f2bd5c3eSSean Callanan bool initialize = false; 61997206d57SZachary Turner Status repl_error; 6203a0e1270SRaphael Isemann REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language, 6213a0e1270SRaphael Isemann nullptr, false)); 622f2bd5c3eSSean Callanan 623b9c1b51eSKate Stone if (!repl_sp) { 624f2bd5c3eSSean Callanan initialize = true; 625b9c1b51eSKate Stone repl_sp = target->GetREPL(repl_error, m_command_options.language, 626b9c1b51eSKate Stone nullptr, true); 627b9c1b51eSKate Stone if (!repl_error.Success()) { 628f2bd5c3eSSean Callanan result.SetError(repl_error); 629f2bd5c3eSSean Callanan return result.Succeeded(); 630f2bd5c3eSSean Callanan } 631f2bd5c3eSSean Callanan } 632f2bd5c3eSSean Callanan 633b9c1b51eSKate Stone if (repl_sp) { 634b9c1b51eSKate Stone if (initialize) { 635f2bd5c3eSSean Callanan repl_sp->SetCommandOptions(m_command_options); 636f2bd5c3eSSean Callanan repl_sp->SetFormatOptions(m_format_options); 637f2bd5c3eSSean Callanan repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 638f2bd5c3eSSean Callanan } 639f2bd5c3eSSean Callanan 640f2bd5c3eSSean Callanan IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); 641f2bd5c3eSSean Callanan 642f2bd5c3eSSean Callanan io_handler_sp->SetIsDone(false); 643f2bd5c3eSSean Callanan 644f2bd5c3eSSean Callanan debugger.PushIOHandler(io_handler_sp); 645b9c1b51eSKate Stone } else { 646b9c1b51eSKate Stone repl_error.SetErrorStringWithFormat( 647b9c1b51eSKate Stone "Couldn't create a REPL for %s", 648b9c1b51eSKate Stone Language::GetNameForLanguageType(m_command_options.language)); 649f2bd5c3eSSean Callanan result.SetError(repl_error); 650f2bd5c3eSSean Callanan return result.Succeeded(); 651f2bd5c3eSSean Callanan } 652f2bd5c3eSSean Callanan } 653f2bd5c3eSSean Callanan } 654f2bd5c3eSSean Callanan } 655cf28a8b7SGreg Clayton // No expression following options 6564d51a902SRaphael Isemann else if (expr.empty()) { 657cf28a8b7SGreg Clayton GetMultilineExpression(); 658cf28a8b7SGreg Clayton return result.Succeeded(); 659cf28a8b7SGreg Clayton } 66030fdc8d8SChris Lattner } 66130fdc8d8SChris Lattner 6620df817aaSDavide Italiano Target *target = GetSelectedOrDummyTarget(); 66324fff242SDavide Italiano if (EvaluateExpression(expr, &(result.GetOutputStream()), 66424fff242SDavide Italiano &(result.GetErrorStream()), &result)) { 66524fff242SDavide Italiano 666b9c1b51eSKate Stone if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) { 667e5ee6f04SJim Ingham CommandHistory &history = m_interpreter.GetCommandHistory(); 668b9c1b51eSKate Stone // FIXME: Can we figure out what the user actually typed (e.g. some alias 669b9c1b51eSKate Stone // for expr???) 670e5ee6f04SJim Ingham // If we can it would be nice to show that. 671e5ee6f04SJim Ingham std::string fixed_command("expression "); 6723a0e1270SRaphael Isemann if (args.HasArgs()) { 673e5ee6f04SJim Ingham // Add in any options that might have been in the original command: 6743a0e1270SRaphael Isemann fixed_command.append(args.GetArgStringWithDelimiter()); 675e5ee6f04SJim Ingham fixed_command.append(m_fixed_expression); 6763a0e1270SRaphael Isemann } else 6773a0e1270SRaphael Isemann fixed_command.append(m_fixed_expression); 678e5ee6f04SJim Ingham history.AppendString(fixed_command); 679e5ee6f04SJim Ingham } 68005097246SAdrian Prantl // Increment statistics to record this expression evaluation success. 68124fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionSuccessful); 682fcd43b71SJohnny Chen return true; 683e5ee6f04SJim Ingham } 684fcd43b71SJohnny Chen 68505097246SAdrian Prantl // Increment statistics to record this expression evaluation failure. 68624fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionFailure); 687fcd43b71SJohnny Chen result.SetStatus(eReturnStatusFailed); 688fcd43b71SJohnny Chen return false; 68930fdc8d8SChris Lattner } 690