Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:42:49

0001 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLDB_INTERPRETER_COMMANDINTERPRETER_H
0010 #define LLDB_INTERPRETER_COMMANDINTERPRETER_H
0011 
0012 #include "lldb/Core/Debugger.h"
0013 #include "lldb/Core/IOHandler.h"
0014 #include "lldb/Interpreter/CommandAlias.h"
0015 #include "lldb/Interpreter/CommandHistory.h"
0016 #include "lldb/Interpreter/CommandObject.h"
0017 #include "lldb/Interpreter/ScriptInterpreter.h"
0018 #include "lldb/Utility/Args.h"
0019 #include "lldb/Utility/Broadcaster.h"
0020 #include "lldb/Utility/CompletionRequest.h"
0021 #include "lldb/Utility/Event.h"
0022 #include "lldb/Utility/Log.h"
0023 #include "lldb/Utility/StreamString.h"
0024 #include "lldb/Utility/StringList.h"
0025 #include "lldb/Utility/StructuredData.h"
0026 #include "lldb/lldb-forward.h"
0027 #include "lldb/lldb-private.h"
0028 
0029 #include <mutex>
0030 #include <optional>
0031 #include <stack>
0032 #include <unordered_map>
0033 
0034 namespace lldb_private {
0035 class CommandInterpreter;
0036 
0037 class CommandInterpreterRunResult {
0038 public:
0039   CommandInterpreterRunResult() = default;
0040 
0041   uint32_t GetNumErrors() const { return m_num_errors; }
0042 
0043   lldb::CommandInterpreterResult GetResult() const { return m_result; }
0044 
0045   bool IsResult(lldb::CommandInterpreterResult result) {
0046     return m_result == result;
0047   }
0048 
0049 protected:
0050   friend CommandInterpreter;
0051 
0052   void IncrementNumberOfErrors() { m_num_errors++; }
0053 
0054   void SetResult(lldb::CommandInterpreterResult result) { m_result = result; }
0055 
0056 private:
0057   int m_num_errors = 0;
0058   lldb::CommandInterpreterResult m_result =
0059       lldb::eCommandInterpreterResultSuccess;
0060 };
0061 
0062 class CommandInterpreterRunOptions {
0063 public:
0064   /// Construct a CommandInterpreterRunOptions object. This class is used to
0065   /// control all the instances where we run multiple commands, e.g.
0066   /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
0067   ///
0068   /// The meanings of the options in this object are:
0069   ///
0070   /// \param[in] stop_on_continue
0071   ///    If \b true, execution will end on the first command that causes the
0072   ///    process in the execution context to continue. If \b false, we won't
0073   ///    check the execution status.
0074   /// \param[in] stop_on_error
0075   ///    If \b true, execution will end on the first command that causes an
0076   ///    error.
0077   /// \param[in] stop_on_crash
0078   ///    If \b true, when a command causes the target to run, and the end of the
0079   ///    run is a signal or exception, stop executing the commands.
0080   /// \param[in] echo_commands
0081   ///    If \b true, echo the command before executing it. If \b false, execute
0082   ///    silently.
0083   /// \param[in] echo_comments
0084   ///    If \b true, echo command even if it is a pure comment line. If
0085   ///    \b false, print no ouput in this case. This setting has an effect only
0086   ///    if echo_commands is \b true.
0087   /// \param[in] print_results
0088   ///    If \b true and the command succeeds, print the results of the command
0089   ///    after executing it. If \b false, execute silently.
0090   /// \param[in] print_errors
0091   ///    If \b true and the command fails, print the results of the command
0092   ///    after executing it. If \b false, execute silently.
0093   /// \param[in] add_to_history
0094   ///    If \b true add the commands to the command history. If \b false, don't
0095   ///    add them.
0096   /// \param[in] handle_repeats
0097   ///    If \b true then treat empty lines as repeat commands even if the
0098   ///    interpreter is non-interactive.
0099   CommandInterpreterRunOptions(LazyBool stop_on_continue,
0100                                LazyBool stop_on_error, LazyBool stop_on_crash,
0101                                LazyBool echo_commands, LazyBool echo_comments,
0102                                LazyBool print_results, LazyBool print_errors,
0103                                LazyBool add_to_history,
0104                                LazyBool handle_repeats)
0105       : m_stop_on_continue(stop_on_continue), m_stop_on_error(stop_on_error),
0106         m_stop_on_crash(stop_on_crash), m_echo_commands(echo_commands),
0107         m_echo_comment_commands(echo_comments), m_print_results(print_results),
0108         m_print_errors(print_errors), m_add_to_history(add_to_history),
0109         m_allow_repeats(handle_repeats) {}
0110 
0111   CommandInterpreterRunOptions() = default;
0112 
0113   void SetSilent(bool silent) {
0114     LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
0115 
0116     m_print_results = value;
0117     m_print_errors = value;
0118     m_echo_commands = value;
0119     m_echo_comment_commands = value;
0120     m_add_to_history = value;
0121   }
0122   // These return the default behaviors if the behavior is not
0123   // eLazyBoolCalculate. But I've also left the ivars public since for
0124   // different ways of running the interpreter you might want to force
0125   // different defaults...  In that case, just grab the LazyBool ivars directly
0126   // and do what you want with eLazyBoolCalculate.
0127   bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); }
0128 
0129   void SetStopOnContinue(bool stop_on_continue) {
0130     m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
0131   }
0132 
0133   bool GetStopOnError() const { return DefaultToNo(m_stop_on_error); }
0134 
0135   void SetStopOnError(bool stop_on_error) {
0136     m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
0137   }
0138 
0139   bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
0140 
0141   void SetStopOnCrash(bool stop_on_crash) {
0142     m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
0143   }
0144 
0145   bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
0146 
0147   void SetEchoCommands(bool echo_commands) {
0148     m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
0149   }
0150 
0151   bool GetEchoCommentCommands() const {
0152     return DefaultToYes(m_echo_comment_commands);
0153   }
0154 
0155   void SetEchoCommentCommands(bool echo_comments) {
0156     m_echo_comment_commands = echo_comments ? eLazyBoolYes : eLazyBoolNo;
0157   }
0158 
0159   bool GetPrintResults() const { return DefaultToYes(m_print_results); }
0160 
0161   void SetPrintResults(bool print_results) {
0162     m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
0163   }
0164 
0165   bool GetPrintErrors() const { return DefaultToYes(m_print_errors); }
0166 
0167   void SetPrintErrors(bool print_errors) {
0168     m_print_errors = print_errors ? eLazyBoolYes : eLazyBoolNo;
0169   }
0170 
0171   bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
0172 
0173   void SetAddToHistory(bool add_to_history) {
0174     m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
0175   }
0176 
0177   bool GetAutoHandleEvents() const {
0178     return DefaultToYes(m_auto_handle_events);
0179   }
0180 
0181   void SetAutoHandleEvents(bool auto_handle_events) {
0182     m_auto_handle_events = auto_handle_events ? eLazyBoolYes : eLazyBoolNo;
0183   }
0184 
0185   bool GetSpawnThread() const { return DefaultToNo(m_spawn_thread); }
0186 
0187   void SetSpawnThread(bool spawn_thread) {
0188     m_spawn_thread = spawn_thread ? eLazyBoolYes : eLazyBoolNo;
0189   }
0190 
0191   bool GetAllowRepeats() const { return DefaultToNo(m_allow_repeats); }
0192 
0193   void SetAllowRepeats(bool allow_repeats) {
0194     m_allow_repeats = allow_repeats ? eLazyBoolYes : eLazyBoolNo;
0195   }
0196 
0197   LazyBool m_stop_on_continue = eLazyBoolCalculate;
0198   LazyBool m_stop_on_error = eLazyBoolCalculate;
0199   LazyBool m_stop_on_crash = eLazyBoolCalculate;
0200   LazyBool m_echo_commands = eLazyBoolCalculate;
0201   LazyBool m_echo_comment_commands = eLazyBoolCalculate;
0202   LazyBool m_print_results = eLazyBoolCalculate;
0203   LazyBool m_print_errors = eLazyBoolCalculate;
0204   LazyBool m_add_to_history = eLazyBoolCalculate;
0205   LazyBool m_auto_handle_events;
0206   LazyBool m_spawn_thread;
0207   LazyBool m_allow_repeats = eLazyBoolCalculate;
0208 
0209 private:
0210   static bool DefaultToYes(LazyBool flag) {
0211     switch (flag) {
0212     case eLazyBoolNo:
0213       return false;
0214     default:
0215       return true;
0216     }
0217   }
0218 
0219   static bool DefaultToNo(LazyBool flag) {
0220     switch (flag) {
0221     case eLazyBoolYes:
0222       return true;
0223     default:
0224       return false;
0225     }
0226   }
0227 };
0228 
0229 class CommandInterpreter : public Broadcaster,
0230                            public Properties,
0231                            public IOHandlerDelegate {
0232 public:
0233   enum {
0234     eBroadcastBitThreadShouldExit = (1 << 0),
0235     eBroadcastBitResetPrompt = (1 << 1),
0236     eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
0237     eBroadcastBitAsynchronousOutputData = (1 << 3),
0238     eBroadcastBitAsynchronousErrorData = (1 << 4)
0239   };
0240 
0241   /// Tristate boolean to manage children omission warnings.
0242   enum ChildrenOmissionWarningStatus {
0243     eNoOmission = 0,       ///< No children were omitted.
0244     eUnwarnedOmission = 1, ///< Children omitted, and not yet notified.
0245     eWarnedOmission = 2    ///< Children omitted and notified.
0246   };
0247 
0248   enum CommandTypes {
0249     eCommandTypesBuiltin = 0x0001, //< native commands such as "frame"
0250     eCommandTypesUserDef = 0x0002, //< scripted commands
0251     eCommandTypesUserMW  = 0x0004, //< multiword commands (command containers)
0252     eCommandTypesAliases = 0x0008, //< aliases such as "po"
0253     eCommandTypesHidden  = 0x0010, //< commands prefixed with an underscore
0254     eCommandTypesAllThem = 0xFFFF  //< all commands
0255   };
0256 
0257   // The CommandAlias and CommandInterpreter both have a hand in 
0258   // substituting for alias commands.  They work by writing special tokens
0259   // in the template form of the Alias command, and then detecting them when the
0260   // command is executed.  These are the special tokens:
0261   static const char *g_no_argument;
0262   static const char *g_need_argument;
0263   static const char *g_argument;
0264 
0265   CommandInterpreter(Debugger &debugger, bool synchronous_execution);
0266 
0267   ~CommandInterpreter() override = default;
0268 
0269   // These two functions fill out the Broadcaster interface:
0270 
0271   static llvm::StringRef GetStaticBroadcasterClass();
0272 
0273   llvm::StringRef GetBroadcasterClass() const override {
0274     return GetStaticBroadcasterClass();
0275   }
0276 
0277   void SourceInitFileCwd(CommandReturnObject &result);
0278   void SourceInitFileHome(CommandReturnObject &result, bool is_repl);
0279   void SourceInitFileGlobal(CommandReturnObject &result);
0280 
0281   bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
0282                   bool can_replace);
0283 
0284   Status AddUserCommand(llvm::StringRef name,
0285                         const lldb::CommandObjectSP &cmd_sp, bool can_replace);
0286 
0287   lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
0288                                           bool include_aliases = false) const;
0289 
0290   CommandObject *GetCommandObject(llvm::StringRef cmd,
0291                                   StringList *matches = nullptr,
0292                                   StringList *descriptions = nullptr) const;
0293 
0294   CommandObject *GetUserCommandObject(llvm::StringRef cmd,
0295                                       StringList *matches = nullptr,
0296                                       StringList *descriptions = nullptr) const;
0297 
0298   CommandObject *
0299   GetAliasCommandObject(llvm::StringRef cmd, StringList *matches = nullptr,
0300                         StringList *descriptions = nullptr) const;
0301 
0302   /// Determine whether a root level, built-in command with this name exists.
0303   bool CommandExists(llvm::StringRef cmd) const;
0304 
0305   /// Determine whether an alias command with this name exists
0306   bool AliasExists(llvm::StringRef cmd) const;
0307 
0308   /// Determine whether a root-level user command with this name exists.
0309   bool UserCommandExists(llvm::StringRef cmd) const;
0310 
0311   /// Determine whether a root-level user multiword command with this name
0312   /// exists.
0313   bool UserMultiwordCommandExists(llvm::StringRef cmd) const;
0314 
0315   /// Look up the command pointed to by path encoded in the arguments of
0316   /// the incoming command object.  If all the path components exist
0317   /// and are all actual commands - not aliases, and the leaf command is a
0318   /// multiword command, return the command.  Otherwise return nullptr, and put
0319   /// a useful diagnostic in the Status object.
0320   ///
0321   /// \param[in] path
0322   ///    An Args object holding the path in its arguments
0323   /// \param[in] leaf_is_command
0324   ///    If true, return the container of the leaf name rather than looking up
0325   ///    the whole path as a leaf command.  The leaf needn't exist in this case.
0326   /// \param[in,out] result
0327   ///    If the path is not found, this error shows where we got off track.
0328   /// \return
0329   ///    If found, a pointer to the CommandObjectMultiword pointed to by path,
0330   ///    or to the container of the leaf element is is_leaf_command.
0331   ///    Returns nullptr under two circumstances:
0332   ///      1) The command in not found (check error.Fail)
0333   ///      2) is_leaf is true and the path has only a leaf.  We don't have a
0334   ///         dummy "contains everything MWC, so we return null here, but
0335   ///         in this case error.Success is true.
0336 
0337   CommandObjectMultiword *VerifyUserMultiwordCmdPath(Args &path,
0338                                                      bool leaf_is_command,
0339                                                      Status &result);
0340 
0341   CommandAlias *AddAlias(llvm::StringRef alias_name,
0342                          lldb::CommandObjectSP &command_obj_sp,
0343                          llvm::StringRef args_string = llvm::StringRef());
0344 
0345   /// Remove a command if it is removable (python or regex command). If \b force
0346   /// is provided, the command is removed regardless of its removable status.
0347   bool RemoveCommand(llvm::StringRef cmd, bool force = false);
0348 
0349   bool RemoveAlias(llvm::StringRef alias_name);
0350 
0351   bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
0352 
0353   bool RemoveUserMultiword(llvm::StringRef multiword_name);
0354 
0355   // Do we want to allow top-level user multiword commands to be deleted?
0356   void RemoveAllUserMultiword() { m_user_mw_dict.clear(); }
0357 
0358   bool RemoveUser(llvm::StringRef alias_name);
0359 
0360   void RemoveAllUser() { m_user_dict.clear(); }
0361 
0362   const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
0363 
0364   CommandObject *BuildAliasResult(llvm::StringRef alias_name,
0365                                   std::string &raw_input_string,
0366                                   std::string &alias_result,
0367                                   CommandReturnObject &result);
0368 
0369   bool HandleCommand(const char *command_line, LazyBool add_to_history,
0370                      const ExecutionContext &override_context,
0371                      CommandReturnObject &result);
0372 
0373   bool HandleCommand(const char *command_line, LazyBool add_to_history,
0374                      CommandReturnObject &result,
0375                      bool force_repeat_command = false);
0376 
0377   bool InterruptCommand();
0378 
0379   /// Execute a list of commands in sequence.
0380   ///
0381   /// \param[in] commands
0382   ///    The list of commands to execute.
0383   /// \param[in,out] context
0384   ///    The execution context in which to run the commands.
0385   /// \param[in] options
0386   ///    This object holds the options used to control when to stop, whether to
0387   ///    execute commands,
0388   ///    etc.
0389   /// \param[out] result
0390   ///    This is marked as succeeding with no output if all commands execute
0391   ///    safely,
0392   ///    and failed with some explanation if we aborted executing the commands
0393   ///    at some point.
0394   void HandleCommands(const StringList &commands,
0395                       const ExecutionContext &context,
0396                       const CommandInterpreterRunOptions &options,
0397                       CommandReturnObject &result);
0398 
0399   void HandleCommands(const StringList &commands,
0400                       const CommandInterpreterRunOptions &options,
0401                       CommandReturnObject &result);
0402 
0403   /// Execute a list of commands from a file.
0404   ///
0405   /// \param[in] file
0406   ///    The file from which to read in commands.
0407   /// \param[in,out] context
0408   ///    The execution context in which to run the commands.
0409   /// \param[in] options
0410   ///    This object holds the options used to control when to stop, whether to
0411   ///    execute commands,
0412   ///    etc.
0413   /// \param[out] result
0414   ///    This is marked as succeeding with no output if all commands execute
0415   ///    safely,
0416   ///    and failed with some explanation if we aborted executing the commands
0417   ///    at some point.
0418   void HandleCommandsFromFile(FileSpec &file, const ExecutionContext &context,
0419                               const CommandInterpreterRunOptions &options,
0420                               CommandReturnObject &result);
0421 
0422   void HandleCommandsFromFile(FileSpec &file,
0423                               const CommandInterpreterRunOptions &options,
0424                               CommandReturnObject &result);
0425 
0426   CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
0427 
0428   /// Returns the auto-suggestion string that should be added to the given
0429   /// command line.
0430   std::optional<std::string> GetAutoSuggestionForCommand(llvm::StringRef line);
0431 
0432   // This handles command line completion.
0433   void HandleCompletion(CompletionRequest &request);
0434 
0435   // This version just returns matches, and doesn't compute the substring. It
0436   // is here so the Help command can call it for the first argument.
0437   void HandleCompletionMatches(CompletionRequest &request);
0438 
0439   int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
0440                                            bool include_aliases,
0441                                            StringList &matches,
0442                                            StringList &descriptions);
0443 
0444   void GetHelp(CommandReturnObject &result,
0445                uint32_t types = eCommandTypesAllThem);
0446 
0447   void GetAliasHelp(const char *alias_name, StreamString &help_string);
0448 
0449   void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
0450                                llvm::StringRef help_text);
0451 
0452   void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
0453                                llvm::StringRef separator,
0454                                llvm::StringRef help_text, size_t max_word_len);
0455 
0456   // this mimics OutputFormattedHelpText but it does perform a much simpler
0457   // formatting, basically ensuring line alignment. This is only good if you
0458   // have some complicated layout for your help text and want as little help as
0459   // reasonable in properly displaying it. Most of the times, you simply want
0460   // to type some text and have it printed in a reasonable way on screen. If
0461   // so, use OutputFormattedHelpText
0462   void OutputHelpText(Stream &stream, llvm::StringRef command_word,
0463                       llvm::StringRef separator, llvm::StringRef help_text,
0464                       uint32_t max_word_len);
0465 
0466   Debugger &GetDebugger() { return m_debugger; }
0467 
0468   ExecutionContext GetExecutionContext() const;
0469 
0470   lldb::PlatformSP GetPlatform(bool prefer_target_platform);
0471 
0472   const char *ProcessEmbeddedScriptCommands(const char *arg);
0473 
0474   void UpdatePrompt(llvm::StringRef prompt);
0475 
0476   bool Confirm(llvm::StringRef message, bool default_answer);
0477 
0478   void LoadCommandDictionary();
0479 
0480   void Initialize();
0481 
0482   void Clear();
0483 
0484   bool HasCommands() const;
0485 
0486   bool HasAliases() const;
0487 
0488   bool HasUserCommands() const;
0489 
0490   bool HasUserMultiwordCommands() const;
0491 
0492   bool HasAliasOptions() const;
0493 
0494   void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
0495                              const char *alias_name, Args &cmd_args,
0496                              std::string &raw_input_string,
0497                              CommandReturnObject &result);
0498 
0499   /// Picks the number out of a string of the form "%NNN", otherwise return 0.
0500   int GetOptionArgumentPosition(const char *in_string);
0501 
0502   void SkipLLDBInitFiles(bool skip_lldbinit_files) {
0503     m_skip_lldbinit_files = skip_lldbinit_files;
0504   }
0505 
0506   void SkipAppInitFiles(bool skip_app_init_files) {
0507     m_skip_app_init_files = skip_app_init_files;
0508   }
0509 
0510   bool GetSynchronous();
0511 
0512   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
0513                               StringList &commands_help,
0514                               bool search_builtin_commands,
0515                               bool search_user_commands,
0516                               bool search_alias_commands,
0517                               bool search_user_mw_commands);
0518 
0519   bool GetBatchCommandMode() { return m_batch_command_mode; }
0520 
0521   bool SetBatchCommandMode(bool value) {
0522     const bool old_value = m_batch_command_mode;
0523     m_batch_command_mode = value;
0524     return old_value;
0525   }
0526 
0527   void ChildrenTruncated() {
0528     if (m_truncation_warning == eNoOmission)
0529       m_truncation_warning = eUnwarnedOmission;
0530   }
0531 
0532   void SetReachedMaximumDepth() {
0533     if (m_max_depth_warning == eNoOmission)
0534       m_max_depth_warning = eUnwarnedOmission;
0535   }
0536 
0537   void PrintWarningsIfNecessary(Stream &s, const std::string &cmd_name) {
0538     if (m_truncation_warning == eUnwarnedOmission) {
0539       s.Printf("*** Some of the displayed variables have more members than the "
0540                "debugger will show by default. To show all of them, you can "
0541                "either use the --show-all-children option to %s or raise the "
0542                "limit by changing the target.max-children-count setting.\n",
0543                cmd_name.c_str());
0544       m_truncation_warning = eWarnedOmission;
0545     }
0546 
0547     if (m_max_depth_warning == eUnwarnedOmission) {
0548       s.Printf("*** Some of the displayed variables have a greater depth of "
0549                "members than the debugger will show by default. To increase "
0550                "the limit, use the --depth option to %s, or raise the limit by "
0551                "changing the target.max-children-depth setting.\n",
0552                cmd_name.c_str());
0553       m_max_depth_warning = eWarnedOmission;
0554     }
0555   }
0556 
0557   CommandHistory &GetCommandHistory() { return m_command_history; }
0558 
0559   bool IsActive();
0560 
0561   CommandInterpreterRunResult
0562   RunCommandInterpreter(CommandInterpreterRunOptions &options);
0563 
0564   void GetLLDBCommandsFromIOHandler(const char *prompt,
0565                                     IOHandlerDelegate &delegate,
0566                                     void *baton = nullptr);
0567 
0568   void GetPythonCommandsFromIOHandler(const char *prompt,
0569                                       IOHandlerDelegate &delegate,
0570                                       void *baton = nullptr);
0571 
0572   const char *GetCommandPrefix();
0573 
0574   // Properties
0575   bool GetExpandRegexAliases() const;
0576 
0577   bool GetPromptOnQuit() const;
0578   void SetPromptOnQuit(bool enable);
0579 
0580   bool GetSaveTranscript() const;
0581   void SetSaveTranscript(bool enable);
0582 
0583   bool GetSaveSessionOnQuit() const;
0584   void SetSaveSessionOnQuit(bool enable);
0585 
0586   bool GetOpenTranscriptInEditor() const;
0587   void SetOpenTranscriptInEditor(bool enable);
0588 
0589   FileSpec GetSaveSessionDirectory() const;
0590   void SetSaveSessionDirectory(llvm::StringRef path);
0591 
0592   bool GetEchoCommands() const;
0593   void SetEchoCommands(bool enable);
0594 
0595   bool GetEchoCommentCommands() const;
0596   void SetEchoCommentCommands(bool enable);
0597 
0598   bool GetRepeatPreviousCommand() const;
0599   
0600   bool GetRequireCommandOverwrite() const;
0601 
0602   const CommandObject::CommandMap &GetUserCommands() const {
0603     return m_user_dict;
0604   }
0605 
0606   const CommandObject::CommandMap &GetUserMultiwordCommands() const {
0607     return m_user_mw_dict;
0608   }
0609 
0610   const CommandObject::CommandMap &GetCommands() const {
0611     return m_command_dict;
0612   }
0613 
0614   const CommandObject::CommandMap &GetAliases() const { return m_alias_dict; }
0615 
0616   /// Specify if the command interpreter should allow that the user can
0617   /// specify a custom exit code when calling 'quit'.
0618   void AllowExitCodeOnQuit(bool allow);
0619 
0620   /// Sets the exit code for the quit command.
0621   /// \param[in] exit_code
0622   ///     The exit code that the driver should return on exit.
0623   /// \return True if the exit code was successfully set; false if the
0624   ///         interpreter doesn't allow custom exit codes.
0625   /// \see AllowExitCodeOnQuit
0626   [[nodiscard]] bool SetQuitExitCode(int exit_code);
0627 
0628   /// Returns the exit code that the user has specified when running the
0629   /// 'quit' command.
0630   /// \param[out] exited
0631   ///     Set to true if the user has called quit with a custom exit code.
0632   int GetQuitExitCode(bool &exited) const;
0633 
0634   void ResolveCommand(const char *command_line, CommandReturnObject &result);
0635 
0636   bool GetStopCmdSourceOnError() const;
0637 
0638   lldb::IOHandlerSP
0639   GetIOHandler(bool force_create = false,
0640                CommandInterpreterRunOptions *options = nullptr);
0641 
0642   bool GetSpaceReplPrompts() const;
0643 
0644   /// Save the current debugger session transcript to a file on disk.
0645   /// \param output_file
0646   ///     The file path to which the session transcript will be written. Since
0647   ///     the argument is optional, an arbitrary temporary file will be create
0648   ///     when no argument is passed.
0649   /// \param result
0650   ///     This is used to pass function output and error messages.
0651   /// \return \b true if the session transcript was successfully written to
0652   /// disk, \b false otherwise.
0653   bool SaveTranscript(CommandReturnObject &result,
0654                       std::optional<std::string> output_file = std::nullopt);
0655 
0656   FileSpec GetCurrentSourceDir();
0657 
0658   bool IsInteractive();
0659 
0660   bool IOHandlerInterrupt(IOHandler &io_handler) override;
0661 
0662   Status PreprocessCommand(std::string &command);
0663   Status PreprocessToken(std::string &token);
0664 
0665   void IncreaseCommandUsage(const CommandObject &cmd_obj) {
0666     ++m_command_usages[cmd_obj.GetCommandName()];
0667   }
0668 
0669   llvm::json::Value GetStatistics();
0670   const StructuredData::Array &GetTranscript() const;
0671 
0672 protected:
0673   friend class Debugger;
0674 
0675   // This checks just the RunCommandInterpreter interruption state.  It is only
0676   // meant to be used in Debugger::InterruptRequested
0677   bool WasInterrupted() const;
0678 
0679   // IOHandlerDelegate functions
0680   void IOHandlerInputComplete(IOHandler &io_handler,
0681                               std::string &line) override;
0682 
0683   llvm::StringRef IOHandlerGetControlSequence(char ch) override {
0684     static constexpr llvm::StringLiteral control_sequence("quit\n");
0685     if (ch == 'd')
0686       return control_sequence;
0687     return {};
0688   }
0689 
0690   void GetProcessOutput();
0691 
0692   bool DidProcessStopAbnormally() const;
0693 
0694   void SetSynchronous(bool value);
0695 
0696   lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
0697                                      bool include_aliases = true,
0698                                      bool exact = true,
0699                                      StringList *matches = nullptr,
0700                                      StringList *descriptions = nullptr) const;
0701 
0702 private:
0703   void OverrideExecutionContext(const ExecutionContext &override_context);
0704 
0705   void RestoreExecutionContext();
0706 
0707   void SourceInitFile(FileSpec file, CommandReturnObject &result);
0708 
0709   // Completely resolves aliases and abbreviations, returning a pointer to the
0710   // final command object and updating command_line to the fully substituted
0711   // and translated command.
0712   CommandObject *ResolveCommandImpl(std::string &command_line,
0713                                     CommandReturnObject &result);
0714 
0715   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
0716                               StringList &commands_help,
0717                               const CommandObject::CommandMap &command_map);
0718 
0719   // An interruptible wrapper around the stream output
0720   void PrintCommandOutput(IOHandler &io_handler, llvm::StringRef str,
0721                           bool is_stdout);
0722 
0723   bool EchoCommandNonInteractive(llvm::StringRef line,
0724                                  const Flags &io_handler_flags) const;
0725 
0726   // A very simple state machine which models the command handling transitions
0727   enum class CommandHandlingState {
0728     eIdle,
0729     eInProgress,
0730     eInterrupted,
0731   };
0732 
0733   std::atomic<CommandHandlingState> m_command_state{
0734       CommandHandlingState::eIdle};
0735 
0736   int m_iohandler_nesting_level = 0;
0737 
0738   void StartHandlingCommand();
0739   void FinishHandlingCommand();
0740 
0741   Debugger &m_debugger; // The debugger session that this interpreter is
0742                         // associated with
0743   // Execution contexts that were temporarily set by some of HandleCommand*
0744   // overloads.
0745   std::stack<ExecutionContext> m_overriden_exe_contexts;
0746   bool m_synchronous_execution;
0747   bool m_skip_lldbinit_files;
0748   bool m_skip_app_init_files;
0749   CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
0750                                             // (they cannot be deleted, removed
0751                                             // or overwritten).
0752   CommandObject::CommandMap
0753       m_alias_dict; // Stores user aliases/abbreviations for commands
0754   CommandObject::CommandMap m_user_dict; // Stores user-defined commands
0755   CommandObject::CommandMap
0756       m_user_mw_dict; // Stores user-defined multiword commands
0757   CommandHistory m_command_history;
0758   std::string m_repeat_command; // Stores the command that will be executed for
0759                                 // an empty command string.
0760   lldb::IOHandlerSP m_command_io_handler_sp;
0761   char m_comment_char;
0762   bool m_batch_command_mode;
0763   /// Whether we truncated a value's list of children and whether the user has
0764   /// been told.
0765   ChildrenOmissionWarningStatus m_truncation_warning;
0766   /// Whether we reached the maximum child nesting depth and whether the user
0767   /// has been told.
0768   ChildrenOmissionWarningStatus m_max_depth_warning;
0769 
0770   // FIXME: Stop using this to control adding to the history and then replace
0771   // this with m_command_source_dirs.size().
0772   uint32_t m_command_source_depth;
0773   /// A stack of directory paths. When not empty, the last one is the directory
0774   /// of the file that's currently sourced.
0775   std::vector<FileSpec> m_command_source_dirs;
0776   std::vector<uint32_t> m_command_source_flags;
0777   CommandInterpreterRunResult m_result;
0778 
0779   // The exit code the user has requested when calling the 'quit' command.
0780   // No value means the user hasn't set a custom exit code so far.
0781   std::optional<int> m_quit_exit_code;
0782   // If the driver is accepts custom exit codes for the 'quit' command.
0783   bool m_allow_exit_code = false;
0784 
0785   /// Command usage statistics.
0786   typedef llvm::StringMap<uint64_t> CommandUsageMap;
0787   CommandUsageMap m_command_usages;
0788 
0789   /// Turn on settings `interpreter.save-transcript` for LLDB to populate
0790   /// this stream. Otherwise this stream is empty.
0791   StreamString m_transcript_stream;
0792 
0793   /// Contains a list of handled commands and their details. Each element in
0794   /// the list is a dictionary with the following keys/values:
0795   /// - "command" (string): The command that was given by the user.
0796   /// - "commandName" (string): The name of the executed command.
0797   /// - "commandArguments" (string): The arguments of the executed command.
0798   /// - "output" (string): The output of the command. Empty ("") if no output.
0799   /// - "error" (string): The error of the command. Empty ("") if no error.
0800   /// - "durationInSeconds" (float): The time it took to execute the command.
0801   /// - "timestampInEpochSeconds" (int): The timestamp when the command is
0802   ///   executed.
0803   ///
0804   /// Turn on settings `interpreter.save-transcript` for LLDB to populate
0805   /// this list. Otherwise this list is empty.
0806   StructuredData::Array m_transcript;
0807 };
0808 
0809 } // namespace lldb_private
0810 
0811 #endif // LLDB_INTERPRETER_COMMANDINTERPRETER_H