1 //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 // C++ Includes 12 // Other libraries and framework includes 13 #include "llvm/ADT/STLExtras.h" 14 #include "llvm/ADT/StringRef.h" 15 16 // Project includes 17 #include "CommandObjectExpression.h" 18 #include "lldb/Core/Value.h" 19 #include "lldb/Core/ValueObjectVariable.h" 20 #include "lldb/DataFormatters/ValueObjectPrinter.h" 21 #include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" 22 #include "lldb/Expression/UserExpression.h" 23 #include "lldb/Expression/DWARFExpression.h" 24 #include "lldb/Expression/REPL.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/StringConvert.h" 27 #include "lldb/Core/Debugger.h" 28 #include "lldb/Interpreter/CommandInterpreter.h" 29 #include "lldb/Interpreter/CommandReturnObject.h" 30 #include "lldb/Target/Language.h" 31 #include "lldb/Symbol/ObjectFile.h" 32 #include "lldb/Symbol/Variable.h" 33 #include "lldb/Target/Process.h" 34 #include "lldb/Target/StackFrame.h" 35 #include "lldb/Target/Target.h" 36 #include "lldb/Target/Thread.h" 37 38 using namespace lldb; 39 using namespace lldb_private; 40 41 CommandObjectExpression::CommandOptions::CommandOptions () : 42 OptionGroup() 43 { 44 } 45 46 CommandObjectExpression::CommandOptions::~CommandOptions() = default; 47 48 static OptionEnumValueElement g_description_verbosity_type[] = 49 { 50 { eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", "Only show the description string"}, 51 { eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", "Show the full output, including persistent variable's name and type"}, 52 { 0, nullptr, nullptr } 53 }; 54 55 OptionDefinition 56 CommandObjectExpression::CommandOptions::g_option_table[] = 57 { 58 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."}, 59 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"}, 60 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."}, 61 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error", 'u', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, or raises a signal. Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."}, 62 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug", 'g', OptionParser::eNoArgument , nullptr, nullptr, 0, eArgTypeNone, "When specified, debug the JIT code by setting a breakpoint on the first instruction and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."}, 63 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Specifies the Language to use when parsing the expression. If not set the target.language setting is used." }, 64 { LLDB_OPT_SET_1, false, "description-verbosity", 'v', OptionParser::eOptionalArgument, nullptr, g_description_verbosity_type, 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."}, 65 }; 66 67 uint32_t 68 CommandObjectExpression::CommandOptions::GetNumDefinitions () 69 { 70 return llvm::array_lengthof(g_option_table); 71 } 72 73 Error 74 CommandObjectExpression::CommandOptions::SetOptionValue (CommandInterpreter &interpreter, 75 uint32_t option_idx, 76 const char *option_arg) 77 { 78 Error error; 79 80 const int short_option = g_option_table[option_idx].short_option; 81 82 switch (short_option) 83 { 84 case 'l': 85 language = Language::GetLanguageTypeFromString (option_arg); 86 if (language == eLanguageTypeUnknown) 87 error.SetErrorStringWithFormat ("unknown language type: '%s' for expression", option_arg); 88 break; 89 90 case 'a': 91 { 92 bool success; 93 bool result; 94 result = Args::StringToBoolean(option_arg, true, &success); 95 if (!success) 96 error.SetErrorStringWithFormat("invalid all-threads value setting: \"%s\"", option_arg); 97 else 98 try_all_threads = result; 99 } 100 break; 101 102 case 'i': 103 { 104 bool success; 105 bool tmp_value = Args::StringToBoolean(option_arg, true, &success); 106 if (success) 107 ignore_breakpoints = tmp_value; 108 else 109 error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); 110 break; 111 } 112 case 't': 113 { 114 bool success; 115 uint32_t result; 116 result = StringConvert::ToUInt32(option_arg, 0, 0, &success); 117 if (success) 118 timeout = result; 119 else 120 error.SetErrorStringWithFormat ("invalid timeout setting \"%s\"", option_arg); 121 } 122 break; 123 124 case 'u': 125 { 126 bool success; 127 bool tmp_value = Args::StringToBoolean(option_arg, true, &success); 128 if (success) 129 unwind_on_error = tmp_value; 130 else 131 error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); 132 break; 133 } 134 135 case 'v': 136 if (!option_arg) 137 { 138 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; 139 break; 140 } 141 m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error); 142 if (!error.Success()) 143 error.SetErrorStringWithFormat ("unrecognized value for description-verbosity '%s'", option_arg); 144 break; 145 146 case 'g': 147 debug = true; 148 unwind_on_error = false; 149 ignore_breakpoints = false; 150 break; 151 152 default: 153 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 154 break; 155 } 156 157 return error; 158 } 159 160 void 161 CommandObjectExpression::CommandOptions::OptionParsingStarting (CommandInterpreter &interpreter) 162 { 163 Process *process = interpreter.GetExecutionContext().GetProcessPtr(); 164 if (process != nullptr) 165 { 166 ignore_breakpoints = process->GetIgnoreBreakpointsInExpressions(); 167 unwind_on_error = process->GetUnwindOnErrorInExpressions(); 168 } 169 else 170 { 171 ignore_breakpoints = true; 172 unwind_on_error = true; 173 } 174 175 show_summary = true; 176 try_all_threads = true; 177 timeout = 0; 178 debug = false; 179 language = eLanguageTypeUnknown; 180 m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; 181 } 182 183 const OptionDefinition* 184 CommandObjectExpression::CommandOptions::GetDefinitions () 185 { 186 return g_option_table; 187 } 188 189 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) : 190 CommandObjectRaw(interpreter, 191 "expression", 192 "Evaluate an expression in the current program context, using user defined variables and variables currently in scope.", 193 nullptr, 194 eCommandProcessMustBePaused | eCommandTryTargetAPILock), 195 IOHandlerDelegate (IOHandlerDelegate::Completion::Expression), 196 m_option_group (interpreter), 197 m_format_options (eFormatDefault), 198 m_repl_option (LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, true), 199 m_command_options (), 200 m_expr_line_count (0), 201 m_expr_lines () 202 { 203 SetHelpLong( 204 R"( 205 Timeouts: 206 207 )" " If the expression can be evaluated statically (without running code) then it will be. \ 208 Otherwise, by default the expression will run on the current thread with a short timeout: \ 209 currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ 210 and resumed with all threads running. You can use the -a option to disable retrying on all \ 211 threads. You can use the -t option to set a shorter timeout." R"( 212 213 User defined variables: 214 215 )" " You can define your own variables for convenience or to be used in subsequent expressions. \ 216 You define them the same way you would define variables in C. If the first character of \ 217 your user defined variable is a $, then the variable's value will be available in future \ 218 expressions, otherwise it will just be available in the current expression." R"( 219 220 Continuing evaluation after a breakpoint: 221 222 )" " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ 223 you are done with your investigation, you can either remove the expression execution frames \ 224 from the stack with \"thread return -x\" or if you are still interested in the expression result \ 225 you can issue the \"continue\" command and the expression evaluation will complete and the \ 226 expression result will be available using the \"thread.completed-expression\" key in the thread \ 227 format." R"( 228 229 Examples: 230 231 expr my_struct->a = my_array[3] 232 expr -f bin -- (index * 8) + 5 233 expr unsigned int $foo = 5 234 expr char c[] = \"foo\"; c[0])" 235 ); 236 237 CommandArgumentEntry arg; 238 CommandArgumentData expression_arg; 239 240 // Define the first (and only) variant of this arg. 241 expression_arg.arg_type = eArgTypeExpression; 242 expression_arg.arg_repetition = eArgRepeatPlain; 243 244 // There is only one variant this argument could be; put it into the argument entry. 245 arg.push_back (expression_arg); 246 247 // Push the data for the first argument into the m_arguments vector. 248 m_arguments.push_back (arg); 249 250 // Add the "--format" and "--gdb-format" 251 m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1); 252 m_option_group.Append (&m_command_options); 253 m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 254 m_option_group.Append (&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 255 m_option_group.Finalize(); 256 } 257 258 CommandObjectExpression::~CommandObjectExpression() = default; 259 260 Options * 261 CommandObjectExpression::GetOptions () 262 { 263 return &m_option_group; 264 } 265 266 bool 267 CommandObjectExpression::EvaluateExpression(const char *expr, 268 Stream *output_stream, 269 Stream *error_stream, 270 CommandReturnObject *result) 271 { 272 // Don't use m_exe_ctx as this might be called asynchronously 273 // after the command object DoExecute has finished when doing 274 // multi-line expression that use an input reader... 275 ExecutionContext exe_ctx (m_interpreter.GetExecutionContext()); 276 277 Target *target = exe_ctx.GetTargetPtr(); 278 279 if (!target) 280 target = GetDummyTarget(); 281 282 if (target) 283 { 284 lldb::ValueObjectSP result_valobj_sp; 285 bool keep_in_memory = true; 286 StackFrame *frame = exe_ctx.GetFramePtr(); 287 288 EvaluateExpressionOptions options; 289 options.SetCoerceToId(m_varobj_options.use_objc); 290 options.SetUnwindOnError(m_command_options.unwind_on_error); 291 options.SetIgnoreBreakpoints (m_command_options.ignore_breakpoints); 292 options.SetKeepInMemory(keep_in_memory); 293 options.SetUseDynamic(m_varobj_options.use_dynamic); 294 options.SetTryAllThreads(m_command_options.try_all_threads); 295 options.SetDebug(m_command_options.debug); 296 options.SetLanguage(m_command_options.language); 297 298 // If there is any chance we are going to stop and want to see 299 // what went wrong with our expression, we should generate debug info 300 if (!m_command_options.ignore_breakpoints || 301 !m_command_options.unwind_on_error) 302 options.SetGenerateDebugInfo(true); 303 304 if (m_command_options.timeout > 0) 305 options.SetTimeoutUsec(m_command_options.timeout); 306 else 307 options.SetTimeoutUsec(0); 308 309 target->EvaluateExpression(expr, frame, result_valobj_sp, options); 310 311 if (result_valobj_sp) 312 { 313 Format format = m_format_options.GetFormat(); 314 315 if (result_valobj_sp->GetError().Success()) 316 { 317 if (format != eFormatVoid) 318 { 319 if (format != eFormatDefault) 320 result_valobj_sp->SetFormat (format); 321 322 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(m_command_options.m_verbosity,format)); 323 options.SetVariableFormatDisplayLanguage(result_valobj_sp->GetPreferredDisplayLanguage()); 324 325 result_valobj_sp->Dump(*output_stream,options); 326 327 if (result) 328 result->SetStatus (eReturnStatusSuccessFinishResult); 329 } 330 } 331 else 332 { 333 if (result_valobj_sp->GetError().GetError() == UserExpression::kNoResult) 334 { 335 if (format != eFormatVoid && m_interpreter.GetDebugger().GetNotifyVoid()) 336 { 337 error_stream->PutCString("(void)\n"); 338 } 339 340 if (result) 341 result->SetStatus (eReturnStatusSuccessFinishResult); 342 } 343 else 344 { 345 const char *error_cstr = result_valobj_sp->GetError().AsCString(); 346 if (error_cstr && error_cstr[0]) 347 { 348 const size_t error_cstr_len = strlen (error_cstr); 349 const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n'; 350 if (strstr(error_cstr, "error:") != error_cstr) 351 error_stream->PutCString ("error: "); 352 error_stream->Write(error_cstr, error_cstr_len); 353 if (!ends_with_newline) 354 error_stream->EOL(); 355 } 356 else 357 { 358 error_stream->PutCString ("error: unknown error\n"); 359 } 360 361 if (result) 362 result->SetStatus (eReturnStatusFailed); 363 } 364 } 365 } 366 } 367 else 368 { 369 error_stream->Printf ("error: invalid execution context for expression\n"); 370 return false; 371 } 372 373 return true; 374 } 375 376 void 377 CommandObjectExpression::IOHandlerInputComplete (IOHandler &io_handler, std::string &line) 378 { 379 io_handler.SetIsDone(true); 380 // StreamSP output_stream = io_handler.GetDebugger().GetAsyncOutputStream(); 381 // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); 382 StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 383 StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 384 385 EvaluateExpression (line.c_str(), 386 output_sp.get(), 387 error_sp.get()); 388 if (output_sp) 389 output_sp->Flush(); 390 if (error_sp) 391 error_sp->Flush(); 392 } 393 394 LineStatus 395 CommandObjectExpression::IOHandlerLinesUpdated (IOHandler &io_handler, 396 StringList &lines, 397 uint32_t line_idx, 398 Error &error) 399 { 400 if (line_idx == UINT32_MAX) 401 { 402 // Remove the last line from "lines" so it doesn't appear 403 // in our final expression 404 lines.PopBack(); 405 error.Clear(); 406 return LineStatus::Done; 407 } 408 else if (line_idx + 1 == lines.GetSize()) 409 { 410 // The last line was edited, if this line is empty, then we are done 411 // getting our multiple lines. 412 if (lines[line_idx].empty()) 413 return LineStatus::Done; 414 } 415 return LineStatus::Success; 416 } 417 418 void 419 CommandObjectExpression::GetMultilineExpression () 420 { 421 m_expr_lines.clear(); 422 m_expr_line_count = 0; 423 424 Debugger &debugger = GetCommandInterpreter().GetDebugger(); 425 bool color_prompt = debugger.GetUseColor(); 426 const bool multiple_lines = true; // Get multiple lines 427 IOHandlerSP io_handler_sp(new IOHandlerEditline(debugger, 428 IOHandler::Type::Expression, 429 "lldb-expr", // Name of input reader for history 430 nullptr, // No prompt 431 nullptr, // Continuation prompt 432 multiple_lines, 433 color_prompt, 434 1, // Show line numbers starting at 1 435 *this)); 436 437 StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); 438 if (output_sp) 439 { 440 output_sp->PutCString("Enter expressions, then terminate with an empty line to evaluate:\n"); 441 output_sp->Flush(); 442 } 443 debugger.PushIOHandler(io_handler_sp); 444 } 445 446 bool 447 CommandObjectExpression::DoExecute(const char *command, 448 CommandReturnObject &result) 449 { 450 m_option_group.NotifyOptionParsingStarting(); 451 452 const char * expr = nullptr; 453 454 if (command[0] == '\0') 455 { 456 GetMultilineExpression (); 457 return result.Succeeded(); 458 } 459 460 if (command[0] == '-') 461 { 462 // We have some options and these options MUST end with --. 463 const char *end_options = nullptr; 464 const char *s = command; 465 while (s && s[0]) 466 { 467 end_options = ::strstr (s, "--"); 468 if (end_options) 469 { 470 end_options += 2; // Get past the "--" 471 if (::isspace (end_options[0])) 472 { 473 expr = end_options; 474 while (::isspace (*expr)) 475 ++expr; 476 break; 477 } 478 } 479 s = end_options; 480 } 481 482 if (end_options) 483 { 484 Args args (llvm::StringRef(command, end_options - command)); 485 if (!ParseOptions (args, result)) 486 return false; 487 488 Error error (m_option_group.NotifyOptionParsingFinished()); 489 if (error.Fail()) 490 { 491 result.AppendError (error.AsCString()); 492 result.SetStatus (eReturnStatusFailed); 493 return false; 494 } 495 496 if (m_repl_option.GetOptionValue().GetCurrentValue()) 497 { 498 Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); 499 if (target) 500 { 501 // Drop into REPL 502 m_expr_lines.clear(); 503 m_expr_line_count = 0; 504 505 Debugger &debugger = target->GetDebugger(); 506 507 // Check if the LLDB command interpreter is sitting on top of a REPL that 508 // launched it... 509 if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, IOHandler::Type::REPL)) 510 { 511 // the LLDB command interpreter is sitting on top of a REPL that launched it, 512 // so just say the command interpreter is done and fall back to the existing REPL 513 m_interpreter.GetIOHandler(false)->SetIsDone(true); 514 } 515 else 516 { 517 // We are launching the REPL on top of the current LLDB command interpreter, 518 // so just push one 519 bool initialize = false; 520 Error repl_error; 521 REPLSP repl_sp (target->GetREPL(repl_error, m_command_options.language, nullptr, false)); 522 523 if (!repl_sp) 524 { 525 initialize = true; 526 repl_sp = target->GetREPL(repl_error, m_command_options.language, nullptr, true); 527 if (!repl_error.Success()) 528 { 529 result.SetError(repl_error); 530 return result.Succeeded(); 531 } 532 } 533 534 if (repl_sp) 535 { 536 if (initialize) 537 { 538 repl_sp->SetCommandOptions(m_command_options); 539 repl_sp->SetFormatOptions(m_format_options); 540 repl_sp->SetValueObjectDisplayOptions(m_varobj_options); 541 } 542 543 IOHandlerSP io_handler_sp (repl_sp->GetIOHandler()); 544 545 io_handler_sp->SetIsDone(false); 546 547 debugger.PushIOHandler(io_handler_sp); 548 } 549 else 550 { 551 repl_error.SetErrorStringWithFormat("Couldn't create a REPL for %s", Language::GetNameForLanguageType(m_command_options.language)); 552 result.SetError(repl_error); 553 return result.Succeeded(); 554 } 555 } 556 } 557 } 558 // No expression following options 559 else if (expr == nullptr || expr[0] == '\0') 560 { 561 GetMultilineExpression (); 562 return result.Succeeded(); 563 } 564 } 565 } 566 567 if (expr == nullptr) 568 expr = command; 569 570 if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result)) 571 return true; 572 573 result.SetStatus (eReturnStatusFailed); 574 return false; 575 } 576