Coverage Report

Created: 2022-07-16 07:03

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