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