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