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 10c8ecc2a9SEugene Zelenko #include "llvm/ADT/STLExtras.h" 11c8ecc2a9SEugene Zelenko #include "llvm/ADT/StringRef.h" 12c8ecc2a9SEugene Zelenko 13c8ecc2a9SEugene Zelenko #include "CommandObjectExpression.h" 14b9c1b51eSKate Stone #include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" 15b9c1b51eSKate Stone #include "lldb/Core/Debugger.h" 1630fdc8d8SChris Lattner #include "lldb/Core/Value.h" 176c68fb45SJim Ingham #include "lldb/Core/ValueObjectVariable.h" 184d93b8cdSEnrico Granata #include "lldb/DataFormatters/ValueObjectPrinter.h" 1930fdc8d8SChris Lattner #include "lldb/Expression/DWARFExpression.h" 20f2bd5c3eSSean Callanan #include "lldb/Expression/REPL.h" 21b9c1b51eSKate Stone #include "lldb/Expression/UserExpression.h" 2230fdc8d8SChris Lattner #include "lldb/Host/Host.h" 233eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h" 246611103cSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h" 2530fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h" 2647cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h" 2730fdc8d8SChris Lattner #include "lldb/Symbol/ObjectFile.h" 2830fdc8d8SChris Lattner #include "lldb/Symbol/Variable.h" 29b9c1b51eSKate Stone #include "lldb/Target/Language.h" 3030fdc8d8SChris Lattner #include "lldb/Target/Process.h" 31b57e4a1bSJason Molenda #include "lldb/Target/StackFrame.h" 3230fdc8d8SChris Lattner #include "lldb/Target/Target.h" 337260f620SGreg Clayton #include "lldb/Target/Thread.h" 3430fdc8d8SChris Lattner 3530fdc8d8SChris Lattner using namespace lldb; 3630fdc8d8SChris Lattner using namespace lldb_private; 3730fdc8d8SChris Lattner 38b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {} 3930fdc8d8SChris Lattner 40c8ecc2a9SEugene Zelenko CommandObjectExpression::CommandOptions::~CommandOptions() = default; 4130fdc8d8SChris Lattner 428fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_description_verbosity_type[] = { 43b9c1b51eSKate Stone {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", 44b9c1b51eSKate Stone "Only show the description string"}, 45b9c1b51eSKate Stone {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", 468fe53c49STatyana Krasnukha "Show the full output, including persistent variable's name and type"} }; 474d93b8cdSEnrico Granata 488fe53c49STatyana Krasnukha static constexpr OptionEnumValues DescriptionVerbosityTypes() { 498fe53c49STatyana Krasnukha return OptionEnumValues(g_description_verbosity_type); 508fe53c49STatyana Krasnukha } 518fe53c49STatyana Krasnukha 528fe53c49STatyana Krasnukha static constexpr OptionDefinition g_expression_options[] = { 53ac9c3a62SKate Stone // clang-format off 548fe53c49STatyana 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."}, 558fe53c49STatyana Krasnukha {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"}, 568fe53c49STatyana 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."}, 578fe53c49STatyana 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. " 58ac9c3a62SKate Stone "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."}, 598fe53c49STatyana 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 " 60ac9c3a62SKate Stone "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."}, 618fe53c49STatyana 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 " 62ac9c3a62SKate Stone "setting is used." }, 638fe53c49STatyana 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." }, 648fe53c49STatyana 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."}, 658fe53c49STatyana 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 " 660354a688SSean Callanan "context. Allows declaration of persistent, top-level entities without a $ prefix."}, 678fe53c49STatyana 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 " 68ac9c3a62SKate Stone "the interpreter (defaults to true)."} 69ac9c3a62SKate Stone // clang-format on 701deb7962SGreg Clayton }; 711deb7962SGreg Clayton 7297206d57SZachary Turner Status CommandObjectExpression::CommandOptions::SetOptionValue( 738cef4b0bSZachary Turner uint32_t option_idx, llvm::StringRef option_arg, 74b9c1b51eSKate Stone ExecutionContext *execution_context) { 7597206d57SZachary Turner Status error; 7630fdc8d8SChris Lattner 771f0f5b5bSZachary Turner const int short_option = GetDefinitions()[option_idx].short_option; 7830fdc8d8SChris Lattner 79b9c1b51eSKate Stone switch (short_option) { 8015663c53SDawn Perchik case 'l': 810e0984eeSJim Ingham language = Language::GetLanguageTypeFromString(option_arg); 8215663c53SDawn Perchik if (language == eLanguageTypeUnknown) 83b9c1b51eSKate Stone error.SetErrorStringWithFormat( 848cef4b0bSZachary Turner "unknown language type: '%s' for expression", 858cef4b0bSZachary Turner option_arg.str().c_str()); 8615663c53SDawn Perchik break; 8730fdc8d8SChris Lattner 88b9c1b51eSKate Stone case 'a': { 8935e1bda6SJim Ingham bool success; 9035e1bda6SJim Ingham bool result; 9147cbf4a0SPavel Labath result = OptionArgParser::ToBoolean(option_arg, true, &success); 9235e1bda6SJim Ingham if (!success) 93b9c1b51eSKate Stone error.SetErrorStringWithFormat( 948cef4b0bSZachary Turner "invalid all-threads value setting: \"%s\"", 958cef4b0bSZachary Turner option_arg.str().c_str()); 9635e1bda6SJim Ingham else 9735e1bda6SJim Ingham try_all_threads = result; 98b9c1b51eSKate Stone } break; 996c68fb45SJim Ingham 100b9c1b51eSKate Stone case 'i': { 101184e9811SJim Ingham bool success; 10247cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 103184e9811SJim Ingham if (success) 104184e9811SJim Ingham ignore_breakpoints = tmp_value; 105184e9811SJim Ingham else 106b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1078cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1088cef4b0bSZachary Turner option_arg.str().c_str()); 109184e9811SJim Ingham break; 110184e9811SJim Ingham } 1113fe71581SMarianne Mailhot-Sarrasin 112b9c1b51eSKate Stone case 'j': { 1133fe71581SMarianne Mailhot-Sarrasin bool success; 11447cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 1153fe71581SMarianne Mailhot-Sarrasin if (success) 1163fe71581SMarianne Mailhot-Sarrasin allow_jit = tmp_value; 1173fe71581SMarianne Mailhot-Sarrasin else 118b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1198cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1208cef4b0bSZachary Turner option_arg.str().c_str()); 1213fe71581SMarianne Mailhot-Sarrasin break; 1223fe71581SMarianne Mailhot-Sarrasin } 1233fe71581SMarianne Mailhot-Sarrasin 1248cef4b0bSZachary Turner case 't': 1258cef4b0bSZachary Turner if (option_arg.getAsInteger(0, timeout)) { 1268cef4b0bSZachary Turner timeout = 0; 127b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid timeout setting \"%s\"", 1288cef4b0bSZachary Turner option_arg.str().c_str()); 1298cef4b0bSZachary Turner } 1308cef4b0bSZachary Turner break; 13135e1bda6SJim Ingham 132b9c1b51eSKate Stone case 'u': { 133399f1cafSJim Ingham bool success; 13447cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 135184e9811SJim Ingham if (success) 136184e9811SJim Ingham unwind_on_error = tmp_value; 137184e9811SJim Ingham else 138b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1398cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1408cef4b0bSZachary Turner option_arg.str().c_str()); 141399f1cafSJim Ingham break; 1423bfdaa2aSSean Callanan } 1434d93b8cdSEnrico Granata 1444d93b8cdSEnrico Granata case 'v': 145543a26e9SEnrico Granata if (option_arg.empty()) { 1464d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 1474d93b8cdSEnrico Granata break; 1484d93b8cdSEnrico Granata } 14947cbf4a0SPavel Labath m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) 15047cbf4a0SPavel Labath OptionArgParser::ToOptionEnum( 1511f0f5b5bSZachary Turner option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 1524d93b8cdSEnrico Granata if (!error.Success()) 153b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1548cef4b0bSZachary Turner "unrecognized value for description-verbosity '%s'", 1558cef4b0bSZachary Turner option_arg.str().c_str()); 1564d93b8cdSEnrico Granata break; 1574d93b8cdSEnrico Granata 15862afb9f6SGreg Clayton case 'g': 15962afb9f6SGreg Clayton debug = true; 16062afb9f6SGreg Clayton unwind_on_error = false; 16162afb9f6SGreg Clayton ignore_breakpoints = false; 16262afb9f6SGreg Clayton break; 16362afb9f6SGreg Clayton 164863fab69SSean Callanan case 'p': 165863fab69SSean Callanan top_level = true; 166863fab69SSean Callanan break; 167863fab69SSean Callanan 168b9c1b51eSKate Stone case 'X': { 169a1e541bfSJim Ingham bool success; 17047cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 171a1e541bfSJim Ingham if (success) 172a1e541bfSJim Ingham auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; 173a1e541bfSJim Ingham else 174b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1758cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1768cef4b0bSZachary Turner option_arg.str().c_str()); 177a1e541bfSJim Ingham break; 178a1e541bfSJim Ingham } 179a1e541bfSJim Ingham 18030fdc8d8SChris Lattner default: 181b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid short option character '%c'", 182b9c1b51eSKate Stone short_option); 18330fdc8d8SChris Lattner break; 18430fdc8d8SChris Lattner } 18530fdc8d8SChris Lattner 18630fdc8d8SChris Lattner return error; 18730fdc8d8SChris Lattner } 18830fdc8d8SChris Lattner 189b9c1b51eSKate Stone void CommandObjectExpression::CommandOptions::OptionParsingStarting( 190b9c1b51eSKate Stone ExecutionContext *execution_context) { 191e1cfbc79STodd Fiala auto process_sp = 192e1cfbc79STodd Fiala execution_context ? execution_context->GetProcessSP() : ProcessSP(); 193b9c1b51eSKate Stone if (process_sp) { 194e1cfbc79STodd Fiala ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); 195e1cfbc79STodd Fiala unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); 196b9c1b51eSKate Stone } else { 197fc03f8fcSGreg Clayton ignore_breakpoints = true; 198399f1cafSJim Ingham unwind_on_error = true; 199184e9811SJim Ingham } 200184e9811SJim Ingham 20130fdc8d8SChris Lattner show_summary = true; 20235e1bda6SJim Ingham try_all_threads = true; 20335e1bda6SJim Ingham timeout = 0; 20462afb9f6SGreg Clayton debug = false; 20515663c53SDawn Perchik language = eLanguageTypeUnknown; 2064d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 207a1e541bfSJim Ingham auto_apply_fixits = eLazyBoolCalculate; 208863fab69SSean Callanan top_level = false; 2093fe71581SMarianne Mailhot-Sarrasin allow_jit = true; 21030fdc8d8SChris Lattner } 21130fdc8d8SChris Lattner 2121f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> 213b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::GetDefinitions() { 21470602439SZachary Turner return llvm::makeArrayRef(g_expression_options); 21530fdc8d8SChris Lattner } 21630fdc8d8SChris Lattner 217b9c1b51eSKate Stone CommandObjectExpression::CommandObjectExpression( 218b9c1b51eSKate Stone CommandInterpreter &interpreter) 2197428a18cSKate Stone : CommandObjectRaw( 220b9c1b51eSKate Stone interpreter, "expression", "Evaluate an expression on the current " 221b9c1b51eSKate Stone "thread. Displays any returned value " 222b9c1b51eSKate Stone "with LLDB's default formatting.", 223a449698cSZachary Turner "", eCommandProcessMustBePaused | eCommandTryTargetAPILock), 22444d93782SGreg Clayton IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), 225b9c1b51eSKate Stone m_option_group(), m_format_options(eFormatDefault), 226b9c1b51eSKate Stone m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, 227b9c1b51eSKate Stone true), 228b9c1b51eSKate Stone m_command_options(), m_expr_line_count(0), m_expr_lines() { 22930fdc8d8SChris Lattner SetHelpLong( 230ea671fbdSKate Stone R"( 231d0309916SJim Ingham Single and multi-line expressions: 232d0309916SJim Ingham 233d0309916SJim Ingham )" 234d0309916SJim Ingham " The expression provided on the command line must be a complete expression \ 235d0309916SJim Ingham with no newlines. To evaluate a multi-line expression, \ 236d0309916SJim Ingham hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ 237d0309916SJim Ingham Hit return on an empty line to end the multi-line expression." 238d0309916SJim Ingham 239d0309916SJim Ingham R"( 240d0309916SJim Ingham 241ea671fbdSKate Stone Timeouts: 242ea671fbdSKate Stone 243b9c1b51eSKate Stone )" 244b9c1b51eSKate Stone " If the expression can be evaluated statically (without running code) then it will be. \ 245ea671fbdSKate Stone Otherwise, by default the expression will run on the current thread with a short timeout: \ 246ea671fbdSKate Stone currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 247ea671fbdSKate Stone and resumed with all threads running. You can use the -a option to disable retrying on all \ 248b9c1b51eSKate Stone threads. You can use the -t option to set a shorter timeout." 249b9c1b51eSKate Stone R"( 250ea671fbdSKate Stone 251ea671fbdSKate Stone User defined variables: 252ea671fbdSKate Stone 253b9c1b51eSKate Stone )" 254b9c1b51eSKate Stone " You can define your own variables for convenience or to be used in subsequent expressions. \ 255ea671fbdSKate Stone You define them the same way you would define variables in C. If the first character of \ 256ea671fbdSKate Stone your user defined variable is a $, then the variable's value will be available in future \ 257b9c1b51eSKate Stone expressions, otherwise it will just be available in the current expression." 258b9c1b51eSKate Stone R"( 259ea671fbdSKate Stone 260ea671fbdSKate Stone Continuing evaluation after a breakpoint: 261ea671fbdSKate Stone 262b9c1b51eSKate Stone )" 263b9c1b51eSKate Stone " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 264ea671fbdSKate Stone you are done with your investigation, you can either remove the expression execution frames \ 265ea671fbdSKate Stone from the stack with \"thread return -x\" or if you are still interested in the expression result \ 266ea671fbdSKate Stone you can issue the \"continue\" command and the expression evaluation will complete and the \ 267ea671fbdSKate Stone expression result will be available using the \"thread.completed-expression\" key in the thread \ 268b9c1b51eSKate Stone format." 269d0309916SJim Ingham 270b9c1b51eSKate Stone R"( 271ea671fbdSKate Stone 272ea671fbdSKate Stone Examples: 273ea671fbdSKate Stone 274ea671fbdSKate Stone expr my_struct->a = my_array[3] 275ea671fbdSKate Stone expr -f bin -- (index * 8) + 5 276ea671fbdSKate Stone expr unsigned int $foo = 5 277b9c1b51eSKate Stone expr char c[] = \"foo\"; c[0])"); 278405fe67fSCaroline Tice 279405fe67fSCaroline Tice CommandArgumentEntry arg; 280405fe67fSCaroline Tice CommandArgumentData expression_arg; 281405fe67fSCaroline Tice 282405fe67fSCaroline Tice // Define the first (and only) variant of this arg. 283405fe67fSCaroline Tice expression_arg.arg_type = eArgTypeExpression; 284405fe67fSCaroline Tice expression_arg.arg_repetition = eArgRepeatPlain; 285405fe67fSCaroline Tice 286b9c1b51eSKate Stone // There is only one variant this argument could be; put it into the argument 287b9c1b51eSKate Stone // entry. 288405fe67fSCaroline Tice arg.push_back(expression_arg); 289405fe67fSCaroline Tice 290405fe67fSCaroline Tice // Push the data for the first argument into the m_arguments vector. 291405fe67fSCaroline Tice m_arguments.push_back(arg); 2921deb7962SGreg Clayton 2935009f9d5SGreg Clayton // Add the "--format" and "--gdb-format" 294b9c1b51eSKate Stone m_option_group.Append(&m_format_options, 295b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_FORMAT | 296b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_GDB_FMT, 297b9c1b51eSKate Stone LLDB_OPT_SET_1); 2981deb7962SGreg Clayton m_option_group.Append(&m_command_options); 299b9c1b51eSKate Stone m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, 300b9c1b51eSKate Stone LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 301f2bd5c3eSSean Callanan m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 3021deb7962SGreg Clayton m_option_group.Finalize(); 30330fdc8d8SChris Lattner } 30430fdc8d8SChris Lattner 305c8ecc2a9SEugene Zelenko CommandObjectExpression::~CommandObjectExpression() = default; 30630fdc8d8SChris Lattner 307b9c1b51eSKate Stone Options *CommandObjectExpression::GetOptions() { return &m_option_group; } 30830fdc8d8SChris Lattner 30974829734SRaphael Isemann int CommandObjectExpression::HandleCompletion(CompletionRequest &request) { 31074829734SRaphael Isemann EvaluateExpressionOptions options; 31174829734SRaphael Isemann options.SetCoerceToId(m_varobj_options.use_objc); 31274829734SRaphael Isemann options.SetLanguage(m_command_options.language); 31374829734SRaphael Isemann options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever); 31474829734SRaphael Isemann options.SetAutoApplyFixIts(false); 31574829734SRaphael Isemann options.SetGenerateDebugInfo(false); 31674829734SRaphael Isemann 31774829734SRaphael Isemann // We need a valid execution context with a frame pointer for this 31874829734SRaphael Isemann // completion, so if we don't have one we should try to make a valid 31974829734SRaphael Isemann // execution context. 32074829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 32174829734SRaphael Isemann m_interpreter.UpdateExecutionContext(nullptr); 32274829734SRaphael Isemann 32374829734SRaphael Isemann // This didn't work, so let's get out before we start doing things that 32474829734SRaphael Isemann // expect a valid frame pointer. 32574829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 32674829734SRaphael Isemann return 0; 32774829734SRaphael Isemann 32874829734SRaphael Isemann ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 32974829734SRaphael Isemann 33074829734SRaphael Isemann Target *target = exe_ctx.GetTargetPtr(); 33174829734SRaphael Isemann 33274829734SRaphael Isemann if (!target) 33374829734SRaphael Isemann target = GetDummyTarget(); 33474829734SRaphael Isemann 33574829734SRaphael Isemann if (!target) 33674829734SRaphael Isemann return 0; 33774829734SRaphael Isemann 33874829734SRaphael Isemann unsigned cursor_pos = request.GetRawCursorPos(); 33974829734SRaphael Isemann llvm::StringRef code = request.GetRawLine(); 34074829734SRaphael Isemann 34174829734SRaphael Isemann const std::size_t original_code_size = code.size(); 34274829734SRaphael Isemann 34374829734SRaphael Isemann // Remove the first token which is 'expr' or some alias/abbreviation of that. 34474829734SRaphael Isemann code = llvm::getToken(code).second.ltrim(); 34574829734SRaphael Isemann OptionsWithRaw args(code); 34674829734SRaphael Isemann code = args.GetRawPart(); 34774829734SRaphael Isemann 34874829734SRaphael Isemann // The position where the expression starts in the command line. 34974829734SRaphael Isemann assert(original_code_size >= code.size()); 35074829734SRaphael Isemann std::size_t raw_start = original_code_size - code.size(); 35174829734SRaphael Isemann 35274829734SRaphael Isemann // Check if the cursor is actually in the expression string, and if not, we 35374829734SRaphael Isemann // exit. 35474829734SRaphael Isemann // FIXME: We should complete the options here. 35574829734SRaphael Isemann if (cursor_pos < raw_start) 35674829734SRaphael Isemann return 0; 35774829734SRaphael Isemann 35874829734SRaphael Isemann // Make the cursor_pos again relative to the start of the code string. 35974829734SRaphael Isemann assert(cursor_pos >= raw_start); 36074829734SRaphael Isemann cursor_pos -= raw_start; 36174829734SRaphael Isemann 36274829734SRaphael Isemann auto language = exe_ctx.GetFrameRef().GetLanguage(); 36374829734SRaphael Isemann 36474829734SRaphael Isemann Status error; 36574829734SRaphael Isemann lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage( 36674829734SRaphael Isemann code, llvm::StringRef(), language, UserExpression::eResultTypeAny, 36774829734SRaphael Isemann options, error)); 36874829734SRaphael Isemann if (error.Fail()) 36974829734SRaphael Isemann return 0; 37074829734SRaphael Isemann 371c11a780eSRaphael Isemann expr->Complete(exe_ctx, request, cursor_pos); 37274829734SRaphael Isemann return request.GetNumberOfMatches(); 37374829734SRaphael Isemann } 37474829734SRaphael Isemann 37597206d57SZachary Turner static lldb_private::Status 376b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) { 377520a422bSEnrico Granata CompilerType type(valobj.GetCompilerType()); 378520a422bSEnrico Granata CompilerType pointee; 379520a422bSEnrico Granata if (!type.IsPointerType(&pointee)) 38097206d57SZachary Turner return Status("as it does not refer to a pointer"); 381520a422bSEnrico Granata if (pointee.IsVoidType()) 38297206d57SZachary Turner return Status("as it refers to a pointer to void"); 38397206d57SZachary Turner return Status(); 384520a422bSEnrico Granata } 385520a422bSEnrico Granata 3864d51a902SRaphael Isemann bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr, 3876e8dc334SCaroline Tice Stream *output_stream, 3886e8dc334SCaroline Tice Stream *error_stream, 389b9c1b51eSKate Stone CommandReturnObject *result) { 39005097246SAdrian Prantl // Don't use m_exe_ctx as this might be called asynchronously after the 39105097246SAdrian Prantl // command object DoExecute has finished when doing multi-line expression 39205097246SAdrian Prantl // that use an input reader... 393ba7b8e2cSGreg Clayton ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 394ba7b8e2cSGreg Clayton 395ba7b8e2cSGreg Clayton Target *target = exe_ctx.GetTargetPtr(); 396c0a6e061SSean Callanan 397c0a6e061SSean Callanan if (!target) 398893c932aSJim Ingham target = GetDummyTarget(); 399c0a6e061SSean Callanan 400b9c1b51eSKate Stone if (target) { 4018b2fe6dcSGreg Clayton lldb::ValueObjectSP result_valobj_sp; 40292adcac9SSean Callanan bool keep_in_memory = true; 403009d110dSDawn Perchik StackFrame *frame = exe_ctx.GetFramePtr(); 40492adcac9SSean Callanan 40535e1bda6SJim Ingham EvaluateExpressionOptions options; 4066fbc48bcSJim Ingham options.SetCoerceToId(m_varobj_options.use_objc); 4076fbc48bcSJim Ingham options.SetUnwindOnError(m_command_options.unwind_on_error); 4086fbc48bcSJim Ingham options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); 4096fbc48bcSJim Ingham options.SetKeepInMemory(keep_in_memory); 4106fbc48bcSJim Ingham options.SetUseDynamic(m_varobj_options.use_dynamic); 4116fbc48bcSJim Ingham options.SetTryAllThreads(m_command_options.try_all_threads); 4126fbc48bcSJim Ingham options.SetDebug(m_command_options.debug); 41315663c53SDawn Perchik options.SetLanguage(m_command_options.language); 414b9c1b51eSKate Stone options.SetExecutionPolicy( 415b9c1b51eSKate Stone m_command_options.allow_jit 416b9c1b51eSKate Stone ? EvaluateExpressionOptions::default_execution_policy 417b9c1b51eSKate Stone : lldb_private::eExecutionPolicyNever); 41815663c53SDawn Perchik 419a1e541bfSJim Ingham bool auto_apply_fixits; 420a1e541bfSJim Ingham if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) 421a1e541bfSJim Ingham auto_apply_fixits = target->GetEnableAutoApplyFixIts(); 422a1e541bfSJim Ingham else 423*a6682a41SJonas Devlieghere auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes; 424a1e541bfSJim Ingham 425a1e541bfSJim Ingham options.SetAutoApplyFixIts(auto_apply_fixits); 426a1e541bfSJim Ingham 427863fab69SSean Callanan if (m_command_options.top_level) 428863fab69SSean Callanan options.SetExecutionPolicy(eExecutionPolicyTopLevel); 429863fab69SSean Callanan 43005097246SAdrian Prantl // If there is any chance we are going to stop and want to see what went 43105097246SAdrian Prantl // wrong with our expression, we should generate debug info 43223f8c95aSGreg Clayton if (!m_command_options.ignore_breakpoints || 43323f8c95aSGreg Clayton !m_command_options.unwind_on_error) 43423f8c95aSGreg Clayton options.SetGenerateDebugInfo(true); 43523f8c95aSGreg Clayton 43662afb9f6SGreg Clayton if (m_command_options.timeout > 0) 43743d35418SPavel Labath options.SetTimeout(std::chrono::microseconds(m_command_options.timeout)); 4386f78f386SJim Ingham else 43943d35418SPavel Labath options.SetTimeout(llvm::None); 440d4439aa9SEnrico Granata 441b9c1b51eSKate Stone ExpressionResults success = target->EvaluateExpression( 442b9c1b51eSKate Stone expr, frame, result_valobj_sp, options, &m_fixed_expression); 443e5ee6f04SJim Ingham 444b9c1b51eSKate Stone // We only tell you about the FixIt if we applied it. The compiler errors 445b9c1b51eSKate Stone // will suggest the FixIt if it parsed. 446b9c1b51eSKate Stone if (error_stream && !m_fixed_expression.empty() && 447b9c1b51eSKate Stone target->GetEnableNotifyAboutFixIts()) { 448e5ee6f04SJim Ingham if (success == eExpressionCompleted) 449b9c1b51eSKate Stone error_stream->Printf( 450b9c1b51eSKate Stone " Fix-it applied, fixed expression was: \n %s\n", 451b9c1b51eSKate Stone m_fixed_expression.c_str()); 452e5ee6f04SJim Ingham } 4538b2fe6dcSGreg Clayton 454b9c1b51eSKate Stone if (result_valobj_sp) { 455bf154daeSSean Callanan Format format = m_format_options.GetFormat(); 456bf154daeSSean Callanan 457b9c1b51eSKate Stone if (result_valobj_sp->GetError().Success()) { 458b9c1b51eSKate Stone if (format != eFormatVoid) { 4591deb7962SGreg Clayton if (format != eFormatDefault) 4601deb7962SGreg Clayton result_valobj_sp->SetFormat(format); 46132c4085bSGreg Clayton 462b9c1b51eSKate Stone if (m_varobj_options.elem_count > 0) { 46397206d57SZachary Turner Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); 464b9c1b51eSKate Stone if (error.Fail()) { 465b9c1b51eSKate Stone result->AppendErrorWithFormat( 466b9c1b51eSKate Stone "expression cannot be used with --element-count %s\n", 467b9c1b51eSKate Stone error.AsCString("")); 468520a422bSEnrico Granata result->SetStatus(eReturnStatusFailed); 469520a422bSEnrico Granata return false; 470520a422bSEnrico Granata } 471520a422bSEnrico Granata } 472520a422bSEnrico Granata 473b9c1b51eSKate Stone DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 474b9c1b51eSKate Stone m_command_options.m_verbosity, format)); 475b9c1b51eSKate Stone options.SetVariableFormatDisplayLanguage( 476b9c1b51eSKate Stone result_valobj_sp->GetPreferredDisplayLanguage()); 477770eb05aSEnrico Granata 4784d93b8cdSEnrico Granata result_valobj_sp->Dump(*output_stream, options); 4794d93b8cdSEnrico Granata 480fcd43b71SJohnny Chen if (result) 481fcd43b71SJohnny Chen result->SetStatus(eReturnStatusSuccessFinishResult); 48230fdc8d8SChris Lattner } 483b9c1b51eSKate Stone } else { 484b9c1b51eSKate Stone if (result_valobj_sp->GetError().GetError() == 485a35912daSKrasimir Georgiev UserExpression::kNoResult) { 486b9c1b51eSKate Stone if (format != eFormatVoid && 487b9c1b51eSKate Stone m_interpreter.GetDebugger().GetNotifyVoid()) { 488bcf897faSSean Callanan error_stream->PutCString("(void)\n"); 489bcf897faSSean Callanan } 490bccce813SSean Callanan 491bccce813SSean Callanan if (result) 492bccce813SSean Callanan result->SetStatus(eReturnStatusSuccessFinishResult); 493b9c1b51eSKate Stone } else { 4945fd05903SGreg Clayton const char *error_cstr = result_valobj_sp->GetError().AsCString(); 495b9c1b51eSKate Stone if (error_cstr && error_cstr[0]) { 496c7bece56SGreg Clayton const size_t error_cstr_len = strlen(error_cstr); 497b9c1b51eSKate Stone const bool ends_with_newline = 498b9c1b51eSKate Stone error_cstr[error_cstr_len - 1] == '\n'; 4995fd05903SGreg Clayton if (strstr(error_cstr, "error:") != error_cstr) 5005fd05903SGreg Clayton error_stream->PutCString("error: "); 5015fd05903SGreg Clayton error_stream->Write(error_cstr, error_cstr_len); 5025fd05903SGreg Clayton if (!ends_with_newline) 5035fd05903SGreg Clayton error_stream->EOL(); 504b9c1b51eSKate Stone } else { 5055fd05903SGreg Clayton error_stream->PutCString("error: unknown error\n"); 5065fd05903SGreg Clayton } 5075fd05903SGreg Clayton 508fcd43b71SJohnny Chen if (result) 509b71f3844SGreg Clayton result->SetStatus(eReturnStatusFailed); 51030fdc8d8SChris Lattner } 5118b2fe6dcSGreg Clayton } 5128b2fe6dcSGreg Clayton } 513b9c1b51eSKate Stone } else { 5146e8dc334SCaroline Tice error_stream->Printf("error: invalid execution context for expression\n"); 5158b2fe6dcSGreg Clayton return false; 5168b2fe6dcSGreg Clayton } 51730fdc8d8SChris Lattner 51816ad5faeSSean Callanan return true; 51930fdc8d8SChris Lattner } 52030fdc8d8SChris Lattner 521b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, 522b9c1b51eSKate Stone std::string &line) { 52344d93782SGreg Clayton io_handler.SetIsDone(true); 524b9c1b51eSKate Stone // StreamSP output_stream = 525b9c1b51eSKate Stone // io_handler.GetDebugger().GetAsyncOutputStream(); 52644d93782SGreg Clayton // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); 52744d93782SGreg Clayton StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 52844d93782SGreg Clayton StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 52944d93782SGreg Clayton 530b9c1b51eSKate Stone EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get()); 53144d93782SGreg Clayton if (output_sp) 53244d93782SGreg Clayton output_sp->Flush(); 53344d93782SGreg Clayton if (error_sp) 53444d93782SGreg Clayton error_sp->Flush(); 53544d93782SGreg Clayton } 53644d93782SGreg Clayton 537b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, 538b9c1b51eSKate Stone StringList &lines) { 539f52c40c5SSean Callanan // An empty lines is used to indicate the end of input 540f52c40c5SSean Callanan const size_t num_lines = lines.GetSize(); 541b9c1b51eSKate Stone if (num_lines > 0 && lines[num_lines - 1].empty()) { 54205097246SAdrian Prantl // Remove the last empty line from "lines" so it doesn't appear in our 54305097246SAdrian Prantl // resulting input and return true to indicate we are done getting lines 54444d93782SGreg Clayton lines.PopBack(); 545f52c40c5SSean Callanan return true; 54644d93782SGreg Clayton } 547f52c40c5SSean Callanan return false; 54844d93782SGreg Clayton } 54944d93782SGreg Clayton 550b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() { 55130fdc8d8SChris Lattner m_expr_lines.clear(); 55230fdc8d8SChris Lattner m_expr_line_count = 0; 55330fdc8d8SChris Lattner 55444d93782SGreg Clayton Debugger &debugger = GetCommandInterpreter().GetDebugger(); 555e30f11d9SKate Stone bool color_prompt = debugger.GetUseColor(); 55644d93782SGreg Clayton const bool multiple_lines = true; // Get multiple lines 557b9c1b51eSKate Stone IOHandlerSP io_handler_sp( 558b9c1b51eSKate Stone new IOHandlerEditline(debugger, IOHandler::Type::Expression, 55944d93782SGreg Clayton "lldb-expr", // Name of input reader for history 560514d8cd8SZachary Turner llvm::StringRef(), // No prompt 561514d8cd8SZachary Turner llvm::StringRef(), // Continuation prompt 562b9c1b51eSKate Stone multiple_lines, color_prompt, 563f6913cd7SGreg Clayton 1, // Show line numbers starting at 1 56444d93782SGreg Clayton *this)); 565b6892508SGreg Clayton 566b6892508SGreg Clayton StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); 567b9c1b51eSKate Stone if (output_sp) { 568b9c1b51eSKate Stone output_sp->PutCString( 569b9c1b51eSKate Stone "Enter expressions, then terminate with an empty line to evaluate:\n"); 570b6892508SGreg Clayton output_sp->Flush(); 571b6892508SGreg Clayton } 57244d93782SGreg Clayton debugger.PushIOHandler(io_handler_sp); 573cf28a8b7SGreg Clayton } 574cf28a8b7SGreg Clayton 5754d51a902SRaphael Isemann bool CommandObjectExpression::DoExecute(llvm::StringRef command, 576b9c1b51eSKate Stone CommandReturnObject &result) { 577e5ee6f04SJim Ingham m_fixed_expression.clear(); 578e1cfbc79STodd Fiala auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); 579e1cfbc79STodd Fiala m_option_group.NotifyOptionParsingStarting(&exe_ctx); 580cf28a8b7SGreg Clayton 5814d51a902SRaphael Isemann if (command.empty()) { 582cf28a8b7SGreg Clayton GetMultilineExpression(); 58330fdc8d8SChris Lattner return result.Succeeded(); 58430fdc8d8SChris Lattner } 58530fdc8d8SChris Lattner 5863a0e1270SRaphael Isemann OptionsWithRaw args(command); 5874d51a902SRaphael Isemann llvm::StringRef expr = args.GetRawPart(); 58830fdc8d8SChris Lattner 5893a0e1270SRaphael Isemann if (args.HasArgs()) { 5903a0e1270SRaphael Isemann if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx)) 59130fdc8d8SChris Lattner return false; 592f6b8b581SGreg Clayton 593b9c1b51eSKate Stone if (m_repl_option.GetOptionValue().GetCurrentValue()) { 594f2bd5c3eSSean Callanan Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); 595b9c1b51eSKate Stone if (target) { 596f2bd5c3eSSean Callanan // Drop into REPL 597f2bd5c3eSSean Callanan m_expr_lines.clear(); 598f2bd5c3eSSean Callanan m_expr_line_count = 0; 599f2bd5c3eSSean Callanan 600f2bd5c3eSSean Callanan Debugger &debugger = target->GetDebugger(); 601f2bd5c3eSSean Callanan 602b9c1b51eSKate Stone // Check if the LLDB command interpreter is sitting on top of a REPL 60305097246SAdrian Prantl // that launched it... 6043a0e1270SRaphael Isemann if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, 6053a0e1270SRaphael Isemann IOHandler::Type::REPL)) { 606b9c1b51eSKate Stone // the LLDB command interpreter is sitting on top of a REPL that 60705097246SAdrian Prantl // launched it, so just say the command interpreter is done and 60805097246SAdrian Prantl // fall back to the existing REPL 609f2bd5c3eSSean Callanan m_interpreter.GetIOHandler(false)->SetIsDone(true); 610b9c1b51eSKate Stone } else { 611b9c1b51eSKate Stone // We are launching the REPL on top of the current LLDB command 61205097246SAdrian Prantl // interpreter, so just push one 613f2bd5c3eSSean Callanan bool initialize = false; 61497206d57SZachary Turner Status repl_error; 6153a0e1270SRaphael Isemann REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language, 6163a0e1270SRaphael Isemann nullptr, false)); 617f2bd5c3eSSean Callanan 618b9c1b51eSKate Stone if (!repl_sp) { 619f2bd5c3eSSean Callanan initialize = true; 620b9c1b51eSKate Stone repl_sp = target->GetREPL(repl_error, m_command_options.language, 621b9c1b51eSKate Stone nullptr, true); 622b9c1b51eSKate Stone if (!repl_error.Success()) { 623f2bd5c3eSSean Callanan result.SetError(repl_error); 624f2bd5c3eSSean Callanan return result.Succeeded(); 625f2bd5c3eSSean Callanan } 626f2bd5c3eSSean Callanan } 627f2bd5c3eSSean Callanan 628b9c1b51eSKate Stone if (repl_sp) { 629b9c1b51eSKate Stone if (initialize) { 630f2bd5c3eSSean Callanan repl_sp->SetCommandOptions(m_command_options); 631f2bd5c3eSSean Callanan repl_sp->SetFormatOptions(m_format_options); 632f2bd5c3eSSean Callanan repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 633f2bd5c3eSSean Callanan } 634f2bd5c3eSSean Callanan 635f2bd5c3eSSean Callanan IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); 636f2bd5c3eSSean Callanan 637f2bd5c3eSSean Callanan io_handler_sp->SetIsDone(false); 638f2bd5c3eSSean Callanan 639f2bd5c3eSSean Callanan debugger.PushIOHandler(io_handler_sp); 640b9c1b51eSKate Stone } else { 641b9c1b51eSKate Stone repl_error.SetErrorStringWithFormat( 642b9c1b51eSKate Stone "Couldn't create a REPL for %s", 643b9c1b51eSKate Stone Language::GetNameForLanguageType(m_command_options.language)); 644f2bd5c3eSSean Callanan result.SetError(repl_error); 645f2bd5c3eSSean Callanan return result.Succeeded(); 646f2bd5c3eSSean Callanan } 647f2bd5c3eSSean Callanan } 648f2bd5c3eSSean Callanan } 649f2bd5c3eSSean Callanan } 650cf28a8b7SGreg Clayton // No expression following options 6514d51a902SRaphael Isemann else if (expr.empty()) { 652cf28a8b7SGreg Clayton GetMultilineExpression(); 653cf28a8b7SGreg Clayton return result.Succeeded(); 654cf28a8b7SGreg Clayton } 65530fdc8d8SChris Lattner } 65630fdc8d8SChris Lattner 6570df817aaSDavide Italiano Target *target = GetSelectedOrDummyTarget(); 65824fff242SDavide Italiano if (EvaluateExpression(expr, &(result.GetOutputStream()), 65924fff242SDavide Italiano &(result.GetErrorStream()), &result)) { 66024fff242SDavide Italiano 661b9c1b51eSKate Stone if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) { 662e5ee6f04SJim Ingham CommandHistory &history = m_interpreter.GetCommandHistory(); 663b9c1b51eSKate Stone // FIXME: Can we figure out what the user actually typed (e.g. some alias 664b9c1b51eSKate Stone // for expr???) 665e5ee6f04SJim Ingham // If we can it would be nice to show that. 666e5ee6f04SJim Ingham std::string fixed_command("expression "); 6673a0e1270SRaphael Isemann if (args.HasArgs()) { 668e5ee6f04SJim Ingham // Add in any options that might have been in the original command: 6693a0e1270SRaphael Isemann fixed_command.append(args.GetArgStringWithDelimiter()); 670e5ee6f04SJim Ingham fixed_command.append(m_fixed_expression); 6713a0e1270SRaphael Isemann } else 6723a0e1270SRaphael Isemann fixed_command.append(m_fixed_expression); 673e5ee6f04SJim Ingham history.AppendString(fixed_command); 674e5ee6f04SJim Ingham } 67505097246SAdrian Prantl // Increment statistics to record this expression evaluation success. 67624fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionSuccessful); 677fcd43b71SJohnny Chen return true; 678e5ee6f04SJim Ingham } 679fcd43b71SJohnny Chen 68005097246SAdrian Prantl // Increment statistics to record this expression evaluation failure. 68124fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionFailure); 682fcd43b71SJohnny Chen result.SetStatus(eReturnStatusFailed); 683fcd43b71SJohnny Chen return false; 68430fdc8d8SChris Lattner } 685