1 //===-- ScriptInterpreterPython.h -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
11 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H
13 #ifdef LLDB_DISABLE_PYTHON
15 // Python is disabled in this build
25 // Other libraries and framework includes
27 #include "PythonDataObjects.h"
28 #include "lldb/Breakpoint/BreakpointOptions.h"
29 #include "lldb/Core/IOHandler.h"
30 #include "lldb/Host/Terminal.h"
31 #include "lldb/Interpreter/ScriptInterpreter.h"
32 #include "lldb/lldb-private.h"
34 class IOHandlerPythonInterpreter;
36 namespace lldb_private {
38 class ScriptInterpreterPython : public ScriptInterpreter,
39 public IOHandlerDelegateMultiline {
41 class CommandDataPython : public BreakpointOptions::CommandData {
43 CommandDataPython() : BreakpointOptions::CommandData() {
44 interpreter = lldb::eScriptLanguagePython;
48 #if PY_MAJOR_VERSION >= 3
49 typedef PyObject *(*SWIGInitCallback)(void);
51 typedef void (*SWIGInitCallback)(void);
54 typedef bool (*SWIGBreakpointCallbackFunction)(
55 const char *python_function_name, const char *session_dictionary_name,
56 const lldb::StackFrameSP &frame_sp,
57 const lldb::BreakpointLocationSP &bp_loc_sp);
59 typedef bool (*SWIGWatchpointCallbackFunction)(
60 const char *python_function_name, const char *session_dictionary_name,
61 const lldb::StackFrameSP &frame_sp, const lldb::WatchpointSP &wp_sp);
63 typedef bool (*SWIGPythonTypeScriptCallbackFunction)(
64 const char *python_function_name, void *session_dictionary,
65 const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
66 const lldb::TypeSummaryOptionsSP &options, std::string &retval);
68 typedef void *(*SWIGPythonCreateSyntheticProvider)(
69 const char *python_class_name, const char *session_dictionary_name,
70 const lldb::ValueObjectSP &valobj_sp);
72 typedef void *(*SWIGPythonCreateCommandObject)(
73 const char *python_class_name, const char *session_dictionary_name,
74 const lldb::DebuggerSP debugger_sp);
76 typedef void *(*SWIGPythonCreateScriptedThreadPlan)(
77 const char *python_class_name, const char *session_dictionary_name,
78 const lldb::ThreadPlanSP &thread_plan_sp);
80 typedef bool (*SWIGPythonCallThreadPlan)(void *implementor,
81 const char *method_name,
82 Event *event_sp, bool &got_error);
84 typedef void *(*SWIGPythonCreateOSPlugin)(const char *python_class_name,
85 const char *session_dictionary_name,
86 const lldb::ProcessSP &process_sp);
88 typedef size_t (*SWIGPythonCalculateNumChildren)(void *implementor,
91 typedef void *(*SWIGPythonGetChildAtIndex)(void *implementor, uint32_t idx);
93 typedef int (*SWIGPythonGetIndexOfChildWithName)(void *implementor,
94 const char *child_name);
96 typedef void *(*SWIGPythonCastPyObjectToSBValue)(void *data);
98 typedef lldb::ValueObjectSP (*SWIGPythonGetValueObjectSPFromSBValue)(
101 typedef bool (*SWIGPythonUpdateSynthProviderInstance)(void *data);
103 typedef bool (*SWIGPythonMightHaveChildrenSynthProviderInstance)(void *data);
105 typedef void *(*SWIGPythonGetValueSynthProviderInstance)(void *implementor);
107 typedef bool (*SWIGPythonCallCommand)(
108 const char *python_function_name, const char *session_dictionary_name,
109 lldb::DebuggerSP &debugger, const char *args,
110 lldb_private::CommandReturnObject &cmd_retobj,
111 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
113 typedef bool (*SWIGPythonCallCommandObject)(
114 void *implementor, lldb::DebuggerSP &debugger, const char *args,
115 lldb_private::CommandReturnObject &cmd_retobj,
116 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
118 typedef bool (*SWIGPythonCallModuleInit)(const char *python_module_name,
119 const char *session_dictionary_name,
120 lldb::DebuggerSP &debugger);
122 typedef bool (*SWIGPythonScriptKeyword_Process)(
123 const char *python_function_name, const char *session_dictionary_name,
124 lldb::ProcessSP &process, std::string &output);
126 typedef bool (*SWIGPythonScriptKeyword_Thread)(
127 const char *python_function_name, const char *session_dictionary_name,
128 lldb::ThreadSP &thread, std::string &output);
130 typedef bool (*SWIGPythonScriptKeyword_Target)(
131 const char *python_function_name, const char *session_dictionary_name,
132 lldb::TargetSP &target, std::string &output);
134 typedef bool (*SWIGPythonScriptKeyword_Frame)(
135 const char *python_function_name, const char *session_dictionary_name,
136 lldb::StackFrameSP &frame, std::string &output);
138 typedef bool (*SWIGPythonScriptKeyword_Value)(
139 const char *python_function_name, const char *session_dictionary_name,
140 lldb::ValueObjectSP &value, std::string &output);
142 typedef void *(*SWIGPython_GetDynamicSetting)(
143 void *module, const char *setting, const lldb::TargetSP &target_sp);
145 friend class ::IOHandlerPythonInterpreter;
147 ScriptInterpreterPython(CommandInterpreter &interpreter);
149 ~ScriptInterpreterPython() override;
151 bool Interrupt() override;
154 llvm::StringRef command, CommandReturnObject *result,
155 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
157 void ExecuteInterpreterLoop() override;
159 bool ExecuteOneLineWithReturn(
160 llvm::StringRef in_string,
161 ScriptInterpreter::ScriptReturnType return_type, void *ret_value,
162 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
164 lldb_private::Status ExecuteMultipleLines(
165 const char *in_string,
166 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
169 ExportFunctionDefinitionToInterpreter(StringList &function_def) override;
171 bool GenerateTypeScriptFunction(StringList &input, std::string &output,
172 const void *name_token = nullptr) override;
174 bool GenerateTypeSynthClass(StringList &input, std::string &output,
175 const void *name_token = nullptr) override;
177 bool GenerateTypeSynthClass(const char *oneliner, std::string &output,
178 const void *name_token = nullptr) override;
180 // use this if the function code is just a one-liner script
181 bool GenerateTypeScriptFunction(const char *oneliner, std::string &output,
182 const void *name_token = nullptr) override;
184 bool GenerateScriptAliasFunction(StringList &input,
185 std::string &output) override;
187 StructuredData::ObjectSP
188 CreateSyntheticScriptedProvider(const char *class_name,
189 lldb::ValueObjectSP valobj) override;
191 StructuredData::GenericSP
192 CreateScriptCommandObject(const char *class_name) override;
194 StructuredData::ObjectSP
195 CreateScriptedThreadPlan(const char *class_name,
196 lldb::ThreadPlanSP thread_plan) override;
198 bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,
200 bool &script_error) override;
202 bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,
203 Event *event, bool &script_error) override;
205 bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,
206 bool &script_error) override;
209 ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,
210 bool &script_error) override;
212 StructuredData::GenericSP
213 OSPlugin_CreatePluginObject(const char *class_name,
214 lldb::ProcessSP process_sp) override;
216 StructuredData::DictionarySP
217 OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
219 StructuredData::ArraySP
220 OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override;
222 StructuredData::StringSP
223 OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,
224 lldb::tid_t thread_id) override;
226 StructuredData::DictionarySP
227 OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,
228 lldb::tid_t tid, lldb::addr_t context) override;
230 StructuredData::ObjectSP
231 LoadPluginModule(const FileSpec &file_spec,
232 lldb_private::Status &error) override;
234 StructuredData::DictionarySP
235 GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target,
236 const char *setting_name,
237 lldb_private::Status &error) override;
239 size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor,
240 uint32_t max) override;
243 GetChildAtIndex(const StructuredData::ObjectSP &implementor,
244 uint32_t idx) override;
246 int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor,
247 const char *child_name) override;
249 bool UpdateSynthProviderInstance(
250 const StructuredData::ObjectSP &implementor) override;
252 bool MightHaveChildrenSynthProviderInstance(
253 const StructuredData::ObjectSP &implementor) override;
256 GetSyntheticValue(const StructuredData::ObjectSP &implementor) override;
259 GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override;
262 RunScriptBasedCommand(const char *impl_function, llvm::StringRef args,
263 ScriptedCommandSynchronicity synchronicity,
264 lldb_private::CommandReturnObject &cmd_retobj,
266 const lldb_private::ExecutionContext &exe_ctx) override;
268 bool RunScriptBasedCommand(
269 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
270 ScriptedCommandSynchronicity synchronicity,
271 lldb_private::CommandReturnObject &cmd_retobj, Status &error,
272 const lldb_private::ExecutionContext &exe_ctx) override;
274 Status GenerateFunction(const char *signature,
275 const StringList &input) override;
277 Status GenerateBreakpointCommandCallbackData(StringList &input,
278 std::string &output) override;
280 bool GenerateWatchpointCommandCallbackData(StringList &input,
281 std::string &output) override;
284 // GenerateBreakpointOptionsCommandCallback (void *baton,
285 // InputReader &reader,
286 // lldb::InputReaderAction
288 // const char *bytes,
289 // size_t bytes_len);
292 // GenerateWatchpointOptionsCommandCallback (void *baton,
293 // InputReader &reader,
294 // lldb::InputReaderAction
296 // const char *bytes,
297 // size_t bytes_len);
299 static bool BreakpointCallbackFunction(void *baton,
300 StoppointCallbackContext *context,
301 lldb::user_id_t break_id,
302 lldb::user_id_t break_loc_id);
304 static bool WatchpointCallbackFunction(void *baton,
305 StoppointCallbackContext *context,
306 lldb::user_id_t watch_id);
308 bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj,
309 StructuredData::ObjectSP &callee_wrapper_sp,
310 const TypeSummaryOptions &options,
311 std::string &retval) override;
313 void Clear() override;
315 bool GetDocumentationForItem(const char *item, std::string &dest) override;
317 bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
318 std::string &dest) override;
321 GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override;
323 bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,
324 std::string &dest) override;
326 bool CheckObjectExists(const char *name) override {
327 if (!name || !name[0])
330 return GetDocumentationForItem(name, temp);
333 bool RunScriptFormatKeyword(const char *impl_function, Process *process,
334 std::string &output, Status &error) override;
336 bool RunScriptFormatKeyword(const char *impl_function, Thread *thread,
337 std::string &output, Status &error) override;
339 bool RunScriptFormatKeyword(const char *impl_function, Target *target,
340 std::string &output, Status &error) override;
342 bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame,
343 std::string &output, Status &error) override;
345 bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value,
346 std::string &output, Status &error) override;
349 LoadScriptingModule(const char *filename, bool can_reload, bool init_session,
350 lldb_private::Status &error,
351 StructuredData::ObjectSP *module_sp = nullptr) override;
353 bool IsReservedWord(const char *word) override;
355 std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override;
357 void CollectDataForBreakpointCommandCallback(
358 std::vector<BreakpointOptions *> &bp_options_vec,
359 CommandReturnObject &result) override;
362 CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
363 CommandReturnObject &result) override;
365 /// Set the callback body text into the callback for the breakpoint.
366 Status SetBreakpointCommandCallback(BreakpointOptions *bp_options,
367 const char *callback_body) override;
369 void SetBreakpointCommandCallbackFunction(BreakpointOptions *bp_options,
370 const char *function_name) override;
372 /// This one is for deserialization:
373 Status SetBreakpointCommandCallback(
374 BreakpointOptions *bp_options,
375 std::unique_ptr<BreakpointOptions::CommandData> &data_up) override;
377 /// Set a one-liner as the callback for the watchpoint.
378 void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
379 const char *oneliner) override;
381 StringList ReadCommandInputFromUser(FILE *in_file);
383 void ResetOutputFileHandle(FILE *new_fh) override;
385 static void InitializePrivate();
387 static void InitializeInterpreter(
388 SWIGInitCallback python_swig_init_callback,
389 SWIGBreakpointCallbackFunction swig_breakpoint_callback,
390 SWIGWatchpointCallbackFunction swig_watchpoint_callback,
391 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
392 SWIGPythonCreateSyntheticProvider swig_synthetic_script,
393 SWIGPythonCreateCommandObject swig_create_cmd,
394 SWIGPythonCalculateNumChildren swig_calc_children,
395 SWIGPythonGetChildAtIndex swig_get_child_index,
396 SWIGPythonGetIndexOfChildWithName swig_get_index_child,
397 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue,
398 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
399 SWIGPythonUpdateSynthProviderInstance swig_update_provider,
400 SWIGPythonMightHaveChildrenSynthProviderInstance
401 swig_mighthavechildren_provider,
402 SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
403 SWIGPythonCallCommand swig_call_command,
404 SWIGPythonCallCommandObject swig_call_command_object,
405 SWIGPythonCallModuleInit swig_call_module_init,
406 SWIGPythonCreateOSPlugin swig_create_os_plugin,
407 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
408 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
409 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
410 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
411 SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
412 SWIGPython_GetDynamicSetting swig_plugin_get,
413 SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
414 SWIGPythonCallThreadPlan swig_call_thread_plan);
416 const char *GetDictionaryName() { return m_dictionary_name.c_str(); }
418 PyThreadState *GetThreadState() { return m_command_thread_state; }
420 void SetThreadState(PyThreadState *s) {
422 m_command_thread_state = s;
425 //----------------------------------------------------------------------
427 //----------------------------------------------------------------------
428 void IOHandlerActivated(IOHandler &io_handler) override;
430 void IOHandlerInputComplete(IOHandler &io_handler,
431 std::string &data) override;
433 //------------------------------------------------------------------
435 //------------------------------------------------------------------
436 static void Initialize();
438 static void Terminate();
440 static lldb::ScriptInterpreterSP
441 CreateInstance(CommandInterpreter &interpreter);
443 static lldb_private::ConstString GetPluginNameStatic();
445 static const char *GetPluginDescriptionStatic();
447 static FileSpec GetPythonDir();
449 //------------------------------------------------------------------
450 // PluginInterface protocol
451 //------------------------------------------------------------------
452 lldb_private::ConstString GetPluginName() override;
454 uint32_t GetPluginVersion() override;
456 class Locker : public ScriptInterpreterLocker {
459 AcquireLock = 0x0001,
460 InitSession = 0x0002,
461 InitGlobals = 0x0004,
467 FreeAcquiredLock = 0x0002, // do not free the lock if we already held it
468 // when calling constructor
469 TearDownSession = 0x0004
472 Locker(ScriptInterpreterPython *py_interpreter = nullptr,
473 uint16_t on_entry = AcquireLock | InitSession,
474 uint16_t on_leave = FreeLock | TearDownSession, FILE *in = nullptr,
475 FILE *out = nullptr, FILE *err = nullptr);
480 bool DoAcquireLock();
482 bool DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err);
486 bool DoTearDownSession();
488 static void ReleasePythonLock();
490 bool m_teardown_session;
491 ScriptInterpreterPython *m_python_interpreter;
493 PyGILState_STATE m_GILState;
497 class SynchronicityHandler {
499 lldb::DebuggerSP m_debugger_sp;
500 ScriptedCommandSynchronicity m_synch_wanted;
504 SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity);
506 ~SynchronicityHandler();
509 enum class AddLocation { Beginning, End };
511 static void AddToSysPath(AddLocation location, std::string path);
513 static void ComputePythonDirForApple(llvm::SmallVectorImpl<char> &path);
514 static void ComputePythonDirForPosix(llvm::SmallVectorImpl<char> &path);
515 static void ComputePythonDirForWindows(llvm::SmallVectorImpl<char> &path);
517 bool EnterSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err);
521 void SaveTerminalState(int fd);
523 void RestoreTerminalState();
525 uint32_t IsExecutingPython() const { return m_lock_count > 0; }
527 uint32_t IncrementLockCount() { return ++m_lock_count; }
529 uint32_t DecrementLockCount() {
530 if (m_lock_count > 0)
535 enum ActiveIOHandler {
537 eIOHandlerBreakpoint,
541 PythonObject &GetMainModule();
543 PythonDictionary &GetSessionDictionary();
545 PythonDictionary &GetSysModuleDictionary();
547 bool GetEmbeddedInterpreterModuleObjects();
549 bool SetStdHandle(File &file, const char *py_name, PythonFile &save_file,
552 PythonFile m_saved_stdin;
553 PythonFile m_saved_stdout;
554 PythonFile m_saved_stderr;
555 PythonObject m_main_module;
556 PythonObject m_lldb_module;
557 PythonDictionary m_session_dict;
558 PythonDictionary m_sys_module_dict;
559 PythonObject m_run_one_line_function;
560 PythonObject m_run_one_line_str_global;
561 std::string m_dictionary_name;
562 TerminalState m_terminal_state;
563 ActiveIOHandler m_active_io_handler;
564 bool m_session_is_active;
565 bool m_pty_slave_is_open;
566 bool m_valid_session;
567 uint32_t m_lock_count;
568 PyThreadState *m_command_thread_state;
571 } // namespace lldb_private
573 #endif // LLDB_DISABLE_PYTHON
575 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H