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
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>
37int AddNamesMatchingPartialString(
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
73 struct ArgumentHelpCallback {
74 ArgumentHelpCallbackFunction *help_callback;
75 bool self_formatting;
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.
83 struct ArgumentTableEntry {
84 lldb::CommandArgumentType arg_type;
85 const char *arg_name;
86 lldb::CompletionType completion_type;
87 OptionEnumValues enum_values;
88 ArgumentHelpCallback help_function;
89 const char *help_text;
90 };
91
92 /// Used to build individual command argument lists.
93 struct CommandArgumentData {
94 lldb::CommandArgumentType arg_type;
95 ArgumentRepetitionType arg_repetition;
96 /// This arg might be associated only with some particular option set(s). By
97 /// default the arg associates to all option sets.
98 uint32_t arg_opt_set_association;
99
100 CommandArgumentData(lldb::CommandArgumentType type = lldb::eArgTypeNone,
101 ArgumentRepetitionType repetition = eArgRepeatPlain,
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 *
119 GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type);
120
121 static const char *
122 GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type);
123
124 CommandInterpreter &GetCommandInterpreter() { return m_interpreter; }
125 Debugger &GetDebugger();
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
148 bool IsUserCommand() { return m_is_user_command; }
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
177 void GenerateHelpText(CommandReturnObject &result);
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(EC: llvm::inconvertibleErrorCode(),
193 Msg: "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 *
208 FindArgumentDataByType(lldb::CommandArgumentType arg_type);
209
210 int GetNumArgumentEntries();
211
212 CommandArgumentEntry *GetArgumentEntryAtIndex(int idx);
213
214 static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type,
215 CommandInterpreter &interpreter);
216
217 static const char *GetArgumentName(lldb::CommandArgumentType arg_type);
218
219 // Generates a nicely formatted command args string for help command output.
220 // By default, all possible args are taken into account, for example, '<expr
221 // | variable-name>'. This can be refined by passing a second arg specifying
222 // which option set(s) we are interested, which could then, for example,
223 // produce either '<expr>' or '<variable-name>'.
224 void GetFormattedCommandArguments(Stream &str,
225 uint32_t opt_set_mask = LLDB_OPT_SET_ALL);
226
227 static bool IsPairType(ArgumentRepetitionType arg_repeat_type);
228
229 static std::optional<ArgumentRepetitionType>
230 ArgRepetitionFromString(llvm::StringRef string);
231
232 bool ParseOptions(Args &args, CommandReturnObject &result);
233
234 void SetCommandName(llvm::StringRef name);
235
236 /// This default version handles calling option argument completions and then
237 /// calls HandleArgumentCompletion if the cursor is on an argument, not an
238 /// option. Don't override this method, override HandleArgumentCompletion
239 /// instead unless you have special reasons.
240 ///
241 /// \param[in,out] request
242 /// The completion request that needs to be answered.
243 virtual void HandleCompletion(CompletionRequest &request);
244
245 /// The input array contains a parsed version of the line.
246 ///
247 /// We've constructed the map of options and their arguments as well if that
248 /// is helpful for the completion.
249 ///
250 /// \param[in,out] request
251 /// The completion request that needs to be answered.
252 virtual void
253 HandleArgumentCompletion(CompletionRequest &request,
254 OptionElementVector &opt_element_vector) {}
255
256 bool HelpTextContainsWord(llvm::StringRef search_word,
257 bool search_short_help = true,
258 bool search_long_help = true,
259 bool search_syntax = true,
260 bool search_options = true);
261
262 /// The flags accessor.
263 ///
264 /// \return
265 /// A reference to the Flags member variable.
266 Flags &GetFlags() { return m_flags; }
267
268 /// The flags const accessor.
269 ///
270 /// \return
271 /// A const reference to the Flags member variable.
272 const Flags &GetFlags() const { return m_flags; }
273
274 /// Get the command that appropriate for a "repeat" of the current command.
275 ///
276 /// \param[in] current_command_args
277 /// The command arguments.
278 ///
279 /// \return
280 /// std::nullopt if there is no special repeat command - it will use the
281 /// current command line.
282 /// Otherwise a std::string containing the command to be repeated.
283 /// If the string is empty, the command won't be allow repeating.
284 virtual std::optional<std::string>
285 GetRepeatCommand(Args &current_command_args, uint32_t index) {
286 return std::nullopt;
287 }
288
289 bool HasOverrideCallback() const {
290 return m_command_override_callback ||
291 m_deprecated_command_override_callback;
292 }
293
294 void SetOverrideCallback(lldb::CommandOverrideCallback callback,
295 void *baton) {
296 m_deprecated_command_override_callback = callback;
297 m_command_override_baton = baton;
298 }
299
300 void
301 SetOverrideCallback(lldb_private::CommandOverrideCallbackWithResult callback,
302 void *baton) {
303 m_command_override_callback = callback;
304 m_command_override_baton = baton;
305 }
306
307 bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) {
308 if (m_command_override_callback)
309 return m_command_override_callback(m_command_override_baton, argv,
310 result);
311 else if (m_deprecated_command_override_callback)
312 return m_deprecated_command_override_callback(m_command_override_baton,
313 argv);
314 else
315 return false;
316 }
317
318 virtual void Execute(const char *args_string,
319 CommandReturnObject &result) = 0;
320
321protected:
322 bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result,
323 OptionGroupOptions &group_options,
324 ExecutionContext &exe_ctx);
325
326 virtual const char *GetInvalidTargetDescription() {
327 return "invalid target, create a target using the 'target create' command";
328 }
329
330 virtual const char *GetInvalidProcessDescription() {
331 return "Command requires a current process.";
332 }
333
334 virtual const char *GetInvalidThreadDescription() {
335 return "Command requires a process which is currently stopped.";
336 }
337
338 virtual const char *GetInvalidFrameDescription() {
339 return "Command requires a process, which is currently stopped.";
340 }
341
342 virtual const char *GetInvalidRegContextDescription() {
343 return "invalid frame, no registers, command requires a process which is "
344 "currently stopped.";
345 }
346
347 // This is for use in the command interpreter, when you either want the
348 // selected target, or if no target is present you want to prime the dummy
349 // target with entities that will be copied over to new targets.
350 Target &GetSelectedOrDummyTarget(bool prefer_dummy = false);
351 Target &GetSelectedTarget();
352 Target &GetDummyTarget();
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.
359 Thread *GetDefaultThread();
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.
370 bool CheckRequirements(CommandReturnObject &result);
371
372 void Cleanup();
373
374 CommandInterpreter &m_interpreter;
375 ExecutionContext m_exe_ctx;
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;
381 Flags m_flags;
382 std::vector<CommandArgumentEntry> m_arguments;
383 lldb::CommandOverrideCallback m_deprecated_command_override_callback;
384 lldb_private::CommandOverrideCallbackWithResult m_command_override_callback;
385 void *m_command_override_baton;
386 bool m_is_user_command = false;
387
388 // Helper function to populate IDs or ID ranges as the command argument data
389 // to the specified command argument entry.
390 static void AddIDsArgumentData(CommandArgumentEntry &arg,
391 lldb::CommandArgumentType ID,
392 lldb::CommandArgumentType IDRange);
393};
394
395class CommandObjectParsed : public CommandObject {
396public:
397 CommandObjectParsed(CommandInterpreter &interpreter, const char *name,
398 const char *help = nullptr, const char *syntax = nullptr,
399 uint32_t flags = 0)
400 : CommandObject(interpreter, name, help, syntax, flags) {}
401
402 ~CommandObjectParsed() override = default;
403
404 void Execute(const char *args_string, CommandReturnObject &result) override;
405
406protected:
407 virtual void DoExecute(Args &command, CommandReturnObject &result) = 0;
408
409 bool WantsRawCommandString() override { return false; }
410};
411
412class CommandObjectRaw : public CommandObject {
413public:
414 CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name,
415 llvm::StringRef help = "", llvm::StringRef syntax = "",
416 uint32_t flags = 0)
417 : CommandObject(interpreter, name, help, syntax, flags) {}
418
419 ~CommandObjectRaw() override = default;
420
421 void Execute(const char *args_string, CommandReturnObject &result) override;
422
423protected:
424 virtual void DoExecute(llvm::StringRef command,
425 CommandReturnObject &result) = 0;
426
427 bool WantsRawCommandString() override { return true; }
428};
429
430} // namespace lldb_private
431
432#endif // LLDB_INTERPRETER_COMMANDOBJECT_H
433

source code of lldb/include/lldb/Interpreter/CommandObject.h