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