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'.",
666 args[0].c_str());
667 else
668 result.AppendErrorWithFormat("'%s' is not an existing alias.",
669 args[0].c_str());
670 return;
671 }
672
674 }
675};
676
677#pragma mark CommandObjectCommandsDelete
678// CommandObjectCommandsDelete
679
681public:
684 interpreter, "command delete",
685 "Delete one or more custom commands defined by 'command regex'.",
686 nullptr) {
688 }
689
690 ~CommandObjectCommandsDelete() override = default;
691
692 void
694 OptionElementVector &opt_element_vector) override {
695 if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
696 return;
697
698 for (const auto &ent : m_interpreter.GetCommands()) {
699 if (ent.second->IsRemovable())
700 request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
701 }
702 }
703
704protected:
705 void DoExecute(Args &args, CommandReturnObject &result) override {
706 CommandObject::CommandMap::iterator pos;
707
708 if (args.empty()) {
709 result.AppendErrorWithFormat("must call '%s' with one or more valid user "
710 "defined regular expression command names",
711 GetCommandName().str().c_str());
712 return;
713 }
714
715 auto command_name = args[0].ref();
716 if (!m_interpreter.CommandExists(command_name)) {
717 StreamString error_msg_stream;
718 const bool generate_upropos = true;
719 const bool generate_type_lookup = false;
721 &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
722 generate_upropos, generate_type_lookup);
723 result.AppendError(error_msg_stream.GetString());
724 return;
725 }
726
727 if (!m_interpreter.RemoveCommand(command_name)) {
729 "'%s' is a permanent debugger command and cannot be removed.",
730 args[0].c_str());
731 return;
732 }
733
735 }
736};
737
738// CommandObjectCommandsAddRegex
739
740#define LLDB_OPTIONS_regex
741#include "CommandOptions.inc"
742
743#pragma mark CommandObjectCommandsAddRegex
744
747public:
750 interpreter, "command regex",
751 "Define a custom command in terms of "
752 "existing commands by matching "
753 "regular expressions.",
754 "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
758 R"(
759)"
760 "This command allows the user to create powerful regular expression commands \
761with substitutions. The regular expressions and substitutions are specified \
762using the regular expression substitution format of:"
763 R"(
764
765 s/<regex>/<subst>/
766
767)"
768 "<regex> is a regular expression that can use parenthesis to capture regular \
769expression input and substitute the captured matches in the output using %1 \
770for the first match, %2 for the second, and so on."
771 R"(
772
773)"
774 "The regular expressions can all be specified on the command line if more than \
775one argument is provided. If just the command name is provided on the command \
776line, then the regular expressions and substitutions can be entered on separate \
777lines, followed by an empty line to terminate the command definition."
778 R"(
780EXAMPLES
781
783 "The following example will define a regular expression command named 'f' that \
784will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
785a number follows 'f':"
786 R"(
787
788 (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
790 }
791
792 ~CommandObjectCommandsAddRegex() override = default;
793
794protected:
795 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
796 if (interactive) {
797 if (lldb::LockableStreamFileSP output_sp =
798 io_handler.GetOutputStreamFileSP()) {
799 LockedStreamFile locked_stream = output_sp->Lock();
800 locked_stream.PutCString(
801 "Enter one or more sed substitution commands in "
802 "the form: 's/<regex>/<subst>/'.\nTerminate the "
803 "substitution list with an empty line.\n");
804 }
805 }
806 }
807
808 void IOHandlerInputComplete(IOHandler &io_handler,
809 std::string &data) override {
810 io_handler.SetIsDone(true);
811 if (m_regex_cmd_up) {
812 StringList lines;
813 if (lines.SplitIntoLines(data)) {
814 bool check_only = false;
815 for (const std::string &line : lines) {
816 Status error = AppendRegexSubstitution(line, check_only);
817 if (error.Fail()) {
818 if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode())
819 GetDebugger().GetAsyncOutputStream()->Printf("error: %s\n",
820 error.AsCString());
821 }
822 }
823 }
824 if (m_regex_cmd_up->HasRegexEntries()) {
825 CommandObjectSP cmd_sp(m_regex_cmd_up.release());
826 m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
827 }
828 }
829 }
830
831 void DoExecute(Args &command, CommandReturnObject &result) override {
832 const size_t argc = command.GetArgumentCount();
833 if (argc == 0) {
834 result.AppendError("usage: 'command regex <command-name> "
835 "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
836 return;
837 }
838
840 auto name = command[0].ref();
841 m_regex_cmd_up = std::make_unique<CommandObjectRegexCommand>(
842 m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 0,
843 true);
844
845 if (argc == 1) {
846 Debugger &debugger = GetDebugger();
847 bool color_prompt = debugger.GetUseColor();
848 const bool multiple_lines = true; // Get multiple lines
849 IOHandlerSP io_handler_sp(new IOHandlerEditline(
850 debugger, IOHandler::Type::Other,
851 "lldb-regex", // Name of input reader for history
852 llvm::StringRef("> "), // Prompt
853 llvm::StringRef(), // Continuation prompt
854 multiple_lines, color_prompt,
855 0, // Don't show line numbers
856 *this));
857
858 if (io_handler_sp) {
859 debugger.RunIOHandlerAsync(io_handler_sp);
861 }
862 } else {
863 for (auto &entry : command.entries().drop_front()) {
864 bool check_only = false;
865 error = AppendRegexSubstitution(entry.ref(), check_only);
866 if (error.Fail())
867 break;
868 }
869
870 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 {0} of arguments "
1920 "list element {1}: %s.",
1921 elem_counter, counter, err_txt);
1922 return false;
1923 };
1924
1925 StructuredData::Dictionary *arg_dict = object->GetAsDictionary();
1926 if (!arg_dict) {
1927 report_error("is not a dictionary.");
1928 return false;
1929 }
1930 // Argument Type:
1932 = arg_dict->GetValueForKey("arg_type");
1933 if (obj_sp) {
1935 = obj_sp->GetAsUnsignedInteger();
1936 if (!uint_val) {
1937 report_error("value type must be an unsigned integer");
1938 return false;
1939 }
1940 uint64_t arg_type_int = uint_val->GetValue();
1941 if (arg_type_int >= eArgTypeLastArg) {
1942 report_error("value type beyond ArgumentRepetitionType bounds");
1943 return false;
1944 }
1945 arg_type = (CommandArgumentType) arg_type_int;
1946 }
1947 // Repeat Value:
1948 obj_sp = arg_dict->GetValueForKey("repeat");
1949 std::optional<ArgumentRepetitionType> repeat;
1950 if (obj_sp) {
1951 llvm::StringRef repeat_str = obj_sp->GetStringValue();
1952 if (repeat_str.empty()) {
1953 report_error("repeat value is empty");
1954 return false;
1955 }
1956 repeat = ArgRepetitionFromString(repeat_str);
1957 if (!repeat) {
1958 report_error("invalid repeat value");
1959 return false;
1960 }
1961 arg_repetition = *repeat;
1962 }
1963
1964 // Usage Mask:
1965 obj_sp = arg_dict->GetValueForKey("groups");
1967 counter, arg_opt_set_association);
1968 this_entry.emplace_back(arg_type, arg_repetition,
1969 arg_opt_set_association);
1970 elem_counter++;
1971 return true;
1972 };
1973 StructuredData::Array *args_array = object->GetAsArray();
1974 if (!args_array) {
1975 m_args_error =
1976 Status::FromErrorStringWithFormatv("Argument definition element "
1977 "{0} is not an array",
1978 counter);
1979 }
1980
1981 args_array->ForEach(args_adder);
1982 if (m_args_error.Fail())
1983 return false;
1984 if (this_entry.empty()) {
1985 m_args_error =
1986 Status::FromErrorStringWithFormatv("Argument definition element "
1987 "{0} is empty",
1988 counter);
1989 return false;
1990 }
1991 m_arguments.push_back(this_entry);
1992 counter++;
1993 return true;
1994 }; // end of arg_array_adder
1995 // Here we actually parse the args definition:
1996 args_array->ForEach(arg_array_adder);
1997 }
1998 }
1999
2001
2003 Status GetArgsError() { return m_args_error.Clone(); }
2004 bool WantsCompletion() override { return true; }
2005
2006private:
2008 OptionElementVector &option_vec) {
2009 // First, we have to tell the Scripted side to set the values in its
2010 // option store, then we call into the handle_completion passing in
2011 // an array of the args, the arg index and the cursor position in the arg.
2012 // We want the script side to have a chance to clear its state, so tell
2013 // it argument parsing has started:
2014 Options *options = GetOptions();
2015 // If there are not options, this will be nullptr, and in that case we
2016 // can just skip setting the options on the scripted side:
2017 if (options)
2018 m_options.PrepareOptionsForCompletion(request, option_vec, &m_exe_ctx);
2019 }
2020
2021public:
2023 OptionElementVector &option_vec) override {
2025
2026 if (!scripter)
2027 return;
2028
2029 // Set up the options values on the scripted side:
2030 PrepareOptionsForCompletion(request, option_vec);
2031
2032 // Now we have to make up the argument list.
2033 // The ParseForCompletion only identifies tokens in the m_parsed_line
2034 // it doesn't remove the options leaving only the args as it does for
2035 // the regular Parse, so we have to filter out the option ones using the
2036 // option_element_vector:
2037
2038 Options *options = GetOptions();
2039 auto defs = options ? options->GetDefinitions()
2040 : llvm::ArrayRef<OptionDefinition>();
2041
2042 std::unordered_set<size_t> option_slots;
2043 for (const auto &elem : option_vec) {
2044 if (elem.opt_defs_index == -1)
2045 continue;
2046 option_slots.insert(elem.opt_pos);
2047 if (defs[elem.opt_defs_index].option_has_arg)
2048 option_slots.insert(elem.opt_arg_pos);
2049 }
2050
2051 std::vector<llvm::StringRef> args_vec;
2052 Args &args = request.GetParsedLine();
2053 size_t num_args = args.GetArgumentCount();
2054 size_t cursor_idx = request.GetCursorIndex();
2055 size_t args_elem_pos = cursor_idx;
2056
2057 for (size_t idx = 0; idx < num_args; idx++) {
2058 if (option_slots.count(idx) == 0)
2059 args_vec.push_back(args[idx].ref());
2060 else if (idx < cursor_idx)
2061 args_elem_pos--;
2062 }
2063 StructuredData::DictionarySP completion_dict_sp =
2065 m_cmd_obj_sp, args_vec, args_elem_pos, request.GetCursorCharPos());
2066
2067 if (!completion_dict_sp) {
2068 CommandObject::HandleArgumentCompletion(request, option_vec);
2069 return;
2070 }
2071
2072 m_options.ProcessCompletionDict(request, completion_dict_sp);
2073 }
2074
2075 bool IsRemovable() const override { return true; }
2076
2078
2079 std::optional<std::string> GetRepeatCommand(Args &args,
2080 uint32_t index) override {
2082 if (!scripter)
2083 return std::nullopt;
2084
2085 return scripter->GetRepeatCommandForScriptedCommand(m_cmd_obj_sp, args);
2086 }
2087
2088 llvm::StringRef GetHelp() override {
2092 if (!scripter)
2094 std::string docstring;
2096 scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
2097 if (!docstring.empty())
2098 SetHelp(docstring);
2099
2101 }
2102
2103 llvm::StringRef GetHelpLong() override {
2106
2108 if (!scripter)
2110
2111 std::string docstring;
2113 scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
2114 if (!docstring.empty())
2115 SetHelpLong(docstring);
2117 }
2118
2119 Options *GetOptions() override {
2120 // CommandObjectParsed requires that a command with no options return
2121 // nullptr.
2122 if (m_options.GetNumOptions() == 0)
2123 return nullptr;
2124 return &m_options;
2125 }
2126
2127protected:
2128 void DoExecute(Args &args,
2129 CommandReturnObject &result) override {
2131
2132 Status error;
2133
2135
2136 if (!scripter ||
2138 m_synchro, result, error, m_exe_ctx)) {
2139 result.AppendError(error.AsCString());
2140 } else {
2141 // Don't change the status if the command already set it...
2142 if (result.GetStatus() == eReturnStatusInvalid) {
2143 if (result.GetOutputString().empty())
2145 else
2147 }
2148 }
2149 }
2150
2151private:
2159};
2160
2161std::unordered_set<std::string>
2163
2164// CommandObjectCommandsScriptImport
2165#define LLDB_OPTIONS_script_import
2166#include "CommandOptions.inc"
2167
2169public:
2171 : CommandObjectParsed(interpreter, "command script import",
2172 "Import a scripting module in LLDB.", nullptr) {
2174 }
2175
2177
2178 Options *GetOptions() override { return &m_options; }
2179
2180protected:
2181 class CommandOptions : public Options {
2182 public:
2183 CommandOptions() = default;
2184
2185 ~CommandOptions() override = default;
2186
2187 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2188 ExecutionContext *execution_context) override {
2189 Status error;
2190 const int short_option = m_getopt_table[option_idx].val;
2191
2192 switch (short_option) {
2193 case 'r':
2194 // NO-OP
2195 break;
2196 case 'c':
2198 break;
2199 case 's':
2200 silent = true;
2201 break;
2202 default:
2203 llvm_unreachable("Unimplemented option");
2204 }
2205
2206 return error;
2207 }
2208
2209 void OptionParsingStarting(ExecutionContext *execution_context) override {
2211 }
2212
2213 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2214 return llvm::ArrayRef(g_script_import_options);
2215 }
2217 bool silent = false;
2218 };
2219
2220 void DoExecute(Args &command, CommandReturnObject &result) override {
2221 if (command.empty()) {
2222 result.AppendError("command script import needs one or more arguments");
2223 return;
2224 }
2225
2226 FileSpec source_dir = {};
2227 if (m_options.relative_to_command_file) {
2229 if (!source_dir) {
2230 result.AppendError("command script import -c can only be specified "
2231 "from a command file");
2232 return;
2233 }
2234 }
2235
2236 for (auto &entry : command.entries()) {
2237 Status error;
2238
2239 LoadScriptOptions options;
2240 options.SetInitSession(true);
2241 options.SetSilent(m_options.silent);
2242
2243 // FIXME: this is necessary because CommandObject::CheckRequirements()
2244 // assumes that commands won't ever be recursively invoked, but it's
2245 // actually possible to craft a Python script that does other "command
2246 // script imports" in __lldb_init_module the real fix is to have
2247 // recursive commands possible with a CommandInvocation object separate
2248 // from the CommandObject itself, so that recursive command invocations
2249 // won't stomp on each other (wrt to execution contents, options, and
2250 // more)
2251 m_exe_ctx.Clear();
2252 if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
2253 entry.c_str(), options, error, /*module_sp=*/nullptr,
2254 source_dir)) {
2256 } else {
2257 result.AppendErrorWithFormat("module importing failed: %s",
2258 error.AsCString());
2259 }
2260 }
2261 }
2262
2264};
2265
2266#define LLDB_OPTIONS_script_add
2267#include "CommandOptions.inc"
2268
2271public:
2273 : CommandObjectParsed(interpreter, "command script add",
2274 "Add a scripted function as an LLDB command.",
2275 "Add a scripted function as an lldb command. "
2276 "If you provide a single argument, the command "
2277 "will be added at the root level of the command "
2278 "hierarchy. If there are more arguments they "
2279 "must be a path to a user-added container "
2280 "command, and the last element will be the new "
2281 "command name."),
2284 }
2285
2287
2288 Options *GetOptions() override { return &m_options; }
2289
2290 void
2292 OptionElementVector &opt_element_vector) override {
2294 opt_element_vector);
2295 }
2296
2297protected:
2298 class CommandOptions : public Options {
2299 public:
2300 CommandOptions() = default;
2301
2302 ~CommandOptions() override = default;
2303
2304 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2305 ExecutionContext *execution_context) override {
2306 Status error;
2307 const int short_option = m_getopt_table[option_idx].val;
2308
2309 switch (short_option) {
2310 case 'f':
2311 if (!option_arg.empty())
2312 m_funct_name = std::string(option_arg);
2313 break;
2314 case 'c':
2315 if (!option_arg.empty())
2316 m_class_name = std::string(option_arg);
2317 break;
2318 case 'h':
2319 if (!option_arg.empty())
2320 m_short_help = std::string(option_arg);
2321 break;
2322 case 'o':
2324 break;
2325 case 'p':
2326 m_parsed_command = true;
2327 break;
2328 case 's':
2331 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
2332 if (!error.Success())
2334 "unrecognized value for synchronicity '%s'",
2335 option_arg.str().c_str());
2336 break;
2337 case 'C': {
2338 Status error;
2339 OptionDefinition definition = GetDefinitions()[option_idx];
2340 lldb::CompletionType completion_type =
2342 option_arg, definition.enum_values, eNoCompletion, error));
2343 if (!error.Success())
2345 "unrecognized value for command completion type '%s'",
2346 option_arg.str().c_str());
2347 m_completion_type = completion_type;
2348 } break;
2349 default:
2350 llvm_unreachable("Unimplemented option");
2351 }
2352
2353 return error;
2354 }
2355
2365
2366 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2367 return llvm::ArrayRef(g_script_add_options);
2368 }
2369
2370 // Instance variables to hold the values for command options.
2371
2372 std::string m_class_name;
2373 std::string m_funct_name;
2374 std::string m_short_help;
2379 bool m_parsed_command = false;
2380 };
2381
2382 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
2383 if (interactive) {
2384 if (lldb::LockableStreamFileSP output_sp =
2385 io_handler.GetOutputStreamFileSP()) {
2386 LockedStreamFile locked_stream = output_sp->Lock();
2388 }
2389 }
2390 }
2391
2393 std::string &data) override {
2394 LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
2395
2397 if (interpreter) {
2398 StringList lines;
2399 lines.SplitIntoLines(data);
2400 if (lines.GetSize() > 0) {
2401 std::string funct_name_str;
2402 if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
2403 if (funct_name_str.empty()) {
2404 LockedStreamFile locked_stream = error_sp->Lock();
2405 locked_stream.Printf(
2406 "error: unable to obtain a function name, didn't "
2407 "add python command.\n");
2408 } else {
2409 // everything should be fine now, let's add this alias
2410
2412 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
2414 if (!m_container) {
2415 Status error = m_interpreter.AddUserCommand(
2416 m_cmd_name, command_obj_sp, m_overwrite);
2417 if (error.Fail()) {
2418 LockedStreamFile locked_stream = error_sp->Lock();
2419 locked_stream.Printf(
2420 "error: unable to add selected command: '%s'",
2421 error.AsCString());
2422 }
2423 } else {
2424 llvm::Error llvm_error = m_container->LoadUserSubcommand(
2425 m_cmd_name, command_obj_sp, m_overwrite);
2426 if (llvm_error) {
2427 LockedStreamFile locked_stream = error_sp->Lock();
2428 locked_stream.Printf(
2429 "error: unable to add selected command: '%s'",
2430 llvm::toString(std::move(llvm_error)).c_str());
2431 }
2432 }
2433 }
2434 } else {
2435 LockedStreamFile locked_stream = error_sp->Lock();
2436 locked_stream.Printf(
2437 "error: unable to create function, didn't add python command\n");
2438 }
2439 } else {
2440 LockedStreamFile locked_stream = error_sp->Lock();
2441 locked_stream.Printf(
2442 "error: empty function, didn't add python command\n");
2443 }
2444 } else {
2445 LockedStreamFile locked_stream = error_sp->Lock();
2446 locked_stream.Printf(
2447 "error: script interpreter missing, didn't add python command\n");
2448 }
2449
2450 io_handler.SetIsDone(true);
2451 }
2452
2453 void DoExecute(Args &command, CommandReturnObject &result) override {
2454 if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
2455 result.AppendError("only scripting language supported for scripted "
2456 "commands is currently Python");
2457 return;
2458 }
2459
2460 if (command.GetArgumentCount() == 0) {
2461 result.AppendError("'command script add' requires at least one argument");
2462 return;
2463 }
2464 // Store the options in case we get multi-line input, also figure out the
2465 // default if not user supplied:
2466 switch (m_options.m_overwrite_lazy) {
2467 case eLazyBoolCalculate:
2469 break;
2470 case eLazyBoolYes:
2471 m_overwrite = true;
2472 break;
2473 case eLazyBoolNo:
2474 m_overwrite = false;
2475 }
2476
2477 Status path_error;
2479 command, true, path_error);
2480
2481 if (path_error.Fail()) {
2482 result.AppendErrorWithFormat("error in command path: %s",
2483 path_error.AsCString());
2484 return;
2485 }
2486
2487 if (!m_container) {
2488 // This is getting inserted into the root of the interpreter.
2489 m_cmd_name = std::string(command[0].ref());
2490 } else {
2491 size_t num_args = command.GetArgumentCount();
2492 m_cmd_name = std::string(command[num_args - 1].ref());
2493 }
2494
2495 m_short_help.assign(m_options.m_short_help);
2496 m_synchronicity = m_options.m_synchronicity;
2497 m_completion_type = m_options.m_completion_type;
2498
2499 // Handle the case where we prompt for the script code first:
2500 if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
2501 m_interpreter.GetPythonCommandsFromIOHandler(" ", // Prompt
2502 *this); // IOHandlerDelegate
2503 return;
2504 }
2505
2506 CommandObjectSP new_cmd_sp;
2507 if (m_options.m_class_name.empty()) {
2508 new_cmd_sp = std::make_shared<CommandObjectPythonFunction>(
2509 m_interpreter, m_cmd_name, m_options.m_funct_name,
2511 } else {
2513 if (!interpreter) {
2514 result.AppendError("cannot find ScriptInterpreter");
2515 return;
2516 }
2517
2518 auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
2519 m_options.m_class_name.c_str());
2520 if (!cmd_obj_sp) {
2521 result.AppendErrorWithFormatv("cannot create helper object for: "
2522 "'{0}'", m_options.m_class_name);
2523 return;
2524 }
2525
2526 if (m_options.m_parsed_command) {
2528 m_cmd_name, cmd_obj_sp, m_synchronicity, result);
2529 if (!result.Succeeded())
2530 return;
2531 } else
2532 new_cmd_sp = std::make_shared<CommandObjectScriptingObjectRaw>(
2535 }
2536
2537 // Assume we're going to succeed...
2539 if (!m_container) {
2540 Status add_error =
2541 m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
2542 if (add_error.Fail())
2543 result.AppendErrorWithFormat("cannot add command: %s",
2544 add_error.AsCString());
2545 } else {
2546 llvm::Error llvm_error =
2547 m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
2548 if (llvm_error)
2549 result.AppendErrorWithFormat(
2550 "cannot add command: %s",
2551 llvm::toString(std::move(llvm_error)).c_str());
2552 }
2553 }
2554
2556 std::string m_cmd_name;
2558 std::string m_short_help;
2559 bool m_overwrite = false;
2563};
2564
2565// CommandObjectCommandsScriptList
2566
2568public:
2570 : CommandObjectParsed(interpreter, "command script list",
2571 "List defined top-level scripted commands.",
2572 nullptr) {}
2573
2575
2576 void DoExecute(Args &command, CommandReturnObject &result) override {
2578
2580 }
2581};
2582
2583// CommandObjectCommandsScriptClear
2584
2586public:
2588 : CommandObjectParsed(interpreter, "command script clear",
2589 "Delete all scripted commands.", nullptr) {}
2590
2592
2593protected:
2594 void DoExecute(Args &command, CommandReturnObject &result) override {
2595 m_interpreter.RemoveAllUser();
2596
2598 }
2599};
2600
2601// CommandObjectCommandsScriptDelete
2602
2604public:
2607 interpreter, "command script delete",
2608 "Delete a scripted command by specifying the path to the command.",
2609 nullptr) {
2611 }
2612
2614
2615 void
2617 OptionElementVector &opt_element_vector) override {
2619 m_interpreter, request, opt_element_vector);
2620 }
2621
2622protected:
2623 void DoExecute(Args &command, CommandReturnObject &result) override {
2624
2625 llvm::StringRef root_cmd = command[0].ref();
2626 size_t num_args = command.GetArgumentCount();
2627
2628 if (root_cmd.empty()) {
2629 result.AppendErrorWithFormat("empty root command name");
2630 return;
2631 }
2632 if (!m_interpreter.HasUserCommands() &&
2633 !m_interpreter.HasUserMultiwordCommands()) {
2634 result.AppendErrorWithFormat("can only delete user defined commands, "
2635 "but no user defined commands found");
2636 return;
2637 }
2638
2639 CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
2640 if (!cmd_sp) {
2641 result.AppendErrorWithFormat("command '%s' not found.",
2642 command[0].c_str());
2643 return;
2644 }
2645 if (!cmd_sp->IsUserCommand()) {
2646 result.AppendErrorWithFormat("command '%s' is not a user command.",
2647 command[0].c_str());
2648 return;
2649 }
2650 if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
2651 result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
2652 "Delete with \"command container delete\"",
2653 command[0].c_str());
2654 return;
2655 }
2656
2657 if (command.GetArgumentCount() == 1) {
2658 m_interpreter.RemoveUser(root_cmd);
2660 return;
2661 }
2662 // We're deleting a command from a multiword command. Verify the command
2663 // path:
2664 Status error;
2665 CommandObjectMultiword *container =
2667 error);
2668 if (error.Fail()) {
2669 result.AppendErrorWithFormat("could not resolve command path: %s",
2670 error.AsCString());
2671 return;
2672 }
2673 if (!container) {
2674 // This means that command only had a leaf command, so the container is
2675 // the root. That should have been handled above.
2676 result.AppendErrorWithFormat("could not find a container for '%s'",
2677 command[0].c_str());
2678 return;
2679 }
2680 const char *leaf_cmd = command[num_args - 1].c_str();
2681 llvm::Error llvm_error =
2682 container->RemoveUserSubcommand(leaf_cmd,
2683 /* multiword not okay */ false);
2684 if (llvm_error) {
2685 result.AppendErrorWithFormat(
2686 "could not delete command '%s': %s", leaf_cmd,
2687 llvm::toString(std::move(llvm_error)).c_str());
2688 return;
2689 }
2690
2691 Stream &out_stream = result.GetOutputStream();
2692
2693 out_stream << "Deleted command:";
2694 for (size_t idx = 0; idx < num_args; idx++) {
2695 out_stream << ' ';
2696 out_stream << command[idx].c_str();
2697 }
2698 out_stream << '\n';
2700 }
2701};
2702
2703#pragma mark CommandObjectMultiwordCommandsScript
2704
2705// CommandObjectMultiwordCommandsScript
2706
2708public:
2711 interpreter, "command script",
2712 "Commands for managing custom "
2713 "commands implemented by "
2714 "interpreter scripts.",
2715 "command script <subcommand> [<subcommand-options>]") {
2717 new CommandObjectCommandsScriptAdd(interpreter)));
2719 "delete",
2722 "clear",
2725 interpreter)));
2727 "import",
2729 }
2730
2732};
2733
2734#pragma mark CommandObjectCommandContainer
2735#define LLDB_OPTIONS_container_add
2736#include "CommandOptions.inc"
2737
2739public:
2742 interpreter, "command container add",
2743 "Add a container command to lldb. Adding to built-"
2744 "in container commands is not allowed.",
2745 "command container add [[path1]...] container-name") {
2747 }
2748
2750
2751 Options *GetOptions() override { return &m_options; }
2752
2753 void
2755 OptionElementVector &opt_element_vector) override {
2757 m_interpreter, request, opt_element_vector);
2758 }
2759
2760protected:
2761 class CommandOptions : public Options {
2762 public:
2763 CommandOptions() = default;
2764
2765 ~CommandOptions() override = default;
2766
2767 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2768 ExecutionContext *execution_context) override {
2769 Status error;
2770 const int short_option = m_getopt_table[option_idx].val;
2771
2772 switch (short_option) {
2773 case 'h':
2774 if (!option_arg.empty())
2775 m_short_help = std::string(option_arg);
2776 break;
2777 case 'o':
2778 m_overwrite = true;
2779 break;
2780 case 'H':
2781 if (!option_arg.empty())
2782 m_long_help = std::string(option_arg);
2783 break;
2784 default:
2785 llvm_unreachable("Unimplemented option");
2786 }
2787
2788 return error;
2789 }
2790
2791 void OptionParsingStarting(ExecutionContext *execution_context) override {
2792 m_short_help.clear();
2793 m_long_help.clear();
2794 m_overwrite = false;
2795 }
2796
2797 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2798 return llvm::ArrayRef(g_container_add_options);
2799 }
2800
2801 // Instance variables to hold the values for command options.
2802
2803 std::string m_short_help;
2804 std::string m_long_help;
2805 bool m_overwrite = false;
2806 };
2807 void DoExecute(Args &command, CommandReturnObject &result) override {
2808 size_t num_args = command.GetArgumentCount();
2809
2810 if (num_args == 0) {
2811 result.AppendError("no command was specified");
2812 return;
2813 }
2814
2815 if (num_args == 1) {
2816 // We're adding this as a root command, so use the interpreter.
2817 const char *cmd_name = command.GetArgumentAtIndex(0);
2818 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2819 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2820 m_options.m_long_help.c_str()));
2821 cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
2823 cmd_name, cmd_sp, m_options.m_overwrite);
2824 if (add_error.Fail()) {
2825 result.AppendErrorWithFormat("error adding command: %s",
2826 add_error.AsCString());
2827 return;
2828 }
2830 return;
2831 }
2832
2833 // We're adding this to a subcommand, first find the subcommand:
2834 Status path_error;
2835 CommandObjectMultiword *add_to_me =
2837 path_error);
2838
2839 if (!add_to_me) {
2840 result.AppendErrorWithFormat("error adding command: %s",
2841 path_error.AsCString());
2842 return;
2843 }
2844
2845 const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
2846 auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
2847 GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
2848 m_options.m_long_help.c_str()));
2849 llvm::Error llvm_error =
2850 add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
2851 if (llvm_error) {
2852 result.AppendErrorWithFormat("error adding subcommand: %s",
2853 llvm::toString(std::move(llvm_error)).c_str());
2854 return;
2855 }
2856
2858 }
2859
2860private:
2862};
2863
2864#define LLDB_OPTIONS_multiword_delete
2865#include "CommandOptions.inc"
2867public:
2870 interpreter, "command container delete",
2871 "Delete a container command previously added to "
2872 "lldb.",
2873 "command container delete [[path1] ...] container-cmd") {
2875 }
2876
2878
2879 void
2881 OptionElementVector &opt_element_vector) override {
2883 m_interpreter, request, opt_element_vector);
2884 }
2885
2886protected:
2887 void DoExecute(Args &command, CommandReturnObject &result) override {
2888 size_t num_args = command.GetArgumentCount();
2889
2890 if (num_args == 0) {
2891 result.AppendError("no command was specified");
2892 return;
2893 }
2894
2895 if (num_args == 1) {
2896 // We're removing a root command, so we need to delete it from the
2897 // interpreter.
2898 const char *cmd_name = command.GetArgumentAtIndex(0);
2899 // Let's do a little more work here so we can do better error reporting.
2901 CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2902 if (!cmd_sp) {
2903 result.AppendErrorWithFormat("container command %s doesn't exist.",
2904 cmd_name);
2905 return;
2906 }
2907 if (!cmd_sp->IsUserCommand()) {
2908 result.AppendErrorWithFormat(
2909 "container command %s is not a user command", cmd_name);
2910 return;
2911 }
2912 if (!cmd_sp->GetAsMultiwordCommand()) {
2913 result.AppendErrorWithFormat("command %s is not a container command",
2914 cmd_name);
2915 return;
2916 }
2917
2918 bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2919 if (!did_remove) {
2920 result.AppendErrorWithFormat("error removing command %s.", cmd_name);
2921 return;
2922 }
2923
2925 return;
2926 }
2927
2928 // We're removing a subcommand, first find the subcommand's owner:
2929 Status path_error;
2930 CommandObjectMultiword *container =
2932 path_error);
2933
2934 if (!container) {
2935 result.AppendErrorWithFormat("error removing container command: %s",
2936 path_error.AsCString());
2937 return;
2938 }
2939 const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2940 llvm::Error llvm_error =
2941 container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2942 if (llvm_error) {
2943 result.AppendErrorWithFormat("error removing container command: %s",
2944 llvm::toString(std::move(llvm_error)).c_str());
2945 return;
2946 }
2948 }
2949};
2950
2952public:
2955 interpreter, "command container",
2956 "Commands for adding container commands to lldb. "
2957 "Container commands are containers for other commands. You can "
2958 "add nested container commands by specifying a command path, "
2959 "but you can't add commands into the built-in command hierarchy.",
2960 "command container <subcommand> [<subcommand-options>]") {
2962 interpreter)));
2964 "delete",
2966 }
2967
2969};
2970
2971#pragma mark CommandObjectMultiwordCommands
2972
2973// CommandObjectMultiwordCommands
2974
2976 CommandInterpreter &interpreter)
2977 : CommandObjectMultiword(interpreter, "command",
2978 "Commands for managing custom LLDB commands.",
2979 "command <subcommand> [<subcommand-options>]") {
2980 LoadSubCommand("source",
2982 LoadSubCommand("alias",
2985 new CommandObjectCommandsUnalias(interpreter)));
2986 LoadSubCommand("delete",
2989 interpreter)));
2991 "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2993 "script",
2995}
2996
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:132
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
@ 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.