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/Interpreter/Args.h" 17 #include "lldb/Core/Value.h" 18 #include "lldb/Core/InputReader.h" 19 #include "lldb/Core/ValueObjectVariable.h" 20 #include "lldb/Expression/ClangExpressionVariable.h" 21 #include "lldb/Expression/ClangUserExpression.h" 22 #include "lldb/Expression/ClangFunction.h" 23 #include "lldb/Expression/DWARFExpression.h" 24 #include "lldb/Host/Host.h" 25 #include "lldb/Core/Debugger.h" 26 #include "lldb/Interpreter/CommandInterpreter.h" 27 #include "lldb/Interpreter/CommandReturnObject.h" 28 #include "lldb/Target/ObjCLanguageRuntime.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/StringRef.h" 36 37 using namespace lldb; 38 using namespace lldb_private; 39 40 CommandObjectExpression::CommandOptions::CommandOptions (CommandInterpreter &interpreter) : 41 Options(interpreter) 42 { 43 // Keep only one place to reset the values to their defaults 44 OptionParsingStarting(); 45 } 46 47 48 CommandObjectExpression::CommandOptions::~CommandOptions () 49 { 50 } 51 52 Error 53 CommandObjectExpression::CommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg) 54 { 55 Error error; 56 57 char short_option = (char) m_getopt_table[option_idx].val; 58 59 switch (short_option) 60 { 61 //case 'l': 62 //if (language.SetLanguageFromCString (option_arg) == false) 63 //{ 64 // error.SetErrorStringWithFormat("Invalid language option argument '%s'.\n", option_arg); 65 //} 66 //break; 67 68 case 'g': 69 debug = true; 70 break; 71 72 case 'f': 73 error = Args::StringToFormat(option_arg, format, NULL); 74 break; 75 76 case 'o': 77 print_object = true; 78 break; 79 80 case 'd': 81 { 82 bool success; 83 bool result; 84 result = Args::StringToBoolean(option_arg, true, &success); 85 if (!success) 86 error.SetErrorStringWithFormat("Invalid dynamic value setting: \"%s\".\n", option_arg); 87 else 88 { 89 if (result) 90 use_dynamic = eLazyBoolYes; 91 else 92 use_dynamic = eLazyBoolNo; 93 } 94 } 95 break; 96 97 case 'u': 98 bool success; 99 unwind_on_error = Args::StringToBoolean(option_arg, true, &success); 100 if (!success) 101 error.SetErrorStringWithFormat("Could not convert \"%s\" to a boolean value.", option_arg); 102 break; 103 104 default: 105 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); 106 break; 107 } 108 109 return error; 110 } 111 112 void 113 CommandObjectExpression::CommandOptions::OptionParsingStarting () 114 { 115 //language.Clear(); 116 debug = false; 117 format = eFormatDefault; 118 print_object = false; 119 use_dynamic = eLazyBoolCalculate; 120 unwind_on_error = true; 121 show_types = true; 122 show_summary = true; 123 } 124 125 const OptionDefinition* 126 CommandObjectExpression::CommandOptions::GetDefinitions () 127 { 128 return g_option_table; 129 } 130 131 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) : 132 CommandObject (interpreter, 133 "expression", 134 "Evaluate a C/ObjC/C++ expression in the current program context, using variables currently in scope.", 135 NULL), 136 m_options (interpreter), 137 m_expr_line_count (0), 138 m_expr_lines () 139 { 140 SetHelpLong( 141 "Examples: \n\ 142 \n\ 143 expr my_struct->a = my_array[3] \n\ 144 expr -f bin -- (index * 8) + 5 \n\ 145 expr char c[] = \"foo\"; c[0]\n"); 146 147 CommandArgumentEntry arg; 148 CommandArgumentData expression_arg; 149 150 // Define the first (and only) variant of this arg. 151 expression_arg.arg_type = eArgTypeExpression; 152 expression_arg.arg_repetition = eArgRepeatPlain; 153 154 // There is only one variant this argument could be; put it into the argument entry. 155 arg.push_back (expression_arg); 156 157 // Push the data for the first argument into the m_arguments vector. 158 m_arguments.push_back (arg); 159 } 160 161 CommandObjectExpression::~CommandObjectExpression () 162 { 163 } 164 165 Options * 166 CommandObjectExpression::GetOptions () 167 { 168 return &m_options; 169 } 170 171 172 bool 173 CommandObjectExpression::Execute 174 ( 175 Args& command, 176 CommandReturnObject &result 177 ) 178 { 179 return false; 180 } 181 182 183 size_t 184 CommandObjectExpression::MultiLineExpressionCallback 185 ( 186 void *baton, 187 InputReader &reader, 188 lldb::InputReaderAction notification, 189 const char *bytes, 190 size_t bytes_len 191 ) 192 { 193 CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton; 194 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode(); 195 196 switch (notification) 197 { 198 case eInputReaderActivate: 199 if (!batch_mode) 200 { 201 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream(); 202 out_stream->Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:"); 203 out_stream->Flush(); 204 } 205 // Fall through 206 case eInputReaderReactivate: 207 break; 208 209 case eInputReaderDeactivate: 210 break; 211 212 case eInputReaderAsynchronousOutputWritten: 213 break; 214 215 case eInputReaderGotToken: 216 ++cmd_object_expr->m_expr_line_count; 217 if (bytes && bytes_len) 218 { 219 cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1); 220 } 221 222 if (bytes_len == 0) 223 reader.SetIsDone(true); 224 break; 225 226 case eInputReaderInterrupt: 227 cmd_object_expr->m_expr_lines.clear(); 228 reader.SetIsDone (true); 229 if (!batch_mode) 230 { 231 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream(); 232 out_stream->Printf("%s\n", "Expression evaluation cancelled."); 233 out_stream->Flush(); 234 } 235 break; 236 237 case eInputReaderEndOfFile: 238 reader.SetIsDone (true); 239 break; 240 241 case eInputReaderDone: 242 if (cmd_object_expr->m_expr_lines.size() > 0) 243 { 244 StreamSP output_stream = reader.GetDebugger().GetAsyncOutputStream(); 245 StreamSP error_stream = reader.GetDebugger().GetAsyncErrorStream(); 246 cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(), 247 output_stream.get(), 248 error_stream.get()); 249 output_stream->Flush(); 250 error_stream->Flush(); 251 } 252 break; 253 } 254 255 return bytes_len; 256 } 257 258 bool 259 CommandObjectExpression::EvaluateExpression 260 ( 261 const char *expr, 262 Stream *output_stream, 263 Stream *error_stream, 264 CommandReturnObject *result 265 ) 266 { 267 if (m_exe_ctx.target) 268 { 269 lldb::ValueObjectSP result_valobj_sp; 270 271 ExecutionResults exe_results; 272 273 bool keep_in_memory = true; 274 lldb::DynamicValueType use_dynamic; 275 // If use dynamic is not set, get it from the target: 276 switch (m_options.use_dynamic) 277 { 278 case eLazyBoolCalculate: 279 use_dynamic = m_exe_ctx.target->GetPreferDynamicValue(); 280 break; 281 case eLazyBoolYes: 282 use_dynamic = lldb::eDynamicCanRunTarget; 283 break; 284 case eLazyBoolNo: 285 use_dynamic = lldb::eNoDynamicValues; 286 break; 287 } 288 289 exe_results = m_exe_ctx.target->EvaluateExpression(expr, m_exe_ctx.frame, m_options.unwind_on_error, keep_in_memory, use_dynamic, result_valobj_sp); 290 291 if (exe_results == eExecutionInterrupted && !m_options.unwind_on_error) 292 { 293 uint32_t start_frame = 0; 294 uint32_t num_frames = 1; 295 uint32_t num_frames_with_source = 0; 296 if (m_exe_ctx.thread) 297 { 298 m_exe_ctx.thread->GetStatus (result->GetOutputStream(), 299 start_frame, 300 num_frames, 301 num_frames_with_source); 302 } 303 else if (m_exe_ctx.process) 304 { 305 bool only_threads_with_stop_reason = true; 306 m_exe_ctx.process->GetThreadStatus (result->GetOutputStream(), 307 only_threads_with_stop_reason, 308 start_frame, 309 num_frames, 310 num_frames_with_source); 311 } 312 } 313 314 if (result_valobj_sp) 315 { 316 if (result_valobj_sp->GetError().Success()) 317 { 318 if (m_options.format != eFormatDefault) 319 result_valobj_sp->SetFormat (m_options.format); 320 321 ValueObject::DumpValueObject (*(output_stream), 322 result_valobj_sp.get(), // Variable object to dump 323 result_valobj_sp->GetName().GetCString(),// Root object name 324 0, // Pointer depth to traverse (zero means stop at pointers) 325 0, // Current depth, this is the top most, so zero... 326 UINT32_MAX, // Max depth to go when dumping concrete types, dump everything... 327 m_options.show_types, // Show types when dumping? 328 false, // Show locations of variables, no since this is a host address which we don't care to see 329 m_options.print_object, // Print the objective C object? 330 use_dynamic, 331 true, // Scope is already checked. Const results are always in scope. 332 false); // Don't flatten output 333 if (result) 334 result->SetStatus (eReturnStatusSuccessFinishResult); 335 } 336 else 337 { 338 const char *error_cstr = result_valobj_sp->GetError().AsCString(); 339 if (error_cstr && error_cstr[0]) 340 { 341 int error_cstr_len = strlen (error_cstr); 342 const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n'; 343 if (strstr(error_cstr, "error:") != error_cstr) 344 error_stream->PutCString ("error: "); 345 error_stream->Write(error_cstr, error_cstr_len); 346 if (!ends_with_newline) 347 error_stream->EOL(); 348 } 349 else 350 { 351 error_stream->PutCString ("error: unknown error\n"); 352 } 353 354 if (result) 355 result->SetStatus (eReturnStatusFailed); 356 } 357 } 358 } 359 else 360 { 361 error_stream->Printf ("error: invalid execution context for expression\n"); 362 return false; 363 } 364 365 return true; 366 } 367 368 bool 369 CommandObjectExpression::ExecuteRawCommandString 370 ( 371 const char *command, 372 CommandReturnObject &result 373 ) 374 { 375 m_exe_ctx = m_interpreter.GetExecutionContext(); 376 377 m_options.NotifyOptionParsingStarting(); 378 379 const char * expr = NULL; 380 381 if (command[0] == '\0') 382 { 383 m_expr_lines.clear(); 384 m_expr_line_count = 0; 385 386 InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger())); 387 if (reader_sp) 388 { 389 Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback, 390 this, // baton 391 eInputReaderGranularityLine, // token size, to pass to callback function 392 NULL, // end token 393 NULL, // prompt 394 true)); // echo input 395 if (err.Success()) 396 { 397 m_interpreter.GetDebugger().PushInputReader (reader_sp); 398 result.SetStatus (eReturnStatusSuccessFinishNoResult); 399 } 400 else 401 { 402 result.AppendError (err.AsCString()); 403 result.SetStatus (eReturnStatusFailed); 404 } 405 } 406 else 407 { 408 result.AppendError("out of memory"); 409 result.SetStatus (eReturnStatusFailed); 410 } 411 return result.Succeeded(); 412 } 413 414 if (command[0] == '-') 415 { 416 // We have some options and these options MUST end with --. 417 const char *end_options = NULL; 418 const char *s = command; 419 while (s && s[0]) 420 { 421 end_options = ::strstr (s, "--"); 422 if (end_options) 423 { 424 end_options += 2; // Get past the "--" 425 if (::isspace (end_options[0])) 426 { 427 expr = end_options; 428 while (::isspace (*expr)) 429 ++expr; 430 break; 431 } 432 } 433 s = end_options; 434 } 435 436 if (end_options) 437 { 438 Args args (command, end_options - command); 439 if (!ParseOptions (args, result)) 440 return false; 441 442 Error error (m_options.NotifyOptionParsingFinished()); 443 if (error.Fail()) 444 { 445 result.AppendError (error.AsCString()); 446 result.SetStatus (eReturnStatusFailed); 447 return false; 448 } 449 } 450 } 451 452 if (expr == NULL) 453 expr = command; 454 455 if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result)) 456 return true; 457 458 result.SetStatus (eReturnStatusFailed); 459 return false; 460 } 461 462 OptionDefinition 463 CommandObjectExpression::CommandOptions::g_option_table[] = 464 { 465 //{ LLDB_OPT_SET_ALL, false, "language", 'l', required_argument, NULL, 0, "[c|c++|objc|objc++]", "Sets the language to use when parsing the expression."}, 466 //{ LLDB_OPT_SET_1, false, "format", 'f', required_argument, NULL, 0, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]", "Specify the format that the expression output should use."}, 467 { LLDB_OPT_SET_1, false, "format", 'f', required_argument, NULL, 0, eArgTypeExprFormat, "Specify the format that the expression output should use."}, 468 { LLDB_OPT_SET_2, false, "object-description", 'o', no_argument, NULL, 0, eArgTypeNone, "Print the object description of the value resulting from the expression."}, 469 { LLDB_OPT_SET_2, false, "dynamic-value", 'd', required_argument, NULL, 0, eArgTypeBoolean, "Upcast the value resulting from the expression to its dynamic type if available."}, 470 { LLDB_OPT_SET_ALL, false, "unwind-on-error", 'u', required_argument, NULL, 0, eArgTypeBoolean, "Clean up program state if the expression causes a crash, breakpoint hit or signal."}, 471 { LLDB_OPT_SET_ALL, false, "debug", 'g', no_argument, NULL, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."}, 472 { LLDB_OPT_SET_ALL, false, "use-ir", 'i', no_argument, NULL, 0, eArgTypeNone, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."}, 473 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL } 474 }; 475 476