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, std::less<>> &in_map,
39 llvm::StringRef cmd_str, StringList &matches,
40 StringList *descriptions = nullptr) {
41 int number_added = 0;
42
43 const bool add_all = cmd_str.empty();
44
45 for (auto iter = in_map.begin(), end = in_map.end(); iter != end; iter++) {
46 if (add_all || (iter->first.find(std::string(cmd_str), 0) == 0)) {
47 ++number_added;
48 matches.AppendString(iter->first.c_str());
49 if (descriptions)
50 descriptions->AppendString(iter->second->GetHelp());
51 }
52 }
53
54 return number_added;
55}
56
57template <typename ValueType>
58size_t
59FindLongestCommandWord(std::map<std::string, ValueType, std::less<>> &dict) {
60 auto end = dict.end();
61 size_t max_len = 0;
62
63 for (auto pos = dict.begin(); pos != end; ++pos) {
64 size_t len = pos->first.size();
65 if (max_len < len)
66 max_len = len;
67 }
68 return max_len;
69}
70
71class CommandObject : public std::enable_shared_from_this<CommandObject> {
72public:
73 typedef llvm::StringRef(ArgumentHelpCallbackFunction)();
74
78
79 llvm::StringRef operator()() const { return (*help_callback)(); }
80
81 explicit operator bool() const { return (help_callback != nullptr); }
82 };
83
84 /// Entries in the main argument information table.
87 const char *arg_name;
91 const char *help_text;
92 };
93
94 /// Used to build individual command argument lists.
98 /// This arg might be associated only with some particular option set(s). By
99 /// default the arg associates to all option sets.
101
104 uint32_t opt_set = LLDB_OPT_SET_ALL)
105 : arg_type(type), arg_repetition(repetition),
106 arg_opt_set_association(opt_set) {}
107 };
108
109 typedef std::vector<CommandArgumentData>
110 CommandArgumentEntry; // Used to build individual command argument lists
111
112 typedef std::map<std::string, lldb::CommandObjectSP, std::less<>> CommandMap;
113
114 CommandObject(CommandInterpreter &interpreter, llvm::StringRef name,
115 llvm::StringRef help = "", llvm::StringRef syntax = "",
116 uint32_t flags = 0);
117
118 virtual ~CommandObject() = default;
119
120 static const char *
122
123 static const char *
125
128
129 virtual llvm::StringRef GetHelp();
130
131 virtual llvm::StringRef GetHelpLong();
132
133 virtual llvm::StringRef GetSyntax();
134
135 llvm::StringRef GetCommandName() const;
136
137 virtual void SetHelp(llvm::StringRef str);
138
139 virtual void SetHelpLong(llvm::StringRef str);
140
141 void SetSyntax(llvm::StringRef str);
142
143 // override this to return true if you want to enable the user to delete the
144 // Command object from the Command dictionary (aliases have their own
145 // deletion scheme, so they do not need to care about this)
146 virtual bool IsRemovable() const { return false; }
147
148 virtual bool IsMultiwordObject() { return false; }
149
151
152 void SetIsUserCommand(bool is_user) { m_is_user_command = is_user; }
153
154 virtual CommandObjectMultiword *GetAsMultiwordCommand() { return nullptr; }
155
156 virtual bool IsAlias() { return false; }
157
158 // override this to return true if your command is somehow a "dash-dash" form
159 // of some other command (e.g. po is expr -O --); this is a powerful hint to
160 // the help system that one cannot pass options to this command
161 virtual bool IsDashDashCommand() { return false; }
162
163 virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd,
164 StringList *matches = nullptr) {
165 return lldb::CommandObjectSP();
166 }
167
168 virtual lldb::CommandObjectSP GetSubcommandSPExact(llvm::StringRef sub_cmd) {
169 return lldb::CommandObjectSP();
170 }
171
172 virtual CommandObject *GetSubcommandObject(llvm::StringRef sub_cmd,
173 StringList *matches = nullptr) {
174 return nullptr;
175 }
176
177 void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help);
178
180
181 virtual void GenerateHelpText(Stream &result);
182
183 // this is needed in order to allow the SBCommand class to transparently try
184 // and load subcommands - it will fail on anything but a multiword command,
185 // but it avoids us doing type checkings and casts
186 virtual bool LoadSubCommand(llvm::StringRef cmd_name,
187 const lldb::CommandObjectSP &command_obj) {
188 return false;
189 }
190
191 virtual llvm::Error LoadUserSubcommand(llvm::StringRef cmd_name,
192 const lldb::CommandObjectSP &command_obj,
193 bool can_replace) {
194 return llvm::createStringError(llvm::inconvertibleErrorCode(),
195 "can only add commands to container commands");
196 }
197
198 virtual bool WantsRawCommandString() = 0;
199
200 // By default, WantsCompletion = !WantsRawCommandString. Subclasses who want
201 // raw command string but desire, for example, argument completion should
202 // override this method to return true.
203 virtual bool WantsCompletion() { return !WantsRawCommandString(); }
204
205 virtual Options *GetOptions();
206
207 static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name);
208
209 static const ArgumentTableEntry *
211
212 // Sets the argument list for this command to one homogenous argument type,
213 // with the repeat specified.
216 ArgumentRepetitionType repetition_type = eArgRepeatPlain);
217
218 // Helper function to set BP IDs or ID ranges as the command argument data
219 // for this command.
220 // This used to just populate an entry you could add to, but that was never
221 // used. If we ever need that we can take optional extra args here.
222 // Use this to define a simple argument list:
224 void AddIDsArgumentData(IDType type);
225
227
229
230 static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type,
231 CommandInterpreter &interpreter);
232
233 static const char *GetArgumentName(lldb::CommandArgumentType arg_type);
234
235 // Generates a nicely formatted command args string for help command output.
236 // By default, all possible args are taken into account, for example, '<expr
237 // | variable-name>'. This can be refined by passing a second arg specifying
238 // which option set(s) we are interested, which could then, for example,
239 // produce either '<expr>' or '<variable-name>'.
241 uint32_t opt_set_mask = LLDB_OPT_SET_ALL);
242
243 static bool IsPairType(ArgumentRepetitionType arg_repeat_type);
244
245 static std::optional<ArgumentRepetitionType>
246 ArgRepetitionFromString(llvm::StringRef string);
247
248 bool ParseOptions(Args &args, CommandReturnObject &result);
249
250 void SetCommandName(llvm::StringRef name);
251
252 /// This default version handles calling option argument completions and then
253 /// calls HandleArgumentCompletion if the cursor is on an argument, not an
254 /// option. Don't override this method, override HandleArgumentCompletion
255 /// instead unless you have special reasons.
256 ///
257 /// \param[in,out] request
258 /// The completion request that needs to be answered.
259 virtual void HandleCompletion(CompletionRequest &request);
260
261 /// The default version handles argument definitions that have only one
262 /// argument type, and use one of the argument types that have an entry in
263 /// the CommonCompletions. Override this if you have a more complex
264 /// argument setup.
265 /// FIXME: we should be able to extend this to more complex argument
266 /// definitions provided we have completers for all the argument types.
267 ///
268 /// The input array contains a parsed version of the line.
269 ///
270 /// We've constructed the map of options and their arguments as well if that
271 /// is helpful for the completion.
272 ///
273 /// \param[in,out] request
274 /// The completion request that needs to be answered.
275 virtual void
277 OptionElementVector &opt_element_vector);
278
279 bool HelpTextContainsWord(llvm::StringRef search_word,
280 bool search_short_help = true,
281 bool search_long_help = true,
282 bool search_syntax = true,
283 bool search_options = true);
284
285 /// The flags accessor.
286 ///
287 /// \return
288 /// A reference to the Flags member variable.
289 Flags &GetFlags() { return m_flags; }
290
291 /// The flags const accessor.
292 ///
293 /// \return
294 /// A const reference to the Flags member variable.
295 const Flags &GetFlags() const { return m_flags; }
296
297 /// Get the command that appropriate for a "repeat" of the current command.
298 ///
299 /// \param[in] current_command_args
300 /// The command arguments.
301 ///
302 /// \param[in] index
303 /// This is for internal use - it is how the completion request is tracked
304 /// in CommandObjectMultiword, and should otherwise be ignored.
305 ///
306 /// \return
307 /// std::nullopt if there is no special repeat command - it will use the
308 /// current command line.
309 /// Otherwise a std::string containing the command to be repeated.
310 /// If the string is empty, the command won't be allow repeating.
311 virtual std::optional<std::string>
312 GetRepeatCommand(Args &current_command_args, uint32_t index) {
313 return std::nullopt;
314 }
315
316 bool HasOverrideCallback() const {
319 }
320
322 void *baton) {
325 }
326
327 void
329 void *baton) {
332 }
333
334 bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) {
337 result);
340 argv);
341 else
342 return false;
343 }
344
345 /// Set the command input as it appeared in the terminal. This
346 /// is used to have errors refer directly to the original command.
347 void SetOriginalCommandString(std::string s) { m_original_command = s; }
348
349 /// \param offset_in_command is on what column \c args_string
350 /// appears, if applicable. This enables diagnostics that refer back
351 /// to the user input.
352 virtual void Execute(const char *args_string,
353 CommandReturnObject &result) = 0;
354
355protected:
357 OptionGroupOptions &group_options,
358 ExecutionContext &exe_ctx);
359
360 virtual const char *GetInvalidTargetDescription() {
361 return "invalid target, create a target using the 'target create' command";
362 }
363
364 virtual const char *GetInvalidProcessDescription() {
365 return "Command requires a current process.";
366 }
367
368 virtual const char *GetInvalidThreadDescription() {
369 return "Command requires a process which is currently stopped.";
370 }
371
372 virtual const char *GetInvalidFrameDescription() {
373 return "Command requires a process, which is currently stopped.";
374 }
375
376 virtual const char *GetInvalidRegContextDescription() {
377 return "invalid frame, no registers, command requires a process which is "
378 "currently stopped.";
379 }
380
382
383 // This is for use in the command interpreter, and returns the most relevant
384 // target. In order of priority, that's the target from the command object's
385 // execution context, the target from the interpreter's execution context, the
386 // selected target or the dummy target.
387 Target &GetTarget();
388
389 // If a command needs to use the "current" thread, use this call. Command
390 // objects will have an ExecutionContext to use, and that may or may not have
391 // a thread in it. If it does, you should use that by default, if not, then
392 // use the ExecutionContext's target's selected thread, etc... This call
393 // insulates you from the details of this calculation.
395
396 /// Check the command to make sure anything required by this
397 /// command is available.
398 ///
399 /// \param[out] result
400 /// A command result object, if it is not okay to run the command
401 /// this will be filled in with a suitable error.
402 ///
403 /// \return
404 /// \b true if it is okay to run this command, \b false otherwise.
406
407 void Cleanup();
408
411 std::unique_lock<std::recursive_mutex> m_api_locker;
412 std::string m_cmd_name;
413 std::string m_cmd_help_short;
414 std::string m_cmd_help_long;
415 std::string m_cmd_syntax;
418 std::vector<CommandArgumentEntry> m_arguments;
422 bool m_is_user_command = false;
423};
424
426public:
427 CommandObjectParsed(CommandInterpreter &interpreter, const char *name,
428 const char *help = nullptr, const char *syntax = nullptr,
429 uint32_t flags = 0)
430 : CommandObject(interpreter, name, help, syntax, flags) {}
431
432 ~CommandObjectParsed() override = default;
433
434 void Execute(const char *args_string, CommandReturnObject &result) override;
435
436protected:
437 virtual void DoExecute(Args &command, CommandReturnObject &result) = 0;
438
439 bool WantsRawCommandString() override { return false; }
440};
441
443public:
444 CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name,
445 llvm::StringRef help = "", llvm::StringRef syntax = "",
446 uint32_t flags = 0)
447 : CommandObject(interpreter, name, help, syntax, flags) {}
448
449 ~CommandObjectRaw() override = default;
450
451 void Execute(const char *args_string, CommandReturnObject &result) override;
452
453protected:
454 virtual void DoExecute(llvm::StringRef command,
455 CommandReturnObject &result) = 0;
456
457 bool WantsRawCommandString() override { return true; }
458};
459
460} // namespace lldb_private
461
462#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 SetOriginalCommandString(std::string s)
Set the command input as it appeared in the terminal.
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:73
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
std::map< std::string, lldb::CommandObjectSP, std::less<> > CommandMap
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)
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.
size_t FindLongestCommandWord(std::map< std::string, ValueType, std::less<> > &dict)
Definition: CommandObject.h:59
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
int AddNamesMatchingPartialString(const std::map< std::string, ValueType, std::less<> > &in_map, llvm::StringRef cmd_str, StringList &matches, StringList *descriptions=nullptr)
Definition: CommandObject.h:37
bool(* CommandOverrideCallbackWithResult)(void *baton, const char **argv, lldb_private::CommandReturnObject &result)
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
Definition: lldb-forward.h:333
bool(* CommandOverrideCallback)(void *baton, const char **argv)
Definition: lldb-types.h:74
ArgumentHelpCallbackFunction * help_callback
Definition: CommandObject.h:76
Entries in the main argument information table.
Definition: CommandObject.h:85
Used to build individual command argument lists.
Definition: CommandObject.h:95
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).