xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h (revision 9ac7a6c51f8643e8a44af41efca0c8c148315bc5)
1 //===-- ScriptInterpreterPython.h -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 
11 #ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
12 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
13 
14 #ifdef LLDB_DISABLE_PYTHON
15 
16 // Python is disabled in this build
17 
18 #else
19 
20 #include "lldb/lldb-private.h"
21 #include "PythonDataObjects.h"
22 #include "lldb/Core/IOHandler.h"
23 #include "lldb/Interpreter/ScriptInterpreter.h"
24 #include "lldb/Host/Terminal.h"
25 
26 class IOHandlerPythonInterpreter;
27 
28 namespace lldb_private {
29 
30 class ScriptInterpreterPython :
31     public ScriptInterpreter,
32     public IOHandlerDelegateMultiline
33 {
34 public:
35 #if PY_MAJOR_VERSION >= 3
36     typedef PyObject*(*SWIGInitCallback) (void);
37 #else
38     typedef void(*SWIGInitCallback) (void);
39 #endif
40 
41     typedef bool (*SWIGBreakpointCallbackFunction) (const char *python_function_name,
42                                                     const char *session_dictionary_name,
43                                                     const lldb::StackFrameSP& frame_sp,
44                                                     const lldb::BreakpointLocationSP &bp_loc_sp);
45 
46     typedef bool (*SWIGWatchpointCallbackFunction) (const char *python_function_name,
47                                                     const char *session_dictionary_name,
48                                                     const lldb::StackFrameSP& frame_sp,
49                                                     const lldb::WatchpointSP &wp_sp);
50 
51     typedef bool (*SWIGPythonTypeScriptCallbackFunction) (const char *python_function_name,
52                                                           void *session_dictionary,
53                                                           const lldb::ValueObjectSP& valobj_sp,
54                                                           void** pyfunct_wrapper,
55                                                           const lldb::TypeSummaryOptionsSP& options,
56                                                           std::string& retval);
57 
58     typedef void* (*SWIGPythonCreateSyntheticProvider) (const char *python_class_name,
59                                                         const char *session_dictionary_name,
60                                                         const lldb::ValueObjectSP& valobj_sp);
61 
62     typedef void* (*SWIGPythonCreateCommandObject) (const char *python_class_name,
63                                                     const char *session_dictionary_name,
64                                                     const lldb::DebuggerSP debugger_sp);
65 
66     typedef void* (*SWIGPythonCreateScriptedThreadPlan) (const char *python_class_name,
67                                                         const char *session_dictionary_name,
68                                                         const lldb::ThreadPlanSP& thread_plan_sp);
69 
70     typedef bool (*SWIGPythonCallThreadPlan) (void *implementor, const char *method_name, Event *event_sp, bool &got_error);
71 
72     typedef void* (*SWIGPythonCreateOSPlugin) (const char *python_class_name,
73                                                const char *session_dictionary_name,
74                                                const lldb::ProcessSP& process_sp);
75 
76     typedef size_t          (*SWIGPythonCalculateNumChildren)                   (void *implementor, uint32_t max);
77     typedef void*           (*SWIGPythonGetChildAtIndex)                        (void *implementor, uint32_t idx);
78     typedef int             (*SWIGPythonGetIndexOfChildWithName)                (void *implementor, const char* child_name);
79     typedef void*           (*SWIGPythonCastPyObjectToSBValue)                  (void* data);
80     typedef lldb::ValueObjectSP  (*SWIGPythonGetValueObjectSPFromSBValue)       (void* data);
81     typedef bool            (*SWIGPythonUpdateSynthProviderInstance)            (void* data);
82     typedef bool            (*SWIGPythonMightHaveChildrenSynthProviderInstance) (void* data);
83     typedef void*           (*SWIGPythonGetValueSynthProviderInstance)          (void *implementor);
84 
85     typedef bool            (*SWIGPythonCallCommand)            (const char *python_function_name,
86                                                                  const char *session_dictionary_name,
87                                                                  lldb::DebuggerSP& debugger,
88                                                                  const char* args,
89                                                                  lldb_private::CommandReturnObject& cmd_retobj,
90                                                                  lldb::ExecutionContextRefSP exe_ctx_ref_sp);
91 
92     typedef bool            (*SWIGPythonCallCommandObject)        (void *implementor,
93                                                                    lldb::DebuggerSP& debugger,
94                                                                    const char* args,
95                                                                    lldb_private::CommandReturnObject& cmd_retobj,
96                                                                    lldb::ExecutionContextRefSP exe_ctx_ref_sp);
97 
98 
99     typedef bool            (*SWIGPythonCallModuleInit)         (const char *python_module_name,
100                                                                  const char *session_dictionary_name,
101                                                                  lldb::DebuggerSP& debugger);
102 
103     typedef bool            (*SWIGPythonScriptKeyword_Process)  (const char* python_function_name,
104                                                                  const char* session_dictionary_name,
105                                                                  lldb::ProcessSP& process,
106                                                                  std::string& output);
107     typedef bool            (*SWIGPythonScriptKeyword_Thread)   (const char* python_function_name,
108                                                                  const char* session_dictionary_name,
109                                                                  lldb::ThreadSP& thread,
110                                                                  std::string& output);
111 
112     typedef bool            (*SWIGPythonScriptKeyword_Target)   (const char* python_function_name,
113                                                                  const char* session_dictionary_name,
114                                                                  lldb::TargetSP& target,
115                                                                  std::string& output);
116 
117     typedef bool            (*SWIGPythonScriptKeyword_Frame)    (const char* python_function_name,
118                                                                  const char* session_dictionary_name,
119                                                                  lldb::StackFrameSP& frame,
120                                                                  std::string& output);
121 
122     typedef bool            (*SWIGPythonScriptKeyword_Value)    (const char* python_function_name,
123                                                                  const char* session_dictionary_name,
124                                                                  lldb::ValueObjectSP& value,
125                                                                  std::string& output);
126 
127     typedef void*           (*SWIGPython_GetDynamicSetting)     (void* module,
128                                                                  const char* setting,
129                                                                  const lldb::TargetSP& target_sp);
130 
131     friend class ::IOHandlerPythonInterpreter;
132 
133     ScriptInterpreterPython (CommandInterpreter &interpreter);
134 
135     ~ScriptInterpreterPython() override;
136 
137     bool
138     Interrupt() override;
139 
140     bool
141     ExecuteOneLine (const char *command,
142                     CommandReturnObject *result,
143                     const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
144 
145     void
146     ExecuteInterpreterLoop () override;
147 
148     bool
149     ExecuteOneLineWithReturn (const char *in_string,
150                               ScriptInterpreter::ScriptReturnType return_type,
151                               void *ret_value,
152                               const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
153 
154     lldb_private::Error
155     ExecuteMultipleLines (const char *in_string,
156                           const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
157 
158     Error
159     ExportFunctionDefinitionToInterpreter (StringList &function_def) override;
160 
161     bool
162     GenerateTypeScriptFunction (StringList &input, std::string& output, const void* name_token = NULL) override;
163 
164     bool
165     GenerateTypeSynthClass (StringList &input, std::string& output, const void* name_token = NULL) override;
166 
167     bool
168     GenerateTypeSynthClass (const char* oneliner, std::string& output, const void* name_token = NULL) override;
169 
170     // use this if the function code is just a one-liner script
171     bool
172     GenerateTypeScriptFunction (const char* oneliner, std::string& output, const void* name_token = NULL) override;
173 
174     bool
175     GenerateScriptAliasFunction (StringList &input, std::string& output) override;
176 
177     StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override;
178 
179     StructuredData::GenericSP CreateScriptCommandObject (const char *class_name) override;
180 
181     StructuredData::ObjectSP CreateScriptedThreadPlan(const char *class_name, lldb::ThreadPlanSP thread_plan) override;
182 
183     bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) override;
184     bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) override;
185     lldb::StateType ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, bool &script_error) override;
186 
187     StructuredData::GenericSP OSPlugin_CreatePluginObject(const char *class_name, lldb::ProcessSP process_sp) override;
188 
189     StructuredData::DictionarySP OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
190 
191     StructuredData::ArraySP OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
192 
193     StructuredData::StringSP OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t thread_id) override;
194 
195     StructuredData::DictionarySP OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
196                                                        lldb::addr_t context) override;
197 
198     StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Error &error) override;
199 
200     StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name,
201                                                     lldb_private::Error &error) override;
202 
203     size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override;
204 
205     lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override;
206 
207     int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override;
208 
209     bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override;
210 
211     bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override;
212 
213     lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override;
214 
215     bool
216     RunScriptBasedCommand(const char* impl_function,
217                           const char* args,
218                           ScriptedCommandSynchronicity synchronicity,
219                           lldb_private::CommandReturnObject& cmd_retobj,
220                           Error& error,
221                           const lldb_private::ExecutionContext& exe_ctx) override;
222 
223     bool
224     RunScriptBasedCommand (StructuredData::GenericSP impl_obj_sp,
225                            const char* args,
226                            ScriptedCommandSynchronicity synchronicity,
227                            lldb_private::CommandReturnObject& cmd_retobj,
228                            Error& error,
229                            const lldb_private::ExecutionContext& exe_ctx) override;
230 
231     Error
232     GenerateFunction(const char *signature, const StringList &input) override;
233 
234     Error
235     GenerateBreakpointCommandCallbackData (StringList &input, std::string& output) override;
236 
237     bool
238     GenerateWatchpointCommandCallbackData (StringList &input, std::string& output) override;
239 
240 //    static size_t
241 //    GenerateBreakpointOptionsCommandCallback (void *baton,
242 //                                              InputReader &reader,
243 //                                              lldb::InputReaderAction notification,
244 //                                              const char *bytes,
245 //                                              size_t bytes_len);
246 //
247 //    static size_t
248 //    GenerateWatchpointOptionsCommandCallback (void *baton,
249 //                                              InputReader &reader,
250 //                                              lldb::InputReaderAction notification,
251 //                                              const char *bytes,
252 //                                              size_t bytes_len);
253 
254     static bool
255     BreakpointCallbackFunction (void *baton,
256                                 StoppointCallbackContext *context,
257                                 lldb::user_id_t break_id,
258                                 lldb::user_id_t break_loc_id);
259 
260     static bool
261     WatchpointCallbackFunction (void *baton,
262                                 StoppointCallbackContext *context,
263                                 lldb::user_id_t watch_id);
264 
265     bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp,
266                             const TypeSummaryOptions &options, std::string &retval) override;
267 
268     void
269     Clear () override;
270 
271     bool
272     GetDocumentationForItem (const char* item, std::string& dest) override;
273 
274     bool
275     GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string& dest) override;
276 
277     uint32_t
278     GetFlagsForCommandObject (StructuredData::GenericSP cmd_obj_sp) override;
279 
280     bool
281     GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string& dest) override;
282 
283     bool
284     CheckObjectExists (const char* name) override
285     {
286         if (!name || !name[0])
287             return false;
288         std::string temp;
289         return GetDocumentationForItem (name,temp);
290     }
291 
292     bool
293     RunScriptFormatKeyword (const char* impl_function,
294                             Process* process,
295                             std::string& output,
296                             Error& error) override;
297 
298     bool
299     RunScriptFormatKeyword (const char* impl_function,
300                             Thread* thread,
301                             std::string& output,
302                             Error& error) override;
303 
304     bool
305     RunScriptFormatKeyword (const char* impl_function,
306                             Target* target,
307                             std::string& output,
308                             Error& error) override;
309 
310     bool
311     RunScriptFormatKeyword (const char* impl_function,
312                             StackFrame* frame,
313                             std::string& output,
314                             Error& error) override;
315 
316     bool
317     RunScriptFormatKeyword (const char* impl_function,
318                             ValueObject* value,
319                             std::string& output,
320                             Error& error) override;
321 
322     bool LoadScriptingModule(const char *filename, bool can_reload, bool init_session, lldb_private::Error &error,
323                              StructuredData::ObjectSP *module_sp = nullptr) override;
324 
325     bool
326     IsReservedWord (const char* word) override;
327 
328     std::unique_ptr<ScriptInterpreterLocker>
329     AcquireInterpreterLock () override;
330 
331     void
332     CollectDataForBreakpointCommandCallback (std::vector<BreakpointOptions *> &bp_options_vec,
333                                              CommandReturnObject &result) override;
334 
335     void
336     CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
337                                              CommandReturnObject &result) override;
338 
339     /// Set the callback body text into the callback for the breakpoint.
340     Error
341     SetBreakpointCommandCallback (BreakpointOptions *bp_options,
342                                   const char *callback_body) override;
343 
344     void
345     SetBreakpointCommandCallbackFunction (BreakpointOptions *bp_options,
346                                           const char *function_name) override;
347 
348     /// Set a one-liner as the callback for the watchpoint.
349     void
350     SetWatchpointCommandCallback (WatchpointOptions *wp_options,
351                                   const char *oneliner) override;
352 
353     StringList
354     ReadCommandInputFromUser (FILE *in_file);
355 
356     void ResetOutputFileHandle(FILE *new_fh) override;
357 
358     static void
359     InitializePrivate ();
360 
361     static void
362     InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
363                            SWIGBreakpointCallbackFunction swig_breakpoint_callback,
364                            SWIGWatchpointCallbackFunction swig_watchpoint_callback,
365                            SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
366                            SWIGPythonCreateSyntheticProvider swig_synthetic_script,
367                            SWIGPythonCreateCommandObject swig_create_cmd,
368                            SWIGPythonCalculateNumChildren swig_calc_children,
369                            SWIGPythonGetChildAtIndex swig_get_child_index,
370                            SWIGPythonGetIndexOfChildWithName swig_get_index_child,
371                            SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue ,
372                            SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
373                            SWIGPythonUpdateSynthProviderInstance swig_update_provider,
374                            SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider,
375                            SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
376                            SWIGPythonCallCommand swig_call_command,
377                            SWIGPythonCallCommandObject swig_call_command_object,
378                            SWIGPythonCallModuleInit swig_call_module_init,
379                            SWIGPythonCreateOSPlugin swig_create_os_plugin,
380                            SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
381                            SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
382                            SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
383                            SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
384                            SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
385                            SWIGPython_GetDynamicSetting swig_plugin_get,
386                            SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
387                            SWIGPythonCallThreadPlan swig_call_thread_plan);
388 
389     const char *
390     GetDictionaryName ()
391     {
392         return m_dictionary_name.c_str();
393     }
394 
395 
396     PyThreadState *
397     GetThreadState()
398     {
399         return m_command_thread_state;
400     }
401 
402     void
403     SetThreadState (PyThreadState *s)
404     {
405         if (s)
406             m_command_thread_state = s;
407     }
408 
409     //----------------------------------------------------------------------
410     // IOHandlerDelegate
411     //----------------------------------------------------------------------
412     void
413     IOHandlerActivated (IOHandler &io_handler) override;
414 
415     void
416     IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override;
417 
418 
419     //------------------------------------------------------------------
420     // Static Functions
421     //------------------------------------------------------------------
422     static void
423     Initialize();
424 
425     static void
426     Terminate();
427 
428     static lldb::ScriptInterpreterSP
429     CreateInstance(CommandInterpreter &interpreter);
430 
431     static lldb_private::ConstString
432     GetPluginNameStatic();
433 
434     static const char *
435     GetPluginDescriptionStatic();
436 
437     //------------------------------------------------------------------
438     // PluginInterface protocol
439     //------------------------------------------------------------------
440     virtual lldb_private::ConstString
441     GetPluginName() override;
442 
443     virtual uint32_t
444     GetPluginVersion() override;
445 
446 protected:
447 
448     bool
449     EnterSession (uint16_t on_entry_flags,
450                   FILE *in,
451                   FILE *out,
452                   FILE *err);
453 
454     void
455     LeaveSession ();
456 
457     void
458     SaveTerminalState (int fd);
459 
460     void
461     RestoreTerminalState ();
462 
463     class SynchronicityHandler
464     {
465     private:
466         lldb::DebuggerSP             m_debugger_sp;
467         ScriptedCommandSynchronicity m_synch_wanted;
468         bool                         m_old_asynch;
469     public:
470         SynchronicityHandler(lldb::DebuggerSP,
471                              ScriptedCommandSynchronicity);
472         ~SynchronicityHandler();
473     };
474 
475 public:
476 	class Locker : public ScriptInterpreterLocker
477 	{
478 	public:
479 
480         enum OnEntry
481         {
482             AcquireLock         = 0x0001,
483             InitSession         = 0x0002,
484             InitGlobals         = 0x0004,
485             NoSTDIN             = 0x0008
486         };
487 
488         enum OnLeave
489         {
490             FreeLock            = 0x0001,
491             FreeAcquiredLock    = 0x0002,    // do not free the lock if we already held it when calling constructor
492             TearDownSession     = 0x0004
493         };
494 
495         Locker (ScriptInterpreterPython *py_interpreter = NULL,
496                 uint16_t on_entry = AcquireLock | InitSession,
497                 uint16_t on_leave = FreeLock | TearDownSession,
498                 FILE *in = NULL,
499                 FILE *out = NULL,
500                 FILE *err = NULL);
501 
502         ~Locker () override;
503 
504 	private:
505 
506         bool
507         DoAcquireLock ();
508 
509         bool
510         DoInitSession (uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err);
511 
512         bool
513         DoFreeLock ();
514 
515         bool
516         DoTearDownSession ();
517 
518         static void
519         ReleasePythonLock ();
520 
521     	bool                     m_teardown_session;
522     	ScriptInterpreterPython *m_python_interpreter;
523 //    	FILE*                    m_tmp_fh;
524         PyGILState_STATE         m_GILState;
525 	};
526 protected:
527 
528     enum class AddLocation
529     {
530         Beginning,
531         End
532     };
533 
534     static void AddToSysPath(AddLocation location, std::string path);
535 
536     uint32_t
537     IsExecutingPython () const
538     {
539         return m_lock_count > 0;
540     }
541 
542     uint32_t
543     IncrementLockCount()
544     {
545         return ++m_lock_count;
546     }
547 
548     uint32_t
549     DecrementLockCount()
550     {
551         if (m_lock_count > 0)
552             --m_lock_count;
553         return m_lock_count;
554     }
555 
556     enum ActiveIOHandler {
557         eIOHandlerNone,
558         eIOHandlerBreakpoint,
559         eIOHandlerWatchpoint
560     };
561 
562     PythonObject &GetMainModule();
563 
564     PythonDictionary &
565     GetSessionDictionary ();
566 
567     PythonDictionary &
568     GetSysModuleDictionary ();
569 
570     bool
571     GetEmbeddedInterpreterModuleObjects ();
572 
573     PythonFile m_saved_stdin;
574     PythonFile m_saved_stdout;
575     PythonFile m_saved_stderr;
576     PythonObject m_main_module;
577     PythonObject m_lldb_module;
578     PythonDictionary m_session_dict;
579     PythonDictionary m_sys_module_dict;
580     PythonObject m_run_one_line_function;
581     PythonObject m_run_one_line_str_global;
582     std::string m_dictionary_name;
583     TerminalState m_terminal_state;
584     ActiveIOHandler m_active_io_handler;
585     bool m_session_is_active;
586     bool m_pty_slave_is_open;
587     bool m_valid_session;
588     uint32_t m_lock_count;
589     PyThreadState *m_command_thread_state;
590 };
591 } // namespace lldb_private
592 
593 #endif // LLDB_DISABLE_PYTHON
594 
595 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
596