CommandInterpreter.h revision 9d855c667f8006ffcfd20dc8858fea6a0308b411
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    void
133    BuildAliasResult (const char *alias_name,
134                      std::string &raw_input_string,
135                      std::string &alias_result,
136                      CommandObject *&alias_cmd_obj,
137                      CommandReturnObject &result);
138
139    bool
140    HandleCommand (const char *command_line,
141                   bool add_to_history,
142                   CommandReturnObject &result,
143                   ExecutionContext *override_context = NULL,
144                   bool repeat_on_empty_command = true,
145                   bool no_context_switching = false);
146
147    //------------------------------------------------------------------
148    /// Execute a list of commands in sequence.
149    ///
150    /// @param[in] commands
151    ///    The list of commands to execute.
152    /// @param[in/out] context
153    ///    The execution context in which to run the commands.  Can be NULL in which case the default
154    ///    context will be used.
155    /// @param[in] stop_on_continue
156    ///    If \b true execution will end on the first command that causes the process in the
157    ///    execution context to continue.  If \false, we won't check the execution status.
158    /// @param[in] stop_on_error
159    ///    If \b true execution will end on the first command that causes an error.
160    /// @param[in] echo_commands
161    ///    If \b true echo the command before executing it.  If \false, execute silently.
162    /// @param[in] print_results
163    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
164    /// @param[out] result
165    ///    This is marked as succeeding with no output if all commands execute safely,
166    ///    and failed with some explanation if we aborted executing the commands at some point.
167    //------------------------------------------------------------------
168    void
169    HandleCommands (const StringList &commands,
170                    ExecutionContext *context,
171                    bool stop_on_continue,
172                    bool stop_on_error,
173                    bool echo_commands,
174                    bool print_results,
175                    CommandReturnObject &result);
176
177    //------------------------------------------------------------------
178    /// Execute a list of commands from a file.
179    ///
180    /// @param[in] file
181    ///    The file from which to read in commands.
182    /// @param[in/out] context
183    ///    The execution context in which to run the commands.  Can be NULL in which case the default
184    ///    context will be used.
185    /// @param[in] stop_on_continue
186    ///    If \b true execution will end on the first command that causes the process in the
187    ///    execution context to continue.  If \false, we won't check the execution status.
188    /// @param[in] stop_on_error
189    ///    If \b true execution will end on the first command that causes an error.
190    /// @param[in] echo_commands
191    ///    If \b true echo the command before executing it.  If \false, execute silently.
192    /// @param[in] print_results
193    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
194    /// @param[out] result
195    ///    This is marked as succeeding with no output if all commands execute safely,
196    ///    and failed with some explanation if we aborted executing the commands at some point.
197    //------------------------------------------------------------------
198    void
199    HandleCommandsFromFile (FileSpec &file,
200                            ExecutionContext *context,
201                            bool stop_on_continue,
202                            bool stop_on_error,
203                            bool echo_commands,
204                            bool print_results,
205                            CommandReturnObject &result);
206
207    CommandObject *
208    GetCommandObjectForCommand (std::string &command_line);
209
210    // This handles command line completion.  You are given a pointer to the command string buffer, to the current cursor,
211    // and to the end of the string (in case it is not NULL terminated).
212    // You also passed in an StringList object to fill with the returns.
213    // The first element of the array will be filled with the string that you would need to insert at
214    // the cursor point to complete the cursor point to the longest common matching prefix.
215    // If you want to limit the number of elements returned, set max_return_elements to the number of elements
216    // you want returned.  Otherwise set max_return_elements to -1.
217    // If you want to start some way into the match list, then set match_start_point to the desired start
218    // point.
219    // Returns:
220    // -1 if the completion character should be inserted
221    // -2 if the entire command line should be deleted and replaced with matches.GetStringAtIndex(0)
222    // INT_MAX if the number of matches is > max_return_elements, but it is expensive to compute.
223    // Otherwise, returns the number of matches.
224    //
225    // FIXME: Only max_return_elements == -1 is supported at present.
226
227    int
228    HandleCompletion (const char *current_line,
229                      const char *cursor,
230                      const char *last_char,
231                      int match_start_point,
232                      int max_return_elements,
233                      StringList &matches);
234
235    // This version just returns matches, and doesn't compute the substring.  It is here so the
236    // Help command can call it for the first argument.
237    // word_complete tells whether a the completions are considered a "complete" response (so the
238    // completer should complete the quote & put a space after the word.
239
240    int
241    HandleCompletionMatches (Args &input,
242                             int &cursor_index,
243                             int &cursor_char_position,
244                             int match_start_point,
245                             int max_return_elements,
246                             bool &word_complete,
247                             StringList &matches);
248
249
250    int
251    GetCommandNamesMatchingPartialString (const char *cmd_cstr,
252                                          bool include_aliases,
253                                          StringList &matches);
254
255    void
256    GetHelp (CommandReturnObject &result,
257             uint32_t types = eCommandTypesAllThem);
258
259    void
260    GetAliasHelp (const char *alias_name,
261                  const char *command_name,
262                  StreamString &help_string);
263
264    void
265    OutputFormattedHelpText (Stream &stream,
266                             const char *command_word,
267                             const char *separator,
268                             const char *help_text,
269                             uint32_t max_word_len);
270
271    // this mimics OutputFormattedHelpText but it does perform a much simpler
272    // formatting, basically ensuring line alignment. This is only good if you have
273    // some complicated layout for your help text and want as little help as reasonable
274    // in properly displaying it. Most of the times, you simply want to type some text
275    // and have it printed in a reasonable way on screen. If so, use OutputFormattedHelpText
276    void
277    OutputHelpText (Stream &stream,
278                             const char *command_word,
279                             const char *separator,
280                             const char *help_text,
281                             uint32_t max_word_len);
282
283    Debugger &
284    GetDebugger ()
285    {
286        return m_debugger;
287    }
288
289    ExecutionContext &
290    GetExecutionContext()
291    {
292        return m_exe_ctx;
293    }
294
295    void
296    UpdateExecutionContext (ExecutionContext *override_context);
297
298    lldb::PlatformSP
299    GetPlatform (bool prefer_target_platform);
300
301    const char *
302    ProcessEmbeddedScriptCommands (const char *arg);
303
304    const char *
305    GetPrompt ();
306
307    void
308    SetPrompt (const char *);
309
310    bool Confirm (const char *message, bool default_answer);
311
312    static size_t
313    GetConfirmationInputReaderCallback (void *baton,
314                                        InputReader &reader,
315                                        lldb::InputReaderAction action,
316                                        const char *bytes,
317                                        size_t bytes_len);
318
319    void
320    LoadCommandDictionary ();
321
322    void
323    Initialize ();
324
325    void
326    CrossRegisterCommand (const char *dest_cmd,
327                          const char *object_type);
328
329    void
330    SetScriptLanguage (lldb::ScriptLanguage lang);
331
332
333    bool
334    HasCommands ();
335
336    bool
337    HasAliases ();
338
339    bool
340    HasUserCommands ();
341
342    bool
343    HasAliasOptions ();
344
345    void
346    BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
347                           const char *alias_name,
348                           Args &cmd_args,
349                           std::string &raw_input_string,
350                           CommandReturnObject &result);
351
352    int
353    GetOptionArgumentPosition (const char *in_string);
354
355    ScriptInterpreter *
356    GetScriptInterpreter ();
357
358    void
359    SkipLLDBInitFiles (bool skip_lldbinit_files)
360    {
361        m_skip_lldbinit_files = skip_lldbinit_files;
362    }
363
364    void
365    SkipAppInitFiles (bool skip_app_init_files)
366    {
367        m_skip_app_init_files = m_skip_lldbinit_files;
368    }
369
370    bool
371    GetSynchronous ();
372
373    void
374    DumpHistory (Stream &stream, uint32_t count) const;
375
376    void
377    DumpHistory (Stream &stream, uint32_t start, uint32_t end) const;
378
379    const char *
380    FindHistoryString (const char *input_str) const;
381
382
383#ifndef SWIG
384    void
385    AddLogChannel (const char *name,
386                   const Log::Callbacks &log_callbacks);
387
388    bool
389    GetLogChannelCallbacks (const char *channel,
390                            Log::Callbacks &log_callbacks);
391
392    bool
393    RemoveLogChannel (const char *name);
394#endif
395
396    size_t
397    FindLongestCommandWord (CommandObject::CommandMap &dict);
398
399    void
400    FindCommandsForApropos (const char *word,
401                            StringList &commands_found,
402                            StringList &commands_help);
403
404    void
405    AproposAllSubCommands (CommandObject *cmd_obj,
406                           const char *prefix,
407                           const char *search_word,
408                           StringList &commands_found,
409                           StringList &commands_help);
410
411    bool
412    GetBatchCommandMode () { return m_batch_command_mode; }
413
414    void
415    SetBatchCommandMode (bool value) { m_batch_command_mode = value; }
416
417    void
418    ChildrenTruncated()
419    {
420        if (m_truncation_warning == eNoTruncation)
421            m_truncation_warning = eUnwarnedTruncation;
422    }
423
424    bool
425    TruncationWarningNecessary()
426    {
427        return (m_truncation_warning == eUnwarnedTruncation);
428    }
429
430    void
431    TruncationWarningGiven()
432    {
433        m_truncation_warning = eWarnedTruncation;
434    }
435
436    const char *
437    TruncationWarningText()
438    {
439        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";
440    }
441
442protected:
443    friend class Debugger;
444
445    void
446    SetSynchronous (bool value);
447
448    lldb::CommandObjectSP
449    GetCommandSP (const char *cmd, bool include_aliases = true, bool exact = true, StringList *matches = NULL);
450
451private:
452
453    Error
454    PreprocessCommand (std::string &command);
455
456    Debugger &m_debugger;                       // The debugger session that this interpreter is associated with
457    ExecutionContext m_exe_ctx;                 // The current execution context to use when handling commands
458    bool m_synchronous_execution;
459    bool m_skip_lldbinit_files;
460    bool m_skip_app_init_files;
461    CommandObject::CommandMap m_command_dict;   // Stores basic built-in commands (they cannot be deleted, removed or overwritten).
462    CommandObject::CommandMap m_alias_dict;     // Stores user aliases/abbreviations for commands
463    CommandObject::CommandMap m_user_dict;      // Stores user-defined commands
464    OptionArgMap m_alias_options;               // Stores any options (with or without arguments) that go with any alias.
465    std::vector<std::string> m_command_history;
466    std::string m_repeat_command;               // Stores the command that will be executed for an empty command string.
467    std::auto_ptr<ScriptInterpreter> m_script_interpreter_ap;
468    char m_comment_char;
469    char m_repeat_char;
470    bool m_batch_command_mode;
471    ChildrenTruncatedWarningStatus m_truncation_warning;    // Whether we truncated children and whether the user has been told
472};
473
474
475} // namespace lldb_private
476
477#endif  // liblldb_CommandInterpreter_h_
478