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