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