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