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 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.
312   void HandleCompletion(CompletionRequest &request);
313 
314   // This version just returns matches, and doesn't compute the substring. It
315   // is here so the Help command can call it for the first argument.
316   void HandleCompletionMatches(CompletionRequest &request);
317 
318   int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
319                                            bool include_aliases,
320                                            StringList &matches,
321                                            StringList &descriptions);
322 
323   void GetHelp(CommandReturnObject &result,
324                uint32_t types = eCommandTypesAllThem);
325 
326   void GetAliasHelp(const char *alias_name, StreamString &help_string);
327 
328   void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
329                                llvm::StringRef help_text);
330 
331   void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
332                                llvm::StringRef separator,
333                                llvm::StringRef help_text, size_t max_word_len);
334 
335   // this mimics OutputFormattedHelpText but it does perform a much simpler
336   // formatting, basically ensuring line alignment. This is only good if you
337   // have some complicated layout for your help text and want as little help as
338   // reasonable in properly displaying it. Most of the times, you simply want
339   // to type some text and have it printed in a reasonable way on screen. If
340   // so, use OutputFormattedHelpText
341   void OutputHelpText(Stream &stream, llvm::StringRef command_word,
342                       llvm::StringRef separator, llvm::StringRef help_text,
343                       uint32_t max_word_len);
344 
345   Debugger &GetDebugger() { return m_debugger; }
346 
347   ExecutionContext GetExecutionContext() {
348     const bool thread_and_frame_only_if_stopped = true;
349     return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped);
350   }
351 
352   void UpdateExecutionContext(ExecutionContext *override_context);
353 
354   lldb::PlatformSP GetPlatform(bool prefer_target_platform);
355 
356   const char *ProcessEmbeddedScriptCommands(const char *arg);
357 
358   void UpdatePrompt(llvm::StringRef prompt);
359 
360   bool Confirm(llvm::StringRef message, bool default_answer);
361 
362   void LoadCommandDictionary();
363 
364   void Initialize();
365 
366   void Clear();
367 
368   bool HasCommands() const;
369 
370   bool HasAliases() const;
371 
372   bool HasUserCommands() const;
373 
374   bool HasAliasOptions() const;
375 
376   void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
377                              const char *alias_name, Args &cmd_args,
378                              std::string &raw_input_string,
379                              CommandReturnObject &result);
380 
381   int GetOptionArgumentPosition(const char *in_string);
382 
383   void SkipLLDBInitFiles(bool skip_lldbinit_files) {
384     m_skip_lldbinit_files = skip_lldbinit_files;
385   }
386 
387   void SkipAppInitFiles(bool skip_app_init_files) {
388     m_skip_app_init_files = skip_app_init_files;
389   }
390 
391   bool GetSynchronous();
392 
393   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
394                               StringList &commands_help,
395                               bool search_builtin_commands,
396                               bool search_user_commands,
397                               bool search_alias_commands);
398 
399   bool GetBatchCommandMode() { return m_batch_command_mode; }
400 
401   bool SetBatchCommandMode(bool value) {
402     const bool old_value = m_batch_command_mode;
403     m_batch_command_mode = value;
404     return old_value;
405   }
406 
407   void ChildrenTruncated() {
408     if (m_truncation_warning == eNoTruncation)
409       m_truncation_warning = eUnwarnedTruncation;
410   }
411 
412   bool TruncationWarningNecessary() {
413     return (m_truncation_warning == eUnwarnedTruncation);
414   }
415 
416   void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
417 
418   const char *TruncationWarningText() {
419     return "*** Some of your variables have more members than the debugger "
420            "will show by default. To show all of them, you can either use the "
421            "--show-all-children option to %s or raise the limit by changing "
422            "the target.max-children-count setting.\n";
423   }
424 
425   CommandHistory &GetCommandHistory() { return m_command_history; }
426 
427   bool IsActive();
428 
429   void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
430                              CommandInterpreterRunOptions &options);
431 
432   void GetLLDBCommandsFromIOHandler(const char *prompt,
433                                     IOHandlerDelegate &delegate,
434                                     void *baton = nullptr);
435 
436   void GetPythonCommandsFromIOHandler(const char *prompt,
437                                       IOHandlerDelegate &delegate,
438                                       void *baton = nullptr);
439 
440   const char *GetCommandPrefix();
441 
442   // Properties
443   bool GetExpandRegexAliases() const;
444 
445   bool GetPromptOnQuit() const;
446 
447   void SetPromptOnQuit(bool enable);
448 
449   bool GetEchoCommands() const;
450   void SetEchoCommands(bool enable);
451 
452   bool GetEchoCommentCommands() const;
453   void SetEchoCommentCommands(bool enable);
454 
455   /// Specify if the command interpreter should allow that the user can
456   /// specify a custom exit code when calling 'quit'.
457   void AllowExitCodeOnQuit(bool allow);
458 
459   /// Sets the exit code for the quit command.
460   /// \param[in] exit_code
461   ///     The exit code that the driver should return on exit.
462   /// \return True if the exit code was successfully set; false if the
463   ///         interpreter doesn't allow custom exit codes.
464   /// \see AllowExitCodeOnQuit
465   LLVM_NODISCARD bool SetQuitExitCode(int exit_code);
466 
467   /// Returns the exit code that the user has specified when running the
468   /// 'quit' command.
469   /// \param[out] exited
470   ///     Set to true if the user has called quit with a custom exit code.
471   int GetQuitExitCode(bool &exited) const;
472 
473   void ResolveCommand(const char *command_line, CommandReturnObject &result);
474 
475   bool GetStopCmdSourceOnError() const;
476 
477   uint32_t GetNumErrors() const { return m_num_errors; }
478 
479   bool GetQuitRequested() const { return m_quit_requested; }
480 
481   lldb::IOHandlerSP
482   GetIOHandler(bool force_create = false,
483                CommandInterpreterRunOptions *options = nullptr);
484 
485   bool GetStoppedForCrash() const { return m_stopped_for_crash; }
486 
487   bool GetSpaceReplPrompts() const;
488 
489 protected:
490   friend class Debugger;
491 
492   // IOHandlerDelegate functions
493   void IOHandlerInputComplete(IOHandler &io_handler,
494                               std::string &line) override;
495 
496   ConstString IOHandlerGetControlSequence(char ch) override {
497     if (ch == 'd')
498       return ConstString("quit\n");
499     return ConstString();
500   }
501 
502   bool IOHandlerInterrupt(IOHandler &io_handler) override;
503 
504   void GetProcessOutput();
505 
506   bool DidProcessStopAbnormally() const;
507 
508   void SetSynchronous(bool value);
509 
510   lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
511                                      bool include_aliases = true,
512                                      bool exact = true,
513                                      StringList *matches = nullptr,
514                                      StringList *descriptions = nullptr) const;
515 
516 private:
517   Status PreprocessCommand(std::string &command);
518 
519   void SourceInitFile(FileSpec file, CommandReturnObject &result);
520 
521   // Completely resolves aliases and abbreviations, returning a pointer to the
522   // final command object and updating command_line to the fully substituted
523   // and translated command.
524   CommandObject *ResolveCommandImpl(std::string &command_line,
525                                     CommandReturnObject &result);
526 
527   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
528                               StringList &commands_help,
529                               CommandObject::CommandMap &command_map);
530 
531   // An interruptible wrapper around the stream output
532   void PrintCommandOutput(Stream &stream, llvm::StringRef str);
533 
534   bool EchoCommandNonInteractive(llvm::StringRef line,
535                                  const Flags &io_handler_flags) const;
536 
537   // A very simple state machine which models the command handling transitions
538   enum class CommandHandlingState {
539     eIdle,
540     eInProgress,
541     eInterrupted,
542   };
543 
544   std::atomic<CommandHandlingState> m_command_state{
545       CommandHandlingState::eIdle};
546 
547   int m_iohandler_nesting_level = 0;
548 
549   void StartHandlingCommand();
550   void FinishHandlingCommand();
551   bool InterruptCommand();
552 
553   Debugger &m_debugger; // The debugger session that this interpreter is
554                         // associated with
555   ExecutionContextRef m_exe_ctx_ref; // The current execution context to use
556                                      // when handling commands
557   bool m_synchronous_execution;
558   bool m_skip_lldbinit_files;
559   bool m_skip_app_init_files;
560   CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
561                                             // (they cannot be deleted, removed
562                                             // or overwritten).
563   CommandObject::CommandMap
564       m_alias_dict; // Stores user aliases/abbreviations for commands
565   CommandObject::CommandMap m_user_dict; // Stores user-defined commands
566   CommandHistory m_command_history;
567   std::string m_repeat_command; // Stores the command that will be executed for
568                                 // an empty command string.
569   lldb::IOHandlerSP m_command_io_handler_sp;
570   char m_comment_char;
571   bool m_batch_command_mode;
572   ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated
573                                                        // children and whether
574                                                        // the user has been told
575   uint32_t m_command_source_depth;
576   std::vector<uint32_t> m_command_source_flags;
577   uint32_t m_num_errors;
578   bool m_quit_requested;
579   bool m_stopped_for_crash;
580 
581   // The exit code the user has requested when calling the 'quit' command.
582   // No value means the user hasn't set a custom exit code so far.
583   llvm::Optional<int> m_quit_exit_code;
584   // If the driver is accepts custom exit codes for the 'quit' command.
585   bool m_allow_exit_code = false;
586 };
587 
588 } // namespace lldb_private
589 
590 #endif // liblldb_CommandInterpreter_h_
591