xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h (revision 77374d3b53cee7829ba70b13abf33e0d63d9d256)
1 //===-- ScriptInterpreterPythonImpl.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 LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
10 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
11 
12 #include "lldb/Host/Config.h"
13 
14 #if LLDB_ENABLE_PYTHON
15 
16 #include "lldb-python.h"
17 
18 #include "PythonDataObjects.h"
19 #include "ScriptInterpreterPython.h"
20 
21 #include "lldb/Host/Terminal.h"
22 #include "lldb/Utility/StreamString.h"
23 
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 
27 namespace lldb_private {
28 class IOHandlerPythonInterpreter;
29 class ScriptInterpreterPythonImpl : public ScriptInterpreterPython {
30 public:
31   friend class IOHandlerPythonInterpreter;
32 
33   ScriptInterpreterPythonImpl(Debugger &debugger);
34 
35   ~ScriptInterpreterPythonImpl() override;
36 
37   bool Interrupt() override;
38 
39   bool ExecuteOneLine(
40       llvm::StringRef command, CommandReturnObject *result,
41       const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
42 
43   void ExecuteInterpreterLoop() override;
44 
45   bool ExecuteOneLineWithReturn(
46       llvm::StringRef in_string,
47       ScriptInterpreter::ScriptReturnType return_type, void *ret_value,
48       const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
49 
50   lldb_private::Status ExecuteMultipleLines(
51       const char *in_string,
52       const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
53 
54   Status
55   ExportFunctionDefinitionToInterpreter(StringList &function_def) override;
56 
57   bool GenerateTypeScriptFunction(StringList &input, std::string &output,
58                                   const void *name_token = nullptr) override;
59 
60   bool GenerateTypeSynthClass(StringList &input, std::string &output,
61                               const void *name_token = nullptr) override;
62 
63   bool GenerateTypeSynthClass(const char *oneliner, std::string &output,
64                               const void *name_token = nullptr) override;
65 
66   // use this if the function code is just a one-liner script
67   bool GenerateTypeScriptFunction(const char *oneliner, std::string &output,
68                                   const void *name_token = nullptr) override;
69 
70   bool GenerateScriptAliasFunction(StringList &input,
71                                    std::string &output) override;
72 
73   StructuredData::ObjectSP
74   CreateSyntheticScriptedProvider(const char *class_name,
75                                   lldb::ValueObjectSP valobj) override;
76 
77   StructuredData::GenericSP
78   CreateScriptCommandObject(const char *class_name) override;
79 
80   StructuredData::ObjectSP
81   CreateScriptedThreadPlan(const char *class_name,
82                            const StructuredDataImpl &args_data,
83                            std::string &error_str,
84                            lldb::ThreadPlanSP thread_plan) override;
85 
86   StructuredData::ObjectSP
87   CreateStructuredDataFromScriptObject(ScriptObject obj) override;
88 
89   bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,
90                                       Event *event,
91                                       bool &script_error) override;
92 
93   bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,
94                                     Event *event, bool &script_error) override;
95 
96   bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,
97                                  bool &script_error) override;
98 
99   lldb::StateType
100   ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,
101                                 bool &script_error) override;
102 
103   bool
104   ScriptedThreadPlanGetStopDescription(StructuredData::ObjectSP implementor_sp,
105                                 lldb_private::Stream *s,
106                                 bool &script_error) override;
107 
108   StructuredData::GenericSP
109   CreateScriptedBreakpointResolver(const char *class_name,
110                                    const StructuredDataImpl &args_data,
111                                    lldb::BreakpointSP &bkpt_sp) override;
112   bool ScriptedBreakpointResolverSearchCallback(
113       StructuredData::GenericSP implementor_sp,
114       SymbolContext *sym_ctx) override;
115 
116   lldb::SearchDepth ScriptedBreakpointResolverSearchDepth(
117       StructuredData::GenericSP implementor_sp) override;
118 
119   StructuredData::GenericSP
120   CreateScriptedStopHook(lldb::TargetSP target_sp, const char *class_name,
121                          const StructuredDataImpl &args_data,
122                          Status &error) override;
123 
124   bool ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,
125                                   ExecutionContext &exc_ctx,
126                                   lldb::StreamSP stream_sp) override;
127 
128   StructuredData::GenericSP
129   CreateFrameRecognizer(const char *class_name) override;
130 
131   lldb::ValueObjectListSP
132   GetRecognizedArguments(const StructuredData::ObjectSP &implementor,
133                          lldb::StackFrameSP frame_sp) override;
134 
135   lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override;
136 
137   StructuredData::GenericSP
138   OSPlugin_CreatePluginObject(const char *class_name,
139                               lldb::ProcessSP process_sp) override;
140 
141   StructuredData::DictionarySP
142   OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
143   lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override;
144 
145   StructuredData::ArraySP
146   OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
147 
148   StructuredData::StringSP
149   OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,
150                                lldb::tid_t thread_id) override;
151 
152   StructuredData::DictionarySP
153   OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,
154                         lldb::tid_t tid, lldb::addr_t context) override;
155 
156   StructuredData::ObjectSP
157   LoadPluginModule(const FileSpec &file_spec,
158                    lldb_private::Status &error) override;
159 
160   StructuredData::DictionarySP
161   GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target,
162                      const char *setting_name,
163                      lldb_private::Status &error) override;
164 
165   size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor,
166                               uint32_t max) override;
167 
168   lldb::ValueObjectSP
169   GetChildAtIndex(const StructuredData::ObjectSP &implementor,
170                   uint32_t idx) override;
171 
172   int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor,
173                               const char *child_name) override;
174 
175   bool UpdateSynthProviderInstance(
176       const StructuredData::ObjectSP &implementor) override;
177 
178   bool MightHaveChildrenSynthProviderInstance(
179       const StructuredData::ObjectSP &implementor) override;
180 
181   lldb::ValueObjectSP
182   GetSyntheticValue(const StructuredData::ObjectSP &implementor) override;
183 
184   ConstString
185   GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override;
186 
187   bool
188   RunScriptBasedCommand(const char *impl_function, llvm::StringRef args,
189                         ScriptedCommandSynchronicity synchronicity,
190                         lldb_private::CommandReturnObject &cmd_retobj,
191                         Status &error,
192                         const lldb_private::ExecutionContext &exe_ctx) override;
193 
194   bool RunScriptBasedCommand(
195       StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
196       ScriptedCommandSynchronicity synchronicity,
197       lldb_private::CommandReturnObject &cmd_retobj, Status &error,
198       const lldb_private::ExecutionContext &exe_ctx) override;
199 
200   Status GenerateFunction(const char *signature, const StringList &input,
201                           bool is_callback) override;
202 
203   Status GenerateBreakpointCommandCallbackData(StringList &input,
204                                                std::string &output,
205                                                bool has_extra_args,
206                                                bool is_callback) override;
207 
208   bool GenerateWatchpointCommandCallbackData(StringList &input,
209                                              std::string &output,
210                                              bool is_callback) override;
211 
212   bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj,
213                           StructuredData::ObjectSP &callee_wrapper_sp,
214                           const TypeSummaryOptions &options,
215                           std::string &retval) override;
216 
217   bool FormatterCallbackFunction(const char *function_name,
218                                  lldb::TypeImplSP type_impl_sp) override;
219 
220   bool GetDocumentationForItem(const char *item, std::string &dest) override;
221 
222   bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
223                                     std::string &dest) override;
224 
225   uint32_t
226   GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override;
227 
228   bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
229                                    std::string &dest) override;
230 
231   bool CheckObjectExists(const char *name) override {
232     if (!name || !name[0])
233       return false;
234     std::string temp;
235     return GetDocumentationForItem(name, temp);
236   }
237 
238   bool RunScriptFormatKeyword(const char *impl_function, Process *process,
239                               std::string &output, Status &error) override;
240 
241   bool RunScriptFormatKeyword(const char *impl_function, Thread *thread,
242                               std::string &output, Status &error) override;
243 
244   bool RunScriptFormatKeyword(const char *impl_function, Target *target,
245                               std::string &output, Status &error) override;
246 
247   bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame,
248                               std::string &output, Status &error) override;
249 
250   bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value,
251                               std::string &output, Status &error) override;
252 
253   bool LoadScriptingModule(const char *filename,
254                            const LoadScriptOptions &options,
255                            lldb_private::Status &error,
256                            StructuredData::ObjectSP *module_sp = nullptr,
257                            FileSpec extra_search_dir = {}) override;
258 
259   bool IsReservedWord(const char *word) override;
260 
261   std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override;
262 
263   void CollectDataForBreakpointCommandCallback(
264       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
265       CommandReturnObject &result) override;
266 
267   void
268   CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
269                                           CommandReturnObject &result) override;
270 
271   /// Set the callback body text into the callback for the breakpoint.
272   Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
273                                       const char *callback_body,
274                                       bool is_callback) override;
275 
276   Status SetBreakpointCommandCallbackFunction(
277       BreakpointOptions &bp_options, const char *function_name,
278       StructuredData::ObjectSP extra_args_sp) override;
279 
280   /// This one is for deserialization:
281   Status SetBreakpointCommandCallback(
282       BreakpointOptions &bp_options,
283       std::unique_ptr<BreakpointOptions::CommandData> &data_up) override;
284 
285   Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
286                                       const char *command_body_text,
287                                       StructuredData::ObjectSP extra_args_sp,
288                                       bool uses_extra_args,
289                                       bool is_callback);
290 
291   /// Set a one-liner as the callback for the watchpoint.
292   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
293                                     const char *user_input,
294                                     bool is_callback) override;
295 
296   const char *GetDictionaryName() { return m_dictionary_name.c_str(); }
297 
298   PyThreadState *GetThreadState() { return m_command_thread_state; }
299 
300   void SetThreadState(PyThreadState *s) {
301     if (s)
302       m_command_thread_state = s;
303   }
304 
305   // IOHandlerDelegate
306   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override;
307 
308   void IOHandlerInputComplete(IOHandler &io_handler,
309                               std::string &data) override;
310 
311   static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger);
312 
313   // PluginInterface protocol
314   llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); }
315 
316   class Locker : public ScriptInterpreterLocker {
317   public:
318     enum OnEntry {
319       AcquireLock = 0x0001,
320       InitSession = 0x0002,
321       InitGlobals = 0x0004,
322       NoSTDIN = 0x0008
323     };
324 
325     enum OnLeave {
326       FreeLock = 0x0001,
327       FreeAcquiredLock = 0x0002, // do not free the lock if we already held it
328                                  // when calling constructor
329       TearDownSession = 0x0004
330     };
331 
332     Locker(ScriptInterpreterPythonImpl *py_interpreter,
333            uint16_t on_entry = AcquireLock | InitSession,
334            uint16_t on_leave = FreeLock | TearDownSession,
335            lldb::FileSP in = nullptr, lldb::FileSP out = nullptr,
336            lldb::FileSP err = nullptr);
337 
338     ~Locker() override;
339 
340   private:
341     bool DoAcquireLock();
342 
343     bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in,
344                        lldb::FileSP out, lldb::FileSP err);
345 
346     bool DoFreeLock();
347 
348     bool DoTearDownSession();
349 
350     bool m_teardown_session;
351     ScriptInterpreterPythonImpl *m_python_interpreter;
352     PyGILState_STATE m_GILState;
353   };
354 
355   static bool BreakpointCallbackFunction(void *baton,
356                                          StoppointCallbackContext *context,
357                                          lldb::user_id_t break_id,
358                                          lldb::user_id_t break_loc_id);
359   static bool WatchpointCallbackFunction(void *baton,
360                                          StoppointCallbackContext *context,
361                                          lldb::user_id_t watch_id);
362   static void Initialize();
363 
364   class SynchronicityHandler {
365   private:
366     lldb::DebuggerSP m_debugger_sp;
367     ScriptedCommandSynchronicity m_synch_wanted;
368     bool m_old_asynch;
369 
370   public:
371     SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity);
372 
373     ~SynchronicityHandler();
374   };
375 
376   enum class AddLocation { Beginning, End };
377 
378   static void AddToSysPath(AddLocation location, std::string path);
379 
380   bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out,
381                     lldb::FileSP err);
382 
383   void LeaveSession();
384 
385   uint32_t IsExecutingPython() {
386     std::lock_guard<std::mutex> guard(m_mutex);
387     return m_lock_count > 0;
388   }
389 
390   uint32_t IncrementLockCount() {
391     std::lock_guard<std::mutex> guard(m_mutex);
392     return ++m_lock_count;
393   }
394 
395   uint32_t DecrementLockCount() {
396     std::lock_guard<std::mutex> guard(m_mutex);
397     if (m_lock_count > 0)
398       --m_lock_count;
399     return m_lock_count;
400   }
401 
402   enum ActiveIOHandler {
403     eIOHandlerNone,
404     eIOHandlerBreakpoint,
405     eIOHandlerWatchpoint
406   };
407 
408   python::PythonModule &GetMainModule();
409 
410   python::PythonDictionary &GetSessionDictionary();
411 
412   python::PythonDictionary &GetSysModuleDictionary();
413 
414   llvm::Expected<unsigned> GetMaxPositionalArgumentsForCallable(
415       const llvm::StringRef &callable_name) override;
416 
417   bool GetEmbeddedInterpreterModuleObjects();
418 
419   bool SetStdHandle(lldb::FileSP file, const char *py_name,
420                     python::PythonObject &save_file, const char *mode);
421 
422   python::PythonObject m_saved_stdin;
423   python::PythonObject m_saved_stdout;
424   python::PythonObject m_saved_stderr;
425   python::PythonModule m_main_module;
426   python::PythonDictionary m_session_dict;
427   python::PythonDictionary m_sys_module_dict;
428   python::PythonObject m_run_one_line_function;
429   python::PythonObject m_run_one_line_str_global;
430   std::string m_dictionary_name;
431   ActiveIOHandler m_active_io_handler;
432   bool m_session_is_active;
433   bool m_pty_secondary_is_open;
434   bool m_valid_session;
435   uint32_t m_lock_count;
436   std::mutex m_mutex;
437   PyThreadState *m_command_thread_state;
438 };
439 
440 class IOHandlerPythonInterpreter : public IOHandler {
441 public:
442   IOHandlerPythonInterpreter(Debugger &debugger,
443                              ScriptInterpreterPythonImpl *python)
444       : IOHandler(debugger, IOHandler::Type::PythonInterpreter),
445         m_python(python) {}
446 
447   ~IOHandlerPythonInterpreter() override = default;
448 
449   llvm::StringRef GetControlSequence(char ch) override {
450     static constexpr llvm::StringLiteral control_sequence("quit()\n");
451     if (ch == 'd')
452       return control_sequence;
453     return {};
454   }
455 
456   void Run() override {
457     if (m_python) {
458       int stdin_fd = GetInputFD();
459       if (stdin_fd >= 0) {
460         Terminal terminal(stdin_fd);
461         TerminalState terminal_state(terminal);
462 
463         if (terminal.IsATerminal()) {
464           // FIXME: error handling?
465           llvm::consumeError(terminal.SetCanonical(false));
466           llvm::consumeError(terminal.SetEcho(true));
467         }
468 
469         ScriptInterpreterPythonImpl::Locker locker(
470             m_python,
471             ScriptInterpreterPythonImpl::Locker::AcquireLock |
472                 ScriptInterpreterPythonImpl::Locker::InitSession |
473                 ScriptInterpreterPythonImpl::Locker::InitGlobals,
474             ScriptInterpreterPythonImpl::Locker::FreeAcquiredLock |
475                 ScriptInterpreterPythonImpl::Locker::TearDownSession);
476 
477         // The following call drops into the embedded interpreter loop and
478         // stays there until the user chooses to exit from the Python
479         // interpreter. This embedded interpreter will, as any Python code that
480         // performs I/O, unlock the GIL before a system call that can hang, and
481         // lock it when the syscall has returned.
482 
483         // We need to surround the call to the embedded interpreter with calls
484         // to PyGILState_Ensure and PyGILState_Release (using the Locker
485         // above). This is because Python has a global lock which must be held
486         // whenever we want to touch any Python objects. Otherwise, if the user
487         // calls Python code, the interpreter state will be off, and things
488         // could hang (it's happened before).
489 
490         StreamString run_string;
491         run_string.Printf("run_python_interpreter (%s)",
492                           m_python->GetDictionaryName());
493         PyRun_SimpleString(run_string.GetData());
494       }
495     }
496     SetIsDone(true);
497   }
498 
499   void Cancel() override {}
500 
501   bool Interrupt() override { return m_python->Interrupt(); }
502 
503   void GotEOF() override {}
504 
505 protected:
506   ScriptInterpreterPythonImpl *m_python;
507 };
508 
509 } // namespace lldb_private
510 
511 #endif // LLDB_ENABLE_PYTHON
512 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
513