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