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