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