LLDB  mainline
CommandInterpreter.h
Go to the documentation of this file.
1 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_CommandInterpreter_h_
10 #define liblldb_CommandInterpreter_h_
11 
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/IOHandler.h"
18 #include "lldb/Utility/Args.h"
21 #include "lldb/Utility/Event.h"
22 #include "lldb/Utility/Log.h"
24 #include "lldb/lldb-forward.h"
25 #include "lldb/lldb-private.h"
26 #include <mutex>
27 
28 namespace lldb_private {
29 
31 public:
32  /// Construct a CommandInterpreterRunOptions object. This class is used to
33  /// control all the instances where we run multiple commands, e.g.
34  /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
35  ///
36  /// The meanings of the options in this object are:
37  ///
38  /// \param[in] stop_on_continue
39  /// If \b true, execution will end on the first command that causes the
40  /// process in the execution context to continue. If \b false, we won't
41  /// check the execution status.
42  /// \param[in] stop_on_error
43  /// If \b true, execution will end on the first command that causes an
44  /// error.
45  /// \param[in] stop_on_crash
46  /// If \b true, when a command causes the target to run, and the end of the
47  /// run is a signal or exception, stop executing the commands.
48  /// \param[in] echo_commands
49  /// If \b true, echo the command before executing it. If \b false, execute
50  /// silently.
51  /// \param[in] echo_comments
52  /// If \b true, echo command even if it is a pure comment line. If
53  /// \b false, print no ouput in this case. This setting has an effect only
54  /// if \param echo_commands is \b true.
55  /// \param[in] print_results
56  /// If \b true print the results of the command after executing it. If
57  /// \b false, execute silently.
58  /// \param[in] add_to_history
59  /// If \b true add the commands to the command history. If \b false, don't
60  /// add them.
62  LazyBool stop_on_error, LazyBool stop_on_crash,
63  LazyBool echo_commands, LazyBool echo_comments,
64  LazyBool print_results, LazyBool add_to_history)
65  : m_stop_on_continue(stop_on_continue), m_stop_on_error(stop_on_error),
66  m_stop_on_crash(stop_on_crash), m_echo_commands(echo_commands),
67  m_echo_comment_commands(echo_comments), m_print_results(print_results),
68  m_add_to_history(add_to_history) {}
69 
78 
79  void SetSilent(bool silent) {
80  LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
81 
82  m_print_results = value;
83  m_echo_commands = value;
85  m_add_to_history = value;
86  }
87  // These return the default behaviors if the behavior is not
88  // eLazyBoolCalculate. But I've also left the ivars public since for
89  // different ways of running the interpreter you might want to force
90  // different defaults... In that case, just grab the LazyBool ivars directly
91  // and do what you want with eLazyBoolCalculate.
92  bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); }
93 
94  void SetStopOnContinue(bool stop_on_continue) {
95  m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
96  }
97 
98  bool GetStopOnError() const { return DefaultToNo(m_stop_on_error); }
99 
100  void SetStopOnError(bool stop_on_error) {
101  m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
102  }
103 
104  bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
105 
106  void SetStopOnCrash(bool stop_on_crash) {
107  m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
108  }
109 
110  bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
111 
112  void SetEchoCommands(bool echo_commands) {
113  m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
114  }
115 
116  bool GetEchoCommentCommands() const {
117  return DefaultToYes(m_echo_comment_commands);
118  }
119 
120  void SetEchoCommentCommands(bool echo_comments) {
122  }
123 
124  bool GetPrintResults() const { return DefaultToYes(m_print_results); }
125 
126  void SetPrintResults(bool print_results) {
127  m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
128  }
129 
130  bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
131 
132  void SetAddToHistory(bool add_to_history) {
133  m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
134  }
135 
143 
144 private:
145  static bool DefaultToYes(LazyBool flag) {
146  switch (flag) {
147  case eLazyBoolNo:
148  return false;
149  default:
150  return true;
151  }
152  }
153 
154  static bool DefaultToNo(LazyBool flag) {
155  switch (flag) {
156  case eLazyBoolYes:
157  return true;
158  default:
159  return false;
160  }
161  }
162 };
163 
165  public Properties,
166  public IOHandlerDelegate {
167 public:
168  enum {
169  eBroadcastBitThreadShouldExit = (1 << 0),
170  eBroadcastBitResetPrompt = (1 << 1),
171  eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
172  eBroadcastBitAsynchronousOutputData = (1 << 3),
173  eBroadcastBitAsynchronousErrorData = (1 << 4)
174  };
175 
176  enum ChildrenTruncatedWarningStatus // tristate boolean to manage children
177  // truncation warning
178  { eNoTruncation = 0, // never truncated
179  eUnwarnedTruncation = 1, // truncated but did not notify
180  eWarnedTruncation = 2 // truncated and notified
181  };
182 
184  eCommandTypesBuiltin = 0x0001, // native commands such as "frame"
185  eCommandTypesUserDef = 0x0002, // scripted commands
186  eCommandTypesAliases = 0x0004, // aliases such as "po"
187  eCommandTypesHidden = 0x0008, // commands prefixed with an underscore
188  eCommandTypesAllThem = 0xFFFF // all commands
189  };
190 
191  CommandInterpreter(Debugger &debugger, bool synchronous_execution);
192 
193  ~CommandInterpreter() override;
194 
195  // These two functions fill out the Broadcaster interface:
196 
197  static ConstString &GetStaticBroadcasterClass();
198 
199  ConstString &GetBroadcasterClass() const override {
200  return GetStaticBroadcasterClass();
201  }
202 
203  void SourceInitFile(bool in_cwd, CommandReturnObject &result);
204 
205  bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
206  bool can_replace);
207 
208  bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
209  bool can_replace);
210 
211  lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
212  bool include_aliases) const;
213 
214  CommandObject *GetCommandObject(llvm::StringRef cmd,
215  StringList *matches = nullptr,
216  StringList *descriptions = nullptr) const;
217 
218  bool CommandExists(llvm::StringRef cmd) const;
219 
220  bool AliasExists(llvm::StringRef cmd) const;
221 
222  bool UserCommandExists(llvm::StringRef cmd) const;
223 
224  CommandAlias *AddAlias(llvm::StringRef alias_name,
225  lldb::CommandObjectSP &command_obj_sp,
226  llvm::StringRef args_string = llvm::StringRef());
227 
228  // Remove a command if it is removable (python or regex command)
229  bool RemoveCommand(llvm::StringRef cmd);
230 
231  bool RemoveAlias(llvm::StringRef alias_name);
232 
233  bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
234 
235  bool RemoveUser(llvm::StringRef alias_name);
236 
237  void RemoveAllUser() { m_user_dict.clear(); }
238 
239  const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
240 
241  CommandObject *BuildAliasResult(llvm::StringRef alias_name,
242  std::string &raw_input_string,
243  std::string &alias_result,
244  CommandReturnObject &result);
245 
246  bool HandleCommand(const char *command_line, LazyBool add_to_history,
247  CommandReturnObject &result,
248  ExecutionContext *override_context = nullptr,
249  bool repeat_on_empty_command = true,
250  bool no_context_switching = false);
251 
252  bool WasInterrupted() const;
253 
254  /// Execute a list of commands in sequence.
255  ///
256  /// \param[in] commands
257  /// The list of commands to execute.
258  /// \param[in,out] context
259  /// The execution context in which to run the commands. Can be nullptr in
260  /// which case the default
261  /// context will be used.
262  /// \param[in] options
263  /// This object holds the options used to control when to stop, whether to
264  /// execute commands,
265  /// etc.
266  /// \param[out] result
267  /// This is marked as succeeding with no output if all commands execute
268  /// safely,
269  /// and failed with some explanation if we aborted executing the commands
270  /// at some point.
271  void HandleCommands(const StringList &commands, ExecutionContext *context,
273  CommandReturnObject &result);
274 
275  /// Execute a list of commands from a file.
276  ///
277  /// \param[in] file
278  /// The file from which to read in commands.
279  /// \param[in,out] context
280  /// The execution context in which to run the commands. Can be nullptr in
281  /// which case the default
282  /// context will be used.
283  /// \param[in] options
284  /// This object holds the options used to control when to stop, whether to
285  /// execute commands,
286  /// etc.
287  /// \param[out] result
288  /// This is marked as succeeding with no output if all commands execute
289  /// safely,
290  /// and failed with some explanation if we aborted executing the commands
291  /// at some point.
292  void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context,
294  CommandReturnObject &result);
295 
296  CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
297 
298  // This handles command line completion. You are given a pointer to the
299  // command string buffer, to the current cursor, and to the end of the string
300  // (in case it is not NULL terminated). You also passed in an StringList
301  // object to fill with the returns. The first element of the array will be
302  // filled with the string that you would need to insert at the cursor point
303  // to complete the cursor point to the longest common matching prefix. If you
304  // want to limit the number of elements returned, set max_return_elements to
305  // the number of elements you want returned. Otherwise set
306  // max_return_elements to -1. If you want to start some way into the match
307  // list, then set match_start_point to the desired start point. Returns: -1
308  // if the completion character should be inserted -2 if the entire command
309  // line should be deleted and replaced with matches.GetStringAtIndex(0)
310  // INT_MAX if the number of matches is > max_return_elements, but it is
311  // expensive to compute. Otherwise, returns the number of matches.
312  //
313  // FIXME: Only max_return_elements == -1 is supported at present.
314  int HandleCompletion(const char *current_line, const char *cursor,
315  const char *last_char, int match_start_point,
316  int max_return_elements, StringList &matches,
317  StringList &descriptions);
318 
319  // This version just returns matches, and doesn't compute the substring. It
320  // is here so the Help command can call it for the first argument. It uses
321  // a CompletionRequest for simplicity reasons.
322  int HandleCompletionMatches(CompletionRequest &request);
323 
324  int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
325  bool include_aliases,
326  StringList &matches,
327  StringList &descriptions);
328 
329  void GetHelp(CommandReturnObject &result,
330  uint32_t types = eCommandTypesAllThem);
331 
332  void GetAliasHelp(const char *alias_name, StreamString &help_string);
333 
334  void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
335  llvm::StringRef help_text);
336 
337  void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
338  llvm::StringRef separator,
339  llvm::StringRef help_text, size_t max_word_len);
340 
341  // this mimics OutputFormattedHelpText but it does perform a much simpler
342  // formatting, basically ensuring line alignment. This is only good if you
343  // have some complicated layout for your help text and want as little help as
344  // reasonable in properly displaying it. Most of the times, you simply want
345  // to type some text and have it printed in a reasonable way on screen. If
346  // so, use OutputFormattedHelpText
347  void OutputHelpText(Stream &stream, llvm::StringRef command_word,
348  llvm::StringRef separator, llvm::StringRef help_text,
349  uint32_t max_word_len);
350 
351  Debugger &GetDebugger() { return m_debugger; }
352 
354  const bool thread_and_frame_only_if_stopped = true;
355  return m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped);
356  }
357 
358  void UpdateExecutionContext(ExecutionContext *override_context);
359 
360  lldb::PlatformSP GetPlatform(bool prefer_target_platform);
361 
362  const char *ProcessEmbeddedScriptCommands(const char *arg);
363 
364  void UpdatePrompt(llvm::StringRef prompt);
365 
366  bool Confirm(llvm::StringRef message, bool default_answer);
367 
368  void LoadCommandDictionary();
369 
370  void Initialize();
371 
372  void Clear();
373 
374  bool HasCommands() const;
375 
376  bool HasAliases() const;
377 
378  bool HasUserCommands() const;
379 
380  bool HasAliasOptions() const;
381 
382  void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
383  const char *alias_name, Args &cmd_args,
384  std::string &raw_input_string,
385  CommandReturnObject &result);
386 
387  int GetOptionArgumentPosition(const char *in_string);
388 
389  void SkipLLDBInitFiles(bool skip_lldbinit_files) {
390  m_skip_lldbinit_files = skip_lldbinit_files;
391  }
392 
393  void SkipAppInitFiles(bool skip_app_init_files) {
394  m_skip_app_init_files = m_skip_lldbinit_files;
395  }
396 
397  bool GetSynchronous();
398 
399  void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
400  StringList &commands_help,
401  bool search_builtin_commands,
402  bool search_user_commands,
403  bool search_alias_commands);
404 
405  bool GetBatchCommandMode() { return m_batch_command_mode; }
406 
407  bool SetBatchCommandMode(bool value) {
408  const bool old_value = m_batch_command_mode;
409  m_batch_command_mode = value;
410  return old_value;
411  }
412 
414  if (m_truncation_warning == eNoTruncation)
415  m_truncation_warning = eUnwarnedTruncation;
416  }
417 
419  return (m_truncation_warning == eUnwarnedTruncation);
420  }
421 
422  void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
423 
424  const char *TruncationWarningText() {
425  return "*** Some of your variables have more members than the debugger "
426  "will show by default. To show all of them, you can either use the "
427  "--show-all-children option to %s or raise the limit by changing "
428  "the target.max-children-count setting.\n";
429  }
430 
431  const CommandHistory &GetCommandHistory() const { return m_command_history; }
432 
433  CommandHistory &GetCommandHistory() { return m_command_history; }
434 
435  bool IsActive();
436 
437  void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
439  void GetLLDBCommandsFromIOHandler(const char *prompt,
440  IOHandlerDelegate &delegate,
441  bool asynchronously, void *baton);
442 
443  void GetPythonCommandsFromIOHandler(const char *prompt,
444  IOHandlerDelegate &delegate,
445  bool asynchronously, void *baton);
446 
447  const char *GetCommandPrefix();
448 
449  // Properties
450  bool GetExpandRegexAliases() const;
451 
452  bool GetPromptOnQuit() const;
453 
454  void SetPromptOnQuit(bool b);
455 
456  bool GetEchoCommands() const;
457  void SetEchoCommands(bool b);
458 
459  bool GetEchoCommentCommands() const;
460  void SetEchoCommentCommands(bool b);
461 
462  /// Specify if the command interpreter should allow that the user can
463  /// specify a custom exit code when calling 'quit'.
464  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  LLVM_NODISCARD bool SetQuitExitCode(int exit_code);
473 
474  /// Returns the exit code that the user has specified when running the
475  /// 'quit' command.
476  /// \param[out] exited
477  /// Set to true if the user has called quit with a custom exit code.
478  int GetQuitExitCode(bool &exited) const;
479 
480  void ResolveCommand(const char *command_line, CommandReturnObject &result);
481 
482  bool GetStopCmdSourceOnError() const;
483 
484  uint32_t GetNumErrors() const { return m_num_errors; }
485 
486  bool GetQuitRequested() const { return m_quit_requested; }
487 
488  lldb::IOHandlerSP
489  GetIOHandler(bool force_create = false,
490  CommandInterpreterRunOptions *options = nullptr);
491 
492  bool GetStoppedForCrash() const { return m_stopped_for_crash; }
493 
494  bool GetSpaceReplPrompts() const;
495 
496 protected:
497  friend class Debugger;
498 
499  // IOHandlerDelegate functions
500  void IOHandlerInputComplete(IOHandler &io_handler,
501  std::string &line) override;
502 
504  if (ch == 'd')
505  return ConstString("quit\n");
506  return ConstString();
507  }
508 
509  bool IOHandlerInterrupt(IOHandler &io_handler) override;
510 
511  size_t GetProcessOutput();
512 
513  void SetSynchronous(bool value);
514 
515  lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
516  bool include_aliases = true,
517  bool exact = true,
518  StringList *matches = nullptr,
519  StringList *descriptions = nullptr) const;
520 
521 private:
522  Status PreprocessCommand(std::string &command);
523 
524  // Completely resolves aliases and abbreviations, returning a pointer to the
525  // final command object and updating command_line to the fully substituted
526  // and translated command.
527  CommandObject *ResolveCommandImpl(std::string &command_line,
528  CommandReturnObject &result);
529 
530  void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
531  StringList &commands_help,
532  CommandObject::CommandMap &command_map);
533 
534  // An interruptible wrapper around the stream output
535  void PrintCommandOutput(Stream &stream, llvm::StringRef str);
536 
537  bool EchoCommandNonInteractive(llvm::StringRef line,
538  const Flags &io_handler_flags) const;
539 
540  // A very simple state machine which models the command handling transitions
541  enum class CommandHandlingState {
542  eIdle,
543  eInProgress,
544  eInterrupted,
545  };
546 
547  std::atomic<CommandHandlingState> m_command_state{
548  CommandHandlingState::eIdle};
549 
550  int m_iohandler_nesting_level = 0;
551 
552  void StartHandlingCommand();
553  void FinishHandlingCommand();
554  bool InterruptCommand();
555 
556  Debugger &m_debugger; // The debugger session that this interpreter is
557  // associated with
558  ExecutionContextRef m_exe_ctx_ref; // The current execution context to use
559  // when handling commands
560  bool m_synchronous_execution;
561  bool m_skip_lldbinit_files;
562  bool m_skip_app_init_files;
563  CommandObject::CommandMap m_command_dict; // Stores basic built-in commands
564  // (they cannot be deleted, removed
565  // or overwritten).
567  m_alias_dict; // Stores user aliases/abbreviations for commands
568  CommandObject::CommandMap m_user_dict; // Stores user-defined commands
569  CommandHistory m_command_history;
570  std::string m_repeat_command; // Stores the command that will be executed for
571  // an empty command string.
572  lldb::IOHandlerSP m_command_io_handler_sp;
573  char m_comment_char;
574  bool m_batch_command_mode;
575  ChildrenTruncatedWarningStatus m_truncation_warning; // Whether we truncated
576  // children and whether
577  // the user has been told
578  uint32_t m_command_source_depth;
579  std::vector<uint32_t> m_command_source_flags;
580  uint32_t m_num_errors;
581  bool m_quit_requested;
582  bool m_stopped_for_crash;
583 
584  // The exit code the user has requested when calling the 'quit' command.
585  // No value means the user hasn't set a custom exit code so far.
586  llvm::Optional<int> m_quit_exit_code;
587  // If the driver is accepts custom exit codes for the 'quit' command.
588  bool m_allow_exit_code = false;
589 };
590 
591 } // namespace lldb_private
592 
593 #endif // liblldb_CommandInterpreter_h_
A class to manage flag bits.
Definition: Debugger.h:82
A command line argument class.
Definition: Args.h:32
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
A file utility class.
Definition: FileSpec.h:55
An event broadcasting class.
Definition: Broadcaster.h:250
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
CommandInterpreterRunOptions(LazyBool stop_on_continue, LazyBool stop_on_error, LazyBool stop_on_crash, LazyBool echo_commands, LazyBool echo_comments, LazyBool print_results, LazyBool add_to_history)
Construct a CommandInterpreterRunOptions object.
A delegate class for use with IOHandler subclasses.
Definition: IOHandler.h:188
"lldb/Utility/ArgCompletionRequest.h"
void SkipLLDBInitFiles(bool skip_lldbinit_files)
Execution context objects refer to objects in the execution of the program that is being debugged...
ConstString & GetBroadcasterClass() const override
const CommandHistory & GetCommandHistory() const
A class to manage flags.
Definition: Flags.h:22
A uniqued constant string class.
Definition: ConstString.h:38
void SetStopOnContinue(bool stop_on_continue)
std::map< std::string, lldb::CommandObjectSP > CommandMap
ConstString IOHandlerGetControlSequence(char ch) override
void SkipAppInitFiles(bool skip_app_init_files)
An error handling class.
Definition: Status.h:44