1 //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/ADT/STLExtras.h" 10 #include "llvm/ADT/StringRef.h" 11 12 #include "CommandObjectExpression.h" 13 #include "lldb/Core/Debugger.h" 14 #include "lldb/Core/Value.h" 15 #include "lldb/Core/ValueObjectVariable.h" 16 #include "lldb/DataFormatters/ValueObjectPrinter.h" 17 #include "lldb/Expression/DWARFExpression.h" 18 #include "lldb/Expression/REPL.h" 19 #include "lldb/Expression/UserExpression.h" 20 #include "lldb/Host/Host.h" 21 #include "lldb/Host/OptionParser.h" 22 #include "lldb/Interpreter/CommandInterpreter.h" 23 #include "lldb/Interpreter/CommandReturnObject.h" 24 #include "lldb/Interpreter/OptionArgParser.h" 25 #include "lldb/Symbol/ObjectFile.h" 26 #include "lldb/Symbol/Variable.h" 27 #include "lldb/Target/Language.h" 28 #include "lldb/Target/Process.h" 29 #include "lldb/Target/StackFrame.h" 30 #include "lldb/Target/Target.h" 31 #include "lldb/Target/Thread.h" 32 33 using namespace lldb; 34 using namespace lldb_private; 35 36 CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {} 37 38 CommandObjectExpression::CommandOptions::~CommandOptions() = default; 39 40 static constexpr OptionEnumValueElement g_description_verbosity_type[] = { 41 {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", 42 "Only show the description string"}, 43 {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", 44 "Show the full output, including persistent variable's name and type"} }; 45 46 static constexpr OptionEnumValues DescriptionVerbosityTypes() { 47 return OptionEnumValues(g_description_verbosity_type); 48 } 49 50 static constexpr OptionDefinition g_expression_options[] = { 51 // clang-format off 52 {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."}, 53 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"}, 54 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."}, 55 {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. " 56 "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."}, 57 {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 " 58 "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."}, 59 {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 " 60 "setting is used." }, 61 {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." }, 62 {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."}, 63 {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 " 64 "context. Allows declaration of persistent, top-level entities without a $ prefix."}, 65 {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 " 66 "the interpreter (defaults to true)."} 67 // clang-format on 68 }; 69 70 Status CommandObjectExpression::CommandOptions::SetOptionValue( 71 uint32_t option_idx, llvm::StringRef option_arg, 72 ExecutionContext *execution_context) { 73 Status error; 74 75 const int short_option = GetDefinitions()[option_idx].short_option; 76 77 switch (short_option) { 78 case 'l': 79 language = Language::GetLanguageTypeFromString(option_arg); 80 if (language == eLanguageTypeUnknown) 81 error.SetErrorStringWithFormat( 82 "unknown language type: '%s' for expression", 83 option_arg.str().c_str()); 84 break; 85 86 case 'a': { 87 bool success; 88 bool result; 89 result = OptionArgParser::ToBoolean(option_arg, true, &success); 90 if (!success) 91 error.SetErrorStringWithFormat( 92 "invalid all-threads value setting: \"%s\"", 93 option_arg.str().c_str()); 94 else 95 try_all_threads = result; 96 } break; 97 98 case 'i': { 99 bool success; 100 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 101 if (success) 102 ignore_breakpoints = tmp_value; 103 else 104 error.SetErrorStringWithFormat( 105 "could not convert \"%s\" to a boolean value.", 106 option_arg.str().c_str()); 107 break; 108 } 109 110 case 'j': { 111 bool success; 112 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 113 if (success) 114 allow_jit = tmp_value; 115 else 116 error.SetErrorStringWithFormat( 117 "could not convert \"%s\" to a boolean value.", 118 option_arg.str().c_str()); 119 break; 120 } 121 122 case 't': 123 if (option_arg.getAsInteger(0, timeout)) { 124 timeout = 0; 125 error.SetErrorStringWithFormat("invalid timeout setting \"%s\"", 126 option_arg.str().c_str()); 127 } 128 break; 129 130 case 'u': { 131 bool success; 132 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 133 if (success) 134 unwind_on_error = tmp_value; 135 else 136 error.SetErrorStringWithFormat( 137 "could not convert \"%s\" to a boolean value.", 138 option_arg.str().c_str()); 139 break; 140 } 141 142 case 'v': 143 if (option_arg.empty()) { 144 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 145 break; 146 } 147 m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) 148 OptionArgParser::ToOptionEnum( 149 option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 150 if (!error.Success()) 151 error.SetErrorStringWithFormat( 152 "unrecognized value for description-verbosity '%s'", 153 option_arg.str().c_str()); 154 break; 155 156 case 'g': 157 debug = true; 158 unwind_on_error = false; 159 ignore_breakpoints = false; 160 break; 161 162 case 'p': 163 top_level = true; 164 break; 165 166 case 'X': { 167 bool success; 168 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 169 if (success) 170 auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; 171 else 172 error.SetErrorStringWithFormat( 173 "could not convert \"%s\" to a boolean value.", 174 option_arg.str().c_str()); 175 break; 176 } 177 178 default: 179 error.SetErrorStringWithFormat("invalid short option character '%c'", 180 short_option); 181 break; 182 } 183 184 return error; 185 } 186 187 void CommandObjectExpression::CommandOptions::OptionParsingStarting( 188 ExecutionContext *execution_context) { 189 auto process_sp = 190 execution_context ? execution_context->GetProcessSP() : ProcessSP(); 191 if (process_sp) { 192 ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); 193 unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); 194 } else { 195 ignore_breakpoints = true; 196 unwind_on_error = true; 197 } 198 199 show_summary = true; 200 try_all_threads = true; 201 timeout = 0; 202 debug = false; 203 language = eLanguageTypeUnknown; 204 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 205 auto_apply_fixits = eLazyBoolCalculate; 206 top_level = false; 207 allow_jit = true; 208 } 209 210 llvm::ArrayRef<OptionDefinition> 211 CommandObjectExpression::CommandOptions::GetDefinitions() { 212 return llvm::makeArrayRef(g_expression_options); 213 } 214 215 CommandObjectExpression::CommandObjectExpression( 216 CommandInterpreter &interpreter) 217 : CommandObjectRaw( 218 interpreter, "expression", "Evaluate an expression on the current " 219 "thread. Displays any returned value " 220 "with LLDB's default formatting.", 221 "", eCommandProcessMustBePaused | eCommandTryTargetAPILock), 222 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), 223 m_option_group(), m_format_options(eFormatDefault), 224 m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, 225 true), 226 m_command_options(), m_expr_line_count(0), m_expr_lines() { 227 SetHelpLong( 228 R"( 229 Single and multi-line expressions: 230 231 )" 232 " The expression provided on the command line must be a complete expression \ 233 with no newlines. To evaluate a multi-line expression, \ 234 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ 235 Hit return on an empty line to end the multi-line expression." 236 237 R"( 238 239 Timeouts: 240 241 )" 242 " If the expression can be evaluated statically (without running code) then it will be. \ 243 Otherwise, by default the expression will run on the current thread with a short timeout: \ 244 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 245 and resumed with all threads running. You can use the -a option to disable retrying on all \ 246 threads. You can use the -t option to set a shorter timeout." 247 R"( 248 249 User defined variables: 250 251 )" 252 " You can define your own variables for convenience or to be used in subsequent expressions. \ 253 You define them the same way you would define variables in C. If the first character of \ 254 your user defined variable is a $, then the variable's value will be available in future \ 255 expressions, otherwise it will just be available in the current expression." 256 R"( 257 258 Continuing evaluation after a breakpoint: 259 260 )" 261 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 262 you are done with your investigation, you can either remove the expression execution frames \ 263 from the stack with \"thread return -x\" or if you are still interested in the expression result \ 264 you can issue the \"continue\" command and the expression evaluation will complete and the \ 265 expression result will be available using the \"thread.completed-expression\" key in the thread \ 266 format." 267 268 R"( 269 270 Examples: 271 272 expr my_struct->a = my_array[3] 273 expr -f bin -- (index * 8) + 5 274 expr unsigned int $foo = 5 275 expr char c[] = \"foo\"; c[0])"); 276 277 CommandArgumentEntry arg; 278 CommandArgumentData expression_arg; 279 280 // Define the first (and only) variant of this arg. 281 expression_arg.arg_type = eArgTypeExpression; 282 expression_arg.arg_repetition = eArgRepeatPlain; 283 284 // There is only one variant this argument could be; put it into the argument 285 // entry. 286 arg.push_back(expression_arg); 287 288 // Push the data for the first argument into the m_arguments vector. 289 m_arguments.push_back(arg); 290 291 // Add the "--format" and "--gdb-format" 292 m_option_group.Append(&m_format_options, 293 OptionGroupFormat::OPTION_GROUP_FORMAT | 294 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 295 LLDB_OPT_SET_1); 296 m_option_group.Append(&m_command_options); 297 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, 298 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 299 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 300 m_option_group.Finalize(); 301 } 302 303 CommandObjectExpression::~CommandObjectExpression() = default; 304 305 Options *CommandObjectExpression::GetOptions() { return &m_option_group; } 306 307 int CommandObjectExpression::HandleCompletion(CompletionRequest &request) { 308 EvaluateExpressionOptions options; 309 options.SetCoerceToId(m_varobj_options.use_objc); 310 options.SetLanguage(m_command_options.language); 311 options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever); 312 options.SetAutoApplyFixIts(false); 313 options.SetGenerateDebugInfo(false); 314 315 // We need a valid execution context with a frame pointer for this 316 // completion, so if we don't have one we should try to make a valid 317 // execution context. 318 if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 319 m_interpreter.UpdateExecutionContext(nullptr); 320 321 // This didn't work, so let's get out before we start doing things that 322 // expect a valid frame pointer. 323 if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr) 324 return 0; 325 326 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 327 328 Target *target = exe_ctx.GetTargetPtr(); 329 330 if (!target) 331 target = GetDummyTarget(); 332 333 if (!target) 334 return 0; 335 336 unsigned cursor_pos = request.GetRawCursorPos(); 337 llvm::StringRef code = request.GetRawLine(); 338 339 const std::size_t original_code_size = code.size(); 340 341 // Remove the first token which is 'expr' or some alias/abbreviation of that. 342 code = llvm::getToken(code).second.ltrim(); 343 OptionsWithRaw args(code); 344 code = args.GetRawPart(); 345 346 // The position where the expression starts in the command line. 347 assert(original_code_size >= code.size()); 348 std::size_t raw_start = original_code_size - code.size(); 349 350 // Check if the cursor is actually in the expression string, and if not, we 351 // exit. 352 // FIXME: We should complete the options here. 353 if (cursor_pos < raw_start) 354 return 0; 355 356 // Make the cursor_pos again relative to the start of the code string. 357 assert(cursor_pos >= raw_start); 358 cursor_pos -= raw_start; 359 360 auto language = exe_ctx.GetFrameRef().GetLanguage(); 361 362 Status error; 363 lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage( 364 code, llvm::StringRef(), language, UserExpression::eResultTypeAny, 365 options, nullptr, error)); 366 if (error.Fail()) 367 return 0; 368 369 expr->Complete(exe_ctx, request, cursor_pos); 370 return request.GetNumberOfMatches(); 371 } 372 373 static lldb_private::Status 374 CanBeUsedForElementCountPrinting(ValueObject &valobj) { 375 CompilerType type(valobj.GetCompilerType()); 376 CompilerType pointee; 377 if (!type.IsPointerType(&pointee)) 378 return Status("as it does not refer to a pointer"); 379 if (pointee.IsVoidType()) 380 return Status("as it refers to a pointer to void"); 381 return Status(); 382 } 383 384 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr, 385 Stream *output_stream, 386 Stream *error_stream, 387 CommandReturnObject *result) { 388 // Don't use m_exe_ctx as this might be called asynchronously after the 389 // command object DoExecute has finished when doing multi-line expression 390 // that use an input reader... 391 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 392 393 Target *target = exe_ctx.GetTargetPtr(); 394 395 if (!target) 396 target = GetDummyTarget(); 397 398 if (target) { 399 lldb::ValueObjectSP result_valobj_sp; 400 bool keep_in_memory = true; 401 StackFrame *frame = exe_ctx.GetFramePtr(); 402 403 EvaluateExpressionOptions options; 404 options.SetCoerceToId(m_varobj_options.use_objc); 405 options.SetUnwindOnError(m_command_options.unwind_on_error); 406 options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); 407 options.SetKeepInMemory(keep_in_memory); 408 options.SetUseDynamic(m_varobj_options.use_dynamic); 409 options.SetTryAllThreads(m_command_options.try_all_threads); 410 options.SetDebug(m_command_options.debug); 411 options.SetLanguage(m_command_options.language); 412 options.SetExecutionPolicy( 413 m_command_options.allow_jit 414 ? EvaluateExpressionOptions::default_execution_policy 415 : lldb_private::eExecutionPolicyNever); 416 417 bool auto_apply_fixits; 418 if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) 419 auto_apply_fixits = target->GetEnableAutoApplyFixIts(); 420 else 421 auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes; 422 423 options.SetAutoApplyFixIts(auto_apply_fixits); 424 425 if (m_command_options.top_level) 426 options.SetExecutionPolicy(eExecutionPolicyTopLevel); 427 428 // If there is any chance we are going to stop and want to see what went 429 // wrong with our expression, we should generate debug info 430 if (!m_command_options.ignore_breakpoints || 431 !m_command_options.unwind_on_error) 432 options.SetGenerateDebugInfo(true); 433 434 if (m_command_options.timeout > 0) 435 options.SetTimeout(std::chrono::microseconds(m_command_options.timeout)); 436 else 437 options.SetTimeout(llvm::None); 438 439 ExpressionResults success = target->EvaluateExpression( 440 expr, frame, result_valobj_sp, options, &m_fixed_expression); 441 442 // We only tell you about the FixIt if we applied it. The compiler errors 443 // will suggest the FixIt if it parsed. 444 if (error_stream && !m_fixed_expression.empty() && 445 target->GetEnableNotifyAboutFixIts()) { 446 if (success == eExpressionCompleted) 447 error_stream->Printf( 448 " Fix-it applied, fixed expression was: \n %s\n", 449 m_fixed_expression.c_str()); 450 } 451 452 if (result_valobj_sp) { 453 Format format = m_format_options.GetFormat(); 454 455 if (result_valobj_sp->GetError().Success()) { 456 if (format != eFormatVoid) { 457 if (format != eFormatDefault) 458 result_valobj_sp->SetFormat(format); 459 460 if (m_varobj_options.elem_count > 0) { 461 Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); 462 if (error.Fail()) { 463 result->AppendErrorWithFormat( 464 "expression cannot be used with --element-count %s\n", 465 error.AsCString("")); 466 result->SetStatus(eReturnStatusFailed); 467 return false; 468 } 469 } 470 471 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 472 m_command_options.m_verbosity, format)); 473 options.SetVariableFormatDisplayLanguage( 474 result_valobj_sp->GetPreferredDisplayLanguage()); 475 476 result_valobj_sp->Dump(*output_stream, options); 477 478 if (result) 479 result->SetStatus(eReturnStatusSuccessFinishResult); 480 } 481 } else { 482 if (result_valobj_sp->GetError().GetError() == 483 UserExpression::kNoResult) { 484 if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) { 485 error_stream->PutCString("(void)\n"); 486 } 487 488 if (result) 489 result->SetStatus(eReturnStatusSuccessFinishResult); 490 } else { 491 const char *error_cstr = result_valobj_sp->GetError().AsCString(); 492 if (error_cstr && error_cstr[0]) { 493 const size_t error_cstr_len = strlen(error_cstr); 494 const bool ends_with_newline = 495 error_cstr[error_cstr_len - 1] == '\n'; 496 if (strstr(error_cstr, "error:") != error_cstr) 497 error_stream->PutCString("error: "); 498 error_stream->Write(error_cstr, error_cstr_len); 499 if (!ends_with_newline) 500 error_stream->EOL(); 501 } else { 502 error_stream->PutCString("error: unknown error\n"); 503 } 504 505 if (result) 506 result->SetStatus(eReturnStatusFailed); 507 } 508 } 509 } 510 } else { 511 error_stream->Printf("error: invalid execution context for expression\n"); 512 return false; 513 } 514 515 return true; 516 } 517 518 void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, 519 std::string &line) { 520 io_handler.SetIsDone(true); 521 // StreamSP output_stream = 522 // io_handler.GetDebugger().GetAsyncOutputStream(); 523 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); 524 StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 525 StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 526 527 EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get()); 528 if (output_sp) 529 output_sp->Flush(); 530 if (error_sp) 531 error_sp->Flush(); 532 } 533 534 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, 535 StringList &lines) { 536 // An empty lines is used to indicate the end of input 537 const size_t num_lines = lines.GetSize(); 538 if (num_lines > 0 && lines[num_lines - 1].empty()) { 539 // Remove the last empty line from "lines" so it doesn't appear in our 540 // resulting input and return true to indicate we are done getting lines 541 lines.PopBack(); 542 return true; 543 } 544 return false; 545 } 546 547 void CommandObjectExpression::GetMultilineExpression() { 548 m_expr_lines.clear(); 549 m_expr_line_count = 0; 550 551 Debugger &debugger = GetCommandInterpreter().GetDebugger(); 552 bool color_prompt = debugger.GetUseColor(); 553 const bool multiple_lines = true; // Get multiple lines 554 IOHandlerSP io_handler_sp( 555 new IOHandlerEditline(debugger, IOHandler::Type::Expression, 556 "lldb-expr", // Name of input reader for history 557 llvm::StringRef(), // No prompt 558 llvm::StringRef(), // Continuation prompt 559 multiple_lines, color_prompt, 560 1, // Show line numbers starting at 1 561 *this, nullptr)); 562 563 StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); 564 if (output_sp) { 565 output_sp->PutCString( 566 "Enter expressions, then terminate with an empty line to evaluate:\n"); 567 output_sp->Flush(); 568 } 569 debugger.PushIOHandler(io_handler_sp); 570 } 571 572 static EvaluateExpressionOptions 573 GetExprOptions(ExecutionContext &ctx, 574 CommandObjectExpression::CommandOptions command_options) { 575 command_options.OptionParsingStarting(&ctx); 576 577 // Default certain settings for REPL regardless of the global settings. 578 command_options.unwind_on_error = false; 579 command_options.ignore_breakpoints = false; 580 command_options.debug = false; 581 582 EvaluateExpressionOptions expr_options; 583 expr_options.SetUnwindOnError(command_options.unwind_on_error); 584 expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints); 585 expr_options.SetTryAllThreads(command_options.try_all_threads); 586 587 if (command_options.timeout > 0) 588 expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout)); 589 else 590 expr_options.SetTimeout(llvm::None); 591 592 return expr_options; 593 } 594 595 bool CommandObjectExpression::DoExecute(llvm::StringRef command, 596 CommandReturnObject &result) { 597 m_fixed_expression.clear(); 598 auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); 599 m_option_group.NotifyOptionParsingStarting(&exe_ctx); 600 601 if (command.empty()) { 602 GetMultilineExpression(); 603 return result.Succeeded(); 604 } 605 606 OptionsWithRaw args(command); 607 llvm::StringRef expr = args.GetRawPart(); 608 609 if (args.HasArgs()) { 610 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx)) 611 return false; 612 613 if (m_repl_option.GetOptionValue().GetCurrentValue()) { 614 Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); 615 if (target) { 616 // Drop into REPL 617 m_expr_lines.clear(); 618 m_expr_line_count = 0; 619 620 Debugger &debugger = target->GetDebugger(); 621 622 // Check if the LLDB command interpreter is sitting on top of a REPL 623 // that launched it... 624 if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, 625 IOHandler::Type::REPL)) { 626 // the LLDB command interpreter is sitting on top of a REPL that 627 // launched it, so just say the command interpreter is done and 628 // fall back to the existing REPL 629 m_interpreter.GetIOHandler(false)->SetIsDone(true); 630 } else { 631 // We are launching the REPL on top of the current LLDB command 632 // interpreter, so just push one 633 bool initialize = false; 634 Status repl_error; 635 REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language, 636 nullptr, false)); 637 638 if (!repl_sp) { 639 initialize = true; 640 repl_sp = target->GetREPL(repl_error, m_command_options.language, 641 nullptr, true); 642 if (!repl_error.Success()) { 643 result.SetError(repl_error); 644 return result.Succeeded(); 645 } 646 } 647 648 if (repl_sp) { 649 if (initialize) { 650 repl_sp->SetEvaluateOptions( 651 GetExprOptions(exe_ctx, m_command_options)); 652 repl_sp->SetFormatOptions(m_format_options); 653 repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 654 } 655 656 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); 657 658 io_handler_sp->SetIsDone(false); 659 660 debugger.PushIOHandler(io_handler_sp); 661 } else { 662 repl_error.SetErrorStringWithFormat( 663 "Couldn't create a REPL for %s", 664 Language::GetNameForLanguageType(m_command_options.language)); 665 result.SetError(repl_error); 666 return result.Succeeded(); 667 } 668 } 669 } 670 } 671 // No expression following options 672 else if (expr.empty()) { 673 GetMultilineExpression(); 674 return result.Succeeded(); 675 } 676 } 677 678 Target *target = GetSelectedOrDummyTarget(); 679 if (EvaluateExpression(expr, &(result.GetOutputStream()), 680 &(result.GetErrorStream()), &result)) { 681 682 if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) { 683 CommandHistory &history = m_interpreter.GetCommandHistory(); 684 // FIXME: Can we figure out what the user actually typed (e.g. some alias 685 // for expr???) 686 // If we can it would be nice to show that. 687 std::string fixed_command("expression "); 688 if (args.HasArgs()) { 689 // Add in any options that might have been in the original command: 690 fixed_command.append(args.GetArgStringWithDelimiter()); 691 fixed_command.append(m_fixed_expression); 692 } else 693 fixed_command.append(m_fixed_expression); 694 history.AppendString(fixed_command); 695 } 696 // Increment statistics to record this expression evaluation success. 697 target->IncrementStats(StatisticKind::ExpressionSuccessful); 698 return true; 699 } 700 701 // Increment statistics to record this expression evaluation failure. 702 target->IncrementStats(StatisticKind::ExpressionFailure); 703 result.SetStatus(eReturnStatusFailed); 704 return false; 705 } 706