130fdc8d8SChris Lattner //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===// 230fdc8d8SChris Lattner // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 630fdc8d8SChris Lattner // 730fdc8d8SChris Lattner //===----------------------------------------------------------------------===// 830fdc8d8SChris Lattner 9c8ecc2a9SEugene Zelenko #include "llvm/ADT/STLExtras.h" 10c8ecc2a9SEugene Zelenko #include "llvm/ADT/StringRef.h" 11c8ecc2a9SEugene Zelenko 12c8ecc2a9SEugene Zelenko #include "CommandObjectExpression.h" 13b9c1b51eSKate Stone #include "lldb/Core/Debugger.h" 1430fdc8d8SChris Lattner #include "lldb/Core/Value.h" 156c68fb45SJim Ingham #include "lldb/Core/ValueObjectVariable.h" 164d93b8cdSEnrico Granata #include "lldb/DataFormatters/ValueObjectPrinter.h" 1730fdc8d8SChris Lattner #include "lldb/Expression/DWARFExpression.h" 18f2bd5c3eSSean Callanan #include "lldb/Expression/REPL.h" 19b9c1b51eSKate Stone #include "lldb/Expression/UserExpression.h" 2030fdc8d8SChris Lattner #include "lldb/Host/Host.h" 213eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h" 226611103cSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h" 2330fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h" 2447cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h" 2530fdc8d8SChris Lattner #include "lldb/Symbol/ObjectFile.h" 2630fdc8d8SChris Lattner #include "lldb/Symbol/Variable.h" 27b9c1b51eSKate Stone #include "lldb/Target/Language.h" 2830fdc8d8SChris Lattner #include "lldb/Target/Process.h" 29b57e4a1bSJason Molenda #include "lldb/Target/StackFrame.h" 3030fdc8d8SChris Lattner #include "lldb/Target/Target.h" 317260f620SGreg Clayton #include "lldb/Target/Thread.h" 3230fdc8d8SChris Lattner 3330fdc8d8SChris Lattner using namespace lldb; 3430fdc8d8SChris Lattner using namespace lldb_private; 3530fdc8d8SChris Lattner 36b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {} 3730fdc8d8SChris Lattner 38c8ecc2a9SEugene Zelenko CommandObjectExpression::CommandOptions::~CommandOptions() = default; 3930fdc8d8SChris Lattner 408fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_description_verbosity_type[] = { 41*e063ecccSJonas Devlieghere { 42*e063ecccSJonas Devlieghere eLanguageRuntimeDescriptionDisplayVerbosityCompact, 43*e063ecccSJonas Devlieghere "compact", 44*e063ecccSJonas Devlieghere "Only show the description string", 45*e063ecccSJonas Devlieghere }, 46*e063ecccSJonas Devlieghere { 47*e063ecccSJonas Devlieghere eLanguageRuntimeDescriptionDisplayVerbosityFull, 48*e063ecccSJonas Devlieghere "full", 49*e063ecccSJonas Devlieghere "Show the full output, including persistent variable's name and type", 50*e063ecccSJonas Devlieghere }, 51*e063ecccSJonas Devlieghere }; 524d93b8cdSEnrico Granata 538fe53c49STatyana Krasnukha static constexpr OptionEnumValues DescriptionVerbosityTypes() { 548fe53c49STatyana Krasnukha return OptionEnumValues(g_description_verbosity_type); 558fe53c49STatyana Krasnukha } 568fe53c49STatyana Krasnukha 57ec67e734SRaphael Isemann #define LLDB_OPTIONS_expression 58ec67e734SRaphael Isemann #include "CommandOptions.inc" 591deb7962SGreg Clayton 6097206d57SZachary Turner Status CommandObjectExpression::CommandOptions::SetOptionValue( 618cef4b0bSZachary Turner uint32_t option_idx, llvm::StringRef option_arg, 62b9c1b51eSKate Stone ExecutionContext *execution_context) { 6397206d57SZachary Turner Status error; 6430fdc8d8SChris Lattner 651f0f5b5bSZachary Turner const int short_option = GetDefinitions()[option_idx].short_option; 6630fdc8d8SChris Lattner 67b9c1b51eSKate Stone switch (short_option) { 6815663c53SDawn Perchik case 'l': 690e0984eeSJim Ingham language = Language::GetLanguageTypeFromString(option_arg); 7015663c53SDawn Perchik if (language == eLanguageTypeUnknown) 71b9c1b51eSKate Stone error.SetErrorStringWithFormat( 728cef4b0bSZachary Turner "unknown language type: '%s' for expression", 738cef4b0bSZachary Turner option_arg.str().c_str()); 7415663c53SDawn Perchik break; 7530fdc8d8SChris Lattner 76b9c1b51eSKate Stone case 'a': { 7735e1bda6SJim Ingham bool success; 7835e1bda6SJim Ingham bool result; 7947cbf4a0SPavel Labath result = OptionArgParser::ToBoolean(option_arg, true, &success); 8035e1bda6SJim Ingham if (!success) 81b9c1b51eSKate Stone error.SetErrorStringWithFormat( 828cef4b0bSZachary Turner "invalid all-threads value setting: \"%s\"", 838cef4b0bSZachary Turner option_arg.str().c_str()); 8435e1bda6SJim Ingham else 8535e1bda6SJim Ingham try_all_threads = result; 86b9c1b51eSKate Stone } break; 876c68fb45SJim Ingham 88b9c1b51eSKate Stone case 'i': { 89184e9811SJim Ingham bool success; 9047cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 91184e9811SJim Ingham if (success) 92184e9811SJim Ingham ignore_breakpoints = tmp_value; 93184e9811SJim Ingham else 94b9c1b51eSKate Stone error.SetErrorStringWithFormat( 958cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 968cef4b0bSZachary Turner option_arg.str().c_str()); 97184e9811SJim Ingham break; 98184e9811SJim Ingham } 993fe71581SMarianne Mailhot-Sarrasin 100b9c1b51eSKate Stone case 'j': { 1013fe71581SMarianne Mailhot-Sarrasin bool success; 10247cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 1033fe71581SMarianne Mailhot-Sarrasin if (success) 1043fe71581SMarianne Mailhot-Sarrasin allow_jit = tmp_value; 1053fe71581SMarianne Mailhot-Sarrasin else 106b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1078cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1088cef4b0bSZachary Turner option_arg.str().c_str()); 1093fe71581SMarianne Mailhot-Sarrasin break; 1103fe71581SMarianne Mailhot-Sarrasin } 1113fe71581SMarianne Mailhot-Sarrasin 1128cef4b0bSZachary Turner case 't': 1138cef4b0bSZachary Turner if (option_arg.getAsInteger(0, timeout)) { 1148cef4b0bSZachary Turner timeout = 0; 115b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid timeout setting \"%s\"", 1168cef4b0bSZachary Turner option_arg.str().c_str()); 1178cef4b0bSZachary Turner } 1188cef4b0bSZachary Turner break; 11935e1bda6SJim Ingham 120b9c1b51eSKate Stone case 'u': { 121399f1cafSJim Ingham bool success; 12247cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 123184e9811SJim Ingham if (success) 124184e9811SJim Ingham unwind_on_error = tmp_value; 125184e9811SJim Ingham else 126b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1278cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1288cef4b0bSZachary Turner option_arg.str().c_str()); 129399f1cafSJim Ingham break; 1303bfdaa2aSSean Callanan } 1314d93b8cdSEnrico Granata 1324d93b8cdSEnrico Granata case 'v': 133543a26e9SEnrico Granata if (option_arg.empty()) { 1344d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 1354d93b8cdSEnrico Granata break; 1364d93b8cdSEnrico Granata } 13747cbf4a0SPavel Labath m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) 13847cbf4a0SPavel Labath OptionArgParser::ToOptionEnum( 1391f0f5b5bSZachary Turner option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 1404d93b8cdSEnrico Granata if (!error.Success()) 141b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1428cef4b0bSZachary Turner "unrecognized value for description-verbosity '%s'", 1438cef4b0bSZachary Turner option_arg.str().c_str()); 1444d93b8cdSEnrico Granata break; 1454d93b8cdSEnrico Granata 14662afb9f6SGreg Clayton case 'g': 14762afb9f6SGreg Clayton debug = true; 14862afb9f6SGreg Clayton unwind_on_error = false; 14962afb9f6SGreg Clayton ignore_breakpoints = false; 15062afb9f6SGreg Clayton break; 15162afb9f6SGreg Clayton 152863fab69SSean Callanan case 'p': 153863fab69SSean Callanan top_level = true; 154863fab69SSean Callanan break; 155863fab69SSean Callanan 156b9c1b51eSKate Stone case 'X': { 157a1e541bfSJim Ingham bool success; 15847cbf4a0SPavel Labath bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 159a1e541bfSJim Ingham if (success) 160a1e541bfSJim Ingham auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; 161a1e541bfSJim Ingham else 162b9c1b51eSKate Stone error.SetErrorStringWithFormat( 1638cef4b0bSZachary Turner "could not convert \"%s\" to a boolean value.", 1648cef4b0bSZachary Turner option_arg.str().c_str()); 165a1e541bfSJim Ingham break; 166a1e541bfSJim Ingham } 167a1e541bfSJim Ingham 16830fdc8d8SChris Lattner default: 169b9c1b51eSKate Stone error.SetErrorStringWithFormat("invalid short option character '%c'", 170b9c1b51eSKate Stone short_option); 17130fdc8d8SChris Lattner break; 17230fdc8d8SChris Lattner } 17330fdc8d8SChris Lattner 17430fdc8d8SChris Lattner return error; 17530fdc8d8SChris Lattner } 17630fdc8d8SChris Lattner 177b9c1b51eSKate Stone void CommandObjectExpression::CommandOptions::OptionParsingStarting( 178b9c1b51eSKate Stone ExecutionContext *execution_context) { 179e1cfbc79STodd Fiala auto process_sp = 180e1cfbc79STodd Fiala execution_context ? execution_context->GetProcessSP() : ProcessSP(); 181b9c1b51eSKate Stone if (process_sp) { 182e1cfbc79STodd Fiala ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); 183e1cfbc79STodd Fiala unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); 184b9c1b51eSKate Stone } else { 185fc03f8fcSGreg Clayton ignore_breakpoints = true; 186399f1cafSJim Ingham unwind_on_error = true; 187184e9811SJim Ingham } 188184e9811SJim Ingham 18930fdc8d8SChris Lattner show_summary = true; 19035e1bda6SJim Ingham try_all_threads = true; 19135e1bda6SJim Ingham timeout = 0; 19262afb9f6SGreg Clayton debug = false; 19315663c53SDawn Perchik language = eLanguageTypeUnknown; 1944d93b8cdSEnrico Granata m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 195a1e541bfSJim Ingham auto_apply_fixits = eLazyBoolCalculate; 196863fab69SSean Callanan top_level = false; 1973fe71581SMarianne Mailhot-Sarrasin allow_jit = true; 19830fdc8d8SChris Lattner } 19930fdc8d8SChris Lattner 2001f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> 201b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::GetDefinitions() { 20270602439SZachary Turner return llvm::makeArrayRef(g_expression_options); 20330fdc8d8SChris Lattner } 20430fdc8d8SChris Lattner 205b9c1b51eSKate Stone CommandObjectExpression::CommandObjectExpression( 206b9c1b51eSKate Stone CommandInterpreter &interpreter) 2077428a18cSKate Stone : CommandObjectRaw( 208b9c1b51eSKate Stone interpreter, "expression", "Evaluate an expression on the current " 209b9c1b51eSKate Stone "thread. Displays any returned value " 210b9c1b51eSKate Stone "with LLDB's default formatting.", 211a449698cSZachary Turner "", eCommandProcessMustBePaused | eCommandTryTargetAPILock), 21244d93782SGreg Clayton IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), 213b9c1b51eSKate Stone m_option_group(), m_format_options(eFormatDefault), 214b9c1b51eSKate Stone m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, 215b9c1b51eSKate Stone true), 216b9c1b51eSKate Stone m_command_options(), m_expr_line_count(0), m_expr_lines() { 21730fdc8d8SChris Lattner SetHelpLong( 218ea671fbdSKate Stone R"( 219d0309916SJim Ingham Single and multi-line expressions: 220d0309916SJim Ingham 221d0309916SJim Ingham )" 222d0309916SJim Ingham " The expression provided on the command line must be a complete expression \ 223d0309916SJim Ingham with no newlines. To evaluate a multi-line expression, \ 224d0309916SJim Ingham hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ 225d0309916SJim Ingham Hit return on an empty line to end the multi-line expression." 226d0309916SJim Ingham 227d0309916SJim Ingham R"( 228d0309916SJim Ingham 229ea671fbdSKate Stone Timeouts: 230ea671fbdSKate Stone 231b9c1b51eSKate Stone )" 232b9c1b51eSKate Stone " If the expression can be evaluated statically (without running code) then it will be. \ 233ea671fbdSKate Stone Otherwise, by default the expression will run on the current thread with a short timeout: \ 234ea671fbdSKate Stone currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 235ea671fbdSKate Stone and resumed with all threads running. You can use the -a option to disable retrying on all \ 236b9c1b51eSKate Stone threads. You can use the -t option to set a shorter timeout." 237b9c1b51eSKate Stone R"( 238ea671fbdSKate Stone 239ea671fbdSKate Stone User defined variables: 240ea671fbdSKate Stone 241b9c1b51eSKate Stone )" 242b9c1b51eSKate Stone " You can define your own variables for convenience or to be used in subsequent expressions. \ 243ea671fbdSKate Stone You define them the same way you would define variables in C. If the first character of \ 244ea671fbdSKate Stone your user defined variable is a $, then the variable's value will be available in future \ 245b9c1b51eSKate Stone expressions, otherwise it will just be available in the current expression." 246b9c1b51eSKate Stone R"( 247ea671fbdSKate Stone 248ea671fbdSKate Stone Continuing evaluation after a breakpoint: 249ea671fbdSKate Stone 250b9c1b51eSKate Stone )" 251b9c1b51eSKate Stone " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 252ea671fbdSKate Stone you are done with your investigation, you can either remove the expression execution frames \ 253ea671fbdSKate Stone from the stack with \"thread return -x\" or if you are still interested in the expression result \ 254ea671fbdSKate Stone you can issue the \"continue\" command and the expression evaluation will complete and the \ 255ea671fbdSKate Stone expression result will be available using the \"thread.completed-expression\" key in the thread \ 256b9c1b51eSKate Stone format." 257d0309916SJim Ingham 258b9c1b51eSKate Stone R"( 259ea671fbdSKate Stone 260ea671fbdSKate Stone Examples: 261ea671fbdSKate Stone 262ea671fbdSKate Stone expr my_struct->a = my_array[3] 263ea671fbdSKate Stone expr -f bin -- (index * 8) + 5 264ea671fbdSKate Stone expr unsigned int $foo = 5 265b9c1b51eSKate Stone expr char c[] = \"foo\"; c[0])"); 266405fe67fSCaroline Tice 267405fe67fSCaroline Tice CommandArgumentEntry arg; 268405fe67fSCaroline Tice CommandArgumentData expression_arg; 269405fe67fSCaroline Tice 270405fe67fSCaroline Tice // Define the first (and only) variant of this arg. 271405fe67fSCaroline Tice expression_arg.arg_type = eArgTypeExpression; 272405fe67fSCaroline Tice expression_arg.arg_repetition = eArgRepeatPlain; 273405fe67fSCaroline Tice 274b9c1b51eSKate Stone // There is only one variant this argument could be; put it into the argument 275b9c1b51eSKate Stone // entry. 276405fe67fSCaroline Tice arg.push_back(expression_arg); 277405fe67fSCaroline Tice 278405fe67fSCaroline Tice // Push the data for the first argument into the m_arguments vector. 279405fe67fSCaroline Tice m_arguments.push_back(arg); 2801deb7962SGreg Clayton 2815009f9d5SGreg Clayton // Add the "--format" and "--gdb-format" 282b9c1b51eSKate Stone m_option_group.Append(&m_format_options, 283b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_FORMAT | 284b9c1b51eSKate Stone OptionGroupFormat::OPTION_GROUP_GDB_FMT, 285b9c1b51eSKate Stone LLDB_OPT_SET_1); 2861deb7962SGreg Clayton m_option_group.Append(&m_command_options); 287b9c1b51eSKate Stone m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, 288b9c1b51eSKate Stone LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 289f2bd5c3eSSean Callanan m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 2901deb7962SGreg Clayton m_option_group.Finalize(); 29130fdc8d8SChris Lattner } 29230fdc8d8SChris Lattner 293c8ecc2a9SEugene Zelenko CommandObjectExpression::~CommandObjectExpression() = default; 29430fdc8d8SChris Lattner 295b9c1b51eSKate Stone Options *CommandObjectExpression::GetOptions() { return &m_option_group; } 29630fdc8d8SChris Lattner 29774829734SRaphael Isemann int CommandObjectExpression::HandleCompletion(CompletionRequest &request) { 29874829734SRaphael Isemann EvaluateExpressionOptions options; 29974829734SRaphael Isemann options.SetCoerceToId(m_varobj_options.use_objc); 30074829734SRaphael Isemann options.SetLanguage(m_command_options.language); 30174829734SRaphael Isemann options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever); 30274829734SRaphael Isemann options.SetAutoApplyFixIts(false); 30374829734SRaphael Isemann options.SetGenerateDebugInfo(false); 30474829734SRaphael Isemann 30574829734SRaphael Isemann // We need a valid execution context with a frame pointer for this 30674829734SRaphael Isemann // completion, so if we don't have one we should try to make a valid 30774829734SRaphael Isemann // execution context. 30874829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 30974829734SRaphael Isemann m_interpreter.UpdateExecutionContext(nullptr); 31074829734SRaphael Isemann 31174829734SRaphael Isemann // This didn't work, so let's get out before we start doing things that 31274829734SRaphael Isemann // expect a valid frame pointer. 31374829734SRaphael Isemann if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 31474829734SRaphael Isemann return 0; 31574829734SRaphael Isemann 31674829734SRaphael Isemann ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 31774829734SRaphael Isemann 31874829734SRaphael Isemann Target *target = exe_ctx.GetTargetPtr(); 31974829734SRaphael Isemann 32074829734SRaphael Isemann if (!target) 32174829734SRaphael Isemann target = GetDummyTarget(); 32274829734SRaphael Isemann 32374829734SRaphael Isemann if (!target) 32474829734SRaphael Isemann return 0; 32574829734SRaphael Isemann 32674829734SRaphael Isemann unsigned cursor_pos = request.GetRawCursorPos(); 32774829734SRaphael Isemann llvm::StringRef code = request.GetRawLine(); 32874829734SRaphael Isemann 32974829734SRaphael Isemann const std::size_t original_code_size = code.size(); 33074829734SRaphael Isemann 33174829734SRaphael Isemann // Remove the first token which is 'expr' or some alias/abbreviation of that. 33274829734SRaphael Isemann code = llvm::getToken(code).second.ltrim(); 33374829734SRaphael Isemann OptionsWithRaw args(code); 33474829734SRaphael Isemann code = args.GetRawPart(); 33574829734SRaphael Isemann 33674829734SRaphael Isemann // The position where the expression starts in the command line. 33774829734SRaphael Isemann assert(original_code_size >= code.size()); 33874829734SRaphael Isemann std::size_t raw_start = original_code_size - code.size(); 33974829734SRaphael Isemann 34074829734SRaphael Isemann // Check if the cursor is actually in the expression string, and if not, we 34174829734SRaphael Isemann // exit. 34274829734SRaphael Isemann // FIXME: We should complete the options here. 34374829734SRaphael Isemann if (cursor_pos < raw_start) 34474829734SRaphael Isemann return 0; 34574829734SRaphael Isemann 34674829734SRaphael Isemann // Make the cursor_pos again relative to the start of the code string. 34774829734SRaphael Isemann assert(cursor_pos >= raw_start); 34874829734SRaphael Isemann cursor_pos -= raw_start; 34974829734SRaphael Isemann 35074829734SRaphael Isemann auto language = exe_ctx.GetFrameRef().GetLanguage(); 35174829734SRaphael Isemann 35274829734SRaphael Isemann Status error; 35374829734SRaphael Isemann lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage( 35474829734SRaphael Isemann code, llvm::StringRef(), language, UserExpression::eResultTypeAny, 35540624a08SAleksandr Urakov options, nullptr, error)); 35674829734SRaphael Isemann if (error.Fail()) 35774829734SRaphael Isemann return 0; 35874829734SRaphael Isemann 359c11a780eSRaphael Isemann expr->Complete(exe_ctx, request, cursor_pos); 36074829734SRaphael Isemann return request.GetNumberOfMatches(); 36174829734SRaphael Isemann } 36274829734SRaphael Isemann 36397206d57SZachary Turner static lldb_private::Status 364b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) { 365520a422bSEnrico Granata CompilerType type(valobj.GetCompilerType()); 366520a422bSEnrico Granata CompilerType pointee; 367520a422bSEnrico Granata if (!type.IsPointerType(&pointee)) 36897206d57SZachary Turner return Status("as it does not refer to a pointer"); 369520a422bSEnrico Granata if (pointee.IsVoidType()) 37097206d57SZachary Turner return Status("as it refers to a pointer to void"); 37197206d57SZachary Turner return Status(); 372520a422bSEnrico Granata } 373520a422bSEnrico Granata 3744d51a902SRaphael Isemann bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr, 3756e8dc334SCaroline Tice Stream *output_stream, 3766e8dc334SCaroline Tice Stream *error_stream, 377b9c1b51eSKate Stone CommandReturnObject *result) { 37805097246SAdrian Prantl // Don't use m_exe_ctx as this might be called asynchronously after the 37905097246SAdrian Prantl // command object DoExecute has finished when doing multi-line expression 38005097246SAdrian Prantl // that use an input reader... 381ba7b8e2cSGreg Clayton ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 382ba7b8e2cSGreg Clayton 383ba7b8e2cSGreg Clayton Target *target = exe_ctx.GetTargetPtr(); 384c0a6e061SSean Callanan 385c0a6e061SSean Callanan if (!target) 386893c932aSJim Ingham target = GetDummyTarget(); 387c0a6e061SSean Callanan 388b9c1b51eSKate Stone if (target) { 3898b2fe6dcSGreg Clayton lldb::ValueObjectSP result_valobj_sp; 39092adcac9SSean Callanan bool keep_in_memory = true; 391009d110dSDawn Perchik StackFrame *frame = exe_ctx.GetFramePtr(); 39292adcac9SSean Callanan 39335e1bda6SJim Ingham EvaluateExpressionOptions options; 3946fbc48bcSJim Ingham options.SetCoerceToId(m_varobj_options.use_objc); 3956fbc48bcSJim Ingham options.SetUnwindOnError(m_command_options.unwind_on_error); 3966fbc48bcSJim Ingham options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); 3976fbc48bcSJim Ingham options.SetKeepInMemory(keep_in_memory); 3986fbc48bcSJim Ingham options.SetUseDynamic(m_varobj_options.use_dynamic); 3996fbc48bcSJim Ingham options.SetTryAllThreads(m_command_options.try_all_threads); 4006fbc48bcSJim Ingham options.SetDebug(m_command_options.debug); 40115663c53SDawn Perchik options.SetLanguage(m_command_options.language); 402b9c1b51eSKate Stone options.SetExecutionPolicy( 403b9c1b51eSKate Stone m_command_options.allow_jit 404b9c1b51eSKate Stone ? EvaluateExpressionOptions::default_execution_policy 405b9c1b51eSKate Stone : lldb_private::eExecutionPolicyNever); 40615663c53SDawn Perchik 407a1e541bfSJim Ingham bool auto_apply_fixits; 408a1e541bfSJim Ingham if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) 409a1e541bfSJim Ingham auto_apply_fixits = target->GetEnableAutoApplyFixIts(); 410a1e541bfSJim Ingham else 411a6682a41SJonas Devlieghere auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes; 412a1e541bfSJim Ingham 413a1e541bfSJim Ingham options.SetAutoApplyFixIts(auto_apply_fixits); 414a1e541bfSJim Ingham 415863fab69SSean Callanan if (m_command_options.top_level) 416863fab69SSean Callanan options.SetExecutionPolicy(eExecutionPolicyTopLevel); 417863fab69SSean Callanan 41805097246SAdrian Prantl // If there is any chance we are going to stop and want to see what went 41905097246SAdrian Prantl // wrong with our expression, we should generate debug info 42023f8c95aSGreg Clayton if (!m_command_options.ignore_breakpoints || 42123f8c95aSGreg Clayton !m_command_options.unwind_on_error) 42223f8c95aSGreg Clayton options.SetGenerateDebugInfo(true); 42323f8c95aSGreg Clayton 42462afb9f6SGreg Clayton if (m_command_options.timeout > 0) 42543d35418SPavel Labath options.SetTimeout(std::chrono::microseconds(m_command_options.timeout)); 4266f78f386SJim Ingham else 42743d35418SPavel Labath options.SetTimeout(llvm::None); 428d4439aa9SEnrico Granata 429b9c1b51eSKate Stone ExpressionResults success = target->EvaluateExpression( 430b9c1b51eSKate Stone expr, frame, result_valobj_sp, options, &m_fixed_expression); 431e5ee6f04SJim Ingham 432b9c1b51eSKate Stone // We only tell you about the FixIt if we applied it. The compiler errors 433b9c1b51eSKate Stone // will suggest the FixIt if it parsed. 434b9c1b51eSKate Stone if (error_stream && !m_fixed_expression.empty() && 435b9c1b51eSKate Stone target->GetEnableNotifyAboutFixIts()) { 436e5ee6f04SJim Ingham if (success == eExpressionCompleted) 437b9c1b51eSKate Stone error_stream->Printf( 438b9c1b51eSKate Stone " Fix-it applied, fixed expression was: \n %s\n", 439b9c1b51eSKate Stone m_fixed_expression.c_str()); 440e5ee6f04SJim Ingham } 4418b2fe6dcSGreg Clayton 442b9c1b51eSKate Stone if (result_valobj_sp) { 443bf154daeSSean Callanan Format format = m_format_options.GetFormat(); 444bf154daeSSean Callanan 445b9c1b51eSKate Stone if (result_valobj_sp->GetError().Success()) { 446b9c1b51eSKate Stone if (format != eFormatVoid) { 4471deb7962SGreg Clayton if (format != eFormatDefault) 4481deb7962SGreg Clayton result_valobj_sp->SetFormat(format); 44932c4085bSGreg Clayton 450b9c1b51eSKate Stone if (m_varobj_options.elem_count > 0) { 45197206d57SZachary Turner Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); 452b9c1b51eSKate Stone if (error.Fail()) { 453b9c1b51eSKate Stone result->AppendErrorWithFormat( 454b9c1b51eSKate Stone "expression cannot be used with --element-count %s\n", 455b9c1b51eSKate Stone error.AsCString("")); 456520a422bSEnrico Granata result->SetStatus(eReturnStatusFailed); 457520a422bSEnrico Granata return false; 458520a422bSEnrico Granata } 459520a422bSEnrico Granata } 460520a422bSEnrico Granata 461b9c1b51eSKate Stone DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 462b9c1b51eSKate Stone m_command_options.m_verbosity, format)); 463b9c1b51eSKate Stone options.SetVariableFormatDisplayLanguage( 464b9c1b51eSKate Stone result_valobj_sp->GetPreferredDisplayLanguage()); 465770eb05aSEnrico Granata 4664d93b8cdSEnrico Granata result_valobj_sp->Dump(*output_stream, options); 4674d93b8cdSEnrico Granata 468fcd43b71SJohnny Chen if (result) 469fcd43b71SJohnny Chen result->SetStatus(eReturnStatusSuccessFinishResult); 47030fdc8d8SChris Lattner } 471b9c1b51eSKate Stone } else { 472b9c1b51eSKate Stone if (result_valobj_sp->GetError().GetError() == 473a35912daSKrasimir Georgiev UserExpression::kNoResult) { 47457179860SJonas Devlieghere if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) { 475bcf897faSSean Callanan error_stream->PutCString("(void)\n"); 476bcf897faSSean Callanan } 477bccce813SSean Callanan 478bccce813SSean Callanan if (result) 479bccce813SSean Callanan result->SetStatus(eReturnStatusSuccessFinishResult); 480b9c1b51eSKate Stone } else { 4815fd05903SGreg Clayton const char *error_cstr = result_valobj_sp->GetError().AsCString(); 482b9c1b51eSKate Stone if (error_cstr && error_cstr[0]) { 483c7bece56SGreg Clayton const size_t error_cstr_len = strlen(error_cstr); 484b9c1b51eSKate Stone const bool ends_with_newline = 485b9c1b51eSKate Stone error_cstr[error_cstr_len - 1] == '\n'; 4865fd05903SGreg Clayton if (strstr(error_cstr, "error:") != error_cstr) 4875fd05903SGreg Clayton error_stream->PutCString("error: "); 4885fd05903SGreg Clayton error_stream->Write(error_cstr, error_cstr_len); 4895fd05903SGreg Clayton if (!ends_with_newline) 4905fd05903SGreg Clayton error_stream->EOL(); 491b9c1b51eSKate Stone } else { 4925fd05903SGreg Clayton error_stream->PutCString("error: unknown error\n"); 4935fd05903SGreg Clayton } 4945fd05903SGreg Clayton 495fcd43b71SJohnny Chen if (result) 496b71f3844SGreg Clayton result->SetStatus(eReturnStatusFailed); 49730fdc8d8SChris Lattner } 4988b2fe6dcSGreg Clayton } 4998b2fe6dcSGreg Clayton } 500b9c1b51eSKate Stone } else { 5016e8dc334SCaroline Tice error_stream->Printf("error: invalid execution context for expression\n"); 5028b2fe6dcSGreg Clayton return false; 5038b2fe6dcSGreg Clayton } 50430fdc8d8SChris Lattner 50516ad5faeSSean Callanan return true; 50630fdc8d8SChris Lattner } 50730fdc8d8SChris Lattner 508b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, 509b9c1b51eSKate Stone std::string &line) { 51044d93782SGreg Clayton io_handler.SetIsDone(true); 511b9c1b51eSKate Stone // StreamSP output_stream = 512b9c1b51eSKate Stone // io_handler.GetDebugger().GetAsyncOutputStream(); 51344d93782SGreg Clayton // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); 51444d93782SGreg Clayton StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 51544d93782SGreg Clayton StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 51644d93782SGreg Clayton 517b9c1b51eSKate Stone EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get()); 51844d93782SGreg Clayton if (output_sp) 51944d93782SGreg Clayton output_sp->Flush(); 52044d93782SGreg Clayton if (error_sp) 52144d93782SGreg Clayton error_sp->Flush(); 52244d93782SGreg Clayton } 52344d93782SGreg Clayton 524b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, 525b9c1b51eSKate Stone StringList &lines) { 526f52c40c5SSean Callanan // An empty lines is used to indicate the end of input 527f52c40c5SSean Callanan const size_t num_lines = lines.GetSize(); 528b9c1b51eSKate Stone if (num_lines > 0 && lines[num_lines - 1].empty()) { 52905097246SAdrian Prantl // Remove the last empty line from "lines" so it doesn't appear in our 53005097246SAdrian Prantl // resulting input and return true to indicate we are done getting lines 53144d93782SGreg Clayton lines.PopBack(); 532f52c40c5SSean Callanan return true; 53344d93782SGreg Clayton } 534f52c40c5SSean Callanan return false; 53544d93782SGreg Clayton } 53644d93782SGreg Clayton 537b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() { 53830fdc8d8SChris Lattner m_expr_lines.clear(); 53930fdc8d8SChris Lattner m_expr_line_count = 0; 54030fdc8d8SChris Lattner 54144d93782SGreg Clayton Debugger &debugger = GetCommandInterpreter().GetDebugger(); 542e30f11d9SKate Stone bool color_prompt = debugger.GetUseColor(); 54344d93782SGreg Clayton const bool multiple_lines = true; // Get multiple lines 544b9c1b51eSKate Stone IOHandlerSP io_handler_sp( 545b9c1b51eSKate Stone new IOHandlerEditline(debugger, IOHandler::Type::Expression, 54644d93782SGreg Clayton "lldb-expr", // Name of input reader for history 547514d8cd8SZachary Turner llvm::StringRef(), // No prompt 548514d8cd8SZachary Turner llvm::StringRef(), // Continuation prompt 549b9c1b51eSKate Stone multiple_lines, color_prompt, 550f6913cd7SGreg Clayton 1, // Show line numbers starting at 1 551d77c2e09SJonas Devlieghere *this, nullptr)); 552b6892508SGreg Clayton 553b6892508SGreg Clayton StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); 554b9c1b51eSKate Stone if (output_sp) { 555b9c1b51eSKate Stone output_sp->PutCString( 556b9c1b51eSKate Stone "Enter expressions, then terminate with an empty line to evaluate:\n"); 557b6892508SGreg Clayton output_sp->Flush(); 558b6892508SGreg Clayton } 55944d93782SGreg Clayton debugger.PushIOHandler(io_handler_sp); 560cf28a8b7SGreg Clayton } 561cf28a8b7SGreg Clayton 562c5bfa3daSJonas Devlieghere static EvaluateExpressionOptions 563c5bfa3daSJonas Devlieghere GetExprOptions(ExecutionContext &ctx, 564c5bfa3daSJonas Devlieghere CommandObjectExpression::CommandOptions command_options) { 565c5bfa3daSJonas Devlieghere command_options.OptionParsingStarting(&ctx); 566c5bfa3daSJonas Devlieghere 567c5bfa3daSJonas Devlieghere // Default certain settings for REPL regardless of the global settings. 568c5bfa3daSJonas Devlieghere command_options.unwind_on_error = false; 569c5bfa3daSJonas Devlieghere command_options.ignore_breakpoints = false; 570c5bfa3daSJonas Devlieghere command_options.debug = false; 571c5bfa3daSJonas Devlieghere 572c5bfa3daSJonas Devlieghere EvaluateExpressionOptions expr_options; 573c5bfa3daSJonas Devlieghere expr_options.SetUnwindOnError(command_options.unwind_on_error); 574c5bfa3daSJonas Devlieghere expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints); 575c5bfa3daSJonas Devlieghere expr_options.SetTryAllThreads(command_options.try_all_threads); 576c5bfa3daSJonas Devlieghere 577c5bfa3daSJonas Devlieghere if (command_options.timeout > 0) 578c5bfa3daSJonas Devlieghere expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout)); 579c5bfa3daSJonas Devlieghere else 580c5bfa3daSJonas Devlieghere expr_options.SetTimeout(llvm::None); 581c5bfa3daSJonas Devlieghere 582c5bfa3daSJonas Devlieghere return expr_options; 583c5bfa3daSJonas Devlieghere } 584c5bfa3daSJonas Devlieghere 5854d51a902SRaphael Isemann bool CommandObjectExpression::DoExecute(llvm::StringRef command, 586b9c1b51eSKate Stone CommandReturnObject &result) { 587e5ee6f04SJim Ingham m_fixed_expression.clear(); 588e1cfbc79STodd Fiala auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); 589e1cfbc79STodd Fiala m_option_group.NotifyOptionParsingStarting(&exe_ctx); 590cf28a8b7SGreg Clayton 5914d51a902SRaphael Isemann if (command.empty()) { 592cf28a8b7SGreg Clayton GetMultilineExpression(); 59330fdc8d8SChris Lattner return result.Succeeded(); 59430fdc8d8SChris Lattner } 59530fdc8d8SChris Lattner 5963a0e1270SRaphael Isemann OptionsWithRaw args(command); 5974d51a902SRaphael Isemann llvm::StringRef expr = args.GetRawPart(); 59830fdc8d8SChris Lattner 5993a0e1270SRaphael Isemann if (args.HasArgs()) { 6003a0e1270SRaphael Isemann if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx)) 60130fdc8d8SChris Lattner return false; 602f6b8b581SGreg Clayton 603b9c1b51eSKate Stone if (m_repl_option.GetOptionValue().GetCurrentValue()) { 604f2bd5c3eSSean Callanan Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); 605b9c1b51eSKate Stone if (target) { 606f2bd5c3eSSean Callanan // Drop into REPL 607f2bd5c3eSSean Callanan m_expr_lines.clear(); 608f2bd5c3eSSean Callanan m_expr_line_count = 0; 609f2bd5c3eSSean Callanan 610f2bd5c3eSSean Callanan Debugger &debugger = target->GetDebugger(); 611f2bd5c3eSSean Callanan 612b9c1b51eSKate Stone // Check if the LLDB command interpreter is sitting on top of a REPL 61305097246SAdrian Prantl // that launched it... 6143a0e1270SRaphael Isemann if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, 6153a0e1270SRaphael Isemann IOHandler::Type::REPL)) { 616b9c1b51eSKate Stone // the LLDB command interpreter is sitting on top of a REPL that 61705097246SAdrian Prantl // launched it, so just say the command interpreter is done and 61805097246SAdrian Prantl // fall back to the existing REPL 619f2bd5c3eSSean Callanan m_interpreter.GetIOHandler(false)->SetIsDone(true); 620b9c1b51eSKate Stone } else { 621b9c1b51eSKate Stone // We are launching the REPL on top of the current LLDB command 62205097246SAdrian Prantl // interpreter, so just push one 623f2bd5c3eSSean Callanan bool initialize = false; 62497206d57SZachary Turner Status repl_error; 6253a0e1270SRaphael Isemann REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language, 6263a0e1270SRaphael Isemann nullptr, false)); 627f2bd5c3eSSean Callanan 628b9c1b51eSKate Stone if (!repl_sp) { 629f2bd5c3eSSean Callanan initialize = true; 630b9c1b51eSKate Stone repl_sp = target->GetREPL(repl_error, m_command_options.language, 631b9c1b51eSKate Stone nullptr, true); 632b9c1b51eSKate Stone if (!repl_error.Success()) { 633f2bd5c3eSSean Callanan result.SetError(repl_error); 634f2bd5c3eSSean Callanan return result.Succeeded(); 635f2bd5c3eSSean Callanan } 636f2bd5c3eSSean Callanan } 637f2bd5c3eSSean Callanan 638b9c1b51eSKate Stone if (repl_sp) { 639b9c1b51eSKate Stone if (initialize) { 640c5bfa3daSJonas Devlieghere repl_sp->SetEvaluateOptions( 641c5bfa3daSJonas Devlieghere GetExprOptions(exe_ctx, m_command_options)); 642f2bd5c3eSSean Callanan repl_sp->SetFormatOptions(m_format_options); 643f2bd5c3eSSean Callanan repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 644f2bd5c3eSSean Callanan } 645f2bd5c3eSSean Callanan 646f2bd5c3eSSean Callanan IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); 647f2bd5c3eSSean Callanan 648f2bd5c3eSSean Callanan io_handler_sp->SetIsDone(false); 649f2bd5c3eSSean Callanan 650f2bd5c3eSSean Callanan debugger.PushIOHandler(io_handler_sp); 651b9c1b51eSKate Stone } else { 652b9c1b51eSKate Stone repl_error.SetErrorStringWithFormat( 653b9c1b51eSKate Stone "Couldn't create a REPL for %s", 654b9c1b51eSKate Stone Language::GetNameForLanguageType(m_command_options.language)); 655f2bd5c3eSSean Callanan result.SetError(repl_error); 656f2bd5c3eSSean Callanan return result.Succeeded(); 657f2bd5c3eSSean Callanan } 658f2bd5c3eSSean Callanan } 659f2bd5c3eSSean Callanan } 660f2bd5c3eSSean Callanan } 661cf28a8b7SGreg Clayton // No expression following options 6624d51a902SRaphael Isemann else if (expr.empty()) { 663cf28a8b7SGreg Clayton GetMultilineExpression(); 664cf28a8b7SGreg Clayton return result.Succeeded(); 665cf28a8b7SGreg Clayton } 66630fdc8d8SChris Lattner } 66730fdc8d8SChris Lattner 6680df817aaSDavide Italiano Target *target = GetSelectedOrDummyTarget(); 66924fff242SDavide Italiano if (EvaluateExpression(expr, &(result.GetOutputStream()), 67024fff242SDavide Italiano &(result.GetErrorStream()), &result)) { 67124fff242SDavide Italiano 672b9c1b51eSKate Stone if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) { 673e5ee6f04SJim Ingham CommandHistory &history = m_interpreter.GetCommandHistory(); 674b9c1b51eSKate Stone // FIXME: Can we figure out what the user actually typed (e.g. some alias 675b9c1b51eSKate Stone // for expr???) 676e5ee6f04SJim Ingham // If we can it would be nice to show that. 677e5ee6f04SJim Ingham std::string fixed_command("expression "); 6783a0e1270SRaphael Isemann if (args.HasArgs()) { 679e5ee6f04SJim Ingham // Add in any options that might have been in the original command: 6803a0e1270SRaphael Isemann fixed_command.append(args.GetArgStringWithDelimiter()); 681e5ee6f04SJim Ingham fixed_command.append(m_fixed_expression); 6823a0e1270SRaphael Isemann } else 6833a0e1270SRaphael Isemann fixed_command.append(m_fixed_expression); 684e5ee6f04SJim Ingham history.AppendString(fixed_command); 685e5ee6f04SJim Ingham } 68605097246SAdrian Prantl // Increment statistics to record this expression evaluation success. 68724fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionSuccessful); 688fcd43b71SJohnny Chen return true; 689e5ee6f04SJim Ingham } 690fcd43b71SJohnny Chen 69105097246SAdrian Prantl // Increment statistics to record this expression evaluation failure. 69224fff242SDavide Italiano target->IncrementStats(StatisticKind::ExpressionFailure); 693fcd43b71SJohnny Chen result.SetStatus(eReturnStatusFailed); 694fcd43b71SJohnny Chen return false; 69530fdc8d8SChris Lattner } 696