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