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/Args.h"
23 #include "lldb/Interpreter/CommandAlias.h"
24 #include "lldb/Interpreter/CommandHistory.h"
25 #include "lldb/Interpreter/CommandObject.h"
26 #include "lldb/Interpreter/ScriptInterpreter.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/StringList.h"
29 #include "lldb/lldb-forward.h"
30 #include "lldb/lldb-private.h"
32 namespace lldb_private {
34 class CommandInterpreterRunOptions {
36 //------------------------------------------------------------------
37 /// Construct a CommandInterpreterRunOptions object.
38 /// This class is used to control all the instances where we run multiple
40 /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
41 /// The meanings of the options in this object are:
43 /// @param[in] stop_on_continue
44 /// If \b true execution will end on the first command that causes the
46 /// execution context to continue. If \false, we won't check the execution
48 /// @param[in] stop_on_error
49 /// If \b true execution will end on the first command that causes an
51 /// @param[in] stop_on_crash
52 /// If \b true when a command causes the target to run, and the end of the
54 /// signal or exception, stop executing the commands.
55 /// @param[in] echo_commands
56 /// If \b true echo the command before executing it. If \false, execute
58 /// @param[in] print_results
59 /// If \b true print the results of the command after executing it. If
60 /// \false, execute silently.
61 /// @param[in] add_to_history
62 /// If \b true add the commands to the command history. If \false, don't
64 //------------------------------------------------------------------
65 CommandInterpreterRunOptions(LazyBool stop_on_continue,
66 LazyBool stop_on_error, LazyBool stop_on_crash,
67 LazyBool echo_commands, LazyBool print_results,
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_print_results(print_results), m_add_to_history(add_to_history) {}
73 CommandInterpreterRunOptions()
74 : m_stop_on_continue(eLazyBoolCalculate),
75 m_stop_on_error(eLazyBoolCalculate),
76 m_stop_on_crash(eLazyBoolCalculate),
77 m_echo_commands(eLazyBoolCalculate),
78 m_print_results(eLazyBoolCalculate),
79 m_add_to_history(eLazyBoolCalculate) {}
81 void SetSilent(bool silent) {
82 LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
84 m_echo_commands = value;
85 m_print_results = value;
86 m_add_to_history = value;
88 // These return the default behaviors if the behavior is not
89 // eLazyBoolCalculate.
90 // But I've also left the ivars public since for different ways of running the
91 // interpreter you might want to force different defaults... In that case,
93 // the LazyBool ivars directly 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,
297 // and to the end of the string (in case it is not NULL terminated).
298 // You also passed in an StringList object to fill with the returns.
299 // The first element of the array will be filled with the string that you
300 // would need to insert at
301 // the cursor point to complete the cursor point to the longest common
303 // If you want to limit the number of elements returned, set
304 // max_return_elements to the number of elements
305 // you want returned. Otherwise set max_return_elements to -1.
306 // If you want to start some way into the match list, then set
307 // match_start_point to the desired start
310 // -1 if the completion character should be inserted
311 // -2 if the entire command line should be deleted and replaced with
312 // matches.GetStringAtIndex(0)
313 // INT_MAX if the number of matches is > max_return_elements, but it is
314 // expensive to compute.
315 // Otherwise, returns the number of matches.
317 // FIXME: Only max_return_elements == -1 is supported at present.
318 int HandleCompletion(const char *current_line, const char *cursor,
319 const char *last_char, int match_start_point,
320 int max_return_elements, StringList &matches);
322 // This version just returns matches, and doesn't compute the substring. It
324 // Help command can call it for the first argument.
325 // word_complete tells whether the completions are considered a "complete"
327 // completer should complete the quote & put a space after the word.
328 int HandleCompletionMatches(Args &input, int &cursor_index,
329 int &cursor_char_position, int match_start_point,
330 int max_return_elements, bool &word_complete,
331 StringList &matches);
333 int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
334 bool include_aliases,
335 StringList &matches);
337 void GetHelp(CommandReturnObject &result,
338 uint32_t types = eCommandTypesAllThem);
340 void GetAliasHelp(const char *alias_name, StreamString &help_string);
342 void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
343 llvm::StringRef help_text);
345 void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
346 llvm::StringRef separator,
347 llvm::StringRef help_text, size_t max_word_len);
349 // this mimics OutputFormattedHelpText but it does perform a much simpler
350 // formatting, basically ensuring line alignment. This is only good if you
351 // have some complicated layout for your help text and want as little help as
352 // reasonable in properly displaying it. Most of the times, you simply want
353 // to type some text and have it printed in a reasonable way on screen. If
354 // so, use OutputFormattedHelpText
355 void OutputHelpText(Stream &stream, llvm::StringRef command_word,
356 llvm::StringRef separator, llvm::StringRef help_text,
357 uint32_t max_word_len);
359 Debugger &GetDebugger() { return m_debugger; }
361 ExecutionContext GetExecutionContext() {
362 const bool thread_and_frame_only_if_stopped = true;
363 return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped);
366 void UpdateExecutionContext(ExecutionContext *override_context);
368 lldb::PlatformSP GetPlatform(bool prefer_target_platform);
370 const char *ProcessEmbeddedScriptCommands(const char *arg);
372 void UpdatePrompt(llvm::StringRef prompt);
374 bool Confirm(llvm::StringRef message, bool default_answer);
376 void LoadCommandDictionary();
382 void SetScriptLanguage(lldb::ScriptLanguage lang);
384 bool HasCommands() const;
386 bool HasAliases() const;
388 bool HasUserCommands() const;
390 bool HasAliasOptions() const;
392 void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
393 const char *alias_name, Args &cmd_args,
394 std::string &raw_input_string,
395 CommandReturnObject &result);
397 int GetOptionArgumentPosition(const char *in_string);
399 ScriptInterpreter *GetScriptInterpreter(bool can_create = true);
401 void SetScriptInterpreter();
403 void SkipLLDBInitFiles(bool skip_lldbinit_files) {
404 m_skip_lldbinit_files = skip_lldbinit_files;
407 void SkipAppInitFiles(bool skip_app_init_files) {
408 m_skip_app_init_files = m_skip_lldbinit_files;
411 bool GetSynchronous();
413 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
414 StringList &commands_help,
415 bool search_builtin_commands,
416 bool search_user_commands,
417 bool search_alias_commands);
419 bool GetBatchCommandMode() { return m_batch_command_mode; }
421 bool SetBatchCommandMode(bool value) {
422 const bool old_value = m_batch_command_mode;
423 m_batch_command_mode = value;
427 void ChildrenTruncated() {
428 if (m_truncation_warning == eNoTruncation)
429 m_truncation_warning = eUnwarnedTruncation;
432 bool TruncationWarningNecessary() {
433 return (m_truncation_warning == eUnwarnedTruncation);
436 void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
438 const char *TruncationWarningText() {
439 return "*** Some of your variables have more members than the debugger "
440 "will show by default. To show all of them, you can either use the "
441 "--show-all-children option to %s or raise the limit by changing "
442 "the target.max-children-count setting.\n";
445 const CommandHistory &GetCommandHistory() const { return m_command_history; }
447 CommandHistory &GetCommandHistory() { return m_command_history; }
451 void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
452 CommandInterpreterRunOptions &options);
453 void GetLLDBCommandsFromIOHandler(const char *prompt,
454 IOHandlerDelegate &delegate,
455 bool asynchronously, void *baton);
457 void GetPythonCommandsFromIOHandler(const char *prompt,
458 IOHandlerDelegate &delegate,
459 bool asynchronously, void *baton);
461 const char *GetCommandPrefix();
463 //------------------------------------------------------------------
465 //------------------------------------------------------------------
466 bool GetExpandRegexAliases() const;
468 bool GetPromptOnQuit() const;
470 void SetPromptOnQuit(bool b);
472 void ResolveCommand(const char *command_line, CommandReturnObject &result);
474 bool GetStopCmdSourceOnError() const;
476 uint32_t GetNumErrors() const { return m_num_errors; }
478 bool GetQuitRequested() const { return m_quit_requested; }
481 GetIOHandler(bool force_create = false,
482 CommandInterpreterRunOptions *options = nullptr);
484 bool GetStoppedForCrash() const { return m_stopped_for_crash; }
486 bool GetSpaceReplPrompts() const;
489 friend class Debugger;
491 //------------------------------------------------------------------
492 // IOHandlerDelegate functions
493 //------------------------------------------------------------------
494 void IOHandlerInputComplete(IOHandler &io_handler,
495 std::string &line) override;
497 ConstString IOHandlerGetControlSequence(char ch) override {
499 return ConstString("quit\n");
500 return ConstString();
503 bool IOHandlerInterrupt(IOHandler &io_handler) override;
505 size_t GetProcessOutput();
507 void SetSynchronous(bool value);
509 lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
510 bool include_aliases = true,
512 StringList *matches = nullptr) const;
515 Status PreprocessCommand(std::string &command);
517 // Completely resolves aliases and abbreviations, returning a pointer to the
518 // final command object and updating command_line to the fully substituted
519 // and translated command.
520 CommandObject *ResolveCommandImpl(std::string &command_line,
521 CommandReturnObject &result);
523 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
524 StringList &commands_help,
525 CommandObject::CommandMap &command_map);
527 // An interruptible wrapper around the stream output
528 void PrintCommandOutput(Stream &stream, llvm::StringRef str);
530 // A very simple state machine which models the command handling transitions
531 enum class CommandHandlingState {
537 std::atomic<CommandHandlingState> m_command_state{
538 CommandHandlingState::eIdle};
540 int m_iohandler_nesting_level = 0;
542 void StartHandlingCommand();
543 void FinishHandlingCommand();
544 bool InterruptCommand();
546 Debugger &m_debugger; // The debugger session that this interpreter is
548 ExecutionContextRef m_exe_ctx_ref; // The current execution context to use
549 // when handling commands
550 bool m_synchronous_execution;
551 bool m_skip_lldbinit_files;
552 bool m_skip_app_init_files;
553 CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
554 // (they cannot be deleted, removed
556 CommandObject::CommandMap
557 m_alias_dict; // Stores user aliases/abbreviations for commands
558 CommandObject::CommandMap m_user_dict; // Stores user-defined commands
559 CommandHistory m_command_history;
560 std::string m_repeat_command; // Stores the command that will be executed for
561 // an empty command string.
562 lldb::ScriptInterpreterSP m_script_interpreter_sp;
563 std::recursive_mutex m_script_interpreter_mutex;
564 lldb::IOHandlerSP m_command_io_handler_sp;
566 bool m_batch_command_mode;
567 ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated
568 // children and whether
569 // the user has been told
570 uint32_t m_command_source_depth;
571 std::vector<uint32_t> m_command_source_flags;
572 uint32_t m_num_errors;
573 bool m_quit_requested;
574 bool m_stopped_for_crash;
577 } // namespace lldb_private
579 #endif // liblldb_CommandInterpreter_h_