xref: /freebsd/contrib/llvm-project/lldb/include/lldb/Interpreter/CommandObject.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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 
20 #include "lldb/Interpreter/CommandCompletions.h"
21 #include "lldb/Interpreter/Options.h"
22 #include "lldb/Target/ExecutionContext.h"
23 #include "lldb/Utility/Args.h"
24 #include "lldb/Utility/CompletionRequest.h"
25 #include "lldb/Utility/StringList.h"
26 #include "lldb/lldb-private.h"
27 
28 namespace 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 
36 template <typename ValueType>
37 int AddNamesMatchingPartialString(
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 
56 template <typename ValueType>
57 size_t
FindLongestCommandWord(std::map<std::string,ValueType,std::less<>> & dict)58 FindLongestCommandWord(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 
70 class CommandObject : public std::enable_shared_from_this<CommandObject> {
71 public:
72   typedef llvm::StringRef(ArgumentHelpCallbackFunction)();
73 
74   struct ArgumentHelpCallback {
75     ArgumentHelpCallbackFunction *help_callback;
76     bool self_formatting;
77 
operatorArgumentHelpCallback78     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.
84   struct ArgumentTableEntry {
85     lldb::CommandArgumentType arg_type;
86     const char *arg_name;
87     lldb::CompletionType completion_type;
88     OptionEnumValues enum_values;
89     ArgumentHelpCallback help_function;
90     const char *help_text;
91   };
92 
93   /// Used to build individual command argument lists.
94   struct CommandArgumentData {
95     lldb::CommandArgumentType arg_type;
96     ArgumentRepetitionType arg_repetition;
97     /// This arg might be associated only with some particular option set(s). By
98     /// default the arg associates to all option sets.
99     uint32_t arg_opt_set_association;
100 
101     CommandArgumentData(lldb::CommandArgumentType type = lldb::eArgTypeNone,
102                         ArgumentRepetitionType repetition = eArgRepeatPlain,
103                         uint32_t opt_set = LLDB_OPT_SET_ALL)
arg_typeCommandArgumentData104         : arg_type(type), arg_repetition(repetition),
105           arg_opt_set_association(opt_set) {}
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 *
120   GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type);
121 
122   static const char *
123   GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type);
124 
GetCommandInterpreter()125   CommandInterpreter &GetCommandInterpreter() { return m_interpreter; }
126   Debugger &GetDebugger();
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)
IsRemovable()145   virtual bool IsRemovable() const { return false; }
146 
IsMultiwordObject()147   virtual bool IsMultiwordObject() { return false; }
148 
IsUserCommand()149   bool IsUserCommand() { return m_is_user_command; }
150 
SetIsUserCommand(bool is_user)151   void SetIsUserCommand(bool is_user) { m_is_user_command = is_user; }
152 
GetAsMultiwordCommand()153   virtual CommandObjectMultiword *GetAsMultiwordCommand() { return nullptr; }
154 
IsAlias()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
IsDashDashCommand()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 
GetSubcommandSPExact(llvm::StringRef sub_cmd)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 
178   void GenerateHelpText(CommandReturnObject &result);
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
LoadSubCommand(llvm::StringRef cmd_name,const lldb::CommandObjectSP & command_obj)185   virtual bool LoadSubCommand(llvm::StringRef cmd_name,
186                               const lldb::CommandObjectSP &command_obj) {
187     return false;
188   }
189 
LoadUserSubcommand(llvm::StringRef cmd_name,const lldb::CommandObjectSP & command_obj,bool can_replace)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.
WantsCompletion()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 *
209   FindArgumentDataByType(lldb::CommandArgumentType arg_type);
210 
211   // Sets the argument list for this command to one homogenous argument type,
212   // with the repeat specified.
213   void AddSimpleArgumentList(
214       lldb::CommandArgumentType arg_type,
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:
222   enum IDType { eBreakpointArgs = 0, eWatchpointArgs = 1 };
223   void AddIDsArgumentData(IDType type);
224 
225   int GetNumArgumentEntries();
226 
227   CommandArgumentEntry *GetArgumentEntryAtIndex(int idx);
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>'.
239   void GetFormattedCommandArguments(Stream &str,
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
275   HandleArgumentCompletion(CompletionRequest &request,
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.
GetFlags()288   Flags &GetFlags() { return m_flags; }
289 
290   /// The flags const accessor.
291   ///
292   /// \return
293   ///     A const reference to the Flags member variable.
GetFlags()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>
GetRepeatCommand(Args & current_command_args,uint32_t index)311   GetRepeatCommand(Args &current_command_args, uint32_t index) {
312     return std::nullopt;
313   }
314 
HasOverrideCallback()315   bool HasOverrideCallback() const {
316     return m_command_override_callback ||
317            m_deprecated_command_override_callback;
318   }
319 
SetOverrideCallback(lldb::CommandOverrideCallback callback,void * baton)320   void SetOverrideCallback(lldb::CommandOverrideCallback callback,
321                            void *baton) {
322     m_deprecated_command_override_callback = callback;
323     m_command_override_baton = baton;
324   }
325 
326   void
SetOverrideCallback(lldb_private::CommandOverrideCallbackWithResult callback,void * baton)327   SetOverrideCallback(lldb_private::CommandOverrideCallbackWithResult callback,
328                       void *baton) {
329     m_command_override_callback = callback;
330     m_command_override_baton = baton;
331   }
332 
InvokeOverrideCallback(const char ** argv,CommandReturnObject & result)333   bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) {
334     if (m_command_override_callback)
335       return m_command_override_callback(m_command_override_baton, argv,
336                                          result);
337     else if (m_deprecated_command_override_callback)
338       return m_deprecated_command_override_callback(m_command_override_baton,
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.
SetOriginalCommandString(std::string s)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 
354 protected:
355   bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result,
356                              OptionGroupOptions &group_options,
357                              ExecutionContext &exe_ctx);
358 
GetInvalidTargetDescription()359   virtual const char *GetInvalidTargetDescription() {
360     return "invalid target, create a target using the 'target create' command";
361   }
362 
GetInvalidProcessDescription()363   virtual const char *GetInvalidProcessDescription() {
364     return "Command requires a current process.";
365   }
366 
GetInvalidThreadDescription()367   virtual const char *GetInvalidThreadDescription() {
368     return "Command requires a process which is currently stopped.";
369   }
370 
GetInvalidFrameDescription()371   virtual const char *GetInvalidFrameDescription() {
372     return "Command requires a process, which is currently stopped.";
373   }
374 
GetInvalidRegContextDescription()375   virtual const char *GetInvalidRegContextDescription() {
376     return "invalid frame, no registers, command requires a process which is "
377            "currently stopped.";
378   }
379 
380   Target &GetDummyTarget();
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.
393   Thread *GetDefaultThread();
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.
404   bool CheckRequirements(CommandReturnObject &result);
405 
406   void Cleanup();
407 
408   CommandInterpreter &m_interpreter;
409   ExecutionContext m_exe_ctx;
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;
415   std::string m_original_command;
416   Flags m_flags;
417   std::vector<CommandArgumentEntry> m_arguments;
418   lldb::CommandOverrideCallback m_deprecated_command_override_callback;
419   lldb_private::CommandOverrideCallbackWithResult m_command_override_callback;
420   void *m_command_override_baton;
421   bool m_is_user_command = false;
422 };
423 
424 class CommandObjectParsed : public CommandObject {
425 public:
426   CommandObjectParsed(CommandInterpreter &interpreter, const char *name,
427                       const char *help = nullptr, const char *syntax = nullptr,
428                       uint32_t flags = 0)
CommandObject(interpreter,name,help,syntax,flags)429       : CommandObject(interpreter, name, help, syntax, flags) {}
430 
431   ~CommandObjectParsed() override = default;
432 
433   void Execute(const char *args_string, CommandReturnObject &result) override;
434 
435 protected:
436   virtual void DoExecute(Args &command, CommandReturnObject &result) = 0;
437 
WantsRawCommandString()438   bool WantsRawCommandString() override { return false; }
439 };
440 
441 class CommandObjectRaw : public CommandObject {
442 public:
443   CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name,
444     llvm::StringRef help = "", llvm::StringRef syntax = "",
445                    uint32_t flags = 0)
CommandObject(interpreter,name,help,syntax,flags)446       : CommandObject(interpreter, name, help, syntax, flags) {}
447 
448   ~CommandObjectRaw() override = default;
449 
450   void Execute(const char *args_string, CommandReturnObject &result) override;
451 
452 protected:
453   virtual void DoExecute(llvm::StringRef command,
454                          CommandReturnObject &result) = 0;
455 
WantsRawCommandString()456   bool WantsRawCommandString() override { return true; }
457 };
458 
459 } // namespace lldb_private
460 
461 #endif // LLDB_INTERPRETER_COMMANDOBJECT_H
462