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 <string> 11 #include <vector> 12 13 #include <getopt.h> 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/CommandObjectHelp.h" 26 #include "../Commands/CommandObjectLog.h" 27 #include "../Commands/CommandObjectMemory.h" 28 #include "../Commands/CommandObjectPlatform.h" 29 #include "../Commands/CommandObjectProcess.h" 30 #include "../Commands/CommandObjectQuit.h" 31 #include "../Commands/CommandObjectRegister.h" 32 #include "../Commands/CommandObjectSettings.h" 33 #include "../Commands/CommandObjectSource.h" 34 #include "../Commands/CommandObjectCommands.h" 35 #include "../Commands/CommandObjectSyntax.h" 36 #include "../Commands/CommandObjectTarget.h" 37 #include "../Commands/CommandObjectThread.h" 38 #include "../Commands/CommandObjectType.h" 39 #include "../Commands/CommandObjectVersion.h" 40 #include "../Commands/CommandObjectWatchpoint.h" 41 42 #include "lldb/Interpreter/Args.h" 43 #include "lldb/Interpreter/Options.h" 44 #include "lldb/Core/Debugger.h" 45 #include "lldb/Core/InputReader.h" 46 #include "lldb/Core/Stream.h" 47 #include "lldb/Core/Timer.h" 48 #include "lldb/Host/Host.h" 49 #include "lldb/Target/Process.h" 50 #include "lldb/Target/Thread.h" 51 #include "lldb/Target/TargetList.h" 52 #include "lldb/Utility/CleanUp.h" 53 54 #include "lldb/Interpreter/CommandReturnObject.h" 55 #include "lldb/Interpreter/CommandInterpreter.h" 56 #include "lldb/Interpreter/ScriptInterpreterNone.h" 57 #include "lldb/Interpreter/ScriptInterpreterPython.h" 58 59 using namespace lldb; 60 using namespace lldb_private; 61 62 CommandInterpreter::CommandInterpreter 63 ( 64 Debugger &debugger, 65 ScriptLanguage script_language, 66 bool synchronous_execution 67 ) : 68 Broadcaster ("lldb.command-interpreter"), 69 m_debugger (debugger), 70 m_synchronous_execution (synchronous_execution), 71 m_skip_lldbinit_files (false), 72 m_skip_app_init_files (false), 73 m_script_interpreter_ap (), 74 m_comment_char ('#'), 75 m_repeat_char ('!'), 76 m_batch_command_mode (false), 77 m_truncation_warning(eNoTruncation) 78 { 79 const char *dbg_name = debugger.GetInstanceName().AsCString(); 80 std::string lang_name = ScriptInterpreter::LanguageToString (script_language); 81 StreamString var_name; 82 var_name.Printf ("[%s].script-lang", dbg_name); 83 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(), 84 eVarSetOperationAssign, false, 85 m_debugger.GetInstanceName().AsCString()); 86 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit"); 87 SetEventName (eBroadcastBitResetPrompt, "reset-prompt"); 88 SetEventName (eBroadcastBitQuitCommandReceived, "quit"); 89 } 90 91 void 92 CommandInterpreter::Initialize () 93 { 94 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 95 96 CommandReturnObject result; 97 98 LoadCommandDictionary (); 99 100 // Set up some initial aliases. 101 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false); 102 if (cmd_obj_sp) 103 { 104 AddAlias ("q", cmd_obj_sp); 105 AddAlias ("exit", cmd_obj_sp); 106 } 107 108 cmd_obj_sp = GetCommandSPExact ("process continue", false); 109 if (cmd_obj_sp) 110 { 111 AddAlias ("c", cmd_obj_sp); 112 AddAlias ("continue", cmd_obj_sp); 113 } 114 115 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false); 116 if (cmd_obj_sp) 117 AddAlias ("b", cmd_obj_sp); 118 119 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false); 120 if (cmd_obj_sp) 121 AddAlias ("bt", cmd_obj_sp); 122 123 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false); 124 if (cmd_obj_sp) 125 AddAlias ("si", cmd_obj_sp); 126 127 cmd_obj_sp = GetCommandSPExact ("thread step-in", false); 128 if (cmd_obj_sp) 129 { 130 AddAlias ("s", cmd_obj_sp); 131 AddAlias ("step", cmd_obj_sp); 132 } 133 134 cmd_obj_sp = GetCommandSPExact ("thread step-over", false); 135 if (cmd_obj_sp) 136 { 137 AddAlias ("n", cmd_obj_sp); 138 AddAlias ("next", cmd_obj_sp); 139 } 140 141 cmd_obj_sp = GetCommandSPExact ("thread step-out", false); 142 if (cmd_obj_sp) 143 { 144 AddAlias ("f", cmd_obj_sp); 145 AddAlias ("finish", cmd_obj_sp); 146 } 147 148 cmd_obj_sp = GetCommandSPExact ("source list", false); 149 if (cmd_obj_sp) 150 { 151 AddAlias ("l", cmd_obj_sp); 152 AddAlias ("list", cmd_obj_sp); 153 } 154 155 cmd_obj_sp = GetCommandSPExact ("memory read", false); 156 if (cmd_obj_sp) 157 AddAlias ("x", cmd_obj_sp); 158 159 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false); 160 if (cmd_obj_sp) 161 AddAlias ("up", cmd_obj_sp); 162 163 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false); 164 if (cmd_obj_sp) 165 AddAlias ("down", cmd_obj_sp); 166 167 cmd_obj_sp = GetCommandSPExact ("target create", false); 168 if (cmd_obj_sp) 169 AddAlias ("file", cmd_obj_sp); 170 171 cmd_obj_sp = GetCommandSPExact ("target modules", false); 172 if (cmd_obj_sp) 173 AddAlias ("image", cmd_obj_sp); 174 175 176 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector); 177 178 cmd_obj_sp = GetCommandSPExact ("expression", false); 179 if (cmd_obj_sp) 180 { 181 AddAlias ("expr", cmd_obj_sp); 182 183 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 184 AddAlias ("p", cmd_obj_sp); 185 AddAlias ("print", cmd_obj_sp); 186 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp); 187 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp); 188 189 alias_arguments_vector_sp.reset (new OptionArgVector); 190 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp); 191 AddAlias ("po", cmd_obj_sp); 192 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp); 193 } 194 195 cmd_obj_sp = GetCommandSPExact ("process launch", false); 196 if (cmd_obj_sp) 197 { 198 alias_arguments_vector_sp.reset (new OptionArgVector); 199 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 200 AddAlias ("r", cmd_obj_sp); 201 AddAlias ("run", cmd_obj_sp); 202 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp); 203 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp); 204 } 205 206 } 207 208 const char * 209 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) 210 { 211 // This function has not yet been implemented. 212 213 // Look for any embedded script command 214 // If found, 215 // get interpreter object from the command dictionary, 216 // call execute_one_command on it, 217 // get the results as a string, 218 // substitute that string for current stuff. 219 220 return arg; 221 } 222 223 224 void 225 CommandInterpreter::LoadCommandDictionary () 226 { 227 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 228 229 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 230 // 231 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref) 232 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use 233 // the cross-referencing stuff) are created!!! 234 // 235 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 236 237 238 // Command objects that inherit from CommandObjectCrossref must be created before other command objects 239 // are created. This is so that when another command is created that needs to go into a crossref object, 240 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command 241 // objects into the CommandDictionary now, so they are ready for use when the other commands get created. 242 243 // Non-CommandObjectCrossref commands can now be created. 244 245 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); 246 247 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); 248 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); 249 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this)); 250 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); 251 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); 252 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); 253 // m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this)); 254 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); 255 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); 256 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this)); 257 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); 258 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); 259 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this)); 260 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); 261 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); 262 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); 263 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); 264 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); 265 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); 266 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); 267 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); 268 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this)); 269 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this)); 270 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this)); 271 272 std::auto_ptr<CommandObjectRegexCommand> 273 break_regex_cmd_ap(new CommandObjectRegexCommand (*this, 274 "_regexp-break", 275 "Set a breakpoint using a regular expression to specify the location.", 276 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2)); 277 if (break_regex_cmd_ap.get()) 278 { 279 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") && 280 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") && 281 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") && 282 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") && 283 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") && 284 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") && 285 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'")) 286 { 287 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); 288 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; 289 } 290 } 291 292 std::auto_ptr<CommandObjectRegexCommand> 293 down_regex_cmd_ap(new CommandObjectRegexCommand (*this, 294 "_regexp-down", 295 "Go down \"n\" frames in the stack (1 frame by default).", 296 "_regexp-down [n]", 2)); 297 if (down_regex_cmd_ap.get()) 298 { 299 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && 300 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1")) 301 { 302 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); 303 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp; 304 } 305 } 306 307 std::auto_ptr<CommandObjectRegexCommand> 308 up_regex_cmd_ap(new CommandObjectRegexCommand (*this, 309 "_regexp-up", 310 "Go up \"n\" frames in the stack (1 frame by default).", 311 "_regexp-up [n]", 2)); 312 if (up_regex_cmd_ap.get()) 313 { 314 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && 315 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) 316 { 317 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); 318 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp; 319 } 320 } 321 } 322 323 int 324 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, 325 StringList &matches) 326 { 327 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); 328 329 if (include_aliases) 330 { 331 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); 332 } 333 334 return matches.GetSize(); 335 } 336 337 CommandObjectSP 338 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) 339 { 340 CommandObject::CommandMap::iterator pos; 341 CommandObjectSP ret_val; 342 343 std::string cmd(cmd_cstr); 344 345 if (HasCommands()) 346 { 347 pos = m_command_dict.find(cmd); 348 if (pos != m_command_dict.end()) 349 ret_val = pos->second; 350 } 351 352 if (include_aliases && HasAliases()) 353 { 354 pos = m_alias_dict.find(cmd); 355 if (pos != m_alias_dict.end()) 356 ret_val = pos->second; 357 } 358 359 if (HasUserCommands()) 360 { 361 pos = m_user_dict.find(cmd); 362 if (pos != m_user_dict.end()) 363 ret_val = pos->second; 364 } 365 366 if (!exact && ret_val == NULL) 367 { 368 // We will only get into here if we didn't find any exact matches. 369 370 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 371 372 StringList local_matches; 373 if (matches == NULL) 374 matches = &local_matches; 375 376 unsigned int num_cmd_matches = 0; 377 unsigned int num_alias_matches = 0; 378 unsigned int num_user_matches = 0; 379 380 // Look through the command dictionaries one by one, and if we get only one match from any of 381 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. 382 383 if (HasCommands()) 384 { 385 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); 386 } 387 388 if (num_cmd_matches == 1) 389 { 390 cmd.assign(matches->GetStringAtIndex(0)); 391 pos = m_command_dict.find(cmd); 392 if (pos != m_command_dict.end()) 393 real_match_sp = pos->second; 394 } 395 396 if (include_aliases && HasAliases()) 397 { 398 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); 399 400 } 401 402 if (num_alias_matches == 1) 403 { 404 cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); 405 pos = m_alias_dict.find(cmd); 406 if (pos != m_alias_dict.end()) 407 alias_match_sp = pos->second; 408 } 409 410 if (HasUserCommands()) 411 { 412 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); 413 } 414 415 if (num_user_matches == 1) 416 { 417 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); 418 419 pos = m_user_dict.find (cmd); 420 if (pos != m_user_dict.end()) 421 user_match_sp = pos->second; 422 } 423 424 // If we got exactly one match, return that, otherwise return the match list. 425 426 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) 427 { 428 if (num_cmd_matches) 429 return real_match_sp; 430 else if (num_alias_matches) 431 return alias_match_sp; 432 else 433 return user_match_sp; 434 } 435 } 436 else if (matches && ret_val != NULL) 437 { 438 matches->AppendString (cmd_cstr); 439 } 440 441 442 return ret_val; 443 } 444 445 bool 446 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace) 447 { 448 if (name && name[0]) 449 { 450 std::string name_sstr(name); 451 if (!can_replace) 452 { 453 if (m_command_dict.find (name_sstr) != m_command_dict.end()) 454 return false; 455 } 456 m_command_dict[name_sstr] = cmd_sp; 457 return true; 458 } 459 return false; 460 } 461 462 bool 463 CommandInterpreter::AddUserCommand (const char *name, 464 const lldb::CommandObjectSP &cmd_sp, 465 bool can_replace) 466 { 467 if (name && name[0]) 468 { 469 std::string name_sstr(name); 470 if (!can_replace) 471 { 472 if (m_user_dict.find (name_sstr) != m_user_dict.end()) 473 return false; 474 } 475 m_user_dict[name_sstr] = cmd_sp; 476 return true; 477 } 478 return false; 479 } 480 481 CommandObjectSP 482 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) 483 { 484 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command. 485 CommandObjectSP ret_val; // Possibly empty return value. 486 487 if (cmd_cstr == NULL) 488 return ret_val; 489 490 if (cmd_words.GetArgumentCount() == 1) 491 return GetCommandSP(cmd_cstr, include_aliases, true, NULL); 492 else 493 { 494 // We have a multi-word command (seemingly), so we need to do more work. 495 // First, get the cmd_obj_sp for the first word in the command. 496 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL); 497 if (cmd_obj_sp.get() != NULL) 498 { 499 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a 500 // command name), and find the appropriate sub-command SP for each command word.... 501 size_t end = cmd_words.GetArgumentCount(); 502 for (size_t j= 1; j < end; ++j) 503 { 504 if (cmd_obj_sp->IsMultiwordObject()) 505 { 506 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP 507 (cmd_words.GetArgumentAtIndex (j)); 508 if (cmd_obj_sp.get() == NULL) 509 // The sub-command name was invalid. Fail and return the empty 'ret_val'. 510 return ret_val; 511 } 512 else 513 // We have more words in the command name, but we don't have a multiword object. Fail and return 514 // empty 'ret_val'. 515 return ret_val; 516 } 517 // We successfully looped through all the command words and got valid command objects for them. Assign the 518 // last object retrieved to 'ret_val'. 519 ret_val = cmd_obj_sp; 520 } 521 } 522 return ret_val; 523 } 524 525 CommandObject * 526 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) 527 { 528 return GetCommandSPExact (cmd_cstr, include_aliases).get(); 529 } 530 531 CommandObject * 532 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) 533 { 534 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); 535 536 // If we didn't find an exact match to the command string in the commands, look in 537 // the aliases. 538 539 if (command_obj == NULL) 540 { 541 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); 542 } 543 544 // Finally, if there wasn't an exact match among the aliases, look for an inexact match 545 // in both the commands and the aliases. 546 547 if (command_obj == NULL) 548 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get(); 549 550 return command_obj; 551 } 552 553 bool 554 CommandInterpreter::CommandExists (const char *cmd) 555 { 556 return m_command_dict.find(cmd) != m_command_dict.end(); 557 } 558 559 bool 560 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp, 561 const char *options_args, 562 OptionArgVectorSP &option_arg_vector_sp) 563 { 564 bool success = true; 565 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 566 567 if (!options_args || (strlen (options_args) < 1)) 568 return true; 569 570 std::string options_string (options_args); 571 Args args (options_args); 572 CommandReturnObject result; 573 // Check to see if the command being aliased can take any command options. 574 Options *options = cmd_obj_sp->GetOptions (); 575 if (options) 576 { 577 // See if any options were specified as part of the alias; if so, handle them appropriately. 578 options->NotifyOptionParsingStarting (); 579 args.Unshift ("dummy_arg"); 580 args.ParseAliasOptions (*options, result, option_arg_vector, options_string); 581 args.Shift (); 582 if (result.Succeeded()) 583 options->VerifyPartialOptions (result); 584 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted) 585 { 586 result.AppendError ("Unable to create requested alias.\n"); 587 return false; 588 } 589 } 590 591 if (options_string.size() > 0) 592 { 593 if (cmd_obj_sp->WantsRawCommandString ()) 594 option_arg_vector->push_back (OptionArgPair ("<argument>", 595 OptionArgValue (-1, 596 options_string))); 597 else 598 { 599 int argc = args.GetArgumentCount(); 600 for (size_t i = 0; i < argc; ++i) 601 if (strcmp (args.GetArgumentAtIndex (i), "") != 0) 602 option_arg_vector->push_back 603 (OptionArgPair ("<argument>", 604 OptionArgValue (-1, 605 std::string (args.GetArgumentAtIndex (i))))); 606 } 607 } 608 609 return success; 610 } 611 612 bool 613 CommandInterpreter::AliasExists (const char *cmd) 614 { 615 return m_alias_dict.find(cmd) != m_alias_dict.end(); 616 } 617 618 bool 619 CommandInterpreter::UserCommandExists (const char *cmd) 620 { 621 return m_user_dict.find(cmd) != m_user_dict.end(); 622 } 623 624 void 625 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) 626 { 627 command_obj_sp->SetIsAlias (true); 628 m_alias_dict[alias_name] = command_obj_sp; 629 } 630 631 bool 632 CommandInterpreter::RemoveAlias (const char *alias_name) 633 { 634 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); 635 if (pos != m_alias_dict.end()) 636 { 637 m_alias_dict.erase(pos); 638 return true; 639 } 640 return false; 641 } 642 bool 643 CommandInterpreter::RemoveUser (const char *alias_name) 644 { 645 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); 646 if (pos != m_user_dict.end()) 647 { 648 m_user_dict.erase(pos); 649 return true; 650 } 651 return false; 652 } 653 654 void 655 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) 656 { 657 help_string.Printf ("'%s", command_name); 658 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 659 660 if (option_arg_vector_sp != NULL) 661 { 662 OptionArgVector *options = option_arg_vector_sp.get(); 663 for (int i = 0; i < options->size(); ++i) 664 { 665 OptionArgPair cur_option = (*options)[i]; 666 std::string opt = cur_option.first; 667 OptionArgValue value_pair = cur_option.second; 668 std::string value = value_pair.second; 669 if (opt.compare("<argument>") == 0) 670 { 671 help_string.Printf (" %s", value.c_str()); 672 } 673 else 674 { 675 help_string.Printf (" %s", opt.c_str()); 676 if ((value.compare ("<no-argument>") != 0) 677 && (value.compare ("<need-argument") != 0)) 678 { 679 help_string.Printf (" %s", value.c_str()); 680 } 681 } 682 } 683 } 684 685 help_string.Printf ("'"); 686 } 687 688 size_t 689 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) 690 { 691 CommandObject::CommandMap::const_iterator pos; 692 CommandObject::CommandMap::const_iterator end = dict.end(); 693 size_t max_len = 0; 694 695 for (pos = dict.begin(); pos != end; ++pos) 696 { 697 size_t len = pos->first.size(); 698 if (max_len < len) 699 max_len = len; 700 } 701 return max_len; 702 } 703 704 void 705 CommandInterpreter::GetHelp (CommandReturnObject &result, 706 uint32_t cmd_types) 707 { 708 CommandObject::CommandMap::const_iterator pos; 709 uint32_t max_len = FindLongestCommandWord (m_command_dict); 710 711 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin ) 712 { 713 714 result.AppendMessage("The following is a list of built-in, permanent debugger commands:"); 715 result.AppendMessage(""); 716 717 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 718 { 719 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 720 max_len); 721 } 722 result.AppendMessage(""); 723 724 } 725 726 if (m_alias_dict.size() > 0 && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases )) 727 { 728 result.AppendMessage("The following is a list of your current command abbreviations " 729 "(see 'help command alias' for more info):"); 730 result.AppendMessage(""); 731 max_len = FindLongestCommandWord (m_alias_dict); 732 733 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) 734 { 735 StreamString sstr; 736 StreamString translation_and_help; 737 std::string entry_name = pos->first; 738 std::string second_entry = pos->second.get()->GetCommandName(); 739 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); 740 741 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); 742 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", 743 translation_and_help.GetData(), max_len); 744 } 745 result.AppendMessage(""); 746 } 747 748 if (m_user_dict.size() > 0 && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef )) 749 { 750 result.AppendMessage ("The following is a list of your current user-defined commands:"); 751 result.AppendMessage(""); 752 max_len = FindLongestCommandWord (m_user_dict); 753 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 754 { 755 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 756 max_len); 757 } 758 result.AppendMessage(""); 759 } 760 761 result.AppendMessage("For more information on any particular command, try 'help <command-name>'."); 762 } 763 764 CommandObject * 765 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string) 766 { 767 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will 768 // eventually be invoked by the given command line. 769 770 CommandObject *cmd_obj = NULL; 771 std::string white_space (" \t\v"); 772 size_t start = command_string.find_first_not_of (white_space); 773 size_t end = 0; 774 bool done = false; 775 while (!done) 776 { 777 if (start != std::string::npos) 778 { 779 // Get the next word from command_string. 780 end = command_string.find_first_of (white_space, start); 781 if (end == std::string::npos) 782 end = command_string.size(); 783 std::string cmd_word = command_string.substr (start, end - start); 784 785 if (cmd_obj == NULL) 786 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid 787 // command or alias. 788 cmd_obj = GetCommandObject (cmd_word.c_str()); 789 else if (cmd_obj->IsMultiwordObject ()) 790 { 791 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object. 792 CommandObject *sub_cmd_obj = 793 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str()); 794 if (sub_cmd_obj) 795 cmd_obj = sub_cmd_obj; 796 else // cmd_word was not a valid sub-command word, so we are donee 797 done = true; 798 } 799 else 800 // We have a cmd_obj and it is not a multi-word object, so we are done. 801 done = true; 802 803 // If we didn't find a valid command object, or our command object is not a multi-word object, or 804 // we are at the end of the command_string, then we are done. Otherwise, find the start of the 805 // next word. 806 807 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size()) 808 done = true; 809 else 810 start = command_string.find_first_not_of (white_space, end); 811 } 812 else 813 // Unable to find any more words. 814 done = true; 815 } 816 817 if (end == command_string.size()) 818 command_string.clear(); 819 else 820 command_string = command_string.substr(end); 821 822 return cmd_obj; 823 } 824 825 bool 826 CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char "e_char) 827 { 828 std::string white_space (" \t\v"); 829 size_t start; 830 size_t end; 831 832 start = command_string.find_first_not_of (white_space); 833 if (start != std::string::npos) 834 { 835 size_t len = command_string.size() - start; 836 if (len >= 2 837 && ((command_string[start] == '\'') || (command_string[start] == '"'))) 838 { 839 was_quoted = true; 840 quote_char = command_string[start]; 841 std::string quote_string = command_string.substr (start, 1); 842 start = start + 1; 843 end = command_string.find (quote_string, start); 844 if (end != std::string::npos) 845 { 846 word = command_string.substr (start, end - start); 847 if (end + 1 < len) 848 command_string = command_string.substr (end+1); 849 else 850 command_string.erase (); 851 size_t pos = command_string.find_first_not_of (white_space); 852 if ((pos != 0) && (pos != std::string::npos)) 853 command_string = command_string.substr (pos); 854 } 855 else 856 { 857 word = command_string.substr (start - 1); 858 command_string.erase (); 859 } 860 } 861 else 862 { 863 end = command_string.find_first_of (white_space, start); 864 if (end != std::string::npos) 865 { 866 word = command_string.substr (start, end - start); 867 command_string = command_string.substr (end); 868 size_t pos = command_string.find_first_not_of (white_space); 869 if ((pos != 0) && (pos != std::string::npos)) 870 command_string = command_string.substr (pos); 871 } 872 else 873 { 874 word = command_string.substr (start); 875 command_string.erase(); 876 } 877 } 878 879 } 880 return true; 881 } 882 883 void 884 CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result, 885 CommandObject *&alias_cmd_obj, CommandReturnObject &result) 886 { 887 Args cmd_args (raw_input_string.c_str()); 888 alias_cmd_obj = GetCommandObject (alias_name); 889 StreamString result_str; 890 891 if (alias_cmd_obj) 892 { 893 std::string alias_name_str = alias_name; 894 if ((cmd_args.GetArgumentCount() == 0) 895 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)) 896 cmd_args.Unshift (alias_name); 897 898 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ()); 899 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 900 901 if (option_arg_vector_sp.get()) 902 { 903 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 904 905 for (int i = 0; i < option_arg_vector->size(); ++i) 906 { 907 OptionArgPair option_pair = (*option_arg_vector)[i]; 908 OptionArgValue value_pair = option_pair.second; 909 int value_type = value_pair.first; 910 std::string option = option_pair.first; 911 std::string value = value_pair.second; 912 if (option.compare ("<argument>") == 0) 913 result_str.Printf (" %s", value.c_str()); 914 else 915 { 916 result_str.Printf (" %s", option.c_str()); 917 if (value_type != optional_argument) 918 result_str.Printf (" "); 919 if (value.compare ("<no_argument>") != 0) 920 { 921 int index = GetOptionArgumentPosition (value.c_str()); 922 if (index == 0) 923 result_str.Printf ("%s", value.c_str()); 924 else if (index >= cmd_args.GetArgumentCount()) 925 { 926 927 result.AppendErrorWithFormat 928 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 929 index); 930 result.SetStatus (eReturnStatusFailed); 931 return; 932 } 933 else 934 { 935 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 936 if (strpos != std::string::npos) 937 raw_input_string = raw_input_string.erase (strpos, 938 strlen (cmd_args.GetArgumentAtIndex (index))); 939 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index)); 940 } 941 } 942 } 943 } 944 } 945 946 alias_result = result_str.GetData(); 947 } 948 } 949 950 bool 951 CommandInterpreter::HandleCommand (const char *command_line, 952 bool add_to_history, 953 CommandReturnObject &result, 954 ExecutionContext *override_context, 955 bool repeat_on_empty_command) 956 957 { 958 959 bool done = false; 960 CommandObject *cmd_obj = NULL; 961 std::string next_word; 962 bool wants_raw_input = false; 963 std::string command_string (command_line); 964 std::string original_command_string (command_line); 965 966 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS)); 967 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line); 968 969 // Make a scoped cleanup object that will clear the crash description string 970 // on exit of this function. 971 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription); 972 973 if (log) 974 log->Printf ("Processing command: %s", command_line); 975 976 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line); 977 978 UpdateExecutionContext (override_context); 979 980 bool empty_command = false; 981 bool comment_command = false; 982 if (command_string.empty()) 983 empty_command = true; 984 else 985 { 986 const char *k_space_characters = "\t\n\v\f\r "; 987 988 size_t non_space = command_string.find_first_not_of (k_space_characters); 989 // Check for empty line or comment line (lines whose first 990 // non-space character is the comment character for this interpreter) 991 if (non_space == std::string::npos) 992 empty_command = true; 993 else if (command_string[non_space] == m_comment_char) 994 comment_command = true; 995 else if (command_string[non_space] == m_repeat_char) 996 { 997 const char *history_string = FindHistoryString (command_string.c_str() + non_space); 998 if (history_string == NULL) 999 { 1000 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str()); 1001 result.SetStatus(eReturnStatusFailed); 1002 return false; 1003 } 1004 add_to_history = false; 1005 command_string = history_string; 1006 original_command_string = history_string; 1007 } 1008 } 1009 1010 if (empty_command) 1011 { 1012 if (repeat_on_empty_command) 1013 { 1014 if (m_command_history.empty()) 1015 { 1016 result.AppendError ("empty command"); 1017 result.SetStatus(eReturnStatusFailed); 1018 return false; 1019 } 1020 else 1021 { 1022 command_line = m_repeat_command.c_str(); 1023 command_string = command_line; 1024 original_command_string = command_line; 1025 if (m_repeat_command.empty()) 1026 { 1027 result.AppendErrorWithFormat("No auto repeat.\n"); 1028 result.SetStatus (eReturnStatusFailed); 1029 return false; 1030 } 1031 } 1032 add_to_history = false; 1033 } 1034 else 1035 { 1036 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1037 return true; 1038 } 1039 } 1040 else if (comment_command) 1041 { 1042 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1043 return true; 1044 } 1045 1046 // Phase 1. 1047 1048 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object 1049 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that 1050 // the user could have specified an alias, and in translating the alias there may also be command options and/or 1051 // even data (including raw text strings) that need to be found and inserted into the command line as part of 1052 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command 1053 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions & 1054 // replacements taken care of; 3). whether or not the Execute function wants raw input or not. 1055 1056 StreamString revised_command_line; 1057 size_t actual_cmd_name_len = 0; 1058 while (!done) 1059 { 1060 bool was_quoted = false; 1061 char quote_char = '\0'; 1062 StripFirstWord (command_string, next_word, was_quoted, quote_char); 1063 if (!cmd_obj && AliasExists (next_word.c_str())) 1064 { 1065 std::string alias_result; 1066 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result); 1067 revised_command_line.Printf ("%s", alias_result.c_str()); 1068 if (cmd_obj) 1069 { 1070 wants_raw_input = cmd_obj->WantsRawCommandString (); 1071 actual_cmd_name_len = strlen (cmd_obj->GetCommandName()); 1072 } 1073 } 1074 else if (!cmd_obj) 1075 { 1076 cmd_obj = GetCommandObject (next_word.c_str()); 1077 if (cmd_obj) 1078 { 1079 actual_cmd_name_len += next_word.length(); 1080 revised_command_line.Printf ("%s", next_word.c_str()); 1081 wants_raw_input = cmd_obj->WantsRawCommandString (); 1082 } 1083 else 1084 { 1085 revised_command_line.Printf ("%s", next_word.c_str()); 1086 } 1087 } 1088 else if (cmd_obj->IsMultiwordObject ()) 1089 { 1090 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str()); 1091 if (sub_cmd_obj) 1092 { 1093 actual_cmd_name_len += next_word.length() + 1; 1094 revised_command_line.Printf (" %s", next_word.c_str()); 1095 cmd_obj = sub_cmd_obj; 1096 wants_raw_input = cmd_obj->WantsRawCommandString (); 1097 } 1098 else 1099 { 1100 if (was_quoted) 1101 { 1102 if (quote_char == '"') 1103 revised_command_line.Printf (" \"%s\"", next_word.c_str()); 1104 else 1105 revised_command_line.Printf (" '%s'", next_word.c_str()); 1106 } 1107 else 1108 revised_command_line.Printf (" %s", next_word.c_str()); 1109 done = true; 1110 } 1111 } 1112 else 1113 { 1114 if (was_quoted) 1115 { 1116 if (quote_char == '"') 1117 revised_command_line.Printf (" \"%s\"", next_word.c_str()); 1118 else 1119 revised_command_line.Printf (" '%s'", next_word.c_str()); 1120 } 1121 else 1122 revised_command_line.Printf (" %s", next_word.c_str()); 1123 done = true; 1124 } 1125 1126 if (cmd_obj == NULL) 1127 { 1128 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str()); 1129 result.SetStatus (eReturnStatusFailed); 1130 return false; 1131 } 1132 1133 next_word.erase (); 1134 if (command_string.length() == 0) 1135 done = true; 1136 1137 } 1138 1139 if (command_string.size() > 0) 1140 revised_command_line.Printf (" %s", command_string.c_str()); 1141 1142 // End of Phase 1. 1143 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command 1144 // specified was valid; revised_command_line contains the complete command line (including command name(s)), 1145 // fully translated with all substitutions & translations taken care of (still in raw text format); and 1146 // wants_raw_input specifies whether the Execute method expects raw input or not. 1147 1148 1149 if (log) 1150 { 1151 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>"); 1152 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData()); 1153 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); 1154 } 1155 1156 // Phase 2. 1157 // Take care of things like setting up the history command & calling the appropriate Execute method on the 1158 // CommandObject, with the appropriate arguments. 1159 1160 if (cmd_obj != NULL) 1161 { 1162 if (add_to_history) 1163 { 1164 Args command_args (revised_command_line.GetData()); 1165 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); 1166 if (repeat_command != NULL) 1167 m_repeat_command.assign(repeat_command); 1168 else 1169 m_repeat_command.assign(original_command_string.c_str()); 1170 1171 // Don't keep pushing the same command onto the history... 1172 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string) 1173 m_command_history.push_back (original_command_string); 1174 } 1175 1176 command_string = revised_command_line.GetData(); 1177 std::string command_name (cmd_obj->GetCommandName()); 1178 std::string remainder; 1179 if (actual_cmd_name_len < command_string.length()) 1180 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter 1181 // than cmd_obj->GetCommandName(), because name completion 1182 // allows users to enter short versions of the names, 1183 // e.g. 'br s' for 'breakpoint set'. 1184 1185 // Remove any initial spaces 1186 std::string white_space (" \t\v"); 1187 size_t pos = remainder.find_first_not_of (white_space); 1188 if (pos != 0 && pos != std::string::npos) 1189 remainder.erase(0, pos); 1190 1191 if (log) 1192 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str()); 1193 1194 1195 if (wants_raw_input) 1196 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result); 1197 else 1198 { 1199 Args cmd_args (remainder.c_str()); 1200 cmd_obj->ExecuteWithOptions (cmd_args, result); 1201 } 1202 } 1203 else 1204 { 1205 // We didn't find the first command object, so complete the first argument. 1206 Args command_args (revised_command_line.GetData()); 1207 StringList matches; 1208 int num_matches; 1209 int cursor_index = 0; 1210 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 1211 bool word_complete; 1212 num_matches = HandleCompletionMatches (command_args, 1213 cursor_index, 1214 cursor_char_position, 1215 0, 1216 -1, 1217 word_complete, 1218 matches); 1219 1220 if (num_matches > 0) 1221 { 1222 std::string error_msg; 1223 error_msg.assign ("ambiguous command '"); 1224 error_msg.append(command_args.GetArgumentAtIndex(0)); 1225 error_msg.append ("'."); 1226 1227 error_msg.append (" Possible completions:"); 1228 for (int i = 0; i < num_matches; i++) 1229 { 1230 error_msg.append ("\n\t"); 1231 error_msg.append (matches.GetStringAtIndex (i)); 1232 } 1233 error_msg.append ("\n"); 1234 result.AppendRawError (error_msg.c_str(), error_msg.size()); 1235 } 1236 else 1237 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); 1238 1239 result.SetStatus (eReturnStatusFailed); 1240 } 1241 1242 if (log) 1243 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed")); 1244 1245 return result.Succeeded(); 1246 } 1247 1248 int 1249 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 1250 int &cursor_index, 1251 int &cursor_char_position, 1252 int match_start_point, 1253 int max_return_elements, 1254 bool &word_complete, 1255 StringList &matches) 1256 { 1257 int num_command_matches = 0; 1258 bool look_for_subcommand = false; 1259 1260 // For any of the command completions a unique match will be a complete word. 1261 word_complete = true; 1262 1263 if (cursor_index == -1) 1264 { 1265 // We got nothing on the command line, so return the list of commands 1266 bool include_aliases = true; 1267 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 1268 } 1269 else if (cursor_index == 0) 1270 { 1271 // The cursor is in the first argument, so just do a lookup in the dictionary. 1272 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 1273 num_command_matches = matches.GetSize(); 1274 1275 if (num_command_matches == 1 1276 && cmd_obj && cmd_obj->IsMultiwordObject() 1277 && matches.GetStringAtIndex(0) != NULL 1278 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 1279 { 1280 look_for_subcommand = true; 1281 num_command_matches = 0; 1282 matches.DeleteStringAtIndex(0); 1283 parsed_line.AppendArgument (""); 1284 cursor_index++; 1285 cursor_char_position = 0; 1286 } 1287 } 1288 1289 if (cursor_index > 0 || look_for_subcommand) 1290 { 1291 // We are completing further on into a commands arguments, so find the command and tell it 1292 // to complete the command. 1293 // First see if there is a matching initial command: 1294 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 1295 if (command_object == NULL) 1296 { 1297 return 0; 1298 } 1299 else 1300 { 1301 parsed_line.Shift(); 1302 cursor_index--; 1303 num_command_matches = command_object->HandleCompletion (parsed_line, 1304 cursor_index, 1305 cursor_char_position, 1306 match_start_point, 1307 max_return_elements, 1308 word_complete, 1309 matches); 1310 } 1311 } 1312 1313 return num_command_matches; 1314 1315 } 1316 1317 int 1318 CommandInterpreter::HandleCompletion (const char *current_line, 1319 const char *cursor, 1320 const char *last_char, 1321 int match_start_point, 1322 int max_return_elements, 1323 StringList &matches) 1324 { 1325 // We parse the argument up to the cursor, so the last argument in parsed_line is 1326 // the one containing the cursor, and the cursor is after the last character. 1327 1328 Args parsed_line(current_line, last_char - current_line); 1329 Args partial_parsed_line(current_line, cursor - current_line); 1330 1331 // Don't complete comments, and if the line we are completing is just the history repeat character, 1332 // substitute the appropriate history line. 1333 const char *first_arg = parsed_line.GetArgumentAtIndex(0); 1334 if (first_arg) 1335 { 1336 if (first_arg[0] == m_comment_char) 1337 return 0; 1338 else if (first_arg[0] == m_repeat_char) 1339 { 1340 const char *history_string = FindHistoryString (first_arg); 1341 if (history_string != NULL) 1342 { 1343 matches.Clear(); 1344 matches.InsertStringAtIndex(0, history_string); 1345 return -2; 1346 } 1347 else 1348 return 0; 1349 1350 } 1351 } 1352 1353 1354 int num_args = partial_parsed_line.GetArgumentCount(); 1355 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 1356 int cursor_char_position; 1357 1358 if (cursor_index == -1) 1359 cursor_char_position = 0; 1360 else 1361 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 1362 1363 if (cursor > current_line && cursor[-1] == ' ') 1364 { 1365 // We are just after a space. If we are in an argument, then we will continue 1366 // parsing, but if we are between arguments, then we have to complete whatever the next 1367 // element would be. 1368 // We can distinguish the two cases because if we are in an argument (e.g. because the space is 1369 // protected by a quote) then the space will also be in the parsed argument... 1370 1371 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); 1372 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') 1373 { 1374 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"'); 1375 cursor_index++; 1376 cursor_char_position = 0; 1377 } 1378 } 1379 1380 int num_command_matches; 1381 1382 matches.Clear(); 1383 1384 // Only max_return_elements == -1 is supported at present: 1385 assert (max_return_elements == -1); 1386 bool word_complete; 1387 num_command_matches = HandleCompletionMatches (parsed_line, 1388 cursor_index, 1389 cursor_char_position, 1390 match_start_point, 1391 max_return_elements, 1392 word_complete, 1393 matches); 1394 1395 if (num_command_matches <= 0) 1396 return num_command_matches; 1397 1398 if (num_args == 0) 1399 { 1400 // If we got an empty string, insert nothing. 1401 matches.InsertStringAtIndex(0, ""); 1402 } 1403 else 1404 { 1405 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 1406 // put an empty string in element 0. 1407 std::string command_partial_str; 1408 if (cursor_index >= 0) 1409 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 1410 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 1411 1412 std::string common_prefix; 1413 matches.LongestCommonPrefix (common_prefix); 1414 int partial_name_len = command_partial_str.size(); 1415 1416 // If we matched a unique single command, add a space... 1417 // Only do this if the completer told us this was a complete word, however... 1418 if (num_command_matches == 1 && word_complete) 1419 { 1420 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 1421 if (quote_char != '\0') 1422 common_prefix.push_back(quote_char); 1423 1424 common_prefix.push_back(' '); 1425 } 1426 common_prefix.erase (0, partial_name_len); 1427 matches.InsertStringAtIndex(0, common_prefix.c_str()); 1428 } 1429 return num_command_matches; 1430 } 1431 1432 1433 CommandInterpreter::~CommandInterpreter () 1434 { 1435 } 1436 1437 const char * 1438 CommandInterpreter::GetPrompt () 1439 { 1440 return m_debugger.GetPrompt(); 1441 } 1442 1443 void 1444 CommandInterpreter::SetPrompt (const char *new_prompt) 1445 { 1446 m_debugger.SetPrompt (new_prompt); 1447 } 1448 1449 size_t 1450 CommandInterpreter::GetConfirmationInputReaderCallback 1451 ( 1452 void *baton, 1453 InputReader &reader, 1454 lldb::InputReaderAction action, 1455 const char *bytes, 1456 size_t bytes_len 1457 ) 1458 { 1459 File &out_file = reader.GetDebugger().GetOutputFile(); 1460 bool *response_ptr = (bool *) baton; 1461 1462 switch (action) 1463 { 1464 case eInputReaderActivate: 1465 if (out_file.IsValid()) 1466 { 1467 if (reader.GetPrompt()) 1468 { 1469 out_file.Printf ("%s", reader.GetPrompt()); 1470 out_file.Flush (); 1471 } 1472 } 1473 break; 1474 1475 case eInputReaderDeactivate: 1476 break; 1477 1478 case eInputReaderReactivate: 1479 if (out_file.IsValid() && reader.GetPrompt()) 1480 { 1481 out_file.Printf ("%s", reader.GetPrompt()); 1482 out_file.Flush (); 1483 } 1484 break; 1485 1486 case eInputReaderAsynchronousOutputWritten: 1487 break; 1488 1489 case eInputReaderGotToken: 1490 if (bytes_len == 0) 1491 { 1492 reader.SetIsDone(true); 1493 } 1494 else if (bytes[0] == 'y') 1495 { 1496 *response_ptr = true; 1497 reader.SetIsDone(true); 1498 } 1499 else if (bytes[0] == 'n') 1500 { 1501 *response_ptr = false; 1502 reader.SetIsDone(true); 1503 } 1504 else 1505 { 1506 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt()) 1507 { 1508 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt()); 1509 out_file.Flush (); 1510 } 1511 } 1512 break; 1513 1514 case eInputReaderInterrupt: 1515 case eInputReaderEndOfFile: 1516 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action 1517 reader.SetIsDone (true); 1518 break; 1519 1520 case eInputReaderDone: 1521 break; 1522 } 1523 1524 return bytes_len; 1525 1526 } 1527 1528 bool 1529 CommandInterpreter::Confirm (const char *message, bool default_answer) 1530 { 1531 // Check AutoConfirm first: 1532 if (m_debugger.GetAutoConfirm()) 1533 return default_answer; 1534 1535 InputReaderSP reader_sp (new InputReader(GetDebugger())); 1536 bool response = default_answer; 1537 if (reader_sp) 1538 { 1539 std::string prompt(message); 1540 prompt.append(": ["); 1541 if (default_answer) 1542 prompt.append ("Y/n] "); 1543 else 1544 prompt.append ("y/N] "); 1545 1546 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback, 1547 &response, // baton 1548 eInputReaderGranularityLine, // token size, to pass to callback function 1549 NULL, // end token 1550 prompt.c_str(), // prompt 1551 true)); // echo input 1552 if (err.Success()) 1553 { 1554 GetDebugger().PushInputReader (reader_sp); 1555 } 1556 reader_sp->WaitOnReaderIsDone(); 1557 } 1558 return response; 1559 } 1560 1561 1562 void 1563 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type) 1564 { 1565 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true); 1566 1567 if (cmd_obj_sp != NULL) 1568 { 1569 CommandObject *cmd_obj = cmd_obj_sp.get(); 1570 if (cmd_obj->IsCrossRefObject ()) 1571 cmd_obj->AddObject (object_type); 1572 } 1573 } 1574 1575 OptionArgVectorSP 1576 CommandInterpreter::GetAliasOptions (const char *alias_name) 1577 { 1578 OptionArgMap::iterator pos; 1579 OptionArgVectorSP ret_val; 1580 1581 std::string alias (alias_name); 1582 1583 if (HasAliasOptions()) 1584 { 1585 pos = m_alias_options.find (alias); 1586 if (pos != m_alias_options.end()) 1587 ret_val = pos->second; 1588 } 1589 1590 return ret_val; 1591 } 1592 1593 void 1594 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 1595 { 1596 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 1597 if (pos != m_alias_options.end()) 1598 { 1599 m_alias_options.erase (pos); 1600 } 1601 } 1602 1603 void 1604 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 1605 { 1606 m_alias_options[alias_name] = option_arg_vector_sp; 1607 } 1608 1609 bool 1610 CommandInterpreter::HasCommands () 1611 { 1612 return (!m_command_dict.empty()); 1613 } 1614 1615 bool 1616 CommandInterpreter::HasAliases () 1617 { 1618 return (!m_alias_dict.empty()); 1619 } 1620 1621 bool 1622 CommandInterpreter::HasUserCommands () 1623 { 1624 return (!m_user_dict.empty()); 1625 } 1626 1627 bool 1628 CommandInterpreter::HasAliasOptions () 1629 { 1630 return (!m_alias_options.empty()); 1631 } 1632 1633 void 1634 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 1635 const char *alias_name, 1636 Args &cmd_args, 1637 std::string &raw_input_string, 1638 CommandReturnObject &result) 1639 { 1640 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1641 1642 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 1643 1644 // Make sure that the alias name is the 0th element in cmd_args 1645 std::string alias_name_str = alias_name; 1646 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 1647 cmd_args.Unshift (alias_name); 1648 1649 Args new_args (alias_cmd_obj->GetCommandName()); 1650 if (new_args.GetArgumentCount() == 2) 1651 new_args.Shift(); 1652 1653 if (option_arg_vector_sp.get()) 1654 { 1655 if (wants_raw_input) 1656 { 1657 // We have a command that both has command options and takes raw input. Make *sure* it has a 1658 // " -- " in the right place in the raw_input_string. 1659 size_t pos = raw_input_string.find(" -- "); 1660 if (pos == std::string::npos) 1661 { 1662 // None found; assume it goes at the beginning of the raw input string 1663 raw_input_string.insert (0, " -- "); 1664 } 1665 } 1666 1667 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1668 int old_size = cmd_args.GetArgumentCount(); 1669 std::vector<bool> used (old_size + 1, false); 1670 1671 used[0] = true; 1672 1673 for (int i = 0; i < option_arg_vector->size(); ++i) 1674 { 1675 OptionArgPair option_pair = (*option_arg_vector)[i]; 1676 OptionArgValue value_pair = option_pair.second; 1677 int value_type = value_pair.first; 1678 std::string option = option_pair.first; 1679 std::string value = value_pair.second; 1680 if (option.compare ("<argument>") == 0) 1681 { 1682 if (!wants_raw_input 1683 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice 1684 new_args.AppendArgument (value.c_str()); 1685 } 1686 else 1687 { 1688 if (value_type != optional_argument) 1689 new_args.AppendArgument (option.c_str()); 1690 if (value.compare ("<no-argument>") != 0) 1691 { 1692 int index = GetOptionArgumentPosition (value.c_str()); 1693 if (index == 0) 1694 { 1695 // value was NOT a positional argument; must be a real value 1696 if (value_type != optional_argument) 1697 new_args.AppendArgument (value.c_str()); 1698 else 1699 { 1700 char buffer[255]; 1701 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); 1702 new_args.AppendArgument (buffer); 1703 } 1704 1705 } 1706 else if (index >= cmd_args.GetArgumentCount()) 1707 { 1708 result.AppendErrorWithFormat 1709 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 1710 index); 1711 result.SetStatus (eReturnStatusFailed); 1712 return; 1713 } 1714 else 1715 { 1716 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 1717 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 1718 if (strpos != std::string::npos) 1719 { 1720 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); 1721 } 1722 1723 if (value_type != optional_argument) 1724 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 1725 else 1726 { 1727 char buffer[255]; 1728 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), 1729 cmd_args.GetArgumentAtIndex (index)); 1730 new_args.AppendArgument (buffer); 1731 } 1732 used[index] = true; 1733 } 1734 } 1735 } 1736 } 1737 1738 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j) 1739 { 1740 if (!used[j] && !wants_raw_input) 1741 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 1742 } 1743 1744 cmd_args.Clear(); 1745 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 1746 } 1747 else 1748 { 1749 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1750 // This alias was not created with any options; nothing further needs to be done, unless it is a command that 1751 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw 1752 // input string. 1753 if (wants_raw_input) 1754 { 1755 cmd_args.Clear(); 1756 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 1757 } 1758 return; 1759 } 1760 1761 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1762 return; 1763 } 1764 1765 1766 int 1767 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 1768 { 1769 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 1770 // of zero. 1771 1772 char *cptr = (char *) in_string; 1773 1774 // Does it start with '%' 1775 if (cptr[0] == '%') 1776 { 1777 ++cptr; 1778 1779 // Is the rest of it entirely digits? 1780 if (isdigit (cptr[0])) 1781 { 1782 const char *start = cptr; 1783 while (isdigit (cptr[0])) 1784 ++cptr; 1785 1786 // We've gotten to the end of the digits; are we at the end of the string? 1787 if (cptr[0] == '\0') 1788 position = atoi (start); 1789 } 1790 } 1791 1792 return position; 1793 } 1794 1795 void 1796 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 1797 { 1798 FileSpec init_file; 1799 if (in_cwd) 1800 { 1801 // In the current working directory we don't load any program specific 1802 // .lldbinit files, we only look for a "./.lldbinit" file. 1803 if (m_skip_lldbinit_files) 1804 return; 1805 1806 init_file.SetFile ("./.lldbinit", true); 1807 } 1808 else 1809 { 1810 // If we aren't looking in the current working directory we are looking 1811 // in the home directory. We will first see if there is an application 1812 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a 1813 // "-" and the name of the program. If this file doesn't exist, we fall 1814 // back to just the "~/.lldbinit" file. We also obey any requests to not 1815 // load the init files. 1816 const char *init_file_path = "~/.lldbinit"; 1817 1818 if (m_skip_app_init_files == false) 1819 { 1820 FileSpec program_file_spec (Host::GetProgramFileSpec()); 1821 const char *program_name = program_file_spec.GetFilename().AsCString(); 1822 1823 if (program_name) 1824 { 1825 char program_init_file_name[PATH_MAX]; 1826 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name); 1827 init_file.SetFile (program_init_file_name, true); 1828 if (!init_file.Exists()) 1829 init_file.Clear(); 1830 } 1831 } 1832 1833 if (!init_file && !m_skip_lldbinit_files) 1834 init_file.SetFile (init_file_path, true); 1835 } 1836 1837 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 1838 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 1839 1840 if (init_file.Exists()) 1841 { 1842 ExecutionContext *exe_ctx = NULL; // We don't have any context yet. 1843 bool stop_on_continue = true; 1844 bool stop_on_error = false; 1845 bool echo_commands = false; 1846 bool print_results = false; 1847 1848 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result); 1849 } 1850 else 1851 { 1852 // nothing to be done if the file doesn't exist 1853 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1854 } 1855 } 1856 1857 PlatformSP 1858 CommandInterpreter::GetPlatform (bool prefer_target_platform) 1859 { 1860 PlatformSP platform_sp; 1861 if (prefer_target_platform) 1862 { 1863 Target *target = m_exe_ctx.GetTargetPtr(); 1864 if (target) 1865 platform_sp = target->GetPlatform(); 1866 } 1867 1868 if (!platform_sp) 1869 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 1870 return platform_sp; 1871 } 1872 1873 void 1874 CommandInterpreter::HandleCommands (const StringList &commands, 1875 ExecutionContext *override_context, 1876 bool stop_on_continue, 1877 bool stop_on_error, 1878 bool echo_commands, 1879 bool print_results, 1880 CommandReturnObject &result) 1881 { 1882 size_t num_lines = commands.GetSize(); 1883 1884 // If we are going to continue past a "continue" then we need to run the commands synchronously. 1885 // Make sure you reset this value anywhere you return from the function. 1886 1887 bool old_async_execution = m_debugger.GetAsyncExecution(); 1888 1889 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will 1890 // cause series of commands that change the context, then do an operation that relies on that context to fail. 1891 1892 if (override_context != NULL) 1893 UpdateExecutionContext (override_context); 1894 1895 if (!stop_on_continue) 1896 { 1897 m_debugger.SetAsyncExecution (false); 1898 } 1899 1900 for (int idx = 0; idx < num_lines; idx++) 1901 { 1902 const char *cmd = commands.GetStringAtIndex(idx); 1903 if (cmd[0] == '\0') 1904 continue; 1905 1906 if (echo_commands) 1907 { 1908 result.AppendMessageWithFormat ("%s %s\n", 1909 GetPrompt(), 1910 cmd); 1911 } 1912 1913 CommandReturnObject tmp_result; 1914 bool success = HandleCommand(cmd, false, tmp_result, NULL); 1915 1916 if (print_results) 1917 { 1918 if (tmp_result.Succeeded()) 1919 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData()); 1920 } 1921 1922 if (!success || !tmp_result.Succeeded()) 1923 { 1924 if (stop_on_error) 1925 { 1926 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n", 1927 idx, cmd); 1928 result.SetStatus (eReturnStatusFailed); 1929 m_debugger.SetAsyncExecution (old_async_execution); 1930 return; 1931 } 1932 else if (print_results) 1933 { 1934 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n", 1935 idx + 1, 1936 cmd, 1937 tmp_result.GetErrorData()); 1938 } 1939 } 1940 1941 if (result.GetImmediateOutputStream()) 1942 result.GetImmediateOutputStream()->Flush(); 1943 1944 if (result.GetImmediateErrorStream()) 1945 result.GetImmediateErrorStream()->Flush(); 1946 1947 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution 1948 // could be running (for instance in Breakpoint Commands. 1949 // So we check the return value to see if it is has running in it. 1950 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) 1951 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) 1952 { 1953 if (stop_on_continue) 1954 { 1955 // If we caused the target to proceed, and we're going to stop in that case, set the 1956 // status in our real result before returning. This is an error if the continue was not the 1957 // last command in the set of commands to be run. 1958 if (idx != num_lines - 1) 1959 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n", 1960 idx + 1, cmd); 1961 else 1962 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd); 1963 1964 result.SetStatus(tmp_result.GetStatus()); 1965 m_debugger.SetAsyncExecution (old_async_execution); 1966 1967 return; 1968 } 1969 } 1970 1971 } 1972 1973 result.SetStatus (eReturnStatusSuccessFinishResult); 1974 m_debugger.SetAsyncExecution (old_async_execution); 1975 1976 return; 1977 } 1978 1979 void 1980 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file, 1981 ExecutionContext *context, 1982 bool stop_on_continue, 1983 bool stop_on_error, 1984 bool echo_command, 1985 bool print_result, 1986 CommandReturnObject &result) 1987 { 1988 if (cmd_file.Exists()) 1989 { 1990 bool success; 1991 StringList commands; 1992 success = commands.ReadFileLines(cmd_file); 1993 if (!success) 1994 { 1995 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString()); 1996 result.SetStatus (eReturnStatusFailed); 1997 return; 1998 } 1999 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result); 2000 } 2001 else 2002 { 2003 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n", 2004 cmd_file.GetFilename().AsCString()); 2005 result.SetStatus (eReturnStatusFailed); 2006 return; 2007 } 2008 } 2009 2010 ScriptInterpreter * 2011 CommandInterpreter::GetScriptInterpreter () 2012 { 2013 if (m_script_interpreter_ap.get() != NULL) 2014 return m_script_interpreter_ap.get(); 2015 2016 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); 2017 switch (script_lang) 2018 { 2019 case eScriptLanguageNone: 2020 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this)); 2021 break; 2022 case eScriptLanguagePython: 2023 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this)); 2024 break; 2025 default: 2026 break; 2027 }; 2028 2029 return m_script_interpreter_ap.get(); 2030 } 2031 2032 2033 2034 bool 2035 CommandInterpreter::GetSynchronous () 2036 { 2037 return m_synchronous_execution; 2038 } 2039 2040 void 2041 CommandInterpreter::SetSynchronous (bool value) 2042 { 2043 m_synchronous_execution = value; 2044 } 2045 2046 void 2047 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 2048 const char *word_text, 2049 const char *separator, 2050 const char *help_text, 2051 uint32_t max_word_len) 2052 { 2053 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2054 2055 int indent_size = max_word_len + strlen (separator) + 2; 2056 2057 strm.IndentMore (indent_size); 2058 2059 StreamString text_strm; 2060 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2061 2062 size_t len = text_strm.GetSize(); 2063 const char *text = text_strm.GetData(); 2064 if (text[len - 1] == '\n') 2065 { 2066 text_strm.EOL(); 2067 len = text_strm.GetSize(); 2068 } 2069 2070 if (len < max_columns) 2071 { 2072 // Output it as a single line. 2073 strm.Printf ("%s", text); 2074 } 2075 else 2076 { 2077 // We need to break it up into multiple lines. 2078 bool first_line = true; 2079 int text_width; 2080 int start = 0; 2081 int end = start; 2082 int final_end = strlen (text); 2083 int sub_len; 2084 2085 while (end < final_end) 2086 { 2087 if (first_line) 2088 text_width = max_columns - 1; 2089 else 2090 text_width = max_columns - indent_size - 1; 2091 2092 // Don't start the 'text' on a space, since we're already outputting the indentation. 2093 if (!first_line) 2094 { 2095 while ((start < final_end) && (text[start] == ' ')) 2096 start++; 2097 } 2098 2099 end = start + text_width; 2100 if (end > final_end) 2101 end = final_end; 2102 else 2103 { 2104 // If we're not at the end of the text, make sure we break the line on white space. 2105 while (end > start 2106 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 2107 end--; 2108 } 2109 2110 sub_len = end - start; 2111 if (start != 0) 2112 strm.EOL(); 2113 if (!first_line) 2114 strm.Indent(); 2115 else 2116 first_line = false; 2117 assert (start <= final_end); 2118 assert (start + sub_len <= final_end); 2119 if (sub_len > 0) 2120 strm.Write (text + start, sub_len); 2121 start = end + 1; 2122 } 2123 } 2124 strm.EOL(); 2125 strm.IndentLess(indent_size); 2126 } 2127 2128 void 2129 CommandInterpreter::OutputHelpText (Stream &strm, 2130 const char *word_text, 2131 const char *separator, 2132 const char *help_text, 2133 uint32_t max_word_len) 2134 { 2135 int indent_size = max_word_len + strlen (separator) + 2; 2136 2137 strm.IndentMore (indent_size); 2138 2139 StreamString text_strm; 2140 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2141 2142 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2143 bool first_line = true; 2144 2145 size_t len = text_strm.GetSize(); 2146 const char *text = text_strm.GetData(); 2147 2148 uint32_t chars_left = max_columns; 2149 2150 for (uint32_t i = 0; i < len; i++) 2151 { 2152 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n') 2153 { 2154 first_line = false; 2155 chars_left = max_columns - indent_size; 2156 strm.EOL(); 2157 strm.Indent(); 2158 } 2159 else 2160 { 2161 strm.PutChar(text[i]); 2162 chars_left--; 2163 } 2164 2165 } 2166 2167 strm.EOL(); 2168 strm.IndentLess(indent_size); 2169 } 2170 2171 void 2172 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word, 2173 StringList &commands_found, StringList &commands_help) 2174 { 2175 CommandObject::CommandMap::const_iterator pos; 2176 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict; 2177 CommandObject *sub_cmd_obj; 2178 2179 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos) 2180 { 2181 const char * command_name = pos->first.c_str(); 2182 sub_cmd_obj = pos->second.get(); 2183 StreamString complete_command_name; 2184 2185 complete_command_name.Printf ("%s %s", prefix, command_name); 2186 2187 if (sub_cmd_obj->HelpTextContainsWord (search_word)) 2188 { 2189 commands_found.AppendString (complete_command_name.GetData()); 2190 commands_help.AppendString (sub_cmd_obj->GetHelp()); 2191 } 2192 2193 if (sub_cmd_obj->IsMultiwordObject()) 2194 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found, 2195 commands_help); 2196 } 2197 2198 } 2199 2200 void 2201 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 2202 StringList &commands_help) 2203 { 2204 CommandObject::CommandMap::const_iterator pos; 2205 2206 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 2207 { 2208 const char *command_name = pos->first.c_str(); 2209 CommandObject *cmd_obj = pos->second.get(); 2210 2211 if (cmd_obj->HelpTextContainsWord (search_word)) 2212 { 2213 commands_found.AppendString (command_name); 2214 commands_help.AppendString (cmd_obj->GetHelp()); 2215 } 2216 2217 if (cmd_obj->IsMultiwordObject()) 2218 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help); 2219 2220 } 2221 } 2222 2223 2224 void 2225 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context) 2226 { 2227 m_exe_ctx.Clear(); 2228 2229 if (override_context != NULL) 2230 { 2231 m_exe_ctx = *override_context; 2232 } 2233 else 2234 { 2235 TargetSP target_sp (m_debugger.GetSelectedTarget()); 2236 if (target_sp) 2237 { 2238 m_exe_ctx.SetTargetSP (target_sp); 2239 ProcessSP process_sp (target_sp->GetProcessSP()); 2240 m_exe_ctx.SetProcessSP (process_sp); 2241 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning()) 2242 { 2243 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get()); 2244 if (thread_sp) 2245 { 2246 m_exe_ctx.SetThreadSP (thread_sp); 2247 StackFrameSP frame_sp (thread_sp->GetSelectedFrame()); 2248 if (!frame_sp) 2249 { 2250 frame_sp = thread_sp->GetStackFrameAtIndex (0); 2251 // If we didn't have a selected frame select one here. 2252 if (frame_sp) 2253 thread_sp->SetSelectedFrame(frame_sp.get()); 2254 } 2255 if (frame_sp) 2256 m_exe_ctx.SetFrameSP (frame_sp); 2257 } 2258 } 2259 } 2260 } 2261 } 2262 2263 void 2264 CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const 2265 { 2266 DumpHistory (stream, 0, count - 1); 2267 } 2268 2269 void 2270 CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const 2271 { 2272 size_t num_history_elements = m_command_history.size(); 2273 if (start > num_history_elements) 2274 return; 2275 for (uint32_t i = start; i < num_history_elements && i <= end; i++) 2276 { 2277 if (!m_command_history[i].empty()) 2278 { 2279 stream.Indent(); 2280 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str()); 2281 } 2282 } 2283 } 2284 2285 const char * 2286 CommandInterpreter::FindHistoryString (const char *input_str) const 2287 { 2288 if (input_str[0] != m_repeat_char) 2289 return NULL; 2290 if (input_str[1] == '-') 2291 { 2292 bool success; 2293 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success); 2294 if (!success) 2295 return NULL; 2296 if (idx > m_command_history.size()) 2297 return NULL; 2298 idx = m_command_history.size() - idx; 2299 return m_command_history[idx].c_str(); 2300 2301 } 2302 else if (input_str[1] == m_repeat_char) 2303 { 2304 if (m_command_history.empty()) 2305 return NULL; 2306 else 2307 return m_command_history.back().c_str(); 2308 } 2309 else 2310 { 2311 bool success; 2312 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success); 2313 if (!success) 2314 return NULL; 2315 if (idx >= m_command_history.size()) 2316 return NULL; 2317 return m_command_history[idx].c_str(); 2318 } 2319 } 2320