LLDB mainline
CommandObject.h
Go to the documentation of this file.
1//===-- CommandObject.h -----------------------------------------*- C++ -*-===//
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
9#ifndef LLDB_INTERPRETER_COMMANDOBJECT_H
10#define LLDB_INTERPRETER_COMMANDOBJECT_H
11
12#include <map>
13#include <memory>
14#include <optional>
15#include <string>
16#include <vector>
17
18#include "lldb/Utility/Flags.h"
19
23#include "lldb/Utility/Args.h"
26#include "lldb/lldb-private.h"
27
28namespace lldb_private {
29
30// This function really deals with CommandObjectLists, but we didn't make a
31// CommandObjectList class, so I'm sticking it here. But we really should have
32// such a class. Anyway, it looks up the commands in the map that match the
33// partial string cmd_str, inserts the matches into matches, and returns the
34// number added.
35
36template <typename ValueType>
38 const std::map<std::string, ValueType> &in_map, llvm::StringRef cmd_str,
39 StringList &matches, StringList *descriptions = nullptr) {
40 int number_added = 0;
41
42 const bool add_all = cmd_str.empty();
43
44 for (auto iter = in_map.begin(), end = in_map.end(); iter != end; iter++) {
45 if (add_all || (iter->first.find(std::string(cmd_str), 0) == 0)) {
46 ++number_added;
47 matches.AppendString(iter->first.c_str());
48 if (descriptions)
49 descriptions->AppendString(iter->second->GetHelp());
50 }
51 }
52
53 return number_added;
54}
55
56template <typename ValueType>
57size_t FindLongestCommandWord(std::map<std::string, ValueType> &dict) {
58 auto end = dict.end();
59 size_t max_len = 0;
60
61 for (auto pos = dict.begin(); pos != end; ++pos) {
62 size_t len = pos->first.size();
63 if (max_len < len)
64 max_len = len;
65 }
66 return max_len;
67}
68
69class CommandObject : public std::enable_shared_from_this<CommandObject> {
70public:
71 typedef llvm::StringRef(ArgumentHelpCallbackFunction)();
72
76
77 llvm::StringRef operator()() const { return (*help_callback)(); }
78
79 explicit operator bool() const { return (help_callback != nullptr); }
80 };
81
82 /// Entries in the main argument information table.
85 const char *arg_name;
89 const char *help_text;
90 };
91
92 /// Used to build individual command argument lists.
96 /// This arg might be associated only with some particular option set(s). By
97 /// default the arg associates to all option sets.
99
102 uint32_t opt_set = LLDB_OPT_SET_ALL)
103 : arg_type(type), arg_repetition(repetition),
104 arg_opt_set_association(opt_set) {}
105 };
106
107 typedef std::vector<CommandArgumentData>
108 CommandArgumentEntry; // Used to build individual command argument lists
109
110 typedef std::map<std::string, lldb::CommandObjectSP> CommandMap;
111
112 CommandObject(CommandInterpreter &interpreter, llvm::StringRef name,
113 llvm::StringRef help = "", llvm::StringRef syntax = "",
114 uint32_t flags = 0);
115
116 virtual ~CommandObject() = default;
117
118 static const char *
120
121 static const char *
123
126
127 virtual llvm::StringRef GetHelp();
128
129 virtual llvm::StringRef GetHelpLong();
130
131 virtual llvm::StringRef GetSyntax();
132
133 llvm::StringRef GetCommandName() const;
134
135 virtual void SetHelp(llvm::StringRef str);
136
137 virtual void SetHelpLong(llvm::StringRef str);
138
139 void SetSyntax(llvm::StringRef str);
140
141 // override this to return true if you want to enable the user to delete the
142 // Command object from the Command dictionary (aliases have their own
143 // deletion scheme, so they do not need to care about this)
144 virtual bool IsRemovable() const { return false; }
145
146 virtual bool IsMultiwordObject() { return false; }
147
149
150 void SetIsUserCommand(bool is_user) { m_is_user_command = is_user; }
151
152 virtual CommandObjectMultiword *GetAsMultiwordCommand() { return nullptr; }
153
154 virtual bool IsAlias() { return false; }
155
156 // override this to return true if your command is somehow a "dash-dash" form
157 // of some other command (e.g. po is expr -O --); this is a powerful hint to
158 // the help system that one cannot pass options to this command
159 virtual bool IsDashDashCommand() { return false; }
160
161 virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd,
162 StringList *matches = nullptr) {
163 return lldb::CommandObjectSP();
164 }
165
166 virtual lldb::CommandObjectSP GetSubcommandSPExact(llvm::StringRef sub_cmd) {
167 return lldb::CommandObjectSP();
168 }
169
170 virtual CommandObject *GetSubcommandObject(llvm::StringRef sub_cmd,
171 StringList *matches = nullptr) {
172 return nullptr;
173 }
174
175 void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help);
176
178
179 virtual void GenerateHelpText(Stream &result);
180
181 // this is needed in order to allow the SBCommand class to transparently try
182 // and load subcommands - it will fail on anything but a multiword command,
183 // but it avoids us doing type checkings and casts
184 virtual bool LoadSubCommand(llvm::StringRef cmd_name,
185 const lldb::CommandObjectSP &command_obj) {
186 return false;
187 }
188
189 virtual llvm::Error LoadUserSubcommand(llvm::StringRef cmd_name,
190 const lldb::CommandObjectSP &command_obj,
191 bool can_replace) {
192 return llvm::createStringError(llvm::inconvertibleErrorCode(),
193 "can only add commands to container commands");
194 }
195
196 virtual bool WantsRawCommandString() = 0;
197
198 // By default, WantsCompletion = !WantsRawCommandString. Subclasses who want
199 // raw command string but desire, for example, argument completion should
200 // override this method to return true.
201 virtual bool WantsCompletion() { return !WantsRawCommandString(); }
202
203 virtual Options *GetOptions();
204
205 static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name);
206
207 static const ArgumentTableEntry *
209
210 // Sets the argument list for this command to one homogenous argument type,
211 // with the repeat specified.
214 ArgumentRepetitionType repetition_type = eArgRepeatPlain);
215
216 // Helper function to set BP IDs or ID ranges as the command argument data
217 // for this command.
218 // This used to just populate an entry you could add to, but that was never
219 // used. If we ever need that we can take optional extra args here.
220 // Use this to define a simple argument list:
222 void AddIDsArgumentData(IDType type);
223
225
227
228 static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type,
229 CommandInterpreter &interpreter);
230
231 static const char *GetArgumentName(lldb::CommandArgumentType arg_type);
232
233 // Generates a nicely formatted command args string for help command output.
234 // By default, all possible args are taken into account, for example, '<expr
235 // | variable-name>'. This can be refined by passing a second arg specifying
236 // which option set(s) we are interested, which could then, for example,
237 // produce either '<expr>' or '<variable-name>'.
239 uint32_t opt_set_mask = LLDB_OPT_SET_ALL);
240
241 static bool IsPairType(ArgumentRepetitionType arg_repeat_type);
242
243 static std::optional<ArgumentRepetitionType>
244 ArgRepetitionFromString(llvm::StringRef string);
245
246 bool ParseOptions(Args &args, CommandReturnObject &result);
247
248 void SetCommandName(llvm::StringRef name);
249
250 /// This default version handles calling option argument completions and then
251 /// calls HandleArgumentCompletion if the cursor is on an argument, not an
252 /// option. Don't override this method, override HandleArgumentCompletion
253 /// instead unless you have special reasons.
254 ///
255 /// \param[in,out] request
256 /// The completion request that needs to be answered.
257 virtual void HandleCompletion(CompletionRequest &request);
258
259 /// The default version handles argument definitions that have only one
260 /// argument type, and use one of the argument types that have an entry in
261 /// the CommonCompletions. Override this if you have a more complex
262 /// argument setup.
263 /// FIXME: we should be able to extend this to more complex argument
264 /// definitions provided we have completers for all the argument types.
265 ///
266 /// The input array contains a parsed version of the line.
267 ///
268 /// We've constructed the map of options and their arguments as well if that
269 /// is helpful for the completion.
270 ///
271 /// \param[in,out] request
272 /// The completion request that needs to be answered.
273 virtual void
275 OptionElementVector &opt_element_vector);
276
277 bool HelpTextContainsWord(llvm::StringRef search_word,
278 bool search_short_help = true,
279 bool search_long_help = true,
280 bool search_syntax = true,
281 bool search_options = true);
282
283 /// The flags accessor.
284 ///
285 /// \return
286 /// A reference to the Flags member variable.
287 Flags &GetFlags() { return m_flags; }
288
289 /// The flags const accessor.
290 ///
291 /// \return
292 /// A const reference to the Flags member variable.
293 const Flags &GetFlags() const { return m_flags; }
294
295 /// Get the command that appropriate for a "repeat" of the current command.
296 ///
297 /// \param[in] current_command_args
298 /// The command arguments.
299 ///
300 /// \return
301 /// std::nullopt if there is no special repeat command - it will use the
302 /// current command line.
303 /// Otherwise a std::string containing the command to be repeated.
304 /// If the string is empty, the command won't be allow repeating.
305 virtual std::optional<std::string>
306 GetRepeatCommand(Args &current_command_args, uint32_t index) {
307 return std::nullopt;
308 }
309
310 bool HasOverrideCallback() const {
313 }
314
316 void *baton) {
319 }
320
321 void
323 void *baton) {
326 }
327
328 bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) {
331 result);
334 argv);
335 else
336 return false;
337 }
338
339 virtual void Execute(const char *args_string,
340 CommandReturnObject &result) = 0;
341
342protected:
344 OptionGroupOptions &group_options,
345 ExecutionContext &exe_ctx);
346
347 virtual const char *GetInvalidTargetDescription() {
348 return "invalid target, create a target using the 'target create' command";
349 }
350
351 virtual const char *GetInvalidProcessDescription() {
352 return "Command requires a current process.";
353 }
354
355 virtual const char *GetInvalidThreadDescription() {
356 return "Command requires a process which is currently stopped.";
357 }
358
359 virtual const char *GetInvalidFrameDescription() {
360 return "Command requires a process, which is currently stopped.";
361 }
362
363 virtual const char *GetInvalidRegContextDescription() {
364 return "invalid frame, no registers, command requires a process which is "
365 "currently stopped.";
366 }
367
368 // This is for use in the command interpreter, when you either want the
369 // selected target, or if no target is present you want to prime the dummy
370 // target with entities that will be copied over to new targets.
371 Target &GetSelectedOrDummyTarget(bool prefer_dummy = false);
374
375 // If a command needs to use the "current" thread, use this call. Command
376 // objects will have an ExecutionContext to use, and that may or may not have
377 // a thread in it. If it does, you should use that by default, if not, then
378 // use the ExecutionContext's target's selected thread, etc... This call
379 // insulates you from the details of this calculation.
381
382 /// Check the command to make sure anything required by this
383 /// command is available.
384 ///
385 /// \param[out] result
386 /// A command result object, if it is not okay to run the command
387 /// this will be filled in with a suitable error.
388 ///
389 /// \return
390 /// \b true if it is okay to run this command, \b false otherwise.
392
393 void Cleanup();
394
397 std::unique_lock<std::recursive_mutex> m_api_locker;
398 std::string m_cmd_name;
399 std::string m_cmd_help_short;
400 std::string m_cmd_help_long;
401 std::string m_cmd_syntax;
403 std::vector<CommandArgumentEntry> m_arguments;
407 bool m_is_user_command = false;
408};
409
411public:
412 CommandObjectParsed(CommandInterpreter &interpreter, const char *name,
413 const char *help = nullptr, const char *syntax = nullptr,
414 uint32_t flags = 0)
415 : CommandObject(interpreter, name, help, syntax, flags) {}
416
417 ~CommandObjectParsed() override = default;
418
419 void Execute(const char *args_string, CommandReturnObject &result) override;
420
421protected:
422 virtual void DoExecute(Args &command, CommandReturnObject &result) = 0;
423
424 bool WantsRawCommandString() override { return false; }
425};
426
428public:
429 CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name,
430 llvm::StringRef help = "", llvm::StringRef syntax = "",
431 uint32_t flags = 0)
432 : CommandObject(interpreter, name, help, syntax, flags) {}
433
434 ~CommandObjectRaw() override = default;
435
436 void Execute(const char *args_string, CommandReturnObject &result) override;
437
438protected:
439 virtual void DoExecute(llvm::StringRef command,
440 CommandReturnObject &result) = 0;
441
442 bool WantsRawCommandString() override { return true; }
443};
444
445} // namespace lldb_private
446
447#endif // LLDB_INTERPRETER_COMMANDOBJECT_H
A command line argument class.
Definition: Args.h:33
virtual void DoExecute(Args &command, CommandReturnObject &result)=0
void Execute(const char *args_string, CommandReturnObject &result) override
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
~CommandObjectParsed() override=default
bool WantsRawCommandString() override
~CommandObjectRaw() override=default
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
void Execute(const char *args_string, CommandReturnObject &result) override
virtual void DoExecute(llvm::StringRef command, CommandReturnObject &result)=0
std::vector< CommandArgumentData > CommandArgumentEntry
CommandArgumentEntry * GetArgumentEntryAtIndex(int idx)
virtual void SetHelpLong(llvm::StringRef str)
virtual bool WantsRawCommandString()=0
void GenerateHelpText(CommandReturnObject &result)
lldb::CommandOverrideCallback m_deprecated_command_override_callback
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
std::unique_lock< std::recursive_mutex > m_api_locker
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
virtual const char * GetInvalidProcessDescription()
virtual llvm::StringRef GetHelpLong()
const Flags & GetFlags() const
The flags const accessor.
llvm::StringRef() ArgumentHelpCallbackFunction()
Definition: CommandObject.h:71
static const ArgumentTableEntry * FindArgumentDataByType(lldb::CommandArgumentType arg_type)
virtual lldb::CommandObjectSP GetSubcommandSPExact(llvm::StringRef sub_cmd)
llvm::StringRef GetCommandName() const
void SetIsUserCommand(bool is_user)
static std::optional< ArgumentRepetitionType > ArgRepetitionFromString(llvm::StringRef string)
static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name)
void GetFormattedCommandArguments(Stream &str, uint32_t opt_set_mask=LLDB_OPT_SET_ALL)
bool HelpTextContainsWord(llvm::StringRef search_word, bool search_short_help=true, bool search_long_help=true, bool search_syntax=true, bool search_options=true)
virtual bool IsMultiwordObject()
ExecutionContext m_exe_ctx
virtual const char * GetInvalidTargetDescription()
std::vector< CommandArgumentEntry > m_arguments
virtual bool WantsCompletion()
lldb_private::CommandOverrideCallbackWithResult m_command_override_callback
void AddIDsArgumentData(IDType type)
CommandInterpreter & GetCommandInterpreter()
virtual bool IsDashDashCommand()
static const char * GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type)
virtual void Execute(const char *args_string, CommandReturnObject &result)=0
CommandInterpreter & m_interpreter
virtual const char * GetInvalidRegContextDescription()
virtual bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj)
virtual std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index)
Get the command that appropriate for a "repeat" of the current command.
virtual CommandObject * GetSubcommandObject(llvm::StringRef sub_cmd, StringList *matches=nullptr)
void SetOverrideCallback(lldb::CommandOverrideCallback callback, void *baton)
virtual CommandObjectMultiword * GetAsMultiwordCommand()
virtual Options * GetOptions()
void SetSyntax(llvm::StringRef str)
static const char * GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type)
virtual llvm::Error LoadUserSubcommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj, bool can_replace)
virtual const char * GetInvalidFrameDescription()
virtual ~CommandObject()=default
void SetCommandName(llvm::StringRef name)
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,...
bool ParseOptions(Args &args, CommandReturnObject &result)
void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help)
virtual llvm::StringRef GetSyntax()
virtual const char * GetInvalidThreadDescription()
static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type, CommandInterpreter &interpreter)
void SetOverrideCallback(lldb_private::CommandOverrideCallbackWithResult callback, void *baton)
virtual bool IsRemovable() const
bool CheckRequirements(CommandReturnObject &result)
Check the command to make sure anything required by this command is available.
virtual void HandleCompletion(CompletionRequest &request)
This default version handles calling option argument completions and then calls HandleArgumentComplet...
static bool IsPairType(ArgumentRepetitionType arg_repeat_type)
Target & GetSelectedOrDummyTarget(bool prefer_dummy=false)
std::map< std::string, lldb::CommandObjectSP > CommandMap
static const char * GetArgumentName(lldb::CommandArgumentType arg_type)
virtual llvm::StringRef GetHelp()
bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result)
virtual void SetHelp(llvm::StringRef str)
virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd, StringList *matches=nullptr)
"lldb/Utility/ArgCompletionRequest.h"
A class to manage flag bits.
Definition: Debugger.h:80
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A class to manage flags.
Definition: Flags.h:22
A command line option parsing protocol class.
Definition: Options.h:58
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
void AppendString(const std::string &s)
Definition: StringList.cpp:43
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:110
A class that represents a running process on the host machine.
int AddNamesMatchingPartialString(const std::map< std::string, ValueType > &in_map, llvm::StringRef cmd_str, StringList &matches, StringList *descriptions=nullptr)
Definition: CommandObject.h:37
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
bool(* CommandOverrideCallbackWithResult)(void *baton, const char **argv, lldb_private::CommandReturnObject &result)
size_t FindLongestCommandWord(std::map< std::string, ValueType > &dict)
Definition: CommandObject.h:57
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
Definition: lldb-forward.h:328
bool(* CommandOverrideCallback)(void *baton, const char **argv)
Definition: lldb-types.h:74
ArgumentHelpCallbackFunction * help_callback
Definition: CommandObject.h:74
Entries in the main argument information table.
Definition: CommandObject.h:83
Used to build individual command argument lists.
Definition: CommandObject.h:93
CommandArgumentData(lldb::CommandArgumentType type=lldb::eArgTypeNone, ArgumentRepetitionType repetition=eArgRepeatPlain, uint32_t opt_set=LLDB_OPT_SET_ALL)
uint32_t arg_opt_set_association
This arg might be associated only with some particular option set(s).
Definition: CommandObject.h:98