LLDB mainline
CommandObjectCommands.cpp
Go to the documentation of this file.
1//===-- CommandObjectCommands.cpp -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "CommandObjectHelp.h"
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/IOHandler.h"
26#include "lldb/Utility/Args.h"
28#include "llvm/ADT/StringRef.h"
29#include <memory>
30#include <optional>
31
32using namespace lldb;
33using namespace lldb_private;
34
35// CommandObjectCommandsSource
36
37#define LLDB_OPTIONS_source
38#include "CommandOptions.inc"
39
41public:
44 interpreter, "command source",
45 "Read and execute LLDB commands from the file <filename>.",
46 nullptr) {
48 }
49
50 ~CommandObjectCommandsSource() override = default;
51
52 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
53 uint32_t index) override {
54 return std::string("");
55 }
56
57 Options *GetOptions() override { return &m_options; }
58
59protected:
60 class CommandOptions : public Options {
61 public:
65
66 ~CommandOptions() override = default;
67
68 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
69 ExecutionContext *execution_context) override {
71 const int short_option = m_getopt_table[option_idx].val;
72
73 switch (short_option) {
74 case 'e':
75 error = m_stop_on_error.SetValueFromString(option_arg);
76 break;
77
78 case 'c':
79 error = m_stop_on_continue.SetValueFromString(option_arg);
80 break;
81
82 case 'C':
84 break;
85
86 case 's':
87 error = m_silent_run.SetValueFromString(option_arg);
88 break;
89
90 default:
91 llvm_unreachable("Unimplemented option");
92 }
93
94 return error;
95 }
96
97 void OptionParsingStarting(ExecutionContext *execution_context) override {
98 m_stop_on_error.Clear();
99 m_silent_run.Clear();
100 m_stop_on_continue.Clear();
102 }
103
104 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
105 return llvm::ArrayRef(g_source_options);
106 }
107
108 // Instance variables to hold the values for command options.
109
114 };
115
116 void DoExecute(Args &command, CommandReturnObject &result) override {
117 if (command.GetArgumentCount() != 1) {
119 "'%s' takes exactly one executable filename argument",
120 GetCommandName().str().c_str());
121 return;
122 }
123
124 FileSpec source_dir = {};
125 if (m_options.m_cmd_relative_to_command_file) {
127 if (!source_dir) {
128 result.AppendError("command source -C can only be specified "
129 "from a command file");
131 return;
132 }
133 }
134
135 FileSpec cmd_file(command[0].ref());
136 if (source_dir) {
137 // Prepend the source_dir to the cmd_file path:
138 if (!cmd_file.IsRelative()) {
139 result.AppendError("command source -C can only be used "
140 "with a relative path.");
142 return;
143 }
144 cmd_file.MakeAbsolute(source_dir);
145 }
146
147 FileSystem::Instance().Resolve(cmd_file);
148
150 // If any options were set, then use them
151 if (m_options.m_stop_on_error.OptionWasSet() ||
152 m_options.m_silent_run.OptionWasSet() ||
153 m_options.m_stop_on_continue.OptionWasSet()) {
154 if (m_options.m_stop_on_continue.OptionWasSet())
155 options.SetStopOnContinue(
156 m_options.m_stop_on_continue.GetCurrentValue());
157
158 if (m_options.m_stop_on_error.OptionWasSet())
159 options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
160
161 // Individual silent setting is override for global command echo settings.
162 if (m_options.m_silent_run.GetCurrentValue()) {
163 options.SetSilent(true);
164 } else {
165 options.SetPrintResults(true);
166 options.SetPrintErrors(true);
167 options.SetEchoCommands(m_interpreter.GetEchoCommands());
168 options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands());
169 }
170 }
171
172 m_interpreter.HandleCommandsFromFile(cmd_file, options, result);
173 }
174
176};
177
178#pragma mark CommandObjectCommandsAlias
179// CommandObjectCommandsAlias
180
181#define LLDB_OPTIONS_alias
182#include "CommandOptions.inc"
183
185 "Enter your Python command(s). Type 'DONE' to end.\n"
186 "You must define a Python function with this signature:\n"
187 "def my_command_impl(debugger, args, exe_ctx, result, internal_dict):\n";
188
190protected:
192 public:
193 CommandOptions() = default;
194
195 ~CommandOptions() override = default;
196
197 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
198 return llvm::ArrayRef(g_alias_options);
199 }
200
201 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
202 ExecutionContext *execution_context) override {
204
205 const int short_option = GetDefinitions()[option_idx].short_option;
206 std::string option_str(option_value);
207
208 switch (short_option) {
209 case 'h':
210 m_help.SetCurrentValue(option_str);
211 m_help.SetOptionWasSet();
212 break;
213
214 case 'H':
215 m_long_help.SetCurrentValue(option_str);
216 m_long_help.SetOptionWasSet();
217 break;
218
219 default:
220 llvm_unreachable("Unimplemented option");
221 }
222
223 return error;
224 }
225
226 void OptionParsingStarting(ExecutionContext *execution_context) override {
227 m_help.Clear();
228 m_long_help.Clear();
229 }
230
233 };
234
237
238public:
239 Options *GetOptions() override { return &m_option_group; }
240
243 interpreter, "command alias",
244 "Define a custom command in terms of an existing command.") {
246 m_option_group.Finalize();
247
249 "'alias' allows the user to create a short-cut or abbreviation for long \
250commands, multi-word commands, and commands that take particular options. \
251Below are some simple examples of how one might use the 'alias' command:"
252 R"(
253
254(lldb) command alias sc script
255
256 Creates the abbreviation 'sc' for the 'script' command.
257
258(lldb) command alias bp breakpoint
259
260)"
261 " Creates the abbreviation 'bp' for the 'breakpoint' command. Since \
262breakpoint commands are two-word commands, the user would still need to \
263enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
264 R"(
265
266(lldb) command alias bpl breakpoint list
267
268 Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
269
270)"
271 "An alias can include some options for the command, with the values either \
272filled in at the time the alias is created, or specified as positional \
273arguments, to be filled in when the alias is invoked. The following example \
274shows how to create aliases with options:"
275 R"(
276
277(lldb) command alias bfl breakpoint set -f %1 -l %2
278
279)"
280 " Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
281options already part of the alias. So if the user wants to set a breakpoint \
282by file and line without explicitly having to use the -f and -l options, the \
283user can now use 'bfl' instead. The '%1' and '%2' are positional placeholders \
284for the actual arguments that will be passed when the alias command is used. \
285The number in the placeholder refers to the position/order the actual value \
286occupies when the alias is used. All the occurrences of '%1' in the alias \
287will be replaced with the first argument, all the occurrences of '%2' in the \
288alias will be replaced with the second argument, and so on. This also allows \
289actual arguments to be used multiple times within an alias (see 'process \
290launch' example below)."
291 R"(
292
293)"
294 "Note: the positional arguments must substitute as whole words in the resultant \
295command, so you can't at present do something like this to append the file extension \
296\".cpp\":"
297 R"(
298
299(lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
300
301)"
302 "For more complex aliasing, use the \"command regex\" command instead. In the \
303'bfl' case above, the actual file value will be filled in with the first argument \
304following 'bfl' and the actual line number value will be filled in with the second \
305argument. The user would use this alias as follows:"
306 R"(
307
308(lldb) command alias bfl breakpoint set -f %1 -l %2
309(lldb) bfl my-file.c 137
310
311This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
312
313Another example:
314
315(lldb) command alias pltty process launch -s -o %1 -e %1
316(lldb) pltty /dev/tty0
317
318 Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
319
320)"
321 "If the user always wanted to pass the same value to a particular option, the \
322alias could be defined with that value directly in the alias as a constant, \
323rather than using a positional placeholder:"
324 R"(
325
326(lldb) command alias bl3 breakpoint set -f %1 -l 3
327
328 Always sets a breakpoint on line 3 of whatever file is indicated.
330)"
331
332 "If the alias abbreviation or the full alias command collides with another \
333existing command, the command resolver will prefer to use the alias over any \
334other command as far as there is only one alias command match.");
335
339 CommandArgumentData alias_arg;
340 CommandArgumentData cmd_arg;
341 CommandArgumentData options_arg;
342
343 // Define the first (and only) variant of this arg.
344 alias_arg.arg_type = eArgTypeAliasName;
346
347 // There is only one variant this argument could be; put it into the
348 // argument entry.
349 arg1.push_back(alias_arg);
350
351 // Define the first (and only) variant of this arg.
354
355 // There is only one variant this argument could be; put it into the
356 // argument entry.
357 arg2.push_back(cmd_arg);
358
359 // Define the first (and only) variant of this arg.
360 options_arg.arg_type = eArgTypeAliasOptions;
362
363 // There is only one variant this argument could be; put it into the
364 // argument entry.
365 arg3.push_back(options_arg);
366
367 // Push the data for the first argument into the m_arguments vector.
368 m_arguments.push_back(arg1);
369 m_arguments.push_back(arg2);
370 m_arguments.push_back(arg3);
371 }
372
373 ~CommandObjectCommandsAlias() override = default;
374
375protected:
376 void DoExecute(llvm::StringRef raw_command_line,
377 CommandReturnObject &result) override {
378 if (raw_command_line.empty()) {
379 result.AppendError("'command alias' requires at least two arguments");
380 return;
381 }
382
383 ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
384 m_option_group.NotifyOptionParsingStarting(&exe_ctx);
385
386 OptionsWithRaw args_with_suffix(raw_command_line);
387
388 if (args_with_suffix.HasArgs())
389 if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
390 m_option_group, exe_ctx))
391 return;
392
393 llvm::StringRef raw_command_string = args_with_suffix.GetRawPart();
394 Args args(raw_command_string);
395
396 if (args.GetArgumentCount() < 2) {
397 result.AppendError("'command alias' requires at least two arguments");
398 return;
399 }
400
401 // Get the alias command.
402
403 auto alias_command = args[0].ref();
404 if (alias_command.starts_with("-")) {
405 result.AppendError("aliases starting with a dash are not supported");
406 if (alias_command == "--help" || alias_command == "--long-help") {
407 result.AppendWarning("if trying to pass options to 'command alias' add "
408 "a -- at the end of the options");
409 }
410 return;
411 }
412
413 // Strip the new alias name off 'raw_command_string' (leave it on args,
414 // which gets passed to 'Execute', which does the stripping itself.
415 size_t pos = raw_command_string.find(alias_command);
416 if (pos == 0) {
417 raw_command_string = raw_command_string.substr(alias_command.size());
418 pos = raw_command_string.find_first_not_of(' ');
419 if ((pos != std::string::npos) && (pos > 0))
420 raw_command_string = raw_command_string.substr(pos);
421 } else {
422 result.AppendError("error parsing command string. No alias created");
423 return;
424 }
425
426 // Verify that the command is alias-able.
427 if (m_interpreter.CommandExists(alias_command)) {
429 "'%s' is a permanent debugger command and cannot be redefined",
430 args[0].c_str());
431 return;
432 }
433
434 if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
436 "'%s' is a user container command and cannot be overwritten.\n"
437 "Delete it first with 'command container delete'",
438 args[0].c_str());
439 return;
440 }
441
442 // Get CommandObject that is being aliased. The command name is read from
443 // the front of raw_command_string. raw_command_string is returned with the
444 // name of the command object stripped off the front.
445 llvm::StringRef original_raw_command_string = raw_command_string;
446 CommandObject *cmd_obj =
447 m_interpreter.GetCommandObjectForCommand(raw_command_string);
448
449 if (!cmd_obj) {
450 result.AppendErrorWithFormat("invalid command given to 'command alias'. "
451 "'%s' does not begin with a valid command."
452 " No alias created",
453 original_raw_command_string.str().c_str());
454 } else if (!cmd_obj->WantsRawCommandString()) {
455 // Note that args was initialized with the original command, and has not
456 // been updated to this point. Therefore can we pass it to the version of
457 // Execute that does not need/expect raw input in the alias.
459 } else {
460 HandleAliasingRawCommand(alias_command, raw_command_string, *cmd_obj,
461 result);
462 }
463 }
464
465 bool HandleAliasingRawCommand(llvm::StringRef alias_command,
466 llvm::StringRef raw_command_string,
467 CommandObject &cmd_obj,
468 CommandReturnObject &result) {
469 // Verify & handle any options/arguments passed to the alias command
470
471 OptionArgVectorSP option_arg_vector_sp =
472 std::make_shared<OptionArgVector>();
473
474 const bool include_aliases = true;
475 // Look up the command using command's name first. This is to resolve
476 // aliases when you are making nested aliases. But if you don't find
477 // it that way, then it wasn't an alias and we can just use the object
478 // we were passed in.
479 CommandObjectSP cmd_obj_sp = m_interpreter.GetCommandSPExact(
480 cmd_obj.GetCommandName(), include_aliases);
481 if (!cmd_obj_sp)
482 cmd_obj_sp = cmd_obj.shared_from_this();
483
484 if (m_interpreter.AliasExists(alias_command) ||
485 m_interpreter.UserCommandExists(alias_command)) {
487 "overwriting existing definition for '{0}'", alias_command);
488 }
489 if (CommandAlias *alias = m_interpreter.AddAlias(
490 alias_command, cmd_obj_sp, raw_command_string)) {
491 if (m_command_options.m_help.OptionWasSet())
492 alias->SetHelp(m_command_options.m_help.GetCurrentValue());
493 if (m_command_options.m_long_help.OptionWasSet())
494 alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
496 } else {
497 result.AppendError("Unable to create requested alias.\n");
498 }
499 return result.Succeeded();
500 }
501
502 bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
503 size_t argc = args.GetArgumentCount();
504
505 if (argc < 2) {
506 result.AppendError("'command alias' requires at least two arguments");
507 return false;
508 }
509
510 // Save these in std::strings since we're going to shift them off.
511 const std::string alias_command(std::string(args[0].ref()));
512 const std::string actual_command(std::string(args[1].ref()));
513
514 args.Shift(); // Shift the alias command word off the argument vector.
515 args.Shift(); // Shift the old command word off the argument vector.
516
517 // Verify that the command is alias'able, and get the appropriate command
518 // object.
519
520 if (m_interpreter.CommandExists(alias_command)) {
522 "'%s' is a permanent debugger command and cannot be redefined",
523 alias_command.c_str());
524 return false;
525 }
526
527 if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
529 "'%s' is user container command and cannot be overwritten.\n"
530 "Delete it first with 'command container delete'",
531 alias_command.c_str());
532 return false;
533 }
534
535 CommandObjectSP command_obj_sp(
536 m_interpreter.GetCommandSPExact(actual_command, true));
537 CommandObjectSP subcommand_obj_sp;
538 bool use_subcommand = false;
539 if (!command_obj_sp) {
540 result.AppendErrorWithFormat("'%s' is not an existing command",
541 actual_command.c_str());
542 return false;
543 }
544 CommandObject *cmd_obj = command_obj_sp.get();
545 CommandObject *sub_cmd_obj = nullptr;
546 OptionArgVectorSP option_arg_vector_sp =
547 std::make_shared<OptionArgVector>();
548
549 while (cmd_obj->IsMultiwordObject() && !args.empty()) {
550 auto sub_command = args[0].ref();
551 assert(!sub_command.empty());
552 subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
553 if (!subcommand_obj_sp) {
555 "'%s' is not a valid sub-command of '%s'. "
556 "Unable to create alias",
557 args[0].c_str(), actual_command.c_str());
558 return false;
559 }
560
561 sub_cmd_obj = subcommand_obj_sp.get();
562 use_subcommand = true;
563 args.Shift(); // Shift the sub_command word off the argument vector.
564 cmd_obj = sub_cmd_obj;
565 }
566
567 // Verify & handle any options/arguments passed to the alias command
568
569 std::string args_string;
570
571 if (!args.empty()) {
572 CommandObjectSP tmp_sp =
573 m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName());
574 if (use_subcommand)
575 tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName());
576
577 args.GetCommandString(args_string);
578 }
579
580 if (m_interpreter.AliasExists(alias_command) ||
581 m_interpreter.UserCommandExists(alias_command)) {
583 "overwriting existing definition for '{0}'", alias_command);
584 }
585
586 if (CommandAlias *alias = m_interpreter.AddAlias(
587 alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
588 args_string)) {
589 if (m_command_options.m_help.OptionWasSet())
590 alias->SetHelp(m_command_options.m_help.GetCurrentValue());
591 if (m_command_options.m_long_help.OptionWasSet())
592 alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
594 } else {
595 result.AppendError("Unable to create requested alias.\n");
596 return false;
597 }
598
599 return result.Succeeded();
600 }
601};
602
603#pragma mark CommandObjectCommandsUnalias
604// CommandObjectCommandsUnalias
605
607public:
610 interpreter, "command unalias",
611 "Delete one or more custom commands defined by 'command alias'.",
612 nullptr) {
614 }
615
616 ~CommandObjectCommandsUnalias() override = default;
617
618 void
620 OptionElementVector &opt_element_vector) override {
621 if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
622 return;
623
624 for (const auto &ent : m_interpreter.GetAliases()) {
625 request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
626 }
627 }
628
629protected:
630 void DoExecute(Args &args, CommandReturnObject &result) override {
631 CommandObject *cmd_obj;
632
633 if (args.empty()) {
634 result.AppendError("must call 'unalias' with a valid alias");
635 return;
636 }
637
638 auto command_name = args[0].ref();
639 cmd_obj = m_interpreter.GetCommandObject(command_name);
640 if (!cmd_obj) {
642 "'%s' is not a known command.\nTry 'help' to see a "
643 "current list of commands",
644 args[0].c_str());
645 return;
646 }
647
648 if (m_interpreter.CommandExists(command_name)) {
649 if (cmd_obj->IsRemovable()) {
651 "'%s' is not an alias, it is a debugger command which can be "
652 "removed using the 'command delete' command",
653 args[0].c_str());
654 } else {
656 "'%s' is a permanent debugger command and cannot be removed",
657 args[0].c_str());
658 }
659 return;
660 }
661
662 if (!m_interpreter.RemoveAlias(command_name)) {
663 if (m_interpreter.AliasExists(command_name))
665 "Error occurred while attempting to unalias '%s'", args[0].c_str());
666 else
667 result.AppendErrorWithFormat("'%s' is not an existing alias",
668 args[0].c_str());
669 return;
670 }
671
673 }
674};
675
676#pragma mark CommandObjectCommandsDelete
677// CommandObjectCommandsDelete
678
680public:
683 interpreter, "command delete",
684 "Delete one or more custom commands defined by 'command regex'.",
685 nullptr) {
687 }
688
689 ~CommandObjectCommandsDelete() override = default;
690
691 void
693 OptionElementVector &opt_element_vector) override {
694 if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
695 return;
696
697 for (const auto &ent : m_interpreter.GetCommands()) {
698 if (ent.second->IsRemovable())
699 request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
700 }
701 }
702
703protected:
704 void DoExecute(Args &args, CommandReturnObject &result) override {
705 if (args.empty()) {
706 result.AppendErrorWithFormat("must call '%s' with one or more valid user "
707 "defined regular expression command names",
708 GetCommandName().str().c_str());
709 return;
710 }
711
712 auto command_name = args[0].ref();
713 if (!m_interpreter.CommandExists(command_name)) {
714 StreamString error_msg_stream;
715 const bool generate_upropos = true;
716 const bool generate_type_lookup = false;
718 &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
719 generate_upropos, generate_type_lookup);
720 result.AppendError(error_msg_stream.GetString());
721 return;
722 }
723
724 if (!m_interpreter.RemoveCommand(command_name)) {
726 "'%s' is a permanent debugger command and cannot be removed",
727 args[0].c_str());
728 return;
729 }
730
732 }
733};
734
735// CommandObjectCommandsAddRegex
736
737#define LLDB_OPTIONS_regex
738#include "CommandOptions.inc"
739
740#pragma mark CommandObjectCommandsAddRegex
741
744public:
747 interpreter, "command regex",
748 "Define a custom command in terms of "
749 "existing commands by matching "
750 "regular expressions.",
751 "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
755 R"(
756)"
757 "This command allows the user to create powerful regular expression commands \
758with substitutions. The regular expressions and substitutions are specified \
759using the regular expression substitution format of:"
760 R"(
761
762 s/<regex>/<subst>/
763
764)"
765 "<regex> is a regular expression that can use parenthesis to capture regular \
766expression input and substitute the captured matches in the output using %1 \
767for the first match, %2 for the second, and so on."
768 R"(
769
770)"
771 "The regular expressions can all be specified on the command line if more than \
772one argument is provided. If just the command name is provided on the command \
773line, then the regular expressions and substitutions can be entered on separate \
774lines, followed by an empty line to terminate the command definition."
775 R"(
777EXAMPLES
778
780 "The following example will define a regular expression command named 'f' that \
781will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
782a number follows 'f':"
783 R"(
784
785 (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
787 }
788
789 ~CommandObjectCommandsAddRegex() override = default;
790
791protected:
792 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
793 if (interactive) {
794 if (lldb::LockableStreamFileSP output_sp =
795 io_handler.GetOutputStreamFileSP()) {
796 LockedStreamFile locked_stream = output_sp->Lock();
797 locked_stream.PutCString(
798 "Enter one or more sed substitution commands in "
799 "the form: 's/<regex>/<subst>/'.\nTerminate the "
800 "substitution list with an empty line.\n");
801 }
802 }
803 }
804
805 void IOHandlerInputComplete(IOHandler &io_handler,
806 std::string &data) override {
807 io_handler.SetIsDone(true);
808 if (m_regex_cmd_up) {
809 StringList lines;
810 if (lines.SplitIntoLines(data)) {
811 bool check_only = false;
812 for (const std::string &line : lines) {
813 Status error = AppendRegexSubstitution(line, check_only);
814 if (error.Fail()) {
815 if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode())
816 GetDebugger().GetAsyncOutputStream()->Printf("error: %s\n",
817 error.AsCString());
818 }
819 }
820 }
821 if (m_regex_cmd_up->HasRegexEntries()) {
822 CommandObjectSP cmd_sp(m_regex_cmd_up.release());
823 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
824 }
825 }
826 }
827
828 void DoExecute(Args &command, CommandReturnObject &result) override {
829 const size_t argc = command.GetArgumentCount();
830 if (argc == 0) {
831 result.AppendError("usage: 'command regex <command-name> "
832 "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
833 return;
834 }
835
837 auto name = command[0].ref();
838 m_regex_cmd_up = std::make_unique<CommandObjectRegexCommand>(
839 m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 0,
840 true);
841
842 if (argc == 1) {
843 Debugger &debugger = GetDebugger();
844 bool color_prompt = debugger.GetUseColor();
845 const bool multiple_lines = true; // Get multiple lines
846 IOHandlerSP io_handler_sp(new IOHandlerEditline(
847 debugger, IOHandler::Type::Other,
848 "lldb-regex", // Name of input reader for history
849 llvm::StringRef("> "), // Prompt
850 llvm::StringRef(), // Continuation prompt
851 multiple_lines, color_prompt,
852 0, // Don't show line numbers
853 *this));
854
855 if (io_handler_sp) {
856 debugger.RunIOHandlerAsync(io_handler_sp);
858 }
859 } else {
860 for (auto &entry : command.entries().drop_front()) {
861 bool check_only = false;
862 error = AppendRegexSubstitution(entry.ref(), check_only);
863 if (error.Fail())
864 break;
865 }
866
867 if (error.Success()) {
870 }
871 }
872 if (error.Fail()) {
873 result.AppendError(error.AsCString());
874 }
875 }
876
877 Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
878 bool check_only) {
880
881 if (!m_regex_cmd_up) {
882 return Status::FromErrorStringWithFormat(
883 "invalid regular expression command object for: '%.*s'",
884 (int)regex_sed.size(), regex_sed.data());
885 return error;
886 }
887
888 size_t regex_sed_size = regex_sed.size();
889
890 if (regex_sed_size <= 1) {
891 return Status::FromErrorStringWithFormat(
892 "regular expression substitution string is too short: '%.*s'",
893 (int)regex_sed.size(), regex_sed.data());
894 return error;
895 }
896
897 if (regex_sed[0] != 's') {
898 return Status::FromErrorStringWithFormat(
899 "regular expression substitution string "
900 "doesn't start with 's': '%.*s'",
901 (int)regex_sed.size(), regex_sed.data());
902 return error;
903 }
904 const size_t first_separator_char_pos = 1;
905 // use the char that follows 's' as the regex separator character so we can
906 // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
907 const char separator_char = regex_sed[first_separator_char_pos];
908 const size_t second_separator_char_pos =
909 regex_sed.find(separator_char, first_separator_char_pos + 1);
910
911 if (second_separator_char_pos == std::string::npos) {
912 return Status::FromErrorStringWithFormat(
913 "missing second '%c' separator char after '%.*s' in '%.*s'",
914 separator_char,
915 (int)(regex_sed.size() - first_separator_char_pos - 1),
916 regex_sed.data() + (first_separator_char_pos + 1),
917 (int)regex_sed.size(), regex_sed.data());
918 return error;
919 }
920
921 const size_t third_separator_char_pos =
922 regex_sed.find(separator_char, second_separator_char_pos + 1);
923
924 if (third_separator_char_pos == std::string::npos) {
925 return Status::FromErrorStringWithFormat(
926 "missing third '%c' separator char after '%.*s' in '%.*s'",
927 separator_char,
928 (int)(regex_sed.size() - second_separator_char_pos - 1),
929 regex_sed.data() + (second_separator_char_pos + 1),
930 (int)regex_sed.size(), regex_sed.data());
931 return error;
932 }
933
934 if (third_separator_char_pos != regex_sed_size - 1) {
935 // Make sure that everything that follows the last regex separator char
936 if (regex_sed.find_first_not_of("\t\n\v\f\r ",
937 third_separator_char_pos + 1) !=
938 std::string::npos) {
939 return Status::FromErrorStringWithFormat(
940 "extra data found after the '%.*s' regular expression substitution "
941 "string: '%.*s'",
942 (int)third_separator_char_pos + 1, regex_sed.data(),
943 (int)(regex_sed.size() - third_separator_char_pos - 1),
944 regex_sed.data() + (third_separator_char_pos + 1));
945 return error;
946 }
947 } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
948 return Status::FromErrorStringWithFormat(
949 "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
950 separator_char, separator_char, separator_char, (int)regex_sed.size(),
951 regex_sed.data());
952 return error;
953 } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
954 return Status::FromErrorStringWithFormat(
955 "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
956 separator_char, separator_char, separator_char, (int)regex_sed.size(),
957 regex_sed.data());
958 return error;
959 }
961 if (!check_only) {
962 std::string regex(std::string(regex_sed.substr(
963 first_separator_char_pos + 1,
964 second_separator_char_pos - first_separator_char_pos - 1)));
965 std::string subst(std::string(regex_sed.substr(
966 second_separator_char_pos + 1,
967 third_separator_char_pos - second_separator_char_pos - 1)));
968 m_regex_cmd_up->AddRegexCommand(regex, subst);
969 }
970 return error;
971 }
975 if (m_regex_cmd_up->HasRegexEntries()) {
977 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
979 }
980 }
981
982private:
983 std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
984
985 class CommandOptions : public Options {
986 public:
987 CommandOptions() = default;
988
989 ~CommandOptions() override = default;
990
991 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
992 ExecutionContext *execution_context) override {
994 const int short_option = m_getopt_table[option_idx].val;
995
996 switch (short_option) {
997 case 'h':
998 m_help.assign(std::string(option_arg));
999 break;
1000 case 's':
1001 m_syntax.assign(std::string(option_arg));
1002 break;
1003 default:
1004 llvm_unreachable("Unimplemented option");
1005 }
1007 return error;
1009
1010 void OptionParsingStarting(ExecutionContext *execution_context) override {
1011 m_help.clear();
1012 m_syntax.clear();
1015 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1016 return llvm::ArrayRef(g_regex_options);
1018
1019 llvm::StringRef GetHelp() { return m_help; }
1020
1021 llvm::StringRef GetSyntax() { return m_syntax; }
1022
1023 protected:
1024 // Instance variables to hold the values for command options.
1025
1026 std::string m_help;
1027 std::string m_syntax;
1028 };
1029
1030 Options *GetOptions() override { return &m_options; }
1031
1033};
1034
1036public:
1037 CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1038 std::string funct, std::string help,
1040 CompletionType completion_type)
1041 : CommandObjectRaw(interpreter, name), m_function_name(funct),
1042 m_synchro(synch), m_completion_type(completion_type) {
1043 if (!help.empty())
1044 SetHelp(help);
1045 else {
1046 StreamString stream;
1047 stream.Printf("For more information run 'help %s'", name.c_str());
1048 SetHelp(stream.GetString());
1049 }
1050 }
1051
1052 ~CommandObjectPythonFunction() override = default;
1053
1054 bool IsRemovable() const override { return true; }
1055
1056 const std::string &GetFunctionName() { return m_function_name; }
1057
1059
1060 llvm::StringRef GetHelpLong() override {
1063
1065 if (!scripter)
1067
1068 std::string docstring;
1070 scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1071 if (!docstring.empty())
1072 SetHelpLong(docstring);
1074 }
1075
1076 void
1082
1083 bool WantsCompletion() override { return true; }
1084
1085protected:
1086 void DoExecute(llvm::StringRef raw_command_line,
1087 CommandReturnObject &result) override {
1089
1090 m_interpreter.IncreaseCommandUsage(*this);
1091
1092 Status error;
1093
1095
1096 if (!scripter || !scripter->RunScriptBasedCommand(
1097 m_function_name.c_str(), raw_command_line, m_synchro,
1098 result, error, m_exe_ctx)) {
1099 result.AppendError(error.AsCString());
1100 } else {
1101 // Don't change the status if the command already set it...
1102 if (result.GetStatus() == eReturnStatusInvalid) {
1103 if (result.GetOutputString().empty())
1105 else
1107 }
1108 }
1109 }
1110
1111private:
1112 std::string m_function_name;
1116};
1117
1118/// This class implements a "raw" scripted command. lldb does no parsing of the
1119/// command line, instead passing the line unaltered (except for backtick
1120/// substitution).
1122public:
1124 CommandInterpreter &interpreter, std::string name,
1125 lldb::ScriptedCommandInterfaceSP cmd_interface_sp,
1126 ScriptedCommandSynchronicity synch, CompletionType completion_type)
1127 : CommandObjectRaw(interpreter, name),
1128 m_cmd_interface_sp(cmd_interface_sp), m_synchro(synch),
1130 m_completion_type(completion_type) {
1131 StreamString stream;
1132 stream.Printf("For more information run 'help %s'", name.c_str());
1133 SetHelp(stream.GetString());
1135 GetFlags().Set(m_cmd_interface_sp->GetFlags());
1136 }
1137
1139
1140 void
1146
1147 bool WantsCompletion() override { return true; }
1148
1149 bool IsRemovable() const override { return true; }
1150
1152
1153 std::optional<std::string> GetRepeatCommand(Args &args,
1154 uint32_t index) override {
1155 if (!m_cmd_interface_sp)
1156 return std::nullopt;
1157
1158 return m_cmd_interface_sp->GetRepeatCommand(args);
1159 }
1160
1161 llvm::StringRef GetHelp() override {
1164 if (!m_cmd_interface_sp)
1166 std::string docstring;
1167 m_fetched_help_short = m_cmd_interface_sp->GetShortHelp(docstring);
1168 if (!docstring.empty())
1169 SetHelp(docstring);
1170
1172 }
1173
1174 llvm::StringRef GetHelpLong() override {
1177
1178 if (!m_cmd_interface_sp)
1180
1181 std::string docstring;
1182 m_fetched_help_long = m_cmd_interface_sp->GetLongHelp(docstring);
1183 if (!docstring.empty())
1184 SetHelpLong(docstring);
1186 }
1187
1188protected:
1189 void DoExecute(llvm::StringRef raw_command_line,
1190 CommandReturnObject &result) override {
1191 Status error;
1192
1194
1195 if (!m_cmd_interface_sp ||
1196 !m_cmd_interface_sp->RunRawCommand(raw_command_line, m_synchro, result,
1197 error, m_exe_ctx)) {
1198 result.AppendError(error.AsCString());
1199 } else {
1200 // Don't change the status if the command already set it...
1201 if (result.GetStatus() == eReturnStatusInvalid) {
1202 if (result.GetOutputString().empty())
1204 else
1206 }
1207 }
1208 }
1209
1210private:
1216};
1217
1218
1219/// This command implements a lldb parsed scripted command. The command
1220/// provides a definition of the options and arguments, and a option value
1221/// setting callback, and then the command's execution function gets passed
1222/// just the parsed arguments.
1223/// Note, implementing a command in Python using these base interfaces is a bit
1224/// of a pain, but it is much easier to export this low level interface, and
1225/// then make it nicer on the Python side, than to try to do that in a
1226/// script language neutral way.
1227/// So I've also added a base class in Python that provides a table-driven
1228/// way of defining the options and arguments, which automatically fills the
1229/// option values, making them available as properties in Python.
1230///
1232private:
1233 class CommandOptions : public Options {
1234 public:
1236 : m_cmd_interface_sp(cmd_interface_sp) {}
1237
1238 ~CommandOptions() override = default;
1239
1240 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1241 ExecutionContext *execution_context) override {
1242 Status error;
1243 if (!m_cmd_interface_sp) {
1245 "SetOptionValue called with empty cmd_obj.");
1246 return error;
1247 }
1250 "SetOptionValue called before options definitions "
1251 "were created.");
1252 return error;
1253 }
1254 // Pass the long option, since you aren't actually required to have a
1255 // short_option, and for those options the index or short option character
1256 // aren't meaningful on the python side.
1257 const char *long_option =
1258 m_options_definition_up.get()[option_idx].long_option;
1259 bool success = m_cmd_interface_sp->SetOptionValue(
1260 execution_context, long_option, option_arg);
1261 if (!success)
1263 "Error setting option: {0} to {1}", long_option, option_arg);
1264 return error;
1265 }
1266
1267 void OptionParsingStarting(ExecutionContext *execution_context) override {
1268 if (!m_cmd_interface_sp)
1269 return;
1270
1271 m_cmd_interface_sp->OptionParsingStarted();
1272 }
1273
1274 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1276 return {};
1277 return llvm::ArrayRef(m_options_definition_up.get(), m_num_options);
1278 }
1279
1281 size_t counter, uint32_t &usage_mask) {
1282 // If the usage entry is not provided, we use LLDB_OPT_SET_ALL.
1283 // If the usage mask is a UINT, the option belongs to that group.
1284 // If the usage mask is a vector of UINT's, the option belongs to all the
1285 // groups listed.
1286 // If a subelement of the vector is a vector of two ints, then the option
1287 // belongs to the inclusive range from the first to the second element.
1288 Status error;
1289 if (!obj_sp) {
1290 usage_mask = LLDB_OPT_SET_ALL;
1291 return error;
1292 }
1293
1294 usage_mask = 0;
1295
1297 obj_sp->GetAsUnsignedInteger();
1298 if (uint_val) {
1299 // If this is an integer, then this specifies a single group:
1300 uint32_t value = uint_val->GetValue();
1301 if (value == 0) {
1303 "0 is not a valid group for option {0}", counter);
1304 }
1305 usage_mask = (1 << (value - 1));
1306 return error;
1307 }
1308 // Otherwise it has to be an array:
1309 StructuredData::Array *array_val = obj_sp->GetAsArray();
1310 if (!array_val) {
1312 "required field is not a array for option {0}", counter);
1313 }
1314 // This is the array ForEach for accumulating a group usage mask from
1315 // an array of string descriptions of groups.
1316 auto groups_accumulator
1317 = [counter, &usage_mask, &error]
1318 (StructuredData::Object *obj) -> bool {
1319 StructuredData::UnsignedInteger *int_val = obj->GetAsUnsignedInteger();
1320 if (int_val) {
1321 uint32_t value = int_val->GetValue();
1322 if (value == 0) {
1324 "0 is not a valid group for element {0}", counter);
1325 return false;
1326 }
1327 usage_mask |= (1 << (value - 1));
1328 return true;
1329 }
1330 StructuredData::Array *arr_val = obj->GetAsArray();
1331 if (!arr_val) {
1333 "Group element not an int or array of integers for element {0}",
1334 counter);
1335 return false;
1336 }
1337 size_t num_range_elem = arr_val->GetSize();
1338 if (num_range_elem != 2) {
1340 "Subranges of a group not a start and a stop for element {0}",
1341 counter);
1342 return false;
1343 }
1344 int_val = arr_val->GetItemAtIndex(0)->GetAsUnsignedInteger();
1345 if (!int_val) {
1347 "Start element of a subrange of a "
1348 "group not unsigned int for element {0}",
1349 counter);
1350 return false;
1351 }
1352 uint32_t start = int_val->GetValue();
1353 int_val = arr_val->GetItemAtIndex(1)->GetAsUnsignedInteger();
1354 if (!int_val) {
1356 "End element of a subrange of a group"
1357 " not unsigned int for element {0}",
1358 counter);
1359 return false;
1360 }
1361 uint32_t end = int_val->GetValue();
1362 if (start == 0 || end == 0 || start > end) {
1364 "Invalid subrange of a group: {0} - "
1365 "{1} for element {2}",
1366 start, end, counter);
1367 return false;
1368 }
1369 for (uint32_t i = start; i <= end; i++) {
1370 usage_mask |= (1 << (i - 1));
1371 }
1372 return true;
1373 };
1374 array_val->ForEach(groups_accumulator);
1375 return error;
1376 }
1377
1378
1380 Status error;
1381 m_num_options = options.GetSize();
1383 // We need to hand out pointers to contents of these vectors; we reserve
1384 // as much as we'll need up front so they don't get freed on resize...
1388
1389 size_t counter = 0;
1390 size_t short_opt_counter = 0;
1391 // This is the Array::ForEach function for adding option elements:
1392 auto add_element = [this, &error, &counter, &short_opt_counter]
1393 (llvm::StringRef long_option, StructuredData::Object *object) -> bool {
1394 StructuredData::Dictionary *opt_dict = object->GetAsDictionary();
1395 if (!opt_dict) {
1397 "Value in options dictionary is not a dictionary");
1398 return false;
1399 }
1400 OptionDefinition &option_def = m_options_definition_up.get()[counter];
1401
1402 // We aren't exposing the validator yet, set it to null
1403 option_def.validator = nullptr;
1404 // We don't require usage masks, so set it to one group by default:
1405 option_def.usage_mask = 1;
1406
1407 // Now set the fields of the OptionDefinition Array from the dictionary:
1408 //
1409 // Note that I don't check for unknown fields in the option dictionaries
1410 // so a scriptor can add extra elements that are helpful when they go to
1411 // do "set_option_value"
1412
1413 // Usage Mask:
1414 StructuredData::ObjectSP obj_sp = opt_dict->GetValueForKey("groups");
1415 if (obj_sp) {
1416 error = ParseUsageMaskFromArray(obj_sp, counter,
1417 option_def.usage_mask);
1418 if (error.Fail())
1419 return false;
1420 }
1421
1422 // Required:
1423 option_def.required = false;
1424 obj_sp = opt_dict->GetValueForKey("required");
1425 if (obj_sp) {
1426 StructuredData::Boolean *boolean_val = obj_sp->GetAsBoolean();
1427 if (!boolean_val) {
1429 "'required' field is not a boolean "
1430 "for option {0}",
1431 counter);
1432 return false;
1433 }
1434 option_def.required = boolean_val->GetValue();
1435 }
1436
1437 // Short Option:
1438 int short_option;
1439 obj_sp = opt_dict->GetValueForKey("short_option");
1440 if (obj_sp) {
1441 // The value is a string, so pull the
1442 llvm::StringRef short_str = obj_sp->GetStringValue();
1443 if (short_str.empty()) {
1445 "short_option field empty for "
1446 "option {0}",
1447 counter);
1448 return false;
1449 } else if (short_str.size() != 1) {
1451 "short_option field has extra "
1452 "characters for option {0}",
1453 counter);
1454 return false;
1455 }
1456 short_option = (int) short_str[0];
1457 } else {
1458 // If the short option is not provided, then we need a unique value
1459 // less than the lowest printable ASCII character.
1460 short_option = short_opt_counter++;
1461 }
1462 option_def.short_option = short_option;
1463
1464 // Long Option is the key from the outer dict:
1465 if (long_option.empty()) {
1467 "empty long_option for option {0}", counter);
1468 return false;
1469 }
1470 auto inserted = g_string_storer.insert(long_option.str());
1471 option_def.long_option = ((*(inserted.first)).data());
1472
1473 // Value Type:
1474 obj_sp = opt_dict->GetValueForKey("value_type");
1475 if (obj_sp) {
1477 = obj_sp->GetAsUnsignedInteger();
1478 if (!uint_val) {
1480 "Value type must be an unsigned "
1481 "integer");
1482 return false;
1483 }
1484 uint64_t val_type = uint_val->GetValue();
1485 if (val_type >= eArgTypeLastArg) {
1486 error =
1487 Status::FromErrorStringWithFormatv("Value type {0} beyond the "
1488 "CommandArgumentType bounds",
1489 val_type);
1490 return false;
1491 }
1492 option_def.argument_type = (CommandArgumentType) val_type;
1493 option_def.option_has_arg = true;
1494 } else {
1495 option_def.argument_type = eArgTypeNone;
1496 option_def.option_has_arg = false;
1497 }
1498
1499 // Completion Type:
1500 obj_sp = opt_dict->GetValueForKey("completion_type");
1501 if (obj_sp) {
1502 StructuredData::UnsignedInteger *uint_val = obj_sp->GetAsUnsignedInteger();
1503 if (!uint_val) {
1505 "Completion type must be an "
1506 "unsigned integer for option {0}",
1507 counter);
1508 return false;
1509 }
1510 uint64_t completion_type = uint_val->GetValue();
1511 if (completion_type > eCustomCompletion) {
1513 "Completion type for option {0} "
1514 "beyond the CompletionType bounds",
1515 completion_type);
1516 return false;
1517 }
1518 option_def.completion_type = (CommandArgumentType) completion_type;
1519 } else
1520 option_def.completion_type = eNoCompletion;
1521
1522 // Usage Text:
1523 obj_sp = opt_dict->GetValueForKey("help");
1524 if (!obj_sp) {
1526 "required usage missing from option "
1527 "{0}",
1528 counter);
1529 return false;
1530 }
1531 llvm::StringRef usage_stref;
1532 usage_stref = obj_sp->GetStringValue();
1533 if (usage_stref.empty()) {
1535 "empty usage text for option {0}", counter);
1536 return false;
1537 }
1538 m_usage_container[counter] = usage_stref.str().c_str();
1539 option_def.usage_text = m_usage_container[counter].data();
1540
1541 // Enum Values:
1542
1543 obj_sp = opt_dict->GetValueForKey("enum_values");
1544 if (obj_sp) {
1545 StructuredData::Array *array = obj_sp->GetAsArray();
1546 if (!array) {
1548 "enum values must be an array for "
1549 "option {0}",
1550 counter);
1551 return false;
1552 }
1553 size_t num_elem = array->GetSize();
1554 size_t enum_ctr = 0;
1555 m_enum_storage[counter] = std::vector<EnumValueStorage>(num_elem);
1556 std::vector<EnumValueStorage> &curr_elem = m_enum_storage[counter];
1557
1558 // This is the Array::ForEach function for adding enum elements:
1559 // Since there are only two fields to specify the enum, use a simple
1560 // two element array with value first, usage second.
1561 // counter is only used for reporting so I pass it by value here.
1562 auto add_enum = [&enum_ctr, &curr_elem, counter, &error]
1563 (StructuredData::Object *object) -> bool {
1564 StructuredData::Array *enum_arr = object->GetAsArray();
1565 if (!enum_arr) {
1567 "Enum values for option {0} not "
1568 "an array",
1569 counter);
1570 return false;
1571 }
1572 size_t num_enum_elements = enum_arr->GetSize();
1573 if (num_enum_elements != 2) {
1575 "Wrong number of elements: {0} "
1576 "for enum {1} in option {2}",
1577 num_enum_elements, enum_ctr, counter);
1578 return false;
1579 }
1580 // Enum Value:
1581 StructuredData::ObjectSP obj_sp = enum_arr->GetItemAtIndex(0);
1582 llvm::StringRef val_stref = obj_sp->GetStringValue();
1583 std::string value_cstr_str = val_stref.str().c_str();
1584
1585 // Enum Usage:
1586 obj_sp = enum_arr->GetItemAtIndex(1);
1587 if (!obj_sp) {
1589 "No usage for enum {0} in option "
1590 "{1}",
1591 enum_ctr, counter);
1592 return false;
1593 }
1594 llvm::StringRef usage_stref = obj_sp->GetStringValue();
1595 std::string usage_cstr_str = usage_stref.str().c_str();
1596 curr_elem[enum_ctr] = EnumValueStorage(value_cstr_str,
1597 usage_cstr_str, enum_ctr);
1598
1599 enum_ctr++;
1600 return true;
1601 }; // end of add_enum
1602
1603 array->ForEach(add_enum);
1604 if (!error.Success())
1605 return false;
1606 // We have to have a vector of elements to set in the options, make
1607 // that here:
1608 for (auto &elem : curr_elem)
1609 m_enum_vector[counter].emplace_back(elem.element);
1610
1611 option_def.enum_values = llvm::ArrayRef(m_enum_vector[counter]);
1612 }
1613 counter++;
1614 return true;
1615 }; // end of add_element
1616
1617 options.ForEach(add_element);
1618 return error;
1619 }
1620
1621 size_t GetNumOptions() { return m_num_options; }
1622
1624 OptionElementVector &option_vec,
1625 ExecutionContext *exe_ctx) {
1626 // I'm not sure if we'll get into trouble doing an option parsing start
1627 // and end in this context. If so, then I'll have to directly tell the
1628 // scripter to do this.
1629 OptionParsingStarting(exe_ctx);
1630 auto opt_defs = GetDefinitions();
1631
1632 // Iterate through the options we found so far, and push them into
1633 // the scripted side.
1634 for (auto option_elem : option_vec) {
1635 int cur_defs_index = option_elem.opt_defs_index;
1636 // If we don't recognize this option we can't set it.
1637 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
1638 cur_defs_index == OptionArgElement::eBareDash ||
1639 cur_defs_index == OptionArgElement::eBareDoubleDash)
1640 continue;
1641 bool option_has_arg = opt_defs[cur_defs_index].option_has_arg;
1642 llvm::StringRef cur_arg_value;
1643 if (option_has_arg) {
1644 int cur_arg_pos = option_elem.opt_arg_pos;
1645 if (cur_arg_pos != OptionArgElement::eUnrecognizedArg &&
1646 cur_arg_pos != OptionArgElement::eBareDash &&
1647 cur_arg_pos != OptionArgElement::eBareDoubleDash) {
1648 cur_arg_value =
1649 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
1650 }
1651 }
1652 SetOptionValue(cur_defs_index, cur_arg_value, exe_ctx);
1653 }
1654 OptionParsingFinished(exe_ctx);
1655 }
1656
1657 void
1659 StructuredData::DictionarySP &completion_dict_sp) {
1660 // We don't know how to process an empty completion dict, our callers have
1661 // to do that.
1662 assert(completion_dict_sp && "Must have valid completion dict");
1663 // First handle the case of a single completion:
1664 llvm::StringRef completion;
1665 // If the dictionary has one element "no-completion" then we return here
1666 if (completion_dict_sp->GetValueForKeyAsString("no-completion",
1667 completion))
1668 return;
1669
1670 if (completion_dict_sp->GetValueForKeyAsString("completion",
1671 completion)) {
1672 llvm::StringRef mode_str;
1674 if (completion_dict_sp->GetValueForKeyAsString("mode", mode_str)) {
1675 if (mode_str == "complete")
1677 else if (mode_str == "partial")
1679 else {
1680 // FIXME - how do I report errors here?
1681 return;
1682 }
1683 }
1684 request.AddCompletion(completion, "", mode);
1685 return;
1686 }
1687 // The completions are required, the descriptions are not:
1688 StructuredData::Array *completions;
1689 StructuredData::Array *descriptions;
1690 if (completion_dict_sp->GetValueForKeyAsArray("values", completions)) {
1691 completion_dict_sp->GetValueForKeyAsArray("descriptions", descriptions);
1692 size_t num_completions = completions->GetSize();
1693 for (size_t idx = 0; idx < num_completions; idx++) {
1694 auto val = completions->GetItemAtIndexAsString(idx);
1695 if (!val)
1696 // FIXME: How do I report this error?
1697 return;
1698
1699 if (descriptions) {
1700 auto desc = descriptions->GetItemAtIndexAsString(idx);
1701 request.AddCompletion(*val, desc ? *desc : "");
1702 } else
1703 request.AddCompletion(*val);
1704 }
1705 }
1706 }
1707
1708 void
1710 OptionElementVector &option_vec,
1711 int opt_element_index,
1712 CommandInterpreter &interpreter) override {
1713 if (!m_cmd_interface_sp)
1714 return;
1715
1716 ExecutionContext exe_ctx = interpreter.GetExecutionContext();
1717 PrepareOptionsForCompletion(request, option_vec, &exe_ctx);
1718
1719 auto defs = GetDefinitions();
1720
1721 size_t defs_index = option_vec[opt_element_index].opt_defs_index;
1722 llvm::StringRef option_name = defs[defs_index].long_option;
1723 bool is_enum = defs[defs_index].enum_values.size() != 0;
1724 if (option_name.empty())
1725 return;
1726 // If this is an enum, we don't call the custom completer, just let the
1727 // regular option completer handle that:
1728 StructuredData::DictionarySP completion_dict_sp;
1729 if (!is_enum)
1730 completion_dict_sp = m_cmd_interface_sp->HandleOptionArgumentCompletion(
1731 option_name, request.GetCursorCharPos());
1732
1733 if (!completion_dict_sp) {
1734 Options::HandleOptionArgumentCompletion(request, option_vec,
1735 opt_element_index, interpreter);
1736 return;
1737 }
1738
1739 ProcessCompletionDict(request, completion_dict_sp);
1740 }
1741
1742 private:
1745 element.string_value = "value not set";
1746 element.usage = "usage not set";
1747 element.value = 0;
1748 }
1749
1750 EnumValueStorage(std::string in_str_val, std::string in_usage,
1751 size_t in_value) : value(std::move(in_str_val)), usage(std::move(in_usage)) {
1752 SetElement(in_value);
1753 }
1754
1756 usage(in.usage) {
1758 }
1759
1761 value = in.value;
1762 usage = in.usage;
1764 return *this;
1765 }
1766
1767 void SetElement(size_t in_value) {
1768 element.value = in_value;
1769 element.string_value = value.data();
1770 element.usage = usage.data();
1771 }
1772
1773 std::string value;
1774 std::string usage;
1776 };
1777 // We have to provide char * values for the long option, usage and enum
1778 // values, that's what the option definitions hold.
1779 // The long option strings are quite likely to be reused in other added
1780 // commands, so those are stored in a global set: g_string_storer.
1781 // But the usages are much less likely to be reused, so those are stored in
1782 // a vector in the command instance. It gets resized to the correct size
1783 // and then filled with null-terminated strings in the std::string, so the
1784 // are valid C-strings that won't move around.
1785 // The enum values and descriptions are treated similarly - these aren't
1786 // all that common so it's not worth the effort to dedup them.
1787 size_t m_num_options = 0;
1788 std::unique_ptr<OptionDefinition> m_options_definition_up;
1789 std::vector<std::vector<EnumValueStorage>> m_enum_storage;
1790 std::vector<std::vector<OptionEnumValueElement>> m_enum_vector;
1791 std::vector<std::string> m_usage_container;
1793 static std::unordered_set<std::string> g_string_storer;
1794 };
1795
1796public:
1797 static CommandObjectSP
1798 Create(CommandInterpreter &interpreter, std::string name,
1799 lldb::ScriptedCommandInterfaceSP cmd_interface_sp,
1802 interpreter, name, cmd_interface_sp, synch));
1803
1805 = static_cast<CommandObjectScriptingObjectParsed *>(new_cmd_sp.get());
1806 // Now check all the failure modes, and report if found.
1807 Status opt_error = parsed_cmd->GetOptionsError();
1808 Status arg_error = parsed_cmd->GetArgsError();
1809
1810 if (opt_error.Fail())
1811 result.AppendErrorWithFormat("failed to parse option definitions: %s",
1812 opt_error.AsCString());
1813 if (arg_error.Fail())
1814 result.AppendErrorWithFormat("%sfailed to parse argument definitions: %s",
1815 opt_error.Fail() ? ", also " : "",
1816 arg_error.AsCString());
1817
1818 if (!result.Succeeded())
1819 return {};
1820
1821 return new_cmd_sp;
1822 }
1823
1825 CommandInterpreter &interpreter, std::string name,
1826 lldb::ScriptedCommandInterfaceSP cmd_interface_sp,
1828 : CommandObjectParsed(interpreter, name.c_str()),
1829 m_cmd_interface_sp(cmd_interface_sp), m_synchro(synch),
1830 m_options(cmd_interface_sp), m_fetched_help_short(false),
1831 m_fetched_help_long(false) {
1832 StreamString stream;
1833 if (!m_cmd_interface_sp) {
1834 m_options_error = Status::FromErrorString("No script interpreter");
1835 return;
1836 }
1837
1838 // Set the flags:
1839 GetFlags().Set(m_cmd_interface_sp->GetFlags());
1840
1841 // Now set up the options definitions from the options:
1842 StructuredData::ObjectSP options_object_sp =
1843 m_cmd_interface_sp->GetOptionsDefinition();
1844 // It's okay not to have an options dict.
1845 if (options_object_sp) {
1846 // The options come as a dictionary of dictionaries. The key of the
1847 // outer dict is the long option name (since that's required). The
1848 // value holds all the other option specification bits.
1849 StructuredData::Dictionary *options_dict =
1850 options_object_sp->GetAsDictionary();
1851 // but if it exists, it has to be an array.
1852 if (options_dict) {
1853 m_options_error = m_options.SetOptionsFromArray(*(options_dict));
1854 // If we got an error don't bother with the arguments...
1855 if (m_options_error.Fail())
1856 return;
1857 } else {
1858 m_options_error = Status::FromErrorString("Options array not an array");
1859 return;
1860 }
1861 }
1862 // Then fetch the args. Since the arguments can have usage masks you need
1863 // an array of arrays.
1864 StructuredData::ObjectSP args_object_sp =
1865 m_cmd_interface_sp->GetArgumentsDefinition();
1866 if (args_object_sp) {
1867 StructuredData::Array *args_array = args_object_sp->GetAsArray();
1868 if (!args_array) {
1869 m_args_error =
1870 Status::FromErrorString("Argument specification is not an array");
1871 return;
1872 }
1873 size_t counter = 0;
1874
1875 // This is the Array::ForEach function that handles the
1876 // CommandArgumentEntry arrays one by one:
1877 auto arg_array_adder = [this, &counter] (StructuredData::Object *object)
1878 -> bool {
1879 // This is the Array::ForEach function to add argument entries:
1880 CommandArgumentEntry this_entry;
1881 size_t elem_counter = 0;
1882 auto args_adder = [this, counter, &elem_counter, &this_entry]
1883 (StructuredData::Object *object) -> bool {
1884 // The arguments definition has three fields, the argument type, the
1885 // repeat and the usage mask.
1888 uint32_t arg_opt_set_association;
1889
1890 auto report_error = [this, elem_counter,
1891 counter](const char *err_txt) -> bool {
1893 "element {} of arguments list element {}: {}", elem_counter,
1894 counter, err_txt);
1895 return false;
1896 };
1897
1898 StructuredData::Dictionary *arg_dict = object->GetAsDictionary();
1899 if (!arg_dict) {
1900 report_error("is not a dictionary.");
1901 return false;
1902 }
1903 // Argument Type:
1905 = arg_dict->GetValueForKey("arg_type");
1906 if (obj_sp) {
1908 = obj_sp->GetAsUnsignedInteger();
1909 if (!uint_val) {
1910 report_error("value type must be an unsigned integer");
1911 return false;
1912 }
1913 uint64_t arg_type_int = uint_val->GetValue();
1914 if (arg_type_int >= eArgTypeLastArg) {
1915 report_error("value type beyond ArgumentRepetitionType bounds");
1916 return false;
1917 }
1918 arg_type = (CommandArgumentType) arg_type_int;
1919 }
1920 // Repeat Value:
1921 obj_sp = arg_dict->GetValueForKey("repeat");
1922 std::optional<ArgumentRepetitionType> repeat;
1923 if (obj_sp) {
1924 llvm::StringRef repeat_str = obj_sp->GetStringValue();
1925 if (repeat_str.empty()) {
1926 report_error("repeat value is empty");
1927 return false;
1928 }
1929 repeat = ArgRepetitionFromString(repeat_str);
1930 if (!repeat) {
1931 report_error("invalid repeat value");
1932 return false;
1933 }
1934 arg_repetition = *repeat;
1935 }
1936
1937 // Usage Mask:
1938 obj_sp = arg_dict->GetValueForKey("groups");
1940 counter, arg_opt_set_association);
1941 this_entry.emplace_back(arg_type, arg_repetition,
1942 arg_opt_set_association);
1943 elem_counter++;
1944 return true;
1945 };
1946 StructuredData::Array *args_array = object->GetAsArray();
1947 if (!args_array) {
1948 m_args_error =
1949 Status::FromErrorStringWithFormatv("Argument definition element "
1950 "{0} is not an array",
1951 counter);
1952 }
1953
1954 args_array->ForEach(args_adder);
1955 if (m_args_error.Fail())
1956 return false;
1957 if (this_entry.empty()) {
1958 m_args_error =
1959 Status::FromErrorStringWithFormatv("Argument definition element "
1960 "{0} is empty",
1961 counter);
1962 return false;
1963 }
1964 m_arguments.push_back(this_entry);
1965 counter++;
1966 return true;
1967 }; // end of arg_array_adder
1968 // Here we actually parse the args definition:
1969 args_array->ForEach(arg_array_adder);
1970 }
1971 }
1972
1974
1976 Status GetArgsError() { return m_args_error.Clone(); }
1977 bool WantsCompletion() override { return true; }
1978
1979private:
1981 OptionElementVector &option_vec) {
1982 // First, we have to tell the Scripted side to set the values in its
1983 // option store, then we call into the handle_completion passing in
1984 // an array of the args, the arg index and the cursor position in the arg.
1985 // We want the script side to have a chance to clear its state, so tell
1986 // it argument parsing has started:
1987 Options *options = GetOptions();
1988 // If there are not options, this will be nullptr, and in that case we
1989 // can just skip setting the options on the scripted side:
1990 if (options)
1991 m_options.PrepareOptionsForCompletion(request, option_vec, &m_exe_ctx);
1992 }
1993
1994public:
1996 OptionElementVector &option_vec) override {
1997 if (!m_cmd_interface_sp)
1998 return;
1999
2000 // Set up the options values on the scripted side:
2001 PrepareOptionsForCompletion(request, option_vec);
2002
2003 // Now we have to make up the argument list.
2004 // The ParseForCompletion only identifies tokens in the m_parsed_line
2005 // it doesn't remove the options leaving only the args as it does for
2006 // the regular Parse, so we have to filter out the option ones using the
2007 // option_element_vector:
2008
2009 Options *options = GetOptions();
2010 auto defs = options ? options->GetDefinitions()
2011 : llvm::ArrayRef<OptionDefinition>();
2012
2013 std::unordered_set<size_t> option_slots;
2014 for (const auto &elem : option_vec) {
2015 if (elem.opt_defs_index == -1)
2016 continue;
2017 option_slots.insert(elem.opt_pos);
2018 if (defs[elem.opt_defs_index].option_has_arg)
2019 option_slots.insert(elem.opt_arg_pos);
2020 }
2021
2022 std::vector<std::string> args_vec;
2023 Args &args = request.GetParsedLine();
2024 size_t num_args = args.GetArgumentCount();
2025 size_t cursor_idx = request.GetCursorIndex();
2026 size_t args_elem_pos = cursor_idx;
2027
2028 for (size_t idx = 0; idx < num_args; idx++) {
2029 if (option_slots.count(idx) == 0)
2030 args_vec.push_back(args[idx].ref().str());
2031 else if (idx < cursor_idx)
2032 args_elem_pos--;
2033 }
2034 StructuredData::DictionarySP completion_dict_sp =
2035 m_cmd_interface_sp->HandleArgumentCompletion(
2036 args_vec, args_elem_pos, request.GetCursorCharPos());
2037
2038 if (!completion_dict_sp) {
2039 CommandObject::HandleArgumentCompletion(request, option_vec);
2040 return;
2041 }
2042
2043 m_options.ProcessCompletionDict(request, completion_dict_sp);
2044 }
2045
2046 bool IsRemovable() const override { return true; }
2047
2049
2050 std::optional<std::string> GetRepeatCommand(Args &args,
2051 uint32_t index) override {
2052 if (!m_cmd_interface_sp)
2053 return std::nullopt;
2054
2055 return m_cmd_interface_sp->GetRepeatCommand(args);
2056 }
2057
2058 llvm::StringRef GetHelp() override {
2061 if (!m_cmd_interface_sp)
2063 std::string docstring;
2064 m_fetched_help_short = m_cmd_interface_sp->GetShortHelp(docstring);
2065 if (!docstring.empty())
2066 SetHelp(docstring);
2067
2069 }
2070
2071 llvm::StringRef GetHelpLong() override {
2074
2075 if (!m_cmd_interface_sp)
2077
2078 std::string docstring;
2079 m_fetched_help_long = m_cmd_interface_sp->GetLongHelp(docstring);
2080 if (!docstring.empty())
2081 SetHelpLong(docstring);
2083 }
2084
2085 Options *GetOptions() override {
2086 // CommandObjectParsed requires that a command with no options return
2087 // nullptr.
2088 if (m_options.GetNumOptions() == 0)
2089 return nullptr;
2090 return &m_options;
2091 }
2092
2093protected:
2094 void DoExecute(Args &args, CommandReturnObject &result) override {
2095 Status error;
2096
2098
2099 if (!m_cmd_interface_sp || !m_cmd_interface_sp->RunParsedCommand(
2100 args, m_synchro, result, error, m_exe_ctx)) {
2101 result.AppendError(error.AsCString());
2102 } else {
2103 // Don't change the status if the command already set it...
2104 if (result.GetStatus() == eReturnStatusInvalid) {
2105 if (result.GetOutputString().empty())
2107 else
2109 }
2110 }
2111 }
2112
2113private:
2121};
2122
2123std::unordered_set<std::string>
2125
2126// CommandObjectCommandsScriptImport
2127#define LLDB_OPTIONS_script_import
2128#include "CommandOptions.inc"
2129
2131public:
2133 : CommandObjectParsed(interpreter, "command script import",
2134 "Import a scripting module in LLDB.", nullptr) {
2136 }
2137
2139
2140 Options *GetOptions() override { return &m_options; }
2141
2142protected:
2143 class CommandOptions : public Options {
2144 public:
2145 CommandOptions() = default;
2146
2147 ~CommandOptions() override = default;
2148
2149 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2150 ExecutionContext *execution_context) override {
2151 Status error;
2152 const int short_option = m_getopt_table[option_idx].val;
2153
2154 switch (short_option) {
2155 case 'r':
2156 // NO-OP
2157 break;
2158 case 'c':
2160 break;
2161 case 's':
2162 silent = true;
2163 break;
2164 default:
2165 llvm_unreachable("Unimplemented option");
2166 }
2167
2168 return error;
2169 }
2170
2171 void OptionParsingStarting(ExecutionContext *execution_context) override {
2173 }
2174
2175 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2176 return llvm::ArrayRef(g_script_import_options);
2177 }
2179 bool silent = false;
2180 };
2181
2182 void DoExecute(Args &command, CommandReturnObject &result) override {
2183 if (command.empty()) {
2184 result.AppendError("command script import needs one or more arguments");
2185 return;
2186 }
2187
2188 FileSpec source_dir = {};
2189 if (m_options.relative_to_command_file) {
2191 if (!source_dir) {
2192 result.AppendError("command script import -c can only be specified "
2193 "from a command file");
2194 return;
2195 }
2196 }
2197
2198 for (auto &entry : command.entries()) {
2199 Status error;
2200
2201 LoadScriptOptions options;
2202 options.SetInitSession(true);
2203 options.SetSilent(m_options.silent);
2204
2205 // FIXME: this is necessary because CommandObject::CheckRequirements()
2206 // assumes that commands won't ever be recursively invoked, but it's
2207 // actually possible to craft a Python script that does other "command
2208 // script imports" in __lldb_init_module the real fix is to have
2209 // recursive commands possible with a CommandInvocation object separate
2210 // from the CommandObject itself, so that recursive command invocations
2211 // won't stomp on each other (wrt to execution contents, options, and
2212 // more)
2213 m_exe_ctx.Clear();
2214 if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
2215 entry.c_str(), options, error, /*module_sp=*/nullptr,
2216 source_dir)) {
2218 } else {
2219 result.AppendErrorWithFormat("module importing failed: %s",
2220 error.AsCString());
2221 }
2222 }
2223 }
2224
2226};
2227
2228#define LLDB_OPTIONS_script_add
2229#include "CommandOptions.inc"
2230
2233public:
2235 : CommandObjectParsed(interpreter, "command script add",
2236 "Add a scripted function as an LLDB command.",
2237 "Add a scripted function as an lldb command. "
2238 "If you provide a single argument, the command "
2239 "will be added at the root level of the command "
2240 "hierarchy. If there are more arguments they "
2241 "must be a path to a user-added container "
2242 "command, and the last element will be the new "
2243 "command name."),
2246 }
2247
2249
2250 Options *GetOptions() override { return &m_options; }
2251
2252 void
2254 OptionElementVector &opt_element_vector) override {
2256 opt_element_vector);
2257 }
2258
2259protected:
2260 class CommandOptions : public Options {
2261 public:
2262 CommandOptions() = default;
2263
2264 ~CommandOptions() override = default;
2265
2266 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2267 ExecutionContext *execution_context) override {
2268 Status error;
2269 const int short_option = m_getopt_table[option_idx].val;
2270
2271 switch (short_option) {
2272 case 'f':
2273 if (!option_arg.empty())
2274 m_funct_name = std::string(option_arg);
2275 break;
2276 case 'c':
2277 if (!option_arg.empty())
2278 m_class_name = std::string(option_arg);
2279 break;
2280 case 'h':
2281 if (!option_arg.empty())
2282 m_short_help = std::string(option_arg);
2283 break;
2284 case 'o':
2286 break;
2287 case 'p':
2288 m_parsed_command = true;
2289 break;
2290 case 's':
2293 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
2294 if (!error.Success())
2296 "unrecognized value for synchronicity '%s'",
2297 option_arg.str().c_str());
2298 break;
2299 case 'C': {
2300 Status error;
2301 OptionDefinition definition = GetDefinitions()[option_idx];
2302 lldb::CompletionType completion_type =
2304 option_arg, definition.enum_values, eNoCompletion, error));
2305 if (!error.Success())
2307 "unrecognized value for command completion type '%s'",
2308 option_arg.str().c_str());
2309 m_completion_type = completion_type;
2310 } break;
2311 default:
2312 llvm_unreachable("Unimplemented option");
2313 }
2314
2315 return error;
2316 }
2317
2327
2328 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2329 return llvm::ArrayRef(g_script_add_options);
2330 }
2331
2332 // Instance variables to hold the values for command options.
2333
2334 std::string m_class_name;
2335 std::string m_funct_name;
2336 std::string m_short_help;
2341 bool m_parsed_command = false;
2342 };
2343
2344 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
2345 if (interactive) {
2346 if (lldb::LockableStreamFileSP output_sp =
2347 io_handler.GetOutputStreamFileSP()) {
2348 LockedStreamFile locked_stream = output_sp->Lock();
2350 }
2351 }
2352 }
2353
2355 std::string &data) override {
2356 LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
2357
2359 if (interpreter) {
2360 StringList lines;
2361 lines.SplitIntoLines(data);
2362 if (lines.GetSize() > 0) {
2363 std::string funct_name_str;
2364 if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
2365 if (funct_name_str.empty()) {
2366 LockedStreamFile locked_stream = error_sp->Lock();
2367 locked_stream.Printf(
2368 "error: unable to obtain a function name, didn't "
2369 "add python command.\n");
2370 } else {
2371 // everything should be fine now, let's add this alias
2372
2374 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
2376 if (!m_container) {
2377 Status error = m_interpreter.AddUserCommand(
2378 m_cmd_name, command_obj_sp, m_overwrite);
2379 if (error.Fail()) {
2380 LockedStreamFile locked_stream = error_sp->Lock();
2381 locked_stream.Printf(
2382 "error: unable to add selected command: '%s'",
2383 error.AsCString());
2384 }
2385 } else {
2386 llvm::Error llvm_error = m_container->LoadUserSubcommand(
2387 m_cmd_name, command_obj_sp, m_overwrite);
2388 if (llvm_error) {
2389 LockedStreamFile locked_stream = error_sp->Lock();
2390 locked_stream.Printf(
2391 "error: unable to add selected command: '%s'",
2392 llvm::toString(std::move(llvm_error)).c_str());
2393 }
2394 }
2395 }
2396 } else {
2397 LockedStreamFile locked_stream = error_sp->Lock();
2398 locked_stream.Printf(
2399 "error: unable to create function, didn't add python command\n");
2400 }
2401 } else {
2402 LockedStreamFile locked_stream = error_sp->Lock();
2403 locked_stream.Printf(
2404 "error: empty function, didn't add python command\n");
2405 }
2406 } else {
2407 LockedStreamFile locked_stream = error_sp->Lock();
2408 locked_stream.Printf(
2409 "error: script interpreter missing, didn't add python command\n");
2410 }
2411
2412 io_handler.SetIsDone(true);
2413 }
2414
2415 void DoExecute(Args &command, CommandReturnObject &result) override {
2416 if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
2417 result.AppendError("only scripting language supported for scripted "
2418 "commands is currently Python");
2419 return;
2420 }
2421
2422 if (command.GetArgumentCount() == 0) {
2423 result.AppendError("'command script add' requires at least one argument");
2424 return;
2425 }
2426 // Store the options in case we get multi-line input, also figure out the
2427 // default if not user supplied:
2428 switch (m_options.m_overwrite_lazy) {
2429 case eLazyBoolCalculate:
2431 break;
2432 case eLazyBoolYes:
2433 m_overwrite = true;
2434 break;
2435 case eLazyBoolNo:
2436 m_overwrite = false;
2437 }
2438
2439 Status path_error;
2441 command, true, path_error);
2442
2443 if (path_error.Fail()) {
2444 result.AppendErrorWithFormat("error in command path: %s",
2445 path_error.AsCString());
2446 return;
2447 }
2448
2449 if (!m_container) {
2450 // This is getting inserted into the root of the interpreter.
2451 m_cmd_name = std::string(command[0].ref());
2452 } else {
2453 size_t num_args = command.GetArgumentCount();
2454 m_cmd_name = std::string(command[num_args - 1].ref());
2455 }
2456
2457 m_short_help.assign(m_options.m_short_help);
2458 m_synchronicity = m_options.m_synchronicity;
2459 m_completion_type = m_options.m_completion_type;
2460
2461 // Handle the case where we prompt for the script code first:
2462 if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
2463 m_interpreter.GetPythonCommandsFromIOHandler(" ", // Prompt
2464 *this); // IOHandlerDelegate
2465 // Still gathering input; the IOHandler will set the final status.
2467 return;
2468 }
2469
2470 CommandObjectSP new_cmd_sp;
2471 if (m_options.m_class_name.empty()) {
2472 new_cmd_sp = std::make_shared<CommandObjectPythonFunction>(
2473 m_interpreter, m_cmd_name, m_options.m_funct_name,
2475 } else {
2477 if (!interpreter) {
2478 result.AppendError("cannot find ScriptInterpreter");
2479 return;
2480 }
2481
2482 lldb::ScriptedCommandInterfaceSP cmd_interface_sp =
2483 interpreter->CreateScriptedCommandInterface();
2484 if (!cmd_interface_sp) {
2485 result.AppendError("cannot create ScriptedCommandInterface");
2486 return;
2487 }
2488
2489 auto obj_or_err = cmd_interface_sp->CreatePluginObject(
2490 m_options.m_class_name, GetDebugger().shared_from_this());
2491 if (!obj_or_err) {
2492 result.AppendErrorWithFormatv("cannot create helper object for: "
2493 "'{0}': {1}",
2494 m_options.m_class_name,
2495 llvm::toString(obj_or_err.takeError()));
2496 return;
2497 }
2498
2499 if (m_options.m_parsed_command) {
2501 m_interpreter, m_cmd_name, cmd_interface_sp, m_synchronicity,
2502 result);
2503 if (!result.Succeeded())
2504 return;
2505 } else
2506 new_cmd_sp = std::make_shared<CommandObjectScriptingObjectRaw>(
2507 m_interpreter, m_cmd_name, cmd_interface_sp, m_synchronicity,
2509 }
2510
2511 // Assume we're going to succeed...
2513 if (!m_container) {
2514 Status add_error =
2515 m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
2516 if (add_error.Fail())
2517 result.AppendErrorWithFormat("cannot add command: %s",
2518 add_error.AsCString());
2519 } else {
2520 llvm::Error llvm_error =
2521 m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
2522 if (llvm_error)
2523 result.AppendErrorWithFormat(
2524 "cannot add command: %s",
2525 llvm::toString(std::move(llvm_error)).c_str());
2526 }
2527 }
2528
2530 std::string m_cmd_name;
2532 std::string m_short_help;
2533 bool m_overwrite = false;
2537};
2538
2539// CommandObjectCommandsScriptList
2540
2542public:
2544 : CommandObjectParsed(interpreter, "command script list",
2545 "List defined top-level scripted commands.",
2546 nullptr) {}
2547
2549
2550 void DoExecute(Args &command, CommandReturnObject &result) override {
2552
2554 }
2555};
2556
2557// CommandObjectCommandsScriptClear
2558
2560public:
2562 : CommandObjectParsed(interpreter, "command script clear",
2563 "Delete all scripted commands.", nullptr) {}
2564
2566
2567protected:
2568 void DoExecute(Args &command, CommandReturnObject &result) override {
2569 m_interpreter.RemoveAllUser();
2570
2572 }
2573};
2574
2575// CommandObjectCommandsScriptDelete
2576
2578public:
2581 interpreter, "command script delete",
2582 "Delete a scripted command by specifying the path to the command.",
2583 nullptr) {
2585 }
2586
2588
2589 void
2591 OptionElementVector &opt_element_vector) override {
2593 m_interpreter, request, opt_element_vector);
2594 }
2595
2596protected:
2597 void DoExecute(Args &command, CommandReturnObject &result) override {
2598
2599 llvm::StringRef root_cmd = command[0].ref();
2600 size_t num_args = command.GetArgumentCount();
2601
2602 if (root_cmd.empty()) {
2603 result.AppendErrorWithFormat("empty root command name");
2604 return;
2605 }
2606 if (!m_interpreter.HasUserCommands() &&
2607 !m_interpreter.HasUserMultiwordCommands()) {
2608 result.AppendErrorWithFormat("can only delete user defined commands, "
2609 "but no user defined commands found");
2610 return;
2611 }
2612
2613 CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
2614 if (!cmd_sp) {
2615 result.AppendErrorWithFormat("command '%s' not found",
2616 command[0].c_str());
2617 return;
2618 }
2619 if (!cmd_sp->IsUserCommand()) {
2620 result.AppendErrorWithFormat("command '%s' is not a user command",
2621 command[0].c_str());
2622 return;
2623 }
2624 if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
2625 result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
2626 "Delete with \"command container delete\"",
2627 command[0].c_str());
2628 return;
2629 }
2630
2631 if (command.GetArgumentCount() == 1) {
2632 m_interpreter.RemoveUser(root_cmd);
2634 return;
2635 }
2636 // We're deleting a command from a multiword command. Verify the command
2637 // path:
2638 Status error;
2639 CommandObjectMultiword *container =
2641 error);
2642 if (error.Fail()) {
2643 result.AppendErrorWithFormat("could not resolve command path: %s",
2644 error.AsCString());
2645 return;
2646 }
2647 if (!container) {
2648 // This means that command only had a leaf command, so the container is
2649 // the root. That should have been handled above.
2650 result.AppendErrorWithFormat("could not find a container for '%s'",
2651 command[0].c_str());
2652 return;
2653 }
2654 const char *leaf_cmd = command[num_args - 1].c_str();
2655 llvm::Error llvm_error =
2656 container->RemoveUserSubcommand(leaf_cmd,
2657 /* multiword not okay */ false);
2658 if (llvm_error) {
2659 result.AppendErrorWithFormat(
2660 "could not delete command '%s': %s", leaf_cmd,
2661 llvm::toString(std::move(llvm_error)).c_str());
2662 return;
2663 }
2664
2665 Stream &out_stream = result.GetOutputStream();
2666
2667 out_stream << "Deleted command:";
2668 for (size_t idx = 0; idx < num_args; idx++) {
2669 out_stream << ' ';
2670 out_stream << command[idx].c_str();
2671 }
2672 out_stream << '\n';
2674 }
2675};
2676
2677#pragma mark CommandObjectMultiwordCommandsScript
2678
2679// CommandObjectMultiwordCommandsScript
2680
2682public:
2685 interpreter, "command script",
2686 "Commands for managing custom "
2687 "commands implemented by "
2688 "interpreter scripts.",
2689 "command script <subcommand> [<subcommand-options>]") {
2691 new CommandObjectCommandsScriptAdd(interpreter)));
2693 "delete",
2696 "clear",
2699 interpreter)));
2701 "import",
2703 }
2704
2706};
2707
2708#pragma mark CommandObjectCommandContainer
2709#define LLDB_OPTIONS_container_add
2710#include "CommandOptions.inc"
2711
2713public:
2716 interpreter, "command container add",
2717 "Add a container command to lldb. Adding to built-"
2718 "in container commands is not allowed.",
2719 "command container add [[path1]...] container-name") {
2721 }
2722
2724
2725 Options *GetOptions() override { return &m_options; }
2726
2727 void
2729 OptionElementVector &opt_element_vector) override {
2731 m_interpreter, request, opt_element_vector);
2732 }
2733
2734protected:
2735 class CommandOptions : public Options {
2736 public:
2737 CommandOptions() = default;
2738
2739 ~CommandOptions() override = default;
2740
2741 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2742 ExecutionContext *execution_context) override {
2743 Status error;
2744 const int short_option = m_getopt_table[option_idx].val;
2745
2746 switch (short_option) {
2747 case 'h':
2748 if (!option_arg.empty())
2749 m_short_help = std::string(option_arg);
2750 break;
2751 case 'o':
2752 m_overwrite = true;
2753 break;
2754 case 'H':
2755 if (!option_arg.empty())
2756 m_long_help = std::string(option_arg);
2757 break;
2758 default:
2759 llvm_unreachable("Unimplemented option");
2760 }
2761
2762 return error;
2763 }
2764
2765 void OptionParsingStarting(ExecutionContext *execution_context) override {
2766 m_short_help.clear();
2767 m_long_help.clear();
2768 m_overwrite = false;
2769 }
2770
2771 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2772 return llvm::ArrayRef(g_container_add_options);
2773 }
2774
2775 // Instance variables to hold the values for command options.
2776
2777 std::string m_short_help;
2778 std::string m_long_help;
2779 bool m_overwrite = false;
2780 };
2781 void DoExecute(Args &command, CommandReturnObject &result) override {
2782 size_t num_args = command.GetArgumentCount();
2783
2784 if (num_args == 0) {
2785 result.AppendError("no command was specified");
2786 return;
2787 }
2788
2789 if (num_args == 1) {
2790 // We're adding this as a root command, so use the interpreter.
2791 const char *cmd_name = command.GetArgumentAtIndex(0);
2792 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2793 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2794 m_options.m_long_help.c_str()));
2795 cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
2797 cmd_name, cmd_sp, m_options.m_overwrite);
2798 if (add_error.Fail()) {
2799 result.AppendErrorWithFormat("error adding command: %s",
2800 add_error.AsCString());
2801 return;
2802 }
2804 return;
2805 }
2806
2807 // We're adding this to a subcommand, first find the subcommand:
2808 Status path_error;
2809 CommandObjectMultiword *add_to_me =
2811 path_error);
2812
2813 if (!add_to_me) {
2814 result.AppendErrorWithFormat("error adding command: %s",
2815 path_error.AsCString());
2816 return;
2817 }
2818
2819 const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
2820 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2821 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2822 m_options.m_long_help.c_str()));
2823 llvm::Error llvm_error =
2824 add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
2825 if (llvm_error) {
2826 result.AppendErrorWithFormat("error adding subcommand: %s",
2827 llvm::toString(std::move(llvm_error)).c_str());
2828 return;
2829 }
2830
2832 }
2833
2834private:
2836};
2837
2838#define LLDB_OPTIONS_multiword_delete
2839#include "CommandOptions.inc"
2841public:
2844 interpreter, "command container delete",
2845 "Delete a container command previously added to "
2846 "lldb.",
2847 "command container delete [[path1] ...] container-cmd") {
2849 }
2850
2852
2853 void
2855 OptionElementVector &opt_element_vector) override {
2857 m_interpreter, request, opt_element_vector);
2858 }
2859
2860protected:
2861 void DoExecute(Args &command, CommandReturnObject &result) override {
2862 size_t num_args = command.GetArgumentCount();
2863
2864 if (num_args == 0) {
2865 result.AppendError("no command was specified");
2866 return;
2867 }
2868
2869 if (num_args == 1) {
2870 // We're removing a root command, so we need to delete it from the
2871 // interpreter.
2872 const char *cmd_name = command.GetArgumentAtIndex(0);
2873 // Let's do a little more work here so we can do better error reporting.
2875 CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2876 if (!cmd_sp) {
2877 result.AppendErrorWithFormat("container command %s doesn't exist",
2878 cmd_name);
2879 return;
2880 }
2881 if (!cmd_sp->IsUserCommand()) {
2882 result.AppendErrorWithFormat(
2883 "container command %s is not a user command", cmd_name);
2884 return;
2885 }
2886 if (!cmd_sp->GetAsMultiwordCommand()) {
2887 result.AppendErrorWithFormat("command %s is not a container command",
2888 cmd_name);
2889 return;
2890 }
2891
2892 bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2893 if (!did_remove) {
2894 result.AppendErrorWithFormat("error removing command %s", cmd_name);
2895 return;
2896 }
2897
2899 return;
2900 }
2901
2902 // We're removing a subcommand, first find the subcommand's owner:
2903 Status path_error;
2904 CommandObjectMultiword *container =
2906 path_error);
2907
2908 if (!container) {
2909 result.AppendErrorWithFormat("error removing container command: %s",
2910 path_error.AsCString());
2911 return;
2912 }
2913 const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2914 llvm::Error llvm_error =
2915 container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2916 if (llvm_error) {
2917 result.AppendErrorWithFormat("error removing container command: %s",
2918 llvm::toString(std::move(llvm_error)).c_str());
2919 return;
2920 }
2922 }
2923};
2924
2926public:
2929 interpreter, "command container",
2930 "Commands for adding container commands to lldb. "
2931 "Container commands are containers for other commands. You can "
2932 "add nested container commands by specifying a command path, "
2933 "but you can't add commands into the built-in command hierarchy.",
2934 "command container <subcommand> [<subcommand-options>]") {
2936 interpreter)));
2938 "delete",
2940 }
2941
2943};
2944
2945#pragma mark CommandObjectMultiwordCommands
2946
2947// CommandObjectMultiwordCommands
2948
2950 CommandInterpreter &interpreter)
2951 : CommandObjectMultiword(interpreter, "command",
2952 "Commands for managing custom LLDB commands.",
2953 "command <subcommand> [<subcommand-options>]") {
2954 LoadSubCommand("source",
2956 LoadSubCommand("alias",
2959 new CommandObjectCommandsUnalias(interpreter)));
2960 LoadSubCommand("delete",
2963 interpreter)));
2965 "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2967 "script",
2969}
2970
static const char * g_python_command_instructions
static llvm::raw_ostream & error(Stream &strm)
static bool LoadScriptingModule(const FileSpec &scripting_fspec, ScriptInterpreter &script_interpreter, Target &target, Status &error)
CommandObjectCommandContainer(CommandInterpreter &interpreter)
~CommandObjectCommandContainer() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
std::unique_ptr< CommandObjectRegexCommand > m_regex_cmd_up
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
~CommandObjectCommandsAddRegex() override=default
CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
Status AppendRegexSubstitution(const llvm::StringRef &regex_sed, bool check_only)
void DoExecute(Args &command, CommandReturnObject &result) override
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result)
void DoExecute(llvm::StringRef raw_command_line, CommandReturnObject &result) override
~CommandObjectCommandsAlias() override=default
bool HandleAliasingRawCommand(llvm::StringRef alias_command, llvm::StringRef raw_command_string, CommandObject &cmd_obj, CommandReturnObject &result)
CommandObjectCommandsAlias(CommandInterpreter &interpreter)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
~CommandObjectCommandsContainerAdd() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectCommandsContainerAdd(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectCommandsContainerDelete(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
~CommandObjectCommandsContainerDelete() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectCommandsDelete(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
~CommandObjectCommandsDelete() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectCommandsScriptAdd() override=default
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
ScriptedCommandSynchronicity m_synchronicity
CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
~CommandObjectCommandsScriptClear() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectCommandsScriptDelete() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectCommandsScriptImport() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectCommandsScriptList() override=default
CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
CommandObjectCommandsSource(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectCommandsSource() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
~CommandObjectCommandsUnalias() override=default
~CommandObjectMultiwordCommandsScript() override=default
CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
void DoExecute(llvm::StringRef raw_command_line, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
ScriptedCommandSynchronicity GetSynchronicity()
CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name, std::string funct, std::string help, ScriptedCommandSynchronicity synch, CompletionType completion_type)
ScriptedCommandSynchronicity m_synchro
llvm::StringRef GetHelpLong() override
~CommandObjectPythonFunction() override=default
static Status ParseUsageMaskFromArray(StructuredData::ObjectSP obj_sp, size_t counter, uint32_t &usage_mask)
std::unique_ptr< OptionDefinition > m_options_definition_up
CommandOptions(lldb::ScriptedCommandInterfaceSP cmd_interface_sp)
void OptionParsingStarting(ExecutionContext *execution_context) override
void HandleOptionArgumentCompletion(lldb_private::CompletionRequest &request, OptionElementVector &option_vec, int opt_element_index, CommandInterpreter &interpreter) override
Handles the generic bits of figuring out whether we are in an option, and if so completing it.
static std::unordered_set< std::string > g_string_storer
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
std::vector< std::vector< OptionEnumValueElement > > m_enum_vector
void ProcessCompletionDict(CompletionRequest &request, StructuredData::DictionarySP &completion_dict_sp)
std::vector< std::vector< EnumValueStorage > > m_enum_storage
void PrepareOptionsForCompletion(CompletionRequest &request, OptionElementVector &option_vec, ExecutionContext *exe_ctx)
Status SetOptionsFromArray(StructuredData::Dictionary &options)
static CommandObjectSP Create(CommandInterpreter &interpreter, std::string name, lldb::ScriptedCommandInterfaceSP cmd_interface_sp, ScriptedCommandSynchronicity synch, CommandReturnObject &result)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &option_vec) override
The default version handles argument definitions that have only one argument type,...
CommandObjectScriptingObjectParsed(CommandInterpreter &interpreter, std::string name, lldb::ScriptedCommandInterfaceSP cmd_interface_sp, ScriptedCommandSynchronicity synch)
void DoExecute(Args &args, CommandReturnObject &result) override
std::optional< std::string > GetRepeatCommand(Args &args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
~CommandObjectScriptingObjectParsed() override=default
void PrepareOptionsForCompletion(CompletionRequest &request, OptionElementVector &option_vec)
lldb::ScriptedCommandInterfaceSP m_cmd_interface_sp
ScriptedCommandSynchronicity GetSynchronicity()
CommandObjectScriptingObjectRaw(CommandInterpreter &interpreter, std::string name, lldb::ScriptedCommandInterfaceSP cmd_interface_sp, ScriptedCommandSynchronicity synch, CompletionType completion_type)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
std::optional< std::string > GetRepeatCommand(Args &args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
ScriptedCommandSynchronicity m_synchro
~CommandObjectScriptingObjectRaw() override=default
lldb::ScriptedCommandInterfaceSP m_cmd_interface_sp
ScriptedCommandSynchronicity GetSynchronicity()
void DoExecute(llvm::StringRef raw_command_line, CommandReturnObject &result) override
A command line argument class.
Definition Args.h:33
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition Args.cpp:295
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool GetCommandString(std::string &command) const
Definition Args.cpp:215
bool empty() const
Definition Args.h:122
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
static void CompleteModifiableCmdPathArgs(CommandInterpreter &interpreter, CompletionRequest &request, OptionElementVector &opt_element_vector)
This completer works for commands whose only arguments are a command path.
CommandObjectMultiword * VerifyUserMultiwordCmdPath(Args &path, bool leaf_is_command, Status &result)
Look up the command pointed to by path encoded in the arguments of the incoming command object.
Status AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd, bool include_aliases=false) const
ExecutionContext GetExecutionContext(bool adopt_dummy_target=true) const
Returns the execution context the interpreter should run a command in.
bool RemoveUserMultiword(llvm::StringRef multiword_name)
static void GenerateAdditionalHelpAvenuesMessage(Stream *s, llvm::StringRef command, llvm::StringRef prefix, llvm::StringRef subcommand, bool include_upropos=true, bool include_type_lookup=true)
CommandObjectMultiwordCommands(CommandInterpreter &interpreter)
llvm::Error LoadUserSubcommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj, bool can_replace) override
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
llvm::Error RemoveUserSubcommand(llvm::StringRef cmd_name, bool multiword_okay)
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
std::vector< CommandArgumentData > CommandArgumentEntry
virtual void SetHelpLong(llvm::StringRef str)
virtual bool WantsRawCommandString()=0
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
virtual llvm::StringRef GetHelpLong()
llvm::StringRef GetCommandName() const
static std::optional< ArgumentRepetitionType > ArgRepetitionFromString(llvm::StringRef string)
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
CommandObject(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
Flags & GetFlags()
The flags accessor.
virtual void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector)
The default version handles argument definitions that have only one argument type,...
virtual bool IsRemovable() const
virtual llvm::StringRef GetHelp()
virtual void SetHelp(llvm::StringRef str)
virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd, StringList *matches=nullptr)
void AppendError(llvm::StringRef in_string)
llvm::StringRef GetOutputString() const
void AppendWarningWithFormatv(const char *format, Args &&...args)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendWarning(llvm::StringRef in_string)
void AppendErrorWithFormatv(const char *format, Args &&...args)
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:182
bool GetUseColor() const
Definition Debugger.cpp:543
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
lldb::StreamUP GetAsyncOutputStream()
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:512
void MakeAbsolute(const FileSpec &dir)
Make the FileSpec absolute by treating it relative to dir.
Definition FileSpec.cpp:535
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
ValueType Set(ValueType mask)
Set one or more flags by logical OR'ing mask with the current flags.
Definition Flags.h:73
IOHandlerDelegateMultiline(llvm::StringRef end_line, Completion completion=Completion::None)
Definition IOHandler.h:289
A delegate class for use with IOHandler subclasses.
Definition IOHandler.h:184
lldb::LockableStreamFileSP GetErrorStreamFileSP()
Definition IOHandler.cpp:95
lldb::LockableStreamFileSP GetOutputStreamFileSP()
Definition IOHandler.cpp:93
void SetIsDone(bool b)
Definition IOHandler.h:81
LoadScriptOptions & SetInitSession(bool b)
LoadScriptOptions & SetSilent(bool b)
A command line option parsing protocol class.
Definition Options.h:58
virtual void HandleOptionArgumentCompletion(lldb_private::CompletionRequest &request, OptionElementVector &opt_element_vector, int opt_element_index, CommandInterpreter &interpreter)
Handles the generic bits of figuring out whether we are in an option, and if so completing it.
Definition Options.cpp:688
virtual Status OptionParsingFinished(ExecutionContext *execution_context)
Definition Options.h:226
virtual llvm::ArrayRef< OptionDefinition > GetDefinitions()
Definition Options.h:98
std::vector< Option > m_getopt_table
Definition Options.h:198
virtual lldb::ScriptedCommandInterfaceSP CreateScriptedCommandInterface()
virtual bool RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx)
virtual bool GenerateScriptAliasFunction(StringList &input, std::string &output)
virtual bool GetDocumentationForItem(const char *item, std::string &dest)
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t SplitIntoLines(const std::string &lines)
ObjectSP GetItemAtIndex(size_t idx) const
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
std::optional< llvm::StringRef > GetItemAtIndexAsString(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
void ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
Integer< uint64_t > UnsignedInteger
#define LLDB_OPT_SET_ALL
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
std::shared_ptr< OptionArgVector > OptionArgVectorSP
Definition Options.h:30
@ Partial
The current token has been partially completed.
@ Normal
The current token has been completed.
@ eScriptLanguagePython
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
@ eReturnStatusStarted
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eReturnStatusInvalid
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeSEDStylePair
@ eArgTypeCommandName
@ eArgTypeAliasOptions
std::shared_ptr< lldb_private::ScriptedCommandInterface > ScriptedCommandInterfaceSP
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
EnumValueStorage(std::string in_str_val, std::string in_usage, size_t in_value)
Used to build individual command argument lists.
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
OptionValidator * validator
If non-NULL, option is valid iff |validator->IsValid()|, otherwise always valid.
const char * long_option
Full name for this option.
const char * usage_text
Full text explaining what this options does and what (if any) argument to pass it.
bool required
This option is required (in the current usage level).
uint32_t completion_type
The kind of completion for this option.
int option_has_arg
no_argument, required_argument or optional_argument
uint32_t usage_mask
Used to mark options that can be used together.
lldb::CommandArgumentType argument_type
Type of argument this option takes.
OptionEnumValues enum_values
If not empty, an array of enum values.
int short_option
Single character for this option.