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