1 //===-- CommandInterpreter.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 "lldb/lldb-python.h" 11 12 #include <string> 13 #include <vector> 14 #include <stdlib.h> 15 16 #include "CommandObjectScript.h" 17 #include "lldb/Interpreter/CommandObjectRegexCommand.h" 18 19 #include "../Commands/CommandObjectApropos.h" 20 #include "../Commands/CommandObjectArgs.h" 21 #include "../Commands/CommandObjectBreakpoint.h" 22 #include "../Commands/CommandObjectDisassemble.h" 23 #include "../Commands/CommandObjectExpression.h" 24 #include "../Commands/CommandObjectFrame.h" 25 #include "../Commands/CommandObjectGUI.h" 26 #include "../Commands/CommandObjectHelp.h" 27 #include "../Commands/CommandObjectLog.h" 28 #include "../Commands/CommandObjectMemory.h" 29 #include "../Commands/CommandObjectPlatform.h" 30 #include "../Commands/CommandObjectPlugin.h" 31 #include "../Commands/CommandObjectProcess.h" 32 #include "../Commands/CommandObjectQuit.h" 33 #include "../Commands/CommandObjectRegister.h" 34 #include "../Commands/CommandObjectSettings.h" 35 #include "../Commands/CommandObjectSource.h" 36 #include "../Commands/CommandObjectCommands.h" 37 #include "../Commands/CommandObjectSyntax.h" 38 #include "../Commands/CommandObjectTarget.h" 39 #include "../Commands/CommandObjectThread.h" 40 #include "../Commands/CommandObjectType.h" 41 #include "../Commands/CommandObjectVersion.h" 42 #include "../Commands/CommandObjectWatchpoint.h" 43 44 45 #include "lldb/Core/Debugger.h" 46 #include "lldb/Core/Log.h" 47 #include "lldb/Core/State.h" 48 #include "lldb/Core/Stream.h" 49 #include "lldb/Core/StreamFile.h" 50 #include "lldb/Core/Timer.h" 51 52 #ifndef LLDB_DISABLE_LIBEDIT 53 #include "lldb/Host/Editline.h" 54 #endif 55 #include "lldb/Host/Host.h" 56 #include "lldb/Host/HostInfo.h" 57 58 #include "lldb/Interpreter/Args.h" 59 #include "lldb/Interpreter/CommandCompletions.h" 60 #include "lldb/Interpreter/CommandInterpreter.h" 61 #include "lldb/Interpreter/CommandReturnObject.h" 62 #include "lldb/Interpreter/Options.h" 63 #include "lldb/Interpreter/ScriptInterpreterNone.h" 64 #include "lldb/Interpreter/ScriptInterpreterPython.h" 65 66 67 #include "lldb/Target/Process.h" 68 #include "lldb/Target/Thread.h" 69 #include "lldb/Target/TargetList.h" 70 71 #include "lldb/Utility/CleanUp.h" 72 73 #include "llvm/ADT/SmallString.h" 74 #include "llvm/ADT/STLExtras.h" 75 #include "llvm/Support/Path.h" 76 77 using namespace lldb; 78 using namespace lldb_private; 79 80 81 static PropertyDefinition 82 g_properties[] = 83 { 84 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." }, 85 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." }, 86 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." }, 87 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr } 88 }; 89 90 enum 91 { 92 ePropertyExpandRegexAliases = 0, 93 ePropertyPromptOnQuit = 1, 94 ePropertyStopCmdSourceOnError = 2 95 }; 96 97 ConstString & 98 CommandInterpreter::GetStaticBroadcasterClass () 99 { 100 static ConstString class_name ("lldb.commandInterpreter"); 101 return class_name; 102 } 103 104 CommandInterpreter::CommandInterpreter 105 ( 106 Debugger &debugger, 107 ScriptLanguage script_language, 108 bool synchronous_execution 109 ) : 110 Broadcaster (&debugger, "lldb.command-interpreter"), 111 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))), 112 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand), 113 m_debugger (debugger), 114 m_synchronous_execution (synchronous_execution), 115 m_skip_lldbinit_files (false), 116 m_skip_app_init_files (false), 117 m_script_interpreter_ap (), 118 m_command_io_handler_sp (), 119 m_comment_char ('#'), 120 m_batch_command_mode (false), 121 m_truncation_warning(eNoTruncation), 122 m_command_source_depth (0), 123 m_num_errors(0), 124 m_quit_requested(false), 125 m_stopped_for_crash(false) 126 127 { 128 debugger.SetScriptLanguage (script_language); 129 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit"); 130 SetEventName (eBroadcastBitResetPrompt, "reset-prompt"); 131 SetEventName (eBroadcastBitQuitCommandReceived, "quit"); 132 CheckInWithManager (); 133 m_collection_sp->Initialize (g_properties); 134 } 135 136 bool 137 CommandInterpreter::GetExpandRegexAliases () const 138 { 139 const uint32_t idx = ePropertyExpandRegexAliases; 140 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); 141 } 142 143 bool 144 CommandInterpreter::GetPromptOnQuit () const 145 { 146 const uint32_t idx = ePropertyPromptOnQuit; 147 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); 148 } 149 150 bool 151 CommandInterpreter::GetStopCmdSourceOnError () const 152 { 153 const uint32_t idx = ePropertyStopCmdSourceOnError; 154 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); 155 } 156 157 void 158 CommandInterpreter::Initialize () 159 { 160 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 161 162 CommandReturnObject result; 163 164 LoadCommandDictionary (); 165 166 // Set up some initial aliases. 167 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false); 168 if (cmd_obj_sp) 169 { 170 AddAlias ("q", cmd_obj_sp); 171 AddAlias ("exit", cmd_obj_sp); 172 } 173 174 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false); 175 if (cmd_obj_sp) 176 { 177 AddAlias ("attach", cmd_obj_sp); 178 } 179 180 cmd_obj_sp = GetCommandSPExact ("process detach",false); 181 if (cmd_obj_sp) 182 { 183 AddAlias ("detach", cmd_obj_sp); 184 } 185 186 cmd_obj_sp = GetCommandSPExact ("process continue", false); 187 if (cmd_obj_sp) 188 { 189 AddAlias ("c", cmd_obj_sp); 190 AddAlias ("continue", cmd_obj_sp); 191 } 192 193 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false); 194 if (cmd_obj_sp) 195 AddAlias ("b", cmd_obj_sp); 196 197 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false); 198 if (cmd_obj_sp) 199 AddAlias ("tbreak", cmd_obj_sp); 200 201 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false); 202 if (cmd_obj_sp) 203 { 204 AddAlias ("stepi", cmd_obj_sp); 205 AddAlias ("si", cmd_obj_sp); 206 } 207 208 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false); 209 if (cmd_obj_sp) 210 { 211 AddAlias ("nexti", cmd_obj_sp); 212 AddAlias ("ni", cmd_obj_sp); 213 } 214 215 cmd_obj_sp = GetCommandSPExact ("thread step-in", false); 216 if (cmd_obj_sp) 217 { 218 AddAlias ("s", cmd_obj_sp); 219 AddAlias ("step", cmd_obj_sp); 220 } 221 222 cmd_obj_sp = GetCommandSPExact ("thread step-over", false); 223 if (cmd_obj_sp) 224 { 225 AddAlias ("n", cmd_obj_sp); 226 AddAlias ("next", cmd_obj_sp); 227 } 228 229 cmd_obj_sp = GetCommandSPExact ("thread step-out", false); 230 if (cmd_obj_sp) 231 { 232 AddAlias ("finish", cmd_obj_sp); 233 } 234 235 cmd_obj_sp = GetCommandSPExact ("frame select", false); 236 if (cmd_obj_sp) 237 { 238 AddAlias ("f", cmd_obj_sp); 239 } 240 241 cmd_obj_sp = GetCommandSPExact ("thread select", false); 242 if (cmd_obj_sp) 243 { 244 AddAlias ("t", cmd_obj_sp); 245 } 246 247 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false); 248 if (cmd_obj_sp) 249 { 250 AddAlias ("j", cmd_obj_sp); 251 AddAlias ("jump", cmd_obj_sp); 252 } 253 254 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false); 255 if (cmd_obj_sp) 256 { 257 AddAlias ("l", cmd_obj_sp); 258 AddAlias ("list", cmd_obj_sp); 259 } 260 261 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false); 262 if (cmd_obj_sp) 263 { 264 AddAlias ("env", cmd_obj_sp); 265 } 266 267 cmd_obj_sp = GetCommandSPExact ("memory read", false); 268 if (cmd_obj_sp) 269 AddAlias ("x", cmd_obj_sp); 270 271 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false); 272 if (cmd_obj_sp) 273 AddAlias ("up", cmd_obj_sp); 274 275 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false); 276 if (cmd_obj_sp) 277 AddAlias ("down", cmd_obj_sp); 278 279 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false); 280 if (cmd_obj_sp) 281 AddAlias ("display", cmd_obj_sp); 282 283 cmd_obj_sp = GetCommandSPExact ("disassemble", false); 284 if (cmd_obj_sp) 285 AddAlias ("dis", cmd_obj_sp); 286 287 cmd_obj_sp = GetCommandSPExact ("disassemble", false); 288 if (cmd_obj_sp) 289 AddAlias ("di", cmd_obj_sp); 290 291 292 293 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false); 294 if (cmd_obj_sp) 295 AddAlias ("undisplay", cmd_obj_sp); 296 297 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false); 298 if (cmd_obj_sp) 299 AddAlias ("bt", cmd_obj_sp); 300 301 cmd_obj_sp = GetCommandSPExact ("target create", false); 302 if (cmd_obj_sp) 303 AddAlias ("file", cmd_obj_sp); 304 305 cmd_obj_sp = GetCommandSPExact ("target modules", false); 306 if (cmd_obj_sp) 307 AddAlias ("image", cmd_obj_sp); 308 309 310 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector); 311 312 cmd_obj_sp = GetCommandSPExact ("expression", false); 313 if (cmd_obj_sp) 314 { 315 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 316 AddAlias ("p", cmd_obj_sp); 317 AddAlias ("print", cmd_obj_sp); 318 AddAlias ("call", cmd_obj_sp); 319 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp); 320 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp); 321 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp); 322 323 alias_arguments_vector_sp.reset (new OptionArgVector); 324 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp); 325 AddAlias ("po", cmd_obj_sp); 326 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp); 327 } 328 329 cmd_obj_sp = GetCommandSPExact ("process kill", false); 330 if (cmd_obj_sp) 331 { 332 AddAlias ("kill", cmd_obj_sp); 333 } 334 335 cmd_obj_sp = GetCommandSPExact ("process launch", false); 336 if (cmd_obj_sp) 337 { 338 alias_arguments_vector_sp.reset (new OptionArgVector); 339 #if defined (__arm__) || defined (__arm64__) || defined (__aarch64__) 340 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 341 #else 342 std::string shell_option; 343 shell_option.append("--shell="); 344 shell_option.append(HostInfo::GetDefaultShell().GetPath()); 345 shell_option.append(" --"); 346 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp); 347 #endif 348 AddAlias ("r", cmd_obj_sp); 349 AddAlias ("run", cmd_obj_sp); 350 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp); 351 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp); 352 } 353 354 cmd_obj_sp = GetCommandSPExact ("target symbols add", false); 355 if (cmd_obj_sp) 356 { 357 AddAlias ("add-dsym", cmd_obj_sp); 358 } 359 360 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false); 361 if (cmd_obj_sp) 362 { 363 alias_arguments_vector_sp.reset (new OptionArgVector); 364 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp); 365 AddAlias ("rbreak", cmd_obj_sp); 366 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp); 367 } 368 } 369 370 void 371 CommandInterpreter::Clear() 372 { 373 m_command_io_handler_sp.reset(); 374 375 if (m_script_interpreter_ap) 376 m_script_interpreter_ap->Clear(); 377 } 378 379 const char * 380 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) 381 { 382 // This function has not yet been implemented. 383 384 // Look for any embedded script command 385 // If found, 386 // get interpreter object from the command dictionary, 387 // call execute_one_command on it, 388 // get the results as a string, 389 // substitute that string for current stuff. 390 391 return arg; 392 } 393 394 395 void 396 CommandInterpreter::LoadCommandDictionary () 397 { 398 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 399 400 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); 401 402 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); 403 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); 404 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); 405 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); 406 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); 407 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); 408 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this)); 409 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); 410 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); 411 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); 412 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this)); 413 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this)); 414 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); 415 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); 416 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); 417 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); 418 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); 419 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); 420 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); 421 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); 422 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this)); 423 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this)); 424 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this)); 425 426 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"}, 427 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"}, 428 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"}, 429 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}, 430 {"^(-.*)$", "breakpoint set %1"}, 431 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"}, 432 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"}, 433 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}}; 434 435 size_t num_regexes = llvm::array_lengthof(break_regexes); 436 437 std::unique_ptr<CommandObjectRegexCommand> 438 break_regex_cmd_ap(new CommandObjectRegexCommand (*this, 439 "_regexp-break", 440 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.", 441 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 442 2, 443 CommandCompletions::eSymbolCompletion | 444 CommandCompletions::eSourceFileCompletion)); 445 446 if (break_regex_cmd_ap.get()) 447 { 448 bool success = true; 449 for (size_t i = 0; i < num_regexes; i++) 450 { 451 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]); 452 if (!success) 453 break; 454 } 455 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); 456 457 if (success) 458 { 459 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); 460 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; 461 } 462 } 463 464 std::unique_ptr<CommandObjectRegexCommand> 465 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this, 466 "_regexp-tbreak", 467 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.", 468 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 469 2, 470 CommandCompletions::eSymbolCompletion | 471 CommandCompletions::eSourceFileCompletion)); 472 473 if (tbreak_regex_cmd_ap.get()) 474 { 475 bool success = true; 476 for (size_t i = 0; i < num_regexes; i++) 477 { 478 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer. 479 char buffer[1024]; 480 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o"); 481 assert (num_printed < 1024); 482 // Quiet unused variable warning for release builds. 483 (void) num_printed; 484 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer); 485 if (!success) 486 break; 487 } 488 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); 489 490 if (success) 491 { 492 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release()); 493 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp; 494 } 495 } 496 497 std::unique_ptr<CommandObjectRegexCommand> 498 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this, 499 "_regexp-attach", 500 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.", 501 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 502 2)); 503 if (attach_regex_cmd_ap.get()) 504 { 505 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") && 506 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach' 507 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") && 508 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) 509 { 510 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release()); 511 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp; 512 } 513 } 514 515 std::unique_ptr<CommandObjectRegexCommand> 516 down_regex_cmd_ap(new CommandObjectRegexCommand (*this, 517 "_regexp-down", 518 "Go down \"n\" frames in the stack (1 frame by default).", 519 "_regexp-down [n]", 2)); 520 if (down_regex_cmd_ap.get()) 521 { 522 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && 523 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1")) 524 { 525 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); 526 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp; 527 } 528 } 529 530 std::unique_ptr<CommandObjectRegexCommand> 531 up_regex_cmd_ap(new CommandObjectRegexCommand (*this, 532 "_regexp-up", 533 "Go up \"n\" frames in the stack (1 frame by default).", 534 "_regexp-up [n]", 2)); 535 if (up_regex_cmd_ap.get()) 536 { 537 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && 538 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) 539 { 540 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); 541 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp; 542 } 543 } 544 545 std::unique_ptr<CommandObjectRegexCommand> 546 display_regex_cmd_ap(new CommandObjectRegexCommand (*this, 547 "_regexp-display", 548 "Add an expression evaluation stop-hook.", 549 "_regexp-display expression", 2)); 550 if (display_regex_cmd_ap.get()) 551 { 552 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\"")) 553 { 554 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release()); 555 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp; 556 } 557 } 558 559 std::unique_ptr<CommandObjectRegexCommand> 560 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this, 561 "_regexp-undisplay", 562 "Remove an expression evaluation stop-hook.", 563 "_regexp-undisplay stop-hook-number", 2)); 564 if (undisplay_regex_cmd_ap.get()) 565 { 566 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1")) 567 { 568 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release()); 569 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp; 570 } 571 } 572 573 std::unique_ptr<CommandObjectRegexCommand> 574 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this, 575 "gdb-remote", 576 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.", 577 "gdb-remote [<hostname>:]<portnum>", 2)); 578 if (connect_gdb_remote_cmd_ap.get()) 579 { 580 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") && 581 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1")) 582 { 583 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release()); 584 m_command_dict[command_sp->GetCommandName ()] = command_sp; 585 } 586 } 587 588 std::unique_ptr<CommandObjectRegexCommand> 589 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this, 590 "kdp-remote", 591 "Connect to a remote KDP server. udp port 41139 is the default port number.", 592 "kdp-remote <hostname>[:<portnum>]", 2)); 593 if (connect_kdp_remote_cmd_ap.get()) 594 { 595 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") && 596 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) 597 { 598 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release()); 599 m_command_dict[command_sp->GetCommandName ()] = command_sp; 600 } 601 } 602 603 std::unique_ptr<CommandObjectRegexCommand> 604 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this, 605 "_regexp-bt", 606 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.", 607 "bt [<digit>|all]", 2)); 608 if (bt_regex_cmd_ap.get()) 609 { 610 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace 611 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and 612 // so now "bt 3" is the preferred form, in line with gdb. 613 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") && 614 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") && 615 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") && 616 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) 617 { 618 CommandObjectSP command_sp(bt_regex_cmd_ap.release()); 619 m_command_dict[command_sp->GetCommandName ()] = command_sp; 620 } 621 } 622 623 std::unique_ptr<CommandObjectRegexCommand> 624 list_regex_cmd_ap(new CommandObjectRegexCommand (*this, 625 "_regexp-list", 626 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.", 627 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]", 628 2, 629 CommandCompletions::eSourceFileCompletion)); 630 if (list_regex_cmd_ap.get()) 631 { 632 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") && 633 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") && 634 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") && 635 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") && 636 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") && 637 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") && 638 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) 639 { 640 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release()); 641 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp; 642 } 643 } 644 645 std::unique_ptr<CommandObjectRegexCommand> 646 env_regex_cmd_ap(new CommandObjectRegexCommand (*this, 647 "_regexp-env", 648 "Implements a shortcut to viewing and setting environment variables.", 649 "_regexp-env\n_regexp-env FOO=BAR", 2)); 650 if (env_regex_cmd_ap.get()) 651 { 652 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") && 653 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1")) 654 { 655 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release()); 656 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp; 657 } 658 } 659 660 std::unique_ptr<CommandObjectRegexCommand> 661 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this, 662 "_regexp-jump", 663 "Sets the program counter to a new address.", 664 "_regexp-jump [<line>]\n" 665 "_regexp-jump [<+-lineoffset>]\n" 666 "_regexp-jump [<file>:<line>]\n" 667 "_regexp-jump [*<addr>]\n", 2)); 668 if (jump_regex_cmd_ap.get()) 669 { 670 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") && 671 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") && 672 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") && 673 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1")) 674 { 675 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release()); 676 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp; 677 } 678 } 679 680 } 681 682 int 683 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, 684 StringList &matches) 685 { 686 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); 687 688 if (include_aliases) 689 { 690 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); 691 } 692 693 return matches.GetSize(); 694 } 695 696 CommandObjectSP 697 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) 698 { 699 CommandObject::CommandMap::iterator pos; 700 CommandObjectSP command_sp; 701 702 std::string cmd(cmd_cstr); 703 704 if (HasCommands()) 705 { 706 pos = m_command_dict.find(cmd); 707 if (pos != m_command_dict.end()) 708 command_sp = pos->second; 709 } 710 711 if (include_aliases && HasAliases()) 712 { 713 pos = m_alias_dict.find(cmd); 714 if (pos != m_alias_dict.end()) 715 command_sp = pos->second; 716 } 717 718 if (HasUserCommands()) 719 { 720 pos = m_user_dict.find(cmd); 721 if (pos != m_user_dict.end()) 722 command_sp = pos->second; 723 } 724 725 if (!exact && !command_sp) 726 { 727 // We will only get into here if we didn't find any exact matches. 728 729 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 730 731 StringList local_matches; 732 if (matches == nullptr) 733 matches = &local_matches; 734 735 unsigned int num_cmd_matches = 0; 736 unsigned int num_alias_matches = 0; 737 unsigned int num_user_matches = 0; 738 739 // Look through the command dictionaries one by one, and if we get only one match from any of 740 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. 741 742 if (HasCommands()) 743 { 744 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); 745 } 746 747 if (num_cmd_matches == 1) 748 { 749 cmd.assign(matches->GetStringAtIndex(0)); 750 pos = m_command_dict.find(cmd); 751 if (pos != m_command_dict.end()) 752 real_match_sp = pos->second; 753 } 754 755 if (include_aliases && HasAliases()) 756 { 757 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); 758 759 } 760 761 if (num_alias_matches == 1) 762 { 763 cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); 764 pos = m_alias_dict.find(cmd); 765 if (pos != m_alias_dict.end()) 766 alias_match_sp = pos->second; 767 } 768 769 if (HasUserCommands()) 770 { 771 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); 772 } 773 774 if (num_user_matches == 1) 775 { 776 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); 777 778 pos = m_user_dict.find (cmd); 779 if (pos != m_user_dict.end()) 780 user_match_sp = pos->second; 781 } 782 783 // If we got exactly one match, return that, otherwise return the match list. 784 785 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) 786 { 787 if (num_cmd_matches) 788 return real_match_sp; 789 else if (num_alias_matches) 790 return alias_match_sp; 791 else 792 return user_match_sp; 793 } 794 } 795 else if (matches && command_sp) 796 { 797 matches->AppendString (cmd_cstr); 798 } 799 800 801 return command_sp; 802 } 803 804 bool 805 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace) 806 { 807 if (name && name[0]) 808 { 809 std::string name_sstr(name); 810 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end()); 811 if (found && !can_replace) 812 return false; 813 if (found && m_command_dict[name_sstr]->IsRemovable() == false) 814 return false; 815 m_command_dict[name_sstr] = cmd_sp; 816 return true; 817 } 818 return false; 819 } 820 821 bool 822 CommandInterpreter::AddUserCommand (std::string name, 823 const lldb::CommandObjectSP &cmd_sp, 824 bool can_replace) 825 { 826 if (!name.empty()) 827 { 828 829 const char* name_cstr = name.c_str(); 830 831 // do not allow replacement of internal commands 832 if (CommandExists(name_cstr)) 833 { 834 if (can_replace == false) 835 return false; 836 if (m_command_dict[name]->IsRemovable() == false) 837 return false; 838 } 839 840 if (UserCommandExists(name_cstr)) 841 { 842 if (can_replace == false) 843 return false; 844 if (m_user_dict[name]->IsRemovable() == false) 845 return false; 846 } 847 848 m_user_dict[name] = cmd_sp; 849 return true; 850 } 851 return false; 852 } 853 854 CommandObjectSP 855 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) 856 { 857 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command. 858 CommandObjectSP ret_val; // Possibly empty return value. 859 860 if (cmd_cstr == nullptr) 861 return ret_val; 862 863 if (cmd_words.GetArgumentCount() == 1) 864 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr); 865 else 866 { 867 // We have a multi-word command (seemingly), so we need to do more work. 868 // First, get the cmd_obj_sp for the first word in the command. 869 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr); 870 if (cmd_obj_sp.get() != nullptr) 871 { 872 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a 873 // command name), and find the appropriate sub-command SP for each command word.... 874 size_t end = cmd_words.GetArgumentCount(); 875 for (size_t j= 1; j < end; ++j) 876 { 877 if (cmd_obj_sp->IsMultiwordObject()) 878 { 879 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j)); 880 if (cmd_obj_sp.get() == nullptr) 881 // The sub-command name was invalid. Fail and return the empty 'ret_val'. 882 return ret_val; 883 } 884 else 885 // We have more words in the command name, but we don't have a multiword object. Fail and return 886 // empty 'ret_val'. 887 return ret_val; 888 } 889 // We successfully looped through all the command words and got valid command objects for them. Assign the 890 // last object retrieved to 'ret_val'. 891 ret_val = cmd_obj_sp; 892 } 893 } 894 return ret_val; 895 } 896 897 CommandObject * 898 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) 899 { 900 return GetCommandSPExact (cmd_cstr, include_aliases).get(); 901 } 902 903 CommandObject * 904 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) 905 { 906 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); 907 908 // If we didn't find an exact match to the command string in the commands, look in 909 // the aliases. 910 911 if (command_obj) 912 return command_obj; 913 914 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); 915 916 if (command_obj) 917 return command_obj; 918 919 // If there wasn't an exact match then look for an inexact one in just the commands 920 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get(); 921 922 // Finally, if there wasn't an inexact match among the commands, look for an inexact 923 // match in both the commands and aliases. 924 925 if (command_obj) 926 { 927 if (matches) 928 matches->AppendString(command_obj->GetCommandName()); 929 return command_obj; 930 } 931 932 return GetCommandSP(cmd_cstr, true, false, matches).get(); 933 } 934 935 bool 936 CommandInterpreter::CommandExists (const char *cmd) 937 { 938 return m_command_dict.find(cmd) != m_command_dict.end(); 939 } 940 941 bool 942 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp, 943 const char *options_args, 944 OptionArgVectorSP &option_arg_vector_sp) 945 { 946 bool success = true; 947 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 948 949 if (!options_args || (strlen (options_args) < 1)) 950 return true; 951 952 std::string options_string (options_args); 953 Args args (options_args); 954 CommandReturnObject result; 955 // Check to see if the command being aliased can take any command options. 956 Options *options = cmd_obj_sp->GetOptions (); 957 if (options) 958 { 959 // See if any options were specified as part of the alias; if so, handle them appropriately. 960 options->NotifyOptionParsingStarting (); 961 args.Unshift ("dummy_arg"); 962 args.ParseAliasOptions (*options, result, option_arg_vector, options_string); 963 args.Shift (); 964 if (result.Succeeded()) 965 options->VerifyPartialOptions (result); 966 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted) 967 { 968 result.AppendError ("Unable to create requested alias.\n"); 969 return false; 970 } 971 } 972 973 if (!options_string.empty()) 974 { 975 if (cmd_obj_sp->WantsRawCommandString ()) 976 option_arg_vector->push_back (OptionArgPair ("<argument>", 977 OptionArgValue (-1, 978 options_string))); 979 else 980 { 981 const size_t argc = args.GetArgumentCount(); 982 for (size_t i = 0; i < argc; ++i) 983 if (strcmp (args.GetArgumentAtIndex (i), "") != 0) 984 option_arg_vector->push_back 985 (OptionArgPair ("<argument>", 986 OptionArgValue (-1, 987 std::string (args.GetArgumentAtIndex (i))))); 988 } 989 } 990 991 return success; 992 } 993 994 bool 995 CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name) 996 { 997 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end()); 998 if (exact_match) 999 { 1000 full_name.assign(cmd); 1001 return exact_match; 1002 } 1003 else 1004 { 1005 StringList matches; 1006 size_t num_alias_matches; 1007 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches); 1008 if (num_alias_matches == 1) 1009 { 1010 // Make sure this isn't shadowing a command in the regular command space: 1011 StringList regular_matches; 1012 const bool include_aliases = false; 1013 const bool exact = false; 1014 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, ®ular_matches)); 1015 if (cmd_obj_sp || regular_matches.GetSize() > 0) 1016 return false; 1017 else 1018 { 1019 full_name.assign (matches.GetStringAtIndex(0)); 1020 return true; 1021 } 1022 } 1023 else 1024 return false; 1025 } 1026 } 1027 1028 bool 1029 CommandInterpreter::AliasExists (const char *cmd) 1030 { 1031 return m_alias_dict.find(cmd) != m_alias_dict.end(); 1032 } 1033 1034 bool 1035 CommandInterpreter::UserCommandExists (const char *cmd) 1036 { 1037 return m_user_dict.find(cmd) != m_user_dict.end(); 1038 } 1039 1040 void 1041 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) 1042 { 1043 command_obj_sp->SetIsAlias (true); 1044 m_alias_dict[alias_name] = command_obj_sp; 1045 } 1046 1047 bool 1048 CommandInterpreter::RemoveAlias (const char *alias_name) 1049 { 1050 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); 1051 if (pos != m_alias_dict.end()) 1052 { 1053 m_alias_dict.erase(pos); 1054 return true; 1055 } 1056 return false; 1057 } 1058 bool 1059 CommandInterpreter::RemoveUser (const char *alias_name) 1060 { 1061 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); 1062 if (pos != m_user_dict.end()) 1063 { 1064 m_user_dict.erase(pos); 1065 return true; 1066 } 1067 return false; 1068 } 1069 1070 void 1071 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) 1072 { 1073 help_string.Printf ("'%s", command_name); 1074 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1075 1076 if (option_arg_vector_sp) 1077 { 1078 OptionArgVector *options = option_arg_vector_sp.get(); 1079 for (size_t i = 0; i < options->size(); ++i) 1080 { 1081 OptionArgPair cur_option = (*options)[i]; 1082 std::string opt = cur_option.first; 1083 OptionArgValue value_pair = cur_option.second; 1084 std::string value = value_pair.second; 1085 if (opt.compare("<argument>") == 0) 1086 { 1087 help_string.Printf (" %s", value.c_str()); 1088 } 1089 else 1090 { 1091 help_string.Printf (" %s", opt.c_str()); 1092 if ((value.compare ("<no-argument>") != 0) 1093 && (value.compare ("<need-argument") != 0)) 1094 { 1095 help_string.Printf (" %s", value.c_str()); 1096 } 1097 } 1098 } 1099 } 1100 1101 help_string.Printf ("'"); 1102 } 1103 1104 size_t 1105 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) 1106 { 1107 CommandObject::CommandMap::const_iterator pos; 1108 CommandObject::CommandMap::const_iterator end = dict.end(); 1109 size_t max_len = 0; 1110 1111 for (pos = dict.begin(); pos != end; ++pos) 1112 { 1113 size_t len = pos->first.size(); 1114 if (max_len < len) 1115 max_len = len; 1116 } 1117 return max_len; 1118 } 1119 1120 void 1121 CommandInterpreter::GetHelp (CommandReturnObject &result, 1122 uint32_t cmd_types) 1123 { 1124 CommandObject::CommandMap::const_iterator pos; 1125 size_t max_len = FindLongestCommandWord (m_command_dict); 1126 1127 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin ) 1128 { 1129 1130 result.AppendMessage("The following is a list of built-in, permanent debugger commands:"); 1131 result.AppendMessage(""); 1132 1133 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 1134 { 1135 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 1136 max_len); 1137 } 1138 result.AppendMessage(""); 1139 1140 } 1141 1142 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases )) 1143 { 1144 result.AppendMessage("The following is a list of your current command abbreviations " 1145 "(see 'help command alias' for more info):"); 1146 result.AppendMessage(""); 1147 max_len = FindLongestCommandWord (m_alias_dict); 1148 1149 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) 1150 { 1151 StreamString sstr; 1152 StreamString translation_and_help; 1153 std::string entry_name = pos->first; 1154 std::string second_entry = pos->second.get()->GetCommandName(); 1155 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); 1156 1157 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); 1158 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", 1159 translation_and_help.GetData(), max_len); 1160 } 1161 result.AppendMessage(""); 1162 } 1163 1164 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef )) 1165 { 1166 result.AppendMessage ("The following is a list of your current user-defined commands:"); 1167 result.AppendMessage(""); 1168 max_len = FindLongestCommandWord (m_user_dict); 1169 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 1170 { 1171 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 1172 max_len); 1173 } 1174 result.AppendMessage(""); 1175 } 1176 1177 result.AppendMessage("For more information on any particular command, try 'help <command-name>'."); 1178 } 1179 1180 CommandObject * 1181 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string) 1182 { 1183 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will 1184 // eventually be invoked by the given command line. 1185 1186 CommandObject *cmd_obj = nullptr; 1187 std::string white_space (" \t\v"); 1188 size_t start = command_string.find_first_not_of (white_space); 1189 size_t end = 0; 1190 bool done = false; 1191 while (!done) 1192 { 1193 if (start != std::string::npos) 1194 { 1195 // Get the next word from command_string. 1196 end = command_string.find_first_of (white_space, start); 1197 if (end == std::string::npos) 1198 end = command_string.size(); 1199 std::string cmd_word = command_string.substr (start, end - start); 1200 1201 if (cmd_obj == nullptr) 1202 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid 1203 // command or alias. 1204 cmd_obj = GetCommandObject (cmd_word.c_str()); 1205 else if (cmd_obj->IsMultiwordObject ()) 1206 { 1207 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object. 1208 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str()); 1209 if (sub_cmd_obj) 1210 cmd_obj = sub_cmd_obj; 1211 else // cmd_word was not a valid sub-command word, so we are donee 1212 done = true; 1213 } 1214 else 1215 // We have a cmd_obj and it is not a multi-word object, so we are done. 1216 done = true; 1217 1218 // If we didn't find a valid command object, or our command object is not a multi-word object, or 1219 // we are at the end of the command_string, then we are done. Otherwise, find the start of the 1220 // next word. 1221 1222 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size()) 1223 done = true; 1224 else 1225 start = command_string.find_first_not_of (white_space, end); 1226 } 1227 else 1228 // Unable to find any more words. 1229 done = true; 1230 } 1231 1232 if (end == command_string.size()) 1233 command_string.clear(); 1234 else 1235 command_string = command_string.substr(end); 1236 1237 return cmd_obj; 1238 } 1239 1240 static const char *k_white_space = " \t\v"; 1241 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; 1242 static void 1243 StripLeadingSpaces (std::string &s) 1244 { 1245 if (!s.empty()) 1246 { 1247 size_t pos = s.find_first_not_of (k_white_space); 1248 if (pos == std::string::npos) 1249 s.clear(); 1250 else if (pos == 0) 1251 return; 1252 s.erase (0, pos); 1253 } 1254 } 1255 1256 static size_t 1257 FindArgumentTerminator (const std::string &s) 1258 { 1259 const size_t s_len = s.size(); 1260 size_t offset = 0; 1261 while (offset < s_len) 1262 { 1263 size_t pos = s.find ("--", offset); 1264 if (pos == std::string::npos) 1265 break; 1266 if (pos > 0) 1267 { 1268 if (isspace(s[pos-1])) 1269 { 1270 // Check if the string ends "\s--" (where \s is a space character) 1271 // or if we have "\s--\s". 1272 if ((pos + 2 >= s_len) || isspace(s[pos+2])) 1273 { 1274 return pos; 1275 } 1276 } 1277 } 1278 offset = pos + 2; 1279 } 1280 return std::string::npos; 1281 } 1282 1283 static bool 1284 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char "e_char) 1285 { 1286 command.clear(); 1287 suffix.clear(); 1288 StripLeadingSpaces (command_string); 1289 1290 bool result = false; 1291 quote_char = '\0'; 1292 1293 if (!command_string.empty()) 1294 { 1295 const char first_char = command_string[0]; 1296 if (first_char == '\'' || first_char == '"') 1297 { 1298 quote_char = first_char; 1299 const size_t end_quote_pos = command_string.find (quote_char, 1); 1300 if (end_quote_pos == std::string::npos) 1301 { 1302 command.swap (command_string); 1303 command_string.erase (); 1304 } 1305 else 1306 { 1307 command.assign (command_string, 1, end_quote_pos - 1); 1308 if (end_quote_pos + 1 < command_string.size()) 1309 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1)); 1310 else 1311 command_string.erase (); 1312 } 1313 } 1314 else 1315 { 1316 const size_t first_space_pos = command_string.find_first_of (k_white_space); 1317 if (first_space_pos == std::string::npos) 1318 { 1319 command.swap (command_string); 1320 command_string.erase(); 1321 } 1322 else 1323 { 1324 command.assign (command_string, 0, first_space_pos); 1325 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos)); 1326 } 1327 } 1328 result = true; 1329 } 1330 1331 1332 if (!command.empty()) 1333 { 1334 // actual commands can't start with '-' or '_' 1335 if (command[0] != '-' && command[0] != '_') 1336 { 1337 size_t pos = command.find_first_not_of(k_valid_command_chars); 1338 if (pos > 0 && pos != std::string::npos) 1339 { 1340 suffix.assign (command.begin() + pos, command.end()); 1341 command.erase (pos); 1342 } 1343 } 1344 } 1345 1346 return result; 1347 } 1348 1349 CommandObject * 1350 CommandInterpreter::BuildAliasResult (const char *alias_name, 1351 std::string &raw_input_string, 1352 std::string &alias_result, 1353 CommandReturnObject &result) 1354 { 1355 CommandObject *alias_cmd_obj = nullptr; 1356 Args cmd_args (raw_input_string.c_str()); 1357 alias_cmd_obj = GetCommandObject (alias_name); 1358 StreamString result_str; 1359 1360 if (alias_cmd_obj) 1361 { 1362 std::string alias_name_str = alias_name; 1363 if ((cmd_args.GetArgumentCount() == 0) 1364 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)) 1365 cmd_args.Unshift (alias_name); 1366 1367 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ()); 1368 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1369 1370 if (option_arg_vector_sp.get()) 1371 { 1372 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1373 1374 for (size_t i = 0; i < option_arg_vector->size(); ++i) 1375 { 1376 OptionArgPair option_pair = (*option_arg_vector)[i]; 1377 OptionArgValue value_pair = option_pair.second; 1378 int value_type = value_pair.first; 1379 std::string option = option_pair.first; 1380 std::string value = value_pair.second; 1381 if (option.compare ("<argument>") == 0) 1382 result_str.Printf (" %s", value.c_str()); 1383 else 1384 { 1385 result_str.Printf (" %s", option.c_str()); 1386 if (value_type != OptionParser::eOptionalArgument) 1387 result_str.Printf (" "); 1388 if (value.compare ("<OptionParser::eNoArgument>") != 0) 1389 { 1390 int index = GetOptionArgumentPosition (value.c_str()); 1391 if (index == 0) 1392 result_str.Printf ("%s", value.c_str()); 1393 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) 1394 { 1395 1396 result.AppendErrorWithFormat 1397 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 1398 index); 1399 result.SetStatus (eReturnStatusFailed); 1400 return alias_cmd_obj; 1401 } 1402 else 1403 { 1404 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 1405 if (strpos != std::string::npos) 1406 raw_input_string = raw_input_string.erase (strpos, 1407 strlen (cmd_args.GetArgumentAtIndex (index))); 1408 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index)); 1409 } 1410 } 1411 } 1412 } 1413 } 1414 1415 alias_result = result_str.GetData(); 1416 } 1417 return alias_cmd_obj; 1418 } 1419 1420 Error 1421 CommandInterpreter::PreprocessCommand (std::string &command) 1422 { 1423 // The command preprocessor needs to do things to the command 1424 // line before any parsing of arguments or anything else is done. 1425 // The only current stuff that gets proprocessed is anyting enclosed 1426 // in backtick ('`') characters is evaluated as an expression and 1427 // the result of the expression must be a scalar that can be substituted 1428 // into the command. An example would be: 1429 // (lldb) memory read `$rsp + 20` 1430 Error error; // Error for any expressions that might not evaluate 1431 size_t start_backtick; 1432 size_t pos = 0; 1433 while ((start_backtick = command.find ('`', pos)) != std::string::npos) 1434 { 1435 if (start_backtick > 0 && command[start_backtick-1] == '\\') 1436 { 1437 // The backtick was preceeded by a '\' character, remove the slash 1438 // and don't treat the backtick as the start of an expression 1439 command.erase(start_backtick-1, 1); 1440 // No need to add one to start_backtick since we just deleted a char 1441 pos = start_backtick; 1442 } 1443 else 1444 { 1445 const size_t expr_content_start = start_backtick + 1; 1446 const size_t end_backtick = command.find ('`', expr_content_start); 1447 if (end_backtick == std::string::npos) 1448 return error; 1449 else if (end_backtick == expr_content_start) 1450 { 1451 // Empty expression (two backticks in a row) 1452 command.erase (start_backtick, 2); 1453 } 1454 else 1455 { 1456 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start); 1457 1458 ExecutionContext exe_ctx(GetExecutionContext()); 1459 Target *target = exe_ctx.GetTargetPtr(); 1460 // Get a dummy target to allow for calculator mode while processing backticks. 1461 // This also helps break the infinite loop caused when target is null. 1462 if (!target) 1463 target = Host::GetDummyTarget(GetDebugger()).get(); 1464 if (target) 1465 { 1466 ValueObjectSP expr_result_valobj_sp; 1467 1468 EvaluateExpressionOptions options; 1469 options.SetCoerceToId(false); 1470 options.SetUnwindOnError(true); 1471 options.SetIgnoreBreakpoints(true); 1472 options.SetKeepInMemory(false); 1473 options.SetTryAllThreads(true); 1474 options.SetTimeoutUsec(0); 1475 1476 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(), 1477 exe_ctx.GetFramePtr(), 1478 expr_result_valobj_sp, 1479 options); 1480 1481 if (expr_result == eExpressionCompleted) 1482 { 1483 Scalar scalar; 1484 if (expr_result_valobj_sp) 1485 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true); 1486 if (expr_result_valobj_sp->ResolveValue (scalar)) 1487 { 1488 command.erase (start_backtick, end_backtick - start_backtick + 1); 1489 StreamString value_strm; 1490 const bool show_type = false; 1491 scalar.GetValue (&value_strm, show_type); 1492 size_t value_string_size = value_strm.GetSize(); 1493 if (value_string_size) 1494 { 1495 command.insert (start_backtick, value_strm.GetData(), value_string_size); 1496 pos = start_backtick + value_string_size; 1497 continue; 1498 } 1499 else 1500 { 1501 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); 1502 } 1503 } 1504 else 1505 { 1506 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); 1507 } 1508 } 1509 else 1510 { 1511 if (expr_result_valobj_sp) 1512 error = expr_result_valobj_sp->GetError(); 1513 if (error.Success()) 1514 { 1515 1516 switch (expr_result) 1517 { 1518 case eExpressionSetupError: 1519 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str()); 1520 break; 1521 case eExpressionParseError: 1522 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str()); 1523 break; 1524 case eExpressionResultUnavailable: 1525 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str()); 1526 case eExpressionCompleted: 1527 break; 1528 case eExpressionDiscarded: 1529 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str()); 1530 break; 1531 case eExpressionInterrupted: 1532 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str()); 1533 break; 1534 case eExpressionHitBreakpoint: 1535 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str()); 1536 break; 1537 case eExpressionTimedOut: 1538 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str()); 1539 break; 1540 case eExpressionStoppedForDebug: 1541 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str()); 1542 break; 1543 } 1544 } 1545 } 1546 } 1547 } 1548 if (error.Fail()) 1549 break; 1550 } 1551 } 1552 return error; 1553 } 1554 1555 1556 bool 1557 CommandInterpreter::HandleCommand (const char *command_line, 1558 LazyBool lazy_add_to_history, 1559 CommandReturnObject &result, 1560 ExecutionContext *override_context, 1561 bool repeat_on_empty_command, 1562 bool no_context_switching) 1563 1564 { 1565 1566 bool done = false; 1567 CommandObject *cmd_obj = nullptr; 1568 bool wants_raw_input = false; 1569 std::string command_string (command_line); 1570 std::string original_command_string (command_line); 1571 1572 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS)); 1573 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line); 1574 1575 // Make a scoped cleanup object that will clear the crash description string 1576 // on exit of this function. 1577 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription); 1578 1579 if (log) 1580 log->Printf ("Processing command: %s", command_line); 1581 1582 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line); 1583 1584 if (!no_context_switching) 1585 UpdateExecutionContext (override_context); 1586 1587 bool add_to_history; 1588 if (lazy_add_to_history == eLazyBoolCalculate) 1589 add_to_history = (m_command_source_depth == 0); 1590 else 1591 add_to_history = (lazy_add_to_history == eLazyBoolYes); 1592 1593 bool empty_command = false; 1594 bool comment_command = false; 1595 if (command_string.empty()) 1596 empty_command = true; 1597 else 1598 { 1599 const char *k_space_characters = "\t\n\v\f\r "; 1600 1601 size_t non_space = command_string.find_first_not_of (k_space_characters); 1602 // Check for empty line or comment line (lines whose first 1603 // non-space character is the comment character for this interpreter) 1604 if (non_space == std::string::npos) 1605 empty_command = true; 1606 else if (command_string[non_space] == m_comment_char) 1607 comment_command = true; 1608 else if (command_string[non_space] == CommandHistory::g_repeat_char) 1609 { 1610 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space); 1611 if (history_string == nullptr) 1612 { 1613 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str()); 1614 result.SetStatus(eReturnStatusFailed); 1615 return false; 1616 } 1617 add_to_history = false; 1618 command_string = history_string; 1619 original_command_string = history_string; 1620 } 1621 } 1622 1623 if (empty_command) 1624 { 1625 if (repeat_on_empty_command) 1626 { 1627 if (m_command_history.IsEmpty()) 1628 { 1629 result.AppendError ("empty command"); 1630 result.SetStatus(eReturnStatusFailed); 1631 return false; 1632 } 1633 else 1634 { 1635 command_line = m_repeat_command.c_str(); 1636 command_string = command_line; 1637 original_command_string = command_line; 1638 if (m_repeat_command.empty()) 1639 { 1640 result.AppendErrorWithFormat("No auto repeat.\n"); 1641 result.SetStatus (eReturnStatusFailed); 1642 return false; 1643 } 1644 } 1645 add_to_history = false; 1646 } 1647 else 1648 { 1649 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1650 return true; 1651 } 1652 } 1653 else if (comment_command) 1654 { 1655 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1656 return true; 1657 } 1658 1659 1660 Error error (PreprocessCommand (command_string)); 1661 1662 if (error.Fail()) 1663 { 1664 result.AppendError (error.AsCString()); 1665 result.SetStatus(eReturnStatusFailed); 1666 return false; 1667 } 1668 // Phase 1. 1669 1670 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object 1671 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that 1672 // the user could have specified an alias, and in translating the alias there may also be command options and/or 1673 // even data (including raw text strings) that need to be found and inserted into the command line as part of 1674 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command 1675 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions & 1676 // replacements taken care of; 3). whether or not the Execute function wants raw input or not. 1677 1678 StreamString revised_command_line; 1679 size_t actual_cmd_name_len = 0; 1680 std::string next_word; 1681 StringList matches; 1682 while (!done) 1683 { 1684 char quote_char = '\0'; 1685 std::string suffix; 1686 ExtractCommand (command_string, next_word, suffix, quote_char); 1687 if (cmd_obj == nullptr) 1688 { 1689 std::string full_name; 1690 if (GetAliasFullName(next_word.c_str(), full_name)) 1691 { 1692 std::string alias_result; 1693 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result); 1694 revised_command_line.Printf ("%s", alias_result.c_str()); 1695 if (cmd_obj) 1696 { 1697 wants_raw_input = cmd_obj->WantsRawCommandString (); 1698 actual_cmd_name_len = strlen (cmd_obj->GetCommandName()); 1699 } 1700 } 1701 else 1702 { 1703 cmd_obj = GetCommandObject (next_word.c_str(), &matches); 1704 if (cmd_obj) 1705 { 1706 actual_cmd_name_len += next_word.length(); 1707 revised_command_line.Printf ("%s", next_word.c_str()); 1708 wants_raw_input = cmd_obj->WantsRawCommandString (); 1709 } 1710 else 1711 { 1712 revised_command_line.Printf ("%s", next_word.c_str()); 1713 } 1714 } 1715 } 1716 else 1717 { 1718 if (cmd_obj->IsMultiwordObject ()) 1719 { 1720 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str()); 1721 if (sub_cmd_obj) 1722 { 1723 actual_cmd_name_len += next_word.length() + 1; 1724 revised_command_line.Printf (" %s", next_word.c_str()); 1725 cmd_obj = sub_cmd_obj; 1726 wants_raw_input = cmd_obj->WantsRawCommandString (); 1727 } 1728 else 1729 { 1730 if (quote_char) 1731 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); 1732 else 1733 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str()); 1734 done = true; 1735 } 1736 } 1737 else 1738 { 1739 if (quote_char) 1740 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); 1741 else 1742 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str()); 1743 done = true; 1744 } 1745 } 1746 1747 if (cmd_obj == nullptr) 1748 { 1749 const size_t num_matches = matches.GetSize(); 1750 if (matches.GetSize() > 1) { 1751 StreamString error_msg; 1752 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str()); 1753 1754 for (uint32_t i = 0; i < num_matches; ++i) { 1755 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i)); 1756 } 1757 result.AppendRawError (error_msg.GetString().c_str()); 1758 } else { 1759 // We didn't have only one match, otherwise we wouldn't get here. 1760 assert(num_matches == 0); 1761 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str()); 1762 } 1763 result.SetStatus (eReturnStatusFailed); 1764 return false; 1765 } 1766 1767 if (cmd_obj->IsMultiwordObject ()) 1768 { 1769 if (!suffix.empty()) 1770 { 1771 1772 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n", 1773 cmd_obj->GetCommandName(), 1774 next_word.empty() ? "" : next_word.c_str(), 1775 next_word.empty() ? " -- " : " ", 1776 suffix.c_str()); 1777 result.SetStatus (eReturnStatusFailed); 1778 return false; 1779 } 1780 } 1781 else 1782 { 1783 // If we found a normal command, we are done 1784 done = true; 1785 if (!suffix.empty()) 1786 { 1787 switch (suffix[0]) 1788 { 1789 case '/': 1790 // GDB format suffixes 1791 { 1792 Options *command_options = cmd_obj->GetOptions(); 1793 if (command_options && command_options->SupportsLongOption("gdb-format")) 1794 { 1795 std::string gdb_format_option ("--gdb-format="); 1796 gdb_format_option += (suffix.c_str() + 1); 1797 1798 bool inserted = false; 1799 std::string &cmd = revised_command_line.GetString(); 1800 size_t arg_terminator_idx = FindArgumentTerminator (cmd); 1801 if (arg_terminator_idx != std::string::npos) 1802 { 1803 // Insert the gdb format option before the "--" that terminates options 1804 gdb_format_option.append(1,' '); 1805 cmd.insert(arg_terminator_idx, gdb_format_option); 1806 inserted = true; 1807 } 1808 1809 if (!inserted) 1810 revised_command_line.Printf (" %s", gdb_format_option.c_str()); 1811 1812 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos) 1813 revised_command_line.PutCString (" --"); 1814 } 1815 else 1816 { 1817 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n", 1818 cmd_obj->GetCommandName()); 1819 result.SetStatus (eReturnStatusFailed); 1820 return false; 1821 } 1822 } 1823 break; 1824 1825 default: 1826 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n", 1827 suffix.c_str()); 1828 result.SetStatus (eReturnStatusFailed); 1829 return false; 1830 1831 } 1832 } 1833 } 1834 if (command_string.length() == 0) 1835 done = true; 1836 1837 } 1838 1839 if (!command_string.empty()) 1840 revised_command_line.Printf (" %s", command_string.c_str()); 1841 1842 // End of Phase 1. 1843 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command 1844 // specified was valid; revised_command_line contains the complete command line (including command name(s)), 1845 // fully translated with all substitutions & translations taken care of (still in raw text format); and 1846 // wants_raw_input specifies whether the Execute method expects raw input or not. 1847 1848 1849 if (log) 1850 { 1851 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>"); 1852 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData()); 1853 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); 1854 } 1855 1856 // Phase 2. 1857 // Take care of things like setting up the history command & calling the appropriate Execute method on the 1858 // CommandObject, with the appropriate arguments. 1859 1860 if (cmd_obj != nullptr) 1861 { 1862 if (add_to_history) 1863 { 1864 Args command_args (revised_command_line.GetData()); 1865 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); 1866 if (repeat_command != nullptr) 1867 m_repeat_command.assign(repeat_command); 1868 else 1869 m_repeat_command.assign(original_command_string.c_str()); 1870 1871 m_command_history.AppendString (original_command_string); 1872 } 1873 1874 command_string = revised_command_line.GetData(); 1875 std::string command_name (cmd_obj->GetCommandName()); 1876 std::string remainder; 1877 if (actual_cmd_name_len < command_string.length()) 1878 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter 1879 // than cmd_obj->GetCommandName(), because name completion 1880 // allows users to enter short versions of the names, 1881 // e.g. 'br s' for 'breakpoint set'. 1882 1883 // Remove any initial spaces 1884 std::string white_space (" \t\v"); 1885 size_t pos = remainder.find_first_not_of (white_space); 1886 if (pos != 0 && pos != std::string::npos) 1887 remainder.erase(0, pos); 1888 1889 if (log) 1890 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str()); 1891 1892 cmd_obj->Execute (remainder.c_str(), result); 1893 } 1894 else 1895 { 1896 // We didn't find the first command object, so complete the first argument. 1897 Args command_args (revised_command_line.GetData()); 1898 StringList matches; 1899 int num_matches; 1900 int cursor_index = 0; 1901 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 1902 bool word_complete; 1903 num_matches = HandleCompletionMatches (command_args, 1904 cursor_index, 1905 cursor_char_position, 1906 0, 1907 -1, 1908 word_complete, 1909 matches); 1910 1911 if (num_matches > 0) 1912 { 1913 std::string error_msg; 1914 error_msg.assign ("ambiguous command '"); 1915 error_msg.append(command_args.GetArgumentAtIndex(0)); 1916 error_msg.append ("'."); 1917 1918 error_msg.append (" Possible completions:"); 1919 for (int i = 0; i < num_matches; i++) 1920 { 1921 error_msg.append ("\n\t"); 1922 error_msg.append (matches.GetStringAtIndex (i)); 1923 } 1924 error_msg.append ("\n"); 1925 result.AppendRawError (error_msg.c_str()); 1926 } 1927 else 1928 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); 1929 1930 result.SetStatus (eReturnStatusFailed); 1931 } 1932 1933 if (log) 1934 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed")); 1935 1936 return result.Succeeded(); 1937 } 1938 1939 int 1940 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 1941 int &cursor_index, 1942 int &cursor_char_position, 1943 int match_start_point, 1944 int max_return_elements, 1945 bool &word_complete, 1946 StringList &matches) 1947 { 1948 int num_command_matches = 0; 1949 bool look_for_subcommand = false; 1950 1951 // For any of the command completions a unique match will be a complete word. 1952 word_complete = true; 1953 1954 if (cursor_index == -1) 1955 { 1956 // We got nothing on the command line, so return the list of commands 1957 bool include_aliases = true; 1958 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 1959 } 1960 else if (cursor_index == 0) 1961 { 1962 // The cursor is in the first argument, so just do a lookup in the dictionary. 1963 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 1964 num_command_matches = matches.GetSize(); 1965 1966 if (num_command_matches == 1 1967 && cmd_obj && cmd_obj->IsMultiwordObject() 1968 && matches.GetStringAtIndex(0) != nullptr 1969 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 1970 { 1971 if (parsed_line.GetArgumentCount() == 1) 1972 { 1973 word_complete = true; 1974 } 1975 else 1976 { 1977 look_for_subcommand = true; 1978 num_command_matches = 0; 1979 matches.DeleteStringAtIndex(0); 1980 parsed_line.AppendArgument (""); 1981 cursor_index++; 1982 cursor_char_position = 0; 1983 } 1984 } 1985 } 1986 1987 if (cursor_index > 0 || look_for_subcommand) 1988 { 1989 // We are completing further on into a commands arguments, so find the command and tell it 1990 // to complete the command. 1991 // First see if there is a matching initial command: 1992 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 1993 if (command_object == nullptr) 1994 { 1995 return 0; 1996 } 1997 else 1998 { 1999 parsed_line.Shift(); 2000 cursor_index--; 2001 num_command_matches = command_object->HandleCompletion (parsed_line, 2002 cursor_index, 2003 cursor_char_position, 2004 match_start_point, 2005 max_return_elements, 2006 word_complete, 2007 matches); 2008 } 2009 } 2010 2011 return num_command_matches; 2012 2013 } 2014 2015 int 2016 CommandInterpreter::HandleCompletion (const char *current_line, 2017 const char *cursor, 2018 const char *last_char, 2019 int match_start_point, 2020 int max_return_elements, 2021 StringList &matches) 2022 { 2023 // We parse the argument up to the cursor, so the last argument in parsed_line is 2024 // the one containing the cursor, and the cursor is after the last character. 2025 2026 Args parsed_line(current_line, last_char - current_line); 2027 Args partial_parsed_line(current_line, cursor - current_line); 2028 2029 // Don't complete comments, and if the line we are completing is just the history repeat character, 2030 // substitute the appropriate history line. 2031 const char *first_arg = parsed_line.GetArgumentAtIndex(0); 2032 if (first_arg) 2033 { 2034 if (first_arg[0] == m_comment_char) 2035 return 0; 2036 else if (first_arg[0] == CommandHistory::g_repeat_char) 2037 { 2038 const char *history_string = m_command_history.FindString (first_arg); 2039 if (history_string != nullptr) 2040 { 2041 matches.Clear(); 2042 matches.InsertStringAtIndex(0, history_string); 2043 return -2; 2044 } 2045 else 2046 return 0; 2047 2048 } 2049 } 2050 2051 2052 int num_args = partial_parsed_line.GetArgumentCount(); 2053 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 2054 int cursor_char_position; 2055 2056 if (cursor_index == -1) 2057 cursor_char_position = 0; 2058 else 2059 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 2060 2061 if (cursor > current_line && cursor[-1] == ' ') 2062 { 2063 // We are just after a space. If we are in an argument, then we will continue 2064 // parsing, but if we are between arguments, then we have to complete whatever the next 2065 // element would be. 2066 // We can distinguish the two cases because if we are in an argument (e.g. because the space is 2067 // protected by a quote) then the space will also be in the parsed argument... 2068 2069 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); 2070 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') 2071 { 2072 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0'); 2073 cursor_index++; 2074 cursor_char_position = 0; 2075 } 2076 } 2077 2078 int num_command_matches; 2079 2080 matches.Clear(); 2081 2082 // Only max_return_elements == -1 is supported at present: 2083 assert (max_return_elements == -1); 2084 bool word_complete; 2085 num_command_matches = HandleCompletionMatches (parsed_line, 2086 cursor_index, 2087 cursor_char_position, 2088 match_start_point, 2089 max_return_elements, 2090 word_complete, 2091 matches); 2092 2093 if (num_command_matches <= 0) 2094 return num_command_matches; 2095 2096 if (num_args == 0) 2097 { 2098 // If we got an empty string, insert nothing. 2099 matches.InsertStringAtIndex(0, ""); 2100 } 2101 else 2102 { 2103 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 2104 // put an empty string in element 0. 2105 std::string command_partial_str; 2106 if (cursor_index >= 0) 2107 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 2108 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 2109 2110 std::string common_prefix; 2111 matches.LongestCommonPrefix (common_prefix); 2112 const size_t partial_name_len = command_partial_str.size(); 2113 2114 // If we matched a unique single command, add a space... 2115 // Only do this if the completer told us this was a complete word, however... 2116 if (num_command_matches == 1 && word_complete) 2117 { 2118 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 2119 if (quote_char != '\0') 2120 common_prefix.push_back(quote_char); 2121 2122 common_prefix.push_back(' '); 2123 } 2124 common_prefix.erase (0, partial_name_len); 2125 matches.InsertStringAtIndex(0, common_prefix.c_str()); 2126 } 2127 return num_command_matches; 2128 } 2129 2130 2131 CommandInterpreter::~CommandInterpreter () 2132 { 2133 } 2134 2135 void 2136 CommandInterpreter::UpdatePrompt (const char *new_prompt) 2137 { 2138 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));; 2139 BroadcastEvent (prompt_change_event_sp); 2140 if (m_command_io_handler_sp) 2141 m_command_io_handler_sp->SetPrompt(new_prompt); 2142 } 2143 2144 2145 bool 2146 CommandInterpreter::Confirm (const char *message, bool default_answer) 2147 { 2148 // Check AutoConfirm first: 2149 if (m_debugger.GetAutoConfirm()) 2150 return default_answer; 2151 2152 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger, 2153 message, 2154 default_answer); 2155 IOHandlerSP io_handler_sp (confirm); 2156 m_debugger.RunIOHandler (io_handler_sp); 2157 return confirm->GetResponse(); 2158 } 2159 2160 OptionArgVectorSP 2161 CommandInterpreter::GetAliasOptions (const char *alias_name) 2162 { 2163 OptionArgMap::iterator pos; 2164 OptionArgVectorSP ret_val; 2165 2166 std::string alias (alias_name); 2167 2168 if (HasAliasOptions()) 2169 { 2170 pos = m_alias_options.find (alias); 2171 if (pos != m_alias_options.end()) 2172 ret_val = pos->second; 2173 } 2174 2175 return ret_val; 2176 } 2177 2178 void 2179 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 2180 { 2181 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 2182 if (pos != m_alias_options.end()) 2183 { 2184 m_alias_options.erase (pos); 2185 } 2186 } 2187 2188 void 2189 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 2190 { 2191 m_alias_options[alias_name] = option_arg_vector_sp; 2192 } 2193 2194 bool 2195 CommandInterpreter::HasCommands () 2196 { 2197 return (!m_command_dict.empty()); 2198 } 2199 2200 bool 2201 CommandInterpreter::HasAliases () 2202 { 2203 return (!m_alias_dict.empty()); 2204 } 2205 2206 bool 2207 CommandInterpreter::HasUserCommands () 2208 { 2209 return (!m_user_dict.empty()); 2210 } 2211 2212 bool 2213 CommandInterpreter::HasAliasOptions () 2214 { 2215 return (!m_alias_options.empty()); 2216 } 2217 2218 void 2219 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 2220 const char *alias_name, 2221 Args &cmd_args, 2222 std::string &raw_input_string, 2223 CommandReturnObject &result) 2224 { 2225 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 2226 2227 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 2228 2229 // Make sure that the alias name is the 0th element in cmd_args 2230 std::string alias_name_str = alias_name; 2231 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 2232 cmd_args.Unshift (alias_name); 2233 2234 Args new_args (alias_cmd_obj->GetCommandName()); 2235 if (new_args.GetArgumentCount() == 2) 2236 new_args.Shift(); 2237 2238 if (option_arg_vector_sp.get()) 2239 { 2240 if (wants_raw_input) 2241 { 2242 // We have a command that both has command options and takes raw input. Make *sure* it has a 2243 // " -- " in the right place in the raw_input_string. 2244 size_t pos = raw_input_string.find(" -- "); 2245 if (pos == std::string::npos) 2246 { 2247 // None found; assume it goes at the beginning of the raw input string 2248 raw_input_string.insert (0, " -- "); 2249 } 2250 } 2251 2252 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 2253 const size_t old_size = cmd_args.GetArgumentCount(); 2254 std::vector<bool> used (old_size + 1, false); 2255 2256 used[0] = true; 2257 2258 for (size_t i = 0; i < option_arg_vector->size(); ++i) 2259 { 2260 OptionArgPair option_pair = (*option_arg_vector)[i]; 2261 OptionArgValue value_pair = option_pair.second; 2262 int value_type = value_pair.first; 2263 std::string option = option_pair.first; 2264 std::string value = value_pair.second; 2265 if (option.compare ("<argument>") == 0) 2266 { 2267 if (!wants_raw_input 2268 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice 2269 new_args.AppendArgument (value.c_str()); 2270 } 2271 else 2272 { 2273 if (value_type != OptionParser::eOptionalArgument) 2274 new_args.AppendArgument (option.c_str()); 2275 if (value.compare ("<no-argument>") != 0) 2276 { 2277 int index = GetOptionArgumentPosition (value.c_str()); 2278 if (index == 0) 2279 { 2280 // value was NOT a positional argument; must be a real value 2281 if (value_type != OptionParser::eOptionalArgument) 2282 new_args.AppendArgument (value.c_str()); 2283 else 2284 { 2285 char buffer[255]; 2286 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); 2287 new_args.AppendArgument (buffer); 2288 } 2289 2290 } 2291 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) 2292 { 2293 result.AppendErrorWithFormat 2294 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 2295 index); 2296 result.SetStatus (eReturnStatusFailed); 2297 return; 2298 } 2299 else 2300 { 2301 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 2302 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 2303 if (strpos != std::string::npos) 2304 { 2305 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); 2306 } 2307 2308 if (value_type != OptionParser::eOptionalArgument) 2309 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 2310 else 2311 { 2312 char buffer[255]; 2313 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), 2314 cmd_args.GetArgumentAtIndex (index)); 2315 new_args.AppendArgument (buffer); 2316 } 2317 used[index] = true; 2318 } 2319 } 2320 } 2321 } 2322 2323 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j) 2324 { 2325 if (!used[j] && !wants_raw_input) 2326 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 2327 } 2328 2329 cmd_args.Clear(); 2330 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2331 } 2332 else 2333 { 2334 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2335 // This alias was not created with any options; nothing further needs to be done, unless it is a command that 2336 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw 2337 // input string. 2338 if (wants_raw_input) 2339 { 2340 cmd_args.Clear(); 2341 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2342 } 2343 return; 2344 } 2345 2346 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2347 return; 2348 } 2349 2350 2351 int 2352 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 2353 { 2354 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 2355 // of zero. 2356 2357 char *cptr = (char *) in_string; 2358 2359 // Does it start with '%' 2360 if (cptr[0] == '%') 2361 { 2362 ++cptr; 2363 2364 // Is the rest of it entirely digits? 2365 if (isdigit (cptr[0])) 2366 { 2367 const char *start = cptr; 2368 while (isdigit (cptr[0])) 2369 ++cptr; 2370 2371 // We've gotten to the end of the digits; are we at the end of the string? 2372 if (cptr[0] == '\0') 2373 position = atoi (start); 2374 } 2375 } 2376 2377 return position; 2378 } 2379 2380 void 2381 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 2382 { 2383 FileSpec init_file; 2384 if (in_cwd) 2385 { 2386 // In the current working directory we don't load any program specific 2387 // .lldbinit files, we only look for a "./.lldbinit" file. 2388 if (m_skip_lldbinit_files) 2389 return; 2390 2391 init_file.SetFile ("./.lldbinit", true); 2392 } 2393 else 2394 { 2395 // If we aren't looking in the current working directory we are looking 2396 // in the home directory. We will first see if there is an application 2397 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a 2398 // "-" and the name of the program. If this file doesn't exist, we fall 2399 // back to just the "~/.lldbinit" file. We also obey any requests to not 2400 // load the init files. 2401 llvm::SmallString<64> home_dir_path; 2402 llvm::sys::path::home_directory(home_dir_path); 2403 FileSpec profilePath(home_dir_path.c_str(), false); 2404 profilePath.AppendPathComponent(".lldbinit"); 2405 std::string init_file_path = profilePath.GetPath(); 2406 2407 if (m_skip_app_init_files == false) 2408 { 2409 FileSpec program_file_spec(HostInfo::GetProgramFileSpec()); 2410 const char *program_name = program_file_spec.GetFilename().AsCString(); 2411 2412 if (program_name) 2413 { 2414 char program_init_file_name[PATH_MAX]; 2415 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path.c_str(), program_name); 2416 init_file.SetFile (program_init_file_name, true); 2417 if (!init_file.Exists()) 2418 init_file.Clear(); 2419 } 2420 } 2421 2422 if (!init_file && !m_skip_lldbinit_files) 2423 init_file.SetFile (init_file_path.c_str(), false); 2424 } 2425 2426 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 2427 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 2428 2429 if (init_file.Exists()) 2430 { 2431 const bool saved_batch = SetBatchCommandMode (true); 2432 CommandInterpreterRunOptions options; 2433 options.SetSilent (true); 2434 options.SetStopOnError (false); 2435 options.SetStopOnContinue (true); 2436 2437 HandleCommandsFromFile (init_file, 2438 nullptr, // Execution context 2439 options, 2440 result); 2441 SetBatchCommandMode (saved_batch); 2442 } 2443 else 2444 { 2445 // nothing to be done if the file doesn't exist 2446 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2447 } 2448 } 2449 2450 PlatformSP 2451 CommandInterpreter::GetPlatform (bool prefer_target_platform) 2452 { 2453 PlatformSP platform_sp; 2454 if (prefer_target_platform) 2455 { 2456 ExecutionContext exe_ctx(GetExecutionContext()); 2457 Target *target = exe_ctx.GetTargetPtr(); 2458 if (target) 2459 platform_sp = target->GetPlatform(); 2460 } 2461 2462 if (!platform_sp) 2463 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 2464 return platform_sp; 2465 } 2466 2467 void 2468 CommandInterpreter::HandleCommands (const StringList &commands, 2469 ExecutionContext *override_context, 2470 CommandInterpreterRunOptions &options, 2471 CommandReturnObject &result) 2472 { 2473 size_t num_lines = commands.GetSize(); 2474 2475 // If we are going to continue past a "continue" then we need to run the commands synchronously. 2476 // Make sure you reset this value anywhere you return from the function. 2477 2478 bool old_async_execution = m_debugger.GetAsyncExecution(); 2479 2480 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will 2481 // cause series of commands that change the context, then do an operation that relies on that context to fail. 2482 2483 if (override_context != nullptr) 2484 UpdateExecutionContext (override_context); 2485 2486 if (!options.GetStopOnContinue()) 2487 { 2488 m_debugger.SetAsyncExecution (false); 2489 } 2490 2491 for (size_t idx = 0; idx < num_lines; idx++) 2492 { 2493 const char *cmd = commands.GetStringAtIndex(idx); 2494 if (cmd[0] == '\0') 2495 continue; 2496 2497 if (options.GetEchoCommands()) 2498 { 2499 result.AppendMessageWithFormat ("%s %s\n", 2500 m_debugger.GetPrompt(), 2501 cmd); 2502 } 2503 2504 CommandReturnObject tmp_result; 2505 // If override_context is not NULL, pass no_context_switching = true for 2506 // HandleCommand() since we updated our context already. 2507 2508 // We might call into a regex or alias command, in which case the add_to_history will get lost. This 2509 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here. 2510 if (!options.GetAddToHistory()) 2511 m_command_source_depth++; 2512 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result, 2513 nullptr, /* override_context */ 2514 true, /* repeat_on_empty_command */ 2515 override_context != nullptr /* no_context_switching */); 2516 if (!options.GetAddToHistory()) 2517 m_command_source_depth--; 2518 2519 if (options.GetPrintResults()) 2520 { 2521 if (tmp_result.Succeeded()) 2522 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData()); 2523 } 2524 2525 if (!success || !tmp_result.Succeeded()) 2526 { 2527 const char *error_msg = tmp_result.GetErrorData(); 2528 if (error_msg == nullptr || error_msg[0] == '\0') 2529 error_msg = "<unknown error>.\n"; 2530 if (options.GetStopOnError()) 2531 { 2532 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s", 2533 (uint64_t)idx, cmd, error_msg); 2534 result.SetStatus (eReturnStatusFailed); 2535 m_debugger.SetAsyncExecution (old_async_execution); 2536 return; 2537 } 2538 else if (options.GetPrintResults()) 2539 { 2540 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s", 2541 (uint64_t)idx + 1, 2542 cmd, 2543 error_msg); 2544 } 2545 } 2546 2547 if (result.GetImmediateOutputStream()) 2548 result.GetImmediateOutputStream()->Flush(); 2549 2550 if (result.GetImmediateErrorStream()) 2551 result.GetImmediateErrorStream()->Flush(); 2552 2553 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution 2554 // could be running (for instance in Breakpoint Commands. 2555 // So we check the return value to see if it is has running in it. 2556 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) 2557 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) 2558 { 2559 if (options.GetStopOnContinue()) 2560 { 2561 // If we caused the target to proceed, and we're going to stop in that case, set the 2562 // status in our real result before returning. This is an error if the continue was not the 2563 // last command in the set of commands to be run. 2564 if (idx != num_lines - 1) 2565 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n", 2566 (uint64_t)idx + 1, cmd); 2567 else 2568 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd); 2569 2570 result.SetStatus(tmp_result.GetStatus()); 2571 m_debugger.SetAsyncExecution (old_async_execution); 2572 2573 return; 2574 } 2575 } 2576 2577 // Also check for "stop on crash here: 2578 bool should_stop = false; 2579 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) 2580 { 2581 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); 2582 if (target_sp) 2583 { 2584 ProcessSP process_sp (target_sp->GetProcessSP()); 2585 if (process_sp) 2586 { 2587 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) 2588 { 2589 StopReason reason = thread_sp->GetStopReason(); 2590 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation) 2591 { 2592 should_stop = true; 2593 break; 2594 } 2595 } 2596 } 2597 } 2598 if (should_stop) 2599 { 2600 if (idx != num_lines - 1) 2601 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n", 2602 (uint64_t)idx + 1, cmd); 2603 else 2604 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd); 2605 2606 result.SetStatus(tmp_result.GetStatus()); 2607 m_debugger.SetAsyncExecution (old_async_execution); 2608 2609 return; 2610 } 2611 } 2612 2613 } 2614 2615 result.SetStatus (eReturnStatusSuccessFinishResult); 2616 m_debugger.SetAsyncExecution (old_async_execution); 2617 2618 return; 2619 } 2620 2621 // Make flags that we can pass into the IOHandler so our delegates can do the right thing 2622 enum { 2623 eHandleCommandFlagStopOnContinue = (1u << 0), 2624 eHandleCommandFlagStopOnError = (1u << 1), 2625 eHandleCommandFlagEchoCommand = (1u << 2), 2626 eHandleCommandFlagPrintResult = (1u << 3), 2627 eHandleCommandFlagStopOnCrash = (1u << 4) 2628 }; 2629 2630 void 2631 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file, 2632 ExecutionContext *context, 2633 CommandInterpreterRunOptions &options, 2634 CommandReturnObject &result) 2635 { 2636 if (cmd_file.Exists()) 2637 { 2638 StreamFileSP input_file_sp (new StreamFile()); 2639 2640 std::string cmd_file_path = cmd_file.GetPath(); 2641 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead); 2642 2643 if (error.Success()) 2644 { 2645 Debugger &debugger = GetDebugger(); 2646 2647 uint32_t flags = 0; 2648 2649 if (options.m_stop_on_continue == eLazyBoolCalculate) 2650 { 2651 if (m_command_source_flags.empty()) 2652 { 2653 // Stop on continue by default 2654 flags |= eHandleCommandFlagStopOnContinue; 2655 } 2656 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue) 2657 { 2658 flags |= eHandleCommandFlagStopOnContinue; 2659 } 2660 } 2661 else if (options.m_stop_on_continue == eLazyBoolYes) 2662 { 2663 flags |= eHandleCommandFlagStopOnContinue; 2664 } 2665 2666 if (options.m_stop_on_error == eLazyBoolCalculate) 2667 { 2668 if (m_command_source_flags.empty()) 2669 { 2670 if (GetStopCmdSourceOnError()) 2671 flags |= eHandleCommandFlagStopOnError; 2672 } 2673 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) 2674 { 2675 flags |= eHandleCommandFlagStopOnError; 2676 } 2677 } 2678 else if (options.m_stop_on_error == eLazyBoolYes) 2679 { 2680 flags |= eHandleCommandFlagStopOnError; 2681 } 2682 2683 if (options.GetStopOnCrash()) 2684 { 2685 if (m_command_source_flags.empty()) 2686 { 2687 // Echo command by default 2688 flags |= eHandleCommandFlagStopOnCrash; 2689 } 2690 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) 2691 { 2692 flags |= eHandleCommandFlagStopOnCrash; 2693 } 2694 } 2695 2696 if (options.m_echo_commands == eLazyBoolCalculate) 2697 { 2698 if (m_command_source_flags.empty()) 2699 { 2700 // Echo command by default 2701 flags |= eHandleCommandFlagEchoCommand; 2702 } 2703 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) 2704 { 2705 flags |= eHandleCommandFlagEchoCommand; 2706 } 2707 } 2708 else if (options.m_echo_commands == eLazyBoolYes) 2709 { 2710 flags |= eHandleCommandFlagEchoCommand; 2711 } 2712 2713 if (options.m_print_results == eLazyBoolCalculate) 2714 { 2715 if (m_command_source_flags.empty()) 2716 { 2717 // Print output by default 2718 flags |= eHandleCommandFlagPrintResult; 2719 } 2720 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) 2721 { 2722 flags |= eHandleCommandFlagPrintResult; 2723 } 2724 } 2725 else if (options.m_print_results == eLazyBoolYes) 2726 { 2727 flags |= eHandleCommandFlagPrintResult; 2728 } 2729 2730 if (flags & eHandleCommandFlagPrintResult) 2731 { 2732 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str()); 2733 } 2734 2735 // Used for inheriting the right settings when "command source" might have 2736 // nested "command source" commands 2737 lldb::StreamFileSP empty_stream_sp; 2738 m_command_source_flags.push_back(flags); 2739 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, 2740 input_file_sp, 2741 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream 2742 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream 2743 flags, 2744 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written 2745 debugger.GetPrompt(), 2746 false, // Not multi-line 2747 0, 2748 *this)); 2749 const bool old_async_execution = debugger.GetAsyncExecution(); 2750 2751 // Set synchronous execution if we are not stopping on continue 2752 if ((flags & eHandleCommandFlagStopOnContinue) == 0) 2753 debugger.SetAsyncExecution (false); 2754 2755 m_command_source_depth++; 2756 2757 debugger.RunIOHandler(io_handler_sp); 2758 if (!m_command_source_flags.empty()) 2759 m_command_source_flags.pop_back(); 2760 m_command_source_depth--; 2761 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2762 debugger.SetAsyncExecution (old_async_execution); 2763 } 2764 else 2765 { 2766 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString()); 2767 result.SetStatus (eReturnStatusFailed); 2768 } 2769 2770 2771 } 2772 else 2773 { 2774 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n", 2775 cmd_file.GetFilename().AsCString()); 2776 result.SetStatus (eReturnStatusFailed); 2777 return; 2778 } 2779 } 2780 2781 ScriptInterpreter * 2782 CommandInterpreter::GetScriptInterpreter (bool can_create) 2783 { 2784 if (m_script_interpreter_ap.get() != nullptr) 2785 return m_script_interpreter_ap.get(); 2786 2787 if (!can_create) 2788 return nullptr; 2789 2790 // <rdar://problem/11751427> 2791 // we need to protect the initialization of the script interpreter 2792 // otherwise we could end up with two threads both trying to create 2793 // their instance of it, and for some languages (e.g. Python) 2794 // this is a bulletproof recipe for disaster! 2795 // this needs to be a function-level static because multiple Debugger instances living in the same process 2796 // still need to be isolated and not try to initialize Python concurrently 2797 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive); 2798 Mutex::Locker interpreter_lock(g_interpreter_mutex); 2799 2800 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 2801 if (log) 2802 log->Printf("Initializing the ScriptInterpreter now\n"); 2803 2804 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); 2805 switch (script_lang) 2806 { 2807 case eScriptLanguagePython: 2808 #ifndef LLDB_DISABLE_PYTHON 2809 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this)); 2810 break; 2811 #else 2812 // Fall through to the None case when python is disabled 2813 #endif 2814 case eScriptLanguageNone: 2815 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this)); 2816 break; 2817 }; 2818 2819 return m_script_interpreter_ap.get(); 2820 } 2821 2822 2823 2824 bool 2825 CommandInterpreter::GetSynchronous () 2826 { 2827 return m_synchronous_execution; 2828 } 2829 2830 void 2831 CommandInterpreter::SetSynchronous (bool value) 2832 { 2833 m_synchronous_execution = value; 2834 } 2835 2836 void 2837 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 2838 const char *word_text, 2839 const char *separator, 2840 const char *help_text, 2841 size_t max_word_len) 2842 { 2843 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2844 2845 int indent_size = max_word_len + strlen (separator) + 2; 2846 2847 strm.IndentMore (indent_size); 2848 2849 StreamString text_strm; 2850 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text); 2851 2852 size_t len = text_strm.GetSize(); 2853 const char *text = text_strm.GetData(); 2854 if (text[len - 1] == '\n') 2855 { 2856 text_strm.EOL(); 2857 len = text_strm.GetSize(); 2858 } 2859 2860 if (len < max_columns) 2861 { 2862 // Output it as a single line. 2863 strm.Printf ("%s", text); 2864 } 2865 else 2866 { 2867 // We need to break it up into multiple lines. 2868 bool first_line = true; 2869 int text_width; 2870 size_t start = 0; 2871 size_t end = start; 2872 const size_t final_end = strlen (text); 2873 2874 while (end < final_end) 2875 { 2876 if (first_line) 2877 text_width = max_columns - 1; 2878 else 2879 text_width = max_columns - indent_size - 1; 2880 2881 // Don't start the 'text' on a space, since we're already outputting the indentation. 2882 if (!first_line) 2883 { 2884 while ((start < final_end) && (text[start] == ' ')) 2885 start++; 2886 } 2887 2888 end = start + text_width; 2889 if (end > final_end) 2890 end = final_end; 2891 else 2892 { 2893 // If we're not at the end of the text, make sure we break the line on white space. 2894 while (end > start 2895 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 2896 end--; 2897 assert (end > 0); 2898 } 2899 2900 const size_t sub_len = end - start; 2901 if (start != 0) 2902 strm.EOL(); 2903 if (!first_line) 2904 strm.Indent(); 2905 else 2906 first_line = false; 2907 assert (start <= final_end); 2908 assert (start + sub_len <= final_end); 2909 if (sub_len > 0) 2910 strm.Write (text + start, sub_len); 2911 start = end + 1; 2912 } 2913 } 2914 strm.EOL(); 2915 strm.IndentLess(indent_size); 2916 } 2917 2918 void 2919 CommandInterpreter::OutputHelpText (Stream &strm, 2920 const char *word_text, 2921 const char *separator, 2922 const char *help_text, 2923 uint32_t max_word_len) 2924 { 2925 int indent_size = max_word_len + strlen (separator) + 2; 2926 2927 strm.IndentMore (indent_size); 2928 2929 StreamString text_strm; 2930 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2931 2932 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2933 2934 size_t len = text_strm.GetSize(); 2935 const char *text = text_strm.GetData(); 2936 2937 uint32_t chars_left = max_columns; 2938 2939 for (uint32_t i = 0; i < len; i++) 2940 { 2941 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n') 2942 { 2943 chars_left = max_columns - indent_size; 2944 strm.EOL(); 2945 strm.Indent(); 2946 } 2947 else 2948 { 2949 strm.PutChar(text[i]); 2950 chars_left--; 2951 } 2952 2953 } 2954 2955 strm.EOL(); 2956 strm.IndentLess(indent_size); 2957 } 2958 2959 void 2960 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 2961 StringList &commands_help, bool search_builtin_commands, bool search_user_commands) 2962 { 2963 CommandObject::CommandMap::const_iterator pos; 2964 2965 if (search_builtin_commands) 2966 { 2967 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 2968 { 2969 const char *command_name = pos->first.c_str(); 2970 CommandObject *cmd_obj = pos->second.get(); 2971 2972 if (cmd_obj->HelpTextContainsWord (search_word)) 2973 { 2974 commands_found.AppendString (command_name); 2975 commands_help.AppendString (cmd_obj->GetHelp()); 2976 } 2977 2978 if (cmd_obj->IsMultiwordObject()) 2979 cmd_obj->AproposAllSubCommands (command_name, 2980 search_word, 2981 commands_found, 2982 commands_help); 2983 2984 } 2985 } 2986 2987 if (search_user_commands) 2988 { 2989 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 2990 { 2991 const char *command_name = pos->first.c_str(); 2992 CommandObject *cmd_obj = pos->second.get(); 2993 2994 if (cmd_obj->HelpTextContainsWord (search_word)) 2995 { 2996 commands_found.AppendString (command_name); 2997 commands_help.AppendString (cmd_obj->GetHelp()); 2998 } 2999 3000 if (cmd_obj->IsMultiwordObject()) 3001 cmd_obj->AproposAllSubCommands (command_name, 3002 search_word, 3003 commands_found, 3004 commands_help); 3005 3006 } 3007 } 3008 } 3009 3010 void 3011 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context) 3012 { 3013 if (override_context != nullptr) 3014 { 3015 m_exe_ctx_ref = *override_context; 3016 } 3017 else 3018 { 3019 const bool adopt_selected = true; 3020 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected); 3021 } 3022 } 3023 3024 3025 size_t 3026 CommandInterpreter::GetProcessOutput () 3027 { 3028 // The process has stuff waiting for stderr; get it and write it out to the appropriate place. 3029 char stdio_buffer[1024]; 3030 size_t len; 3031 size_t total_bytes = 0; 3032 Error error; 3033 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); 3034 if (target_sp) 3035 { 3036 ProcessSP process_sp (target_sp->GetProcessSP()); 3037 if (process_sp) 3038 { 3039 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0) 3040 { 3041 size_t bytes_written = len; 3042 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written); 3043 total_bytes += len; 3044 } 3045 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0) 3046 { 3047 size_t bytes_written = len; 3048 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written); 3049 total_bytes += len; 3050 } 3051 } 3052 } 3053 return total_bytes; 3054 } 3055 3056 void 3057 CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line) 3058 { 3059 const bool is_interactive = io_handler.GetIsInteractive(); 3060 if (is_interactive == false) 3061 { 3062 // When we are not interactive, don't execute blank lines. This will happen 3063 // sourcing a commands file. We don't want blank lines to repeat the previous 3064 // command and cause any errors to occur (like redefining an alias, get an error 3065 // and stop parsing the commands file). 3066 if (line.empty()) 3067 return; 3068 3069 // When using a non-interactive file handle (like when sourcing commands from a file) 3070 // we need to echo the command out so we don't just see the command output and no 3071 // command... 3072 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand)) 3073 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str()); 3074 } 3075 3076 lldb_private::CommandReturnObject result; 3077 HandleCommand(line.c_str(), eLazyBoolCalculate, result); 3078 3079 // Now emit the command output text from the command we just executed 3080 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) 3081 { 3082 // Display any STDOUT/STDERR _prior_ to emitting the command result text 3083 GetProcessOutput (); 3084 3085 if (!result.GetImmediateOutputStream()) 3086 { 3087 const char *output = result.GetOutputData(); 3088 if (output && output[0]) 3089 io_handler.GetOutputStreamFile()->PutCString(output); 3090 } 3091 3092 // Now emit the command error text from the command we just executed 3093 if (!result.GetImmediateErrorStream()) 3094 { 3095 const char *error = result.GetErrorData(); 3096 if (error && error[0]) 3097 io_handler.GetErrorStreamFile()->PutCString(error); 3098 } 3099 } 3100 3101 switch (result.GetStatus()) 3102 { 3103 case eReturnStatusInvalid: 3104 case eReturnStatusSuccessFinishNoResult: 3105 case eReturnStatusSuccessFinishResult: 3106 case eReturnStatusStarted: 3107 break; 3108 3109 case eReturnStatusSuccessContinuingNoResult: 3110 case eReturnStatusSuccessContinuingResult: 3111 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue)) 3112 io_handler.SetIsDone(true); 3113 break; 3114 3115 case eReturnStatusFailed: 3116 m_num_errors++; 3117 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) 3118 io_handler.SetIsDone(true); 3119 break; 3120 3121 case eReturnStatusQuit: 3122 m_quit_requested = true; 3123 io_handler.SetIsDone(true); 3124 break; 3125 } 3126 3127 // Finally, if we're going to stop on crash, check that here: 3128 if (!m_quit_requested 3129 && result.GetDidChangeProcessState() 3130 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) 3131 { 3132 bool should_stop = false; 3133 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); 3134 if (target_sp) 3135 { 3136 ProcessSP process_sp (target_sp->GetProcessSP()); 3137 if (process_sp) 3138 { 3139 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) 3140 { 3141 StopReason reason = thread_sp->GetStopReason(); 3142 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation) 3143 { 3144 should_stop = true; 3145 break; 3146 } 3147 } 3148 } 3149 } 3150 if (should_stop) 3151 { 3152 io_handler.SetIsDone(true); 3153 m_stopped_for_crash = true; 3154 } 3155 } 3156 } 3157 3158 bool 3159 CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler) 3160 { 3161 ExecutionContext exe_ctx (GetExecutionContext()); 3162 Process *process = exe_ctx.GetProcessPtr(); 3163 3164 if (process) 3165 { 3166 StateType state = process->GetState(); 3167 if (StateIsRunningState(state)) 3168 { 3169 process->Halt(); 3170 return true; // Don't do any updating when we are running 3171 } 3172 } 3173 return false; 3174 } 3175 3176 void 3177 CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt, 3178 IOHandlerDelegate &delegate, 3179 bool asynchronously, 3180 void *baton) 3181 { 3182 Debugger &debugger = GetDebugger(); 3183 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, 3184 "lldb", // Name of input reader for history 3185 prompt, // Prompt 3186 true, // Get multiple lines 3187 0, // Don't show line numbers 3188 delegate)); // IOHandlerDelegate 3189 3190 if (io_handler_sp) 3191 { 3192 io_handler_sp->SetUserData (baton); 3193 if (asynchronously) 3194 debugger.PushIOHandler(io_handler_sp); 3195 else 3196 debugger.RunIOHandler(io_handler_sp); 3197 } 3198 3199 } 3200 3201 3202 void 3203 CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt, 3204 IOHandlerDelegate &delegate, 3205 bool asynchronously, 3206 void *baton) 3207 { 3208 Debugger &debugger = GetDebugger(); 3209 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, 3210 "lldb-python", // Name of input reader for history 3211 prompt, // Prompt 3212 true, // Get multiple lines 3213 0, // Don't show line numbers 3214 delegate)); // IOHandlerDelegate 3215 3216 if (io_handler_sp) 3217 { 3218 io_handler_sp->SetUserData (baton); 3219 if (asynchronously) 3220 debugger.PushIOHandler(io_handler_sp); 3221 else 3222 debugger.RunIOHandler(io_handler_sp); 3223 } 3224 3225 } 3226 3227 bool 3228 CommandInterpreter::IsActive () 3229 { 3230 return m_debugger.IsTopIOHandler (m_command_io_handler_sp); 3231 } 3232 3233 void 3234 CommandInterpreter::RunCommandInterpreter(bool auto_handle_events, 3235 bool spawn_thread, 3236 CommandInterpreterRunOptions &options) 3237 { 3238 // Only get one line at a time 3239 const bool multiple_lines = false; 3240 m_num_errors = 0; 3241 m_quit_requested = false; 3242 m_stopped_for_crash = false; 3243 3244 // Always re-create the IOHandlerEditline in case the input 3245 // changed. The old instance might have had a non-interactive 3246 // input and now it does or vice versa. 3247 uint32_t flags= 0; 3248 3249 if (options.m_stop_on_continue == eLazyBoolYes) 3250 flags |= eHandleCommandFlagStopOnContinue; 3251 if (options.m_stop_on_error == eLazyBoolYes) 3252 flags |= eHandleCommandFlagStopOnError; 3253 if (options.m_stop_on_crash == eLazyBoolYes) 3254 flags |= eHandleCommandFlagStopOnCrash; 3255 if (options.m_echo_commands != eLazyBoolNo) 3256 flags |= eHandleCommandFlagEchoCommand; 3257 if (options.m_print_results != eLazyBoolNo) 3258 flags |= eHandleCommandFlagPrintResult; 3259 3260 3261 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger, 3262 m_debugger.GetInputFile(), 3263 m_debugger.GetOutputFile(), 3264 m_debugger.GetErrorFile(), 3265 flags, 3266 "lldb", 3267 m_debugger.GetPrompt(), 3268 multiple_lines, 3269 0, // Don't show line numbers 3270 *this)); 3271 3272 m_debugger.PushIOHandler(m_command_io_handler_sp); 3273 3274 if (auto_handle_events) 3275 m_debugger.StartEventHandlerThread(); 3276 3277 if (spawn_thread) 3278 { 3279 m_debugger.StartIOHandlerThread(); 3280 } 3281 else 3282 { 3283 m_debugger.ExecuteIOHanders(); 3284 3285 if (auto_handle_events) 3286 m_debugger.StopEventHandlerThread(); 3287 } 3288 3289 } 3290 3291