1 //===-- CommandInterpreter.h ------------------------------------*- 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 #ifndef liblldb_CommandInterpreter_h_ 11 #define liblldb_CommandInterpreter_h_ 12 13 // C Includes 14 // C++ Includes 15 // Other libraries and framework includes 16 // Project includes 17 #include "lldb/lldb-private.h" 18 #include "lldb/Core/Broadcaster.h" 19 #include "lldb/Core/Debugger.h" 20 #include "lldb/Core/IOHandler.h" 21 #include "lldb/Core/Log.h" 22 #include "lldb/Interpreter/CommandHistory.h" 23 #include "lldb/Interpreter/CommandObject.h" 24 #include "lldb/Interpreter/ScriptInterpreter.h" 25 #include "lldb/Core/Event.h" 26 #include "lldb/Interpreter/Args.h" 27 #include "lldb/Core/StringList.h" 28 29 namespace lldb_private { 30 31 class CommandInterpreterRunOptions 32 { 33 public: 34 //------------------------------------------------------------------ 35 /// Construct a CommandInterpreterRunOptions object. 36 /// This class is used to control all the instances where we run multiple commands, e.g. 37 /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter. 38 /// The meanings of the options in this object are: 39 /// 40 /// @param[in] stop_on_continue 41 /// If \b true execution will end on the first command that causes the process in the 42 /// execution context to continue. If \false, we won't check the execution status. 43 /// @param[in] stop_on_error 44 /// If \b true execution will end on the first command that causes an error. 45 /// @param[in] stop_on_crash 46 /// If \b true when a command causes the target to run, and the end of the run is a 47 /// signal or exception, stop executing the commands. 48 /// @param[in] echo_commands 49 /// If \b true echo the command before executing it. If \false, execute silently. 50 /// @param[in] print_results 51 /// If \b true print the results of the command after executing it. If \false, execute silently. 52 /// @param[in] add_to_history 53 /// If \b true add the commands to the command history. If \false, don't add them. 54 //------------------------------------------------------------------ CommandInterpreterRunOptions(LazyBool stop_on_continue,LazyBool stop_on_error,LazyBool stop_on_crash,LazyBool echo_commands,LazyBool print_results,LazyBool add_to_history)55 CommandInterpreterRunOptions (LazyBool stop_on_continue, 56 LazyBool stop_on_error, 57 LazyBool stop_on_crash, 58 LazyBool echo_commands, 59 LazyBool print_results, 60 LazyBool add_to_history) : 61 m_stop_on_continue(stop_on_continue), 62 m_stop_on_error(stop_on_error), 63 m_stop_on_crash(stop_on_crash), 64 m_echo_commands(echo_commands), 65 m_print_results(print_results), 66 m_add_to_history(add_to_history) 67 {} 68 CommandInterpreterRunOptions()69 CommandInterpreterRunOptions () : 70 m_stop_on_continue(eLazyBoolCalculate), 71 m_stop_on_error(eLazyBoolCalculate), 72 m_stop_on_crash(eLazyBoolCalculate), 73 m_echo_commands(eLazyBoolCalculate), 74 m_print_results(eLazyBoolCalculate), 75 m_add_to_history(eLazyBoolCalculate) 76 {} 77 78 void SetSilent(bool silent)79 SetSilent (bool silent) 80 { 81 LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes; 82 83 m_echo_commands = value; 84 m_print_results = value; 85 m_add_to_history = value; 86 } 87 // These return the default behaviors if the behavior is not eLazyBoolCalculate. 88 // But I've also left the ivars public since for different ways of running the 89 // interpreter you might want to force different defaults... In that case, just grab 90 // the LazyBool ivars directly and do what you want with eLazyBoolCalculate. 91 bool GetStopOnContinue()92 GetStopOnContinue () const 93 { 94 return DefaultToNo (m_stop_on_continue); 95 } 96 97 void SetStopOnContinue(bool stop_on_continue)98 SetStopOnContinue (bool stop_on_continue) 99 { 100 m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo; 101 } 102 103 bool GetStopOnError()104 GetStopOnError () const 105 { 106 return DefaultToNo (m_stop_on_continue); 107 } 108 109 void SetStopOnError(bool stop_on_error)110 SetStopOnError (bool stop_on_error) 111 { 112 m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo; 113 } 114 115 bool GetStopOnCrash()116 GetStopOnCrash () const 117 { 118 return DefaultToNo (m_stop_on_crash); 119 } 120 121 void SetStopOnCrash(bool stop_on_crash)122 SetStopOnCrash (bool stop_on_crash) 123 { 124 m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo; 125 } 126 127 bool GetEchoCommands()128 GetEchoCommands () const 129 { 130 return DefaultToYes (m_echo_commands); 131 } 132 133 void SetEchoCommands(bool echo_commands)134 SetEchoCommands (bool echo_commands) 135 { 136 m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo; 137 } 138 139 bool GetPrintResults()140 GetPrintResults () const 141 { 142 return DefaultToYes (m_print_results); 143 } 144 145 void SetPrintResults(bool print_results)146 SetPrintResults (bool print_results) 147 { 148 m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo; 149 } 150 151 bool GetAddToHistory()152 GetAddToHistory () const 153 { 154 return DefaultToYes (m_add_to_history); 155 } 156 157 void SetAddToHistory(bool add_to_history)158 SetAddToHistory (bool add_to_history) 159 { 160 m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo; 161 } 162 163 LazyBool m_stop_on_continue; 164 LazyBool m_stop_on_error; 165 LazyBool m_stop_on_crash; 166 LazyBool m_echo_commands; 167 LazyBool m_print_results; 168 LazyBool m_add_to_history; 169 170 private: 171 static bool DefaultToYes(LazyBool flag)172 DefaultToYes (LazyBool flag) 173 { 174 switch (flag) 175 { 176 case eLazyBoolNo: 177 return false; 178 default: 179 return true; 180 } 181 } 182 183 static bool DefaultToNo(LazyBool flag)184 DefaultToNo (LazyBool flag) 185 { 186 switch (flag) 187 { 188 case eLazyBoolYes: 189 return true; 190 default: 191 return false; 192 } 193 } 194 }; 195 196 class CommandInterpreter : 197 public Broadcaster, 198 public Properties, 199 public IOHandlerDelegate 200 { 201 public: 202 203 204 typedef std::map<std::string, OptionArgVectorSP> OptionArgMap; 205 206 enum 207 { 208 eBroadcastBitThreadShouldExit = (1 << 0), 209 eBroadcastBitResetPrompt = (1 << 1), 210 eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit 211 eBroadcastBitAsynchronousOutputData = (1 << 3), 212 eBroadcastBitAsynchronousErrorData = (1 << 4) 213 }; 214 215 enum ChildrenTruncatedWarningStatus // tristate boolean to manage children truncation warning 216 { 217 eNoTruncation = 0, // never truncated 218 eUnwarnedTruncation = 1, // truncated but did not notify 219 eWarnedTruncation = 2 // truncated and notified 220 }; 221 222 enum CommandTypes 223 { 224 eCommandTypesBuiltin = 0x0001, // native commands such as "frame" 225 eCommandTypesUserDef = 0x0002, // scripted commands 226 eCommandTypesAliases = 0x0004, // aliases such as "po" 227 eCommandTypesHidden = 0x0008, // commands prefixed with an underscore 228 eCommandTypesAllThem = 0xFFFF // all commands 229 }; 230 231 // These two functions fill out the Broadcaster interface: 232 233 static ConstString &GetStaticBroadcasterClass (); 234 GetBroadcasterClass()235 virtual ConstString &GetBroadcasterClass() const 236 { 237 return GetStaticBroadcasterClass(); 238 } 239 240 void 241 SourceInitFile (bool in_cwd, 242 CommandReturnObject &result); 243 244 CommandInterpreter (Debugger &debugger, 245 lldb::ScriptLanguage script_language, 246 bool synchronous_execution); 247 248 virtual 249 ~CommandInterpreter (); 250 251 bool 252 AddCommand (const char *name, 253 const lldb::CommandObjectSP &cmd_sp, 254 bool can_replace); 255 256 bool 257 AddUserCommand (std::string name, 258 const lldb::CommandObjectSP &cmd_sp, 259 bool can_replace); 260 261 lldb::CommandObjectSP 262 GetCommandSPExact (const char *cmd, 263 bool include_aliases); 264 265 CommandObject * 266 GetCommandObjectExact (const char *cmd_cstr, 267 bool include_aliases); 268 269 CommandObject * 270 GetCommandObject (const char *cmd, 271 StringList *matches = NULL); 272 273 bool 274 CommandExists (const char *cmd); 275 276 bool 277 AliasExists (const char *cmd); 278 279 bool 280 UserCommandExists (const char *cmd); 281 282 void 283 AddAlias (const char *alias_name, 284 lldb::CommandObjectSP& command_obj_sp); 285 286 // Remove a command if it is removable (python or regex command) 287 bool 288 RemoveCommand (const char *cmd); 289 290 bool 291 RemoveAlias (const char *alias_name); 292 293 bool 294 GetAliasFullName (const char *cmd, std::string &full_name); 295 296 bool 297 RemoveUser (const char *alias_name); 298 299 void RemoveAllUser()300 RemoveAllUser () 301 { 302 m_user_dict.clear(); 303 } 304 305 OptionArgVectorSP 306 GetAliasOptions (const char *alias_name); 307 308 309 bool 310 ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp, 311 const char *options_args, 312 OptionArgVectorSP &option_arg_vector_sp); 313 314 void 315 RemoveAliasOptions (const char *alias_name); 316 317 void 318 AddOrReplaceAliasOptions (const char *alias_name, 319 OptionArgVectorSP &option_arg_vector_sp); 320 321 CommandObject * 322 BuildAliasResult (const char *alias_name, 323 std::string &raw_input_string, 324 std::string &alias_result, 325 CommandReturnObject &result); 326 327 bool 328 HandleCommand (const char *command_line, 329 LazyBool add_to_history, 330 CommandReturnObject &result, 331 ExecutionContext *override_context = NULL, 332 bool repeat_on_empty_command = true, 333 bool no_context_switching = false); 334 335 //------------------------------------------------------------------ 336 /// Execute a list of commands in sequence. 337 /// 338 /// @param[in] commands 339 /// The list of commands to execute. 340 /// @param[in/out] context 341 /// The execution context in which to run the commands. Can be NULL in which case the default 342 /// context will be used. 343 /// @param[in] options 344 /// This object holds the options used to control when to stop, whether to execute commands, 345 /// etc. 346 /// @param[out] result 347 /// This is marked as succeeding with no output if all commands execute safely, 348 /// and failed with some explanation if we aborted executing the commands at some point. 349 //------------------------------------------------------------------ 350 void 351 HandleCommands (const StringList &commands, 352 ExecutionContext *context, 353 CommandInterpreterRunOptions &options, 354 CommandReturnObject &result); 355 356 //------------------------------------------------------------------ 357 /// Execute a list of commands from a file. 358 /// 359 /// @param[in] file 360 /// The file from which to read in commands. 361 /// @param[in/out] context 362 /// The execution context in which to run the commands. Can be NULL in which case the default 363 /// context will be used. 364 /// @param[in] options 365 /// This object holds the options used to control when to stop, whether to execute commands, 366 /// etc. 367 /// @param[out] result 368 /// This is marked as succeeding with no output if all commands execute safely, 369 /// and failed with some explanation if we aborted executing the commands at some point. 370 //------------------------------------------------------------------ 371 void 372 HandleCommandsFromFile (FileSpec &file, 373 ExecutionContext *context, 374 CommandInterpreterRunOptions &options, 375 CommandReturnObject &result); 376 377 CommandObject * 378 GetCommandObjectForCommand (std::string &command_line); 379 380 // This handles command line completion. You are given a pointer to the command string buffer, to the current cursor, 381 // and to the end of the string (in case it is not NULL terminated). 382 // You also passed in an StringList object to fill with the returns. 383 // The first element of the array will be filled with the string that you would need to insert at 384 // the cursor point to complete the cursor point to the longest common matching prefix. 385 // If you want to limit the number of elements returned, set max_return_elements to the number of elements 386 // you want returned. Otherwise set max_return_elements to -1. 387 // If you want to start some way into the match list, then set match_start_point to the desired start 388 // point. 389 // Returns: 390 // -1 if the completion character should be inserted 391 // -2 if the entire command line should be deleted and replaced with matches.GetStringAtIndex(0) 392 // INT_MAX if the number of matches is > max_return_elements, but it is expensive to compute. 393 // Otherwise, returns the number of matches. 394 // 395 // FIXME: Only max_return_elements == -1 is supported at present. 396 397 int 398 HandleCompletion (const char *current_line, 399 const char *cursor, 400 const char *last_char, 401 int match_start_point, 402 int max_return_elements, 403 StringList &matches); 404 405 // This version just returns matches, and doesn't compute the substring. It is here so the 406 // Help command can call it for the first argument. 407 // word_complete tells whether the completions are considered a "complete" response (so the 408 // completer should complete the quote & put a space after the word. 409 410 int 411 HandleCompletionMatches (Args &input, 412 int &cursor_index, 413 int &cursor_char_position, 414 int match_start_point, 415 int max_return_elements, 416 bool &word_complete, 417 StringList &matches); 418 419 420 int 421 GetCommandNamesMatchingPartialString (const char *cmd_cstr, 422 bool include_aliases, 423 StringList &matches); 424 425 void 426 GetHelp (CommandReturnObject &result, 427 uint32_t types = eCommandTypesAllThem); 428 429 void 430 GetAliasHelp (const char *alias_name, 431 const char *command_name, 432 StreamString &help_string); 433 434 void 435 OutputFormattedHelpText (Stream &strm, 436 const char *prefix, 437 const char *help_text); 438 439 void 440 OutputFormattedHelpText (Stream &stream, 441 const char *command_word, 442 const char *separator, 443 const char *help_text, 444 size_t max_word_len); 445 446 // this mimics OutputFormattedHelpText but it does perform a much simpler 447 // formatting, basically ensuring line alignment. This is only good if you have 448 // some complicated layout for your help text and want as little help as reasonable 449 // in properly displaying it. Most of the times, you simply want to type some text 450 // and have it printed in a reasonable way on screen. If so, use OutputFormattedHelpText 451 void 452 OutputHelpText (Stream &stream, 453 const char *command_word, 454 const char *separator, 455 const char *help_text, 456 uint32_t max_word_len); 457 458 Debugger & GetDebugger()459 GetDebugger () 460 { 461 return m_debugger; 462 } 463 464 ExecutionContext GetExecutionContext()465 GetExecutionContext() 466 { 467 const bool thread_and_frame_only_if_stopped = true; 468 return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped); 469 } 470 471 void 472 UpdateExecutionContext (ExecutionContext *override_context); 473 474 lldb::PlatformSP 475 GetPlatform (bool prefer_target_platform); 476 477 const char * 478 ProcessEmbeddedScriptCommands (const char *arg); 479 480 void 481 UpdatePrompt (const char *); 482 483 bool 484 Confirm (const char *message, 485 bool default_answer); 486 487 void 488 LoadCommandDictionary (); 489 490 void 491 Initialize (); 492 493 void 494 Clear (); 495 496 void 497 SetScriptLanguage (lldb::ScriptLanguage lang); 498 499 500 bool 501 HasCommands (); 502 503 bool 504 HasAliases (); 505 506 bool 507 HasUserCommands (); 508 509 bool 510 HasAliasOptions (); 511 512 void 513 BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 514 const char *alias_name, 515 Args &cmd_args, 516 std::string &raw_input_string, 517 CommandReturnObject &result); 518 519 int 520 GetOptionArgumentPosition (const char *in_string); 521 522 ScriptInterpreter * 523 GetScriptInterpreter (bool can_create = true); 524 525 void SkipLLDBInitFiles(bool skip_lldbinit_files)526 SkipLLDBInitFiles (bool skip_lldbinit_files) 527 { 528 m_skip_lldbinit_files = skip_lldbinit_files; 529 } 530 531 void SkipAppInitFiles(bool skip_app_init_files)532 SkipAppInitFiles (bool skip_app_init_files) 533 { 534 m_skip_app_init_files = m_skip_lldbinit_files; 535 } 536 537 bool 538 GetSynchronous (); 539 540 size_t 541 FindLongestCommandWord (CommandObject::CommandMap &dict); 542 543 void 544 FindCommandsForApropos (const char *word, 545 StringList &commands_found, 546 StringList &commands_help, 547 bool search_builtin_commands, 548 bool search_user_commands); 549 550 bool GetBatchCommandMode()551 GetBatchCommandMode () { return m_batch_command_mode; } 552 553 bool SetBatchCommandMode(bool value)554 SetBatchCommandMode (bool value) { 555 const bool old_value = m_batch_command_mode; 556 m_batch_command_mode = value; 557 return old_value; 558 } 559 560 void ChildrenTruncated()561 ChildrenTruncated () 562 { 563 if (m_truncation_warning == eNoTruncation) 564 m_truncation_warning = eUnwarnedTruncation; 565 } 566 567 bool TruncationWarningNecessary()568 TruncationWarningNecessary () 569 { 570 return (m_truncation_warning == eUnwarnedTruncation); 571 } 572 573 void TruncationWarningGiven()574 TruncationWarningGiven () 575 { 576 m_truncation_warning = eWarnedTruncation; 577 } 578 579 const char * TruncationWarningText()580 TruncationWarningText () 581 { 582 return "*** Some of your variables have more members than the debugger will show by default. To show all of them, you can either use the --show-all-children option to %s or raise the limit by changing the target.max-children-count setting.\n"; 583 } 584 585 const CommandHistory& GetCommandHistory()586 GetCommandHistory () const 587 { 588 return m_command_history; 589 } 590 591 CommandHistory& GetCommandHistory()592 GetCommandHistory () 593 { 594 return m_command_history; 595 } 596 597 bool 598 IsActive (); 599 600 void 601 RunCommandInterpreter (bool auto_handle_events, 602 bool spawn_thread, 603 CommandInterpreterRunOptions &options); 604 void 605 GetLLDBCommandsFromIOHandler (const char *prompt, 606 IOHandlerDelegate &delegate, 607 bool asynchronously, 608 void *baton); 609 610 void 611 GetPythonCommandsFromIOHandler (const char *prompt, 612 IOHandlerDelegate &delegate, 613 bool asynchronously, 614 void *baton); 615 616 const char * 617 GetCommandPrefix (); 618 619 //------------------------------------------------------------------ 620 // Properties 621 //------------------------------------------------------------------ 622 bool 623 GetExpandRegexAliases () const; 624 625 bool 626 GetPromptOnQuit () const; 627 628 void 629 SetPromptOnQuit (bool b); 630 631 void 632 ResolveCommand(const char *command_line, CommandReturnObject &result); 633 634 bool 635 GetStopCmdSourceOnError () const; 636 637 uint32_t GetNumErrors()638 GetNumErrors() const 639 { 640 return m_num_errors; 641 } 642 643 bool GetQuitRequested()644 GetQuitRequested () const 645 { 646 return m_quit_requested; 647 } 648 649 lldb::IOHandlerSP 650 GetIOHandler(bool force_create = false, CommandInterpreterRunOptions *options = NULL); 651 652 bool GetStoppedForCrash()653 GetStoppedForCrash () const 654 { 655 return m_stopped_for_crash; 656 } 657 658 protected: 659 friend class Debugger; 660 661 //------------------------------------------------------------------ 662 // IOHandlerDelegate functions 663 //------------------------------------------------------------------ 664 virtual void 665 IOHandlerInputComplete (IOHandler &io_handler, 666 std::string &line); 667 668 virtual ConstString IOHandlerGetControlSequence(char ch)669 IOHandlerGetControlSequence (char ch) 670 { 671 if (ch == 'd') 672 return ConstString("quit\n"); 673 return ConstString(); 674 } 675 676 virtual bool 677 IOHandlerInterrupt (IOHandler &io_handler); 678 679 size_t 680 GetProcessOutput (); 681 682 void 683 SetSynchronous (bool value); 684 685 lldb::CommandObjectSP 686 GetCommandSP (const char *cmd, bool include_aliases = true, bool exact = true, StringList *matches = NULL); 687 688 689 private: 690 691 Error 692 PreprocessCommand (std::string &command); 693 694 // Completely resolves aliases and abbreviations, returning a pointer to the 695 // final command object and updating command_line to the fully substituted 696 // and translated command. 697 CommandObject * 698 ResolveCommandImpl(std::string &command_line, CommandReturnObject &result); 699 700 701 Debugger &m_debugger; // The debugger session that this interpreter is associated with 702 ExecutionContextRef m_exe_ctx_ref; // The current execution context to use when handling commands 703 bool m_synchronous_execution; 704 bool m_skip_lldbinit_files; 705 bool m_skip_app_init_files; 706 CommandObject::CommandMap m_command_dict; // Stores basic built-in commands (they cannot be deleted, removed or overwritten). 707 CommandObject::CommandMap m_alias_dict; // Stores user aliases/abbreviations for commands 708 CommandObject::CommandMap m_user_dict; // Stores user-defined commands 709 OptionArgMap m_alias_options; // Stores any options (with or without arguments) that go with any alias. 710 CommandHistory m_command_history; 711 std::string m_repeat_command; // Stores the command that will be executed for an empty command string. 712 std::unique_ptr<ScriptInterpreter> m_script_interpreter_ap; 713 lldb::IOHandlerSP m_command_io_handler_sp; 714 char m_comment_char; 715 bool m_batch_command_mode; 716 ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated children and whether the user has been told 717 uint32_t m_command_source_depth; 718 std::vector<uint32_t> m_command_source_flags; 719 uint32_t m_num_errors; 720 bool m_quit_requested; 721 bool m_stopped_for_crash; 722 723 }; 724 725 726 } // namespace lldb_private 727 728 #endif // liblldb_CommandInterpreter_h_ 729