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