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