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