]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h
MFV r337216: 7263 deeply nested nvlist can overflow stack
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Interpreter / CommandInterpreter.h
1 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef liblldb_CommandInterpreter_h_
11 #define liblldb_CommandInterpreter_h_
12
13 // C Includes
14 // C++ Includes
15 #include <mutex>
16 // Other libraries and framework includes
17 // Project 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"
31
32 namespace lldb_private {
33
34 class CommandInterpreterRunOptions {
35 public:
36   //------------------------------------------------------------------
37   /// Construct a CommandInterpreterRunOptions object.
38   /// This class is used to control all the instances where we run multiple
39   /// commands, e.g.
40   /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter.
41   /// The meanings of the options in this object are:
42   ///
43   /// @param[in] stop_on_continue
44   ///    If \b true execution will end on the first command that causes the
45   ///    process in the
46   ///    execution context to continue.  If \false, we won't check the execution
47   ///    status.
48   /// @param[in] stop_on_error
49   ///    If \b true execution will end on the first command that causes an
50   ///    error.
51   /// @param[in] stop_on_crash
52   ///    If \b true when a command causes the target to run, and the end of the
53   ///    run is a
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
57   ///    silently.
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
63   ///    add them.
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) {}
72
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) {}
80
81   void SetSilent(bool silent) {
82     LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes;
83
84     m_echo_commands = value;
85     m_print_results = value;
86     m_add_to_history = value;
87   }
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,
92   // just grab
93   // the LazyBool ivars directly and do what you want with eLazyBoolCalculate.
94   bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); }
95
96   void SetStopOnContinue(bool stop_on_continue) {
97     m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo;
98   }
99
100   bool GetStopOnError() const { return DefaultToNo(m_stop_on_continue); }
101
102   void SetStopOnError(bool stop_on_error) {
103     m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo;
104   }
105
106   bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); }
107
108   void SetStopOnCrash(bool stop_on_crash) {
109     m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo;
110   }
111
112   bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); }
113
114   void SetEchoCommands(bool echo_commands) {
115     m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo;
116   }
117
118   bool GetPrintResults() const { return DefaultToYes(m_print_results); }
119
120   void SetPrintResults(bool print_results) {
121     m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo;
122   }
123
124   bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); }
125
126   void SetAddToHistory(bool add_to_history) {
127     m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo;
128   }
129
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;
136
137 private:
138   static bool DefaultToYes(LazyBool flag) {
139     switch (flag) {
140     case eLazyBoolNo:
141       return false;
142     default:
143       return true;
144     }
145   }
146
147   static bool DefaultToNo(LazyBool flag) {
148     switch (flag) {
149     case eLazyBoolYes:
150       return true;
151     default:
152       return false;
153     }
154   }
155 };
156
157 class CommandInterpreter : public Broadcaster,
158                            public Properties,
159                            public IOHandlerDelegate {
160 public:
161   enum {
162     eBroadcastBitThreadShouldExit = (1 << 0),
163     eBroadcastBitResetPrompt = (1 << 1),
164     eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit
165     eBroadcastBitAsynchronousOutputData = (1 << 3),
166     eBroadcastBitAsynchronousErrorData = (1 << 4)
167   };
168
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
174   };
175
176   enum CommandTypes {
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
182   };
183
184   CommandInterpreter(Debugger &debugger, lldb::ScriptLanguage script_language,
185                      bool synchronous_execution);
186
187   ~CommandInterpreter() override;
188
189   // These two functions fill out the Broadcaster interface:
190
191   static ConstString &GetStaticBroadcasterClass();
192
193   ConstString &GetBroadcasterClass() const override {
194     return GetStaticBroadcasterClass();
195   }
196
197   void SourceInitFile(bool in_cwd, CommandReturnObject &result);
198
199   bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
200                   bool can_replace);
201
202   bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp,
203                       bool can_replace);
204
205   lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd,
206                                           bool include_aliases) const;
207
208   CommandObject *GetCommandObject(llvm::StringRef cmd,
209                                   StringList *matches = nullptr) const;
210
211   bool CommandExists(llvm::StringRef cmd) const;
212
213   bool AliasExists(llvm::StringRef cmd) const;
214
215   bool UserCommandExists(llvm::StringRef cmd) const;
216
217   CommandAlias *AddAlias(llvm::StringRef alias_name,
218                          lldb::CommandObjectSP &command_obj_sp,
219                          llvm::StringRef args_string = llvm::StringRef());
220
221   // Remove a command if it is removable (python or regex command)
222   bool RemoveCommand(llvm::StringRef cmd);
223
224   bool RemoveAlias(llvm::StringRef alias_name);
225
226   bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const;
227
228   bool RemoveUser(llvm::StringRef alias_name);
229
230   void RemoveAllUser() { m_user_dict.clear(); }
231
232   const CommandAlias *GetAlias(llvm::StringRef alias_name) const;
233
234   CommandObject *BuildAliasResult(llvm::StringRef alias_name,
235                                   std::string &raw_input_string,
236                                   std::string &alias_result,
237                                   CommandReturnObject &result);
238
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);
244
245   bool WasInterrupted() const;
246
247   //------------------------------------------------------------------
248   /// Execute a list of commands in sequence.
249   ///
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,
259   ///    etc.
260   /// @param[out] result
261   ///    This is marked as succeeding with no output if all commands execute
262   ///    safely,
263   ///    and failed with some explanation if we aborted executing the commands
264   ///    at some point.
265   //------------------------------------------------------------------
266   void HandleCommands(const StringList &commands, ExecutionContext *context,
267                       CommandInterpreterRunOptions &options,
268                       CommandReturnObject &result);
269
270   //------------------------------------------------------------------
271   /// Execute a list of commands from a file.
272   ///
273   /// @param[in] 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,
282   ///    etc.
283   /// @param[out] result
284   ///    This is marked as succeeding with no output if all commands execute
285   ///    safely,
286   ///    and failed with some explanation if we aborted executing the commands
287   ///    at some point.
288   //------------------------------------------------------------------
289   void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context,
290                               CommandInterpreterRunOptions &options,
291                               CommandReturnObject &result);
292
293   CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line);
294
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
302   // matching prefix.
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
308   // point.
309   // Returns:
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.
316   //
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);
321
322   // This version just returns matches, and doesn't compute the substring.  It
323   // is here so the
324   // Help command can call it for the first argument.
325   // word_complete tells whether the completions are considered a "complete"
326   // response (so the
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);
332
333   int GetCommandNamesMatchingPartialString(const char *cmd_cstr,
334                                            bool include_aliases,
335                                            StringList &matches);
336
337   void GetHelp(CommandReturnObject &result,
338                uint32_t types = eCommandTypesAllThem);
339
340   void GetAliasHelp(const char *alias_name, StreamString &help_string);
341
342   void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix,
343                                llvm::StringRef help_text);
344
345   void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word,
346                                llvm::StringRef separator,
347                                llvm::StringRef help_text, size_t max_word_len);
348
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);
358
359   Debugger &GetDebugger() { return m_debugger; }
360
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);
364   }
365
366   void UpdateExecutionContext(ExecutionContext *override_context);
367
368   lldb::PlatformSP GetPlatform(bool prefer_target_platform);
369
370   const char *ProcessEmbeddedScriptCommands(const char *arg);
371
372   void UpdatePrompt(llvm::StringRef prompt);
373
374   bool Confirm(llvm::StringRef message, bool default_answer);
375
376   void LoadCommandDictionary();
377
378   void Initialize();
379
380   void Clear();
381
382   void SetScriptLanguage(lldb::ScriptLanguage lang);
383
384   bool HasCommands() const;
385
386   bool HasAliases() const;
387
388   bool HasUserCommands() const;
389
390   bool HasAliasOptions() const;
391
392   void BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
393                              const char *alias_name, Args &cmd_args,
394                              std::string &raw_input_string,
395                              CommandReturnObject &result);
396
397   int GetOptionArgumentPosition(const char *in_string);
398
399   ScriptInterpreter *GetScriptInterpreter(bool can_create = true);
400
401   void SetScriptInterpreter();
402
403   void SkipLLDBInitFiles(bool skip_lldbinit_files) {
404     m_skip_lldbinit_files = skip_lldbinit_files;
405   }
406
407   void SkipAppInitFiles(bool skip_app_init_files) {
408     m_skip_app_init_files = m_skip_lldbinit_files;
409   }
410
411   bool GetSynchronous();
412
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);
418
419   bool GetBatchCommandMode() { return m_batch_command_mode; }
420
421   bool SetBatchCommandMode(bool value) {
422     const bool old_value = m_batch_command_mode;
423     m_batch_command_mode = value;
424     return old_value;
425   }
426
427   void ChildrenTruncated() {
428     if (m_truncation_warning == eNoTruncation)
429       m_truncation_warning = eUnwarnedTruncation;
430   }
431
432   bool TruncationWarningNecessary() {
433     return (m_truncation_warning == eUnwarnedTruncation);
434   }
435
436   void TruncationWarningGiven() { m_truncation_warning = eWarnedTruncation; }
437
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";
443   }
444
445   const CommandHistory &GetCommandHistory() const { return m_command_history; }
446
447   CommandHistory &GetCommandHistory() { return m_command_history; }
448
449   bool IsActive();
450
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);
456
457   void GetPythonCommandsFromIOHandler(const char *prompt,
458                                       IOHandlerDelegate &delegate,
459                                       bool asynchronously, void *baton);
460
461   const char *GetCommandPrefix();
462
463   //------------------------------------------------------------------
464   // Properties
465   //------------------------------------------------------------------
466   bool GetExpandRegexAliases() const;
467
468   bool GetPromptOnQuit() const;
469
470   void SetPromptOnQuit(bool b);
471
472   void ResolveCommand(const char *command_line, CommandReturnObject &result);
473
474   bool GetStopCmdSourceOnError() const;
475
476   uint32_t GetNumErrors() const { return m_num_errors; }
477
478   bool GetQuitRequested() const { return m_quit_requested; }
479
480   lldb::IOHandlerSP
481   GetIOHandler(bool force_create = false,
482                CommandInterpreterRunOptions *options = nullptr);
483
484   bool GetStoppedForCrash() const { return m_stopped_for_crash; }
485
486   bool GetSpaceReplPrompts() const;
487
488 protected:
489   friend class Debugger;
490
491   //------------------------------------------------------------------
492   // IOHandlerDelegate functions
493   //------------------------------------------------------------------
494   void IOHandlerInputComplete(IOHandler &io_handler,
495                               std::string &line) override;
496
497   ConstString IOHandlerGetControlSequence(char ch) override {
498     if (ch == 'd')
499       return ConstString("quit\n");
500     return ConstString();
501   }
502
503   bool IOHandlerInterrupt(IOHandler &io_handler) override;
504
505   size_t GetProcessOutput();
506
507   void SetSynchronous(bool value);
508
509   lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd,
510                                      bool include_aliases = true,
511                                      bool exact = true,
512                                      StringList *matches = nullptr) const;
513
514 private:
515   Status PreprocessCommand(std::string &command);
516
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);
522
523   void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found,
524                               StringList &commands_help,
525                               CommandObject::CommandMap &command_map);
526
527   // An interruptible wrapper around the stream output
528   void PrintCommandOutput(Stream &stream, llvm::StringRef str);
529
530   // A very simple state machine which models the command handling transitions
531   enum class CommandHandlingState {
532     eIdle,
533     eInProgress,
534     eInterrupted,
535   };
536
537   std::atomic<CommandHandlingState> m_command_state{
538       CommandHandlingState::eIdle};
539
540   int m_iohandler_nesting_level = 0;
541
542   void StartHandlingCommand();
543   void FinishHandlingCommand();
544   bool InterruptCommand();
545
546   Debugger &m_debugger; // The debugger session that this interpreter is
547                         // associated with
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
555                                             // or overwritten).
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;
565   char m_comment_char;
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;
575 };
576
577 } // namespace lldb_private
578
579 #endif // liblldb_CommandInterpreter_h_