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