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