1 //===-- CommandObjectSource.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommandObjectCommands.h"
14 // Other libraries and framework includes
15 #include "llvm/ADT/StringRef.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/IOHandler.h"
20 #include "lldb/Core/StringList.h"
21 #include "lldb/Interpreter/Args.h"
22 #include "lldb/Interpreter/CommandHistory.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
25 #include "lldb/Interpreter/CommandReturnObject.h"
26 #include "lldb/Interpreter/OptionValueBoolean.h"
27 #include "lldb/Interpreter/OptionValueUInt64.h"
28 #include "lldb/Interpreter/Options.h"
29 #include "lldb/Interpreter/ScriptInterpreter.h"
32 using namespace lldb_private;
34 //-------------------------------------------------------------------------
35 // CommandObjectCommandsSource
36 //-------------------------------------------------------------------------
38 class CommandObjectCommandsHistory : public CommandObjectParsed
41 CommandObjectCommandsHistory(CommandInterpreter &interpreter) :
42 CommandObjectParsed (interpreter,
44 "Dump the history of commands in this session.",
46 m_options (interpreter)
50 ~CommandObjectCommandsHistory () override {}
53 GetOptions () override
60 class CommandOptions : public Options
64 CommandOptions (CommandInterpreter &interpreter) :
65 Options (interpreter),
73 ~CommandOptions () override {}
76 SetOptionValue (uint32_t option_idx, const char *option_arg) override
79 const int short_option = m_getopt_table[option_idx].val;
84 error = m_count.SetValueFromString(option_arg,eVarSetOperationAssign);
87 if (option_arg && strcmp("end", option_arg) == 0)
89 m_start_idx.SetCurrentValue(UINT64_MAX);
90 m_start_idx.SetOptionWasSet();
93 error = m_start_idx.SetValueFromString(option_arg,eVarSetOperationAssign);
96 error = m_stop_idx.SetValueFromString(option_arg,eVarSetOperationAssign);
99 m_clear.SetCurrentValue(true);
100 m_clear.SetOptionWasSet();
103 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
111 OptionParsingStarting () override
119 const OptionDefinition*
120 GetDefinitions () override
122 return g_option_table;
125 // Options table: Required for subclasses of Options.
127 static OptionDefinition g_option_table[];
129 // Instance variables to hold the values for command options.
131 OptionValueUInt64 m_start_idx;
132 OptionValueUInt64 m_stop_idx;
133 OptionValueUInt64 m_count;
134 OptionValueBoolean m_clear;
138 DoExecute (Args& command, CommandReturnObject &result) override
140 if (m_options.m_clear.GetCurrentValue() && m_options.m_clear.OptionWasSet())
142 m_interpreter.GetCommandHistory().Clear();
143 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
147 if (m_options.m_start_idx.OptionWasSet() && m_options.m_stop_idx.OptionWasSet() && m_options.m_count.OptionWasSet())
149 result.AppendError("--count, --start-index and --end-index cannot be all specified in the same invocation");
150 result.SetStatus(lldb::eReturnStatusFailed);
154 std::pair<bool,uint64_t> start_idx(m_options.m_start_idx.OptionWasSet(),m_options.m_start_idx.GetCurrentValue());
155 std::pair<bool,uint64_t> stop_idx(m_options.m_stop_idx.OptionWasSet(),m_options.m_stop_idx.GetCurrentValue());
156 std::pair<bool,uint64_t> count(m_options.m_count.OptionWasSet(),m_options.m_count.GetCurrentValue());
158 const CommandHistory& history(m_interpreter.GetCommandHistory());
160 if (start_idx.first && start_idx.second == UINT64_MAX)
164 start_idx.second = history.GetSize() - count.second;
165 stop_idx.second = history.GetSize() - 1;
167 else if (stop_idx.first)
169 start_idx.second = stop_idx.second;
170 stop_idx.second = history.GetSize() - 1;
174 start_idx.second = 0;
175 stop_idx.second = history.GetSize() - 1;
180 if (!start_idx.first && !stop_idx.first && !count.first)
182 start_idx.second = 0;
183 stop_idx.second = history.GetSize() - 1;
185 else if (start_idx.first)
189 stop_idx.second = start_idx.second + count.second - 1;
191 else if (!stop_idx.first)
193 stop_idx.second = history.GetSize() - 1;
196 else if (stop_idx.first)
200 if (stop_idx.second >= count.second)
201 start_idx.second = stop_idx.second - count.second + 1;
203 start_idx.second = 0;
206 else /* if (count.first) */
208 start_idx.second = 0;
209 stop_idx.second = count.second - 1;
212 history.Dump(result.GetOutputStream(), start_idx.second, stop_idx.second);
215 return result.Succeeded();
219 CommandOptions m_options;
223 CommandObjectCommandsHistory::CommandOptions::g_option_table[] =
225 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, "How many history commands to print."},
226 { LLDB_OPT_SET_1, false, "start-index", 's', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, "Index at which to start printing history commands (or end to mean tail mode)."},
227 { LLDB_OPT_SET_1, false, "end-index", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands."},
228 { LLDB_OPT_SET_2, false, "clear", 'C', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeBoolean, "Clears the current command history."},
229 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
233 //-------------------------------------------------------------------------
234 // CommandObjectCommandsSource
235 //-------------------------------------------------------------------------
237 class CommandObjectCommandsSource : public CommandObjectParsed
240 CommandObjectCommandsSource(CommandInterpreter &interpreter) :
241 CommandObjectParsed (interpreter,
243 "Read in debugger commands from the file <filename> and execute them.",
245 m_options (interpreter)
247 CommandArgumentEntry arg;
248 CommandArgumentData file_arg;
250 // Define the first (and only) variant of this arg.
251 file_arg.arg_type = eArgTypeFilename;
252 file_arg.arg_repetition = eArgRepeatPlain;
254 // There is only one variant this argument could be; put it into the argument entry.
255 arg.push_back (file_arg);
257 // Push the data for the first argument into the m_arguments vector.
258 m_arguments.push_back (arg);
261 ~CommandObjectCommandsSource () override {}
264 GetRepeatCommand (Args ¤t_command_args, uint32_t index) override
270 HandleArgumentCompletion (Args &input,
272 int &cursor_char_position,
273 OptionElementVector &opt_element_vector,
274 int match_start_point,
275 int max_return_elements,
277 StringList &matches) override
279 std::string completion_str (input.GetArgumentAtIndex(cursor_index));
280 completion_str.erase (cursor_char_position);
282 CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
283 CommandCompletions::eDiskFileCompletion,
284 completion_str.c_str(),
290 return matches.GetSize();
294 GetOptions () override
301 class CommandOptions : public Options
305 CommandOptions (CommandInterpreter &interpreter) :
306 Options (interpreter),
307 m_stop_on_error (true),
308 m_silent_run (false),
309 m_stop_on_continue (true)
313 ~CommandOptions () override {}
316 SetOptionValue (uint32_t option_idx, const char *option_arg) override
319 const int short_option = m_getopt_table[option_idx].val;
321 switch (short_option)
324 error = m_stop_on_error.SetValueFromString(option_arg);
328 error = m_stop_on_continue.SetValueFromString(option_arg);
332 error = m_silent_run.SetValueFromString(option_arg);
336 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
344 OptionParsingStarting () override
346 m_stop_on_error.Clear();
347 m_silent_run.Clear();
348 m_stop_on_continue.Clear();
351 const OptionDefinition*
352 GetDefinitions () override
354 return g_option_table;
357 // Options table: Required for subclasses of Options.
359 static OptionDefinition g_option_table[];
361 // Instance variables to hold the values for command options.
363 OptionValueBoolean m_stop_on_error;
364 OptionValueBoolean m_silent_run;
365 OptionValueBoolean m_stop_on_continue;
369 DoExecute(Args& command, CommandReturnObject &result) override
371 const size_t argc = command.GetArgumentCount();
374 const char *filename = command.GetArgumentAtIndex(0);
376 FileSpec cmd_file (filename, true);
377 ExecutionContext *exe_ctx = NULL; // Just use the default context.
379 // If any options were set, then use them
380 if (m_options.m_stop_on_error.OptionWasSet() ||
381 m_options.m_silent_run.OptionWasSet() ||
382 m_options.m_stop_on_continue.OptionWasSet())
384 // Use user set settings
385 CommandInterpreterRunOptions options;
386 options.SetStopOnContinue(m_options.m_stop_on_continue.GetCurrentValue());
387 options.SetStopOnError (m_options.m_stop_on_error.GetCurrentValue());
388 options.SetEchoCommands (!m_options.m_silent_run.GetCurrentValue());
389 options.SetPrintResults (!m_options.m_silent_run.GetCurrentValue());
391 m_interpreter.HandleCommandsFromFile (cmd_file,
399 // No options were set, inherit any settings from nested "command source" commands,
400 // or set to sane default settings...
401 CommandInterpreterRunOptions options;
402 m_interpreter.HandleCommandsFromFile (cmd_file,
411 result.AppendErrorWithFormat("'%s' takes exactly one executable filename argument.\n", GetCommandName());
412 result.SetStatus (eReturnStatusFailed);
414 return result.Succeeded();
417 CommandOptions m_options;
421 CommandObjectCommandsSource::CommandOptions::g_option_table[] =
423 { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "If true, stop executing commands on error."},
424 { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "If true, stop executing commands on continue."},
425 { LLDB_OPT_SET_ALL, false, "silent-run", 's', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "If true don't echo commands while executing."},
426 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
429 #pragma mark CommandObjectCommandsAlias
430 //-------------------------------------------------------------------------
431 // CommandObjectCommandsAlias
432 //-------------------------------------------------------------------------
434 static const char *g_python_command_instructions = "Enter your Python command(s). Type 'DONE' to end.\n"
435 "You must define a Python function with this signature:\n"
436 "def my_command_impl(debugger, args, result, internal_dict):\n";
439 class CommandObjectCommandsAlias : public CommandObjectRaw
444 CommandObjectCommandsAlias (CommandInterpreter &interpreter) :
445 CommandObjectRaw (interpreter,
447 "Allow users to define their own debugger command abbreviations.",
451 "'alias' allows the user to create a short-cut or abbreviation for long \
452 commands, multi-word commands, and commands that take particular options. \
453 Below are some simple examples of how one might use the 'alias' command:" R"(
455 (lldb) command alias sc script
457 Creates the abbreviation 'sc' for the 'script' command.
459 (lldb) command alias bp breakpoint
461 )" " Creates the abbreviation 'bp' for the 'breakpoint' command. Since \
462 breakpoint commands are two-word commands, the user would still need to \
463 enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'." R"(
465 (lldb) command alias bpl breakpoint list
467 Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
469 )" "An alias can include some options for the command, with the values either \
470 filled in at the time the alias is created, or specified as positional \
471 arguments, to be filled in when the alias is invoked. The following example \
472 shows how to create aliases with options:" R"(
474 (lldb) command alias bfl breakpoint set -f %1 -l %2
476 )" " Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
477 options already part of the alias. So if the user wants to set a breakpoint \
478 by file and line without explicitly having to use the -f and -l options, the \
479 user can now use 'bfl' instead. The '%1' and '%2' are positional placeholders \
480 for the actual arguments that will be passed when the alias command is used. \
481 The number in the placeholder refers to the position/order the actual value \
482 occupies when the alias is used. All the occurrences of '%1' in the alias \
483 will be replaced with the first argument, all the occurrences of '%2' in the \
484 alias will be replaced with the second argument, and so on. This also allows \
485 actual arguments to be used multiple times within an alias (see 'process \
486 launch' example below)." R"(
488 )" "Note: the positional arguments must substitute as whole words in the resultant \
489 command, so you can't at present do something like this to append the file extension \
492 (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
494 )" "For more complex aliasing, use the \"command regex\" command instead. In the \
495 'bfl' case above, the actual file value will be filled in with the first argument \
496 following 'bfl' and the actual line number value will be filled in with the second \
497 argument. The user would use this alias as follows:" R"(
499 (lldb) command alias bfl breakpoint set -f %1 -l %2
500 (lldb) bfl my-file.c 137
502 This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
506 (lldb) command alias pltty process launch -s -o %1 -e %1
507 (lldb) pltty /dev/tty0
509 Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
511 )" "If the user always wanted to pass the same value to a particular option, the \
512 alias could be defined with that value directly in the alias as a constant, \
513 rather than using a positional placeholder:" R"(
515 (lldb) command alias bl3 breakpoint set -f %1 -l 3
517 Always sets a breakpoint on line 3 of whatever file is indicated.)"
520 CommandArgumentEntry arg1;
521 CommandArgumentEntry arg2;
522 CommandArgumentEntry arg3;
523 CommandArgumentData alias_arg;
524 CommandArgumentData cmd_arg;
525 CommandArgumentData options_arg;
527 // Define the first (and only) variant of this arg.
528 alias_arg.arg_type = eArgTypeAliasName;
529 alias_arg.arg_repetition = eArgRepeatPlain;
531 // There is only one variant this argument could be; put it into the argument entry.
532 arg1.push_back (alias_arg);
534 // Define the first (and only) variant of this arg.
535 cmd_arg.arg_type = eArgTypeCommandName;
536 cmd_arg.arg_repetition = eArgRepeatPlain;
538 // There is only one variant this argument could be; put it into the argument entry.
539 arg2.push_back (cmd_arg);
541 // Define the first (and only) variant of this arg.
542 options_arg.arg_type = eArgTypeAliasOptions;
543 options_arg.arg_repetition = eArgRepeatOptional;
545 // There is only one variant this argument could be; put it into the argument entry.
546 arg3.push_back (options_arg);
548 // Push the data for the first argument into the m_arguments vector.
549 m_arguments.push_back (arg1);
550 m_arguments.push_back (arg2);
551 m_arguments.push_back (arg3);
554 ~CommandObjectCommandsAlias () override
560 DoExecute (const char *raw_command_line, CommandReturnObject &result) override
562 Args args (raw_command_line);
563 std::string raw_command_string (raw_command_line);
565 size_t argc = args.GetArgumentCount();
569 result.AppendError ("'alias' requires at least two arguments");
570 result.SetStatus (eReturnStatusFailed);
574 // Get the alias command.
576 const std::string alias_command = args.GetArgumentAtIndex (0);
578 // Strip the new alias name off 'raw_command_string' (leave it on args, which gets passed to 'Execute', which
579 // does the stripping itself.
580 size_t pos = raw_command_string.find (alias_command);
583 raw_command_string = raw_command_string.substr (alias_command.size());
584 pos = raw_command_string.find_first_not_of (' ');
585 if ((pos != std::string::npos) && (pos > 0))
586 raw_command_string = raw_command_string.substr (pos);
590 result.AppendError ("Error parsing command string. No alias created.");
591 result.SetStatus (eReturnStatusFailed);
596 // Verify that the command is alias-able.
597 if (m_interpreter.CommandExists (alias_command.c_str()))
599 result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be redefined.\n",
600 alias_command.c_str());
601 result.SetStatus (eReturnStatusFailed);
605 // Get CommandObject that is being aliased. The command name is read from the front of raw_command_string.
606 // raw_command_string is returned with the name of the command object stripped off the front.
607 CommandObject *cmd_obj = m_interpreter.GetCommandObjectForCommand (raw_command_string);
611 result.AppendErrorWithFormat ("invalid command given to 'alias'. '%s' does not begin with a valid command."
612 " No alias created.", raw_command_string.c_str());
613 result.SetStatus (eReturnStatusFailed);
616 else if (!cmd_obj->WantsRawCommandString ())
618 // Note that args was initialized with the original command, and has not been updated to this point.
619 // Therefore can we pass it to the version of Execute that does not need/expect raw input in the alias.
620 return HandleAliasingNormalCommand (args, result);
624 return HandleAliasingRawCommand (alias_command, raw_command_string, *cmd_obj, result);
626 return result.Succeeded();
630 HandleAliasingRawCommand (const std::string &alias_command, std::string &raw_command_string, CommandObject &cmd_obj, CommandReturnObject &result)
632 // Verify & handle any options/arguments passed to the alias command
634 OptionArgVectorSP option_arg_vector_sp = OptionArgVectorSP (new OptionArgVector);
635 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
637 CommandObjectSP cmd_obj_sp = m_interpreter.GetCommandSPExact (cmd_obj.GetCommandName(), false);
639 if (!m_interpreter.ProcessAliasOptionsArgs (cmd_obj_sp, raw_command_string.c_str(), option_arg_vector_sp))
641 result.AppendError ("Unable to create requested alias.\n");
642 result.SetStatus (eReturnStatusFailed);
647 if (m_interpreter.AliasExists (alias_command.c_str())
648 || m_interpreter.UserCommandExists (alias_command.c_str()))
650 OptionArgVectorSP temp_option_arg_sp (m_interpreter.GetAliasOptions (alias_command.c_str()));
651 if (temp_option_arg_sp.get())
653 if (option_arg_vector->size() == 0)
654 m_interpreter.RemoveAliasOptions (alias_command.c_str());
656 result.AppendWarningWithFormat ("Overwriting existing definition for '%s'.\n",
657 alias_command.c_str());
662 m_interpreter.AddAlias (alias_command.c_str(), cmd_obj_sp);
663 if (option_arg_vector->size() > 0)
664 m_interpreter.AddOrReplaceAliasOptions (alias_command.c_str(), option_arg_vector_sp);
665 result.SetStatus (eReturnStatusSuccessFinishNoResult);
669 result.AppendError ("Unable to create requested alias.\n");
670 result.SetStatus (eReturnStatusFailed);
672 return result.Succeeded ();
676 HandleAliasingNormalCommand (Args& args, CommandReturnObject &result)
678 size_t argc = args.GetArgumentCount();
682 result.AppendError ("'alias' requires at least two arguments");
683 result.SetStatus (eReturnStatusFailed);
687 const std::string alias_command = args.GetArgumentAtIndex(0);
688 const std::string actual_command = args.GetArgumentAtIndex(1);
690 args.Shift(); // Shift the alias command word off the argument vector.
691 args.Shift(); // Shift the old command word off the argument vector.
693 // Verify that the command is alias'able, and get the appropriate command object.
695 if (m_interpreter.CommandExists (alias_command.c_str()))
697 result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be redefined.\n",
698 alias_command.c_str());
699 result.SetStatus (eReturnStatusFailed);
703 CommandObjectSP command_obj_sp(m_interpreter.GetCommandSPExact (actual_command.c_str(), true));
704 CommandObjectSP subcommand_obj_sp;
705 bool use_subcommand = false;
706 if (command_obj_sp.get())
708 CommandObject *cmd_obj = command_obj_sp.get();
709 CommandObject *sub_cmd_obj = NULL;
710 OptionArgVectorSP option_arg_vector_sp = OptionArgVectorSP (new OptionArgVector);
711 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
713 while (cmd_obj->IsMultiwordObject() && args.GetArgumentCount() > 0)
717 const std::string sub_command = args.GetArgumentAtIndex(0);
718 assert (sub_command.length() != 0);
719 subcommand_obj_sp = cmd_obj->GetSubcommandSP (sub_command.c_str());
720 if (subcommand_obj_sp.get())
722 sub_cmd_obj = subcommand_obj_sp.get();
723 use_subcommand = true;
724 args.Shift(); // Shift the sub_command word off the argument vector.
725 cmd_obj = sub_cmd_obj;
729 result.AppendErrorWithFormat("'%s' is not a valid sub-command of '%s'. "
730 "Unable to create alias.\n",
731 sub_command.c_str(), actual_command.c_str());
732 result.SetStatus (eReturnStatusFailed);
738 // Verify & handle any options/arguments passed to the alias command
740 if (args.GetArgumentCount () > 0)
742 CommandObjectSP tmp_sp = m_interpreter.GetCommandSPExact (cmd_obj->GetCommandName(), false);
744 tmp_sp = m_interpreter.GetCommandSPExact (sub_cmd_obj->GetCommandName(), false);
746 std::string args_string;
747 args.GetCommandString (args_string);
749 if (!m_interpreter.ProcessAliasOptionsArgs (tmp_sp, args_string.c_str(), option_arg_vector_sp))
751 result.AppendError ("Unable to create requested alias.\n");
752 result.SetStatus (eReturnStatusFailed);
759 if (m_interpreter.AliasExists (alias_command.c_str())
760 || m_interpreter.UserCommandExists (alias_command.c_str()))
762 OptionArgVectorSP tmp_option_arg_sp (m_interpreter.GetAliasOptions (alias_command.c_str()));
763 if (tmp_option_arg_sp.get())
765 if (option_arg_vector->size() == 0)
766 m_interpreter.RemoveAliasOptions (alias_command.c_str());
768 result.AppendWarningWithFormat ("Overwriting existing definition for '%s'.\n",
769 alias_command.c_str());
773 m_interpreter.AddAlias (alias_command.c_str(), subcommand_obj_sp);
775 m_interpreter.AddAlias (alias_command.c_str(), command_obj_sp);
776 if (option_arg_vector->size() > 0)
777 m_interpreter.AddOrReplaceAliasOptions (alias_command.c_str(), option_arg_vector_sp);
778 result.SetStatus (eReturnStatusSuccessFinishNoResult);
782 result.AppendErrorWithFormat ("'%s' is not an existing command.\n", actual_command.c_str());
783 result.SetStatus (eReturnStatusFailed);
788 return result.Succeeded();
793 #pragma mark CommandObjectCommandsUnalias
794 //-------------------------------------------------------------------------
795 // CommandObjectCommandsUnalias
796 //-------------------------------------------------------------------------
798 class CommandObjectCommandsUnalias : public CommandObjectParsed
801 CommandObjectCommandsUnalias (CommandInterpreter &interpreter) :
802 CommandObjectParsed (interpreter,
804 "Allow the user to remove/delete a user-defined command abbreviation.",
807 CommandArgumentEntry arg;
808 CommandArgumentData alias_arg;
810 // Define the first (and only) variant of this arg.
811 alias_arg.arg_type = eArgTypeAliasName;
812 alias_arg.arg_repetition = eArgRepeatPlain;
814 // There is only one variant this argument could be; put it into the argument entry.
815 arg.push_back (alias_arg);
817 // Push the data for the first argument into the m_arguments vector.
818 m_arguments.push_back (arg);
821 ~CommandObjectCommandsUnalias() override
827 DoExecute (Args& args, CommandReturnObject &result) override
829 CommandObject::CommandMap::iterator pos;
830 CommandObject *cmd_obj;
832 if (args.GetArgumentCount() != 0)
834 const char *command_name = args.GetArgumentAtIndex(0);
835 cmd_obj = m_interpreter.GetCommandObject(command_name);
838 if (m_interpreter.CommandExists (command_name))
840 if (cmd_obj->IsRemovable())
842 result.AppendErrorWithFormat ("'%s' is not an alias, it is a debugger command which can be removed using the 'command delete' command.\n",
847 result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be removed.\n",
850 result.SetStatus (eReturnStatusFailed);
855 if (m_interpreter.RemoveAlias (command_name) == false)
857 if (m_interpreter.AliasExists (command_name))
858 result.AppendErrorWithFormat ("Error occurred while attempting to unalias '%s'.\n",
861 result.AppendErrorWithFormat ("'%s' is not an existing alias.\n", command_name);
862 result.SetStatus (eReturnStatusFailed);
865 result.SetStatus (eReturnStatusSuccessFinishNoResult);
870 result.AppendErrorWithFormat ("'%s' is not a known command.\nTry 'help' to see a "
871 "current list of commands.\n",
873 result.SetStatus (eReturnStatusFailed);
878 result.AppendError ("must call 'unalias' with a valid alias");
879 result.SetStatus (eReturnStatusFailed);
882 return result.Succeeded();
886 #pragma mark CommandObjectCommandsDelete
887 //-------------------------------------------------------------------------
888 // CommandObjectCommandsDelete
889 //-------------------------------------------------------------------------
891 class CommandObjectCommandsDelete : public CommandObjectParsed
894 CommandObjectCommandsDelete (CommandInterpreter &interpreter) :
895 CommandObjectParsed (interpreter,
897 "Allow the user to delete user-defined regular expression, python or multi-word commands.",
900 CommandArgumentEntry arg;
901 CommandArgumentData alias_arg;
903 // Define the first (and only) variant of this arg.
904 alias_arg.arg_type = eArgTypeCommandName;
905 alias_arg.arg_repetition = eArgRepeatPlain;
907 // There is only one variant this argument could be; put it into the argument entry.
908 arg.push_back (alias_arg);
910 // Push the data for the first argument into the m_arguments vector.
911 m_arguments.push_back (arg);
914 ~CommandObjectCommandsDelete() override
920 DoExecute (Args& args, CommandReturnObject &result) override
922 CommandObject::CommandMap::iterator pos;
924 if (args.GetArgumentCount() != 0)
926 const char *command_name = args.GetArgumentAtIndex(0);
927 if (m_interpreter.CommandExists (command_name))
929 if (m_interpreter.RemoveCommand (command_name))
931 result.SetStatus (eReturnStatusSuccessFinishNoResult);
935 result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be removed.\n",
937 result.SetStatus (eReturnStatusFailed);
942 result.AppendErrorWithFormat ("'%s' is not a known command.\nTry 'help' to see a current list of commands.\n",
944 result.SetStatus (eReturnStatusFailed);
949 result.AppendErrorWithFormat ("must call '%s' with one or more valid user defined regular expression, python or multi-word command names", GetCommandName ());
950 result.SetStatus (eReturnStatusFailed);
953 return result.Succeeded();
957 //-------------------------------------------------------------------------
958 // CommandObjectCommandsAddRegex
959 //-------------------------------------------------------------------------
960 #pragma mark CommandObjectCommandsAddRegex
962 class CommandObjectCommandsAddRegex :
963 public CommandObjectParsed,
964 public IOHandlerDelegateMultiline
967 CommandObjectCommandsAddRegex (CommandInterpreter &interpreter) :
968 CommandObjectParsed (interpreter,
970 "Allow the user to create a regular expression command.",
971 "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
972 IOHandlerDelegateMultiline ("", IOHandlerDelegate::Completion::LLDBCommand),
973 m_options (interpreter)
976 )" "This command allows the user to create powerful regular expression commands \
977 with substitutions. The regular expressions and substitutions are specified \
978 using the regular expression substitution format of:" R"(
982 )" "<regex> is a regular expression that can use parenthesis to capture regular \
983 expression input and substitute the captured matches in the output using %1 \
984 for the first match, %2 for the second, and so on." R"(
986 )" "The regular expressions can all be specified on the command line if more than \
987 one argument is provided. If just the command name is provided on the command \
988 line, then the regular expressions and substitutions can be entered on separate \
989 lines, followed by an empty line to terminate the command definition." R"(
993 )" "The following example will define a regular expression command named 'f' that \
994 will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
995 a number follows 'f':" R"(
997 (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')"
1001 ~CommandObjectCommandsAddRegex() override
1009 IOHandlerActivated (IOHandler &io_handler) override
1011 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1014 output_sp->PutCString("Enter one of more sed substitution commands in the form: 's/<regex>/<subst>/'.\nTerminate the substitution list with an empty line.\n");
1020 IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override
1022 io_handler.SetIsDone(true);
1023 if (m_regex_cmd_ap.get())
1026 if (lines.SplitIntoLines (data))
1028 const size_t num_lines = lines.GetSize();
1029 bool check_only = false;
1030 for (size_t i=0; i<num_lines; ++i)
1032 llvm::StringRef bytes_strref (lines[i]);
1033 Error error = AppendRegexSubstitution (bytes_strref, check_only);
1036 if (!m_interpreter.GetDebugger().GetCommandInterpreter().GetBatchCommandMode())
1038 StreamSP out_stream = m_interpreter.GetDebugger().GetAsyncOutputStream();
1039 out_stream->Printf("error: %s\n", error.AsCString());
1044 if (m_regex_cmd_ap->HasRegexEntries())
1046 CommandObjectSP cmd_sp (m_regex_cmd_ap.release());
1047 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1053 DoExecute (Args& command, CommandReturnObject &result) override
1055 const size_t argc = command.GetArgumentCount();
1058 result.AppendError ("usage: 'command regex <command-name> [s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
1059 result.SetStatus (eReturnStatusFailed);
1064 const char *name = command.GetArgumentAtIndex(0);
1065 m_regex_cmd_ap.reset (new CommandObjectRegexCommand (m_interpreter,
1067 m_options.GetHelp (),
1068 m_options.GetSyntax (),
1075 Debugger &debugger = m_interpreter.GetDebugger();
1076 bool color_prompt = debugger.GetUseColor();
1077 const bool multiple_lines = true; // Get multiple lines
1078 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
1079 IOHandler::Type::Other,
1080 "lldb-regex", // Name of input reader for history
1082 NULL, // Continuation prompt
1085 0, // Don't show line numbers
1090 debugger.PushIOHandler(io_handler_sp);
1091 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1096 for (size_t arg_idx = 1; arg_idx < argc; ++arg_idx)
1098 llvm::StringRef arg_strref (command.GetArgumentAtIndex(arg_idx));
1099 bool check_only = false;
1100 error = AppendRegexSubstitution (arg_strref, check_only);
1105 if (error.Success())
1107 AddRegexCommandToInterpreter();
1112 result.AppendError (error.AsCString());
1113 result.SetStatus (eReturnStatusFailed);
1117 return result.Succeeded();
1121 AppendRegexSubstitution (const llvm::StringRef ®ex_sed, bool check_only)
1125 if (m_regex_cmd_ap.get() == NULL)
1127 error.SetErrorStringWithFormat("invalid regular expression command object for: '%.*s'",
1128 (int)regex_sed.size(),
1133 size_t regex_sed_size = regex_sed.size();
1135 if (regex_sed_size <= 1)
1137 error.SetErrorStringWithFormat("regular expression substitution string is too short: '%.*s'",
1138 (int)regex_sed.size(),
1143 if (regex_sed[0] != 's')
1145 error.SetErrorStringWithFormat("regular expression substitution string doesn't start with 's': '%.*s'",
1146 (int)regex_sed.size(),
1150 const size_t first_separator_char_pos = 1;
1151 // use the char that follows 's' as the regex separator character
1152 // so we can have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
1153 const char separator_char = regex_sed[first_separator_char_pos];
1154 const size_t second_separator_char_pos = regex_sed.find (separator_char, first_separator_char_pos + 1);
1156 if (second_separator_char_pos == std::string::npos)
1158 error.SetErrorStringWithFormat("missing second '%c' separator char after '%.*s' in '%.*s'",
1160 (int)(regex_sed.size() - first_separator_char_pos - 1),
1161 regex_sed.data() + (first_separator_char_pos + 1),
1162 (int)regex_sed.size(),
1167 const size_t third_separator_char_pos = regex_sed.find (separator_char, second_separator_char_pos + 1);
1169 if (third_separator_char_pos == std::string::npos)
1171 error.SetErrorStringWithFormat("missing third '%c' separator char after '%.*s' in '%.*s'",
1173 (int)(regex_sed.size() - second_separator_char_pos - 1),
1174 regex_sed.data() + (second_separator_char_pos + 1),
1175 (int)regex_sed.size(),
1180 if (third_separator_char_pos != regex_sed_size - 1)
1182 // Make sure that everything that follows the last regex
1184 if (regex_sed.find_first_not_of("\t\n\v\f\r ", third_separator_char_pos + 1) != std::string::npos)
1186 error.SetErrorStringWithFormat("extra data found after the '%.*s' regular expression substitution string: '%.*s'",
1187 (int)third_separator_char_pos + 1,
1189 (int)(regex_sed.size() - third_separator_char_pos - 1),
1190 regex_sed.data() + (third_separator_char_pos + 1));
1195 else if (first_separator_char_pos + 1 == second_separator_char_pos)
1197 error.SetErrorStringWithFormat("<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1201 (int)regex_sed.size(),
1205 else if (second_separator_char_pos + 1 == third_separator_char_pos)
1207 error.SetErrorStringWithFormat("<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1211 (int)regex_sed.size(),
1216 if (check_only == false)
1218 std::string regex(regex_sed.substr(first_separator_char_pos + 1, second_separator_char_pos - first_separator_char_pos - 1));
1219 std::string subst(regex_sed.substr(second_separator_char_pos + 1, third_separator_char_pos - second_separator_char_pos - 1));
1220 m_regex_cmd_ap->AddRegexCommand (regex.c_str(),
1227 AddRegexCommandToInterpreter()
1229 if (m_regex_cmd_ap.get())
1231 if (m_regex_cmd_ap->HasRegexEntries())
1233 CommandObjectSP cmd_sp (m_regex_cmd_ap.release());
1234 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1240 std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap;
1242 class CommandOptions : public Options
1246 CommandOptions (CommandInterpreter &interpreter) :
1247 Options (interpreter)
1251 ~CommandOptions () override {}
1254 SetOptionValue (uint32_t option_idx, const char *option_arg) override
1257 const int short_option = m_getopt_table[option_idx].val;
1259 switch (short_option)
1262 m_help.assign (option_arg);
1265 m_syntax.assign (option_arg);
1269 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1277 OptionParsingStarting () override
1283 const OptionDefinition*
1284 GetDefinitions () override
1286 return g_option_table;
1289 // Options table: Required for subclasses of Options.
1291 static OptionDefinition g_option_table[];
1298 return m_help.c_str();
1303 if (m_syntax.empty())
1305 return m_syntax.c_str();
1307 // Instance variables to hold the values for command options.
1310 std::string m_syntax;
1314 GetOptions () override
1319 CommandOptions m_options;
1323 CommandObjectCommandsAddRegex::CommandOptions::g_option_table[] =
1325 { LLDB_OPT_SET_1, false, "help" , 'h', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "The help text to display for this command."},
1326 { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "A syntax string showing the typical usage syntax."},
1327 { 0 , false, NULL , 0 , 0 , NULL, NULL, 0, eArgTypeNone, NULL }
1331 class CommandObjectPythonFunction : public CommandObjectRaw
1334 std::string m_function_name;
1335 ScriptedCommandSynchronicity m_synchro;
1336 bool m_fetched_help_long;
1340 CommandObjectPythonFunction (CommandInterpreter &interpreter,
1344 ScriptedCommandSynchronicity synch) :
1345 CommandObjectRaw (interpreter,
1349 m_function_name(funct),
1351 m_fetched_help_long(false)
1354 SetHelp(help.c_str());
1357 StreamString stream;
1358 stream.Printf("For more information run 'help %s'",name.c_str());
1359 SetHelp(stream.GetData());
1363 ~CommandObjectPythonFunction () override
1368 IsRemovable () const override
1376 return m_function_name;
1379 ScriptedCommandSynchronicity
1386 GetHelpLong () override
1388 if (!m_fetched_help_long)
1390 ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter();
1393 std::string docstring;
1394 m_fetched_help_long = scripter->GetDocumentationForItem(m_function_name.c_str(),docstring);
1395 if (!docstring.empty())
1396 SetHelpLong(docstring);
1399 return CommandObjectRaw::GetHelpLong();
1404 DoExecute (const char *raw_command_line, CommandReturnObject &result) override
1406 ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter();
1410 result.SetStatus(eReturnStatusInvalid);
1412 if (!scripter || scripter->RunScriptBasedCommand(m_function_name.c_str(),
1417 m_exe_ctx) == false)
1419 result.AppendError(error.AsCString());
1420 result.SetStatus(eReturnStatusFailed);
1424 // Don't change the status if the command already set it...
1425 if (result.GetStatus() == eReturnStatusInvalid)
1427 if (result.GetOutputData() == NULL || result.GetOutputData()[0] == '\0')
1428 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1430 result.SetStatus(eReturnStatusSuccessFinishResult);
1434 return result.Succeeded();
1439 class CommandObjectScriptingObject : public CommandObjectRaw
1442 StructuredData::GenericSP m_cmd_obj_sp;
1443 ScriptedCommandSynchronicity m_synchro;
1444 bool m_fetched_help_short:1;
1445 bool m_fetched_help_long:1;
1449 CommandObjectScriptingObject (CommandInterpreter &interpreter,
1451 StructuredData::GenericSP cmd_obj_sp,
1452 ScriptedCommandSynchronicity synch) :
1453 CommandObjectRaw (interpreter,
1457 m_cmd_obj_sp(cmd_obj_sp),
1459 m_fetched_help_short(false),
1460 m_fetched_help_long(false)
1462 StreamString stream;
1463 stream.Printf("For more information run 'help %s'",name.c_str());
1464 SetHelp(stream.GetData());
1465 if (ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter())
1466 GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
1469 ~CommandObjectScriptingObject () override
1474 IsRemovable () const override
1479 StructuredData::GenericSP
1480 GetImplementingObject ()
1482 return m_cmd_obj_sp;
1485 ScriptedCommandSynchronicity
1494 if (!m_fetched_help_short)
1496 ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter();
1499 std::string docstring;
1500 m_fetched_help_short = scripter->GetShortHelpForCommandObject(m_cmd_obj_sp,docstring);
1501 if (!docstring.empty())
1505 return CommandObjectRaw::GetHelp();
1509 GetHelpLong () override
1511 if (!m_fetched_help_long)
1513 ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter();
1516 std::string docstring;
1517 m_fetched_help_long = scripter->GetLongHelpForCommandObject(m_cmd_obj_sp,docstring);
1518 if (!docstring.empty())
1519 SetHelpLong(docstring);
1522 return CommandObjectRaw::GetHelpLong();
1527 DoExecute (const char *raw_command_line, CommandReturnObject &result) override
1529 ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter();
1533 result.SetStatus(eReturnStatusInvalid);
1535 if (!scripter || scripter->RunScriptBasedCommand(m_cmd_obj_sp,
1540 m_exe_ctx) == false)
1542 result.AppendError(error.AsCString());
1543 result.SetStatus(eReturnStatusFailed);
1547 // Don't change the status if the command already set it...
1548 if (result.GetStatus() == eReturnStatusInvalid)
1550 if (result.GetOutputData() == NULL || result.GetOutputData()[0] == '\0')
1551 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1553 result.SetStatus(eReturnStatusSuccessFinishResult);
1557 return result.Succeeded();
1562 //-------------------------------------------------------------------------
1563 // CommandObjectCommandsScriptImport
1564 //-------------------------------------------------------------------------
1566 class CommandObjectCommandsScriptImport : public CommandObjectParsed
1569 CommandObjectCommandsScriptImport (CommandInterpreter &interpreter) :
1570 CommandObjectParsed (interpreter,
1571 "command script import",
1572 "Import a scripting module in LLDB.",
1574 m_options(interpreter)
1576 CommandArgumentEntry arg1;
1577 CommandArgumentData cmd_arg;
1579 // Define the first (and only) variant of this arg.
1580 cmd_arg.arg_type = eArgTypeFilename;
1581 cmd_arg.arg_repetition = eArgRepeatPlus;
1583 // There is only one variant this argument could be; put it into the argument entry.
1584 arg1.push_back (cmd_arg);
1586 // Push the data for the first argument into the m_arguments vector.
1587 m_arguments.push_back (arg1);
1590 ~CommandObjectCommandsScriptImport () override
1595 HandleArgumentCompletion (Args &input,
1597 int &cursor_char_position,
1598 OptionElementVector &opt_element_vector,
1599 int match_start_point,
1600 int max_return_elements,
1601 bool &word_complete,
1602 StringList &matches) override
1604 std::string completion_str (input.GetArgumentAtIndex(cursor_index));
1605 completion_str.erase (cursor_char_position);
1607 CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
1608 CommandCompletions::eDiskFileCompletion,
1609 completion_str.c_str(),
1611 max_return_elements,
1615 return matches.GetSize();
1619 GetOptions () override
1626 class CommandOptions : public Options
1630 CommandOptions (CommandInterpreter &interpreter) :
1631 Options (interpreter)
1635 ~CommandOptions () override {}
1638 SetOptionValue (uint32_t option_idx, const char *option_arg) override
1641 const int short_option = m_getopt_table[option_idx].val;
1643 switch (short_option)
1646 m_allow_reload = true;
1649 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1657 OptionParsingStarting () override
1659 m_allow_reload = true;
1662 const OptionDefinition*
1663 GetDefinitions () override
1665 return g_option_table;
1668 // Options table: Required for subclasses of Options.
1670 static OptionDefinition g_option_table[];
1672 // Instance variables to hold the values for command options.
1674 bool m_allow_reload;
1678 DoExecute (Args& command, CommandReturnObject &result) override
1680 if (m_interpreter.GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython)
1682 result.AppendError ("only scripting language supported for module importing is currently Python");
1683 result.SetStatus (eReturnStatusFailed);
1687 size_t argc = command.GetArgumentCount();
1690 result.AppendError("command script import needs one or more arguments");
1691 result.SetStatus (eReturnStatusFailed);
1699 std::string path = command.GetArgumentAtIndex(i);
1702 const bool init_session = true;
1703 // FIXME: this is necessary because CommandObject::CheckRequirements() assumes that
1704 // commands won't ever be recursively invoked, but it's actually possible to craft
1705 // a Python script that does other "command script imports" in __lldb_init_module
1706 // the real fix is to have recursive commands possible with a CommandInvocation object
1707 // separate from the CommandObject itself, so that recursive command invocations
1708 // won't stomp on each other (wrt to execution contents, options, and more)
1710 if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(path.c_str(),
1711 m_options.m_allow_reload,
1715 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1719 result.AppendErrorWithFormat("module importing failed: %s", error.AsCString());
1720 result.SetStatus (eReturnStatusFailed);
1724 return result.Succeeded();
1727 CommandOptions m_options;
1731 CommandObjectCommandsScriptImport::CommandOptions::g_option_table[] =
1733 { LLDB_OPT_SET_1, false, "allow-reload", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Allow the script to be loaded even if it was already loaded before. This argument exists for backwards compatibility, but reloading is always allowed, whether you specify it or not."},
1734 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
1738 //-------------------------------------------------------------------------
1739 // CommandObjectCommandsScriptAdd
1740 //-------------------------------------------------------------------------
1742 class CommandObjectCommandsScriptAdd :
1743 public CommandObjectParsed,
1744 public IOHandlerDelegateMultiline
1747 CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter) :
1748 CommandObjectParsed (interpreter,
1749 "command script add",
1750 "Add a scripted function as an LLDB command.",
1752 IOHandlerDelegateMultiline ("DONE"),
1753 m_options (interpreter)
1755 CommandArgumentEntry arg1;
1756 CommandArgumentData cmd_arg;
1758 // Define the first (and only) variant of this arg.
1759 cmd_arg.arg_type = eArgTypeCommandName;
1760 cmd_arg.arg_repetition = eArgRepeatPlain;
1762 // There is only one variant this argument could be; put it into the argument entry.
1763 arg1.push_back (cmd_arg);
1765 // Push the data for the first argument into the m_arguments vector.
1766 m_arguments.push_back (arg1);
1769 ~CommandObjectCommandsScriptAdd () override
1774 GetOptions () override
1781 class CommandOptions : public Options
1785 CommandOptions (CommandInterpreter &interpreter) :
1786 Options (interpreter),
1790 m_synchronicity(eScriptedCommandSynchronicitySynchronous)
1794 ~CommandOptions () override {}
1797 SetOptionValue (uint32_t option_idx, const char *option_arg) override
1800 const int short_option = m_getopt_table[option_idx].val;
1802 switch (short_option)
1806 m_funct_name.assign(option_arg);
1810 m_class_name.assign(option_arg);
1814 m_short_help.assign(option_arg);
1817 m_synchronicity = (ScriptedCommandSynchronicity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
1818 if (!error.Success())
1819 error.SetErrorStringWithFormat ("unrecognized value for synchronicity '%s'", option_arg);
1822 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1830 OptionParsingStarting () override
1832 m_class_name.clear();
1833 m_funct_name.clear();
1834 m_short_help.clear();
1835 m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1838 const OptionDefinition*
1839 GetDefinitions () override
1841 return g_option_table;
1844 // Options table: Required for subclasses of Options.
1846 static OptionDefinition g_option_table[];
1848 // Instance variables to hold the values for command options.
1850 std::string m_class_name;
1851 std::string m_funct_name;
1852 std::string m_short_help;
1853 ScriptedCommandSynchronicity m_synchronicity;
1857 IOHandlerActivated (IOHandler &io_handler) override
1859 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1862 output_sp->PutCString(g_python_command_instructions);
1869 IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override
1871 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
1873 ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter();
1878 lines.SplitIntoLines(data);
1879 if (lines.GetSize() > 0)
1881 std::string funct_name_str;
1882 if (interpreter->GenerateScriptAliasFunction (lines, funct_name_str))
1884 if (funct_name_str.empty())
1886 error_sp->Printf ("error: unable to obtain a function name, didn't add python command.\n");
1891 // everything should be fine now, let's add this alias
1893 CommandObjectSP command_obj_sp(new CommandObjectPythonFunction (m_interpreter,
1895 funct_name_str.c_str(),
1899 if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp, true))
1901 error_sp->Printf ("error: unable to add selected command, didn't add python command.\n");
1908 error_sp->Printf ("error: unable to create function, didn't add python command.\n");
1914 error_sp->Printf ("error: empty function, didn't add python command.\n");
1920 error_sp->Printf ("error: script interpreter missing, didn't add python command.\n");
1924 io_handler.SetIsDone(true);
1931 DoExecute (Args& command, CommandReturnObject &result) override
1934 if (m_interpreter.GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython)
1936 result.AppendError ("only scripting language supported for scripted commands is currently Python");
1937 result.SetStatus (eReturnStatusFailed);
1941 size_t argc = command.GetArgumentCount();
1945 result.AppendError ("'command script add' requires one argument");
1946 result.SetStatus (eReturnStatusFailed);
1950 // Store the options in case we get multi-line input
1951 m_cmd_name = command.GetArgumentAtIndex(0);
1952 m_short_help.assign(m_options.m_short_help);
1953 m_synchronicity = m_options.m_synchronicity;
1955 if (m_options.m_class_name.empty())
1957 if (m_options.m_funct_name.empty())
1959 m_interpreter.GetPythonCommandsFromIOHandler (" ", // Prompt
1960 *this, // IOHandlerDelegate
1961 true, // Run IOHandler in async mode
1962 NULL); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions
1966 CommandObjectSP new_cmd(new CommandObjectPythonFunction(m_interpreter,
1968 m_options.m_funct_name,
1969 m_options.m_short_help,
1971 if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true))
1973 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1977 result.AppendError("cannot add command");
1978 result.SetStatus (eReturnStatusFailed);
1984 ScriptInterpreter *interpreter = GetCommandInterpreter().GetScriptInterpreter();
1987 result.AppendError("cannot find ScriptInterpreter");
1988 result.SetStatus(eReturnStatusFailed);
1992 auto cmd_obj_sp = interpreter->CreateScriptCommandObject(m_options.m_class_name.c_str());
1995 result.AppendError("cannot create helper object");
1996 result.SetStatus(eReturnStatusFailed);
2000 CommandObjectSP new_cmd(new CommandObjectScriptingObject(m_interpreter,
2004 if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true))
2006 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2010 result.AppendError("cannot add command");
2011 result.SetStatus (eReturnStatusFailed);
2015 return result.Succeeded();
2019 CommandOptions m_options;
2020 std::string m_cmd_name;
2021 std::string m_short_help;
2022 ScriptedCommandSynchronicity m_synchronicity;
2025 static OptionEnumValueElement g_script_synchro_type[] =
2027 { eScriptedCommandSynchronicitySynchronous, "synchronous", "Run synchronous"},
2028 { eScriptedCommandSynchronicityAsynchronous, "asynchronous", "Run asynchronous"},
2029 { eScriptedCommandSynchronicityCurrentValue, "current", "Do not alter current setting"},
2034 CommandObjectCommandsScriptAdd::CommandOptions::g_option_table[] =
2036 { LLDB_OPT_SET_1, false, "function", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePythonFunction, "Name of the Python function to bind to this command name."},
2037 { LLDB_OPT_SET_2, false, "class", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePythonClass, "Name of the Python class to bind to this command name."},
2038 { LLDB_OPT_SET_1, false, "help" , 'h', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeHelpText, "The help text to display for this command."},
2039 { LLDB_OPT_SET_ALL, false, "synchronicity", 's', OptionParser::eRequiredArgument, NULL, g_script_synchro_type, 0, eArgTypeScriptedCommandSynchronicity, "Set the synchronicity of this command's executions with regard to LLDB event system."},
2040 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
2043 //-------------------------------------------------------------------------
2044 // CommandObjectCommandsScriptList
2045 //-------------------------------------------------------------------------
2047 class CommandObjectCommandsScriptList : public CommandObjectParsed
2052 CommandObjectCommandsScriptList(CommandInterpreter &interpreter) :
2053 CommandObjectParsed (interpreter,
2054 "command script list",
2055 "List defined scripted commands.",
2060 ~CommandObjectCommandsScriptList () override
2065 DoExecute (Args& command, CommandReturnObject &result) override
2068 m_interpreter.GetHelp(result,
2069 CommandInterpreter::eCommandTypesUserDef);
2071 result.SetStatus (eReturnStatusSuccessFinishResult);
2079 //-------------------------------------------------------------------------
2080 // CommandObjectCommandsScriptClear
2081 //-------------------------------------------------------------------------
2083 class CommandObjectCommandsScriptClear : public CommandObjectParsed
2088 CommandObjectCommandsScriptClear(CommandInterpreter &interpreter) :
2089 CommandObjectParsed (interpreter,
2090 "command script clear",
2091 "Delete all scripted commands.",
2096 ~CommandObjectCommandsScriptClear () override
2102 DoExecute (Args& command, CommandReturnObject &result) override
2105 m_interpreter.RemoveAllUser();
2107 result.SetStatus (eReturnStatusSuccessFinishResult);
2113 //-------------------------------------------------------------------------
2114 // CommandObjectCommandsScriptDelete
2115 //-------------------------------------------------------------------------
2117 class CommandObjectCommandsScriptDelete : public CommandObjectParsed
2120 CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter) :
2121 CommandObjectParsed (interpreter,
2122 "command script delete",
2123 "Delete a scripted command.",
2126 CommandArgumentEntry arg1;
2127 CommandArgumentData cmd_arg;
2129 // Define the first (and only) variant of this arg.
2130 cmd_arg.arg_type = eArgTypeCommandName;
2131 cmd_arg.arg_repetition = eArgRepeatPlain;
2133 // There is only one variant this argument could be; put it into the argument entry.
2134 arg1.push_back (cmd_arg);
2136 // Push the data for the first argument into the m_arguments vector.
2137 m_arguments.push_back (arg1);
2140 ~CommandObjectCommandsScriptDelete () override
2146 DoExecute (Args& command, CommandReturnObject &result) override
2149 size_t argc = command.GetArgumentCount();
2153 result.AppendError ("'command script delete' requires one argument");
2154 result.SetStatus (eReturnStatusFailed);
2158 const char* cmd_name = command.GetArgumentAtIndex(0);
2160 if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() && m_interpreter.UserCommandExists(cmd_name))
2162 m_interpreter.RemoveUser(cmd_name);
2163 result.SetStatus (eReturnStatusSuccessFinishResult);
2167 result.AppendErrorWithFormat ("command %s not found", cmd_name);
2168 result.SetStatus (eReturnStatusFailed);
2171 return result.Succeeded();
2176 #pragma mark CommandObjectMultiwordCommandsScript
2178 //-------------------------------------------------------------------------
2179 // CommandObjectMultiwordCommandsScript
2180 //-------------------------------------------------------------------------
2182 class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword
2185 CommandObjectMultiwordCommandsScript (CommandInterpreter &interpreter) :
2186 CommandObjectMultiword (interpreter,
2188 "A set of commands for managing or customizing script commands.",
2189 "command script <subcommand> [<subcommand-options>]")
2191 LoadSubCommand ("add", CommandObjectSP (new CommandObjectCommandsScriptAdd (interpreter)));
2192 LoadSubCommand ("delete", CommandObjectSP (new CommandObjectCommandsScriptDelete (interpreter)));
2193 LoadSubCommand ("clear", CommandObjectSP (new CommandObjectCommandsScriptClear (interpreter)));
2194 LoadSubCommand ("list", CommandObjectSP (new CommandObjectCommandsScriptList (interpreter)));
2195 LoadSubCommand ("import", CommandObjectSP (new CommandObjectCommandsScriptImport (interpreter)));
2198 ~CommandObjectMultiwordCommandsScript () override
2205 #pragma mark CommandObjectMultiwordCommands
2207 //-------------------------------------------------------------------------
2208 // CommandObjectMultiwordCommands
2209 //-------------------------------------------------------------------------
2211 CommandObjectMultiwordCommands::CommandObjectMultiwordCommands (CommandInterpreter &interpreter) :
2212 CommandObjectMultiword (interpreter,
2214 "A set of commands for managing or customizing the debugger commands.",
2215 "command <subcommand> [<subcommand-options>]")
2217 LoadSubCommand ("source", CommandObjectSP (new CommandObjectCommandsSource (interpreter)));
2218 LoadSubCommand ("alias", CommandObjectSP (new CommandObjectCommandsAlias (interpreter)));
2219 LoadSubCommand ("unalias", CommandObjectSP (new CommandObjectCommandsUnalias (interpreter)));
2220 LoadSubCommand ("delete", CommandObjectSP (new CommandObjectCommandsDelete (interpreter)));
2221 LoadSubCommand ("regex", CommandObjectSP (new CommandObjectCommandsAddRegex (interpreter)));
2222 LoadSubCommand ("history", CommandObjectSP (new CommandObjectCommandsHistory (interpreter)));
2223 LoadSubCommand ("script", CommandObjectSP (new CommandObjectMultiwordCommandsScript (interpreter)));
2226 CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands ()