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