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