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 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback(); 1515 bool handled = false; 1516 if (wants_raw_input) 1517 { 1518 if (command_callback) 1519 { 1520 std::string full_command (cmd_obj->GetCommandName ()); 1521 full_command += ' '; 1522 full_command += remainder; 1523 const char *argv[2] = { NULL, NULL }; 1524 argv[0] = full_command.c_str(); 1525 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv); 1526 } 1527 if (!handled) 1528 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result); 1529 } 1530 else 1531 { 1532 Args cmd_args (remainder.c_str()); 1533 if (command_callback) 1534 { 1535 Args full_args (cmd_obj->GetCommandName ()); 1536 full_args.AppendArguments(cmd_args); 1537 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector()); 1538 } 1539 if (!handled) 1540 cmd_obj->ExecuteWithOptions (cmd_args, result); 1541 } 1542 } 1543 else 1544 { 1545 // We didn't find the first command object, so complete the first argument. 1546 Args command_args (revised_command_line.GetData()); 1547 StringList matches; 1548 int num_matches; 1549 int cursor_index = 0; 1550 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 1551 bool word_complete; 1552 num_matches = HandleCompletionMatches (command_args, 1553 cursor_index, 1554 cursor_char_position, 1555 0, 1556 -1, 1557 word_complete, 1558 matches); 1559 1560 if (num_matches > 0) 1561 { 1562 std::string error_msg; 1563 error_msg.assign ("ambiguous command '"); 1564 error_msg.append(command_args.GetArgumentAtIndex(0)); 1565 error_msg.append ("'."); 1566 1567 error_msg.append (" Possible completions:"); 1568 for (int i = 0; i < num_matches; i++) 1569 { 1570 error_msg.append ("\n\t"); 1571 error_msg.append (matches.GetStringAtIndex (i)); 1572 } 1573 error_msg.append ("\n"); 1574 result.AppendRawError (error_msg.c_str(), error_msg.size()); 1575 } 1576 else 1577 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); 1578 1579 result.SetStatus (eReturnStatusFailed); 1580 } 1581 1582 if (log) 1583 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed")); 1584 1585 return result.Succeeded(); 1586 } 1587 1588 int 1589 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 1590 int &cursor_index, 1591 int &cursor_char_position, 1592 int match_start_point, 1593 int max_return_elements, 1594 bool &word_complete, 1595 StringList &matches) 1596 { 1597 int num_command_matches = 0; 1598 bool look_for_subcommand = false; 1599 1600 // For any of the command completions a unique match will be a complete word. 1601 word_complete = true; 1602 1603 if (cursor_index == -1) 1604 { 1605 // We got nothing on the command line, so return the list of commands 1606 bool include_aliases = true; 1607 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 1608 } 1609 else if (cursor_index == 0) 1610 { 1611 // The cursor is in the first argument, so just do a lookup in the dictionary. 1612 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 1613 num_command_matches = matches.GetSize(); 1614 1615 if (num_command_matches == 1 1616 && cmd_obj && cmd_obj->IsMultiwordObject() 1617 && matches.GetStringAtIndex(0) != NULL 1618 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 1619 { 1620 look_for_subcommand = true; 1621 num_command_matches = 0; 1622 matches.DeleteStringAtIndex(0); 1623 parsed_line.AppendArgument (""); 1624 cursor_index++; 1625 cursor_char_position = 0; 1626 } 1627 } 1628 1629 if (cursor_index > 0 || look_for_subcommand) 1630 { 1631 // We are completing further on into a commands arguments, so find the command and tell it 1632 // to complete the command. 1633 // First see if there is a matching initial command: 1634 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 1635 if (command_object == NULL) 1636 { 1637 return 0; 1638 } 1639 else 1640 { 1641 parsed_line.Shift(); 1642 cursor_index--; 1643 num_command_matches = command_object->HandleCompletion (parsed_line, 1644 cursor_index, 1645 cursor_char_position, 1646 match_start_point, 1647 max_return_elements, 1648 word_complete, 1649 matches); 1650 } 1651 } 1652 1653 return num_command_matches; 1654 1655 } 1656 1657 int 1658 CommandInterpreter::HandleCompletion (const char *current_line, 1659 const char *cursor, 1660 const char *last_char, 1661 int match_start_point, 1662 int max_return_elements, 1663 StringList &matches) 1664 { 1665 // We parse the argument up to the cursor, so the last argument in parsed_line is 1666 // the one containing the cursor, and the cursor is after the last character. 1667 1668 Args parsed_line(current_line, last_char - current_line); 1669 Args partial_parsed_line(current_line, cursor - current_line); 1670 1671 // Don't complete comments, and if the line we are completing is just the history repeat character, 1672 // substitute the appropriate history line. 1673 const char *first_arg = parsed_line.GetArgumentAtIndex(0); 1674 if (first_arg) 1675 { 1676 if (first_arg[0] == m_comment_char) 1677 return 0; 1678 else if (first_arg[0] == m_repeat_char) 1679 { 1680 const char *history_string = FindHistoryString (first_arg); 1681 if (history_string != NULL) 1682 { 1683 matches.Clear(); 1684 matches.InsertStringAtIndex(0, history_string); 1685 return -2; 1686 } 1687 else 1688 return 0; 1689 1690 } 1691 } 1692 1693 1694 int num_args = partial_parsed_line.GetArgumentCount(); 1695 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 1696 int cursor_char_position; 1697 1698 if (cursor_index == -1) 1699 cursor_char_position = 0; 1700 else 1701 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 1702 1703 if (cursor > current_line && cursor[-1] == ' ') 1704 { 1705 // We are just after a space. If we are in an argument, then we will continue 1706 // parsing, but if we are between arguments, then we have to complete whatever the next 1707 // element would be. 1708 // We can distinguish the two cases because if we are in an argument (e.g. because the space is 1709 // protected by a quote) then the space will also be in the parsed argument... 1710 1711 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); 1712 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') 1713 { 1714 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"'); 1715 cursor_index++; 1716 cursor_char_position = 0; 1717 } 1718 } 1719 1720 int num_command_matches; 1721 1722 matches.Clear(); 1723 1724 // Only max_return_elements == -1 is supported at present: 1725 assert (max_return_elements == -1); 1726 bool word_complete; 1727 num_command_matches = HandleCompletionMatches (parsed_line, 1728 cursor_index, 1729 cursor_char_position, 1730 match_start_point, 1731 max_return_elements, 1732 word_complete, 1733 matches); 1734 1735 if (num_command_matches <= 0) 1736 return num_command_matches; 1737 1738 if (num_args == 0) 1739 { 1740 // If we got an empty string, insert nothing. 1741 matches.InsertStringAtIndex(0, ""); 1742 } 1743 else 1744 { 1745 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 1746 // put an empty string in element 0. 1747 std::string command_partial_str; 1748 if (cursor_index >= 0) 1749 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 1750 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 1751 1752 std::string common_prefix; 1753 matches.LongestCommonPrefix (common_prefix); 1754 int partial_name_len = command_partial_str.size(); 1755 1756 // If we matched a unique single command, add a space... 1757 // Only do this if the completer told us this was a complete word, however... 1758 if (num_command_matches == 1 && word_complete) 1759 { 1760 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 1761 if (quote_char != '\0') 1762 common_prefix.push_back(quote_char); 1763 1764 common_prefix.push_back(' '); 1765 } 1766 common_prefix.erase (0, partial_name_len); 1767 matches.InsertStringAtIndex(0, common_prefix.c_str()); 1768 } 1769 return num_command_matches; 1770 } 1771 1772 1773 CommandInterpreter::~CommandInterpreter () 1774 { 1775 } 1776 1777 const char * 1778 CommandInterpreter::GetPrompt () 1779 { 1780 return m_debugger.GetPrompt(); 1781 } 1782 1783 void 1784 CommandInterpreter::SetPrompt (const char *new_prompt) 1785 { 1786 m_debugger.SetPrompt (new_prompt); 1787 } 1788 1789 size_t 1790 CommandInterpreter::GetConfirmationInputReaderCallback 1791 ( 1792 void *baton, 1793 InputReader &reader, 1794 lldb::InputReaderAction action, 1795 const char *bytes, 1796 size_t bytes_len 1797 ) 1798 { 1799 File &out_file = reader.GetDebugger().GetOutputFile(); 1800 bool *response_ptr = (bool *) baton; 1801 1802 switch (action) 1803 { 1804 case eInputReaderActivate: 1805 if (out_file.IsValid()) 1806 { 1807 if (reader.GetPrompt()) 1808 { 1809 out_file.Printf ("%s", reader.GetPrompt()); 1810 out_file.Flush (); 1811 } 1812 } 1813 break; 1814 1815 case eInputReaderDeactivate: 1816 break; 1817 1818 case eInputReaderReactivate: 1819 if (out_file.IsValid() && reader.GetPrompt()) 1820 { 1821 out_file.Printf ("%s", reader.GetPrompt()); 1822 out_file.Flush (); 1823 } 1824 break; 1825 1826 case eInputReaderAsynchronousOutputWritten: 1827 break; 1828 1829 case eInputReaderGotToken: 1830 if (bytes_len == 0) 1831 { 1832 reader.SetIsDone(true); 1833 } 1834 else if (bytes[0] == 'y' || bytes[0] == 'Y') 1835 { 1836 *response_ptr = true; 1837 reader.SetIsDone(true); 1838 } 1839 else if (bytes[0] == 'n' || bytes[0] == 'N') 1840 { 1841 *response_ptr = false; 1842 reader.SetIsDone(true); 1843 } 1844 else 1845 { 1846 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt()) 1847 { 1848 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt()); 1849 out_file.Flush (); 1850 } 1851 } 1852 break; 1853 1854 case eInputReaderInterrupt: 1855 case eInputReaderEndOfFile: 1856 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action 1857 reader.SetIsDone (true); 1858 break; 1859 1860 case eInputReaderDone: 1861 break; 1862 } 1863 1864 return bytes_len; 1865 1866 } 1867 1868 bool 1869 CommandInterpreter::Confirm (const char *message, bool default_answer) 1870 { 1871 // Check AutoConfirm first: 1872 if (m_debugger.GetAutoConfirm()) 1873 return default_answer; 1874 1875 InputReaderSP reader_sp (new InputReader(GetDebugger())); 1876 bool response = default_answer; 1877 if (reader_sp) 1878 { 1879 std::string prompt(message); 1880 prompt.append(": ["); 1881 if (default_answer) 1882 prompt.append ("Y/n] "); 1883 else 1884 prompt.append ("y/N] "); 1885 1886 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback, 1887 &response, // baton 1888 eInputReaderGranularityLine, // token size, to pass to callback function 1889 NULL, // end token 1890 prompt.c_str(), // prompt 1891 true)); // echo input 1892 if (err.Success()) 1893 { 1894 GetDebugger().PushInputReader (reader_sp); 1895 } 1896 reader_sp->WaitOnReaderIsDone(); 1897 } 1898 return response; 1899 } 1900 1901 1902 void 1903 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type) 1904 { 1905 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true); 1906 1907 if (cmd_obj_sp != NULL) 1908 { 1909 CommandObject *cmd_obj = cmd_obj_sp.get(); 1910 if (cmd_obj->IsCrossRefObject ()) 1911 cmd_obj->AddObject (object_type); 1912 } 1913 } 1914 1915 OptionArgVectorSP 1916 CommandInterpreter::GetAliasOptions (const char *alias_name) 1917 { 1918 OptionArgMap::iterator pos; 1919 OptionArgVectorSP ret_val; 1920 1921 std::string alias (alias_name); 1922 1923 if (HasAliasOptions()) 1924 { 1925 pos = m_alias_options.find (alias); 1926 if (pos != m_alias_options.end()) 1927 ret_val = pos->second; 1928 } 1929 1930 return ret_val; 1931 } 1932 1933 void 1934 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 1935 { 1936 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 1937 if (pos != m_alias_options.end()) 1938 { 1939 m_alias_options.erase (pos); 1940 } 1941 } 1942 1943 void 1944 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 1945 { 1946 m_alias_options[alias_name] = option_arg_vector_sp; 1947 } 1948 1949 bool 1950 CommandInterpreter::HasCommands () 1951 { 1952 return (!m_command_dict.empty()); 1953 } 1954 1955 bool 1956 CommandInterpreter::HasAliases () 1957 { 1958 return (!m_alias_dict.empty()); 1959 } 1960 1961 bool 1962 CommandInterpreter::HasUserCommands () 1963 { 1964 return (!m_user_dict.empty()); 1965 } 1966 1967 bool 1968 CommandInterpreter::HasAliasOptions () 1969 { 1970 return (!m_alias_options.empty()); 1971 } 1972 1973 void 1974 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 1975 const char *alias_name, 1976 Args &cmd_args, 1977 std::string &raw_input_string, 1978 CommandReturnObject &result) 1979 { 1980 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1981 1982 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 1983 1984 // Make sure that the alias name is the 0th element in cmd_args 1985 std::string alias_name_str = alias_name; 1986 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 1987 cmd_args.Unshift (alias_name); 1988 1989 Args new_args (alias_cmd_obj->GetCommandName()); 1990 if (new_args.GetArgumentCount() == 2) 1991 new_args.Shift(); 1992 1993 if (option_arg_vector_sp.get()) 1994 { 1995 if (wants_raw_input) 1996 { 1997 // We have a command that both has command options and takes raw input. Make *sure* it has a 1998 // " -- " in the right place in the raw_input_string. 1999 size_t pos = raw_input_string.find(" -- "); 2000 if (pos == std::string::npos) 2001 { 2002 // None found; assume it goes at the beginning of the raw input string 2003 raw_input_string.insert (0, " -- "); 2004 } 2005 } 2006 2007 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 2008 int old_size = cmd_args.GetArgumentCount(); 2009 std::vector<bool> used (old_size + 1, false); 2010 2011 used[0] = true; 2012 2013 for (int i = 0; i < option_arg_vector->size(); ++i) 2014 { 2015 OptionArgPair option_pair = (*option_arg_vector)[i]; 2016 OptionArgValue value_pair = option_pair.second; 2017 int value_type = value_pair.first; 2018 std::string option = option_pair.first; 2019 std::string value = value_pair.second; 2020 if (option.compare ("<argument>") == 0) 2021 { 2022 if (!wants_raw_input 2023 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice 2024 new_args.AppendArgument (value.c_str()); 2025 } 2026 else 2027 { 2028 if (value_type != optional_argument) 2029 new_args.AppendArgument (option.c_str()); 2030 if (value.compare ("<no-argument>") != 0) 2031 { 2032 int index = GetOptionArgumentPosition (value.c_str()); 2033 if (index == 0) 2034 { 2035 // value was NOT a positional argument; must be a real value 2036 if (value_type != optional_argument) 2037 new_args.AppendArgument (value.c_str()); 2038 else 2039 { 2040 char buffer[255]; 2041 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); 2042 new_args.AppendArgument (buffer); 2043 } 2044 2045 } 2046 else if (index >= cmd_args.GetArgumentCount()) 2047 { 2048 result.AppendErrorWithFormat 2049 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 2050 index); 2051 result.SetStatus (eReturnStatusFailed); 2052 return; 2053 } 2054 else 2055 { 2056 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 2057 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 2058 if (strpos != std::string::npos) 2059 { 2060 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); 2061 } 2062 2063 if (value_type != optional_argument) 2064 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 2065 else 2066 { 2067 char buffer[255]; 2068 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), 2069 cmd_args.GetArgumentAtIndex (index)); 2070 new_args.AppendArgument (buffer); 2071 } 2072 used[index] = true; 2073 } 2074 } 2075 } 2076 } 2077 2078 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j) 2079 { 2080 if (!used[j] && !wants_raw_input) 2081 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 2082 } 2083 2084 cmd_args.Clear(); 2085 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2086 } 2087 else 2088 { 2089 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2090 // This alias was not created with any options; nothing further needs to be done, unless it is a command that 2091 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw 2092 // input string. 2093 if (wants_raw_input) 2094 { 2095 cmd_args.Clear(); 2096 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2097 } 2098 return; 2099 } 2100 2101 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2102 return; 2103 } 2104 2105 2106 int 2107 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 2108 { 2109 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 2110 // of zero. 2111 2112 char *cptr = (char *) in_string; 2113 2114 // Does it start with '%' 2115 if (cptr[0] == '%') 2116 { 2117 ++cptr; 2118 2119 // Is the rest of it entirely digits? 2120 if (isdigit (cptr[0])) 2121 { 2122 const char *start = cptr; 2123 while (isdigit (cptr[0])) 2124 ++cptr; 2125 2126 // We've gotten to the end of the digits; are we at the end of the string? 2127 if (cptr[0] == '\0') 2128 position = atoi (start); 2129 } 2130 } 2131 2132 return position; 2133 } 2134 2135 void 2136 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 2137 { 2138 FileSpec init_file; 2139 if (in_cwd) 2140 { 2141 // In the current working directory we don't load any program specific 2142 // .lldbinit files, we only look for a "./.lldbinit" file. 2143 if (m_skip_lldbinit_files) 2144 return; 2145 2146 init_file.SetFile ("./.lldbinit", true); 2147 } 2148 else 2149 { 2150 // If we aren't looking in the current working directory we are looking 2151 // in the home directory. We will first see if there is an application 2152 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a 2153 // "-" and the name of the program. If this file doesn't exist, we fall 2154 // back to just the "~/.lldbinit" file. We also obey any requests to not 2155 // load the init files. 2156 const char *init_file_path = "~/.lldbinit"; 2157 2158 if (m_skip_app_init_files == false) 2159 { 2160 FileSpec program_file_spec (Host::GetProgramFileSpec()); 2161 const char *program_name = program_file_spec.GetFilename().AsCString(); 2162 2163 if (program_name) 2164 { 2165 char program_init_file_name[PATH_MAX]; 2166 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name); 2167 init_file.SetFile (program_init_file_name, true); 2168 if (!init_file.Exists()) 2169 init_file.Clear(); 2170 } 2171 } 2172 2173 if (!init_file && !m_skip_lldbinit_files) 2174 init_file.SetFile (init_file_path, true); 2175 } 2176 2177 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 2178 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 2179 2180 if (init_file.Exists()) 2181 { 2182 ExecutionContext *exe_ctx = NULL; // We don't have any context yet. 2183 bool stop_on_continue = true; 2184 bool stop_on_error = false; 2185 bool echo_commands = false; 2186 bool print_results = false; 2187 2188 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result); 2189 } 2190 else 2191 { 2192 // nothing to be done if the file doesn't exist 2193 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2194 } 2195 } 2196 2197 PlatformSP 2198 CommandInterpreter::GetPlatform (bool prefer_target_platform) 2199 { 2200 PlatformSP platform_sp; 2201 if (prefer_target_platform) 2202 { 2203 Target *target = m_exe_ctx.GetTargetPtr(); 2204 if (target) 2205 platform_sp = target->GetPlatform(); 2206 } 2207 2208 if (!platform_sp) 2209 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 2210 return platform_sp; 2211 } 2212 2213 void 2214 CommandInterpreter::HandleCommands (const StringList &commands, 2215 ExecutionContext *override_context, 2216 bool stop_on_continue, 2217 bool stop_on_error, 2218 bool echo_commands, 2219 bool print_results, 2220 CommandReturnObject &result) 2221 { 2222 size_t num_lines = commands.GetSize(); 2223 2224 // If we are going to continue past a "continue" then we need to run the commands synchronously. 2225 // Make sure you reset this value anywhere you return from the function. 2226 2227 bool old_async_execution = m_debugger.GetAsyncExecution(); 2228 2229 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will 2230 // cause series of commands that change the context, then do an operation that relies on that context to fail. 2231 2232 if (override_context != NULL) 2233 UpdateExecutionContext (override_context); 2234 2235 if (!stop_on_continue) 2236 { 2237 m_debugger.SetAsyncExecution (false); 2238 } 2239 2240 for (int idx = 0; idx < num_lines; idx++) 2241 { 2242 const char *cmd = commands.GetStringAtIndex(idx); 2243 if (cmd[0] == '\0') 2244 continue; 2245 2246 if (echo_commands) 2247 { 2248 result.AppendMessageWithFormat ("%s %s\n", 2249 GetPrompt(), 2250 cmd); 2251 } 2252 2253 CommandReturnObject tmp_result; 2254 // If override_context is not NULL, pass no_context_switching = true for 2255 // HandleCommand() since we updated our context already. 2256 bool success = HandleCommand(cmd, false, tmp_result, 2257 NULL, /* override_context */ 2258 true, /* repeat_on_empty_command */ 2259 override_context != NULL /* no_context_switching */); 2260 2261 if (print_results) 2262 { 2263 if (tmp_result.Succeeded()) 2264 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData()); 2265 } 2266 2267 if (!success || !tmp_result.Succeeded()) 2268 { 2269 if (stop_on_error) 2270 { 2271 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n", 2272 idx, cmd); 2273 result.SetStatus (eReturnStatusFailed); 2274 m_debugger.SetAsyncExecution (old_async_execution); 2275 return; 2276 } 2277 else if (print_results) 2278 { 2279 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n", 2280 idx + 1, 2281 cmd, 2282 tmp_result.GetErrorData()); 2283 } 2284 } 2285 2286 if (result.GetImmediateOutputStream()) 2287 result.GetImmediateOutputStream()->Flush(); 2288 2289 if (result.GetImmediateErrorStream()) 2290 result.GetImmediateErrorStream()->Flush(); 2291 2292 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution 2293 // could be running (for instance in Breakpoint Commands. 2294 // So we check the return value to see if it is has running in it. 2295 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) 2296 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) 2297 { 2298 if (stop_on_continue) 2299 { 2300 // If we caused the target to proceed, and we're going to stop in that case, set the 2301 // status in our real result before returning. This is an error if the continue was not the 2302 // last command in the set of commands to be run. 2303 if (idx != num_lines - 1) 2304 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n", 2305 idx + 1, cmd); 2306 else 2307 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd); 2308 2309 result.SetStatus(tmp_result.GetStatus()); 2310 m_debugger.SetAsyncExecution (old_async_execution); 2311 2312 return; 2313 } 2314 } 2315 2316 } 2317 2318 result.SetStatus (eReturnStatusSuccessFinishResult); 2319 m_debugger.SetAsyncExecution (old_async_execution); 2320 2321 return; 2322 } 2323 2324 void 2325 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file, 2326 ExecutionContext *context, 2327 bool stop_on_continue, 2328 bool stop_on_error, 2329 bool echo_command, 2330 bool print_result, 2331 CommandReturnObject &result) 2332 { 2333 if (cmd_file.Exists()) 2334 { 2335 bool success; 2336 StringList commands; 2337 success = commands.ReadFileLines(cmd_file); 2338 if (!success) 2339 { 2340 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString()); 2341 result.SetStatus (eReturnStatusFailed); 2342 return; 2343 } 2344 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result); 2345 } 2346 else 2347 { 2348 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n", 2349 cmd_file.GetFilename().AsCString()); 2350 result.SetStatus (eReturnStatusFailed); 2351 return; 2352 } 2353 } 2354 2355 ScriptInterpreter * 2356 CommandInterpreter::GetScriptInterpreter () 2357 { 2358 if (m_script_interpreter_ap.get() != NULL) 2359 return m_script_interpreter_ap.get(); 2360 2361 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); 2362 switch (script_lang) 2363 { 2364 case eScriptLanguagePython: 2365 #ifndef LLDB_DISABLE_PYTHON 2366 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this)); 2367 break; 2368 #else 2369 // Fall through to the None case when python is disabled 2370 #endif 2371 case eScriptLanguageNone: 2372 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this)); 2373 break; 2374 default: 2375 break; 2376 }; 2377 2378 return m_script_interpreter_ap.get(); 2379 } 2380 2381 2382 2383 bool 2384 CommandInterpreter::GetSynchronous () 2385 { 2386 return m_synchronous_execution; 2387 } 2388 2389 void 2390 CommandInterpreter::SetSynchronous (bool value) 2391 { 2392 m_synchronous_execution = value; 2393 } 2394 2395 void 2396 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 2397 const char *word_text, 2398 const char *separator, 2399 const char *help_text, 2400 uint32_t max_word_len) 2401 { 2402 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2403 2404 int indent_size = max_word_len + strlen (separator) + 2; 2405 2406 strm.IndentMore (indent_size); 2407 2408 StreamString text_strm; 2409 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2410 2411 size_t len = text_strm.GetSize(); 2412 const char *text = text_strm.GetData(); 2413 if (text[len - 1] == '\n') 2414 { 2415 text_strm.EOL(); 2416 len = text_strm.GetSize(); 2417 } 2418 2419 if (len < max_columns) 2420 { 2421 // Output it as a single line. 2422 strm.Printf ("%s", text); 2423 } 2424 else 2425 { 2426 // We need to break it up into multiple lines. 2427 bool first_line = true; 2428 int text_width; 2429 int start = 0; 2430 int end = start; 2431 int final_end = strlen (text); 2432 int sub_len; 2433 2434 while (end < final_end) 2435 { 2436 if (first_line) 2437 text_width = max_columns - 1; 2438 else 2439 text_width = max_columns - indent_size - 1; 2440 2441 // Don't start the 'text' on a space, since we're already outputting the indentation. 2442 if (!first_line) 2443 { 2444 while ((start < final_end) && (text[start] == ' ')) 2445 start++; 2446 } 2447 2448 end = start + text_width; 2449 if (end > final_end) 2450 end = final_end; 2451 else 2452 { 2453 // If we're not at the end of the text, make sure we break the line on white space. 2454 while (end > start 2455 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 2456 end--; 2457 } 2458 2459 sub_len = end - start; 2460 if (start != 0) 2461 strm.EOL(); 2462 if (!first_line) 2463 strm.Indent(); 2464 else 2465 first_line = false; 2466 assert (start <= final_end); 2467 assert (start + sub_len <= final_end); 2468 if (sub_len > 0) 2469 strm.Write (text + start, sub_len); 2470 start = end + 1; 2471 } 2472 } 2473 strm.EOL(); 2474 strm.IndentLess(indent_size); 2475 } 2476 2477 void 2478 CommandInterpreter::OutputHelpText (Stream &strm, 2479 const char *word_text, 2480 const char *separator, 2481 const char *help_text, 2482 uint32_t max_word_len) 2483 { 2484 int indent_size = max_word_len + strlen (separator) + 2; 2485 2486 strm.IndentMore (indent_size); 2487 2488 StreamString text_strm; 2489 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2490 2491 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2492 bool first_line = true; 2493 2494 size_t len = text_strm.GetSize(); 2495 const char *text = text_strm.GetData(); 2496 2497 uint32_t chars_left = max_columns; 2498 2499 for (uint32_t i = 0; i < len; i++) 2500 { 2501 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n') 2502 { 2503 first_line = false; 2504 chars_left = max_columns - indent_size; 2505 strm.EOL(); 2506 strm.Indent(); 2507 } 2508 else 2509 { 2510 strm.PutChar(text[i]); 2511 chars_left--; 2512 } 2513 2514 } 2515 2516 strm.EOL(); 2517 strm.IndentLess(indent_size); 2518 } 2519 2520 void 2521 CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word, 2522 StringList &commands_found, StringList &commands_help) 2523 { 2524 CommandObject::CommandMap::const_iterator pos; 2525 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict; 2526 CommandObject *sub_cmd_obj; 2527 2528 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos) 2529 { 2530 const char * command_name = pos->first.c_str(); 2531 sub_cmd_obj = pos->second.get(); 2532 StreamString complete_command_name; 2533 2534 complete_command_name.Printf ("%s %s", prefix, command_name); 2535 2536 if (sub_cmd_obj->HelpTextContainsWord (search_word)) 2537 { 2538 commands_found.AppendString (complete_command_name.GetData()); 2539 commands_help.AppendString (sub_cmd_obj->GetHelp()); 2540 } 2541 2542 if (sub_cmd_obj->IsMultiwordObject()) 2543 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found, 2544 commands_help); 2545 } 2546 2547 } 2548 2549 void 2550 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 2551 StringList &commands_help) 2552 { 2553 CommandObject::CommandMap::const_iterator pos; 2554 2555 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 2556 { 2557 const char *command_name = pos->first.c_str(); 2558 CommandObject *cmd_obj = pos->second.get(); 2559 2560 if (cmd_obj->HelpTextContainsWord (search_word)) 2561 { 2562 commands_found.AppendString (command_name); 2563 commands_help.AppendString (cmd_obj->GetHelp()); 2564 } 2565 2566 if (cmd_obj->IsMultiwordObject()) 2567 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help); 2568 2569 } 2570 } 2571 2572 2573 void 2574 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context) 2575 { 2576 m_exe_ctx.Clear(); 2577 2578 if (override_context != NULL) 2579 { 2580 m_exe_ctx = *override_context; 2581 } 2582 else 2583 { 2584 TargetSP target_sp (m_debugger.GetSelectedTarget()); 2585 if (target_sp) 2586 { 2587 m_exe_ctx.SetTargetSP (target_sp); 2588 ProcessSP process_sp (target_sp->GetProcessSP()); 2589 m_exe_ctx.SetProcessSP (process_sp); 2590 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning()) 2591 { 2592 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread()); 2593 if (thread_sp) 2594 { 2595 m_exe_ctx.SetThreadSP (thread_sp); 2596 StackFrameSP frame_sp (thread_sp->GetSelectedFrame()); 2597 if (!frame_sp) 2598 { 2599 frame_sp = thread_sp->GetStackFrameAtIndex (0); 2600 // If we didn't have a selected frame select one here. 2601 if (frame_sp) 2602 thread_sp->SetSelectedFrame(frame_sp.get()); 2603 } 2604 if (frame_sp) 2605 m_exe_ctx.SetFrameSP (frame_sp); 2606 } 2607 } 2608 } 2609 } 2610 } 2611 2612 void 2613 CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const 2614 { 2615 DumpHistory (stream, 0, count - 1); 2616 } 2617 2618 void 2619 CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const 2620 { 2621 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1); 2622 for (size_t i = start; i < last_idx; i++) 2623 { 2624 if (!m_command_history[i].empty()) 2625 { 2626 stream.Indent(); 2627 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str()); 2628 } 2629 } 2630 } 2631 2632 const char * 2633 CommandInterpreter::FindHistoryString (const char *input_str) const 2634 { 2635 if (input_str[0] != m_repeat_char) 2636 return NULL; 2637 if (input_str[1] == '-') 2638 { 2639 bool success; 2640 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success); 2641 if (!success) 2642 return NULL; 2643 if (idx > m_command_history.size()) 2644 return NULL; 2645 idx = m_command_history.size() - idx; 2646 return m_command_history[idx].c_str(); 2647 2648 } 2649 else if (input_str[1] == m_repeat_char) 2650 { 2651 if (m_command_history.empty()) 2652 return NULL; 2653 else 2654 return m_command_history.back().c_str(); 2655 } 2656 else 2657 { 2658 bool success; 2659 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success); 2660 if (!success) 2661 return NULL; 2662 if (idx >= m_command_history.size()) 2663 return NULL; 2664 return m_command_history[idx].c_str(); 2665 } 2666 } 2667