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