1 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_CommandInterpreter_h_
11 #define liblldb_CommandInterpreter_h_
16 // Other libraries and framework includes
18 #include "lldb/Core/Broadcaster.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Event.h"
21 #include "lldb/Core/IOHandler.h"
22 #include "lldb/Interpreter/CommandAlias.h"
23 #include "lldb/Interpreter/CommandHistory.h"
24 #include "lldb/Interpreter/CommandObject.h"
25 #include "lldb/Interpreter/ScriptInterpreter.h"
26 #include "lldb/Utility/Args.h"
27 #include "lldb/Utility/CompletionRequest.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/StringList.h"
30 #include "lldb/lldb-forward.h"
31 #include "lldb/lldb-private.h"
33 namespace lldb_private {
35 class CommandInterpreterRunOptions {
37 //------------------------------------------------------------------
38 /// Construct a CommandInterpreterRunOptions object.
39 /// This class is used to control all the instances where we run multiple
41 /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
42 /// The meanings of the options in this object are:
44 /// @param[in] stop_on_continue
45 /// If \b true execution will end on the first command that causes the
47 /// execution context to continue. If \false, we won't check the execution
49 /// @param[in] stop_on_error
50 /// If \b true execution will end on the first command that causes an
52 /// @param[in] stop_on_crash
53 /// If \b true when a command causes the target to run, and the end of the
55 /// signal or exception, stop executing the commands.
56 /// @param[in] echo_commands
57 /// If \b true echo the command before executing it. If \false, execute
59 /// @param[in] print_results
60 /// If \b true print the results of the command after executing it. If
61 /// \false, execute silently.
62 /// @param[in] add_to_history
63 /// If \b true add the commands to the command history. If \false, don't
65 //------------------------------------------------------------------
66 CommandInterpreterRunOptions(LazyBool stop_on_continue,
67 LazyBool stop_on_error, LazyBool stop_on_crash,
68 LazyBool echo_commands, LazyBool print_results,
69 LazyBool add_to_history)
70 : m_stop_on_continue(stop_on_continue), m_stop_on_error(stop_on_error),
71 m_stop_on_crash(stop_on_crash), m_echo_commands(echo_commands),
72 m_print_results(print_results), m_add_to_history(add_to_history) {}
74 CommandInterpreterRunOptions()
75 : m_stop_on_continue(eLazyBoolCalculate),
76 m_stop_on_error(eLazyBoolCalculate),
77 m_stop_on_crash(eLazyBoolCalculate),
78 m_echo_commands(eLazyBoolCalculate),
79 m_print_results(eLazyBoolCalculate),
80 m_add_to_history(eLazyBoolCalculate) {}
82 void SetSilent(bool silent) {
83 LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
85 m_echo_commands = value;
86 m_print_results = value;
87 m_add_to_history = value;
89 // These return the default behaviors if the behavior is not
90 // eLazyBoolCalculate. But I've also left the ivars public since for
91 // different ways of running the interpreter you might want to force
92 // different defaults... In that case, just grab the LazyBool ivars directly
93 // and do what you want with eLazyBoolCalculate.
94 bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); }
96 void SetStopOnContinue(bool stop_on_continue) {
97 m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
100 bool GetStopOnError() const { return DefaultToNo(m_stop_on_continue); }
102 void SetStopOnError(bool stop_on_error) {
103 m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
106 bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
108 void SetStopOnCrash(bool stop_on_crash) {
109 m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
112 bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
114 void SetEchoCommands(bool echo_commands) {
115 m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
118 bool GetPrintResults() const { return DefaultToYes(m_print_results); }
120 void SetPrintResults(bool print_results) {
121 m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
124 bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
126 void SetAddToHistory(bool add_to_history) {
127 m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
130 LazyBool m_stop_on_continue;
131 LazyBool m_stop_on_error;
132 LazyBool m_stop_on_crash;
133 LazyBool m_echo_commands;
134 LazyBool m_print_results;
135 LazyBool m_add_to_history;
138 static bool DefaultToYes(LazyBool flag) {
147 static bool DefaultToNo(LazyBool flag) {
157 class CommandInterpreter : public Broadcaster,
159 public IOHandlerDelegate {
162 eBroadcastBitThreadShouldExit = (1 << 0),
163 eBroadcastBitResetPrompt = (1 << 1),
164 eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
165 eBroadcastBitAsynchronousOutputData = (1 << 3),
166 eBroadcastBitAsynchronousErrorData = (1 << 4)
169 enum ChildrenTruncatedWarningStatus // tristate boolean to manage children
170 // truncation warning
171 { eNoTruncation = 0, // never truncated
172 eUnwarnedTruncation = 1, // truncated but did not notify
173 eWarnedTruncation = 2 // truncated and notified
177 eCommandTypesBuiltin = 0x0001, // native commands such as "frame"
178 eCommandTypesUserDef = 0x0002, // scripted commands
179 eCommandTypesAliases = 0x0004, // aliases such as "po"
180 eCommandTypesHidden = 0x0008, // commands prefixed with an underscore
181 eCommandTypesAllThem = 0xFFFF // all commands
184 CommandInterpreter(Debugger &debugger, lldb::ScriptLanguage script_language,
185 bool synchronous_execution);
187 ~CommandInterpreter() override;
189 // These two functions fill out the Broadcaster interface:
191 static ConstString &GetStaticBroadcasterClass();
193 ConstString &GetBroadcasterClass() const override {
194 return GetStaticBroadcasterClass();
197 void SourceInitFile(bool in_cwd, CommandReturnObject &result);
199 bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
202 bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
205 lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
206 bool include_aliases) const;
208 CommandObject *GetCommandObject(llvm::StringRef cmd,
209 StringList *matches = nullptr) const;
211 bool CommandExists(llvm::StringRef cmd) const;
213 bool AliasExists(llvm::StringRef cmd) const;
215 bool UserCommandExists(llvm::StringRef cmd) const;
217 CommandAlias *AddAlias(llvm::StringRef alias_name,
218 lldb::CommandObjectSP &command_obj_sp,
219 llvm::StringRef args_string = llvm::StringRef());
221 // Remove a command if it is removable (python or regex command)
222 bool RemoveCommand(llvm::StringRef cmd);
224 bool RemoveAlias(llvm::StringRef alias_name);
226 bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
228 bool RemoveUser(llvm::StringRef alias_name);
230 void RemoveAllUser() { m_user_dict.clear(); }
232 const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
234 CommandObject *BuildAliasResult(llvm::StringRef alias_name,
235 std::string &raw_input_string,
236 std::string &alias_result,
237 CommandReturnObject &result);
239 bool HandleCommand(const char *command_line, LazyBool add_to_history,
240 CommandReturnObject &result,
241 ExecutionContext *override_context = nullptr,
242 bool repeat_on_empty_command = true,
243 bool no_context_switching = false);
245 bool WasInterrupted() const;
247 //------------------------------------------------------------------
248 /// Execute a list of commands in sequence.
250 /// @param[in] commands
251 /// The list of commands to execute.
252 /// @param[in,out] context
253 /// The execution context in which to run the commands. Can be nullptr in
254 /// which case the default
255 /// context will be used.
256 /// @param[in] options
257 /// This object holds the options used to control when to stop, whether to
258 /// execute commands,
260 /// @param[out] result
261 /// This is marked as succeeding with no output if all commands execute
263 /// and failed with some explanation if we aborted executing the commands
265 //------------------------------------------------------------------
266 void HandleCommands(const StringList &commands, ExecutionContext *context,
267 CommandInterpreterRunOptions &options,
268 CommandReturnObject &result);
270 //------------------------------------------------------------------
271 /// Execute a list of commands from a file.
274 /// The file from which to read in commands.
275 /// @param[in,out] context
276 /// The execution context in which to run the commands. Can be nullptr in
277 /// which case the default
278 /// context will be used.
279 /// @param[in] options
280 /// This object holds the options used to control when to stop, whether to
281 /// execute commands,
283 /// @param[out] result
284 /// This is marked as succeeding with no output if all commands execute
286 /// and failed with some explanation if we aborted executing the commands
288 //------------------------------------------------------------------
289 void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context,
290 CommandInterpreterRunOptions &options,
291 CommandReturnObject &result);
293 CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
295 // This handles command line completion. You are given a pointer to the
296 // command string buffer, to the current cursor, and to the end of the string
297 // (in case it is not NULL terminated). You also passed in an StringList
298 // object to fill with the returns. The first element of the array will be
299 // filled with the string that you would need to insert at the cursor point
300 // to complete the cursor point to the longest common matching prefix. If you
301 // want to limit the number of elements returned, set max_return_elements to
302 // the number of elements you want returned. Otherwise set
303 // max_return_elements to -1. If you want to start some way into the match
304 // list, then set match_start_point to the desired start point. Returns: -1
305 // if the completion character should be inserted -2 if the entire command
306 // line should be deleted and replaced with matches.GetStringAtIndex(0)
307 // INT_MAX if the number of matches is > max_return_elements, but it is
308 // expensive to compute. Otherwise, returns the number of matches.
310 // FIXME: Only max_return_elements == -1 is supported at present.
311 int HandleCompletion(const char *current_line, const char *cursor,
312 const char *last_char, int match_start_point,
313 int max_return_elements, StringList &matches);
315 // This version just returns matches, and doesn't compute the substring. It
316 // is here so the Help command can call it for the first argument. It uses
317 // a CompletionRequest for simplicity reasons.
318 int HandleCompletionMatches(CompletionRequest &request);
320 int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
321 bool include_aliases,
322 StringList &matches);
324 void GetHelp(CommandReturnObject &result,
325 uint32_t types = eCommandTypesAllThem);
327 void GetAliasHelp(const char *alias_name, StreamString &help_string);
329 void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
330 llvm::StringRef help_text);
332 void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
333 llvm::StringRef separator,
334 llvm::StringRef help_text, size_t max_word_len);
336 // this mimics OutputFormattedHelpText but it does perform a much simpler
337 // formatting, basically ensuring line alignment. This is only good if you
338 // have some complicated layout for your help text and want as little help as
339 // reasonable in properly displaying it. Most of the times, you simply want
340 // to type some text and have it printed in a reasonable way on screen. If
341 // so, use OutputFormattedHelpText
342 void OutputHelpText(Stream &stream, llvm::StringRef command_word,
343 llvm::StringRef separator, llvm::StringRef help_text,
344 uint32_t max_word_len);
346 Debugger &GetDebugger() { return m_debugger; }
348 ExecutionContext GetExecutionContext() {
349 const bool thread_and_frame_only_if_stopped = true;
350 return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped);
353 void UpdateExecutionContext(ExecutionContext *override_context);
355 lldb::PlatformSP GetPlatform(bool prefer_target_platform);
357 const char *ProcessEmbeddedScriptCommands(const char *arg);
359 void UpdatePrompt(llvm::StringRef prompt);
361 bool Confirm(llvm::StringRef message, bool default_answer);
363 void LoadCommandDictionary();
369 void SetScriptLanguage(lldb::ScriptLanguage lang);
371 bool HasCommands() const;
373 bool HasAliases() const;
375 bool HasUserCommands() const;
377 bool HasAliasOptions() const;
379 void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
380 const char *alias_name, Args &cmd_args,
381 std::string &raw_input_string,
382 CommandReturnObject &result);
384 int GetOptionArgumentPosition(const char *in_string);
386 ScriptInterpreter *GetScriptInterpreter(bool can_create = true);
388 void SetScriptInterpreter();
390 void SkipLLDBInitFiles(bool skip_lldbinit_files) {
391 m_skip_lldbinit_files = skip_lldbinit_files;
394 void SkipAppInitFiles(bool skip_app_init_files) {
395 m_skip_app_init_files = m_skip_lldbinit_files;
398 bool GetSynchronous();
400 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
401 StringList &commands_help,
402 bool search_builtin_commands,
403 bool search_user_commands,
404 bool search_alias_commands);
406 bool GetBatchCommandMode() { return m_batch_command_mode; }
408 bool SetBatchCommandMode(bool value) {
409 const bool old_value = m_batch_command_mode;
410 m_batch_command_mode = value;
414 void ChildrenTruncated() {
415 if (m_truncation_warning == eNoTruncation)
416 m_truncation_warning = eUnwarnedTruncation;
419 bool TruncationWarningNecessary() {
420 return (m_truncation_warning == eUnwarnedTruncation);
423 void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
425 const char *TruncationWarningText() {
426 return "*** Some of your variables have more members than the debugger "
427 "will show by default. To show all of them, you can either use the "
428 "--show-all-children option to %s or raise the limit by changing "
429 "the target.max-children-count setting.\n";
432 const CommandHistory &GetCommandHistory() const { return m_command_history; }
434 CommandHistory &GetCommandHistory() { return m_command_history; }
438 void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
439 CommandInterpreterRunOptions &options);
440 void GetLLDBCommandsFromIOHandler(const char *prompt,
441 IOHandlerDelegate &delegate,
442 bool asynchronously, void *baton);
444 void GetPythonCommandsFromIOHandler(const char *prompt,
445 IOHandlerDelegate &delegate,
446 bool asynchronously, void *baton);
448 const char *GetCommandPrefix();
450 //------------------------------------------------------------------
452 //------------------------------------------------------------------
453 bool GetExpandRegexAliases() const;
455 bool GetPromptOnQuit() const;
457 void SetPromptOnQuit(bool b);
459 //------------------------------------------------------------------
460 /// Specify if the command interpreter should allow that the user can
461 /// specify a custom exit code when calling 'quit'.
462 //------------------------------------------------------------------
463 void AllowExitCodeOnQuit(bool allow);
465 //------------------------------------------------------------------
466 /// Sets the exit code for the quit command.
467 /// @param[in] exit_code
468 /// The exit code that the driver should return on exit.
469 /// @return True if the exit code was successfully set; false if the
470 /// interpreter doesn't allow custom exit codes.
471 /// @see AllowExitCodeOnQuit
472 //------------------------------------------------------------------
473 LLVM_NODISCARD bool SetQuitExitCode(int exit_code);
475 //------------------------------------------------------------------
476 /// Returns the exit code that the user has specified when running the
478 /// @param[out] exited
479 /// Set to true if the user has called quit with a custom exit code.
480 //------------------------------------------------------------------
481 int GetQuitExitCode(bool &exited) const;
483 void ResolveCommand(const char *command_line, CommandReturnObject &result);
485 bool GetStopCmdSourceOnError() const;
487 uint32_t GetNumErrors() const { return m_num_errors; }
489 bool GetQuitRequested() const { return m_quit_requested; }
492 GetIOHandler(bool force_create = false,
493 CommandInterpreterRunOptions *options = nullptr);
495 bool GetStoppedForCrash() const { return m_stopped_for_crash; }
497 bool GetSpaceReplPrompts() const;
500 friend class Debugger;
502 //------------------------------------------------------------------
503 // IOHandlerDelegate functions
504 //------------------------------------------------------------------
505 void IOHandlerInputComplete(IOHandler &io_handler,
506 std::string &line) override;
508 ConstString IOHandlerGetControlSequence(char ch) override {
510 return ConstString("quit\n");
511 return ConstString();
514 bool IOHandlerInterrupt(IOHandler &io_handler) override;
516 size_t GetProcessOutput();
518 void SetSynchronous(bool value);
520 lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
521 bool include_aliases = true,
523 StringList *matches = nullptr) const;
526 Status PreprocessCommand(std::string &command);
528 // Completely resolves aliases and abbreviations, returning a pointer to the
529 // final command object and updating command_line to the fully substituted
530 // and translated command.
531 CommandObject *ResolveCommandImpl(std::string &command_line,
532 CommandReturnObject &result);
534 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
535 StringList &commands_help,
536 CommandObject::CommandMap &command_map);
538 // An interruptible wrapper around the stream output
539 void PrintCommandOutput(Stream &stream, llvm::StringRef str);
541 // A very simple state machine which models the command handling transitions
542 enum class CommandHandlingState {
548 std::atomic<CommandHandlingState> m_command_state{
549 CommandHandlingState::eIdle};
551 int m_iohandler_nesting_level = 0;
553 void StartHandlingCommand();
554 void FinishHandlingCommand();
555 bool InterruptCommand();
557 Debugger &m_debugger; // The debugger session that this interpreter is
559 ExecutionContextRef m_exe_ctx_ref; // The current execution context to use
560 // when handling commands
561 bool m_synchronous_execution;
562 bool m_skip_lldbinit_files;
563 bool m_skip_app_init_files;
564 CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
565 // (they cannot be deleted, removed
567 CommandObject::CommandMap
568 m_alias_dict; // Stores user aliases/abbreviations for commands
569 CommandObject::CommandMap m_user_dict; // Stores user-defined commands
570 CommandHistory m_command_history;
571 std::string m_repeat_command; // Stores the command that will be executed for
572 // an empty command string.
573 lldb::ScriptInterpreterSP m_script_interpreter_sp;
574 std::recursive_mutex m_script_interpreter_mutex;
575 lldb::IOHandlerSP m_command_io_handler_sp;
577 bool m_batch_command_mode;
578 ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated
579 // children and whether
580 // the user has been told
581 uint32_t m_command_source_depth;
582 std::vector<uint32_t> m_command_source_flags;
583 uint32_t m_num_errors;
584 bool m_quit_requested;
585 bool m_stopped_for_crash;
587 // The exit code the user has requested when calling the 'quit' command.
588 // No value means the user hasn't set a custom exit code so far.
589 llvm::Optional<int> m_quit_exit_code;
590 // If the driver is accepts custom exit codes for the 'quit' command.
591 bool m_allow_exit_code = false;
594 } // namespace lldb_private
596 #endif // liblldb_CommandInterpreter_h_