1 //===-- CommandObjectExpression.cpp ---------------------------------------===// 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/StringRef.h" 10 11 #include "CommandObjectExpression.h" 12 #include "lldb/Core/Debugger.h" 13 #include "lldb/Expression/DiagnosticManager.h" 14 #include "lldb/Expression/ExpressionVariable.h" 15 #include "lldb/Expression/REPL.h" 16 #include "lldb/Expression/UserExpression.h" 17 #include "lldb/Host/OptionParser.h" 18 #include "lldb/Interpreter/CommandInterpreter.h" 19 #include "lldb/Interpreter/CommandOptionArgumentTable.h" 20 #include "lldb/Interpreter/CommandReturnObject.h" 21 #include "lldb/Interpreter/OptionArgParser.h" 22 #include "lldb/Target/Language.h" 23 #include "lldb/Target/Process.h" 24 #include "lldb/Target/StackFrame.h" 25 #include "lldb/Target/Target.h" 26 #include "lldb/lldb-enumerations.h" 27 #include "lldb/lldb-private-enumerations.h" 28 29 using namespace lldb; 30 using namespace lldb_private; 31 32 CommandObjectExpression::CommandOptions::CommandOptions() = default; 33 34 CommandObjectExpression::CommandOptions::~CommandOptions() = default; 35 36 #define LLDB_OPTIONS_expression 37 #include "CommandOptions.inc" 38 39 Status CommandObjectExpression::CommandOptions::SetOptionValue( 40 uint32_t option_idx, llvm::StringRef option_arg, 41 ExecutionContext *execution_context) { 42 Status error; 43 44 const int short_option = GetDefinitions()[option_idx].short_option; 45 46 switch (short_option) { 47 case 'l': 48 language = Language::GetLanguageTypeFromString(option_arg); 49 if (language == eLanguageTypeUnknown) { 50 StreamString sstr; 51 sstr.Printf("unknown language type: '%s' for expression. " 52 "List of supported languages:\n", 53 option_arg.str().c_str()); 54 55 Language::PrintSupportedLanguagesForExpressions(sstr, " ", "\n"); 56 error = Status(sstr.GetString().str()); 57 } 58 break; 59 60 case 'a': { 61 bool success; 62 bool result; 63 result = OptionArgParser::ToBoolean(option_arg, true, &success); 64 if (!success) 65 error = Status::FromErrorStringWithFormat( 66 "invalid all-threads value setting: \"%s\"", 67 option_arg.str().c_str()); 68 else 69 try_all_threads = result; 70 } break; 71 72 case 'i': { 73 bool success; 74 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 75 if (success) 76 ignore_breakpoints = tmp_value; 77 else 78 error = Status::FromErrorStringWithFormat( 79 "could not convert \"%s\" to a boolean value.", 80 option_arg.str().c_str()); 81 break; 82 } 83 84 case 'j': { 85 bool success; 86 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 87 if (success) 88 allow_jit = tmp_value; 89 else 90 error = Status::FromErrorStringWithFormat( 91 "could not convert \"%s\" to a boolean value.", 92 option_arg.str().c_str()); 93 break; 94 } 95 96 case 't': 97 if (option_arg.getAsInteger(0, timeout)) { 98 timeout = 0; 99 error = Status::FromErrorStringWithFormat( 100 "invalid timeout setting \"%s\"", option_arg.str().c_str()); 101 } 102 break; 103 104 case 'u': { 105 bool success; 106 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 107 if (success) 108 unwind_on_error = tmp_value; 109 else 110 error = Status::FromErrorStringWithFormat( 111 "could not convert \"%s\" to a boolean value.", 112 option_arg.str().c_str()); 113 break; 114 } 115 116 case 'v': 117 if (option_arg.empty()) { 118 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 119 break; 120 } 121 m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) 122 OptionArgParser::ToOptionEnum( 123 option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 124 if (!error.Success()) 125 error = Status::FromErrorStringWithFormat( 126 "unrecognized value for description-verbosity '%s'", 127 option_arg.str().c_str()); 128 break; 129 130 case 'g': 131 debug = true; 132 unwind_on_error = false; 133 ignore_breakpoints = false; 134 break; 135 136 case 'p': 137 top_level = true; 138 break; 139 140 case 'X': { 141 bool success; 142 bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success); 143 if (success) 144 auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; 145 else 146 error = Status::FromErrorStringWithFormat( 147 "could not convert \"%s\" to a boolean value.", 148 option_arg.str().c_str()); 149 break; 150 } 151 152 case '\x01': { 153 bool success; 154 bool persist_result = 155 OptionArgParser::ToBoolean(option_arg, true, &success); 156 if (success) 157 suppress_persistent_result = !persist_result ? eLazyBoolYes : eLazyBoolNo; 158 else 159 error = Status::FromErrorStringWithFormat( 160 "could not convert \"%s\" to a boolean value.", 161 option_arg.str().c_str()); 162 break; 163 } 164 165 default: 166 llvm_unreachable("Unimplemented option"); 167 } 168 169 return error; 170 } 171 172 void CommandObjectExpression::CommandOptions::OptionParsingStarting( 173 ExecutionContext *execution_context) { 174 auto process_sp = 175 execution_context ? execution_context->GetProcessSP() : ProcessSP(); 176 if (process_sp) { 177 ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); 178 unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); 179 } else { 180 ignore_breakpoints = true; 181 unwind_on_error = true; 182 } 183 184 show_summary = true; 185 try_all_threads = true; 186 timeout = 0; 187 debug = false; 188 language = eLanguageTypeUnknown; 189 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 190 auto_apply_fixits = eLazyBoolCalculate; 191 top_level = false; 192 allow_jit = true; 193 suppress_persistent_result = eLazyBoolCalculate; 194 } 195 196 llvm::ArrayRef<OptionDefinition> 197 CommandObjectExpression::CommandOptions::GetDefinitions() { 198 return llvm::ArrayRef(g_expression_options); 199 } 200 201 EvaluateExpressionOptions 202 CommandObjectExpression::CommandOptions::GetEvaluateExpressionOptions( 203 const Target &target, const OptionGroupValueObjectDisplay &display_opts) { 204 EvaluateExpressionOptions options; 205 options.SetCoerceToId(display_opts.use_objc); 206 options.SetUnwindOnError(unwind_on_error); 207 options.SetIgnoreBreakpoints(ignore_breakpoints); 208 options.SetKeepInMemory(true); 209 options.SetUseDynamic(display_opts.use_dynamic); 210 options.SetTryAllThreads(try_all_threads); 211 options.SetDebug(debug); 212 options.SetLanguage(language); 213 options.SetExecutionPolicy( 214 allow_jit ? EvaluateExpressionOptions::default_execution_policy 215 : lldb_private::eExecutionPolicyNever); 216 217 bool auto_apply_fixits; 218 if (this->auto_apply_fixits == eLazyBoolCalculate) 219 auto_apply_fixits = target.GetEnableAutoApplyFixIts(); 220 else 221 auto_apply_fixits = this->auto_apply_fixits == eLazyBoolYes; 222 223 options.SetAutoApplyFixIts(auto_apply_fixits); 224 options.SetRetriesWithFixIts(target.GetNumberOfRetriesWithFixits()); 225 226 if (top_level) 227 options.SetExecutionPolicy(eExecutionPolicyTopLevel); 228 229 // If there is any chance we are going to stop and want to see what went 230 // wrong with our expression, we should generate debug info 231 if (!ignore_breakpoints || !unwind_on_error) 232 options.SetGenerateDebugInfo(true); 233 234 if (timeout > 0) 235 options.SetTimeout(std::chrono::microseconds(timeout)); 236 else 237 options.SetTimeout(std::nullopt); 238 return options; 239 } 240 241 bool CommandObjectExpression::CommandOptions::ShouldSuppressResult( 242 const OptionGroupValueObjectDisplay &display_opts) const { 243 // Explicitly disabling persistent results takes precedence over the 244 // m_verbosity/use_objc logic. 245 if (suppress_persistent_result != eLazyBoolCalculate) 246 return suppress_persistent_result == eLazyBoolYes; 247 248 return display_opts.use_objc && 249 m_verbosity == eLanguageRuntimeDescriptionDisplayVerbosityCompact; 250 } 251 252 CommandObjectExpression::CommandObjectExpression( 253 CommandInterpreter &interpreter) 254 : CommandObjectRaw(interpreter, "expression", 255 "Evaluate an expression on the current " 256 "thread. Displays any returned value " 257 "with LLDB's default formatting.", 258 "", 259 eCommandProcessMustBePaused | eCommandTryTargetAPILock), 260 IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), 261 m_format_options(eFormatDefault), 262 m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, 263 true), 264 m_expr_line_count(0) { 265 SetHelpLong( 266 R"( 267 Single and multi-line expressions: 268 269 )" 270 " The expression provided on the command line must be a complete expression \ 271 with no newlines. To evaluate a multi-line expression, \ 272 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \ 273 Hit return on an empty line to end the multi-line expression." 274 275 R"( 276 277 Timeouts: 278 279 )" 280 " If the expression can be evaluated statically (without running code) then it will be. \ 281 Otherwise, by default the expression will run on the current thread with a short timeout: \ 282 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 283 and resumed with all threads running. You can use the -a option to disable retrying on all \ 284 threads. You can use the -t option to set a shorter timeout." 285 R"( 286 287 User defined variables: 288 289 )" 290 " You can define your own variables for convenience or to be used in subsequent expressions. \ 291 You define them the same way you would define variables in C. If the first character of \ 292 your user defined variable is a $, then the variable's value will be available in future \ 293 expressions, otherwise it will just be available in the current expression." 294 R"( 295 296 Continuing evaluation after a breakpoint: 297 298 )" 299 " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 300 you are done with your investigation, you can either remove the expression execution frames \ 301 from the stack with \"thread return -x\" or if you are still interested in the expression result \ 302 you can issue the \"continue\" command and the expression evaluation will complete and the \ 303 expression result will be available using the \"thread.completed-expression\" key in the thread \ 304 format." 305 306 R"( 307 308 Examples: 309 310 expr my_struct->a = my_array[3] 311 expr -f bin -- (index * 8) + 5 312 expr unsigned int $foo = 5 313 expr char c[] = \"foo\"; c[0])"); 314 315 AddSimpleArgumentList(eArgTypeExpression); 316 317 // Add the "--format" and "--gdb-format" 318 m_option_group.Append(&m_format_options, 319 OptionGroupFormat::OPTION_GROUP_FORMAT | 320 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 321 LLDB_OPT_SET_1); 322 m_option_group.Append(&m_command_options); 323 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, 324 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 325 m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 326 m_option_group.Finalize(); 327 } 328 329 CommandObjectExpression::~CommandObjectExpression() = default; 330 331 Options *CommandObjectExpression::GetOptions() { return &m_option_group; } 332 333 void CommandObjectExpression::HandleCompletion(CompletionRequest &request) { 334 EvaluateExpressionOptions options; 335 options.SetCoerceToId(m_varobj_options.use_objc); 336 options.SetLanguage(m_command_options.language); 337 options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever); 338 options.SetAutoApplyFixIts(false); 339 options.SetGenerateDebugInfo(false); 340 341 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 342 343 // Get out before we start doing things that expect a valid frame pointer. 344 if (exe_ctx.GetFramePtr() == nullptr) 345 return; 346 347 Target *exe_target = exe_ctx.GetTargetPtr(); 348 Target &target = exe_target ? *exe_target : GetDummyTarget(); 349 350 unsigned cursor_pos = request.GetRawCursorPos(); 351 // Get the full user input including the suffix. The suffix is necessary 352 // as OptionsWithRaw will use it to detect if the cursor is cursor is in the 353 // argument part of in the raw input part of the arguments. If we cut of 354 // of the suffix then "expr -arg[cursor] --" would interpret the "-arg" as 355 // the raw input (as the "--" is hidden in the suffix). 356 llvm::StringRef code = request.GetRawLineWithUnusedSuffix(); 357 358 const std::size_t original_code_size = code.size(); 359 360 // Remove the first token which is 'expr' or some alias/abbreviation of that. 361 code = llvm::getToken(code).second.ltrim(); 362 OptionsWithRaw args(code); 363 code = args.GetRawPart(); 364 365 // The position where the expression starts in the command line. 366 assert(original_code_size >= code.size()); 367 std::size_t raw_start = original_code_size - code.size(); 368 369 // Check if the cursor is actually in the expression string, and if not, we 370 // exit. 371 // FIXME: We should complete the options here. 372 if (cursor_pos < raw_start) 373 return; 374 375 // Make the cursor_pos again relative to the start of the code string. 376 assert(cursor_pos >= raw_start); 377 cursor_pos -= raw_start; 378 379 auto language = exe_ctx.GetFrameRef().GetLanguage(); 380 381 Status error; 382 lldb::UserExpressionSP expr(target.GetUserExpressionForLanguage( 383 code, llvm::StringRef(), language, UserExpression::eResultTypeAny, 384 options, nullptr, error)); 385 if (error.Fail()) 386 return; 387 388 expr->Complete(exe_ctx, request, cursor_pos); 389 } 390 391 static lldb_private::Status 392 CanBeUsedForElementCountPrinting(ValueObject &valobj) { 393 CompilerType type(valobj.GetCompilerType()); 394 CompilerType pointee; 395 if (!type.IsPointerType(&pointee)) 396 return Status::FromErrorString("as it does not refer to a pointer"); 397 if (pointee.IsVoidType()) 398 return Status::FromErrorString("as it refers to a pointer to void"); 399 return Status(); 400 } 401 402 static llvm::raw_ostream &PrintSeverity(Stream &stream, 403 lldb::Severity severity) { 404 llvm::HighlightColor color; 405 llvm::StringRef text; 406 switch (severity) { 407 case eSeverityError: 408 color = llvm::HighlightColor::Error; 409 text = "error: "; 410 break; 411 case eSeverityWarning: 412 color = llvm::HighlightColor::Warning; 413 text = "warning: "; 414 break; 415 case eSeverityInfo: 416 color = llvm::HighlightColor::Remark; 417 text = "note: "; 418 break; 419 } 420 return llvm::WithColor(stream.AsRawOstream(), color, llvm::ColorMode::Enable) 421 << text; 422 } 423 424 namespace lldb_private { 425 // Public for unittesting. 426 void RenderDiagnosticDetails(Stream &stream, 427 std::optional<uint16_t> offset_in_command, 428 bool show_inline, 429 llvm::ArrayRef<DiagnosticDetail> details) { 430 if (details.empty()) 431 return; 432 433 if (!offset_in_command) { 434 for (const DiagnosticDetail &detail : details) { 435 PrintSeverity(stream, detail.severity); 436 stream << detail.rendered << '\n'; 437 } 438 return; 439 } 440 441 // Print a line with caret indicator(s) below the lldb prompt + command. 442 const size_t padding = *offset_in_command; 443 stream << std::string(padding, ' '); 444 445 size_t offset = 1; 446 std::vector<DiagnosticDetail> remaining_details, other_details, 447 hidden_details; 448 for (const DiagnosticDetail &detail : details) { 449 if (!show_inline || !detail.source_location) { 450 other_details.push_back(detail); 451 continue; 452 } 453 if (detail.source_location->hidden) { 454 hidden_details.push_back(detail); 455 continue; 456 } 457 if (!detail.source_location->in_user_input) { 458 other_details.push_back(detail); 459 continue; 460 } 461 462 auto &loc = *detail.source_location; 463 remaining_details.push_back(detail); 464 if (offset > loc.column) 465 continue; 466 stream << std::string(loc.column - offset, ' ') << '^'; 467 if (loc.length > 1) 468 stream << std::string(loc.length - 1, '~'); 469 offset = loc.column + 1; 470 } 471 stream << '\n'; 472 473 // Work through each detail in reverse order using the vector/stack. 474 bool did_print = false; 475 for (auto detail = remaining_details.rbegin(); 476 detail != remaining_details.rend(); 477 ++detail, remaining_details.pop_back()) { 478 // Get the information to print this detail and remove it from the stack. 479 // Print all the lines for all the other messages first. 480 stream << std::string(padding, ' '); 481 size_t offset = 1; 482 for (auto &remaining_detail : 483 llvm::ArrayRef(remaining_details).drop_back(1)) { 484 uint16_t column = remaining_detail.source_location->column; 485 stream << std::string(column - offset, ' ') << "│"; 486 offset = column + 1; 487 } 488 489 // Print the line connecting the ^ with the error message. 490 uint16_t column = detail->source_location->column; 491 if (offset <= column) 492 stream << std::string(column - offset, ' ') << "╰─ "; 493 494 // Print a colorized string based on the message's severity type. 495 PrintSeverity(stream, detail->severity); 496 497 // Finally, print the message and start a new line. 498 stream << detail->message << '\n'; 499 did_print = true; 500 } 501 502 // Print the non-located details. 503 for (const DiagnosticDetail &detail : other_details) { 504 PrintSeverity(stream, detail.severity); 505 stream << detail.rendered << '\n'; 506 did_print = true; 507 } 508 509 // Print the hidden details as a last resort. 510 if (!did_print) 511 for (const DiagnosticDetail &detail : hidden_details) { 512 PrintSeverity(stream, detail.severity); 513 stream << detail.rendered << '\n'; 514 } 515 } 516 } // namespace lldb_private 517 518 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr, 519 Stream &output_stream, 520 Stream &error_stream, 521 CommandReturnObject &result) { 522 // Don't use m_exe_ctx as this might be called asynchronously after the 523 // command object DoExecute has finished when doing multi-line expression 524 // that use an input reader... 525 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); 526 Target *exe_target = exe_ctx.GetTargetPtr(); 527 Target &target = exe_target ? *exe_target : GetDummyTarget(); 528 529 lldb::ValueObjectSP result_valobj_sp; 530 StackFrame *frame = exe_ctx.GetFramePtr(); 531 532 if (m_command_options.top_level && !m_command_options.allow_jit) { 533 result.AppendErrorWithFormat( 534 "Can't disable JIT compilation for top-level expressions.\n"); 535 return false; 536 } 537 538 EvaluateExpressionOptions eval_options = 539 m_command_options.GetEvaluateExpressionOptions(target, m_varobj_options); 540 // This command manually removes the result variable, make sure expression 541 // evaluation doesn't do it first. 542 eval_options.SetSuppressPersistentResult(false); 543 544 ExpressionResults success = target.EvaluateExpression( 545 expr, frame, result_valobj_sp, eval_options, &m_fixed_expression); 546 547 // Only mention Fix-Its if the expression evaluator applied them. 548 // Compiler errors refer to the final expression after applying Fix-It(s). 549 if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) { 550 error_stream << " Evaluated this expression after applying Fix-It(s):\n"; 551 error_stream << " " << m_fixed_expression << "\n"; 552 } 553 554 if (result_valobj_sp) { 555 Format format = m_format_options.GetFormat(); 556 557 if (result_valobj_sp->GetError().Success()) { 558 if (format != eFormatVoid) { 559 if (format != eFormatDefault) 560 result_valobj_sp->SetFormat(format); 561 562 if (m_varobj_options.elem_count > 0) { 563 Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); 564 if (error.Fail()) { 565 result.AppendErrorWithFormat( 566 "expression cannot be used with --element-count %s\n", 567 error.AsCString("")); 568 return false; 569 } 570 } 571 572 bool suppress_result = 573 m_command_options.ShouldSuppressResult(m_varobj_options); 574 575 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 576 m_command_options.m_verbosity, format)); 577 options.SetHideRootName(suppress_result); 578 options.SetVariableFormatDisplayLanguage( 579 result_valobj_sp->GetPreferredDisplayLanguage()); 580 581 if (llvm::Error error = 582 result_valobj_sp->Dump(output_stream, options)) { 583 result.AppendError(toString(std::move(error))); 584 return false; 585 } 586 587 if (suppress_result) 588 if (auto result_var_sp = 589 target.GetPersistentVariable(result_valobj_sp->GetName())) { 590 auto language = result_valobj_sp->GetPreferredDisplayLanguage(); 591 if (auto *persistent_state = 592 target.GetPersistentExpressionStateForLanguage(language)) 593 persistent_state->RemovePersistentVariable(result_var_sp); 594 } 595 result.SetStatus(eReturnStatusSuccessFinishResult); 596 } 597 } else { 598 if (result_valobj_sp->GetError().GetError() == 599 UserExpression::kNoResult) { 600 if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) { 601 error_stream.PutCString("(void)\n"); 602 } 603 604 result.SetStatus(eReturnStatusSuccessFinishResult); 605 } else { 606 // Retrieve the diagnostics. 607 std::vector<DiagnosticDetail> details; 608 llvm::consumeError(llvm::handleErrors( 609 result_valobj_sp->GetError().ToError(), 610 [&](ExpressionError &error) { details = error.GetDetails(); })); 611 // Find the position of the expression in the command. 612 std::optional<uint16_t> expr_pos; 613 size_t nchar = m_original_command.find(expr); 614 if (nchar != std::string::npos) 615 expr_pos = nchar + GetDebugger().GetPrompt().size(); 616 617 if (!details.empty()) { 618 bool show_inline = 619 GetDebugger().GetShowInlineDiagnostics() && !expr.contains('\n'); 620 RenderDiagnosticDetails(error_stream, expr_pos, show_inline, details); 621 } else { 622 const char *error_cstr = result_valobj_sp->GetError().AsCString(); 623 llvm::StringRef error(error_cstr); 624 if (!error.empty()) { 625 if (!error.starts_with("error:")) 626 error_stream << "error: "; 627 error_stream << error; 628 if (!error.ends_with('\n')) 629 error_stream.EOL(); 630 } else { 631 error_stream << "error: unknown error\n"; 632 } 633 } 634 result.SetStatus(eReturnStatusFailed); 635 } 636 } 637 } else { 638 error_stream.Printf("error: unknown error\n"); 639 } 640 641 return (success != eExpressionSetupError && 642 success != eExpressionParseError); 643 } 644 645 void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, 646 std::string &line) { 647 io_handler.SetIsDone(true); 648 StreamFileSP output_sp = io_handler.GetOutputStreamFileSP(); 649 StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 650 651 CommandReturnObject return_obj( 652 GetCommandInterpreter().GetDebugger().GetUseColor()); 653 EvaluateExpression(line.c_str(), *output_sp, *error_sp, return_obj); 654 if (output_sp) 655 output_sp->Flush(); 656 if (error_sp) 657 error_sp->Flush(); 658 } 659 660 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, 661 StringList &lines) { 662 // An empty lines is used to indicate the end of input 663 const size_t num_lines = lines.GetSize(); 664 if (num_lines > 0 && lines[num_lines - 1].empty()) { 665 // Remove the last empty line from "lines" so it doesn't appear in our 666 // resulting input and return true to indicate we are done getting lines 667 lines.PopBack(); 668 return true; 669 } 670 return false; 671 } 672 673 void CommandObjectExpression::GetMultilineExpression() { 674 m_expr_lines.clear(); 675 m_expr_line_count = 0; 676 677 Debugger &debugger = GetCommandInterpreter().GetDebugger(); 678 bool color_prompt = debugger.GetUseColor(); 679 const bool multiple_lines = true; // Get multiple lines 680 IOHandlerSP io_handler_sp( 681 new IOHandlerEditline(debugger, IOHandler::Type::Expression, 682 "lldb-expr", // Name of input reader for history 683 llvm::StringRef(), // No prompt 684 llvm::StringRef(), // Continuation prompt 685 multiple_lines, color_prompt, 686 1, // Show line numbers starting at 1 687 *this)); 688 689 StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP(); 690 if (output_sp) { 691 output_sp->PutCString( 692 "Enter expressions, then terminate with an empty line to evaluate:\n"); 693 output_sp->Flush(); 694 } 695 debugger.RunIOHandlerAsync(io_handler_sp); 696 } 697 698 static EvaluateExpressionOptions 699 GetExprOptions(ExecutionContext &ctx, 700 CommandObjectExpression::CommandOptions command_options) { 701 command_options.OptionParsingStarting(&ctx); 702 703 // Default certain settings for REPL regardless of the global settings. 704 command_options.unwind_on_error = false; 705 command_options.ignore_breakpoints = false; 706 command_options.debug = false; 707 708 EvaluateExpressionOptions expr_options; 709 expr_options.SetUnwindOnError(command_options.unwind_on_error); 710 expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints); 711 expr_options.SetTryAllThreads(command_options.try_all_threads); 712 713 if (command_options.timeout > 0) 714 expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout)); 715 else 716 expr_options.SetTimeout(std::nullopt); 717 718 return expr_options; 719 } 720 721 void CommandObjectExpression::DoExecute(llvm::StringRef command, 722 CommandReturnObject &result) { 723 m_fixed_expression.clear(); 724 auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); 725 m_option_group.NotifyOptionParsingStarting(&exe_ctx); 726 727 if (command.empty()) { 728 GetMultilineExpression(); 729 return; 730 } 731 732 OptionsWithRaw args(command); 733 llvm::StringRef expr = args.GetRawPart(); 734 735 if (args.HasArgs()) { 736 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx)) 737 return; 738 739 if (m_repl_option.GetOptionValue().GetCurrentValue()) { 740 Target &target = GetTarget(); 741 // Drop into REPL 742 m_expr_lines.clear(); 743 m_expr_line_count = 0; 744 745 Debugger &debugger = target.GetDebugger(); 746 747 // Check if the LLDB command interpreter is sitting on top of a REPL 748 // that launched it... 749 if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, 750 IOHandler::Type::REPL)) { 751 // the LLDB command interpreter is sitting on top of a REPL that 752 // launched it, so just say the command interpreter is done and 753 // fall back to the existing REPL 754 m_interpreter.GetIOHandler(false)->SetIsDone(true); 755 } else { 756 // We are launching the REPL on top of the current LLDB command 757 // interpreter, so just push one 758 bool initialize = false; 759 Status repl_error; 760 REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language, 761 nullptr, false)); 762 763 if (!repl_sp) { 764 initialize = true; 765 repl_sp = target.GetREPL(repl_error, m_command_options.language, 766 nullptr, true); 767 if (!repl_error.Success()) { 768 result.SetError(repl_error); 769 return; 770 } 771 } 772 773 if (repl_sp) { 774 if (initialize) { 775 repl_sp->SetEvaluateOptions( 776 GetExprOptions(exe_ctx, m_command_options)); 777 repl_sp->SetFormatOptions(m_format_options); 778 repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 779 } 780 781 IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); 782 io_handler_sp->SetIsDone(false); 783 debugger.RunIOHandlerAsync(io_handler_sp); 784 } else { 785 repl_error = Status::FromErrorStringWithFormat( 786 "Couldn't create a REPL for %s", 787 Language::GetNameForLanguageType(m_command_options.language)); 788 result.SetError(repl_error); 789 return; 790 } 791 } 792 } 793 // No expression following options 794 else if (expr.empty()) { 795 GetMultilineExpression(); 796 return; 797 } 798 } 799 800 Target &target = GetTarget(); 801 if (EvaluateExpression(expr, result.GetOutputStream(), 802 result.GetErrorStream(), result)) { 803 804 if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) { 805 CommandHistory &history = m_interpreter.GetCommandHistory(); 806 // FIXME: Can we figure out what the user actually typed (e.g. some alias 807 // for expr???) 808 // If we can it would be nice to show that. 809 std::string fixed_command("expression "); 810 if (args.HasArgs()) { 811 // Add in any options that might have been in the original command: 812 fixed_command.append(std::string(args.GetArgStringWithDelimiter())); 813 fixed_command.append(m_fixed_expression); 814 } else 815 fixed_command.append(m_fixed_expression); 816 history.AppendString(fixed_command); 817 } 818 return; 819 } 820 result.SetStatus(eReturnStatusFailed); 821 } 822