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