1 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef liblldb_CommandInterpreter_h_
10 #define liblldb_CommandInterpreter_h_
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"
28 namespace lldb_private {
30 class CommandInterpreterRunOptions {
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.
36 /// The meanings of the options in this object are:
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
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
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
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) {}
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) {}
83 void SetSilent(bool silent) {
84 LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
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;
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); }
99 void SetStopOnContinue(bool stop_on_continue) {
100 m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
103 bool GetStopOnError() const { return DefaultToNo(m_stop_on_error); }
105 void SetStopOnError(bool stop_on_error) {
106 m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
109 bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
111 void SetStopOnCrash(bool stop_on_crash) {
112 m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
115 bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
117 void SetEchoCommands(bool echo_commands) {
118 m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
121 bool GetEchoCommentCommands() const {
122 return DefaultToYes(m_echo_comment_commands);
125 void SetEchoCommentCommands(bool echo_comments) {
126 m_echo_comment_commands = echo_comments ? eLazyBoolYes : eLazyBoolNo;
129 bool GetPrintResults() const { return DefaultToYes(m_print_results); }
131 void SetPrintResults(bool print_results) {
132 m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
135 bool GetPrintErrors() const { return DefaultToYes(m_print_errors); }
137 void SetPrintErrors(bool print_errors) {
138 m_print_errors = print_errors ? eLazyBoolYes : eLazyBoolNo;
141 bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
143 void SetAddToHistory(bool add_to_history) {
144 m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
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;
157 static bool DefaultToYes(LazyBool flag) {
166 static bool DefaultToNo(LazyBool flag) {
176 class CommandInterpreter : public Broadcaster,
178 public IOHandlerDelegate {
181 eBroadcastBitThreadShouldExit = (1 << 0),
182 eBroadcastBitResetPrompt = (1 << 1),
183 eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
184 eBroadcastBitAsynchronousOutputData = (1 << 3),
185 eBroadcastBitAsynchronousErrorData = (1 << 4)
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
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
203 CommandInterpreter(Debugger &debugger, bool synchronous_execution);
205 ~CommandInterpreter() override;
207 // These two functions fill out the Broadcaster interface:
209 static ConstString &GetStaticBroadcasterClass();
211 ConstString &GetBroadcasterClass() const override {
212 return GetStaticBroadcasterClass();
215 void SourceInitFileCwd(CommandReturnObject &result);
216 void SourceInitFileHome(CommandReturnObject &result);
218 bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
221 bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
224 lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
225 bool include_aliases) const;
227 CommandObject *GetCommandObject(llvm::StringRef cmd,
228 StringList *matches = nullptr,
229 StringList *descriptions = nullptr) const;
231 bool CommandExists(llvm::StringRef cmd) const;
233 bool AliasExists(llvm::StringRef cmd) const;
235 bool UserCommandExists(llvm::StringRef cmd) const;
237 CommandAlias *AddAlias(llvm::StringRef alias_name,
238 lldb::CommandObjectSP &command_obj_sp,
239 llvm::StringRef args_string = llvm::StringRef());
241 // Remove a command if it is removable (python or regex command)
242 bool RemoveCommand(llvm::StringRef cmd);
244 bool RemoveAlias(llvm::StringRef alias_name);
246 bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
248 bool RemoveUser(llvm::StringRef alias_name);
250 void RemoveAllUser() { m_user_dict.clear(); }
252 const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
254 CommandObject *BuildAliasResult(llvm::StringRef alias_name,
255 std::string &raw_input_string,
256 std::string &alias_result,
257 CommandReturnObject &result);
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);
265 bool WasInterrupted() const;
267 /// Execute a list of commands in sequence.
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,
279 /// \param[out] result
280 /// This is marked as succeeding with no output if all commands execute
282 /// and failed with some explanation if we aborted executing the commands
284 void HandleCommands(const StringList &commands, ExecutionContext *context,
285 CommandInterpreterRunOptions &options,
286 CommandReturnObject &result);
288 /// Execute a list of commands from a 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,
300 /// \param[out] result
301 /// This is marked as succeeding with no output if all commands execute
303 /// and failed with some explanation if we aborted executing the commands
305 void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context,
306 CommandInterpreterRunOptions &options,
307 CommandReturnObject &result);
309 CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
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.
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);
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);
337 int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
338 bool include_aliases,
340 StringList &descriptions);
342 void GetHelp(CommandReturnObject &result,
343 uint32_t types = eCommandTypesAllThem);
345 void GetAliasHelp(const char *alias_name, StreamString &help_string);
347 void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
348 llvm::StringRef help_text);
350 void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
351 llvm::StringRef separator,
352 llvm::StringRef help_text, size_t max_word_len);
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);
364 Debugger &GetDebugger() { return m_debugger; }
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);
371 void UpdateExecutionContext(ExecutionContext *override_context);
373 lldb::PlatformSP GetPlatform(bool prefer_target_platform);
375 const char *ProcessEmbeddedScriptCommands(const char *arg);
377 void UpdatePrompt(llvm::StringRef prompt);
379 bool Confirm(llvm::StringRef message, bool default_answer);
381 void LoadCommandDictionary();
387 bool HasCommands() const;
389 bool HasAliases() const;
391 bool HasUserCommands() const;
393 bool HasAliasOptions() const;
395 void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
396 const char *alias_name, Args &cmd_args,
397 std::string &raw_input_string,
398 CommandReturnObject &result);
400 int GetOptionArgumentPosition(const char *in_string);
402 void SkipLLDBInitFiles(bool skip_lldbinit_files) {
403 m_skip_lldbinit_files = skip_lldbinit_files;
406 void SkipAppInitFiles(bool skip_app_init_files) {
407 m_skip_app_init_files = skip_app_init_files;
410 bool GetSynchronous();
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);
418 bool GetBatchCommandMode() { return m_batch_command_mode; }
420 bool SetBatchCommandMode(bool value) {
421 const bool old_value = m_batch_command_mode;
422 m_batch_command_mode = value;
426 void ChildrenTruncated() {
427 if (m_truncation_warning == eNoTruncation)
428 m_truncation_warning = eUnwarnedTruncation;
431 bool TruncationWarningNecessary() {
432 return (m_truncation_warning == eUnwarnedTruncation);
435 void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
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";
444 CommandHistory &GetCommandHistory() { return m_command_history; }
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);
454 void GetPythonCommandsFromIOHandler(const char *prompt,
455 IOHandlerDelegate &delegate,
456 bool asynchronously, void *baton);
458 const char *GetCommandPrefix();
461 bool GetExpandRegexAliases() const;
463 bool GetPromptOnQuit() const;
465 void SetPromptOnQuit(bool b);
467 bool GetEchoCommands() const;
468 void SetEchoCommands(bool b);
470 bool GetEchoCommentCommands() const;
471 void SetEchoCommentCommands(bool b);
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);
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);
485 /// Returns the exit code that the user has specified when running the
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;
491 void ResolveCommand(const char *command_line, CommandReturnObject &result);
493 bool GetStopCmdSourceOnError() const;
495 uint32_t GetNumErrors() const { return m_num_errors; }
497 bool GetQuitRequested() const { return m_quit_requested; }
500 GetIOHandler(bool force_create = false,
501 CommandInterpreterRunOptions *options = nullptr);
503 bool GetStoppedForCrash() const { return m_stopped_for_crash; }
505 bool GetSpaceReplPrompts() const;
508 friend class Debugger;
510 // IOHandlerDelegate functions
511 void IOHandlerInputComplete(IOHandler &io_handler,
512 std::string &line) override;
514 ConstString IOHandlerGetControlSequence(char ch) override {
516 return ConstString("quit\n");
517 return ConstString();
520 bool IOHandlerInterrupt(IOHandler &io_handler) override;
522 size_t GetProcessOutput();
524 void SetSynchronous(bool value);
526 lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
527 bool include_aliases = true,
529 StringList *matches = nullptr,
530 StringList *descriptions = nullptr) const;
533 Status PreprocessCommand(std::string &command);
535 void SourceInitFile(FileSpec file, CommandReturnObject &result);
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);
543 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
544 StringList &commands_help,
545 CommandObject::CommandMap &command_map);
547 // An interruptible wrapper around the stream output
548 void PrintCommandOutput(Stream &stream, llvm::StringRef str);
550 bool EchoCommandNonInteractive(llvm::StringRef line,
551 const Flags &io_handler_flags) const;
553 // A very simple state machine which models the command handling transitions
554 enum class CommandHandlingState {
560 std::atomic<CommandHandlingState> m_command_state{
561 CommandHandlingState::eIdle};
563 int m_iohandler_nesting_level = 0;
565 void StartHandlingCommand();
566 void FinishHandlingCommand();
567 bool InterruptCommand();
569 Debugger &m_debugger; // The debugger session that this interpreter is
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
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;
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;
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;
604 } // namespace lldb_private
606 #endif // liblldb_CommandInterpreter_h_