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::CommandMap::iterator pos;
631 CommandObject *cmd_obj;
632
633 if (args.empty()) {
634 result.AppendError("must call 'unalias' with a valid alias");
635 return;
636 }
637
638 auto command_name = args[0].ref();
639 cmd_obj = m_interpreter.GetCommandObject(command_name);
640 if (!cmd_obj) {
642 "'%s' is not a known command.\nTry 'help' to see a "
643 "current list of commands",
644 args[0].c_str());
645 return;
646 }
647
648 if (m_interpreter.CommandExists(command_name)) {
649 if (cmd_obj->IsRemovable()) {
651 "'%s' is not an alias, it is a debugger command which can be "
652 "removed using the 'command delete' command",
653 args[0].c_str());
654 } else {
656 "'%s' is a permanent debugger command and cannot be removed",
657 args[0].c_str());
658 }
659 return;
660 }
661
662 if (!m_interpreter.RemoveAlias(command_name)) {
663 if (m_interpreter.AliasExists(command_name))
665 "Error occurred while attempting to unalias '%s'", args[0].c_str());
666 else
667 result.AppendErrorWithFormat("'%s' is not an existing alias",
668 args[0].c_str());
669 return;
670 }
671
673 }
674};
675
676#pragma mark CommandObjectCommandsDelete
677// CommandObjectCommandsDelete
678
680public:
683 interpreter, "command delete",
684 "Delete one or more custom commands defined by 'command regex'.",
685 nullptr) {
687 }
688
689 ~CommandObjectCommandsDelete() override = default;
690
691 void
693 OptionElementVector &opt_element_vector) override {
694 if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
695 return;
696
697 for (const auto &ent : m_interpreter.GetCommands()) {
698 if (ent.second->IsRemovable())
699 request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
700 }
701 }
702
703protected:
704 void DoExecute(Args &args, CommandReturnObject &result) override {
705 CommandObject::CommandMap::iterator pos;
706
707 if (args.empty()) {
708 result.AppendErrorWithFormat("must call '%s' with one or more valid user "
709 "defined regular expression command names",
710 GetCommandName().str().c_str());
711 return;
712 }
713
714 auto command_name = args[0].ref();
715 if (!m_interpreter.CommandExists(command_name)) {
716 StreamString error_msg_stream;
717 const bool generate_upropos = true;
718 const bool generate_type_lookup = false;
720 &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
721 generate_upropos, generate_type_lookup);
722 result.AppendError(error_msg_stream.GetString());
723 return;
724 }
725
726 if (!m_interpreter.RemoveCommand(command_name)) {
728 "'%s' is a permanent debugger command and cannot be removed",
729 args[0].c_str());
730 return;
731 }
732
734 }
735};
736
737// CommandObjectCommandsAddRegex
738
739#define LLDB_OPTIONS_regex
740#include "CommandOptions.inc"
741
742#pragma mark CommandObjectCommandsAddRegex
743
746public:
749 interpreter, "command regex",
750 "Define a custom command in terms of "
751 "existing commands by matching "
752 "regular expressions.",
753 "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
757 R"(
758)"
759 "This command allows the user to create powerful regular expression commands \
760with substitutions. The regular expressions and substitutions are specified \
761using the regular expression substitution format of:"
762 R"(
763
764 s/<regex>/<subst>/
765
766)"
767 "<regex> is a regular expression that can use parenthesis to capture regular \
768expression input and substitute the captured matches in the output using %1 \
769for the first match, %2 for the second, and so on."
770 R"(
771
772)"
773 "The regular expressions can all be specified on the command line if more than \
774one argument is provided. If just the command name is provided on the command \
775line, then the regular expressions and substitutions can be entered on separate \
776lines, followed by an empty line to terminate the command definition."
777 R"(
779EXAMPLES
780
782 "The following example will define a regular expression command named 'f' that \
783will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
784a number follows 'f':"
785 R"(
786
787 (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
789 }
790
791 ~CommandObjectCommandsAddRegex() override = default;
792
793protected:
794 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
795 if (interactive) {
796 if (lldb::LockableStreamFileSP output_sp =
797 io_handler.GetOutputStreamFileSP()) {
798 LockedStreamFile locked_stream = output_sp->Lock();
799 locked_stream.PutCString(
800 "Enter one or more sed substitution commands in "
801 "the form: 's/<regex>/<subst>/'.\nTerminate the "
802 "substitution list with an empty line.\n");
803 }
804 }
805 }
806
807 void IOHandlerInputComplete(IOHandler &io_handler,
808 std::string &data) override {
809 io_handler.SetIsDone(true);
810 if (m_regex_cmd_up) {
811 StringList lines;
812 if (lines.SplitIntoLines(data)) {
813 bool check_only = false;
814 for (const std::string &line : lines) {
815 Status error = AppendRegexSubstitution(line, check_only);
816 if (error.Fail()) {
817 if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode())
818 GetDebugger().GetAsyncOutputStream()->Printf("error: %s\n",
819 error.AsCString());
820 }
821 }
822 }
823 if (m_regex_cmd_up->HasRegexEntries()) {
824 CommandObjectSP cmd_sp(m_regex_cmd_up.release());
825 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
826 }
827 }
828 }
829
830 void DoExecute(Args &command, CommandReturnObject &result) override {
831 const size_t argc = command.GetArgumentCount();
832 if (argc == 0) {
833 result.AppendError("usage: 'command regex <command-name> "
834 "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
835 return;
836 }
837
839 auto name = command[0].ref();
840 m_regex_cmd_up = std::make_unique<CommandObjectRegexCommand>(
841 m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 0,
842 true);
843
844 if (argc == 1) {
845 Debugger &debugger = GetDebugger();
846 bool color_prompt = debugger.GetUseColor();
847 const bool multiple_lines = true; // Get multiple lines
848 IOHandlerSP io_handler_sp(new IOHandlerEditline(
849 debugger, IOHandler::Type::Other,
850 "lldb-regex", // Name of input reader for history
851 llvm::StringRef("> "), // Prompt
852 llvm::StringRef(), // Continuation prompt
853 multiple_lines, color_prompt,
854 0, // Don't show line numbers
855 *this));
856
857 if (io_handler_sp) {
858 debugger.RunIOHandlerAsync(io_handler_sp);
860 }
861 } else {
862 for (auto &entry : command.entries().drop_front()) {
863 bool check_only = false;
864 error = AppendRegexSubstitution(entry.ref(), check_only);
865 if (error.Fail())
866 break;
867 }
868
869 if (error.Success()) {
872 }
873 }
874 if (error.Fail()) {
875 result.AppendError(error.AsCString());
876 }
877 }
878
879 Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
880 bool check_only) {
882
883 if (!m_regex_cmd_up) {
884 return Status::FromErrorStringWithFormat(
885 "invalid regular expression command object for: '%.*s'",
886 (int)regex_sed.size(), regex_sed.data());
887 return error;
888 }
889
890 size_t regex_sed_size = regex_sed.size();
891
892 if (regex_sed_size <= 1) {
893 return Status::FromErrorStringWithFormat(
894 "regular expression substitution string is too short: '%.*s'",
895 (int)regex_sed.size(), regex_sed.data());
896 return error;
897 }
898
899 if (regex_sed[0] != 's') {
900 return Status::FromErrorStringWithFormat(
901 "regular expression substitution string "
902 "doesn't start with 's': '%.*s'",
903 (int)regex_sed.size(), regex_sed.data());
904 return error;
905 }
906 const size_t first_separator_char_pos = 1;
907 // use the char that follows 's' as the regex separator character so we can
908 // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
909 const char separator_char = regex_sed[first_separator_char_pos];
910 const size_t second_separator_char_pos =
911 regex_sed.find(separator_char, first_separator_char_pos + 1);
912
913 if (second_separator_char_pos == std::string::npos) {
914 return Status::FromErrorStringWithFormat(
915 "missing second '%c' separator char after '%.*s' in '%.*s'",
916 separator_char,
917 (int)(regex_sed.size() - first_separator_char_pos - 1),
918 regex_sed.data() + (first_separator_char_pos + 1),
919 (int)regex_sed.size(), regex_sed.data());
920 return error;
921 }
922
923 const size_t third_separator_char_pos =
924 regex_sed.find(separator_char, second_separator_char_pos + 1);
925
926 if (third_separator_char_pos == std::string::npos) {
927 return Status::FromErrorStringWithFormat(
928 "missing third '%c' separator char after '%.*s' in '%.*s'",
929 separator_char,
930 (int)(regex_sed.size() - second_separator_char_pos - 1),
931 regex_sed.data() + (second_separator_char_pos + 1),
932 (int)regex_sed.size(), regex_sed.data());
933 return error;
934 }
935
936 if (third_separator_char_pos != regex_sed_size - 1) {
937 // Make sure that everything that follows the last regex separator char
938 if (regex_sed.find_first_not_of("\t\n\v\f\r ",
939 third_separator_char_pos + 1) !=
940 std::string::npos) {
941 return Status::FromErrorStringWithFormat(
942 "extra data found after the '%.*s' regular expression substitution "
943 "string: '%.*s'",
944 (int)third_separator_char_pos + 1, regex_sed.data(),
945 (int)(regex_sed.size() - third_separator_char_pos - 1),
946 regex_sed.data() + (third_separator_char_pos + 1));
947 return error;
948 }
949 } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
950 return Status::FromErrorStringWithFormat(
951 "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
952 separator_char, separator_char, separator_char, (int)regex_sed.size(),
953 regex_sed.data());
954 return error;
955 } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
956 return Status::FromErrorStringWithFormat(
957 "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
958 separator_char, separator_char, separator_char, (int)regex_sed.size(),
959 regex_sed.data());
960 return error;
961 }
963 if (!check_only) {
964 std::string regex(std::string(regex_sed.substr(
965 first_separator_char_pos + 1,
966 second_separator_char_pos - first_separator_char_pos - 1)));
967 std::string subst(std::string(regex_sed.substr(
968 second_separator_char_pos + 1,
969 third_separator_char_pos - second_separator_char_pos - 1)));
970 m_regex_cmd_up->AddRegexCommand(regex, subst);
971 }
972 return error;
973 }
977 if (m_regex_cmd_up->HasRegexEntries()) {
979 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
981 }
982 }
983
984private:
985 std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
986
987 class CommandOptions : public Options {
988 public:
989 CommandOptions() = default;
990
991 ~CommandOptions() override = default;
992
993 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
994 ExecutionContext *execution_context) override {
996 const int short_option = m_getopt_table[option_idx].val;
997
998 switch (short_option) {
999 case 'h':
1000 m_help.assign(std::string(option_arg));
1001 break;
1002 case 's':
1003 m_syntax.assign(std::string(option_arg));
1004 break;
1005 default:
1006 llvm_unreachable("Unimplemented option");
1007 }
1009 return error;
1011
1012 void OptionParsingStarting(ExecutionContext *execution_context) override {
1013 m_help.clear();
1014 m_syntax.clear();
1017 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1018 return llvm::ArrayRef(g_regex_options);
1020
1021 llvm::StringRef GetHelp() { return m_help; }
1022
1023 llvm::StringRef GetSyntax() { return m_syntax; }
1024
1025 protected:
1026 // Instance variables to hold the values for command options.
1027
1028 std::string m_help;
1029 std::string m_syntax;
1030 };
1031
1032 Options *GetOptions() override { return &m_options; }
1033
1035};
1036
1038public:
1039 CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1040 std::string funct, std::string help,
1042 CompletionType completion_type)
1043 : CommandObjectRaw(interpreter, name), m_function_name(funct),
1044 m_synchro(synch), m_completion_type(completion_type) {
1045 if (!help.empty())
1046 SetHelp(help);
1047 else {
1048 StreamString stream;
1049 stream.Printf("For more information run 'help %s'", name.c_str());
1050 SetHelp(stream.GetString());
1051 }
1052 }
1053
1054 ~CommandObjectPythonFunction() override = default;
1055
1056 bool IsRemovable() const override { return true; }
1057
1058 const std::string &GetFunctionName() { return m_function_name; }
1059
1061
1062 llvm::StringRef GetHelpLong() override {
1065
1067 if (!scripter)
1069
1070 std::string docstring;
1072 scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1073 if (!docstring.empty())
1074 SetHelpLong(docstring);
1076 }
1077
1078 void
1084
1085 bool WantsCompletion() override { return true; }
1086
1087protected:
1088 void DoExecute(llvm::StringRef raw_command_line,
1089 CommandReturnObject &result) override {
1091
1092 m_interpreter.IncreaseCommandUsage(*this);
1093
1094 Status error;
1095
1097
1098 if (!scripter || !scripter->RunScriptBasedCommand(
1099 m_function_name.c_str(), raw_command_line, m_synchro,
1100 result, error, m_exe_ctx)) {
1101 result.AppendError(error.AsCString());
1102 } else {
1103 // Don't change the status if the command already set it...
1104 if (result.GetStatus() == eReturnStatusInvalid) {
1105 if (result.GetOutputString().empty())
1107 else
1109 }
1110 }
1111 }
1112
1113private:
1114 std::string m_function_name;
1118};
1119
1120/// This class implements a "raw" scripted command. lldb does no parsing of the
1121/// command line, instead passing the line unaltered (except for backtick
1122/// substitution).
1124public:
1126 std::string name,
1127 StructuredData::GenericSP cmd_obj_sp,
1129 CompletionType completion_type)
1130 : CommandObjectRaw(interpreter, name), m_cmd_obj_sp(cmd_obj_sp),
1131 m_synchro(synch), m_fetched_help_short(false),
1132 m_fetched_help_long(false), m_completion_type(completion_type) {
1133 StreamString stream;
1134 stream.Printf("For more information run 'help %s'", name.c_str());
1135 SetHelp(stream.GetString());
1136 if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter())
1137 GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
1138 }
1139
1141
1142 void
1148
1149 bool WantsCompletion() override { return true; }
1150
1151 bool IsRemovable() const override { return true; }
1152
1154
1155 std::optional<std::string> GetRepeatCommand(Args &args,
1156 uint32_t index) override {
1158 if (!scripter)
1159 return std::nullopt;
1160
1161 return scripter->GetRepeatCommandForScriptedCommand(m_cmd_obj_sp, args);
1162 }
1163
1164 llvm::StringRef GetHelp() override {
1168 if (!scripter)
1170 std::string docstring;
1172 scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
1173 if (!docstring.empty())
1174 SetHelp(docstring);
1175
1177 }
1178
1179 llvm::StringRef GetHelpLong() override {
1182
1184 if (!scripter)
1186
1187 std::string docstring;
1189 scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
1190 if (!docstring.empty())
1191 SetHelpLong(docstring);
1193 }
1194
1195protected:
1196 void DoExecute(llvm::StringRef raw_command_line,
1197 CommandReturnObject &result) override {
1199
1200 Status error;
1201
1203
1204 if (!scripter ||
1205 !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1206 m_synchro, result, error, m_exe_ctx)) {
1207 result.AppendError(error.AsCString());
1208 } else {
1209 // Don't change the status if the command already set it...
1210 if (result.GetStatus() == eReturnStatusInvalid) {
1211 if (result.GetOutputString().empty())
1213 else
1215 }
1216 }
1217 }
1218
1219private:
1225};
1226
1227
1228/// This command implements a lldb parsed scripted command. The command
1229/// provides a definition of the options and arguments, and a option value
1230/// setting callback, and then the command's execution function gets passed
1231/// just the parsed arguments.
1232/// Note, implementing a command in Python using these base interfaces is a bit
1233/// of a pain, but it is much easier to export this low level interface, and
1234/// then make it nicer on the Python side, than to try to do that in a
1235/// script language neutral way.
1236/// So I've also added a base class in Python that provides a table-driven
1237/// way of defining the options and arguments, which automatically fills the
1238/// option values, making them available as properties in Python.
1239///
1241private:
1242 class CommandOptions : public Options {
1243 public:
1245 StructuredData::GenericSP cmd_obj_sp) : m_interpreter(interpreter),
1246 m_cmd_obj_sp(cmd_obj_sp) {}
1247
1248 ~CommandOptions() override = default;
1249
1250 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1251 ExecutionContext *execution_context) override {
1252 Status error;
1253 ScriptInterpreter *scripter =
1254 m_interpreter.GetDebugger().GetScriptInterpreter();
1255 if (!scripter) {
1257 "No script interpreter for SetOptionValue.");
1258 return error;
1259 }
1260 if (!m_cmd_obj_sp) {
1262 "SetOptionValue called with empty cmd_obj.");
1263 return error;
1264 }
1267 "SetOptionValue called before options definitions "
1268 "were created.");
1269 return error;
1270 }
1271 // Pass the long option, since you aren't actually required to have a
1272 // short_option, and for those options the index or short option character
1273 // aren't meaningful on the python side.
1274 const char * long_option =
1275 m_options_definition_up.get()[option_idx].long_option;
1276 bool success = scripter->SetOptionValueForCommandObject(m_cmd_obj_sp,
1277 execution_context, long_option, option_arg);
1278 if (!success)
1280 "Error setting option: {0} to {1}", long_option, option_arg);
1281 return error;
1282 }
1283
1284 void OptionParsingStarting(ExecutionContext *execution_context) override {
1285 ScriptInterpreter *scripter =
1286 m_interpreter.GetDebugger().GetScriptInterpreter();
1287 if (!scripter || !m_cmd_obj_sp)
1288 return;
1289
1291 }
1292
1293 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1295 return {};
1296 return llvm::ArrayRef(m_options_definition_up.get(), m_num_options);
1297 }
1298
1300 size_t counter, uint32_t &usage_mask) {
1301 // If the usage entry is not provided, we use LLDB_OPT_SET_ALL.
1302 // If the usage mask is a UINT, the option belongs to that group.
1303 // If the usage mask is a vector of UINT's, the option belongs to all the
1304 // groups listed.
1305 // If a subelement of the vector is a vector of two ints, then the option
1306 // belongs to the inclusive range from the first to the second element.
1307 Status error;
1308 if (!obj_sp) {
1309 usage_mask = LLDB_OPT_SET_ALL;
1310 return error;
1311 }
1312
1313 usage_mask = 0;
1314
1316 obj_sp->GetAsUnsignedInteger();
1317 if (uint_val) {
1318 // If this is an integer, then this specifies a single group:
1319 uint32_t value = uint_val->GetValue();
1320 if (value == 0) {
1322 "0 is not a valid group for option {0}", counter);
1323 }
1324 usage_mask = (1 << (value - 1));
1325 return error;
1326 }
1327 // Otherwise it has to be an array:
1328 StructuredData::Array *array_val = obj_sp->GetAsArray();
1329 if (!array_val) {
1331 "required field is not a array for option {0}", counter);
1332 }
1333 // This is the array ForEach for accumulating a group usage mask from
1334 // an array of string descriptions of groups.
1335 auto groups_accumulator
1336 = [counter, &usage_mask, &error]
1337 (StructuredData::Object *obj) -> bool {
1338 StructuredData::UnsignedInteger *int_val = obj->GetAsUnsignedInteger();
1339 if (int_val) {
1340 uint32_t value = int_val->GetValue();
1341 if (value == 0) {
1343 "0 is not a valid group for element {0}", counter);
1344 return false;
1345 }
1346 usage_mask |= (1 << (value - 1));
1347 return true;
1348 }
1349 StructuredData::Array *arr_val = obj->GetAsArray();
1350 if (!arr_val) {
1352 "Group element not an int or array of integers for element {0}",
1353 counter);
1354 return false;
1355 }
1356 size_t num_range_elem = arr_val->GetSize();
1357 if (num_range_elem != 2) {
1359 "Subranges of a group not a start and a stop for element {0}",
1360 counter);
1361 return false;
1362 }
1363 int_val = arr_val->GetItemAtIndex(0)->GetAsUnsignedInteger();
1364 if (!int_val) {
1366 "Start element of a subrange of a "
1367 "group not unsigned int for element {0}",
1368 counter);
1369 return false;
1370 }
1371 uint32_t start = int_val->GetValue();
1372 int_val = arr_val->GetItemAtIndex(1)->GetAsUnsignedInteger();
1373 if (!int_val) {
1375 "End element of a subrange of a group"
1376 " not unsigned int for element {0}",
1377 counter);
1378 return false;
1379 }
1380 uint32_t end = int_val->GetValue();
1381 if (start == 0 || end == 0 || start > end) {
1383 "Invalid subrange of a group: {0} - "
1384 "{1} for element {2}",
1385 start, end, counter);
1386 return false;
1387 }
1388 for (uint32_t i = start; i <= end; i++) {
1389 usage_mask |= (1 << (i - 1));
1390 }
1391 return true;
1392 };
1393 array_val->ForEach(groups_accumulator);
1394 return error;
1395 }
1396
1397
1399 Status error;
1400 m_num_options = options.GetSize();
1402 // We need to hand out pointers to contents of these vectors; we reserve
1403 // as much as we'll need up front so they don't get freed on resize...
1407
1408 size_t counter = 0;
1409 size_t short_opt_counter = 0;
1410 // This is the Array::ForEach function for adding option elements:
1411 auto add_element = [this, &error, &counter, &short_opt_counter]
1412 (llvm::StringRef long_option, StructuredData::Object *object) -> bool {
1413 StructuredData::Dictionary *opt_dict = object->GetAsDictionary();
1414 if (!opt_dict) {
1416 "Value in options dictionary is not a dictionary");
1417 return false;
1418 }
1419 OptionDefinition &option_def = m_options_definition_up.get()[counter];
1420
1421 // We aren't exposing the validator yet, set it to null
1422 option_def.validator = nullptr;
1423 // We don't require usage masks, so set it to one group by default:
1424 option_def.usage_mask = 1;
1425
1426 // Now set the fields of the OptionDefinition Array from the dictionary:
1427 //
1428 // Note that I don't check for unknown fields in the option dictionaries
1429 // so a scriptor can add extra elements that are helpful when they go to
1430 // do "set_option_value"
1431
1432 // Usage Mask:
1433 StructuredData::ObjectSP obj_sp = opt_dict->GetValueForKey("groups");
1434 if (obj_sp) {
1435 error = ParseUsageMaskFromArray(obj_sp, counter,
1436 option_def.usage_mask);
1437 if (error.Fail())
1438 return false;
1439 }
1440
1441 // Required:
1442 option_def.required = false;
1443 obj_sp = opt_dict->GetValueForKey("required");
1444 if (obj_sp) {
1445 StructuredData::Boolean *boolean_val = obj_sp->GetAsBoolean();
1446 if (!boolean_val) {
1448 "'required' field is not a boolean "
1449 "for option {0}",
1450 counter);
1451 return false;
1452 }
1453 option_def.required = boolean_val->GetValue();
1454 }
1455
1456 // Short Option:
1457 int short_option;
1458 obj_sp = opt_dict->GetValueForKey("short_option");
1459 if (obj_sp) {
1460 // The value is a string, so pull the
1461 llvm::StringRef short_str = obj_sp->GetStringValue();
1462 if (short_str.empty()) {
1464 "short_option field empty for "
1465 "option {0}",
1466 counter);
1467 return false;
1468 } else if (short_str.size() != 1) {
1470 "short_option field has extra "
1471 "characters for option {0}",
1472 counter);
1473 return false;
1474 }
1475 short_option = (int) short_str[0];
1476 } else {
1477 // If the short option is not provided, then we need a unique value
1478 // less than the lowest printable ASCII character.
1479 short_option = short_opt_counter++;
1480 }
1481 option_def.short_option = short_option;
1482
1483 // Long Option is the key from the outer dict:
1484 if (long_option.empty()) {
1486 "empty long_option for option {0}", counter);
1487 return false;
1488 }
1489 auto inserted = g_string_storer.insert(long_option.str());
1490 option_def.long_option = ((*(inserted.first)).data());
1491
1492 // Value Type:
1493 obj_sp = opt_dict->GetValueForKey("value_type");
1494 if (obj_sp) {
1496 = obj_sp->GetAsUnsignedInteger();
1497 if (!uint_val) {
1499 "Value type must be an unsigned "
1500 "integer");
1501 return false;
1502 }
1503 uint64_t val_type = uint_val->GetValue();
1504 if (val_type >= eArgTypeLastArg) {
1505 error =
1506 Status::FromErrorStringWithFormatv("Value type {0} beyond the "
1507 "CommandArgumentType bounds",
1508 val_type);
1509 return false;
1510 }
1511 option_def.argument_type = (CommandArgumentType) val_type;
1512 option_def.option_has_arg = true;
1513 } else {
1514 option_def.argument_type = eArgTypeNone;
1515 option_def.option_has_arg = false;
1516 }
1517
1518 // Completion Type:
1519 obj_sp = opt_dict->GetValueForKey("completion_type");
1520 if (obj_sp) {
1521 StructuredData::UnsignedInteger *uint_val = obj_sp->GetAsUnsignedInteger();
1522 if (!uint_val) {
1524 "Completion type must be an "
1525 "unsigned integer for option {0}",
1526 counter);
1527 return false;
1528 }
1529 uint64_t completion_type = uint_val->GetValue();
1530 if (completion_type > eCustomCompletion) {
1532 "Completion type for option {0} "
1533 "beyond the CompletionType bounds",
1534 completion_type);
1535 return false;
1536 }
1537 option_def.completion_type = (CommandArgumentType) completion_type;
1538 } else
1539 option_def.completion_type = eNoCompletion;
1540
1541 // Usage Text:
1542 obj_sp = opt_dict->GetValueForKey("help");
1543 if (!obj_sp) {
1545 "required usage missing from option "
1546 "{0}",
1547 counter);
1548 return false;
1549 }
1550 llvm::StringRef usage_stref;
1551 usage_stref = obj_sp->GetStringValue();
1552 if (usage_stref.empty()) {
1554 "empty usage text for option {0}", counter);
1555 return false;
1556 }
1557 m_usage_container[counter] = usage_stref.str().c_str();
1558 option_def.usage_text = m_usage_container[counter].data();
1559
1560 // Enum Values:
1561
1562 obj_sp = opt_dict->GetValueForKey("enum_values");
1563 if (obj_sp) {
1564 StructuredData::Array *array = obj_sp->GetAsArray();
1565 if (!array) {
1567 "enum values must be an array for "
1568 "option {0}",
1569 counter);
1570 return false;
1571 }
1572 size_t num_elem = array->GetSize();
1573 size_t enum_ctr = 0;
1574 m_enum_storage[counter] = std::vector<EnumValueStorage>(num_elem);
1575 std::vector<EnumValueStorage> &curr_elem = m_enum_storage[counter];
1576
1577 // This is the Array::ForEach function for adding enum elements:
1578 // Since there are only two fields to specify the enum, use a simple
1579 // two element array with value first, usage second.
1580 // counter is only used for reporting so I pass it by value here.
1581 auto add_enum = [&enum_ctr, &curr_elem, counter, &error]
1582 (StructuredData::Object *object) -> bool {
1583 StructuredData::Array *enum_arr = object->GetAsArray();
1584 if (!enum_arr) {
1586 "Enum values for option {0} not "
1587 "an array",
1588 counter);
1589 return false;
1590 }
1591 size_t num_enum_elements = enum_arr->GetSize();
1592 if (num_enum_elements != 2) {
1594 "Wrong number of elements: {0} "
1595 "for enum {1} in option {2}",
1596 num_enum_elements, enum_ctr, counter);
1597 return false;
1598 }
1599 // Enum Value:
1600 StructuredData::ObjectSP obj_sp = enum_arr->GetItemAtIndex(0);
1601 llvm::StringRef val_stref = obj_sp->GetStringValue();
1602 std::string value_cstr_str = val_stref.str().c_str();
1603
1604 // Enum Usage:
1605 obj_sp = enum_arr->GetItemAtIndex(1);
1606 if (!obj_sp) {
1608 "No usage for enum {0} in option "
1609 "{1}",
1610 enum_ctr, counter);
1611 return false;
1612 }
1613 llvm::StringRef usage_stref = obj_sp->GetStringValue();
1614 std::string usage_cstr_str = usage_stref.str().c_str();
1615 curr_elem[enum_ctr] = EnumValueStorage(value_cstr_str,
1616 usage_cstr_str, enum_ctr);
1617
1618 enum_ctr++;
1619 return true;
1620 }; // end of add_enum
1621
1622 array->ForEach(add_enum);
1623 if (!error.Success())
1624 return false;
1625 // We have to have a vector of elements to set in the options, make
1626 // that here:
1627 for (auto &elem : curr_elem)
1628 m_enum_vector[counter].emplace_back(elem.element);
1629
1630 option_def.enum_values = llvm::ArrayRef(m_enum_vector[counter]);
1631 }
1632 counter++;
1633 return true;
1634 }; // end of add_element
1635
1636 options.ForEach(add_element);
1637 return error;
1638 }
1639
1640 size_t GetNumOptions() { return m_num_options; }
1641
1643 OptionElementVector &option_vec,
1644 ExecutionContext *exe_ctx) {
1645 // I'm not sure if we'll get into trouble doing an option parsing start
1646 // and end in this context. If so, then I'll have to directly tell the
1647 // scripter to do this.
1648 OptionParsingStarting(exe_ctx);
1649 auto opt_defs = GetDefinitions();
1650
1651 // Iterate through the options we found so far, and push them into
1652 // the scripted side.
1653 for (auto option_elem : option_vec) {
1654 int cur_defs_index = option_elem.opt_defs_index;
1655 // If we don't recognize this option we can't set it.
1656 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
1657 cur_defs_index == OptionArgElement::eBareDash ||
1658 cur_defs_index == OptionArgElement::eBareDoubleDash)
1659 continue;
1660 bool option_has_arg = opt_defs[cur_defs_index].option_has_arg;
1661 llvm::StringRef cur_arg_value;
1662 if (option_has_arg) {
1663 int cur_arg_pos = option_elem.opt_arg_pos;
1664 if (cur_arg_pos != OptionArgElement::eUnrecognizedArg &&
1665 cur_arg_pos != OptionArgElement::eBareDash &&
1666 cur_arg_pos != OptionArgElement::eBareDoubleDash) {
1667 cur_arg_value =
1668 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
1669 }
1670 }
1671 SetOptionValue(cur_defs_index, cur_arg_value, exe_ctx);
1672 }
1673 OptionParsingFinished(exe_ctx);
1674 }
1675
1676 void
1678 StructuredData::DictionarySP &completion_dict_sp) {
1679 // We don't know how to process an empty completion dict, our callers have
1680 // to do that.
1681 assert(completion_dict_sp && "Must have valid completion dict");
1682 // First handle the case of a single completion:
1683 llvm::StringRef completion;
1684 // If the dictionary has one element "no-completion" then we return here
1685 if (completion_dict_sp->GetValueForKeyAsString("no-completion",
1686 completion))
1687 return;
1688
1689 if (completion_dict_sp->GetValueForKeyAsString("completion",
1690 completion)) {
1691 llvm::StringRef mode_str;
1693 if (completion_dict_sp->GetValueForKeyAsString("mode", mode_str)) {
1694 if (mode_str == "complete")
1696 else if (mode_str == "partial")
1698 else {
1699 // FIXME - how do I report errors here?
1700 return;
1701 }
1702 }
1703 request.AddCompletion(completion, "", mode);
1704 return;
1705 }
1706 // The completions are required, the descriptions are not:
1707 StructuredData::Array *completions;
1708 StructuredData::Array *descriptions;
1709 if (completion_dict_sp->GetValueForKeyAsArray("values", completions)) {
1710 completion_dict_sp->GetValueForKeyAsArray("descriptions", descriptions);
1711 size_t num_completions = completions->GetSize();
1712 for (size_t idx = 0; idx < num_completions; idx++) {
1713 auto val = completions->GetItemAtIndexAsString(idx);
1714 if (!val)
1715 // FIXME: How do I report this error?
1716 return;
1717
1718 if (descriptions) {
1719 auto desc = descriptions->GetItemAtIndexAsString(idx);
1720 request.AddCompletion(*val, desc ? *desc : "");
1721 } else
1722 request.AddCompletion(*val);
1723 }
1724 }
1725 }
1726
1727 void
1729 OptionElementVector &option_vec,
1730 int opt_element_index,
1731 CommandInterpreter &interpreter) override {
1732 ScriptInterpreter *scripter =
1733 interpreter.GetDebugger().GetScriptInterpreter();
1734
1735 if (!scripter)
1736 return;
1737
1738 ExecutionContext exe_ctx = interpreter.GetExecutionContext();
1739 PrepareOptionsForCompletion(request, option_vec, &exe_ctx);
1740
1741 auto defs = GetDefinitions();
1742
1743 size_t defs_index = option_vec[opt_element_index].opt_defs_index;
1744 llvm::StringRef option_name = defs[defs_index].long_option;
1745 bool is_enum = defs[defs_index].enum_values.size() != 0;
1746 if (option_name.empty())
1747 return;
1748 // If this is an enum, we don't call the custom completer, just let the
1749 // regular option completer handle that:
1750 StructuredData::DictionarySP completion_dict_sp;
1751 if (!is_enum)
1752 completion_dict_sp =
1754 m_cmd_obj_sp, option_name, request.GetCursorCharPos());
1755
1756 if (!completion_dict_sp) {
1757 Options::HandleOptionArgumentCompletion(request, option_vec,
1758 opt_element_index, interpreter);
1759 return;
1760 }
1761
1762 ProcessCompletionDict(request, completion_dict_sp);
1763 }
1764
1765 private:
1768 element.string_value = "value not set";
1769 element.usage = "usage not set";
1770 element.value = 0;
1771 }
1772
1773 EnumValueStorage(std::string in_str_val, std::string in_usage,
1774 size_t in_value) : value(std::move(in_str_val)), usage(std::move(in_usage)) {
1775 SetElement(in_value);
1776 }
1777
1779 usage(in.usage) {
1781 }
1782
1784 value = in.value;
1785 usage = in.usage;
1787 return *this;
1788 }
1789
1790 void SetElement(size_t in_value) {
1791 element.value = in_value;
1792 element.string_value = value.data();
1793 element.usage = usage.data();
1794 }
1795
1796 std::string value;
1797 std::string usage;
1799 };
1800 // We have to provide char * values for the long option, usage and enum
1801 // values, that's what the option definitions hold.
1802 // The long option strings are quite likely to be reused in other added
1803 // commands, so those are stored in a global set: g_string_storer.
1804 // But the usages are much less likely to be reused, so those are stored in
1805 // a vector in the command instance. It gets resized to the correct size
1806 // and then filled with null-terminated strings in the std::string, so the
1807 // are valid C-strings that won't move around.
1808 // The enum values and descriptions are treated similarly - these aren't
1809 // all that common so it's not worth the effort to dedup them.
1810 size_t m_num_options = 0;
1811 std::unique_ptr<OptionDefinition> m_options_definition_up;
1812 std::vector<std::vector<EnumValueStorage>> m_enum_storage;
1813 std::vector<std::vector<OptionEnumValueElement>> m_enum_vector;
1814 std::vector<std::string> m_usage_container;
1817 static std::unordered_set<std::string> g_string_storer;
1818 };
1819
1820public:
1822 std::string name,
1823 StructuredData::GenericSP cmd_obj_sp,
1825 CommandReturnObject &result) {
1827 interpreter, name, cmd_obj_sp, synch));
1828
1830 = static_cast<CommandObjectScriptingObjectParsed *>(new_cmd_sp.get());
1831 // Now check all the failure modes, and report if found.
1832 Status opt_error = parsed_cmd->GetOptionsError();
1833 Status arg_error = parsed_cmd->GetArgsError();
1834
1835 if (opt_error.Fail())
1836 result.AppendErrorWithFormat("failed to parse option definitions: %s",
1837 opt_error.AsCString());
1838 if (arg_error.Fail())
1839 result.AppendErrorWithFormat("%sfailed to parse argument definitions: %s",
1840 opt_error.Fail() ? ", also " : "",
1841 arg_error.AsCString());
1842
1843 if (!result.Succeeded())
1844 return {};
1845
1846 return new_cmd_sp;
1847 }
1848
1850 std::string name,
1851 StructuredData::GenericSP cmd_obj_sp,
1853 : CommandObjectParsed(interpreter, name.c_str()),
1854 m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch),
1855 m_options(interpreter, cmd_obj_sp), m_fetched_help_short(false),
1856 m_fetched_help_long(false) {
1857 StreamString stream;
1859 if (!scripter) {
1860 m_options_error = Status::FromErrorString("No script interpreter");
1861 return;
1862 }
1863
1864 // Set the flags:
1865 GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
1866
1867 // Now set up the options definitions from the options:
1868 StructuredData::ObjectSP options_object_sp
1869 = scripter->GetOptionsForCommandObject(cmd_obj_sp);
1870 // It's okay not to have an options dict.
1871 if (options_object_sp) {
1872 // The options come as a dictionary of dictionaries. The key of the
1873 // outer dict is the long option name (since that's required). The
1874 // value holds all the other option specification bits.
1875 StructuredData::Dictionary *options_dict
1876 = options_object_sp->GetAsDictionary();
1877 // but if it exists, it has to be an array.
1878 if (options_dict) {
1879 m_options_error = m_options.SetOptionsFromArray(*(options_dict));
1880 // If we got an error don't bother with the arguments...
1881 if (m_options_error.Fail())
1882 return;
1883 } else {
1884 m_options_error = Status::FromErrorString("Options array not an array");
1885 return;
1886 }
1887 }
1888 // Then fetch the args. Since the arguments can have usage masks you need
1889 // an array of arrays.
1890 StructuredData::ObjectSP args_object_sp
1891 = scripter->GetArgumentsForCommandObject(cmd_obj_sp);
1892 if (args_object_sp) {
1893 StructuredData::Array *args_array = args_object_sp->GetAsArray();
1894 if (!args_array) {
1895 m_args_error =
1896 Status::FromErrorString("Argument specification is not an array");
1897 return;
1898 }
1899 size_t counter = 0;
1900
1901 // This is the Array::ForEach function that handles the
1902 // CommandArgumentEntry arrays one by one:
1903 auto arg_array_adder = [this, &counter] (StructuredData::Object *object)
1904 -> bool {
1905 // This is the Array::ForEach function to add argument entries:
1906 CommandArgumentEntry this_entry;
1907 size_t elem_counter = 0;
1908 auto args_adder = [this, counter, &elem_counter, &this_entry]
1909 (StructuredData::Object *object) -> bool {
1910 // The arguments definition has three fields, the argument type, the
1911 // repeat and the usage mask.
1914 uint32_t arg_opt_set_association;
1915
1916 auto report_error = [this, elem_counter,
1917 counter](const char *err_txt) -> bool {
1919 "element {} of arguments list element {}: {}", elem_counter,
1920 counter, err_txt);
1921 return false;
1922 };
1923
1924 StructuredData::Dictionary *arg_dict = object->GetAsDictionary();
1925 if (!arg_dict) {
1926 report_error("is not a dictionary.");
1927 return false;
1928 }
1929 // Argument Type:
1931 = arg_dict->GetValueForKey("arg_type");
1932 if (obj_sp) {
1934 = obj_sp->GetAsUnsignedInteger();
1935 if (!uint_val) {
1936 report_error("value type must be an unsigned integer");
1937 return false;
1938 }
1939 uint64_t arg_type_int = uint_val->GetValue();
1940 if (arg_type_int >= eArgTypeLastArg) {
1941 report_error("value type beyond ArgumentRepetitionType bounds");
1942 return false;
1943 }
1944 arg_type = (CommandArgumentType) arg_type_int;
1945 }
1946 // Repeat Value:
1947 obj_sp = arg_dict->GetValueForKey("repeat");
1948 std::optional<ArgumentRepetitionType> repeat;
1949 if (obj_sp) {
1950 llvm::StringRef repeat_str = obj_sp->GetStringValue();
1951 if (repeat_str.empty()) {
1952 report_error("repeat value is empty");
1953 return false;
1954 }
1955 repeat = ArgRepetitionFromString(repeat_str);
1956 if (!repeat) {
1957 report_error("invalid repeat value");
1958 return false;
1959 }
1960 arg_repetition = *repeat;
1961 }
1962
1963 // Usage Mask:
1964 obj_sp = arg_dict->GetValueForKey("groups");
1966 counter, arg_opt_set_association);
1967 this_entry.emplace_back(arg_type, arg_repetition,
1968 arg_opt_set_association);
1969 elem_counter++;
1970 return true;
1971 };
1972 StructuredData::Array *args_array = object->GetAsArray();
1973 if (!args_array) {
1974 m_args_error =
1975 Status::FromErrorStringWithFormatv("Argument definition element "
1976 "{0} is not an array",
1977 counter);
1978 }
1979
1980 args_array->ForEach(args_adder);
1981 if (m_args_error.Fail())
1982 return false;
1983 if (this_entry.empty()) {
1984 m_args_error =
1985 Status::FromErrorStringWithFormatv("Argument definition element "
1986 "{0} is empty",
1987 counter);
1988 return false;
1989 }
1990 m_arguments.push_back(this_entry);
1991 counter++;
1992 return true;
1993 }; // end of arg_array_adder
1994 // Here we actually parse the args definition:
1995 args_array->ForEach(arg_array_adder);
1996 }
1997 }
1998
2000
2002 Status GetArgsError() { return m_args_error.Clone(); }
2003 bool WantsCompletion() override { return true; }
2004
2005private:
2007 OptionElementVector &option_vec) {
2008 // First, we have to tell the Scripted side to set the values in its
2009 // option store, then we call into the handle_completion passing in
2010 // an array of the args, the arg index and the cursor position in the arg.
2011 // We want the script side to have a chance to clear its state, so tell
2012 // it argument parsing has started:
2013 Options *options = GetOptions();
2014 // If there are not options, this will be nullptr, and in that case we
2015 // can just skip setting the options on the scripted side:
2016 if (options)
2017 m_options.PrepareOptionsForCompletion(request, option_vec, &m_exe_ctx);
2018 }
2019
2020public:
2022 OptionElementVector &option_vec) override {
2024
2025 if (!scripter)
2026 return;
2027
2028 // Set up the options values on the scripted side:
2029 PrepareOptionsForCompletion(request, option_vec);
2030
2031 // Now we have to make up the argument list.
2032 // The ParseForCompletion only identifies tokens in the m_parsed_line
2033 // it doesn't remove the options leaving only the args as it does for
2034 // the regular Parse, so we have to filter out the option ones using the
2035 // option_element_vector:
2036
2037 Options *options = GetOptions();
2038 auto defs = options ? options->GetDefinitions()
2039 : llvm::ArrayRef<OptionDefinition>();
2040
2041 std::unordered_set<size_t> option_slots;
2042 for (const auto &elem : option_vec) {
2043 if (elem.opt_defs_index == -1)
2044 continue;
2045 option_slots.insert(elem.opt_pos);
2046 if (defs[elem.opt_defs_index].option_has_arg)
2047 option_slots.insert(elem.opt_arg_pos);
2048 }
2049
2050 std::vector<llvm::StringRef> args_vec;
2051 Args &args = request.GetParsedLine();
2052 size_t num_args = args.GetArgumentCount();
2053 size_t cursor_idx = request.GetCursorIndex();
2054 size_t args_elem_pos = cursor_idx;
2055
2056 for (size_t idx = 0; idx < num_args; idx++) {
2057 if (option_slots.count(idx) == 0)
2058 args_vec.push_back(args[idx].ref());
2059 else if (idx < cursor_idx)
2060 args_elem_pos--;
2061 }
2062 StructuredData::DictionarySP completion_dict_sp =
2064 m_cmd_obj_sp, args_vec, args_elem_pos, request.GetCursorCharPos());
2065
2066 if (!completion_dict_sp) {
2067 CommandObject::HandleArgumentCompletion(request, option_vec);
2068 return;
2069 }
2070
2071 m_options.ProcessCompletionDict(request, completion_dict_sp);
2072 }
2073
2074 bool IsRemovable() const override { return true; }
2075
2077
2078 std::optional<std::string> GetRepeatCommand(Args &args,
2079 uint32_t index) override {
2081 if (!scripter)
2082 return std::nullopt;
2083
2084 return scripter->GetRepeatCommandForScriptedCommand(m_cmd_obj_sp, args);
2085 }
2086
2087 llvm::StringRef GetHelp() override {
2091 if (!scripter)
2093 std::string docstring;
2095 scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
2096 if (!docstring.empty())
2097 SetHelp(docstring);
2098
2100 }
2101
2102 llvm::StringRef GetHelpLong() override {
2105
2107 if (!scripter)
2109
2110 std::string docstring;
2112 scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
2113 if (!docstring.empty())
2114 SetHelpLong(docstring);
2116 }
2117
2118 Options *GetOptions() override {
2119 // CommandObjectParsed requires that a command with no options return
2120 // nullptr.
2121 if (m_options.GetNumOptions() == 0)
2122 return nullptr;
2123 return &m_options;
2124 }
2125
2126protected:
2127 void DoExecute(Args &args,
2128 CommandReturnObject &result) override {
2130
2131 Status error;
2132
2134
2135 if (!scripter ||
2137 m_synchro, result, error, m_exe_ctx)) {
2138 result.AppendError(error.AsCString());
2139 } else {
2140 // Don't change the status if the command already set it...
2141 if (result.GetStatus() == eReturnStatusInvalid) {
2142 if (result.GetOutputString().empty())
2144 else
2146 }
2147 }
2148 }
2149
2150private:
2158};
2159
2160std::unordered_set<std::string>
2162
2163// CommandObjectCommandsScriptImport
2164#define LLDB_OPTIONS_script_import
2165#include "CommandOptions.inc"
2166
2168public:
2170 : CommandObjectParsed(interpreter, "command script import",
2171 "Import a scripting module in LLDB.", nullptr) {
2173 }
2174
2176
2177 Options *GetOptions() override { return &m_options; }
2178
2179protected:
2180 class CommandOptions : public Options {
2181 public:
2182 CommandOptions() = default;
2183
2184 ~CommandOptions() override = default;
2185
2186 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2187 ExecutionContext *execution_context) override {
2188 Status error;
2189 const int short_option = m_getopt_table[option_idx].val;
2190
2191 switch (short_option) {
2192 case 'r':
2193 // NO-OP
2194 break;
2195 case 'c':
2197 break;
2198 case 's':
2199 silent = true;
2200 break;
2201 default:
2202 llvm_unreachable("Unimplemented option");
2203 }
2204
2205 return error;
2206 }
2207
2208 void OptionParsingStarting(ExecutionContext *execution_context) override {
2210 }
2211
2212 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2213 return llvm::ArrayRef(g_script_import_options);
2214 }
2216 bool silent = false;
2217 };
2218
2219 void DoExecute(Args &command, CommandReturnObject &result) override {
2220 if (command.empty()) {
2221 result.AppendError("command script import needs one or more arguments");
2222 return;
2223 }
2224
2225 FileSpec source_dir = {};
2226 if (m_options.relative_to_command_file) {
2228 if (!source_dir) {
2229 result.AppendError("command script import -c can only be specified "
2230 "from a command file");
2231 return;
2232 }
2233 }
2234
2235 for (auto &entry : command.entries()) {
2236 Status error;
2237
2238 LoadScriptOptions options;
2239 options.SetInitSession(true);
2240 options.SetSilent(m_options.silent);
2241
2242 // FIXME: this is necessary because CommandObject::CheckRequirements()
2243 // assumes that commands won't ever be recursively invoked, but it's
2244 // actually possible to craft a Python script that does other "command
2245 // script imports" in __lldb_init_module the real fix is to have
2246 // recursive commands possible with a CommandInvocation object separate
2247 // from the CommandObject itself, so that recursive command invocations
2248 // won't stomp on each other (wrt to execution contents, options, and
2249 // more)
2250 m_exe_ctx.Clear();
2251 if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
2252 entry.c_str(), options, error, /*module_sp=*/nullptr,
2253 source_dir)) {
2255 } else {
2256 result.AppendErrorWithFormat("module importing failed: %s",
2257 error.AsCString());
2258 }
2259 }
2260 }
2261
2263};
2264
2265#define LLDB_OPTIONS_script_add
2266#include "CommandOptions.inc"
2267
2270public:
2272 : CommandObjectParsed(interpreter, "command script add",
2273 "Add a scripted function as an LLDB command.",
2274 "Add a scripted function as an lldb command. "
2275 "If you provide a single argument, the command "
2276 "will be added at the root level of the command "
2277 "hierarchy. If there are more arguments they "
2278 "must be a path to a user-added container "
2279 "command, and the last element will be the new "
2280 "command name."),
2283 }
2284
2286
2287 Options *GetOptions() override { return &m_options; }
2288
2289 void
2291 OptionElementVector &opt_element_vector) override {
2293 opt_element_vector);
2294 }
2295
2296protected:
2297 class CommandOptions : public Options {
2298 public:
2299 CommandOptions() = default;
2300
2301 ~CommandOptions() override = default;
2302
2303 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2304 ExecutionContext *execution_context) override {
2305 Status error;
2306 const int short_option = m_getopt_table[option_idx].val;
2307
2308 switch (short_option) {
2309 case 'f':
2310 if (!option_arg.empty())
2311 m_funct_name = std::string(option_arg);
2312 break;
2313 case 'c':
2314 if (!option_arg.empty())
2315 m_class_name = std::string(option_arg);
2316 break;
2317 case 'h':
2318 if (!option_arg.empty())
2319 m_short_help = std::string(option_arg);
2320 break;
2321 case 'o':
2323 break;
2324 case 'p':
2325 m_parsed_command = true;
2326 break;
2327 case 's':
2330 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
2331 if (!error.Success())
2333 "unrecognized value for synchronicity '%s'",
2334 option_arg.str().c_str());
2335 break;
2336 case 'C': {
2337 Status error;
2338 OptionDefinition definition = GetDefinitions()[option_idx];
2339 lldb::CompletionType completion_type =
2341 option_arg, definition.enum_values, eNoCompletion, error));
2342 if (!error.Success())
2344 "unrecognized value for command completion type '%s'",
2345 option_arg.str().c_str());
2346 m_completion_type = completion_type;
2347 } break;
2348 default:
2349 llvm_unreachable("Unimplemented option");
2350 }
2351
2352 return error;
2353 }
2354
2364
2365 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2366 return llvm::ArrayRef(g_script_add_options);
2367 }
2368
2369 // Instance variables to hold the values for command options.
2370
2371 std::string m_class_name;
2372 std::string m_funct_name;
2373 std::string m_short_help;
2378 bool m_parsed_command = false;
2379 };
2380
2381 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
2382 if (interactive) {
2383 if (lldb::LockableStreamFileSP output_sp =
2384 io_handler.GetOutputStreamFileSP()) {
2385 LockedStreamFile locked_stream = output_sp->Lock();
2387 }
2388 }
2389 }
2390
2392 std::string &data) override {
2393 LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
2394
2396 if (interpreter) {
2397 StringList lines;
2398 lines.SplitIntoLines(data);
2399 if (lines.GetSize() > 0) {
2400 std::string funct_name_str;
2401 if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
2402 if (funct_name_str.empty()) {
2403 LockedStreamFile locked_stream = error_sp->Lock();
2404 locked_stream.Printf(
2405 "error: unable to obtain a function name, didn't "
2406 "add python command.\n");
2407 } else {
2408 // everything should be fine now, let's add this alias
2409
2411 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
2413 if (!m_container) {
2414 Status error = m_interpreter.AddUserCommand(
2415 m_cmd_name, command_obj_sp, m_overwrite);
2416 if (error.Fail()) {
2417 LockedStreamFile locked_stream = error_sp->Lock();
2418 locked_stream.Printf(
2419 "error: unable to add selected command: '%s'",
2420 error.AsCString());
2421 }
2422 } else {
2423 llvm::Error llvm_error = m_container->LoadUserSubcommand(
2424 m_cmd_name, command_obj_sp, m_overwrite);
2425 if (llvm_error) {
2426 LockedStreamFile locked_stream = error_sp->Lock();
2427 locked_stream.Printf(
2428 "error: unable to add selected command: '%s'",
2429 llvm::toString(std::move(llvm_error)).c_str());
2430 }
2431 }
2432 }
2433 } else {
2434 LockedStreamFile locked_stream = error_sp->Lock();
2435 locked_stream.Printf(
2436 "error: unable to create function, didn't add python command\n");
2437 }
2438 } else {
2439 LockedStreamFile locked_stream = error_sp->Lock();
2440 locked_stream.Printf(
2441 "error: empty function, didn't add python command\n");
2442 }
2443 } else {
2444 LockedStreamFile locked_stream = error_sp->Lock();
2445 locked_stream.Printf(
2446 "error: script interpreter missing, didn't add python command\n");
2447 }
2448
2449 io_handler.SetIsDone(true);
2450 }
2451
2452 void DoExecute(Args &command, CommandReturnObject &result) override {
2453 if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
2454 result.AppendError("only scripting language supported for scripted "
2455 "commands is currently Python");
2456 return;
2457 }
2458
2459 if (command.GetArgumentCount() == 0) {
2460 result.AppendError("'command script add' requires at least one argument");
2461 return;
2462 }
2463 // Store the options in case we get multi-line input, also figure out the
2464 // default if not user supplied:
2465 switch (m_options.m_overwrite_lazy) {
2466 case eLazyBoolCalculate:
2468 break;
2469 case eLazyBoolYes:
2470 m_overwrite = true;
2471 break;
2472 case eLazyBoolNo:
2473 m_overwrite = false;
2474 }
2475
2476 Status path_error;
2478 command, true, path_error);
2479
2480 if (path_error.Fail()) {
2481 result.AppendErrorWithFormat("error in command path: %s",
2482 path_error.AsCString());
2483 return;
2484 }
2485
2486 if (!m_container) {
2487 // This is getting inserted into the root of the interpreter.
2488 m_cmd_name = std::string(command[0].ref());
2489 } else {
2490 size_t num_args = command.GetArgumentCount();
2491 m_cmd_name = std::string(command[num_args - 1].ref());
2492 }
2493
2494 m_short_help.assign(m_options.m_short_help);
2495 m_synchronicity = m_options.m_synchronicity;
2496 m_completion_type = m_options.m_completion_type;
2497
2498 // Handle the case where we prompt for the script code first:
2499 if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
2500 m_interpreter.GetPythonCommandsFromIOHandler(" ", // Prompt
2501 *this); // IOHandlerDelegate
2502 // Still gathering input; the IOHandler will set the final status.
2504 return;
2505 }
2506
2507 CommandObjectSP new_cmd_sp;
2508 if (m_options.m_class_name.empty()) {
2509 new_cmd_sp = std::make_shared<CommandObjectPythonFunction>(
2510 m_interpreter, m_cmd_name, m_options.m_funct_name,
2512 } else {
2514 if (!interpreter) {
2515 result.AppendError("cannot find ScriptInterpreter");
2516 return;
2517 }
2518
2519 auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
2520 m_options.m_class_name.c_str());
2521 if (!cmd_obj_sp) {
2522 result.AppendErrorWithFormatv("cannot create helper object for: "
2523 "'{0}'", m_options.m_class_name);
2524 return;
2525 }
2526
2527 if (m_options.m_parsed_command) {
2529 m_cmd_name, cmd_obj_sp, m_synchronicity, result);
2530 if (!result.Succeeded())
2531 return;
2532 } else
2533 new_cmd_sp = std::make_shared<CommandObjectScriptingObjectRaw>(
2536 }
2537
2538 // Assume we're going to succeed...
2540 if (!m_container) {
2541 Status add_error =
2542 m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
2543 if (add_error.Fail())
2544 result.AppendErrorWithFormat("cannot add command: %s",
2545 add_error.AsCString());
2546 } else {
2547 llvm::Error llvm_error =
2548 m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
2549 if (llvm_error)
2550 result.AppendErrorWithFormat(
2551 "cannot add command: %s",
2552 llvm::toString(std::move(llvm_error)).c_str());
2553 }
2554 }
2555
2557 std::string m_cmd_name;
2559 std::string m_short_help;
2560 bool m_overwrite = false;
2564};
2565
2566// CommandObjectCommandsScriptList
2567
2569public:
2571 : CommandObjectParsed(interpreter, "command script list",
2572 "List defined top-level scripted commands.",
2573 nullptr) {}
2574
2576
2577 void DoExecute(Args &command, CommandReturnObject &result) override {
2579
2581 }
2582};
2583
2584// CommandObjectCommandsScriptClear
2585
2587public:
2589 : CommandObjectParsed(interpreter, "command script clear",
2590 "Delete all scripted commands.", nullptr) {}
2591
2593
2594protected:
2595 void DoExecute(Args &command, CommandReturnObject &result) override {
2596 m_interpreter.RemoveAllUser();
2597
2599 }
2600};
2601
2602// CommandObjectCommandsScriptDelete
2603
2605public:
2608 interpreter, "command script delete",
2609 "Delete a scripted command by specifying the path to the command.",
2610 nullptr) {
2612 }
2613
2615
2616 void
2618 OptionElementVector &opt_element_vector) override {
2620 m_interpreter, request, opt_element_vector);
2621 }
2622
2623protected:
2624 void DoExecute(Args &command, CommandReturnObject &result) override {
2625
2626 llvm::StringRef root_cmd = command[0].ref();
2627 size_t num_args = command.GetArgumentCount();
2628
2629 if (root_cmd.empty()) {
2630 result.AppendErrorWithFormat("empty root command name");
2631 return;
2632 }
2633 if (!m_interpreter.HasUserCommands() &&
2634 !m_interpreter.HasUserMultiwordCommands()) {
2635 result.AppendErrorWithFormat("can only delete user defined commands, "
2636 "but no user defined commands found");
2637 return;
2638 }
2639
2640 CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
2641 if (!cmd_sp) {
2642 result.AppendErrorWithFormat("command '%s' not found",
2643 command[0].c_str());
2644 return;
2645 }
2646 if (!cmd_sp->IsUserCommand()) {
2647 result.AppendErrorWithFormat("command '%s' is not a user command",
2648 command[0].c_str());
2649 return;
2650 }
2651 if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
2652 result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
2653 "Delete with \"command container delete\"",
2654 command[0].c_str());
2655 return;
2656 }
2657
2658 if (command.GetArgumentCount() == 1) {
2659 m_interpreter.RemoveUser(root_cmd);
2661 return;
2662 }
2663 // We're deleting a command from a multiword command. Verify the command
2664 // path:
2665 Status error;
2666 CommandObjectMultiword *container =
2668 error);
2669 if (error.Fail()) {
2670 result.AppendErrorWithFormat("could not resolve command path: %s",
2671 error.AsCString());
2672 return;
2673 }
2674 if (!container) {
2675 // This means that command only had a leaf command, so the container is
2676 // the root. That should have been handled above.
2677 result.AppendErrorWithFormat("could not find a container for '%s'",
2678 command[0].c_str());
2679 return;
2680 }
2681 const char *leaf_cmd = command[num_args - 1].c_str();
2682 llvm::Error llvm_error =
2683 container->RemoveUserSubcommand(leaf_cmd,
2684 /* multiword not okay */ false);
2685 if (llvm_error) {
2686 result.AppendErrorWithFormat(
2687 "could not delete command '%s': %s", leaf_cmd,
2688 llvm::toString(std::move(llvm_error)).c_str());
2689 return;
2690 }
2691
2692 Stream &out_stream = result.GetOutputStream();
2693
2694 out_stream << "Deleted command:";
2695 for (size_t idx = 0; idx < num_args; idx++) {
2696 out_stream << ' ';
2697 out_stream << command[idx].c_str();
2698 }
2699 out_stream << '\n';
2701 }
2702};
2703
2704#pragma mark CommandObjectMultiwordCommandsScript
2705
2706// CommandObjectMultiwordCommandsScript
2707
2709public:
2712 interpreter, "command script",
2713 "Commands for managing custom "
2714 "commands implemented by "
2715 "interpreter scripts.",
2716 "command script <subcommand> [<subcommand-options>]") {
2718 new CommandObjectCommandsScriptAdd(interpreter)));
2720 "delete",
2723 "clear",
2726 interpreter)));
2728 "import",
2730 }
2731
2733};
2734
2735#pragma mark CommandObjectCommandContainer
2736#define LLDB_OPTIONS_container_add
2737#include "CommandOptions.inc"
2738
2740public:
2743 interpreter, "command container add",
2744 "Add a container command to lldb. Adding to built-"
2745 "in container commands is not allowed.",
2746 "command container add [[path1]...] container-name") {
2748 }
2749
2751
2752 Options *GetOptions() override { return &m_options; }
2753
2754 void
2756 OptionElementVector &opt_element_vector) override {
2758 m_interpreter, request, opt_element_vector);
2759 }
2760
2761protected:
2762 class CommandOptions : public Options {
2763 public:
2764 CommandOptions() = default;
2765
2766 ~CommandOptions() override = default;
2767
2768 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2769 ExecutionContext *execution_context) override {
2770 Status error;
2771 const int short_option = m_getopt_table[option_idx].val;
2772
2773 switch (short_option) {
2774 case 'h':
2775 if (!option_arg.empty())
2776 m_short_help = std::string(option_arg);
2777 break;
2778 case 'o':
2779 m_overwrite = true;
2780 break;
2781 case 'H':
2782 if (!option_arg.empty())
2783 m_long_help = std::string(option_arg);
2784 break;
2785 default:
2786 llvm_unreachable("Unimplemented option");
2787 }
2788
2789 return error;
2790 }
2791
2792 void OptionParsingStarting(ExecutionContext *execution_context) override {
2793 m_short_help.clear();
2794 m_long_help.clear();
2795 m_overwrite = false;
2796 }
2797
2798 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2799 return llvm::ArrayRef(g_container_add_options);
2800 }
2801
2802 // Instance variables to hold the values for command options.
2803
2804 std::string m_short_help;
2805 std::string m_long_help;
2806 bool m_overwrite = false;
2807 };
2808 void DoExecute(Args &command, CommandReturnObject &result) override {
2809 size_t num_args = command.GetArgumentCount();
2810
2811 if (num_args == 0) {
2812 result.AppendError("no command was specified");
2813 return;
2814 }
2815
2816 if (num_args == 1) {
2817 // We're adding this as a root command, so use the interpreter.
2818 const char *cmd_name = command.GetArgumentAtIndex(0);
2819 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2820 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2821 m_options.m_long_help.c_str()));
2822 cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
2824 cmd_name, cmd_sp, m_options.m_overwrite);
2825 if (add_error.Fail()) {
2826 result.AppendErrorWithFormat("error adding command: %s",
2827 add_error.AsCString());
2828 return;
2829 }
2831 return;
2832 }
2833
2834 // We're adding this to a subcommand, first find the subcommand:
2835 Status path_error;
2836 CommandObjectMultiword *add_to_me =
2838 path_error);
2839
2840 if (!add_to_me) {
2841 result.AppendErrorWithFormat("error adding command: %s",
2842 path_error.AsCString());
2843 return;
2844 }
2845
2846 const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
2847 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2848 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2849 m_options.m_long_help.c_str()));
2850 llvm::Error llvm_error =
2851 add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
2852 if (llvm_error) {
2853 result.AppendErrorWithFormat("error adding subcommand: %s",
2854 llvm::toString(std::move(llvm_error)).c_str());
2855 return;
2856 }
2857
2859 }
2860
2861private:
2863};
2864
2865#define LLDB_OPTIONS_multiword_delete
2866#include "CommandOptions.inc"
2868public:
2871 interpreter, "command container delete",
2872 "Delete a container command previously added to "
2873 "lldb.",
2874 "command container delete [[path1] ...] container-cmd") {
2876 }
2877
2879
2880 void
2882 OptionElementVector &opt_element_vector) override {
2884 m_interpreter, request, opt_element_vector);
2885 }
2886
2887protected:
2888 void DoExecute(Args &command, CommandReturnObject &result) override {
2889 size_t num_args = command.GetArgumentCount();
2890
2891 if (num_args == 0) {
2892 result.AppendError("no command was specified");
2893 return;
2894 }
2895
2896 if (num_args == 1) {
2897 // We're removing a root command, so we need to delete it from the
2898 // interpreter.
2899 const char *cmd_name = command.GetArgumentAtIndex(0);
2900 // Let's do a little more work here so we can do better error reporting.
2902 CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2903 if (!cmd_sp) {
2904 result.AppendErrorWithFormat("container command %s doesn't exist",
2905 cmd_name);
2906 return;
2907 }
2908 if (!cmd_sp->IsUserCommand()) {
2909 result.AppendErrorWithFormat(
2910 "container command %s is not a user command", cmd_name);
2911 return;
2912 }
2913 if (!cmd_sp->GetAsMultiwordCommand()) {
2914 result.AppendErrorWithFormat("command %s is not a container command",
2915 cmd_name);
2916 return;
2917 }
2918
2919 bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2920 if (!did_remove) {
2921 result.AppendErrorWithFormat("error removing command %s", cmd_name);
2922 return;
2923 }
2924
2926 return;
2927 }
2928
2929 // We're removing a subcommand, first find the subcommand's owner:
2930 Status path_error;
2931 CommandObjectMultiword *container =
2933 path_error);
2934
2935 if (!container) {
2936 result.AppendErrorWithFormat("error removing container command: %s",
2937 path_error.AsCString());
2938 return;
2939 }
2940 const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2941 llvm::Error llvm_error =
2942 container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2943 if (llvm_error) {
2944 result.AppendErrorWithFormat("error removing container command: %s",
2945 llvm::toString(std::move(llvm_error)).c_str());
2946 return;
2947 }
2949 }
2950};
2951
2953public:
2956 interpreter, "command container",
2957 "Commands for adding container commands to lldb. "
2958 "Container commands are containers for other commands. You can "
2959 "add nested container commands by specifying a command path, "
2960 "but you can't add commands into the built-in command hierarchy.",
2961 "command container <subcommand> [<subcommand-options>]") {
2963 interpreter)));
2965 "delete",
2967 }
2968
2970};
2971
2972#pragma mark CommandObjectMultiwordCommands
2973
2974// CommandObjectMultiwordCommands
2975
2977 CommandInterpreter &interpreter)
2978 : CommandObjectMultiword(interpreter, "command",
2979 "Commands for managing custom LLDB commands.",
2980 "command <subcommand> [<subcommand-options>]") {
2981 LoadSubCommand("source",
2983 LoadSubCommand("alias",
2986 new CommandObjectCommandsUnalias(interpreter)));
2987 LoadSubCommand("delete",
2990 interpreter)));
2992 "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2994 "script",
2996}
2997
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.
ExecutionContext GetExecutionContext() const
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
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:525
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:514
void MakeAbsolute(const FileSpec &dir)
Make the FileSpec absolute by treating it relative to dir.
Definition FileSpec.cpp:537
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.