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 #include "../Commands/CommandObjectVersion.h" 40 41 #include "lldb/Interpreter/Args.h" 42 #include "lldb/Core/Debugger.h" 43 #include "lldb/Core/InputReader.h" 44 #include "lldb/Core/Stream.h" 45 #include "lldb/Core/Timer.h" 46 #include "lldb/Target/Process.h" 47 #include "lldb/Target/Thread.h" 48 #include "lldb/Target/TargetList.h" 49 #include "lldb/Utility/CleanUp.h" 50 51 #include "lldb/Interpreter/CommandReturnObject.h" 52 #include "lldb/Interpreter/CommandInterpreter.h" 53 54 using namespace lldb; 55 using namespace lldb_private; 56 57 CommandInterpreter::CommandInterpreter 58 ( 59 Debugger &debugger, 60 ScriptLanguage script_language, 61 bool synchronous_execution 62 ) : 63 Broadcaster ("lldb.command-interpreter"), 64 m_debugger (debugger), 65 m_synchronous_execution (synchronous_execution), 66 m_skip_lldbinit_files (false) 67 { 68 const char *dbg_name = debugger.GetInstanceName().AsCString(); 69 std::string lang_name = ScriptInterpreter::LanguageToString (script_language); 70 StreamString var_name; 71 var_name.Printf ("[%s].script-lang", dbg_name); 72 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(), 73 lldb::eVarSetOperationAssign, false, 74 m_debugger.GetInstanceName().AsCString()); 75 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit"); 76 SetEventName (eBroadcastBitResetPrompt, "reset-prompt"); 77 SetEventName (eBroadcastBitQuitCommandReceived, "quit"); 78 } 79 80 void 81 CommandInterpreter::Initialize () 82 { 83 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 84 85 CommandReturnObject result; 86 87 LoadCommandDictionary (); 88 89 // Set up some initial aliases. 90 result.Clear(); HandleCommand ("command alias q quit", false, result); 91 result.Clear(); HandleCommand ("command alias run process launch --", false, result); 92 result.Clear(); HandleCommand ("command alias r process launch --", false, result); 93 result.Clear(); HandleCommand ("command alias c process continue", false, result); 94 result.Clear(); HandleCommand ("command alias continue process continue", false, result); 95 result.Clear(); HandleCommand ("command alias expr expression", false, result); 96 result.Clear(); HandleCommand ("command alias exit quit", false, result); 97 result.Clear(); HandleCommand ("command alias b regexp-break", false, result); 98 result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result); 99 result.Clear(); HandleCommand ("command alias si thread step-inst", false, result); 100 result.Clear(); HandleCommand ("command alias step thread step-in", false, result); 101 result.Clear(); HandleCommand ("command alias s thread step-in", false, result); 102 result.Clear(); HandleCommand ("command alias next thread step-over", false, result); 103 result.Clear(); HandleCommand ("command alias n thread step-over", false, result); 104 result.Clear(); HandleCommand ("command alias finish thread step-out", false, result); 105 result.Clear(); HandleCommand ("command alias x memory read", false, result); 106 result.Clear(); HandleCommand ("command alias l source list", false, result); 107 result.Clear(); HandleCommand ("command alias list source list", false, result); 108 result.Clear(); HandleCommand ("command alias p frame variable", false, result); 109 result.Clear(); HandleCommand ("command alias print frame variable", false, result); 110 result.Clear(); HandleCommand ("command alias po expression -o --", false, result); 111 } 112 113 const char * 114 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) 115 { 116 // This function has not yet been implemented. 117 118 // Look for any embedded script command 119 // If found, 120 // get interpreter object from the command dictionary, 121 // call execute_one_command on it, 122 // get the results as a string, 123 // substitute that string for current stuff. 124 125 return arg; 126 } 127 128 129 void 130 CommandInterpreter::LoadCommandDictionary () 131 { 132 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 133 134 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 135 // 136 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref) 137 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use 138 // the cross-referencing stuff) are created!!! 139 // 140 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 141 142 143 // Command objects that inherit from CommandObjectCrossref must be created before other command objects 144 // are created. This is so that when another command is created that needs to go into a crossref object, 145 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command 146 // objects into the CommandDictionary now, so they are ready for use when the other commands get created. 147 148 // Non-CommandObjectCrossref commands can now be created. 149 150 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); 151 152 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); 153 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); 154 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this)); 155 m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); 156 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); 157 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); 158 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this)); 159 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); 160 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); 161 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this)); 162 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); 163 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); 164 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); 165 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); 166 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); 167 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); 168 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); 169 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); 170 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); 171 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); 172 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this)); 173 174 std::auto_ptr<CommandObjectRegexCommand> 175 break_regex_cmd_ap(new CommandObjectRegexCommand (*this, 176 "regexp-break", 177 "Set a breakpoint using a regular expression to specify the location.", 178 "regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2)); 179 if (break_regex_cmd_ap.get()) 180 { 181 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") && 182 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") && 183 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") && 184 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") && 185 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") && 186 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'")) 187 { 188 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); 189 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; 190 } 191 } 192 } 193 194 int 195 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, 196 StringList &matches) 197 { 198 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); 199 200 if (include_aliases) 201 { 202 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); 203 } 204 205 return matches.GetSize(); 206 } 207 208 CommandObjectSP 209 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) 210 { 211 CommandObject::CommandMap::iterator pos; 212 CommandObjectSP ret_val; 213 214 std::string cmd(cmd_cstr); 215 216 if (HasCommands()) 217 { 218 pos = m_command_dict.find(cmd); 219 if (pos != m_command_dict.end()) 220 ret_val = pos->second; 221 } 222 223 if (include_aliases && HasAliases()) 224 { 225 pos = m_alias_dict.find(cmd); 226 if (pos != m_alias_dict.end()) 227 ret_val = pos->second; 228 } 229 230 if (HasUserCommands()) 231 { 232 pos = m_user_dict.find(cmd); 233 if (pos != m_user_dict.end()) 234 ret_val = pos->second; 235 } 236 237 if (!exact && ret_val == NULL) 238 { 239 // We will only get into here if we didn't find any exact matches. 240 241 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 242 243 StringList local_matches; 244 if (matches == NULL) 245 matches = &local_matches; 246 247 unsigned int num_cmd_matches = 0; 248 unsigned int num_alias_matches = 0; 249 unsigned int num_user_matches = 0; 250 251 // Look through the command dictionaries one by one, and if we get only one match from any of 252 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. 253 254 if (HasCommands()) 255 { 256 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); 257 } 258 259 if (num_cmd_matches == 1) 260 { 261 cmd.assign(matches->GetStringAtIndex(0)); 262 pos = m_command_dict.find(cmd); 263 if (pos != m_command_dict.end()) 264 real_match_sp = pos->second; 265 } 266 267 if (include_aliases && HasAliases()) 268 { 269 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); 270 271 } 272 273 if (num_alias_matches == 1) 274 { 275 cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); 276 pos = m_alias_dict.find(cmd); 277 if (pos != m_alias_dict.end()) 278 alias_match_sp = pos->second; 279 } 280 281 if (HasUserCommands()) 282 { 283 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); 284 } 285 286 if (num_user_matches == 1) 287 { 288 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); 289 290 pos = m_user_dict.find (cmd); 291 if (pos != m_user_dict.end()) 292 user_match_sp = pos->second; 293 } 294 295 // If we got exactly one match, return that, otherwise return the match list. 296 297 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) 298 { 299 if (num_cmd_matches) 300 return real_match_sp; 301 else if (num_alias_matches) 302 return alias_match_sp; 303 else 304 return user_match_sp; 305 } 306 } 307 else if (matches && ret_val != NULL) 308 { 309 matches->AppendString (cmd_cstr); 310 } 311 312 313 return ret_val; 314 } 315 316 CommandObjectSP 317 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) 318 { 319 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command. 320 CommandObjectSP ret_val; // Possibly empty return value. 321 322 if (cmd_cstr == NULL) 323 return ret_val; 324 325 if (cmd_words.GetArgumentCount() == 1) 326 return GetCommandSP(cmd_cstr, include_aliases, true, NULL); 327 else 328 { 329 // We have a multi-word command (seemingly), so we need to do more work. 330 // First, get the cmd_obj_sp for the first word in the command. 331 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL); 332 if (cmd_obj_sp.get() != NULL) 333 { 334 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a 335 // command name), and find the appropriate sub-command SP for each command word.... 336 size_t end = cmd_words.GetArgumentCount(); 337 for (size_t j= 1; j < end; ++j) 338 { 339 if (cmd_obj_sp->IsMultiwordObject()) 340 { 341 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP 342 (cmd_words.GetArgumentAtIndex (j)); 343 if (cmd_obj_sp.get() == NULL) 344 // The sub-command name was invalid. Fail and return the empty 'ret_val'. 345 return ret_val; 346 } 347 else 348 // We have more words in the command name, but we don't have a multiword object. Fail and return 349 // empty 'ret_val'. 350 return ret_val; 351 } 352 // We successfully looped through all the command words and got valid command objects for them. Assign the 353 // last object retrieved to 'ret_val'. 354 ret_val = cmd_obj_sp; 355 } 356 } 357 return ret_val; 358 } 359 360 CommandObject * 361 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) 362 { 363 return GetCommandSPExact (cmd_cstr, include_aliases).get(); 364 } 365 366 CommandObject * 367 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) 368 { 369 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); 370 371 // If we didn't find an exact match to the command string in the commands, look in 372 // the aliases. 373 374 if (command_obj == NULL) 375 { 376 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); 377 } 378 379 // Finally, if there wasn't an exact match among the aliases, look for an inexact match 380 // in both the commands and the aliases. 381 382 if (command_obj == NULL) 383 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get(); 384 385 return command_obj; 386 } 387 388 bool 389 CommandInterpreter::CommandExists (const char *cmd) 390 { 391 return m_command_dict.find(cmd) != m_command_dict.end(); 392 } 393 394 bool 395 CommandInterpreter::AliasExists (const char *cmd) 396 { 397 return m_alias_dict.find(cmd) != m_alias_dict.end(); 398 } 399 400 bool 401 CommandInterpreter::UserCommandExists (const char *cmd) 402 { 403 return m_user_dict.find(cmd) != m_user_dict.end(); 404 } 405 406 void 407 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) 408 { 409 command_obj_sp->SetIsAlias (true); 410 m_alias_dict[alias_name] = command_obj_sp; 411 } 412 413 bool 414 CommandInterpreter::RemoveAlias (const char *alias_name) 415 { 416 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); 417 if (pos != m_alias_dict.end()) 418 { 419 m_alias_dict.erase(pos); 420 return true; 421 } 422 return false; 423 } 424 bool 425 CommandInterpreter::RemoveUser (const char *alias_name) 426 { 427 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); 428 if (pos != m_user_dict.end()) 429 { 430 m_user_dict.erase(pos); 431 return true; 432 } 433 return false; 434 } 435 436 void 437 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) 438 { 439 help_string.Printf ("'%s", command_name); 440 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 441 442 if (option_arg_vector_sp != NULL) 443 { 444 OptionArgVector *options = option_arg_vector_sp.get(); 445 for (int i = 0; i < options->size(); ++i) 446 { 447 OptionArgPair cur_option = (*options)[i]; 448 std::string opt = cur_option.first; 449 OptionArgValue value_pair = cur_option.second; 450 std::string value = value_pair.second; 451 if (opt.compare("<argument>") == 0) 452 { 453 help_string.Printf (" %s", value.c_str()); 454 } 455 else 456 { 457 help_string.Printf (" %s", opt.c_str()); 458 if ((value.compare ("<no-argument>") != 0) 459 && (value.compare ("<need-argument") != 0)) 460 { 461 help_string.Printf (" %s", value.c_str()); 462 } 463 } 464 } 465 } 466 467 help_string.Printf ("'"); 468 } 469 470 size_t 471 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) 472 { 473 CommandObject::CommandMap::const_iterator pos; 474 CommandObject::CommandMap::const_iterator end = dict.end(); 475 size_t max_len = 0; 476 477 for (pos = dict.begin(); pos != end; ++pos) 478 { 479 size_t len = pos->first.size(); 480 if (max_len < len) 481 max_len = len; 482 } 483 return max_len; 484 } 485 486 void 487 CommandInterpreter::GetHelp (CommandReturnObject &result) 488 { 489 CommandObject::CommandMap::const_iterator pos; 490 result.AppendMessage("The following is a list of built-in, permanent debugger commands:"); 491 result.AppendMessage(""); 492 uint32_t max_len = FindLongestCommandWord (m_command_dict); 493 494 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 495 { 496 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 497 max_len); 498 } 499 result.AppendMessage(""); 500 501 if (m_alias_dict.size() > 0) 502 { 503 result.AppendMessage("The following is a list of your current command abbreviations " 504 "(see 'help commands alias' for more info):"); 505 result.AppendMessage(""); 506 max_len = FindLongestCommandWord (m_alias_dict); 507 508 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) 509 { 510 StreamString sstr; 511 StreamString translation_and_help; 512 std::string entry_name = pos->first; 513 std::string second_entry = pos->second.get()->GetCommandName(); 514 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); 515 516 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); 517 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", 518 translation_and_help.GetData(), max_len); 519 } 520 result.AppendMessage(""); 521 } 522 523 if (m_user_dict.size() > 0) 524 { 525 result.AppendMessage ("The following is a list of your current user-defined commands:"); 526 result.AppendMessage(""); 527 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 528 { 529 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp()); 530 } 531 result.AppendMessage(""); 532 } 533 534 result.AppendMessage("For more information on any particular command, try 'help <command-name>'."); 535 } 536 537 CommandObject * 538 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string) 539 { 540 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will 541 // eventually be invoked by the given command line. 542 543 CommandObject *cmd_obj = NULL; 544 std::string white_space (" \t\v"); 545 size_t start = command_string.find_first_not_of (white_space); 546 size_t end = 0; 547 bool done = false; 548 while (!done) 549 { 550 if (start != std::string::npos) 551 { 552 // Get the next word from command_string. 553 end = command_string.find_first_of (white_space, start); 554 if (end == std::string::npos) 555 end = command_string.size(); 556 std::string cmd_word = command_string.substr (start, end - start); 557 558 if (cmd_obj == NULL) 559 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid 560 // command or alias. 561 cmd_obj = GetCommandObject (cmd_word.c_str()); 562 else if (cmd_obj->IsMultiwordObject ()) 563 { 564 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object. 565 CommandObject *sub_cmd_obj = 566 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str()); 567 if (sub_cmd_obj) 568 cmd_obj = sub_cmd_obj; 569 else // cmd_word was not a valid sub-command word, so we are donee 570 done = true; 571 } 572 else 573 // We have a cmd_obj and it is not a multi-word object, so we are done. 574 done = true; 575 576 // If we didn't find a valid command object, or our command object is not a multi-word object, or 577 // we are at the end of the command_string, then we are done. Otherwise, find the start of the 578 // next word. 579 580 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size()) 581 done = true; 582 else 583 start = command_string.find_first_not_of (white_space, end); 584 } 585 else 586 // Unable to find any more words. 587 done = true; 588 } 589 590 if (end == command_string.size()) 591 command_string.clear(); 592 else 593 command_string = command_string.substr(end); 594 595 return cmd_obj; 596 } 597 598 bool 599 CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word) 600 { 601 std::string white_space (" \t\v"); 602 size_t start; 603 size_t end; 604 605 start = command_string.find_first_not_of (white_space); 606 if (start != std::string::npos) 607 { 608 end = command_string.find_first_of (white_space, start); 609 if (end != std::string::npos) 610 { 611 word = command_string.substr (start, end - start); 612 command_string = command_string.substr (end); 613 size_t pos = command_string.find_first_not_of (white_space); 614 if ((pos != 0) && (pos != std::string::npos)) 615 command_string = command_string.substr (pos); 616 } 617 else 618 { 619 word = command_string.substr (start); 620 command_string.erase(); 621 } 622 623 } 624 return true; 625 } 626 627 void 628 CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result, 629 CommandObject *&alias_cmd_obj, CommandReturnObject &result) 630 { 631 Args cmd_args (raw_input_string.c_str()); 632 alias_cmd_obj = GetCommandObject (alias_name); 633 StreamString result_str; 634 635 if (alias_cmd_obj) 636 { 637 std::string alias_name_str = alias_name; 638 if ((cmd_args.GetArgumentCount() == 0) 639 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)) 640 cmd_args.Unshift (alias_name); 641 642 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ()); 643 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 644 645 if (option_arg_vector_sp.get()) 646 { 647 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 648 649 for (int i = 0; i < option_arg_vector->size(); ++i) 650 { 651 OptionArgPair option_pair = (*option_arg_vector)[i]; 652 OptionArgValue value_pair = option_pair.second; 653 int value_type = value_pair.first; 654 std::string option = option_pair.first; 655 std::string value = value_pair.second; 656 if (option.compare ("<argument>") == 0) 657 result_str.Printf (" %s", value.c_str()); 658 else 659 { 660 result_str.Printf (" %s", option.c_str()); 661 if (value_type != optional_argument) 662 result_str.Printf (" "); 663 if (value.compare ("<no_argument>") != 0) 664 { 665 int index = GetOptionArgumentPosition (value.c_str()); 666 if (index == 0) 667 result_str.Printf ("%s", value.c_str()); 668 else if (index >= cmd_args.GetArgumentCount()) 669 { 670 671 result.AppendErrorWithFormat 672 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 673 index); 674 result.SetStatus (eReturnStatusFailed); 675 return; 676 } 677 else 678 { 679 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 680 if (strpos != std::string::npos) 681 raw_input_string = raw_input_string.erase (strpos, 682 strlen (cmd_args.GetArgumentAtIndex (index))); 683 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index)); 684 } 685 } 686 } 687 } 688 } 689 690 alias_result = result_str.GetData(); 691 } 692 } 693 694 bool 695 CommandInterpreter::HandleCommand (const char *command_line, 696 bool add_to_history, 697 CommandReturnObject &result, 698 ExecutionContext *override_context) 699 { 700 bool done = false; 701 CommandObject *cmd_obj = NULL; 702 std::string next_word; 703 bool wants_raw_input = false; 704 std::string command_string (command_line); 705 706 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS)); 707 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line); 708 709 // Make a scoped cleanup object that will clear the crash description string 710 // on exit of this function. 711 lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription); 712 713 if (log) 714 log->Printf ("Processing command: %s", command_line); 715 716 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line); 717 718 m_debugger.UpdateExecutionContext (override_context); 719 720 if (command_line == NULL || command_line[0] == '\0') 721 { 722 if (m_command_history.empty()) 723 { 724 result.AppendError ("empty command"); 725 result.SetStatus(eReturnStatusFailed); 726 return false; 727 } 728 else 729 { 730 command_line = m_repeat_command.c_str(); 731 command_string = command_line; 732 if (m_repeat_command.empty()) 733 { 734 result.AppendErrorWithFormat("No auto repeat.\n"); 735 result.SetStatus (eReturnStatusFailed); 736 return false; 737 } 738 } 739 add_to_history = false; 740 } 741 742 // Phase 1. 743 744 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object 745 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that 746 // the user could have specified an alias, and in translating the alias there may also be command options and/or 747 // even data (including raw text strings) that need to be found and inserted into the command line as part of 748 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command 749 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions & 750 // replacements taken care of; 3). whether or not the Execute function wants raw input or not. 751 752 StreamString revised_command_line; 753 size_t actual_cmd_name_len = 0; 754 while (!done) 755 { 756 StripFirstWord (command_string, next_word); 757 if (!cmd_obj && AliasExists (next_word.c_str())) 758 { 759 std::string alias_result; 760 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result); 761 revised_command_line.Printf ("%s", alias_result.c_str()); 762 if (cmd_obj) 763 { 764 wants_raw_input = cmd_obj->WantsRawCommandString (); 765 actual_cmd_name_len = strlen (cmd_obj->GetCommandName()); 766 } 767 } 768 else if (!cmd_obj) 769 { 770 cmd_obj = GetCommandObject (next_word.c_str()); 771 if (cmd_obj) 772 { 773 actual_cmd_name_len += next_word.length(); 774 revised_command_line.Printf ("%s", next_word.c_str()); 775 wants_raw_input = cmd_obj->WantsRawCommandString (); 776 } 777 else 778 { 779 revised_command_line.Printf ("%s", next_word.c_str()); 780 } 781 } 782 else if (cmd_obj->IsMultiwordObject ()) 783 { 784 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str()); 785 if (sub_cmd_obj) 786 { 787 actual_cmd_name_len += next_word.length() + 1; 788 revised_command_line.Printf (" %s", next_word.c_str()); 789 cmd_obj = sub_cmd_obj; 790 wants_raw_input = cmd_obj->WantsRawCommandString (); 791 } 792 else 793 { 794 revised_command_line.Printf (" %s", next_word.c_str()); 795 done = true; 796 } 797 } 798 else 799 { 800 revised_command_line.Printf (" %s", next_word.c_str()); 801 done = true; 802 } 803 804 if (cmd_obj == NULL) 805 { 806 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str()); 807 result.SetStatus (eReturnStatusFailed); 808 return false; 809 } 810 811 next_word.erase (); 812 if (command_string.length() == 0) 813 done = true; 814 815 } 816 817 if (command_string.size() > 0) 818 revised_command_line.Printf (" %s", command_string.c_str()); 819 820 // End of Phase 1. 821 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command 822 // specified was valid; revised_command_line contains the complete command line (including command name(s)), 823 // fully translated with all substitutions & translations taken care of (still in raw text format); and 824 // wants_raw_input specifies whether the Execute method expects raw input or not. 825 826 827 if (log) 828 { 829 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>"); 830 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData()); 831 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); 832 } 833 834 // Phase 2. 835 // Take care of things like setting up the history command & calling the appropriate Execute method on the 836 // CommandObject, with the appropriate arguments. 837 838 if (cmd_obj != NULL) 839 { 840 if (add_to_history) 841 { 842 Args command_args (revised_command_line.GetData()); 843 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); 844 if (repeat_command != NULL) 845 m_repeat_command.assign(repeat_command); 846 else 847 m_repeat_command.assign(command_line); 848 849 m_command_history.push_back (command_line); 850 } 851 852 command_string = revised_command_line.GetData(); 853 std::string command_name (cmd_obj->GetCommandName()); 854 std::string remainder; 855 if (actual_cmd_name_len < command_string.length()) 856 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter 857 // than cmd_obj->GetCommandName(), because name completion 858 // allows users to enter short versions of the names, 859 // e.g. 'br s' for 'breakpoint set'. 860 861 // Remove any initial spaces 862 std::string white_space (" \t\v"); 863 size_t pos = remainder.find_first_not_of (white_space); 864 if (pos != 0 && pos != std::string::npos) 865 remainder = remainder.substr (pos); 866 867 if (log) 868 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str()); 869 870 871 if (wants_raw_input) 872 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result); 873 else 874 { 875 Args cmd_args (remainder.c_str()); 876 cmd_obj->ExecuteWithOptions (cmd_args, result); 877 } 878 } 879 else 880 { 881 // We didn't find the first command object, so complete the first argument. 882 Args command_args (revised_command_line.GetData()); 883 StringList matches; 884 int num_matches; 885 int cursor_index = 0; 886 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 887 bool word_complete; 888 num_matches = HandleCompletionMatches (command_args, 889 cursor_index, 890 cursor_char_position, 891 0, 892 -1, 893 word_complete, 894 matches); 895 896 if (num_matches > 0) 897 { 898 std::string error_msg; 899 error_msg.assign ("ambiguous command '"); 900 error_msg.append(command_args.GetArgumentAtIndex(0)); 901 error_msg.append ("'."); 902 903 error_msg.append (" Possible completions:"); 904 for (int i = 0; i < num_matches; i++) 905 { 906 error_msg.append ("\n\t"); 907 error_msg.append (matches.GetStringAtIndex (i)); 908 } 909 error_msg.append ("\n"); 910 result.AppendRawError (error_msg.c_str(), error_msg.size()); 911 } 912 else 913 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); 914 915 result.SetStatus (eReturnStatusFailed); 916 } 917 918 return result.Succeeded(); 919 } 920 921 int 922 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 923 int &cursor_index, 924 int &cursor_char_position, 925 int match_start_point, 926 int max_return_elements, 927 bool &word_complete, 928 StringList &matches) 929 { 930 int num_command_matches = 0; 931 bool look_for_subcommand = false; 932 933 // For any of the command completions a unique match will be a complete word. 934 word_complete = true; 935 936 if (cursor_index == -1) 937 { 938 // We got nothing on the command line, so return the list of commands 939 bool include_aliases = true; 940 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 941 } 942 else if (cursor_index == 0) 943 { 944 // The cursor is in the first argument, so just do a lookup in the dictionary. 945 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 946 num_command_matches = matches.GetSize(); 947 948 if (num_command_matches == 1 949 && cmd_obj && cmd_obj->IsMultiwordObject() 950 && matches.GetStringAtIndex(0) != NULL 951 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 952 { 953 look_for_subcommand = true; 954 num_command_matches = 0; 955 matches.DeleteStringAtIndex(0); 956 parsed_line.AppendArgument (""); 957 cursor_index++; 958 cursor_char_position = 0; 959 } 960 } 961 962 if (cursor_index > 0 || look_for_subcommand) 963 { 964 // We are completing further on into a commands arguments, so find the command and tell it 965 // to complete the command. 966 // First see if there is a matching initial command: 967 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 968 if (command_object == NULL) 969 { 970 return 0; 971 } 972 else 973 { 974 parsed_line.Shift(); 975 cursor_index--; 976 num_command_matches = command_object->HandleCompletion (parsed_line, 977 cursor_index, 978 cursor_char_position, 979 match_start_point, 980 max_return_elements, 981 word_complete, 982 matches); 983 } 984 } 985 986 return num_command_matches; 987 988 } 989 990 int 991 CommandInterpreter::HandleCompletion (const char *current_line, 992 const char *cursor, 993 const char *last_char, 994 int match_start_point, 995 int max_return_elements, 996 StringList &matches) 997 { 998 // We parse the argument up to the cursor, so the last argument in parsed_line is 999 // the one containing the cursor, and the cursor is after the last character. 1000 1001 Args parsed_line(current_line, last_char - current_line); 1002 Args partial_parsed_line(current_line, cursor - current_line); 1003 1004 int num_args = partial_parsed_line.GetArgumentCount(); 1005 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 1006 int cursor_char_position; 1007 1008 if (cursor_index == -1) 1009 cursor_char_position = 0; 1010 else 1011 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 1012 1013 if (cursor > current_line && cursor[-1] == ' ') 1014 { 1015 // We are just after a space. If we are in an argument, then we will continue 1016 // parsing, but if we are between arguments, then we have to complete whatever the next 1017 // element would be. 1018 // We can distinguish the two cases because if we are in an argument (e.g. because the space is 1019 // protected by a quote) then the space will also be in the parsed argument... 1020 1021 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); 1022 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') 1023 { 1024 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"'); 1025 cursor_index++; 1026 cursor_char_position = 0; 1027 } 1028 } 1029 1030 int num_command_matches; 1031 1032 matches.Clear(); 1033 1034 // Only max_return_elements == -1 is supported at present: 1035 assert (max_return_elements == -1); 1036 bool word_complete; 1037 num_command_matches = HandleCompletionMatches (parsed_line, 1038 cursor_index, 1039 cursor_char_position, 1040 match_start_point, 1041 max_return_elements, 1042 word_complete, 1043 matches); 1044 1045 if (num_command_matches <= 0) 1046 return num_command_matches; 1047 1048 if (num_args == 0) 1049 { 1050 // If we got an empty string, insert nothing. 1051 matches.InsertStringAtIndex(0, ""); 1052 } 1053 else 1054 { 1055 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 1056 // put an empty string in element 0. 1057 std::string command_partial_str; 1058 if (cursor_index >= 0) 1059 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 1060 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 1061 1062 std::string common_prefix; 1063 matches.LongestCommonPrefix (common_prefix); 1064 int partial_name_len = command_partial_str.size(); 1065 1066 // If we matched a unique single command, add a space... 1067 // Only do this if the completer told us this was a complete word, however... 1068 if (num_command_matches == 1 && word_complete) 1069 { 1070 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 1071 if (quote_char != '\0') 1072 common_prefix.push_back(quote_char); 1073 1074 common_prefix.push_back(' '); 1075 } 1076 common_prefix.erase (0, partial_name_len); 1077 matches.InsertStringAtIndex(0, common_prefix.c_str()); 1078 } 1079 return num_command_matches; 1080 } 1081 1082 1083 CommandInterpreter::~CommandInterpreter () 1084 { 1085 } 1086 1087 const char * 1088 CommandInterpreter::GetPrompt () 1089 { 1090 return m_debugger.GetPrompt(); 1091 } 1092 1093 void 1094 CommandInterpreter::SetPrompt (const char *new_prompt) 1095 { 1096 m_debugger.SetPrompt (new_prompt); 1097 } 1098 1099 size_t 1100 CommandInterpreter::GetConfirmationInputReaderCallback (void *baton, 1101 InputReader &reader, 1102 lldb::InputReaderAction action, 1103 const char *bytes, 1104 size_t bytes_len) 1105 { 1106 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle(); 1107 bool *response_ptr = (bool *) baton; 1108 1109 switch (action) 1110 { 1111 case eInputReaderActivate: 1112 if (out_fh) 1113 { 1114 if (reader.GetPrompt()) 1115 ::fprintf (out_fh, "%s", reader.GetPrompt()); 1116 } 1117 break; 1118 1119 case eInputReaderDeactivate: 1120 break; 1121 1122 case eInputReaderReactivate: 1123 if (out_fh && reader.GetPrompt()) 1124 ::fprintf (out_fh, "%s", reader.GetPrompt()); 1125 break; 1126 1127 case eInputReaderGotToken: 1128 if (bytes_len == 0) 1129 { 1130 reader.SetIsDone(true); 1131 } 1132 else if (bytes[0] == 'y') 1133 { 1134 *response_ptr = true; 1135 reader.SetIsDone(true); 1136 } 1137 else if (bytes[0] == 'n') 1138 { 1139 *response_ptr = false; 1140 reader.SetIsDone(true); 1141 } 1142 else 1143 { 1144 if (out_fh && !reader.IsDone() && reader.GetPrompt()) 1145 { 1146 ::fprintf (out_fh, "Please answer \"y\" or \"n\"\n"); 1147 ::fprintf (out_fh, "%s", reader.GetPrompt()); 1148 } 1149 } 1150 break; 1151 1152 case eInputReaderInterrupt: 1153 case eInputReaderEndOfFile: 1154 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action 1155 reader.SetIsDone (true); 1156 break; 1157 1158 case eInputReaderDone: 1159 break; 1160 } 1161 1162 return bytes_len; 1163 1164 } 1165 1166 bool 1167 CommandInterpreter::Confirm (const char *message, bool default_answer) 1168 { 1169 // Check AutoConfirm first: 1170 if (m_debugger.GetAutoConfirm()) 1171 return default_answer; 1172 1173 InputReaderSP reader_sp (new InputReader(GetDebugger())); 1174 bool response = default_answer; 1175 if (reader_sp) 1176 { 1177 std::string prompt(message); 1178 prompt.append(": ["); 1179 if (default_answer) 1180 prompt.append ("Y/n] "); 1181 else 1182 prompt.append ("y/N] "); 1183 1184 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback, 1185 &response, // baton 1186 eInputReaderGranularityLine, // token size, to pass to callback function 1187 NULL, // end token 1188 prompt.c_str(), // prompt 1189 true)); // echo input 1190 if (err.Success()) 1191 { 1192 GetDebugger().PushInputReader (reader_sp); 1193 } 1194 reader_sp->WaitOnReaderIsDone(); 1195 } 1196 return response; 1197 } 1198 1199 1200 void 1201 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type) 1202 { 1203 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true); 1204 1205 if (cmd_obj_sp != NULL) 1206 { 1207 CommandObject *cmd_obj = cmd_obj_sp.get(); 1208 if (cmd_obj->IsCrossRefObject ()) 1209 cmd_obj->AddObject (object_type); 1210 } 1211 } 1212 1213 OptionArgVectorSP 1214 CommandInterpreter::GetAliasOptions (const char *alias_name) 1215 { 1216 OptionArgMap::iterator pos; 1217 OptionArgVectorSP ret_val; 1218 1219 std::string alias (alias_name); 1220 1221 if (HasAliasOptions()) 1222 { 1223 pos = m_alias_options.find (alias); 1224 if (pos != m_alias_options.end()) 1225 ret_val = pos->second; 1226 } 1227 1228 return ret_val; 1229 } 1230 1231 void 1232 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 1233 { 1234 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 1235 if (pos != m_alias_options.end()) 1236 { 1237 m_alias_options.erase (pos); 1238 } 1239 } 1240 1241 void 1242 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 1243 { 1244 m_alias_options[alias_name] = option_arg_vector_sp; 1245 } 1246 1247 bool 1248 CommandInterpreter::HasCommands () 1249 { 1250 return (!m_command_dict.empty()); 1251 } 1252 1253 bool 1254 CommandInterpreter::HasAliases () 1255 { 1256 return (!m_alias_dict.empty()); 1257 } 1258 1259 bool 1260 CommandInterpreter::HasUserCommands () 1261 { 1262 return (!m_user_dict.empty()); 1263 } 1264 1265 bool 1266 CommandInterpreter::HasAliasOptions () 1267 { 1268 return (!m_alias_options.empty()); 1269 } 1270 1271 void 1272 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 1273 const char *alias_name, 1274 Args &cmd_args, 1275 std::string &raw_input_string, 1276 CommandReturnObject &result) 1277 { 1278 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1279 1280 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 1281 1282 // Make sure that the alias name is the 0th element in cmd_args 1283 std::string alias_name_str = alias_name; 1284 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 1285 cmd_args.Unshift (alias_name); 1286 1287 Args new_args (alias_cmd_obj->GetCommandName()); 1288 if (new_args.GetArgumentCount() == 2) 1289 new_args.Shift(); 1290 1291 if (option_arg_vector_sp.get()) 1292 { 1293 if (wants_raw_input) 1294 { 1295 // We have a command that both has command options and takes raw input. Make *sure* it has a 1296 // " -- " in the right place in the raw_input_string. 1297 size_t pos = raw_input_string.find(" -- "); 1298 if (pos == std::string::npos) 1299 { 1300 // None found; assume it goes at the beginning of the raw input string 1301 raw_input_string.insert (0, " -- "); 1302 } 1303 } 1304 1305 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1306 int old_size = cmd_args.GetArgumentCount(); 1307 std::vector<bool> used (old_size + 1, false); 1308 1309 used[0] = true; 1310 1311 for (int i = 0; i < option_arg_vector->size(); ++i) 1312 { 1313 OptionArgPair option_pair = (*option_arg_vector)[i]; 1314 OptionArgValue value_pair = option_pair.second; 1315 int value_type = value_pair.first; 1316 std::string option = option_pair.first; 1317 std::string value = value_pair.second; 1318 if (option.compare ("<argument>") == 0) 1319 { 1320 if (!wants_raw_input 1321 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice 1322 new_args.AppendArgument (value.c_str()); 1323 } 1324 else 1325 { 1326 if (value_type != optional_argument) 1327 new_args.AppendArgument (option.c_str()); 1328 if (value.compare ("<no-argument>") != 0) 1329 { 1330 int index = GetOptionArgumentPosition (value.c_str()); 1331 if (index == 0) 1332 { 1333 // value was NOT a positional argument; must be a real value 1334 if (value_type != optional_argument) 1335 new_args.AppendArgument (value.c_str()); 1336 else 1337 { 1338 char buffer[255]; 1339 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); 1340 new_args.AppendArgument (buffer); 1341 } 1342 1343 } 1344 else if (index >= cmd_args.GetArgumentCount()) 1345 { 1346 result.AppendErrorWithFormat 1347 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 1348 index); 1349 result.SetStatus (eReturnStatusFailed); 1350 return; 1351 } 1352 else 1353 { 1354 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 1355 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 1356 if (strpos != std::string::npos) 1357 { 1358 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); 1359 } 1360 1361 if (value_type != optional_argument) 1362 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 1363 else 1364 { 1365 char buffer[255]; 1366 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), 1367 cmd_args.GetArgumentAtIndex (index)); 1368 new_args.AppendArgument (buffer); 1369 } 1370 used[index] = true; 1371 } 1372 } 1373 } 1374 } 1375 1376 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j) 1377 { 1378 if (!used[j] && !wants_raw_input) 1379 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 1380 } 1381 1382 cmd_args.Clear(); 1383 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 1384 } 1385 else 1386 { 1387 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1388 // This alias was not created with any options; nothing further needs to be done, unless it is a command that 1389 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw 1390 // input string. 1391 if (wants_raw_input) 1392 { 1393 cmd_args.Clear(); 1394 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 1395 } 1396 return; 1397 } 1398 1399 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1400 return; 1401 } 1402 1403 1404 int 1405 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 1406 { 1407 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 1408 // of zero. 1409 1410 char *cptr = (char *) in_string; 1411 1412 // Does it start with '%' 1413 if (cptr[0] == '%') 1414 { 1415 ++cptr; 1416 1417 // Is the rest of it entirely digits? 1418 if (isdigit (cptr[0])) 1419 { 1420 const char *start = cptr; 1421 while (isdigit (cptr[0])) 1422 ++cptr; 1423 1424 // We've gotten to the end of the digits; are we at the end of the string? 1425 if (cptr[0] == '\0') 1426 position = atoi (start); 1427 } 1428 } 1429 1430 return position; 1431 } 1432 1433 void 1434 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 1435 { 1436 // Don't parse any .lldbinit files if we were asked not to 1437 if (m_skip_lldbinit_files) 1438 return; 1439 1440 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit"; 1441 FileSpec init_file (init_file_path, true); 1442 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 1443 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 1444 1445 if (init_file.Exists()) 1446 { 1447 char path[PATH_MAX]; 1448 init_file.GetPath(path, sizeof(path)); 1449 StreamString source_command; 1450 source_command.Printf ("command source '%s'", path); 1451 HandleCommand (source_command.GetData(), false, result); 1452 } 1453 else 1454 { 1455 // nothing to be done if the file doesn't exist 1456 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1457 } 1458 } 1459 1460 ScriptInterpreter * 1461 CommandInterpreter::GetScriptInterpreter () 1462 { 1463 CommandObject::CommandMap::iterator pos; 1464 1465 pos = m_command_dict.find ("script"); 1466 if (pos != m_command_dict.end()) 1467 { 1468 CommandObject *script_cmd_obj = pos->second.get(); 1469 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (); 1470 } 1471 return NULL; 1472 } 1473 1474 1475 1476 bool 1477 CommandInterpreter::GetSynchronous () 1478 { 1479 return m_synchronous_execution; 1480 } 1481 1482 void 1483 CommandInterpreter::SetSynchronous (bool value) 1484 { 1485 m_synchronous_execution = value; 1486 } 1487 1488 void 1489 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 1490 const char *word_text, 1491 const char *separator, 1492 const char *help_text, 1493 uint32_t max_word_len) 1494 { 1495 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 1496 1497 int indent_size = max_word_len + strlen (separator) + 2; 1498 1499 strm.IndentMore (indent_size); 1500 1501 int len = indent_size + strlen (help_text) + 1; 1502 char *text = (char *) malloc (len); 1503 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text); 1504 if (text[len - 1] == '\n') 1505 text[--len] = '\0'; 1506 1507 if (len < max_columns) 1508 { 1509 // Output it as a single line. 1510 strm.Printf ("%s", text); 1511 } 1512 else 1513 { 1514 // We need to break it up into multiple lines. 1515 bool first_line = true; 1516 int text_width; 1517 int start = 0; 1518 int end = start; 1519 int final_end = strlen (text); 1520 int sub_len; 1521 1522 while (end < final_end) 1523 { 1524 if (first_line) 1525 text_width = max_columns - 1; 1526 else 1527 text_width = max_columns - indent_size - 1; 1528 1529 // Don't start the 'text' on a space, since we're already outputting the indentation. 1530 if (!first_line) 1531 { 1532 while ((start < final_end) && (text[start] == ' ')) 1533 start++; 1534 } 1535 1536 end = start + text_width; 1537 if (end > final_end) 1538 end = final_end; 1539 else 1540 { 1541 // If we're not at the end of the text, make sure we break the line on white space. 1542 while (end > start 1543 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 1544 end--; 1545 } 1546 1547 sub_len = end - start; 1548 if (start != 0) 1549 strm.EOL(); 1550 if (!first_line) 1551 strm.Indent(); 1552 else 1553 first_line = false; 1554 assert (start <= final_end); 1555 assert (start + sub_len <= final_end); 1556 if (sub_len > 0) 1557 strm.Write (text + start, sub_len); 1558 start = end + 1; 1559 } 1560 } 1561 strm.EOL(); 1562 strm.IndentLess(indent_size); 1563 free (text); 1564 } 1565 1566 void 1567 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word, 1568 StringList &commands_found, StringList &commands_help) 1569 { 1570 CommandObject::CommandMap::const_iterator pos; 1571 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict; 1572 CommandObject *sub_cmd_obj; 1573 1574 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos) 1575 { 1576 const char * command_name = pos->first.c_str(); 1577 sub_cmd_obj = pos->second.get(); 1578 StreamString complete_command_name; 1579 1580 complete_command_name.Printf ("%s %s", prefix, command_name); 1581 1582 if (sub_cmd_obj->HelpTextContainsWord (search_word)) 1583 { 1584 commands_found.AppendString (complete_command_name.GetData()); 1585 commands_help.AppendString (sub_cmd_obj->GetHelp()); 1586 } 1587 1588 if (sub_cmd_obj->IsMultiwordObject()) 1589 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found, 1590 commands_help); 1591 } 1592 1593 } 1594 1595 void 1596 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 1597 StringList &commands_help) 1598 { 1599 CommandObject::CommandMap::const_iterator pos; 1600 1601 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 1602 { 1603 const char *command_name = pos->first.c_str(); 1604 CommandObject *cmd_obj = pos->second.get(); 1605 1606 if (cmd_obj->HelpTextContainsWord (search_word)) 1607 { 1608 commands_found.AppendString (command_name); 1609 commands_help.AppendString (cmd_obj->GetHelp()); 1610 } 1611 1612 if (cmd_obj->IsMultiwordObject()) 1613 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help); 1614 1615 } 1616 } 1617