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 "../Commands/CommandObjectApropos.h" 17 #include "../Commands/CommandObjectArgs.h" 18 #include "../Commands/CommandObjectBreakpoint.h" 19 //#include "../Commands/CommandObjectCall.h" 20 #include "../Commands/CommandObjectDisassemble.h" 21 #include "../Commands/CommandObjectExpression.h" 22 #include "../Commands/CommandObjectFile.h" 23 #include "../Commands/CommandObjectFrame.h" 24 #include "../Commands/CommandObjectHelp.h" 25 #include "../Commands/CommandObjectImage.h" 26 #include "../Commands/CommandObjectLog.h" 27 #include "../Commands/CommandObjectMemory.h" 28 #include "../Commands/CommandObjectProcess.h" 29 #include "../Commands/CommandObjectQuit.h" 30 #include "lldb/Interpreter/CommandObjectRegexCommand.h" 31 #include "../Commands/CommandObjectRegister.h" 32 #include "CommandObjectScript.h" 33 #include "../Commands/CommandObjectSettings.h" 34 #include "../Commands/CommandObjectSource.h" 35 #include "../Commands/CommandObjectCommands.h" 36 #include "../Commands/CommandObjectSyntax.h" 37 #include "../Commands/CommandObjectTarget.h" 38 #include "../Commands/CommandObjectThread.h" 39 40 #include "lldb/Interpreter/Args.h" 41 #include "lldb/Core/Debugger.h" 42 #include "lldb/Core/InputReader.h" 43 #include "lldb/Core/Stream.h" 44 #include "lldb/Core/Timer.h" 45 #include "lldb/Target/Process.h" 46 #include "lldb/Target/Thread.h" 47 #include "lldb/Target/TargetList.h" 48 49 #include "lldb/Interpreter/CommandReturnObject.h" 50 #include "lldb/Interpreter/CommandInterpreter.h" 51 52 using namespace lldb; 53 using namespace lldb_private; 54 55 CommandInterpreter::CommandInterpreter 56 ( 57 Debugger &debugger, 58 ScriptLanguage script_language, 59 bool synchronous_execution 60 ) : 61 Broadcaster ("CommandInterpreter"), 62 m_debugger (debugger), 63 m_synchronous_execution (synchronous_execution), 64 m_skip_lldbinit_files (false) 65 { 66 const char *dbg_name = debugger.GetInstanceName().AsCString(); 67 std::string lang_name = ScriptInterpreter::LanguageToString (script_language); 68 StreamString var_name; 69 var_name.Printf ("[%s].script-lang", dbg_name); 70 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(), 71 lldb::eVarSetOperationAssign, false, 72 m_debugger.GetInstanceName().AsCString()); 73 } 74 75 void 76 CommandInterpreter::Initialize () 77 { 78 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 79 80 CommandReturnObject result; 81 82 LoadCommandDictionary (); 83 84 // Set up some initial aliases. 85 result.Clear(); HandleCommand ("command alias q quit", false, result); 86 result.Clear(); HandleCommand ("command alias run process launch --", false, result); 87 result.Clear(); HandleCommand ("command alias r process launch --", false, result); 88 result.Clear(); HandleCommand ("command alias c process continue", false, result); 89 result.Clear(); HandleCommand ("command alias continue process continue", false, result); 90 result.Clear(); HandleCommand ("command alias expr expression", false, result); 91 result.Clear(); HandleCommand ("command alias exit quit", false, result); 92 result.Clear(); HandleCommand ("command alias b regexp-break", false, result); 93 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result); 94 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result); 95 result.Clear(); HandleCommand ("command alias step thread step-in", false, result); 96 result.Clear(); HandleCommand ("command alias s thread step-in", false, result); 97 result.Clear(); HandleCommand ("command alias next thread step-over", false, result); 98 result.Clear(); HandleCommand ("command alias n thread step-over", false, result); 99 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result); 100 result.Clear(); HandleCommand ("command alias x memory read", false, result); 101 result.Clear(); HandleCommand ("command alias l source list", false, result); 102 result.Clear(); HandleCommand ("command alias list source list", false, result); 103 result.Clear(); HandleCommand ("command alias p frame variable", false, result); 104 result.Clear(); HandleCommand ("command alias print frame variable", false, result); 105 result.Clear(); HandleCommand ("command alias po expression -o --", false, result); 106 } 107 108 const char * 109 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) 110 { 111 // This function has not yet been implemented. 112 113 // Look for any embedded script command 114 // If found, 115 // get interpreter object from the command dictionary, 116 // call execute_one_command on it, 117 // get the results as a string, 118 // substitute that string for current stuff. 119 120 return arg; 121 } 122 123 124 void 125 CommandInterpreter::LoadCommandDictionary () 126 { 127 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 128 129 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 130 // 131 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref) 132 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use 133 // the cross-referencing stuff) are created!!! 134 // 135 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 136 137 138 // Command objects that inherit from CommandObjectCrossref must be created before other command objects 139 // are created. This is so that when another command is created that needs to go into a crossref object, 140 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command 141 // objects into the CommandDictionary now, so they are ready for use when the other commands get created. 142 143 // Non-CommandObjectCrossref commands can now be created. 144 145 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); 146 147 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); 148 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); 149 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this)); 150 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); 151 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); 152 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); 153 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this)); 154 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); 155 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); 156 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this)); 157 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); 158 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); 159 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); 160 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); 161 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); 162 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); 163 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); 164 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); 165 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); 166 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); 167 168 std::auto_ptr<CommandObjectRegexCommand> 169 break_regex_cmd_ap(new CommandObjectRegexCommand (*this, 170 "regexp-break", 171 "Set a breakpoint using a regular expression to specify the location.", 172 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2)); 173 if (break_regex_cmd_ap.get()) 174 { 175 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") && 176 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") && 177 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") && 178 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") && 179 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") && 180 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'")) 181 { 182 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); 183 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; 184 } 185 } 186 } 187 188 int 189 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, 190 StringList &matches) 191 { 192 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); 193 194 if (include_aliases) 195 { 196 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); 197 } 198 199 return matches.GetSize(); 200 } 201 202 CommandObjectSP 203 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) 204 { 205 CommandObject::CommandMap::iterator pos; 206 CommandObjectSP ret_val; 207 208 std::string cmd(cmd_cstr); 209 210 if (HasCommands()) 211 { 212 pos = m_command_dict.find(cmd); 213 if (pos != m_command_dict.end()) 214 ret_val = pos->second; 215 } 216 217 if (include_aliases && HasAliases()) 218 { 219 pos = m_alias_dict.find(cmd); 220 if (pos != m_alias_dict.end()) 221 ret_val = pos->second; 222 } 223 224 if (HasUserCommands()) 225 { 226 pos = m_user_dict.find(cmd); 227 if (pos != m_user_dict.end()) 228 ret_val = pos->second; 229 } 230 231 if (!exact && ret_val == NULL) 232 { 233 // We will only get into here if we didn't find any exact matches. 234 235 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 236 237 StringList local_matches; 238 if (matches == NULL) 239 matches = &local_matches; 240 241 unsigned int num_cmd_matches = 0; 242 unsigned int num_alias_matches = 0; 243 unsigned int num_user_matches = 0; 244 245 // Look through the command dictionaries one by one, and if we get only one match from any of 246 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. 247 248 if (HasCommands()) 249 { 250 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); 251 } 252 253 if (num_cmd_matches == 1) 254 { 255 cmd.assign(matches->GetStringAtIndex(0)); 256 pos = m_command_dict.find(cmd); 257 if (pos != m_command_dict.end()) 258 real_match_sp = pos->second; 259 } 260 261 if (include_aliases && HasAliases()) 262 { 263 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); 264 265 } 266 267 if (num_alias_matches == 1) 268 { 269 cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); 270 pos = m_alias_dict.find(cmd); 271 if (pos != m_alias_dict.end()) 272 alias_match_sp = pos->second; 273 } 274 275 if (HasUserCommands()) 276 { 277 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); 278 } 279 280 if (num_user_matches == 1) 281 { 282 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); 283 284 pos = m_user_dict.find (cmd); 285 if (pos != m_user_dict.end()) 286 user_match_sp = pos->second; 287 } 288 289 // If we got exactly one match, return that, otherwise return the match list. 290 291 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) 292 { 293 if (num_cmd_matches) 294 return real_match_sp; 295 else if (num_alias_matches) 296 return alias_match_sp; 297 else 298 return user_match_sp; 299 } 300 } 301 else if (matches && ret_val != NULL) 302 { 303 matches->AppendString (cmd_cstr); 304 } 305 306 307 return ret_val; 308 } 309 310 CommandObjectSP 311 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) 312 { 313 return GetCommandSP(cmd_cstr, include_aliases, true, NULL); 314 } 315 316 CommandObject * 317 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) 318 { 319 return GetCommandSPExact (cmd_cstr, include_aliases).get(); 320 } 321 322 CommandObject * 323 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) 324 { 325 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); 326 327 // If we didn't find an exact match to the command string in the commands, look in 328 // the aliases. 329 330 if (command_obj == NULL) 331 { 332 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); 333 } 334 335 // Finally, if there wasn't an exact match among the aliases, look for an inexact match 336 // in both the commands and the aliases. 337 338 if (command_obj == NULL) 339 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get(); 340 341 return command_obj; 342 } 343 344 bool 345 CommandInterpreter::CommandExists (const char *cmd) 346 { 347 return m_command_dict.find(cmd) != m_command_dict.end(); 348 } 349 350 bool 351 CommandInterpreter::AliasExists (const char *cmd) 352 { 353 return m_alias_dict.find(cmd) != m_alias_dict.end(); 354 } 355 356 bool 357 CommandInterpreter::UserCommandExists (const char *cmd) 358 { 359 return m_user_dict.find(cmd) != m_user_dict.end(); 360 } 361 362 void 363 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) 364 { 365 command_obj_sp->SetIsAlias (true); 366 m_alias_dict[alias_name] = command_obj_sp; 367 } 368 369 bool 370 CommandInterpreter::RemoveAlias (const char *alias_name) 371 { 372 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); 373 if (pos != m_alias_dict.end()) 374 { 375 m_alias_dict.erase(pos); 376 return true; 377 } 378 return false; 379 } 380 bool 381 CommandInterpreter::RemoveUser (const char *alias_name) 382 { 383 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); 384 if (pos != m_user_dict.end()) 385 { 386 m_user_dict.erase(pos); 387 return true; 388 } 389 return false; 390 } 391 392 void 393 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) 394 { 395 help_string.Printf ("'%s", command_name); 396 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 397 398 if (option_arg_vector_sp != NULL) 399 { 400 OptionArgVector *options = option_arg_vector_sp.get(); 401 for (int i = 0; i < options->size(); ++i) 402 { 403 OptionArgPair cur_option = (*options)[i]; 404 std::string opt = cur_option.first; 405 std::string value = cur_option.second; 406 if (opt.compare("<argument>") == 0) 407 { 408 help_string.Printf (" %s", value.c_str()); 409 } 410 else 411 { 412 help_string.Printf (" %s", opt.c_str()); 413 if ((value.compare ("<no-argument>") != 0) 414 && (value.compare ("<need-argument") != 0)) 415 { 416 help_string.Printf (" %s", value.c_str()); 417 } 418 } 419 } 420 } 421 422 help_string.Printf ("'"); 423 } 424 425 size_t 426 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) 427 { 428 CommandObject::CommandMap::const_iterator pos; 429 CommandObject::CommandMap::const_iterator end = dict.end(); 430 size_t max_len = 0; 431 432 for (pos = dict.begin(); pos != end; ++pos) 433 { 434 size_t len = pos->first.size(); 435 if (max_len < len) 436 max_len = len; 437 } 438 return max_len; 439 } 440 441 void 442 CommandInterpreter::GetHelp (CommandReturnObject &result) 443 { 444 CommandObject::CommandMap::const_iterator pos; 445 result.AppendMessage("The following is a list of built-in, permanent debugger commands:"); 446 result.AppendMessage(""); 447 uint32_t max_len = FindLongestCommandWord (m_command_dict); 448 449 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 450 { 451 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 452 max_len); 453 } 454 result.AppendMessage(""); 455 456 if (m_alias_dict.size() > 0) 457 { 458 result.AppendMessage("The following is a list of your current command abbreviations " 459 "(see 'help commands alias' for more info):"); 460 result.AppendMessage(""); 461 max_len = FindLongestCommandWord (m_alias_dict); 462 463 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) 464 { 465 StreamString sstr; 466 StreamString translation_and_help; 467 std::string entry_name = pos->first; 468 std::string second_entry = pos->second.get()->GetCommandName(); 469 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); 470 471 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); 472 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", 473 translation_and_help.GetData(), max_len); 474 } 475 result.AppendMessage(""); 476 } 477 478 if (m_user_dict.size() > 0) 479 { 480 result.AppendMessage ("The following is a list of your current user-defined commands:"); 481 result.AppendMessage(""); 482 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 483 { 484 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp()); 485 } 486 result.AppendMessage(""); 487 } 488 489 result.AppendMessage("For more information on any particular command, try 'help <command-name>'."); 490 } 491 492 bool 493 CommandInterpreter::HandleCommand 494 ( 495 const char *command_line, 496 bool add_to_history, 497 CommandReturnObject &result, 498 ExecutionContext *override_context 499 ) 500 { 501 // FIXME: there should probably be a mutex to make sure only one thread can 502 // run the interpreter at a time. 503 504 // TODO: this should be a logging channel in lldb. 505 // if (DebugSelf()) 506 // { 507 // result.AppendMessageWithFormat ("Processing command: %s\n", command_line); 508 // } 509 510 m_debugger.UpdateExecutionContext (override_context); 511 512 if (command_line == NULL || command_line[0] == '\0') 513 { 514 if (m_command_history.empty()) 515 { 516 result.AppendError ("empty command"); 517 result.SetStatus(eReturnStatusFailed); 518 return false; 519 } 520 else 521 { 522 command_line = m_repeat_command.c_str(); 523 if (m_repeat_command.empty()) 524 { 525 result.AppendErrorWithFormat("No auto repeat.\n"); 526 result.SetStatus (eReturnStatusFailed); 527 return false; 528 } 529 } 530 add_to_history = false; 531 } 532 533 Args command_args(command_line); 534 535 if (command_args.GetArgumentCount() > 0) 536 { 537 const char *command_cstr = command_args.GetArgumentAtIndex(0); 538 if (command_cstr) 539 { 540 541 // We're looking up the command object here. So first find an exact match to the 542 // command in the commands. 543 CommandObject *command_obj = GetCommandObject(command_cstr); 544 545 if (command_obj != NULL) 546 { 547 std::string aliased_cmd_str; 548 if (command_obj->IsAlias()) 549 { 550 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result); 551 if (!result.Succeeded()) 552 return false; 553 else 554 { 555 // We need to transfer the newly constructed args back into the command_line, in case 556 // this happens to be an alias for a command that takes raw input. 557 if (command_args.GetCommandString (aliased_cmd_str)) 558 { 559 command_line = aliased_cmd_str.c_str(); 560 command_cstr = command_args.GetArgumentAtIndex (0); 561 } 562 } 563 } 564 565 if (add_to_history) 566 { 567 const char *repeat_command = command_obj->GetRepeatCommand(command_args, 0); 568 if (repeat_command != NULL) 569 m_repeat_command.assign(repeat_command); 570 else 571 m_repeat_command.assign(command_line); 572 573 m_command_history.push_back (command_line); 574 } 575 576 577 if (command_obj->WantsRawCommandString()) 578 { 579 const char *stripped_command = ::strstr (command_line, command_cstr); 580 if (stripped_command) 581 { 582 stripped_command += strlen(command_cstr); 583 while (isspace(*stripped_command)) 584 ++stripped_command; 585 command_obj->ExecuteRawCommandString (stripped_command, result); 586 } 587 } 588 else 589 { 590 // Remove the command from the args. 591 command_args.Shift(); 592 command_obj->ExecuteWithOptions (command_args, result); 593 } 594 } 595 else 596 { 597 // We didn't find the first command object, so complete the first argument. 598 StringList matches; 599 int num_matches; 600 int cursor_index = 0; 601 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 602 bool word_complete; 603 num_matches = HandleCompletionMatches (command_args, 604 cursor_index, 605 cursor_char_position, 606 0, 607 -1, 608 word_complete, 609 matches); 610 611 if (num_matches > 0) 612 { 613 std::string error_msg; 614 error_msg.assign ("ambiguous command '"); 615 error_msg.append(command_cstr); 616 error_msg.append ("'."); 617 618 error_msg.append (" Possible completions:"); 619 for (int i = 0; i < num_matches; i++) 620 { 621 error_msg.append ("\n\t"); 622 error_msg.append (matches.GetStringAtIndex (i)); 623 } 624 error_msg.append ("\n"); 625 result.AppendRawError (error_msg.c_str(), error_msg.size()); 626 } 627 else 628 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr); 629 630 result.SetStatus (eReturnStatusFailed); 631 } 632 } 633 } 634 return result.Succeeded(); 635 } 636 637 int 638 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 639 int &cursor_index, 640 int &cursor_char_position, 641 int match_start_point, 642 int max_return_elements, 643 bool &word_complete, 644 StringList &matches) 645 { 646 int num_command_matches = 0; 647 bool look_for_subcommand = false; 648 649 // For any of the command completions a unique match will be a complete word. 650 word_complete = true; 651 652 if (cursor_index == -1) 653 { 654 // We got nothing on the command line, so return the list of commands 655 bool include_aliases = true; 656 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 657 } 658 else if (cursor_index == 0) 659 { 660 // The cursor is in the first argument, so just do a lookup in the dictionary. 661 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 662 num_command_matches = matches.GetSize(); 663 664 if (num_command_matches == 1 665 && cmd_obj && cmd_obj->IsMultiwordObject() 666 && matches.GetStringAtIndex(0) != NULL 667 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 668 { 669 look_for_subcommand = true; 670 num_command_matches = 0; 671 matches.DeleteStringAtIndex(0); 672 parsed_line.AppendArgument (""); 673 cursor_index++; 674 cursor_char_position = 0; 675 } 676 } 677 678 if (cursor_index > 0 || look_for_subcommand) 679 { 680 // We are completing further on into a commands arguments, so find the command and tell it 681 // to complete the command. 682 // First see if there is a matching initial command: 683 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 684 if (command_object == NULL) 685 { 686 return 0; 687 } 688 else 689 { 690 parsed_line.Shift(); 691 cursor_index--; 692 num_command_matches = command_object->HandleCompletion (parsed_line, 693 cursor_index, 694 cursor_char_position, 695 match_start_point, 696 max_return_elements, 697 word_complete, 698 matches); 699 } 700 } 701 702 return num_command_matches; 703 704 } 705 706 int 707 CommandInterpreter::HandleCompletion (const char *current_line, 708 const char *cursor, 709 const char *last_char, 710 int match_start_point, 711 int max_return_elements, 712 StringList &matches) 713 { 714 // We parse the argument up to the cursor, so the last argument in parsed_line is 715 // the one containing the cursor, and the cursor is after the last character. 716 717 Args parsed_line(current_line, last_char - current_line); 718 Args partial_parsed_line(current_line, cursor - current_line); 719 720 int num_args = partial_parsed_line.GetArgumentCount(); 721 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 722 int cursor_char_position; 723 724 if (cursor_index == -1) 725 cursor_char_position = 0; 726 else 727 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 728 729 int num_command_matches; 730 731 matches.Clear(); 732 733 // Only max_return_elements == -1 is supported at present: 734 assert (max_return_elements == -1); 735 bool word_complete; 736 num_command_matches = HandleCompletionMatches (parsed_line, 737 cursor_index, 738 cursor_char_position, 739 match_start_point, 740 max_return_elements, 741 word_complete, 742 matches); 743 744 if (num_command_matches <= 0) 745 return num_command_matches; 746 747 if (num_args == 0) 748 { 749 // If we got an empty string, insert nothing. 750 matches.InsertStringAtIndex(0, ""); 751 } 752 else 753 { 754 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 755 // put an empty string in element 0. 756 std::string command_partial_str; 757 if (cursor_index >= 0) 758 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 759 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 760 761 std::string common_prefix; 762 matches.LongestCommonPrefix (common_prefix); 763 int partial_name_len = command_partial_str.size(); 764 765 // If we matched a unique single command, add a space... 766 // Only do this if the completer told us this was a complete word, however... 767 if (num_command_matches == 1 && word_complete) 768 { 769 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 770 if (quote_char != '\0') 771 common_prefix.push_back(quote_char); 772 773 common_prefix.push_back(' '); 774 } 775 common_prefix.erase (0, partial_name_len); 776 matches.InsertStringAtIndex(0, common_prefix.c_str()); 777 } 778 return num_command_matches; 779 } 780 781 782 CommandInterpreter::~CommandInterpreter () 783 { 784 } 785 786 const char * 787 CommandInterpreter::GetPrompt () 788 { 789 return m_debugger.GetPrompt(); 790 } 791 792 void 793 CommandInterpreter::SetPrompt (const char *new_prompt) 794 { 795 m_debugger.SetPrompt (new_prompt); 796 } 797 798 size_t 799 CommandInterpreter::GetConfirmationInputReaderCallback (void *baton, 800 InputReader &reader, 801 lldb::InputReaderAction action, 802 const char *bytes, 803 size_t bytes_len) 804 { 805 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle(); 806 bool *response_ptr = (bool *) baton; 807 808 switch (action) 809 { 810 case eInputReaderActivate: 811 if (out_fh) 812 { 813 if (reader.GetPrompt()) 814 ::fprintf (out_fh, "%s", reader.GetPrompt()); 815 } 816 break; 817 818 case eInputReaderDeactivate: 819 break; 820 821 case eInputReaderReactivate: 822 if (out_fh && reader.GetPrompt()) 823 ::fprintf (out_fh, "%s", reader.GetPrompt()); 824 break; 825 826 case eInputReaderGotToken: 827 if (bytes_len == 0) 828 { 829 reader.SetIsDone(true); 830 } 831 else if (bytes[0] == 'y') 832 { 833 *response_ptr = true; 834 reader.SetIsDone(true); 835 } 836 else if (bytes[0] == 'n') 837 { 838 *response_ptr = false; 839 reader.SetIsDone(true); 840 } 841 else 842 { 843 if (out_fh && !reader.IsDone() && reader.GetPrompt()) 844 { 845 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n"); 846 ::fprintf (out_fh, "%s", reader.GetPrompt()); 847 } 848 } 849 break; 850 851 case eInputReaderDone: 852 break; 853 } 854 855 return bytes_len; 856 857 } 858 859 bool 860 CommandInterpreter::Confirm (const char *message, bool default_answer) 861 { 862 // Check AutoConfirm first: 863 if (m_debugger.GetAutoConfirm()) 864 return default_answer; 865 866 InputReaderSP reader_sp (new InputReader(GetDebugger())); 867 bool response = default_answer; 868 if (reader_sp) 869 { 870 std::string prompt(message); 871 prompt.append(": ["); 872 if (default_answer) 873 prompt.append ("Y/n] "); 874 else 875 prompt.append ("y/N] "); 876 877 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback, 878 &response, // baton 879 eInputReaderGranularityLine, // token size, to pass to callback function 880 NULL, // end token 881 prompt.c_str(), // prompt 882 true)); // echo input 883 if (err.Success()) 884 { 885 GetDebugger().PushInputReader (reader_sp); 886 } 887 reader_sp->WaitOnReaderIsDone(); 888 } 889 return response; 890 } 891 892 893 void 894 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type) 895 { 896 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true); 897 898 if (cmd_obj_sp != NULL) 899 { 900 CommandObject *cmd_obj = cmd_obj_sp.get(); 901 if (cmd_obj->IsCrossRefObject ()) 902 cmd_obj->AddObject (object_type); 903 } 904 } 905 906 OptionArgVectorSP 907 CommandInterpreter::GetAliasOptions (const char *alias_name) 908 { 909 OptionArgMap::iterator pos; 910 OptionArgVectorSP ret_val; 911 912 std::string alias (alias_name); 913 914 if (HasAliasOptions()) 915 { 916 pos = m_alias_options.find (alias); 917 if (pos != m_alias_options.end()) 918 ret_val = pos->second; 919 } 920 921 return ret_val; 922 } 923 924 void 925 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 926 { 927 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 928 if (pos != m_alias_options.end()) 929 { 930 m_alias_options.erase (pos); 931 } 932 } 933 934 void 935 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 936 { 937 m_alias_options[alias_name] = option_arg_vector_sp; 938 } 939 940 bool 941 CommandInterpreter::HasCommands () 942 { 943 return (!m_command_dict.empty()); 944 } 945 946 bool 947 CommandInterpreter::HasAliases () 948 { 949 return (!m_alias_dict.empty()); 950 } 951 952 bool 953 CommandInterpreter::HasUserCommands () 954 { 955 return (!m_user_dict.empty()); 956 } 957 958 bool 959 CommandInterpreter::HasAliasOptions () 960 { 961 return (!m_alias_options.empty()); 962 } 963 964 void 965 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 966 const char *alias_name, 967 Args &cmd_args, 968 CommandReturnObject &result) 969 { 970 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 971 972 if (option_arg_vector_sp.get()) 973 { 974 // Make sure that the alias name is the 0th element in cmd_args 975 std::string alias_name_str = alias_name; 976 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 977 cmd_args.Unshift (alias_name); 978 979 Args new_args (alias_cmd_obj->GetCommandName()); 980 if (new_args.GetArgumentCount() == 2) 981 new_args.Shift(); 982 983 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 984 int old_size = cmd_args.GetArgumentCount(); 985 std::vector<bool> used (old_size + 1, false); 986 987 used[0] = true; 988 989 for (int i = 0; i < option_arg_vector->size(); ++i) 990 { 991 OptionArgPair option_pair = (*option_arg_vector)[i]; 992 std::string option = option_pair.first; 993 std::string value = option_pair.second; 994 if (option.compare ("<argument>") == 0) 995 new_args.AppendArgument (value.c_str()); 996 else 997 { 998 new_args.AppendArgument (option.c_str()); 999 if (value.compare ("<no-argument>") != 0) 1000 { 1001 int index = GetOptionArgumentPosition (value.c_str()); 1002 if (index == 0) 1003 // value was NOT a positional argument; must be a real value 1004 new_args.AppendArgument (value.c_str()); 1005 else if (index >= cmd_args.GetArgumentCount()) 1006 { 1007 result.AppendErrorWithFormat 1008 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 1009 index); 1010 result.SetStatus (eReturnStatusFailed); 1011 return; 1012 } 1013 else 1014 { 1015 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 1016 used[index] = true; 1017 } 1018 } 1019 } 1020 } 1021 1022 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j) 1023 { 1024 if (!used[j]) 1025 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 1026 } 1027 1028 cmd_args.Clear(); 1029 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 1030 } 1031 else 1032 { 1033 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1034 // This alias was not created with any options; nothing further needs to be done. 1035 return; 1036 } 1037 1038 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1039 return; 1040 } 1041 1042 1043 int 1044 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 1045 { 1046 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 1047 // of zero. 1048 1049 char *cptr = (char *) in_string; 1050 1051 // Does it start with '%' 1052 if (cptr[0] == '%') 1053 { 1054 ++cptr; 1055 1056 // Is the rest of it entirely digits? 1057 if (isdigit (cptr[0])) 1058 { 1059 const char *start = cptr; 1060 while (isdigit (cptr[0])) 1061 ++cptr; 1062 1063 // We've gotten to the end of the digits; are we at the end of the string? 1064 if (cptr[0] == '\0') 1065 position = atoi (start); 1066 } 1067 } 1068 1069 return position; 1070 } 1071 1072 void 1073 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 1074 { 1075 // Don't parse any .lldbinit files if we were asked not to 1076 if (m_skip_lldbinit_files) 1077 return; 1078 1079 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit"; 1080 FileSpec init_file (init_file_path, true); 1081 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 1082 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 1083 1084 if (init_file.Exists()) 1085 { 1086 char path[PATH_MAX]; 1087 init_file.GetPath(path, sizeof(path)); 1088 StreamString source_command; 1089 source_command.Printf ("command source '%s'", path); 1090 HandleCommand (source_command.GetData(), false, result); 1091 } 1092 else 1093 { 1094 // nothing to be done if the file doesn't exist 1095 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1096 } 1097 } 1098 1099 ScriptInterpreter * 1100 CommandInterpreter::GetScriptInterpreter () 1101 { 1102 CommandObject::CommandMap::iterator pos; 1103 1104 pos = m_command_dict.find ("script"); 1105 if (pos != m_command_dict.end()) 1106 { 1107 CommandObject *script_cmd_obj = pos->second.get(); 1108 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (); 1109 } 1110 return NULL; 1111 } 1112 1113 1114 1115 bool 1116 CommandInterpreter::GetSynchronous () 1117 { 1118 return m_synchronous_execution; 1119 } 1120 1121 void 1122 CommandInterpreter::SetSynchronous (bool value) 1123 { 1124 m_synchronous_execution = value; 1125 } 1126 1127 void 1128 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 1129 const char *word_text, 1130 const char *separator, 1131 const char *help_text, 1132 uint32_t max_word_len) 1133 { 1134 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 1135 1136 int indent_size = max_word_len + strlen (separator) + 2; 1137 1138 strm.IndentMore (indent_size); 1139 1140 int len = indent_size + strlen (help_text) + 1; 1141 char *text = (char *) malloc (len); 1142 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text); 1143 if (text[len - 1] == '\n') 1144 text[--len] = '\0'; 1145 1146 if (len < max_columns) 1147 { 1148 // Output it as a single line. 1149 strm.Printf ("%s", text); 1150 } 1151 else 1152 { 1153 // We need to break it up into multiple lines. 1154 bool first_line = true; 1155 int text_width; 1156 int start = 0; 1157 int end = start; 1158 int final_end = strlen (text); 1159 int sub_len; 1160 1161 while (end < final_end) 1162 { 1163 if (first_line) 1164 text_width = max_columns - 1; 1165 else 1166 text_width = max_columns - indent_size - 1; 1167 1168 // Don't start the 'text' on a space, since we're already outputting the indentation. 1169 if (!first_line) 1170 { 1171 while ((start < final_end) && (text[start] == ' ')) 1172 start++; 1173 } 1174 1175 end = start + text_width; 1176 if (end > final_end) 1177 end = final_end; 1178 else 1179 { 1180 // If we're not at the end of the text, make sure we break the line on white space. 1181 while (end > start 1182 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 1183 end--; 1184 } 1185 1186 sub_len = end - start; 1187 if (start != 0) 1188 strm.EOL(); 1189 if (!first_line) 1190 strm.Indent(); 1191 else 1192 first_line = false; 1193 assert (start <= final_end); 1194 assert (start + sub_len <= final_end); 1195 if (sub_len > 0) 1196 strm.Write (text + start, sub_len); 1197 start = end + 1; 1198 } 1199 } 1200 strm.EOL(); 1201 strm.IndentLess(indent_size); 1202 free (text); 1203 } 1204 1205 void 1206 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word, 1207 StringList &commands_found, StringList &commands_help) 1208 { 1209 CommandObject::CommandMap::const_iterator pos; 1210 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict; 1211 CommandObject *sub_cmd_obj; 1212 1213 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos) 1214 { 1215 const char * command_name = pos->first.c_str(); 1216 sub_cmd_obj = pos->second.get(); 1217 StreamString complete_command_name; 1218 1219 complete_command_name.Printf ("%s %s", prefix, command_name); 1220 1221 if (sub_cmd_obj->HelpTextContainsWord (search_word)) 1222 { 1223 commands_found.AppendString (complete_command_name.GetData()); 1224 commands_help.AppendString (sub_cmd_obj->GetHelp()); 1225 } 1226 1227 if (sub_cmd_obj->IsMultiwordObject()) 1228 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found, 1229 commands_help); 1230 } 1231 1232 } 1233 1234 void 1235 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 1236 StringList &commands_help) 1237 { 1238 CommandObject::CommandMap::const_iterator pos; 1239 1240 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 1241 { 1242 const char *command_name = pos->first.c_str(); 1243 CommandObject *cmd_obj = pos->second.get(); 1244 1245 if (cmd_obj->HelpTextContainsWord (search_word)) 1246 { 1247 commands_found.AppendString (command_name); 1248 commands_help.AppendString (cmd_obj->GetHelp()); 1249 } 1250 1251 if (cmd_obj->IsMultiwordObject()) 1252 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help); 1253 1254 } 1255 } 1256