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