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