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