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