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