CommandObject.h revision 035ef3d0a0136f2b9028b4695a681e58ba899651
1//===-- CommandObject.h -----------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_CommandObject_h_
11#define liblldb_CommandObject_h_
12
13#include <map>
14#include <set>
15#include <string>
16#include <vector>
17
18#include "lldb/lldb-private.h"
19#include "lldb/Interpreter/Args.h"
20#include "lldb/Interpreter/CommandCompletions.h"
21#include "lldb/Core/StringList.h"
22#include "lldb/Core/Flags.h"
23#include "lldb/Host/Mutex.h"
24#include "lldb/Target/ExecutionContext.h"
25
26namespace lldb_private {
27
28class CommandObject
29{
30public:
31
32    typedef const char *(ArgumentHelpCallbackFunction) ();
33
34    struct ArgumentHelpCallback
35    {
36        ArgumentHelpCallbackFunction  *help_callback;
37        bool                           self_formatting;
38
39        const char*
40        operator () () const
41        {
42            return (*help_callback)();
43        }
44
45        operator bool() const
46        {
47            return (help_callback != NULL);
48        }
49
50    };
51
52    struct ArgumentTableEntry  // Entries in the main argument information table
53    {
54        lldb::CommandArgumentType  arg_type;
55        const char *arg_name;
56        CommandCompletions::CommonCompletionTypes completion_type;
57        ArgumentHelpCallback  help_function;
58        const char *help_text;
59    };
60
61    struct CommandArgumentData  // Used to build individual command argument lists
62    {
63        lldb::CommandArgumentType arg_type;
64        ArgumentRepetitionType arg_repetition;
65        uint32_t arg_opt_set_association; // This arg might be associated only with some particular option set(s).
66        CommandArgumentData():
67            arg_type(lldb::eArgTypeNone),
68            arg_repetition(eArgRepeatPlain),
69            arg_opt_set_association(LLDB_OPT_SET_ALL) // By default, the arg associates to all option sets.
70        {}
71    };
72
73    typedef std::vector<CommandArgumentData> CommandArgumentEntry; // Used to build individual command argument lists
74
75    static ArgumentTableEntry g_arguments_data[lldb::eArgTypeLastArg];   // Main argument information table
76
77    typedef std::map<std::string, lldb::CommandObjectSP> CommandMap;
78
79    CommandObject (CommandInterpreter &interpreter,
80                   const char *name,
81                   const char *help = NULL,
82                   const char *syntax = NULL,
83                   uint32_t flags = 0);
84
85    virtual
86    ~CommandObject ();
87
88
89    static const char *
90    GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type);
91
92    static const char *
93    GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type);
94
95    CommandInterpreter &
96    GetCommandInterpreter ()
97    {
98        return m_interpreter;
99    }
100
101    const char *
102    GetHelp ();
103
104    virtual const char *
105    GetHelpLong ();
106
107    const char *
108    GetSyntax ();
109
110    const char *
111    Translate ();
112
113    const char *
114    GetCommandName ();
115
116    void
117    SetHelp (const char * str);
118
119    void
120    SetHelpLong (const char * str);
121
122    void
123    SetHelpLong (std::string str);
124
125    void
126    SetSyntax (const char *str);
127
128    // override this to return true if you want to enable the user to delete
129    // the Command object from the Command dictionary (aliases have their own
130    // deletion scheme, so they do not need to care about this)
131    virtual bool
132    IsRemovable() const { return false; }
133
134    bool
135    IsAlias () { return m_is_alias; }
136
137    void
138    SetIsAlias (bool value) { m_is_alias = value; }
139
140    virtual bool
141    IsMultiwordObject () { return false; }
142
143    virtual lldb::CommandObjectSP
144    GetSubcommandSP (const char *sub_cmd, StringList *matches = NULL)
145    {
146        return lldb::CommandObjectSP();
147    }
148
149    virtual CommandObject *
150    GetSubcommandObject (const char *sub_cmd, StringList *matches = NULL)
151    {
152        return NULL;
153    }
154
155    virtual void
156    AproposAllSubCommands (const char *prefix,
157                           const char *search_word,
158                           StringList &commands_found,
159                           StringList &commands_help)
160    {
161    }
162
163    void
164    GenerateHelpText (CommandReturnObject &result);
165
166    virtual void
167    GenerateHelpText (Stream &result);
168
169    // this is needed in order to allow the SBCommand class to
170    // transparently try and load subcommands - it will fail on
171    // anything but a multiword command, but it avoids us doing
172    // type checkings and casts
173    virtual bool
174    LoadSubCommand (const char *cmd_name,
175                    const lldb::CommandObjectSP& command_obj)
176    {
177        return false;
178    }
179
180    virtual bool
181    WantsRawCommandString() = 0;
182
183    // By default, WantsCompletion = !WantsRawCommandString.
184    // Subclasses who want raw command string but desire, for example,
185    // argument completion should override this method to return true.
186    virtual bool
187    WantsCompletion() { return !WantsRawCommandString(); }
188
189    virtual Options *
190    GetOptions ();
191
192    static const ArgumentTableEntry*
193    GetArgumentTable ();
194
195    static lldb::CommandArgumentType
196    LookupArgumentName (const char *arg_name);
197
198    static ArgumentTableEntry *
199    FindArgumentDataByType (lldb::CommandArgumentType arg_type);
200
201    int
202    GetNumArgumentEntries ();
203
204    CommandArgumentEntry *
205    GetArgumentEntryAtIndex (int idx);
206
207    static void
208    GetArgumentHelp (Stream &str, lldb::CommandArgumentType arg_type, CommandInterpreter &interpreter);
209
210    static const char *
211    GetArgumentName (lldb::CommandArgumentType arg_type);
212
213    // Generates a nicely formatted command args string for help command output.
214    // By default, all possible args are taken into account, for example,
215    // '<expr | variable-name>'.  This can be refined by passing a second arg
216    // specifying which option set(s) we are interested, which could then, for
217    // example, produce either '<expr>' or '<variable-name>'.
218    void
219    GetFormattedCommandArguments (Stream &str, uint32_t opt_set_mask = LLDB_OPT_SET_ALL);
220
221    bool
222    IsPairType (ArgumentRepetitionType arg_repeat_type);
223
224    enum
225    {
226        //----------------------------------------------------------------------
227        // eFlagRequiresTarget
228        //
229        // Ensures a valid target is contained in m_exe_ctx prior to executing
230        // the command. If a target doesn't exist or is invalid, the command
231        // will fail and CommandObject::GetInvalidTargetDescription() will be
232        // returned as the error. CommandObject subclasses can override the
233        // virtual function for GetInvalidTargetDescription() to provide custom
234        // strings when needed.
235        //----------------------------------------------------------------------
236        eFlagRequiresTarget         = (1u << 0),
237        //----------------------------------------------------------------------
238        // eFlagRequiresProcess
239        //
240        // Ensures a valid process is contained in m_exe_ctx prior to executing
241        // the command. If a process doesn't exist or is invalid, the command
242        // will fail and CommandObject::GetInvalidProcessDescription() will be
243        // returned as the error. CommandObject subclasses can override the
244        // virtual function for GetInvalidProcessDescription() to provide custom
245        // strings when needed.
246        //----------------------------------------------------------------------
247        eFlagRequiresProcess        = (1u << 1),
248        //----------------------------------------------------------------------
249        // eFlagRequiresThread
250        //
251        // Ensures a valid thread is contained in m_exe_ctx prior to executing
252        // the command. If a thread doesn't exist or is invalid, the command
253        // will fail and CommandObject::GetInvalidThreadDescription() will be
254        // returned as the error. CommandObject subclasses can override the
255        // virtual function for GetInvalidThreadDescription() to provide custom
256        // strings when needed.
257        //----------------------------------------------------------------------
258        eFlagRequiresThread         = (1u << 2),
259        //----------------------------------------------------------------------
260        // eFlagRequiresFrame
261        //
262        // Ensures a valid frame is contained in m_exe_ctx prior to executing
263        // the command. If a frame doesn't exist or is invalid, the command
264        // will fail and CommandObject::GetInvalidFrameDescription() will be
265        // returned as the error. CommandObject subclasses can override the
266        // virtual function for GetInvalidFrameDescription() to provide custom
267        // strings when needed.
268        //----------------------------------------------------------------------
269        eFlagRequiresFrame          = (1u << 3),
270        //----------------------------------------------------------------------
271        // eFlagRequiresRegContext
272        //
273        // Ensures a valid register context (from the selected frame if there
274        // is a frame in m_exe_ctx, or from the selected thread from m_exe_ctx)
275        // is availble from m_exe_ctx prior to executing the command. If a
276        // target doesn't exist or is invalid, the command will fail and
277        // CommandObject::GetInvalidRegContextDescription() will be returned as
278        // the error. CommandObject subclasses can override the virtual function
279        // for GetInvalidRegContextDescription() to provide custom strings when
280        // needed.
281        //----------------------------------------------------------------------
282        eFlagRequiresRegContext     = (1u << 4),
283        //----------------------------------------------------------------------
284        // eFlagTryTargetAPILock
285        //
286        // Attempts to acquire the target lock if a target is selected in the
287        // command interpreter. If the command object fails to acquire the API
288        // lock, the command will fail with an appropriate error message.
289        //----------------------------------------------------------------------
290        eFlagTryTargetAPILock       = (1u << 5),
291        //----------------------------------------------------------------------
292        // eFlagProcessMustBeLaunched
293        //
294        // Verifies that there is a launched process in m_exe_ctx, if there
295        // isn't, the command will fail with an appropriate error message.
296        //----------------------------------------------------------------------
297        eFlagProcessMustBeLaunched  = (1u << 6),
298        //----------------------------------------------------------------------
299        // eFlagProcessMustBePaused
300        //
301        // Verifies that there is a paused process in m_exe_ctx, if there
302        // isn't, the command will fail with an appropriate error message.
303        //----------------------------------------------------------------------
304        eFlagProcessMustBePaused    = (1u << 7)
305    };
306
307    bool
308    ParseOptions (Args& args, CommandReturnObject &result);
309
310    void
311    SetCommandName (const char *name);
312
313    // This function really deals with CommandObjectLists, but we didn't make a
314    // CommandObjectList class, so I'm sticking it here.  But we really should have
315    // such a class.  Anyway, it looks up the commands in the map that match the partial
316    // string cmd_str, inserts the matches into matches, and returns the number added.
317
318    static int
319    AddNamesMatchingPartialString (CommandMap &in_map, const char *cmd_str, StringList &matches);
320
321    //------------------------------------------------------------------
322    /// The input array contains a parsed version of the line.  The insertion
323    /// point is given by cursor_index (the index in input of the word containing
324    /// the cursor) and cursor_char_position (the position of the cursor in that word.)
325    /// This default version handles calling option argument completions and then calls
326    /// HandleArgumentCompletion if the cursor is on an argument, not an option.
327    /// Don't override this method, override HandleArgumentCompletion instead unless
328    /// you have special reasons.
329    ///
330    /// @param[in] interpreter
331    ///    The command interpreter doing the completion.
332    ///
333    /// @param[in] input
334    ///    The command line parsed into words
335    ///
336    /// @param[in] cursor_index
337    ///     The index in \ainput of the word in which the cursor lies.
338    ///
339    /// @param[in] cursor_char_pos
340    ///     The character position of the cursor in its argument word.
341    ///
342    /// @param[in] match_start_point
343    /// @param[in] match_return_elements
344    ///     FIXME: Not yet implemented...  If there is a match that is expensive to compute, these are
345    ///     here to allow you to compute the completions in batches.  Start the completion from \amatch_start_point,
346    ///     and return \amatch_return_elements elements.
347    ///
348    /// @param[out] word_complete
349    ///     \btrue if this is a complete option value (a space will be inserted after the
350    ///     completion.)  \bfalse otherwise.
351    ///
352    /// @param[out] matches
353    ///     The array of matches returned.
354    ///
355    /// FIXME: This is the wrong return value, since we also need to make a distinction between
356    /// total number of matches, and the window the user wants returned.
357    ///
358    /// @return
359    ///     \btrue if we were in an option, \bfalse otherwise.
360    //------------------------------------------------------------------
361    virtual int
362    HandleCompletion (Args &input,
363                      int &cursor_index,
364                      int &cursor_char_position,
365                      int match_start_point,
366                      int max_return_elements,
367                      bool &word_complete,
368                      StringList &matches);
369
370    //------------------------------------------------------------------
371    /// The input array contains a parsed version of the line.  The insertion
372    /// point is given by cursor_index (the index in input of the word containing
373    /// the cursor) and cursor_char_position (the position of the cursor in that word.)
374    /// We've constructed the map of options and their arguments as well if that is
375    /// helpful for the completion.
376    ///
377    /// @param[in] interpreter
378    ///    The command interpreter doing the completion.
379    ///
380    /// @param[in] input
381    ///    The command line parsed into words
382    ///
383    /// @param[in] cursor_index
384    ///     The index in \ainput of the word in which the cursor lies.
385    ///
386    /// @param[in] cursor_char_pos
387    ///     The character position of the cursor in its argument word.
388    ///
389    /// @param[in] opt_element_vector
390    ///     The results of the options parse of \a input.
391    ///
392    /// @param[in] match_start_point
393    /// @param[in] match_return_elements
394    ///     See CommandObject::HandleCompletions for a description of how these work.
395    ///
396    /// @param[out] word_complete
397    ///     \btrue if this is a complete option value (a space will be inserted after the
398    ///     completion.)  \bfalse otherwise.
399    ///
400    /// @param[out] matches
401    ///     The array of matches returned.
402    ///
403    /// FIXME: This is the wrong return value, since we also need to make a distinction between
404    /// total number of matches, and the window the user wants returned.
405    ///
406    /// @return
407    ///     The number of completions.
408    //------------------------------------------------------------------
409
410    virtual int
411    HandleArgumentCompletion (Args &input,
412                              int &cursor_index,
413                              int &cursor_char_position,
414                              OptionElementVector &opt_element_vector,
415                              int match_start_point,
416                              int max_return_elements,
417                              bool &word_complete,
418                              StringList &matches)
419    {
420        return 0;
421    }
422
423    bool
424    HelpTextContainsWord (const char *search_word);
425
426    //------------------------------------------------------------------
427    /// The flags accessor.
428    ///
429    /// @return
430    ///     A reference to the Flags member variable.
431    //------------------------------------------------------------------
432    Flags&
433    GetFlags()
434    {
435        return m_flags;
436    }
437
438    //------------------------------------------------------------------
439    /// The flags const accessor.
440    ///
441    /// @return
442    ///     A const reference to the Flags member variable.
443    //------------------------------------------------------------------
444    const Flags&
445    GetFlags() const
446    {
447        return m_flags;
448    }
449
450    //------------------------------------------------------------------
451    /// Get the command that appropriate for a "repeat" of the current command.
452    ///
453    /// @param[in] current_command_line
454    ///    The complete current command line.
455    ///
456    /// @return
457    ///     NULL if there is no special repeat command - it will use the current command line.
458    ///     Otherwise a pointer to the command to be repeated.
459    ///     If the returned string is the empty string, the command won't be repeated.
460    //------------------------------------------------------------------
461    virtual const char *GetRepeatCommand (Args &current_command_args, uint32_t index)
462    {
463        return NULL;
464    }
465
466    CommandOverrideCallback
467    GetOverrideCallback () const
468    {
469        return m_command_override_callback;
470    }
471
472    void *
473    GetOverrideCallbackBaton () const
474    {
475        return m_command_override_baton;
476    }
477
478    void
479    SetOverrideCallback (CommandOverrideCallback callback, void *baton)
480    {
481        m_command_override_callback = callback;
482        m_command_override_baton = baton;
483    }
484
485    virtual bool
486    Execute (const char *args_string, CommandReturnObject &result) = 0;
487
488protected:
489    virtual const char *
490    GetInvalidTargetDescription()
491    {
492        return "invalid target, create a target using the 'target create' command";
493    }
494
495    virtual const char *
496    GetInvalidProcessDescription()
497    {
498        return "invalid process";
499    }
500
501    virtual const char *
502    GetInvalidThreadDescription()
503    {
504        return "invalid thread";
505    }
506
507    virtual const char *
508    GetInvalidFrameDescription()
509    {
510        return "invalid frame";
511    }
512
513    virtual const char *
514    GetInvalidRegContextDescription ()
515    {
516        return "invalid frame, no registers";
517    }
518
519    //------------------------------------------------------------------
520    /// Check the command to make sure anything required by this
521    /// command is available.
522    ///
523    /// @param[out] result
524    ///     A command result object, if it is not okay to run the command
525    ///     this will be filled in with a suitable error.
526    ///
527    /// @return
528    ///     \b true if it is okay to run this command, \b false otherwise.
529    //------------------------------------------------------------------
530    bool
531    CheckRequirements (CommandReturnObject &result);
532
533    void
534    Cleanup ();
535
536    CommandInterpreter &m_interpreter;
537    ExecutionContext m_exe_ctx;
538    Mutex::Locker m_api_locker;
539    std::string m_cmd_name;
540    std::string m_cmd_help_short;
541    std::string m_cmd_help_long;
542    std::string m_cmd_syntax;
543    bool m_is_alias;
544    Flags m_flags;
545    std::vector<CommandArgumentEntry> m_arguments;
546    CommandOverrideCallback m_command_override_callback;
547    void * m_command_override_baton;
548
549    // Helper function to populate IDs or ID ranges as the command argument data
550    // to the specified command argument entry.
551    static void
552    AddIDsArgumentData(CommandArgumentEntry &arg, lldb::CommandArgumentType ID, lldb::CommandArgumentType IDRange);
553
554};
555
556class CommandObjectParsed : public CommandObject
557{
558public:
559
560    CommandObjectParsed (CommandInterpreter &interpreter,
561                         const char *name,
562                         const char *help = NULL,
563                         const char *syntax = NULL,
564                         uint32_t flags = 0) :
565        CommandObject (interpreter, name, help, syntax, flags) {}
566
567    virtual
568    ~CommandObjectParsed () {};
569
570    virtual bool
571    Execute (const char *args_string, CommandReturnObject &result);
572
573protected:
574    virtual bool
575    DoExecute (Args& command,
576             CommandReturnObject &result) = 0;
577
578    virtual bool
579    WantsRawCommandString() { return false; };
580};
581
582class CommandObjectRaw : public CommandObject
583{
584public:
585
586    CommandObjectRaw (CommandInterpreter &interpreter,
587                         const char *name,
588                         const char *help = NULL,
589                         const char *syntax = NULL,
590                         uint32_t flags = 0) :
591        CommandObject (interpreter, name, help, syntax, flags) {}
592
593    virtual
594    ~CommandObjectRaw () {};
595
596    virtual bool
597    Execute (const char *args_string, CommandReturnObject &result);
598
599protected:
600    virtual bool
601    DoExecute (const char *command, CommandReturnObject &result) = 0;
602
603    virtual bool
604    WantsRawCommandString() { return true; };
605};
606
607
608} // namespace lldb_private
609
610
611#endif  // liblldb_CommandObject_h_
612