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   bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,
87                                       Event *event,
88                                       bool &script_error) override;
89 
90   bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,
91                                     Event *event, bool &script_error) override;
92 
93   bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,
94                                  bool &script_error) override;
95 
96   lldb::StateType
97   ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,
98                                 bool &script_error) override;
99 
100   StructuredData::GenericSP
101   CreateScriptedBreakpointResolver(const char *class_name,
102                                    const StructuredDataImpl &args_data,
103                                    lldb::BreakpointSP &bkpt_sp) override;
104   bool ScriptedBreakpointResolverSearchCallback(
105       StructuredData::GenericSP implementor_sp,
106       SymbolContext *sym_ctx) override;
107 
108   lldb::SearchDepth ScriptedBreakpointResolverSearchDepth(
109       StructuredData::GenericSP implementor_sp) override;
110 
111   StructuredData::GenericSP
112   CreateScriptedStopHook(lldb::TargetSP target_sp, const char *class_name,
113                          const StructuredDataImpl &args_data,
114                          Status &error) override;
115 
116   bool ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,
117                                   ExecutionContext &exc_ctx,
118                                   lldb::StreamSP stream_sp) override;
119 
120   StructuredData::GenericSP
121   CreateFrameRecognizer(const char *class_name) override;
122 
123   lldb::ValueObjectListSP
124   GetRecognizedArguments(const StructuredData::ObjectSP &implementor,
125                          lldb::StackFrameSP frame_sp) override;
126 
127   StructuredData::GenericSP
128   OSPlugin_CreatePluginObject(const char *class_name,
129                               lldb::ProcessSP process_sp) override;
130 
131   StructuredData::DictionarySP
132   OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
133 
134   StructuredData::ArraySP
135   OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
136 
137   StructuredData::StringSP
138   OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,
139                                lldb::tid_t thread_id) override;
140 
141   StructuredData::DictionarySP
142   OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,
143                         lldb::tid_t tid, lldb::addr_t context) override;
144 
145   StructuredData::ObjectSP
146   LoadPluginModule(const FileSpec &file_spec,
147                    lldb_private::Status &error) override;
148 
149   StructuredData::DictionarySP
150   GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target,
151                      const char *setting_name,
152                      lldb_private::Status &error) override;
153 
154   size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor,
155                               uint32_t max) override;
156 
157   lldb::ValueObjectSP
158   GetChildAtIndex(const StructuredData::ObjectSP &implementor,
159                   uint32_t idx) override;
160 
161   int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor,
162                               const char *child_name) override;
163 
164   bool UpdateSynthProviderInstance(
165       const StructuredData::ObjectSP &implementor) override;
166 
167   bool MightHaveChildrenSynthProviderInstance(
168       const StructuredData::ObjectSP &implementor) override;
169 
170   lldb::ValueObjectSP
171   GetSyntheticValue(const StructuredData::ObjectSP &implementor) override;
172 
173   ConstString
174   GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override;
175 
176   bool
177   RunScriptBasedCommand(const char *impl_function, llvm::StringRef args,
178                         ScriptedCommandSynchronicity synchronicity,
179                         lldb_private::CommandReturnObject &cmd_retobj,
180                         Status &error,
181                         const lldb_private::ExecutionContext &exe_ctx) override;
182 
183   bool RunScriptBasedCommand(
184       StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
185       ScriptedCommandSynchronicity synchronicity,
186       lldb_private::CommandReturnObject &cmd_retobj, Status &error,
187       const lldb_private::ExecutionContext &exe_ctx) override;
188 
189   Status GenerateFunction(const char *signature,
190                           const StringList &input) override;
191 
192   Status GenerateBreakpointCommandCallbackData(
193       StringList &input,
194       std::string &output,
195       bool has_extra_args) override;
196 
197   bool GenerateWatchpointCommandCallbackData(StringList &input,
198                                              std::string &output) override;
199 
200   bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj,
201                           StructuredData::ObjectSP &callee_wrapper_sp,
202                           const TypeSummaryOptions &options,
203                           std::string &retval) override;
204 
205   bool FormatterCallbackFunction(const char *function_name,
206                                  lldb::TypeImplSP type_impl_sp) override;
207 
208   bool GetDocumentationForItem(const char *item, std::string &dest) override;
209 
210   bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
211                                     std::string &dest) override;
212 
213   uint32_t
214   GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override;
215 
216   bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
217                                    std::string &dest) override;
218 
CheckObjectExists(const char * name)219   bool CheckObjectExists(const char *name) override {
220     if (!name || !name[0])
221       return false;
222     std::string temp;
223     return GetDocumentationForItem(name, temp);
224   }
225 
226   bool RunScriptFormatKeyword(const char *impl_function, Process *process,
227                               std::string &output, Status &error) override;
228 
229   bool RunScriptFormatKeyword(const char *impl_function, Thread *thread,
230                               std::string &output, Status &error) override;
231 
232   bool RunScriptFormatKeyword(const char *impl_function, Target *target,
233                               std::string &output, Status &error) override;
234 
235   bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame,
236                               std::string &output, Status &error) override;
237 
238   bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value,
239                               std::string &output, Status &error) override;
240 
241   bool LoadScriptingModule(const char *filename,
242                            const LoadScriptOptions &options,
243                            lldb_private::Status &error,
244                            StructuredData::ObjectSP *module_sp = nullptr,
245                            FileSpec extra_search_dir = {}) override;
246 
247   bool IsReservedWord(const char *word) override;
248 
249   std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override;
250 
251   void CollectDataForBreakpointCommandCallback(
252       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
253       CommandReturnObject &result) override;
254 
255   void
256   CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
257                                           CommandReturnObject &result) override;
258 
259   /// Set the callback body text into the callback for the breakpoint.
260   Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
261                                       const char *callback_body) override;
262 
263   Status SetBreakpointCommandCallbackFunction(
264       BreakpointOptions &bp_options, const char *function_name,
265       StructuredData::ObjectSP extra_args_sp) override;
266 
267   /// This one is for deserialization:
268   Status SetBreakpointCommandCallback(
269       BreakpointOptions &bp_options,
270       std::unique_ptr<BreakpointOptions::CommandData> &data_up) override;
271 
272   Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
273                                       const char *command_body_text,
274                                       StructuredData::ObjectSP extra_args_sp,
275                                       bool uses_extra_args);
276 
277   /// Set a one-liner as the callback for the watchpoint.
278   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
279                                     const char *oneliner) override;
280 
GetDictionaryName()281   const char *GetDictionaryName() { return m_dictionary_name.c_str(); }
282 
GetThreadState()283   PyThreadState *GetThreadState() { return m_command_thread_state; }
284 
SetThreadState(PyThreadState * s)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
GetPluginName()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 
IsExecutingPython()370   uint32_t IsExecutingPython() const { return m_lock_count > 0; }
371 
IncrementLockCount()372   uint32_t IncrementLockCount() { return ++m_lock_count; }
373 
DecrementLockCount()374   uint32_t DecrementLockCount() {
375     if (m_lock_count > 0)
376       --m_lock_count;
377     return m_lock_count;
378   }
379 
380   enum ActiveIOHandler {
381     eIOHandlerNone,
382     eIOHandlerBreakpoint,
383     eIOHandlerWatchpoint
384   };
385 
386   python::PythonModule &GetMainModule();
387 
388   python::PythonDictionary &GetSessionDictionary();
389 
390   python::PythonDictionary &GetSysModuleDictionary();
391 
392   llvm::Expected<unsigned> GetMaxPositionalArgumentsForCallable(
393       const llvm::StringRef &callable_name) override;
394 
395   bool GetEmbeddedInterpreterModuleObjects();
396 
397   bool SetStdHandle(lldb::FileSP file, const char *py_name,
398                     python::PythonObject &save_file, const char *mode);
399 
400   python::PythonObject m_saved_stdin;
401   python::PythonObject m_saved_stdout;
402   python::PythonObject m_saved_stderr;
403   python::PythonModule m_main_module;
404   python::PythonDictionary m_session_dict;
405   python::PythonDictionary m_sys_module_dict;
406   python::PythonObject m_run_one_line_function;
407   python::PythonObject m_run_one_line_str_global;
408   std::string m_dictionary_name;
409   ActiveIOHandler m_active_io_handler;
410   bool m_session_is_active;
411   bool m_pty_secondary_is_open;
412   bool m_valid_session;
413   uint32_t m_lock_count;
414   PyThreadState *m_command_thread_state;
415 };
416 
417 class IOHandlerPythonInterpreter : public IOHandler {
418 public:
IOHandlerPythonInterpreter(Debugger & debugger,ScriptInterpreterPythonImpl * python)419   IOHandlerPythonInterpreter(Debugger &debugger,
420                              ScriptInterpreterPythonImpl *python)
421       : IOHandler(debugger, IOHandler::Type::PythonInterpreter),
422         m_python(python) {}
423 
424   ~IOHandlerPythonInterpreter() override = default;
425 
GetControlSequence(char ch)426   ConstString GetControlSequence(char ch) override {
427     if (ch == 'd')
428       return ConstString("quit()\n");
429     return ConstString();
430   }
431 
Run()432   void Run() override {
433     if (m_python) {
434       int stdin_fd = GetInputFD();
435       if (stdin_fd >= 0) {
436         Terminal terminal(stdin_fd);
437         TerminalState terminal_state(terminal);
438 
439         if (terminal.IsATerminal()) {
440           // FIXME: error handling?
441           llvm::consumeError(terminal.SetCanonical(false));
442           llvm::consumeError(terminal.SetEcho(true));
443         }
444 
445         ScriptInterpreterPythonImpl::Locker locker(
446             m_python,
447             ScriptInterpreterPythonImpl::Locker::AcquireLock |
448                 ScriptInterpreterPythonImpl::Locker::InitSession |
449                 ScriptInterpreterPythonImpl::Locker::InitGlobals,
450             ScriptInterpreterPythonImpl::Locker::FreeAcquiredLock |
451                 ScriptInterpreterPythonImpl::Locker::TearDownSession);
452 
453         // The following call drops into the embedded interpreter loop and
454         // stays there until the user chooses to exit from the Python
455         // interpreter. This embedded interpreter will, as any Python code that
456         // performs I/O, unlock the GIL before a system call that can hang, and
457         // lock it when the syscall has returned.
458 
459         // We need to surround the call to the embedded interpreter with calls
460         // to PyGILState_Ensure and PyGILState_Release (using the Locker
461         // above). This is because Python has a global lock which must be held
462         // whenever we want to touch any Python objects. Otherwise, if the user
463         // calls Python code, the interpreter state will be off, and things
464         // could hang (it's happened before).
465 
466         StreamString run_string;
467         run_string.Printf("run_python_interpreter (%s)",
468                           m_python->GetDictionaryName());
469         PyRun_SimpleString(run_string.GetData());
470       }
471     }
472     SetIsDone(true);
473   }
474 
Cancel()475   void Cancel() override {}
476 
Interrupt()477   bool Interrupt() override { return m_python->Interrupt(); }
478 
GotEOF()479   void GotEOF() override {}
480 
481 protected:
482   ScriptInterpreterPythonImpl *m_python;
483 };
484 
485 } // namespace lldb_private
486 
487 #endif // LLDB_ENABLE_PYTHON
488 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
489