CommandInterpreter.h revision 6b1596d81c34c6efb10ed51a3572d6b145b73f5b
1//===-- CommandInterpreter.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_CommandInterpreter_h_
11#define liblldb_CommandInterpreter_h_
12
13// C Includes
14// C++ Includes
15// Other libraries and framework includes
16// Project includes
17#include "lldb/lldb-private.h"
18#include "lldb/Core/Broadcaster.h"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Interpreter/CommandObject.h"
22#include "lldb/Interpreter/ScriptInterpreter.h"
23#include "lldb/Core/Event.h"
24#include "lldb/Interpreter/Args.h"
25#include "lldb/Core/StringList.h"
26
27namespace lldb_private {
28
29class CommandInterpreter : public Broadcaster
30{
31public:
32    typedef std::map<std::string, OptionArgVectorSP> OptionArgMap;
33
34    enum
35    {
36        eBroadcastBitThreadShouldExit       = (1 << 0),
37        eBroadcastBitResetPrompt            = (1 << 1),
38        eBroadcastBitQuitCommandReceived    = (1 << 2),   // User entered quit
39        eBroadcastBitAsynchronousOutputData = (1 << 3),
40        eBroadcastBitAsynchronousErrorData  = (1 << 4)
41    };
42
43    enum ChildrenTruncatedWarningStatus // tristate boolean to manage children truncation warning
44    {
45        eNoTruncation = 0, // never truncated
46        eUnwarnedTruncation = 1, // truncated but did not notify
47        eWarnedTruncation = 2 // truncated and notified
48    };
49
50    enum CommandTypes
51    {
52        eCommandTypesBuiltin = 0x0001,  // native commands such as "frame"
53        eCommandTypesUserDef = 0x0002,  // scripted commands
54        eCommandTypesAliases = 0x0004,  // aliases such as "po"
55        eCommandTypesAllThem = 0xFFFF   // all commands
56    };
57
58    void
59    SourceInitFile (bool in_cwd,
60                    CommandReturnObject &result);
61
62    CommandInterpreter (Debugger &debugger,
63                        lldb::ScriptLanguage script_language,
64                        bool synchronous_execution);
65
66    virtual
67    ~CommandInterpreter ();
68
69    bool
70    AddCommand (const char *name,
71                const lldb::CommandObjectSP &cmd_sp,
72                bool can_replace);
73
74    bool
75    AddUserCommand (const char *name,
76                    const lldb::CommandObjectSP &cmd_sp,
77                    bool can_replace);
78
79    lldb::CommandObjectSP
80    GetCommandSPExact (const char *cmd,
81                       bool include_aliases);
82
83    CommandObject *
84    GetCommandObjectExact (const char *cmd_cstr,
85                           bool include_aliases);
86
87    CommandObject *
88    GetCommandObject (const char *cmd,
89                      StringList *matches = NULL);
90
91    bool
92    CommandExists (const char *cmd);
93
94    bool
95    AliasExists (const char *cmd);
96
97    bool
98    UserCommandExists (const char *cmd);
99
100    void
101    AddAlias (const char *alias_name,
102              lldb::CommandObjectSP& command_obj_sp);
103
104    bool
105    RemoveAlias (const char *alias_name);
106
107    bool
108    RemoveUser (const char *alias_name);
109
110    void
111    RemoveAllUser ()
112    {
113        m_user_dict.clear();
114    }
115
116    OptionArgVectorSP
117    GetAliasOptions (const char *alias_name);
118
119
120    bool
121    ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
122                             const char *options_args,
123                             OptionArgVectorSP &option_arg_vector_sp);
124
125    void
126    RemoveAliasOptions (const char *alias_name);
127
128    void
129    AddOrReplaceAliasOptions (const char *alias_name,
130                              OptionArgVectorSP &option_arg_vector_sp);
131
132    bool
133    StripFirstWord (std::string &command_string,
134                    std::string &next_word,
135                    bool &was_quoted,
136                    char &quote_char);
137
138    void
139    BuildAliasResult (const char *alias_name,
140                      std::string &raw_input_string,
141                      std::string &alias_result,
142                      CommandObject *&alias_cmd_obj,
143                      CommandReturnObject &result);
144
145    bool
146    HandleCommand (const char *command_line,
147                   bool add_to_history,
148                   CommandReturnObject &result,
149                   ExecutionContext *override_context = NULL,
150                   bool repeat_on_empty_command = true);
151
152    //------------------------------------------------------------------
153    /// Execute a list of commands in sequence.
154    ///
155    /// @param[in] commands
156    ///    The list of commands to execute.
157    /// @param[in/out] context
158    ///    The execution context in which to run the commands.  Can be NULL in which case the default
159    ///    context will be used.
160    /// @param[in] stop_on_continue
161    ///    If \b true execution will end on the first command that causes the process in the
162    ///    execution context to continue.  If \false, we won't check the execution status.
163    /// @param[in] stop_on_error
164    ///    If \b true execution will end on the first command that causes an error.
165    /// @param[in] echo_commands
166    ///    If \b true echo the command before executing it.  If \false, execute silently.
167    /// @param[in] print_results
168    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
169    /// @param[out] result
170    ///    This is marked as succeeding with no output if all commands execute safely,
171    ///    and failed with some explanation if we aborted executing the commands at some point.
172    //------------------------------------------------------------------
173    void
174    HandleCommands (const StringList &commands,
175                    ExecutionContext *context,
176                    bool stop_on_continue,
177                    bool stop_on_error,
178                    bool echo_commands,
179                    bool print_results,
180                    CommandReturnObject &result);
181
182    //------------------------------------------------------------------
183    /// Execute a list of commands from a file.
184    ///
185    /// @param[in] file
186    ///    The file from which to read in commands.
187    /// @param[in/out] context
188    ///    The execution context in which to run the commands.  Can be NULL in which case the default
189    ///    context will be used.
190    /// @param[in] stop_on_continue
191    ///    If \b true execution will end on the first command that causes the process in the
192    ///    execution context to continue.  If \false, we won't check the execution status.
193    /// @param[in] stop_on_error
194    ///    If \b true execution will end on the first command that causes an error.
195    /// @param[in] echo_commands
196    ///    If \b true echo the command before executing it.  If \false, execute silently.
197    /// @param[in] print_results
198    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
199    /// @param[out] result
200    ///    This is marked as succeeding with no output if all commands execute safely,
201    ///    and failed with some explanation if we aborted executing the commands at some point.
202    //------------------------------------------------------------------
203    void
204    HandleCommandsFromFile (FileSpec &file,
205                            ExecutionContext *context,
206                            bool stop_on_continue,
207                            bool stop_on_error,
208                            bool echo_commands,
209                            bool print_results,
210                            CommandReturnObject &result);
211
212    CommandObject *
213    GetCommandObjectForCommand (std::string &command_line);
214
215    // This handles command line completion.  You are given a pointer to the command string buffer, to the current cursor,
216    // and to the end of the string (in case it is not NULL terminated).
217    // You also passed in an Args object to fill with the returns.
218    // The first element of the array will be filled with the string that you would need to insert at
219    // the cursor point to complete the cursor point to the longest common matching prefix.
220    // If you want to limit the number of elements returned, set max_return_elements to the number of elements
221    // you want returned.  Otherwise set max_return_elements to -1.
222    // If you want to start some way into the match list, then set match_start_point to the desired start
223    // point.
224    // Returns:
225    // -1 if the completion character should be inserted
226    // -2 if the entire command line should be deleted and replaced with matches.GetStringAtIndex(0)
227    // INT_MAX if the number of matches is > max_return_elements, but it is expensive to compute.
228    // Otherwise, returns the number of matches.
229    //
230    // FIXME: Only max_return_elements == -1 is supported at present.
231
232    int
233    HandleCompletion (const char *current_line,
234                      const char *cursor,
235                      const char *last_char,
236                      int match_start_point,
237                      int max_return_elements,
238                      StringList &matches);
239
240    // This version just returns matches, and doesn't compute the substring.  It is here so the
241    // Help command can call it for the first argument.
242    // word_complete tells whether a the completions are considered a "complete" response (so the
243    // completer should complete the quote & put a space after the word.
244
245    int
246    HandleCompletionMatches (Args &input,
247                             int &cursor_index,
248                             int &cursor_char_position,
249                             int match_start_point,
250                             int max_return_elements,
251                             bool &word_complete,
252                             StringList &matches);
253
254
255    int
256    GetCommandNamesMatchingPartialString (const char *cmd_cstr,
257                                          bool include_aliases,
258                                          StringList &matches);
259
260    void
261    GetHelp (CommandReturnObject &result,
262             CommandTypes types = eCommandTypesAllThem);
263
264    void
265    GetAliasHelp (const char *alias_name,
266                  const char *command_name,
267                  StreamString &help_string);
268
269    void
270    OutputFormattedHelpText (Stream &stream,
271                             const char *command_word,
272                             const char *separator,
273                             const char *help_text,
274                             uint32_t max_word_len);
275
276    // this mimics OutputFormattedHelpText but it does perform a much simpler
277    // formatting, basically ensuring line alignment. This is only good if you have
278    // some complicated layout for your help text and want as little help as reasonable
279    // in properly displaying it. Most of the times, you simply want to type some text
280    // and have it printed in a reasonable way on screen. If so, use OutputFormattedHelpText
281    void
282    OutputHelpText (Stream &stream,
283                             const char *command_word,
284                             const char *separator,
285                             const char *help_text,
286                             uint32_t max_word_len);
287
288    Debugger &
289    GetDebugger ()
290    {
291        return m_debugger;
292    }
293
294    ExecutionContext &
295    GetExecutionContext()
296    {
297        return m_exe_ctx;
298    }
299
300    void
301    UpdateExecutionContext (ExecutionContext *override_context);
302
303    lldb::PlatformSP
304    GetPlatform (bool prefer_target_platform);
305
306    const char *
307    ProcessEmbeddedScriptCommands (const char *arg);
308
309    const char *
310    GetPrompt ();
311
312    void
313    SetPrompt (const char *);
314
315    bool Confirm (const char *message, bool default_answer);
316
317    static size_t
318    GetConfirmationInputReaderCallback (void *baton,
319                                        InputReader &reader,
320                                        lldb::InputReaderAction action,
321                                        const char *bytes,
322                                        size_t bytes_len);
323
324    void
325    LoadCommandDictionary ();
326
327    void
328    Initialize ();
329
330    void
331    CrossRegisterCommand (const char *dest_cmd,
332                          const char *object_type);
333
334    void
335    SetScriptLanguage (lldb::ScriptLanguage lang);
336
337
338    bool
339    HasCommands ();
340
341    bool
342    HasAliases ();
343
344    bool
345    HasUserCommands ();
346
347    bool
348    HasAliasOptions ();
349
350    void
351    BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
352                           const char *alias_name,
353                           Args &cmd_args,
354                           std::string &raw_input_string,
355                           CommandReturnObject &result);
356
357    int
358    GetOptionArgumentPosition (const char *in_string);
359
360    ScriptInterpreter *
361    GetScriptInterpreter ();
362
363    void
364    SkipLLDBInitFiles (bool skip_lldbinit_files)
365    {
366        m_skip_lldbinit_files = skip_lldbinit_files;
367    }
368
369    void
370    SkipAppInitFiles (bool skip_app_init_files)
371    {
372        m_skip_app_init_files = m_skip_lldbinit_files;
373    }
374
375    bool
376    GetSynchronous ();
377
378    void
379    DumpHistory (Stream &stream, uint32_t count) const;
380
381    void
382    DumpHistory (Stream &stream, uint32_t start, uint32_t end) const;
383
384    const char *
385    FindHistoryString (const char *input_str) const;
386
387
388#ifndef SWIG
389    void
390    AddLogChannel (const char *name,
391                   const Log::Callbacks &log_callbacks);
392
393    bool
394    GetLogChannelCallbacks (const char *channel,
395                            Log::Callbacks &log_callbacks);
396
397    bool
398    RemoveLogChannel (const char *name);
399#endif
400
401    size_t
402    FindLongestCommandWord (CommandObject::CommandMap &dict);
403
404    void
405    FindCommandsForApropos (const char *word,
406                            StringList &commands_found,
407                            StringList &commands_help);
408
409    void
410    AproposAllSubCommands (CommandObject *cmd_obj,
411                           const char *prefix,
412                           const char *search_word,
413                           StringList &commands_found,
414                           StringList &commands_help);
415
416    bool
417    GetBatchCommandMode () { return m_batch_command_mode; }
418
419    void
420    SetBatchCommandMode (bool value) { m_batch_command_mode = value; }
421
422    void
423    ChildrenTruncated()
424    {
425        if (m_truncation_warning == eNoTruncation)
426            m_truncation_warning = eUnwarnedTruncation;
427    }
428
429    bool
430    TruncationWarningNecessary()
431    {
432        return (m_truncation_warning == eUnwarnedTruncation);
433    }
434
435    void
436    TruncationWarningGiven()
437    {
438        m_truncation_warning = eWarnedTruncation;
439    }
440
441    const char *
442    TruncationWarningText()
443    {
444        return "*** Some of your variables have more members than the debugger will show by default. To show all of them, you can either use the --show-all-children option to %s or raise the limit by changing the target.max-children-count setting.\n";
445    }
446
447protected:
448    friend class Debugger;
449
450    void
451    SetSynchronous (bool value);
452
453    lldb::CommandObjectSP
454    GetCommandSP (const char *cmd, bool include_aliases = true, bool exact = true, StringList *matches = NULL);
455
456private:
457
458    Debugger &m_debugger;                       // The debugger session that this interpreter is associated with
459    ExecutionContext m_exe_ctx;                 // The current execution context to use when handling commands
460    bool m_synchronous_execution;
461    bool m_skip_lldbinit_files;
462    bool m_skip_app_init_files;
463    CommandObject::CommandMap m_command_dict;   // Stores basic built-in commands (they cannot be deleted, removed or overwritten).
464    CommandObject::CommandMap m_alias_dict;     // Stores user aliases/abbreviations for commands
465    CommandObject::CommandMap m_user_dict;      // Stores user-defined commands
466    OptionArgMap m_alias_options;               // Stores any options (with or without arguments) that go with any alias.
467    std::vector<std::string> m_command_history;
468    std::string m_repeat_command;               // Stores the command that will be executed for an empty command string.
469    std::auto_ptr<ScriptInterpreter> m_script_interpreter_ap;
470    char m_comment_char;
471    char m_repeat_char;
472    bool m_batch_command_mode;
473    ChildrenTruncatedWarningStatus m_truncation_warning;    // Whether we truncated children and whether the user has been told
474};
475
476
477} // namespace lldb_private
478
479#endif  // liblldb_CommandInterpreter_h_
480