]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Interpreter / CommandInterpreter.h
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 #include <mutex>
16 // Other libraries and framework includes
17 // Project includes
18 #include "lldb/Core/Broadcaster.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Event.h"
21 #include "lldb/Core/IOHandler.h"
22 #include "lldb/Interpreter/CommandAlias.h"
23 #include "lldb/Interpreter/CommandHistory.h"
24 #include "lldb/Interpreter/CommandObject.h"
25 #include "lldb/Interpreter/ScriptInterpreter.h"
26 #include "lldb/Utility/Args.h"
27 #include "lldb/Utility/CompletionRequest.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/StringList.h"
30 #include "lldb/lldb-forward.h"
31 #include "lldb/lldb-private.h"
32
33 namespace lldb_private {
34
35 class CommandInterpreterRunOptions {
36 public:
37   //------------------------------------------------------------------
38   /// Construct a CommandInterpreterRunOptions object.
39   /// This class is used to control all the instances where we run multiple
40   /// commands, e.g.
41   /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
42   /// The meanings of the options in this object are:
43   ///
44   /// @param[in] stop_on_continue
45   ///    If \b true execution will end on the first command that causes the
46   ///    process in the
47   ///    execution context to continue.  If \false, we won't check the execution
48   ///    status.
49   /// @param[in] stop_on_error
50   ///    If \b true execution will end on the first command that causes an
51   ///    error.
52   /// @param[in] stop_on_crash
53   ///    If \b true when a command causes the target to run, and the end of the
54   ///    run is a
55   ///    signal or exception, stop executing the commands.
56   /// @param[in] echo_commands
57   ///    If \b true echo the command before executing it.  If \false, execute
58   ///    silently.
59   /// @param[in] print_results
60   ///    If \b true print the results of the command after executing it.  If
61   ///    \false, execute silently.
62   /// @param[in] add_to_history
63   ///    If \b true add the commands to the command history.  If \false, don't
64   ///    add them.
65   //------------------------------------------------------------------
66   CommandInterpreterRunOptions(LazyBool stop_on_continue,
67                                LazyBool stop_on_error, LazyBool stop_on_crash,
68                                LazyBool echo_commands, LazyBool print_results,
69                                LazyBool add_to_history)
70       : m_stop_on_continue(stop_on_continue), m_stop_on_error(stop_on_error),
71         m_stop_on_crash(stop_on_crash), m_echo_commands(echo_commands),
72         m_print_results(print_results), m_add_to_history(add_to_history) {}
73
74   CommandInterpreterRunOptions()
75       : m_stop_on_continue(eLazyBoolCalculate),
76         m_stop_on_error(eLazyBoolCalculate),
77         m_stop_on_crash(eLazyBoolCalculate),
78         m_echo_commands(eLazyBoolCalculate),
79         m_print_results(eLazyBoolCalculate),
80         m_add_to_history(eLazyBoolCalculate) {}
81
82   void SetSilent(bool silent) {
83     LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
84
85     m_echo_commands = value;
86     m_print_results = value;
87     m_add_to_history = value;
88   }
89   // These return the default behaviors if the behavior is not
90   // eLazyBoolCalculate. But I've also left the ivars public since for
91   // different ways of running the interpreter you might want to force
92   // different defaults...  In that case, just grab the LazyBool ivars directly
93   // and do what you want with eLazyBoolCalculate.
94   bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); }
95
96   void SetStopOnContinue(bool stop_on_continue) {
97     m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
98   }
99
100   bool GetStopOnError() const { return DefaultToNo(m_stop_on_continue); }
101
102   void SetStopOnError(bool stop_on_error) {
103     m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
104   }
105
106   bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
107
108   void SetStopOnCrash(bool stop_on_crash) {
109     m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
110   }
111
112   bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
113
114   void SetEchoCommands(bool echo_commands) {
115     m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
116   }
117
118   bool GetPrintResults() const { return DefaultToYes(m_print_results); }
119
120   void SetPrintResults(bool print_results) {
121     m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
122   }
123
124   bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
125
126   void SetAddToHistory(bool add_to_history) {
127     m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
128   }
129
130   LazyBool m_stop_on_continue;
131   LazyBool m_stop_on_error;
132   LazyBool m_stop_on_crash;
133   LazyBool m_echo_commands;
134   LazyBool m_print_results;
135   LazyBool m_add_to_history;
136
137 private:
138   static bool DefaultToYes(LazyBool flag) {
139     switch (flag) {
140     case eLazyBoolNo:
141       return false;
142     default:
143       return true;
144     }
145   }
146
147   static bool DefaultToNo(LazyBool flag) {
148     switch (flag) {
149     case eLazyBoolYes:
150       return true;
151     default:
152       return false;
153     }
154   }
155 };
156
157 class CommandInterpreter : public Broadcaster,
158                            public Properties,
159                            public IOHandlerDelegate {
160 public:
161   enum {
162     eBroadcastBitThreadShouldExit = (1 << 0),
163     eBroadcastBitResetPrompt = (1 << 1),
164     eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
165     eBroadcastBitAsynchronousOutputData = (1 << 3),
166     eBroadcastBitAsynchronousErrorData = (1 << 4)
167   };
168
169   enum ChildrenTruncatedWarningStatus // tristate boolean to manage children
170                                       // truncation warning
171   { eNoTruncation = 0,                // never truncated
172     eUnwarnedTruncation = 1,          // truncated but did not notify
173     eWarnedTruncation = 2             // truncated and notified
174   };
175
176   enum CommandTypes {
177     eCommandTypesBuiltin = 0x0001, // native commands such as "frame"
178     eCommandTypesUserDef = 0x0002, // scripted commands
179     eCommandTypesAliases = 0x0004, // aliases such as "po"
180     eCommandTypesHidden = 0x0008,  // commands prefixed with an underscore
181     eCommandTypesAllThem = 0xFFFF  // all commands
182   };
183
184   CommandInterpreter(Debugger &debugger, lldb::ScriptLanguage script_language,
185                      bool synchronous_execution);
186
187   ~CommandInterpreter() override;
188
189   // These two functions fill out the Broadcaster interface:
190
191   static ConstString &GetStaticBroadcasterClass();
192
193   ConstString &GetBroadcasterClass() const override {
194     return GetStaticBroadcasterClass();
195   }
196
197   void SourceInitFile(bool in_cwd, CommandReturnObject &result);
198
199   bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
200                   bool can_replace);
201
202   bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
203                       bool can_replace);
204
205   lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
206                                           bool include_aliases) const;
207
208   CommandObject *GetCommandObject(llvm::StringRef cmd,
209                                   StringList *matches = nullptr) const;
210
211   bool CommandExists(llvm::StringRef cmd) const;
212
213   bool AliasExists(llvm::StringRef cmd) const;
214
215   bool UserCommandExists(llvm::StringRef cmd) const;
216
217   CommandAlias *AddAlias(llvm::StringRef alias_name,
218                          lldb::CommandObjectSP &command_obj_sp,
219                          llvm::StringRef args_string = llvm::StringRef());
220
221   // Remove a command if it is removable (python or regex command)
222   bool RemoveCommand(llvm::StringRef cmd);
223
224   bool RemoveAlias(llvm::StringRef alias_name);
225
226   bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
227
228   bool RemoveUser(llvm::StringRef alias_name);
229
230   void RemoveAllUser() { m_user_dict.clear(); }
231
232   const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
233
234   CommandObject *BuildAliasResult(llvm::StringRef alias_name,
235                                   std::string &raw_input_string,
236                                   std::string &alias_result,
237                                   CommandReturnObject &result);
238
239   bool HandleCommand(const char *command_line, LazyBool add_to_history,
240                      CommandReturnObject &result,
241                      ExecutionContext *override_context = nullptr,
242                      bool repeat_on_empty_command = true,
243                      bool no_context_switching = false);
244
245   bool WasInterrupted() const;
246
247   //------------------------------------------------------------------
248   /// Execute a list of commands in sequence.
249   ///
250   /// @param[in] commands
251   ///    The list of commands to execute.
252   /// @param[in,out] context
253   ///    The execution context in which to run the commands. Can be nullptr in
254   ///    which case the default
255   ///    context will be used.
256   /// @param[in] options
257   ///    This object holds the options used to control when to stop, whether to
258   ///    execute commands,
259   ///    etc.
260   /// @param[out] result
261   ///    This is marked as succeeding with no output if all commands execute
262   ///    safely,
263   ///    and failed with some explanation if we aborted executing the commands
264   ///    at some point.
265   //------------------------------------------------------------------
266   void HandleCommands(const StringList &commands, ExecutionContext *context,
267                       CommandInterpreterRunOptions &options,
268                       CommandReturnObject &result);
269
270   //------------------------------------------------------------------
271   /// Execute a list of commands from a file.
272   ///
273   /// @param[in] file
274   ///    The file from which to read in commands.
275   /// @param[in,out] context
276   ///    The execution context in which to run the commands. Can be nullptr in
277   ///    which case the default
278   ///    context will be used.
279   /// @param[in] options
280   ///    This object holds the options used to control when to stop, whether to
281   ///    execute commands,
282   ///    etc.
283   /// @param[out] result
284   ///    This is marked as succeeding with no output if all commands execute
285   ///    safely,
286   ///    and failed with some explanation if we aborted executing the commands
287   ///    at some point.
288   //------------------------------------------------------------------
289   void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context,
290                               CommandInterpreterRunOptions &options,
291                               CommandReturnObject &result);
292
293   CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
294
295   // This handles command line completion.  You are given a pointer to the
296   // command string buffer, to the current cursor, and to the end of the string
297   // (in case it is not NULL terminated). You also passed in an StringList
298   // object to fill with the returns. The first element of the array will be
299   // filled with the string that you would need to insert at the cursor point
300   // to complete the cursor point to the longest common matching prefix. If you
301   // want to limit the number of elements returned, set max_return_elements to
302   // the number of elements you want returned.  Otherwise set
303   // max_return_elements to -1. If you want to start some way into the match
304   // list, then set match_start_point to the desired start point. Returns: -1
305   // if the completion character should be inserted -2 if the entire command
306   // line should be deleted and replaced with matches.GetStringAtIndex(0)
307   // INT_MAX if the number of matches is > max_return_elements, but it is
308   // expensive to compute. Otherwise, returns the number of matches.
309   //
310   // FIXME: Only max_return_elements == -1 is supported at present.
311   int HandleCompletion(const char *current_line, const char *cursor,
312                        const char *last_char, int match_start_point,
313                        int max_return_elements, StringList &matches);
314
315   // This version just returns matches, and doesn't compute the substring.  It
316   // is here so the Help command can call it for the first argument. It uses
317   // a CompletionRequest for simplicity reasons.
318   int HandleCompletionMatches(CompletionRequest &request);
319
320   int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
321                                            bool include_aliases,
322                                            StringList &matches);
323
324   void GetHelp(CommandReturnObject &result,
325                uint32_t types = eCommandTypesAllThem);
326
327   void GetAliasHelp(const char *alias_name, StreamString &help_string);
328
329   void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
330                                llvm::StringRef help_text);
331
332   void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
333                                llvm::StringRef separator,
334                                llvm::StringRef help_text, size_t max_word_len);
335
336   // this mimics OutputFormattedHelpText but it does perform a much simpler
337   // formatting, basically ensuring line alignment. This is only good if you
338   // have some complicated layout for your help text and want as little help as
339   // reasonable in properly displaying it. Most of the times, you simply want
340   // to type some text and have it printed in a reasonable way on screen. If
341   // so, use OutputFormattedHelpText
342   void OutputHelpText(Stream &stream, llvm::StringRef command_word,
343                       llvm::StringRef separator, llvm::StringRef help_text,
344                       uint32_t max_word_len);
345
346   Debugger &GetDebugger() { return m_debugger; }
347
348   ExecutionContext GetExecutionContext() {
349     const bool thread_and_frame_only_if_stopped = true;
350     return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped);
351   }
352
353   void UpdateExecutionContext(ExecutionContext *override_context);
354
355   lldb::PlatformSP GetPlatform(bool prefer_target_platform);
356
357   const char *ProcessEmbeddedScriptCommands(const char *arg);
358
359   void UpdatePrompt(llvm::StringRef prompt);
360
361   bool Confirm(llvm::StringRef message, bool default_answer);
362
363   void LoadCommandDictionary();
364
365   void Initialize();
366
367   void Clear();
368
369   void SetScriptLanguage(lldb::ScriptLanguage lang);
370
371   bool HasCommands() const;
372
373   bool HasAliases() const;
374
375   bool HasUserCommands() const;
376
377   bool HasAliasOptions() const;
378
379   void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
380                              const char *alias_name, Args &cmd_args,
381                              std::string &raw_input_string,
382                              CommandReturnObject &result);
383
384   int GetOptionArgumentPosition(const char *in_string);
385
386   ScriptInterpreter *GetScriptInterpreter(bool can_create = true);
387
388   void SetScriptInterpreter();
389
390   void SkipLLDBInitFiles(bool skip_lldbinit_files) {
391     m_skip_lldbinit_files = skip_lldbinit_files;
392   }
393
394   void SkipAppInitFiles(bool skip_app_init_files) {
395     m_skip_app_init_files = m_skip_lldbinit_files;
396   }
397
398   bool GetSynchronous();
399
400   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
401                               StringList &commands_help,
402                               bool search_builtin_commands,
403                               bool search_user_commands,
404                               bool search_alias_commands);
405
406   bool GetBatchCommandMode() { return m_batch_command_mode; }
407
408   bool SetBatchCommandMode(bool value) {
409     const bool old_value = m_batch_command_mode;
410     m_batch_command_mode = value;
411     return old_value;
412   }
413
414   void ChildrenTruncated() {
415     if (m_truncation_warning == eNoTruncation)
416       m_truncation_warning = eUnwarnedTruncation;
417   }
418
419   bool TruncationWarningNecessary() {
420     return (m_truncation_warning == eUnwarnedTruncation);
421   }
422
423   void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
424
425   const char *TruncationWarningText() {
426     return "*** Some of your variables have more members than the debugger "
427            "will show by default. To show all of them, you can either use the "
428            "--show-all-children option to %s or raise the limit by changing "
429            "the target.max-children-count setting.\n";
430   }
431
432   const CommandHistory &GetCommandHistory() const { return m_command_history; }
433
434   CommandHistory &GetCommandHistory() { return m_command_history; }
435
436   bool IsActive();
437
438   void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
439                              CommandInterpreterRunOptions &options);
440   void GetLLDBCommandsFromIOHandler(const char *prompt,
441                                     IOHandlerDelegate &delegate,
442                                     bool asynchronously, void *baton);
443
444   void GetPythonCommandsFromIOHandler(const char *prompt,
445                                       IOHandlerDelegate &delegate,
446                                       bool asynchronously, void *baton);
447
448   const char *GetCommandPrefix();
449
450   //------------------------------------------------------------------
451   // Properties
452   //------------------------------------------------------------------
453   bool GetExpandRegexAliases() const;
454
455   bool GetPromptOnQuit() const;
456
457   void SetPromptOnQuit(bool b);
458
459   //------------------------------------------------------------------
460   /// Specify if the command interpreter should allow that the user can
461   /// specify a custom exit code when calling 'quit'.
462   //------------------------------------------------------------------
463   void AllowExitCodeOnQuit(bool allow);
464
465   //------------------------------------------------------------------
466   /// Sets the exit code for the quit command.
467   /// @param[in] exit_code
468   ///     The exit code that the driver should return on exit.
469   /// @return True if the exit code was successfully set; false if the
470   ///         interpreter doesn't allow custom exit codes.
471   /// @see AllowExitCodeOnQuit
472   //------------------------------------------------------------------
473   LLVM_NODISCARD bool SetQuitExitCode(int exit_code);
474
475   //------------------------------------------------------------------
476   /// Returns the exit code that the user has specified when running the
477   /// 'quit' command.
478   /// @param[out] exited
479   ///     Set to true if the user has called quit with a custom exit code.
480   //------------------------------------------------------------------
481   int GetQuitExitCode(bool &exited) const;
482
483   void ResolveCommand(const char *command_line, CommandReturnObject &result);
484
485   bool GetStopCmdSourceOnError() const;
486
487   uint32_t GetNumErrors() const { return m_num_errors; }
488
489   bool GetQuitRequested() const { return m_quit_requested; }
490
491   lldb::IOHandlerSP
492   GetIOHandler(bool force_create = false,
493                CommandInterpreterRunOptions *options = nullptr);
494
495   bool GetStoppedForCrash() const { return m_stopped_for_crash; }
496
497   bool GetSpaceReplPrompts() const;
498
499 protected:
500   friend class Debugger;
501
502   //------------------------------------------------------------------
503   // IOHandlerDelegate functions
504   //------------------------------------------------------------------
505   void IOHandlerInputComplete(IOHandler &io_handler,
506                               std::string &line) override;
507
508   ConstString IOHandlerGetControlSequence(char ch) override {
509     if (ch == 'd')
510       return ConstString("quit\n");
511     return ConstString();
512   }
513
514   bool IOHandlerInterrupt(IOHandler &io_handler) override;
515
516   size_t GetProcessOutput();
517
518   void SetSynchronous(bool value);
519
520   lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
521                                      bool include_aliases = true,
522                                      bool exact = true,
523                                      StringList *matches = nullptr) const;
524
525 private:
526   Status PreprocessCommand(std::string &command);
527
528   // Completely resolves aliases and abbreviations, returning a pointer to the
529   // final command object and updating command_line to the fully substituted
530   // and translated command.
531   CommandObject *ResolveCommandImpl(std::string &command_line,
532                                     CommandReturnObject &result);
533
534   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
535                               StringList &commands_help,
536                               CommandObject::CommandMap &command_map);
537
538   // An interruptible wrapper around the stream output
539   void PrintCommandOutput(Stream &stream, llvm::StringRef str);
540
541   // A very simple state machine which models the command handling transitions
542   enum class CommandHandlingState {
543     eIdle,
544     eInProgress,
545     eInterrupted,
546   };
547
548   std::atomic<CommandHandlingState> m_command_state{
549       CommandHandlingState::eIdle};
550
551   int m_iohandler_nesting_level = 0;
552
553   void StartHandlingCommand();
554   void FinishHandlingCommand();
555   bool InterruptCommand();
556
557   Debugger &m_debugger; // The debugger session that this interpreter is
558                         // associated with
559   ExecutionContextRef m_exe_ctx_ref; // The current execution context to use
560                                      // when handling commands
561   bool m_synchronous_execution;
562   bool m_skip_lldbinit_files;
563   bool m_skip_app_init_files;
564   CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
565                                             // (they cannot be deleted, removed
566                                             // or overwritten).
567   CommandObject::CommandMap
568       m_alias_dict; // Stores user aliases/abbreviations for commands
569   CommandObject::CommandMap m_user_dict; // Stores user-defined commands
570   CommandHistory m_command_history;
571   std::string m_repeat_command; // Stores the command that will be executed for
572                                 // an empty command string.
573   lldb::ScriptInterpreterSP m_script_interpreter_sp;
574   std::recursive_mutex m_script_interpreter_mutex;
575   lldb::IOHandlerSP m_command_io_handler_sp;
576   char m_comment_char;
577   bool m_batch_command_mode;
578   ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated
579                                                        // children and whether
580                                                        // the user has been told
581   uint32_t m_command_source_depth;
582   std::vector<uint32_t> m_command_source_flags;
583   uint32_t m_num_errors;
584   bool m_quit_requested;
585   bool m_stopped_for_crash;
586
587   // The exit code the user has requested when calling the 'quit' command.
588   // No value means the user hasn't set a custom exit code so far.
589   llvm::Optional<int> m_quit_exit_code;
590   // If the driver is accepts custom exit codes for the 'quit' command.
591   bool m_allow_exit_code = false;
592 };
593
594 } // namespace lldb_private
595
596 #endif // liblldb_CommandInterpreter_h_