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