1 //===-- ScriptInterpreterPython.cpp -----------------------------*- 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 // In order to guarantee correct working with Python, Python.h *MUST* be
11 // the *FIRST* header file included here.
12 #ifdef LLDB_DISABLE_PYTHON
14 // Python is disabled in this build
18 #include "lldb/lldb-python.h"
19 #include "lldb/Interpreter/ScriptInterpreterPython.h"
26 #include "lldb/API/SBValue.h"
27 #include "lldb/Breakpoint/BreakpointLocation.h"
28 #include "lldb/Breakpoint/StoppointCallbackContext.h"
29 #include "lldb/Breakpoint/WatchpointOptions.h"
30 #include "lldb/Core/Communication.h"
31 #include "lldb/Core/ConnectionFileDescriptor.h"
32 #include "lldb/Core/Debugger.h"
33 #include "lldb/Core/Timer.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Interpreter/CommandInterpreter.h"
36 #include "lldb/Interpreter/CommandReturnObject.h"
37 #include "lldb/Interpreter/PythonDataObjects.h"
38 #include "lldb/Target/Thread.h"
41 using namespace lldb_private;
44 static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
45 static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
46 static ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL;
47 static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
48 static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49 static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50 static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51 static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52 static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
53 static ScriptInterpreter::SWIGPythonGetValueObjectSPFromSBValue g_swig_get_valobj_sp_from_sbvalue = NULL;
54 static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
55 static ScriptInterpreter::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = NULL;
56 static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
57 static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
58 static ScriptInterpreter::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = NULL;
59 static ScriptInterpreter::SWIGPythonScriptKeyword_Process g_swig_run_script_keyword_process = NULL;
60 static ScriptInterpreter::SWIGPythonScriptKeyword_Thread g_swig_run_script_keyword_thread = NULL;
61 static ScriptInterpreter::SWIGPythonScriptKeyword_Target g_swig_run_script_keyword_target = NULL;
62 static ScriptInterpreter::SWIGPythonScriptKeyword_Frame g_swig_run_script_keyword_frame = NULL;
63 static ScriptInterpreter::SWIGPython_GetDynamicSetting g_swig_plugin_get = NULL;
66 _check_and_flush (FILE *stream)
68 int prev_fail = ferror (stream);
69 return fflush (stream) || prev_fail ? EOF : 0;
73 ReadPythonBacktrace (PyObject* py_backtrace);
75 ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
81 ScriptInterpreterLocker (),
82 m_teardown_session( (on_leave & TearDownSession) == TearDownSession ),
83 m_python_interpreter(py_interpreter)
86 if ((on_entry & InitSession) == InitSession)
88 if (DoInitSession(on_entry, in, out, err) == false)
90 // Don't teardown the session if we didn't init it.
91 m_teardown_session = false;
97 ScriptInterpreterPython::Locker::DoAcquireLock()
99 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
100 m_GILState = PyGILState_Ensure();
102 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
107 ScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err)
109 if (!m_python_interpreter)
111 return m_python_interpreter->EnterSession (on_entry_flags, in, out, err);
115 ScriptInterpreterPython::Locker::DoFreeLock()
117 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
119 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
120 PyGILState_Release(m_GILState);
125 ScriptInterpreterPython::Locker::DoTearDownSession()
127 if (!m_python_interpreter)
129 m_python_interpreter->LeaveSession ();
133 ScriptInterpreterPython::Locker::~Locker()
135 if (m_teardown_session)
141 ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
142 ScriptInterpreter (interpreter, eScriptLanguagePython),
143 IOHandlerDelegateMultiline("DONE"),
149 m_session_dict (false), // Don't create an empty dictionary, leave it invalid
150 m_sys_module_dict (false), // Don't create an empty dictionary, leave it invalid
151 m_run_one_line_function (),
152 m_run_one_line_str_global (),
153 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
155 m_active_io_handler (eIOHandlerNone),
156 m_session_is_active (false),
157 m_pty_slave_is_open (false),
158 m_valid_session (true),
159 m_command_thread_state (NULL)
162 ScriptInterpreterPython::InitializePrivate ();
164 m_dictionary_name.append("_dict");
165 StreamString run_string;
166 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
169 ScriptInterpreterPython::Locker::AcquireLock,
170 ScriptInterpreterPython::Locker::FreeAcquiredLock);
171 PyRun_SimpleString (run_string.GetData());
175 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
176 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
177 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
178 // call to Debugger::Terminate is made, the ref-count has the correct value.
180 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
181 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
183 int old_count = Debugger::TestDebuggerRefCount();
185 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb')", m_dictionary_name.c_str());
186 PyRun_SimpleString (run_string.GetData());
188 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
189 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
191 run_string.Printf ("run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", m_dictionary_name.c_str());
192 PyRun_SimpleString (run_string.GetData());
195 int new_count = Debugger::TestDebuggerRefCount();
197 if (new_count > old_count)
198 Debugger::Terminate();
200 run_string.Printf ("run_one_line (%s, 'import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line')", m_dictionary_name.c_str());
201 PyRun_SimpleString (run_string.GetData());
204 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(),
205 interpreter.GetDebugger().GetID());
206 PyRun_SimpleString (run_string.GetData());
209 ScriptInterpreterPython::~ScriptInterpreterPython ()
214 ScriptInterpreterPython::IOHandlerActivated (IOHandler &io_handler)
216 const char *instructions = NULL;
218 switch (m_active_io_handler)
222 case eIOHandlerBreakpoint:
223 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
224 def function (frame, bp_loc, internal_dict):
225 """frame: the lldb.SBFrame for the location at which you stopped
226 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
227 internal_dict: an LLDB support object not to be used"""
230 case eIOHandlerWatchpoint:
231 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
237 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
240 output_sp->PutCString(instructions);
247 ScriptInterpreterPython::IOHandlerInputComplete (IOHandler &io_handler, std::string &data)
249 io_handler.SetIsDone(true);
250 bool batch_mode = m_interpreter.GetBatchCommandMode();
252 switch (m_active_io_handler)
256 case eIOHandlerBreakpoint:
258 BreakpointOptions *bp_options = (BreakpointOptions *)io_handler.GetUserData();
259 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
262 data_ap->user_source.SplitIntoLines(data);
264 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
266 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
267 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
269 else if (!batch_mode)
271 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
274 error_sp->Printf ("Warning: No command attached to breakpoint.\n");
279 m_active_io_handler = eIOHandlerNone;
282 case eIOHandlerWatchpoint:
284 WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData();
285 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
288 data_ap->user_source.SplitIntoLines(data);
290 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
292 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
293 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
295 else if (!batch_mode)
297 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
300 error_sp->Printf ("Warning: No command attached to breakpoint.\n");
305 m_active_io_handler = eIOHandlerNone;
315 ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
320 ScriptInterpreterPython::SaveTerminalState (int fd)
322 // Python mucks with the terminal state of STDIN. If we can possibly avoid
323 // this by setting the file handles up correctly prior to entering the
324 // interpreter we should. For now we save and restore the terminal state
325 // on the input file handle.
326 m_terminal_state.Save (fd, false);
330 ScriptInterpreterPython::RestoreTerminalState ()
332 // Python mucks with the terminal state of STDIN. If we can possibly avoid
333 // this by setting the file handles up correctly prior to entering the
334 // interpreter we should. For now we save and restore the terminal state
335 // on the input file handle.
336 m_terminal_state.Restore();
340 ScriptInterpreterPython::LeaveSession ()
342 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
344 log->PutCString("ScriptInterpreterPython::LeaveSession()");
346 // checking that we have a valid thread state - since we use our own threading and locking
347 // in some (rare) cases during cleanup Python may end up believing we have no thread state
348 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
349 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
351 // rdar://problem/11292882
352 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
353 if (PyThreadState_GetDict())
355 PythonDictionary &sys_module_dict = GetSysModuleDictionary ();
360 sys_module_dict.SetItemForKey("stdin", m_saved_stdin);
361 m_saved_stdin.Reset ();
365 sys_module_dict.SetItemForKey("stdout", m_saved_stdout);
366 m_saved_stdout.Reset ();
370 sys_module_dict.SetItemForKey("stderr", m_saved_stderr);
371 m_saved_stderr.Reset ();
376 m_session_is_active = false;
380 ScriptInterpreterPython::EnterSession (uint16_t on_entry_flags,
385 // If we have already entered the session, without having officially 'left' it, then there is no need to
387 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
388 if (m_session_is_active)
391 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ") session is already active, returning without doing anything", on_entry_flags);
396 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")", on_entry_flags);
399 m_session_is_active = true;
401 StreamString run_string;
403 if (on_entry_flags & Locker::InitGlobals)
405 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
406 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
407 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
408 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
409 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
410 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
411 run_string.PutCString ("')");
415 // If we aren't initing the globals, we should still always set the debugger (since that is always unique.)
416 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
417 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
418 run_string.PutCString ("')");
421 PyRun_SimpleString (run_string.GetData());
424 PythonDictionary &sys_module_dict = GetSysModuleDictionary ();
427 lldb::StreamFileSP in_sp;
428 lldb::StreamFileSP out_sp;
429 lldb::StreamFileSP err_sp;
430 if (in == NULL || out == NULL || err == NULL)
431 m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid (in_sp, out_sp, err_sp);
433 if (in == NULL && in_sp && (on_entry_flags & Locker::NoSTDIN) == 0)
434 in = in_sp->GetFile().GetStream();
437 m_saved_stdin.Reset(sys_module_dict.GetItemForKey("stdin"));
439 PyObject *new_file = PyFile_FromFile (in, (char *) "", (char *) "r", 0);
440 sys_module_dict.SetItemForKey ("stdin", new_file);
441 Py_DECREF (new_file);
444 m_saved_stdin.Reset();
446 if (out == NULL && out_sp)
447 out = out_sp->GetFile().GetStream();
450 m_saved_stdout.Reset(sys_module_dict.GetItemForKey("stdout"));
452 PyObject *new_file = PyFile_FromFile (out, (char *) "", (char *) "w", 0);
453 sys_module_dict.SetItemForKey ("stdout", new_file);
454 Py_DECREF (new_file);
457 m_saved_stdout.Reset();
459 if (err == NULL && err_sp)
460 err = err_sp->GetFile().GetStream();
463 m_saved_stderr.Reset(sys_module_dict.GetItemForKey("stderr"));
465 PyObject *new_file = PyFile_FromFile (err, (char *) "", (char *) "w", 0);
466 sys_module_dict.SetItemForKey ("stderr", new_file);
467 Py_DECREF (new_file);
470 m_saved_stderr.Reset();
473 if (PyErr_Occurred())
480 ScriptInterpreterPython::GetMainModule ()
483 m_main_module.Reset(PyImport_AddModule ("__main__"));
484 return m_main_module;
488 ScriptInterpreterPython::GetSessionDictionary ()
492 PythonObject &main_module = GetMainModule ();
495 PythonDictionary main_dict(PyModule_GetDict (main_module.get()));
498 m_session_dict = main_dict.GetItemForKey(m_dictionary_name.c_str());
502 return m_session_dict;
506 ScriptInterpreterPython::GetSysModuleDictionary ()
508 if (!m_sys_module_dict)
510 PyObject *sys_module = PyImport_AddModule ("sys");
512 m_sys_module_dict.Reset(PyModule_GetDict (sys_module));
514 return m_sys_module_dict;
518 GenerateUniqueName (const char* base_name_wanted,
519 uint32_t& functions_counter,
520 void* name_token = NULL)
524 if (!base_name_wanted)
525 return std::string();
528 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
530 sstr.Printf ("%s_%p", base_name_wanted, name_token);
532 return sstr.GetString();
536 ScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects ()
538 if (!m_run_one_line_function)
540 PyObject *module = PyImport_AddModule ("lldb.embedded_interpreter");
543 PythonDictionary module_dict (PyModule_GetDict (module));
546 m_run_one_line_function = module_dict.GetItemForKey("run_one_line");
547 m_run_one_line_str_global = module_dict.GetItemForKey("g_run_one_line_str");
551 return (bool)m_run_one_line_function;
555 ReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
559 Stream *strm = (Stream *)baton;
560 strm->Write(src, src_len);
566 ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options)
568 if (!m_valid_session)
571 if (command && command[0])
573 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
574 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
575 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
576 // method to pass the command string directly down to Python.
577 Debugger &debugger = m_interpreter.GetDebugger();
579 StreamFileSP input_file_sp;
580 StreamFileSP output_file_sp;
581 StreamFileSP error_file_sp;
582 Communication output_comm ("lldb.ScriptInterpreterPython.ExecuteOneLine.comm");
583 int pipe_fds[2] = { -1, -1 };
585 if (options.GetEnableIO())
589 input_file_sp = debugger.GetInputFile();
590 // Set output to a temporary file so we can forward the results on to the result object
592 int err = pipe(pipe_fds);
595 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor(pipe_fds[0], true));
596 if (conn_ap->IsConnected())
598 output_comm.SetConnection(conn_ap.release());
599 output_comm.SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived, &result->GetOutputStream());
600 output_comm.StartReadThread();
601 FILE *outfile_handle = fdopen (pipe_fds[1], "w");
602 output_file_sp.reset(new StreamFile(outfile_handle, true));
603 error_file_sp = output_file_sp;
605 ::setbuf (outfile_handle, NULL);
607 result->SetImmediateOutputFile(debugger.GetOutputFile()->GetFile().GetStream());
608 result->SetImmediateErrorFile(debugger.GetErrorFile()->GetFile().GetStream());
612 if (!input_file_sp || !output_file_sp || !error_file_sp)
613 debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, error_file_sp);
617 input_file_sp.reset (new StreamFile ());
618 input_file_sp->GetFile().Open("/dev/null", File::eOpenOptionRead);
619 output_file_sp.reset (new StreamFile ());
620 output_file_sp->GetFile().Open("/dev/null", File::eOpenOptionWrite);
621 error_file_sp = output_file_sp;
624 FILE *in_file = input_file_sp->GetFile().GetStream();
625 FILE *out_file = output_file_sp->GetFile().GetStream();
626 FILE *err_file = error_file_sp->GetFile().GetStream();
628 ScriptInterpreterPython::Locker::AcquireLock |
629 ScriptInterpreterPython::Locker::InitSession |
630 (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
631 ScriptInterpreterPython::Locker::FreeAcquiredLock |
632 ScriptInterpreterPython::Locker::TearDownSession,
637 bool success = false;
639 // Find the correct script interpreter dictionary in the main module.
640 PythonDictionary &session_dict = GetSessionDictionary ();
643 if (GetEmbeddedInterpreterModuleObjects ())
645 PyObject *pfunc = m_run_one_line_function.get();
647 if (pfunc && PyCallable_Check (pfunc))
649 PythonObject pargs (Py_BuildValue("(Os)", session_dict.get(), command));
652 PythonObject return_value(PyObject_CallObject (pfunc, pargs.get()));
655 else if (options.GetMaskoutErrors() && PyErr_Occurred ())
665 // Flush our output and error file handles
667 if (out_file != err_file)
670 if (pipe_fds[0] != -1)
672 // Close the write end of the pipe since we are done with our
673 // one line script. This should cause the read thread that
674 // output_comm is using to exit
675 output_file_sp->GetFile().Close();
676 // The close above should cause this thread to exit when it gets
677 // to the end of file, so let it get all its data
678 output_comm.JoinReadThread();
679 // Now we can close the read end of the pipe
680 output_comm.Disconnect();
687 // The one-liner failed. Append the error message.
689 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
694 result->AppendError ("empty command passed to python\n");
699 class IOHandlerPythonInterpreter :
704 IOHandlerPythonInterpreter (Debugger &debugger,
705 ScriptInterpreterPython *python) :
706 IOHandler (debugger),
713 ~IOHandlerPythonInterpreter()
719 GetControlSequence (char ch)
722 return ConstString("quit()\n");
723 return ConstString();
731 int stdin_fd = GetInputFD();
734 Terminal terminal(stdin_fd);
735 TerminalState terminal_state;
736 const bool is_a_tty = terminal.IsATerminal();
740 terminal_state.Save (stdin_fd, false);
741 terminal.SetCanonical(false);
742 terminal.SetEcho(true);
745 ScriptInterpreterPython::Locker locker (m_python,
746 ScriptInterpreterPython::Locker::AcquireLock |
747 ScriptInterpreterPython::Locker::InitSession |
748 ScriptInterpreterPython::Locker::InitGlobals,
749 ScriptInterpreterPython::Locker::FreeAcquiredLock |
750 ScriptInterpreterPython::Locker::TearDownSession);
752 // The following call drops into the embedded interpreter loop and stays there until the
753 // user chooses to exit from the Python interpreter.
754 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
755 // a system call that can hang, and lock it when the syscall has returned.
757 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
758 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
759 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
760 // and things could hang (it's happened before).
762 StreamString run_string;
763 run_string.Printf ("run_python_interpreter (%s)", m_python->GetDictionaryName ());
764 PyRun_SimpleString (run_string.GetData());
767 terminal_state.Restore();
803 ScriptInterpreterPython *m_python;
808 ScriptInterpreterPython::ExecuteInterpreterLoop ()
810 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
812 Debugger &debugger = GetCommandInterpreter().GetDebugger();
814 // At the moment, the only time the debugger does not have an input file handle is when this is called
815 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
816 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
819 if (!debugger.GetInputFile()->GetFile().IsValid())
822 IOHandlerSP io_handler_sp (new IOHandlerPythonInterpreter (debugger, this));
825 debugger.PushIOHandler(io_handler_sp);
830 ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
831 ScriptInterpreter::ScriptReturnType return_type,
833 const ExecuteScriptOptions &options)
837 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
838 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
840 PyObject *py_return = NULL;
841 PythonObject &main_module = GetMainModule ();
842 PythonDictionary globals (PyModule_GetDict(main_module.get()));
843 PyObject *py_error = NULL;
844 bool ret_success = false;
847 PythonDictionary locals = GetSessionDictionary ();
851 locals = PyObject_GetAttrString (globals.get(), m_dictionary_name.c_str());
857 py_error = PyErr_Occurred();
858 if (py_error != NULL)
861 if (in_string != NULL)
863 { // scope for PythonInputReaderManager
864 //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
865 py_return = PyRun_String (in_string, Py_eval_input, globals.get(), locals.get());
866 if (py_return == NULL)
868 py_error = PyErr_Occurred ();
869 if (py_error != NULL)
872 py_return = PyRun_String (in_string, Py_single_input, globals.get(), locals.get());
876 if (py_return != NULL)
880 case eScriptReturnTypeCharPtr: // "char *"
882 const char format[3] = "s#";
883 success = PyArg_Parse (py_return, format, (char **) ret_value);
886 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
888 const char format[3] = "z";
889 success = PyArg_Parse (py_return, format, (char **) ret_value);
892 case eScriptReturnTypeBool:
894 const char format[2] = "b";
895 success = PyArg_Parse (py_return, format, (bool *) ret_value);
898 case eScriptReturnTypeShortInt:
900 const char format[2] = "h";
901 success = PyArg_Parse (py_return, format, (short *) ret_value);
904 case eScriptReturnTypeShortIntUnsigned:
906 const char format[2] = "H";
907 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
910 case eScriptReturnTypeInt:
912 const char format[2] = "i";
913 success = PyArg_Parse (py_return, format, (int *) ret_value);
916 case eScriptReturnTypeIntUnsigned:
918 const char format[2] = "I";
919 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
922 case eScriptReturnTypeLongInt:
924 const char format[2] = "l";
925 success = PyArg_Parse (py_return, format, (long *) ret_value);
928 case eScriptReturnTypeLongIntUnsigned:
930 const char format[2] = "k";
931 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
934 case eScriptReturnTypeLongLong:
936 const char format[2] = "L";
937 success = PyArg_Parse (py_return, format, (long long *) ret_value);
940 case eScriptReturnTypeLongLongUnsigned:
942 const char format[2] = "K";
943 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
946 case eScriptReturnTypeFloat:
948 const char format[2] = "f";
949 success = PyArg_Parse (py_return, format, (float *) ret_value);
952 case eScriptReturnTypeDouble:
954 const char format[2] = "d";
955 success = PyArg_Parse (py_return, format, (double *) ret_value);
958 case eScriptReturnTypeChar:
960 const char format[2] = "c";
961 success = PyArg_Parse (py_return, format, (char *) ret_value);
964 case eScriptReturnTypeOpaqueObject:
967 Py_XINCREF(py_return);
968 *((PyObject**)ret_value) = py_return;
972 Py_XDECREF (py_return);
980 py_error = PyErr_Occurred();
981 if (py_error != NULL)
984 if (options.GetMaskoutErrors())
986 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
996 ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options)
1001 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
1002 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1004 bool success = false;
1005 PythonObject return_value;
1006 PythonObject &main_module = GetMainModule ();
1007 PythonDictionary globals (PyModule_GetDict(main_module.get()));
1008 PyObject *py_error = NULL;
1010 PythonDictionary locals = GetSessionDictionary ();
1014 locals = PyObject_GetAttrString (globals.get(), m_dictionary_name.c_str());
1022 py_error = PyErr_Occurred();
1023 if (py_error != NULL)
1026 if (in_string != NULL)
1028 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1031 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1034 { // scope for PythonInputReaderManager
1035 //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
1036 return_value.Reset(PyEval_EvalCode (compiled_code, globals.get(), locals.get()));
1044 py_error = PyErr_Occurred ();
1045 if (py_error != NULL)
1048 // _PyObject_Dump (py_error);
1052 PyObject *type = NULL;
1053 PyObject *value = NULL;
1054 PyObject *traceback = NULL;
1055 PyErr_Fetch (&type,&value,&traceback);
1057 // get the backtrace
1058 std::string bt = ReadPythonBacktrace(traceback);
1060 if (value && value != Py_None)
1061 error.SetErrorStringWithFormat("%s\n%s", PyString_AsString(PyObject_Str(value)),bt.c_str());
1063 error.SetErrorStringWithFormat("%s",bt.c_str());
1066 Py_XDECREF(traceback);
1067 if (options.GetMaskoutErrors())
1078 ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
1079 CommandReturnObject &result)
1081 m_active_io_handler = eIOHandlerBreakpoint;
1082 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, bp_options);
1086 ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1087 CommandReturnObject &result)
1089 m_active_io_handler = eIOHandlerWatchpoint;
1090 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, wp_options);
1093 // Set a Python one-liner as the callback for the breakpoint.
1095 ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
1096 const char *oneliner)
1098 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1100 // It's necessary to set both user_source and script_source to the oneliner.
1101 // The former is used to generate callback description (as in breakpoint command list)
1102 // while the latter is used for Python to interpret during the actual callback.
1104 data_ap->user_source.AppendString (oneliner);
1105 data_ap->script_source.assign (oneliner);
1107 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1109 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1110 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1116 // Set a Python one-liner as the callback for the watchpoint.
1118 ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1119 const char *oneliner)
1121 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1123 // It's necessary to set both user_source and script_source to the oneliner.
1124 // The former is used to generate callback description (as in watchpoint command list)
1125 // while the latter is used for Python to interpret during the actual callback.
1127 data_ap->user_source.AppendString (oneliner);
1128 data_ap->script_source.assign (oneliner);
1130 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1132 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1133 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1140 ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1142 // Convert StringList to one long, newline delimited, const char *.
1143 std::string function_def_string(function_def.CopyList());
1145 return ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)).Success();
1149 ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
1151 int num_lines = input.GetSize ();
1155 if (!signature || *signature == 0)
1159 StringList auto_generated_function;
1160 auto_generated_function.AppendString (signature);
1161 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1162 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
1163 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1164 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
1165 // global dictionary.
1167 // Wrap everything up inside the function, increasing the indentation.
1169 auto_generated_function.AppendString(" if True:");
1170 for (int i = 0; i < num_lines; ++i)
1173 sstr.Printf (" %s", input.GetStringAtIndex (i));
1174 auto_generated_function.AppendString (sstr.GetData());
1176 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1177 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
1178 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1179 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1181 // Verify that the results are valid Python.
1183 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1191 ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
1193 static uint32_t num_created_functions = 0;
1194 user_input.RemoveBlankLines ();
1197 // Check to see if we have any data; if not, just return.
1198 if (user_input.GetSize() == 0)
1201 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1202 // ValueObject as parameter to the function.
1204 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
1205 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
1207 if (!GenerateFunction(sstr.GetData(), user_input))
1210 // Store the name of the auto-generated function to be called.
1211 output.assign(auto_generated_function_name);
1216 ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
1218 static uint32_t num_created_functions = 0;
1219 user_input.RemoveBlankLines ();
1222 // Check to see if we have any data; if not, just return.
1223 if (user_input.GetSize() == 0)
1226 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1228 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
1230 if (!GenerateFunction(sstr.GetData(),user_input))
1233 // Store the name of the auto-generated function to be called.
1234 output.assign(auto_generated_function_name);
1240 ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
1242 static uint32_t num_created_classes = 0;
1243 user_input.RemoveBlankLines ();
1244 int num_lines = user_input.GetSize ();
1247 // Check to see if we have any data; if not, just return.
1248 if (user_input.GetSize() == 0)
1251 // Wrap all user input into a Python class
1253 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
1255 StringList auto_generated_class;
1257 // Create the function name & definition string.
1259 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1260 auto_generated_class.AppendString (sstr.GetData());
1262 // Wrap everything up inside the class, increasing the indentation.
1263 // we don't need to play any fancy indentation tricks here because there is no
1264 // surrounding code whose indentation we need to honor
1265 for (int i = 0; i < num_lines; ++i)
1268 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1269 auto_generated_class.AppendString (sstr.GetData());
1273 // Verify that the results are valid Python.
1274 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1275 // (TODO: rename that method to ExportDefinitionToInterpreter)
1276 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1279 // Store the name of the auto-generated class
1281 output.assign(auto_generated_class_name);
1285 lldb::ScriptInterpreterObjectSP
1286 ScriptInterpreterPython::OSPlugin_CreatePluginObject (const char *class_name, lldb::ProcessSP process_sp)
1288 if (class_name == NULL || class_name[0] == '\0')
1289 return lldb::ScriptInterpreterObjectSP();
1292 return lldb::ScriptInterpreterObjectSP();
1297 Locker py_lock (this,
1298 Locker::AcquireLock | Locker::NoSTDIN,
1300 ret_val = g_swig_create_os_plugin (class_name,
1301 m_dictionary_name.c_str(),
1305 return MakeScriptObject(ret_val);
1308 lldb::ScriptInterpreterObjectSP
1309 ScriptInterpreterPython::OSPlugin_RegisterInfo (lldb::ScriptInterpreterObjectSP os_plugin_object_sp)
1311 Locker py_lock(this,
1312 Locker::AcquireLock | Locker::NoSTDIN,
1315 static char callee_name[] = "get_register_info";
1317 if (!os_plugin_object_sp)
1318 return lldb::ScriptInterpreterObjectSP();
1320 PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject();
1322 if (implementor == NULL || implementor == Py_None)
1323 return lldb::ScriptInterpreterObjectSP();
1325 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1327 if (PyErr_Occurred())
1332 if (pmeth == NULL || pmeth == Py_None)
1335 return lldb::ScriptInterpreterObjectSP();
1338 if (PyCallable_Check(pmeth) == 0)
1340 if (PyErr_Occurred())
1346 return lldb::ScriptInterpreterObjectSP();
1349 if (PyErr_Occurred())
1356 // right now we know this function exists and is callable..
1357 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1359 // if it fails, print the error but otherwise go on
1360 if (PyErr_Occurred())
1366 return MakeScriptObject(py_return);
1369 lldb::ScriptInterpreterObjectSP
1370 ScriptInterpreterPython::OSPlugin_ThreadsInfo (lldb::ScriptInterpreterObjectSP os_plugin_object_sp)
1372 Locker py_lock (this,
1373 Locker::AcquireLock | Locker::NoSTDIN,
1376 static char callee_name[] = "get_thread_info";
1378 if (!os_plugin_object_sp)
1379 return lldb::ScriptInterpreterObjectSP();
1381 PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject();
1383 if (implementor == NULL || implementor == Py_None)
1384 return lldb::ScriptInterpreterObjectSP();
1386 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1388 if (PyErr_Occurred())
1393 if (pmeth == NULL || pmeth == Py_None)
1396 return lldb::ScriptInterpreterObjectSP();
1399 if (PyCallable_Check(pmeth) == 0)
1401 if (PyErr_Occurred())
1407 return lldb::ScriptInterpreterObjectSP();
1410 if (PyErr_Occurred())
1417 // right now we know this function exists and is callable..
1418 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1420 // if it fails, print the error but otherwise go on
1421 if (PyErr_Occurred())
1427 return MakeScriptObject(py_return);
1430 // GetPythonValueFormatString provides a system independent type safe way to
1431 // convert a variable's type into a python value format. Python value formats
1432 // are defined in terms of builtin C types and could change from system to
1433 // as the underlying typedef for uint* types, size_t, off_t and other values
1436 template <typename T>
1437 const char *GetPythonValueFormatString(T t)
1439 assert(!"Unhandled type passed to GetPythonValueFormatString(T), make a specialization of GetPythonValueFormatString() to support this type.");
1442 template <> const char *GetPythonValueFormatString (char *) { return "s"; }
1443 template <> const char *GetPythonValueFormatString (char) { return "b"; }
1444 template <> const char *GetPythonValueFormatString (unsigned char) { return "B"; }
1445 template <> const char *GetPythonValueFormatString (short) { return "h"; }
1446 template <> const char *GetPythonValueFormatString (unsigned short) { return "H"; }
1447 template <> const char *GetPythonValueFormatString (int) { return "i"; }
1448 template <> const char *GetPythonValueFormatString (unsigned int) { return "I"; }
1449 template <> const char *GetPythonValueFormatString (long) { return "l"; }
1450 template <> const char *GetPythonValueFormatString (unsigned long) { return "k"; }
1451 template <> const char *GetPythonValueFormatString (long long) { return "L"; }
1452 template <> const char *GetPythonValueFormatString (unsigned long long) { return "K"; }
1453 template <> const char *GetPythonValueFormatString (float t) { return "f"; }
1454 template <> const char *GetPythonValueFormatString (double t) { return "d"; }
1456 lldb::ScriptInterpreterObjectSP
1457 ScriptInterpreterPython::OSPlugin_RegisterContextData (lldb::ScriptInterpreterObjectSP os_plugin_object_sp,
1460 Locker py_lock (this,
1461 Locker::AcquireLock | Locker::NoSTDIN,
1464 static char callee_name[] = "get_register_data";
1465 static char *param_format = const_cast<char *>(GetPythonValueFormatString(tid));
1467 if (!os_plugin_object_sp)
1468 return lldb::ScriptInterpreterObjectSP();
1470 PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject();
1472 if (implementor == NULL || implementor == Py_None)
1473 return lldb::ScriptInterpreterObjectSP();
1475 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1477 if (PyErr_Occurred())
1482 if (pmeth == NULL || pmeth == Py_None)
1485 return lldb::ScriptInterpreterObjectSP();
1488 if (PyCallable_Check(pmeth) == 0)
1490 if (PyErr_Occurred())
1496 return lldb::ScriptInterpreterObjectSP();
1499 if (PyErr_Occurred())
1506 // right now we know this function exists and is callable..
1507 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, param_format, tid);
1509 // if it fails, print the error but otherwise go on
1510 if (PyErr_Occurred())
1516 return MakeScriptObject(py_return);
1519 lldb::ScriptInterpreterObjectSP
1520 ScriptInterpreterPython::OSPlugin_CreateThread (lldb::ScriptInterpreterObjectSP os_plugin_object_sp,
1522 lldb::addr_t context)
1524 Locker py_lock(this,
1525 Locker::AcquireLock | Locker::NoSTDIN,
1528 static char callee_name[] = "create_thread";
1529 std::string param_format;
1530 param_format += GetPythonValueFormatString(tid);
1531 param_format += GetPythonValueFormatString(context);
1533 if (!os_plugin_object_sp)
1534 return lldb::ScriptInterpreterObjectSP();
1536 PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject();
1538 if (implementor == NULL || implementor == Py_None)
1539 return lldb::ScriptInterpreterObjectSP();
1541 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1543 if (PyErr_Occurred())
1548 if (pmeth == NULL || pmeth == Py_None)
1551 return lldb::ScriptInterpreterObjectSP();
1554 if (PyCallable_Check(pmeth) == 0)
1556 if (PyErr_Occurred())
1562 return lldb::ScriptInterpreterObjectSP();
1565 if (PyErr_Occurred())
1572 // right now we know this function exists and is callable..
1573 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, ¶m_format[0], tid, context);
1575 // if it fails, print the error but otherwise go on
1576 if (PyErr_Occurred())
1582 return MakeScriptObject(py_return);
1585 lldb::ScriptInterpreterObjectSP
1586 ScriptInterpreterPython::LoadPluginModule (const FileSpec& file_spec,
1587 lldb_private::Error& error)
1589 if (!file_spec.Exists())
1591 error.SetErrorString("no such file");
1592 return lldb::ScriptInterpreterObjectSP();
1595 ScriptInterpreterObjectSP module_sp;
1597 if (LoadScriptingModule(file_spec.GetPath().c_str(),true,true,error,&module_sp))
1600 return lldb::ScriptInterpreterObjectSP();
1603 lldb::ScriptInterpreterObjectSP
1604 ScriptInterpreterPython::GetDynamicSettings (lldb::ScriptInterpreterObjectSP plugin_module_sp,
1606 const char* setting_name,
1607 lldb_private::Error& error)
1609 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1610 return lldb::ScriptInterpreterObjectSP();
1612 if (!g_swig_plugin_get)
1613 return lldb::ScriptInterpreterObjectSP();
1615 PyObject *reply_pyobj = nullptr;
1618 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1619 TargetSP target_sp(target->shared_from_this());
1620 reply_pyobj = (PyObject*)g_swig_plugin_get(plugin_module_sp->GetObject(),setting_name,target_sp);
1623 return MakeScriptObject(reply_pyobj);
1626 lldb::ScriptInterpreterObjectSP
1627 ScriptInterpreterPython::CreateSyntheticScriptedProvider (const char *class_name,
1628 lldb::ValueObjectSP valobj)
1630 if (class_name == NULL || class_name[0] == '\0')
1631 return lldb::ScriptInterpreterObjectSP();
1634 return lldb::ScriptInterpreterObjectSP();
1636 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1637 Target *target = exe_ctx.GetTargetPtr();
1640 return lldb::ScriptInterpreterObjectSP();
1642 Debugger &debugger = target->GetDebugger();
1643 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1644 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1646 if (!script_interpreter)
1647 return lldb::ScriptInterpreterObjectSP();
1652 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1653 ret_val = g_swig_synthetic_script (class_name,
1654 python_interpreter->m_dictionary_name.c_str(),
1658 return MakeScriptObject(ret_val);
1662 ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
1665 input.SplitIntoLines(oneliner, strlen(oneliner));
1666 return GenerateTypeScriptFunction(input, output, name_token);
1670 ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
1673 input.SplitIntoLines(oneliner, strlen(oneliner));
1674 return GenerateTypeSynthClass(input, output, name_token);
1679 ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
1681 static uint32_t num_created_functions = 0;
1682 user_input.RemoveBlankLines ();
1685 if (user_input.GetSize() == 0)
1688 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
1689 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
1691 if (!GenerateFunction(sstr.GetData(), user_input))
1694 // Store the name of the auto-generated function to be called.
1695 output.assign(auto_generated_function_name);
1700 ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1702 static uint32_t num_created_functions = 0;
1703 user_input.RemoveBlankLines ();
1706 if (user_input.GetSize() == 0)
1709 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1710 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1712 if (!GenerateFunction(sstr.GetData(), user_input))
1715 // Store the name of the auto-generated function to be called.
1716 output.assign(auto_generated_function_name);
1721 ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1722 lldb::ValueObjectSP valobj,
1723 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1724 std::string& retval)
1727 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1731 retval.assign("<no object>");
1735 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1736 void* new_callee = old_callee;
1739 if (python_function_name
1740 && *python_function_name)
1743 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1745 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1746 ret_val = g_swig_typescript_callback (python_function_name,
1747 GetSessionDictionary().get(),
1756 retval.assign("<no function name>");
1760 if (new_callee && old_callee != new_callee)
1761 callee_wrapper_sp = MakeScriptObject(new_callee);
1768 ScriptInterpreterPython::BreakpointCallbackFunction
1771 StoppointCallbackContext *context,
1773 user_id_t break_loc_id
1776 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1777 const char *python_function_name = bp_option_data->script_source.c_str();
1782 ExecutionContext exe_ctx (context->exe_ctx_ref);
1783 Target *target = exe_ctx.GetTargetPtr();
1788 Debugger &debugger = target->GetDebugger();
1789 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1790 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1792 if (!script_interpreter)
1795 if (python_function_name && python_function_name[0])
1797 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
1798 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1801 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1803 if (stop_frame_sp && bp_loc_sp)
1805 bool ret_val = true;
1807 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1808 ret_val = g_swig_breakpoint_callback (python_function_name,
1809 python_interpreter->m_dictionary_name.c_str(),
1817 // We currently always true so we stop in case anything goes wrong when
1818 // trying to call the script function
1823 ScriptInterpreterPython::WatchpointCallbackFunction
1826 StoppointCallbackContext *context,
1830 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
1831 const char *python_function_name = wp_option_data->script_source.c_str();
1836 ExecutionContext exe_ctx (context->exe_ctx_ref);
1837 Target *target = exe_ctx.GetTargetPtr();
1842 Debugger &debugger = target->GetDebugger();
1843 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1844 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1846 if (!script_interpreter)
1849 if (python_function_name && python_function_name[0])
1851 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
1852 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
1855 if (stop_frame_sp && wp_sp)
1857 bool ret_val = true;
1859 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1860 ret_val = g_swig_watchpoint_callback (python_function_name,
1861 python_interpreter->m_dictionary_name.c_str(),
1869 // We currently always true so we stop in case anything goes wrong when
1870 // trying to call the script function
1875 ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
1877 if (!implementor_sp)
1880 void* implementor = implementor_sp->GetObject();
1885 if (!g_swig_calc_children)
1888 uint32_t ret_val = 0;
1891 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1892 ret_val = g_swig_calc_children (implementor);
1899 ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
1901 if (!implementor_sp)
1902 return lldb::ValueObjectSP();
1904 void* implementor = implementor_sp->GetObject();
1907 return lldb::ValueObjectSP();
1909 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1910 return lldb::ValueObjectSP();
1912 lldb::ValueObjectSP ret_val;
1915 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1916 void* child_ptr = g_swig_get_child_index (implementor,idx);
1917 if (child_ptr != NULL && child_ptr != Py_None)
1919 lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1920 if (sb_value_ptr == NULL)
1921 Py_XDECREF(child_ptr);
1923 ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr);
1927 Py_XDECREF(child_ptr);
1935 ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
1937 if (!implementor_sp)
1940 void* implementor = implementor_sp->GetObject();
1945 if (!g_swig_get_index_child)
1948 int ret_val = UINT32_MAX;
1951 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1952 ret_val = g_swig_get_index_child (implementor, child_name);
1959 ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
1961 bool ret_val = false;
1963 if (!implementor_sp)
1966 void* implementor = implementor_sp->GetObject();
1971 if (!g_swig_update_provider)
1975 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1976 ret_val = g_swig_update_provider (implementor);
1983 ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
1985 bool ret_val = false;
1987 if (!implementor_sp)
1990 void* implementor = implementor_sp->GetObject();
1995 if (!g_swig_mighthavechildren_provider)
1999 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2000 ret_val = g_swig_mighthavechildren_provider (implementor);
2007 ReadPythonBacktrace (PyObject* py_backtrace)
2009 PyObject* traceback_module = NULL,
2010 *stringIO_module = NULL,
2011 *stringIO_builder = NULL,
2012 *stringIO_buffer = NULL,
2014 *printTB_args = NULL,
2015 *printTB_result = NULL,
2016 *stringIO_getvalue = NULL,
2017 *printTB_string = NULL;
2019 std::string retval("backtrace unavailable");
2021 if (py_backtrace && py_backtrace != Py_None)
2023 traceback_module = PyImport_ImportModule("traceback");
2024 stringIO_module = PyImport_ImportModule("StringIO");
2026 if (traceback_module && traceback_module != Py_None && stringIO_module && stringIO_module != Py_None)
2028 stringIO_builder = PyObject_GetAttrString(stringIO_module, "StringIO");
2029 if (stringIO_builder && stringIO_builder != Py_None)
2031 stringIO_buffer = PyObject_CallObject(stringIO_builder, NULL);
2032 if (stringIO_buffer && stringIO_buffer != Py_None)
2034 printTB = PyObject_GetAttrString(traceback_module, "print_tb");
2035 if (printTB && printTB != Py_None)
2037 printTB_args = Py_BuildValue("OOO",py_backtrace,Py_None,stringIO_buffer);
2038 printTB_result = PyObject_CallObject(printTB, printTB_args);
2039 stringIO_getvalue = PyObject_GetAttrString(stringIO_buffer, "getvalue");
2040 if (stringIO_getvalue && stringIO_getvalue != Py_None)
2042 printTB_string = PyObject_CallObject (stringIO_getvalue,NULL);
2043 if (printTB_string && printTB_string != Py_None && PyString_Check(printTB_string))
2044 retval.assign(PyString_AsString(printTB_string));
2051 Py_XDECREF(traceback_module);
2052 Py_XDECREF(stringIO_module);
2053 Py_XDECREF(stringIO_builder);
2054 Py_XDECREF(stringIO_buffer);
2055 Py_XDECREF(printTB);
2056 Py_XDECREF(printTB_args);
2057 Py_XDECREF(printTB_result);
2058 Py_XDECREF(stringIO_getvalue);
2059 Py_XDECREF(printTB_string);
2064 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2066 std::string& output,
2072 error.SetErrorString("no process");
2075 if (!impl_function || !impl_function[0])
2077 error.SetErrorString("no function to execute");
2080 if (!g_swig_run_script_keyword_process)
2082 error.SetErrorString("internal helper function missing");
2086 ProcessSP process_sp(process->shared_from_this());
2087 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2088 ret_val = g_swig_run_script_keyword_process (impl_function, m_dictionary_name.c_str(), process_sp, output);
2090 error.SetErrorString("python script evaluation failed");
2096 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2098 std::string& output,
2104 error.SetErrorString("no thread");
2107 if (!impl_function || !impl_function[0])
2109 error.SetErrorString("no function to execute");
2112 if (!g_swig_run_script_keyword_thread)
2114 error.SetErrorString("internal helper function missing");
2118 ThreadSP thread_sp(thread->shared_from_this());
2119 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2120 ret_val = g_swig_run_script_keyword_thread (impl_function, m_dictionary_name.c_str(), thread_sp, output);
2122 error.SetErrorString("python script evaluation failed");
2128 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2130 std::string& output,
2136 error.SetErrorString("no thread");
2139 if (!impl_function || !impl_function[0])
2141 error.SetErrorString("no function to execute");
2144 if (!g_swig_run_script_keyword_target)
2146 error.SetErrorString("internal helper function missing");
2150 TargetSP target_sp(target->shared_from_this());
2151 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2152 ret_val = g_swig_run_script_keyword_target (impl_function, m_dictionary_name.c_str(), target_sp, output);
2154 error.SetErrorString("python script evaluation failed");
2160 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2162 std::string& output,
2168 error.SetErrorString("no frame");
2171 if (!impl_function || !impl_function[0])
2173 error.SetErrorString("no function to execute");
2176 if (!g_swig_run_script_keyword_frame)
2178 error.SetErrorString("internal helper function missing");
2182 StackFrameSP frame_sp(frame->shared_from_this());
2183 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2184 ret_val = g_swig_run_script_keyword_frame (impl_function, m_dictionary_name.c_str(), frame_sp, output);
2186 error.SetErrorString("python script evaluation failed");
2191 uint64_t replace_all(std::string& str, const std::string& oldStr, const std::string& newStr)
2194 uint64_t matches = 0;
2195 while((pos = str.find(oldStr, pos)) != std::string::npos)
2198 str.replace(pos, oldStr.length(), newStr);
2199 pos += newStr.length();
2205 ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
2208 lldb_private::Error& error,
2209 lldb::ScriptInterpreterObjectSP* module_sp)
2211 if (!pathname || !pathname[0])
2213 error.SetErrorString("invalid pathname");
2217 if (!g_swig_call_module_init)
2219 error.SetErrorString("internal helper function missing");
2223 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2226 FileSpec target_file(pathname, true);
2227 std::string basename(target_file.GetFilename().GetCString());
2229 StreamString command_stream;
2231 // Before executing Pyton code, lock the GIL.
2232 Locker py_lock (this,
2233 Locker::AcquireLock | (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN,
2234 Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0));
2236 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2237 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2239 // if not a valid file of any sort, check if it might be a filename still
2240 // dot can't be used but / and \ can, and if either is found, reject
2241 if (strchr(pathname,'\\') || strchr(pathname,'/'))
2243 error.SetErrorString("invalid pathname");
2246 basename = pathname; // not a filename, probably a package of some sort, let it go through
2248 else if (target_file.GetFileType() == FileSpec::eFileTypeDirectory ||
2249 target_file.GetFileType() == FileSpec::eFileTypeRegular ||
2250 target_file.GetFileType() == FileSpec::eFileTypeSymbolicLink)
2252 std::string directory(target_file.GetDirectory().GetCString());
2253 replace_all(directory,"'","\\'");
2255 // now make sure that Python has "directory" in the search path
2256 StreamString command_stream;
2257 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n",
2260 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)).Success();
2261 if (!syspath_retval)
2263 error.SetErrorString("Python sys.path handling failed");
2267 // strip .py or .pyc extension
2268 ConstString extension = target_file.GetFileNameExtension();
2271 if (::strcmp(extension.GetCString(), "py") == 0)
2272 basename.resize(basename.length()-3);
2273 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2274 basename.resize(basename.length()-4);
2279 error.SetErrorString("no known way to import this module specification");
2283 // check if the module is already import-ed
2284 command_stream.Clear();
2285 command_stream.Printf("sys.modules.__contains__('%s')",basename.c_str());
2286 bool does_contain = false;
2287 // this call will succeed if the module was ever imported in any Debugger in the lifetime of the process
2288 // in which this LLDB framework is living
2289 bool was_imported_globally = (ExecuteOneLineWithReturn(command_stream.GetData(),
2290 ScriptInterpreterPython::eScriptReturnTypeBool,
2292 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && does_contain);
2293 // this call will fail if the module was not imported in this Debugger before
2294 command_stream.Clear();
2295 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2296 bool was_imported_locally = !(GetSessionDictionary().GetItemForKey(basename.c_str()).IsNULLOrNone());
2298 bool was_imported = (was_imported_globally || was_imported_locally);
2300 if (was_imported == true && can_reload == false)
2302 error.SetErrorString("module already imported");
2306 // now actually do the import
2307 command_stream.Clear();
2311 if (!was_imported_locally)
2312 command_stream.Printf("import %s ; reload(%s)",basename.c_str(),basename.c_str());
2314 command_stream.Printf("reload(%s)",basename.c_str());
2317 command_stream.Printf("import %s",basename.c_str());
2319 error = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false));
2323 // if we are here, everything worked
2324 // call __lldb_init_module(debugger,dict)
2325 if (!g_swig_call_module_init (basename.c_str(),
2326 m_dictionary_name.c_str(),
2329 error.SetErrorString("calling __lldb_init_module failed");
2335 // everything went just great, now set the module object
2336 command_stream.Clear();
2337 command_stream.Printf("%s",basename.c_str());
2338 void* module_pyobj = nullptr;
2339 if (ExecuteOneLineWithReturn(command_stream.GetData(),ScriptInterpreter::eScriptReturnTypeOpaqueObject,&module_pyobj) && module_pyobj)
2340 *module_sp = MakeScriptObject(module_pyobj);
2347 lldb::ScriptInterpreterObjectSP
2348 ScriptInterpreterPython::MakeScriptObject (void* object)
2350 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2353 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2354 ScriptedCommandSynchronicity synchro) :
2355 m_debugger_sp(debugger_sp),
2356 m_synch_wanted(synchro),
2357 m_old_asynch(debugger_sp->GetAsyncExecution())
2359 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2360 m_debugger_sp->SetAsyncExecution(false);
2361 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2362 m_debugger_sp->SetAsyncExecution(true);
2365 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2367 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2368 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2372 ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2374 ScriptedCommandSynchronicity synchronicity,
2375 lldb_private::CommandReturnObject& cmd_retobj,
2380 error.SetErrorString("no function to execute");
2384 if (!g_swig_call_command)
2386 error.SetErrorString("no helper function to run scripted commands");
2390 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2392 if (!debugger_sp.get())
2394 error.SetErrorString("invalid Debugger pointer");
2398 bool ret_val = false;
2400 std::string err_msg;
2403 Locker py_lock(this,
2404 Locker::AcquireLock | Locker::InitSession,
2405 Locker::FreeLock | Locker::TearDownSession);
2407 SynchronicityHandler synch_handler(debugger_sp,
2410 // we need to save the thread state when we first start the command
2411 // because we might decide to interrupt it while some action is taking
2412 // place outside of Python (e.g. printing to screen, waiting for the network, ...)
2413 // in that case, _PyThreadState_Current will be NULL - and we would be unable
2414 // to set the asynchronous exception - not a desirable situation
2415 m_command_thread_state = _PyThreadState_Current;
2417 //PythonInputReaderManager py_input(this);
2419 ret_val = g_swig_call_command (impl_function,
2420 m_dictionary_name.c_str(),
2427 error.SetErrorString("unable to execute script function");
2434 // in Python, a special attribute __doc__ contains the docstring
2435 // for an object (function, method, class, ...) if any is defined
2436 // Otherwise, the attribute's value is None
2438 ScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest)
2441 if (!item || !*item)
2443 std::string command(item);
2444 command += ".__doc__";
2446 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2448 if (ExecuteOneLineWithReturn (command.c_str(),
2449 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2451 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)))
2454 dest.assign(result_ptr);
2459 StreamString str_stream;
2460 str_stream.Printf("Function %s was not found. Containing module might be missing.",item);
2461 dest.assign(str_stream.GetData());
2466 std::unique_ptr<ScriptInterpreterLocker>
2467 ScriptInterpreterPython::AcquireInterpreterLock ()
2469 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(this,
2470 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
2471 Locker::FreeLock | Locker::TearDownSession));
2476 ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback swig_init_callback,
2477 SWIGBreakpointCallbackFunction swig_breakpoint_callback,
2478 SWIGWatchpointCallbackFunction swig_watchpoint_callback,
2479 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
2480 SWIGPythonCreateSyntheticProvider swig_synthetic_script,
2481 SWIGPythonCalculateNumChildren swig_calc_children,
2482 SWIGPythonGetChildAtIndex swig_get_child_index,
2483 SWIGPythonGetIndexOfChildWithName swig_get_index_child,
2484 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue ,
2485 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
2486 SWIGPythonUpdateSynthProviderInstance swig_update_provider,
2487 SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider,
2488 SWIGPythonCallCommand swig_call_command,
2489 SWIGPythonCallModuleInit swig_call_module_init,
2490 SWIGPythonCreateOSPlugin swig_create_os_plugin,
2491 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
2492 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
2493 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
2494 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
2495 SWIGPython_GetDynamicSetting swig_plugin_get)
2497 g_swig_init_callback = swig_init_callback;
2498 g_swig_breakpoint_callback = swig_breakpoint_callback;
2499 g_swig_watchpoint_callback = swig_watchpoint_callback;
2500 g_swig_typescript_callback = swig_typescript_callback;
2501 g_swig_synthetic_script = swig_synthetic_script;
2502 g_swig_calc_children = swig_calc_children;
2503 g_swig_get_child_index = swig_get_child_index;
2504 g_swig_get_index_child = swig_get_index_child;
2505 g_swig_cast_to_sbvalue = swig_cast_to_sbvalue;
2506 g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue;
2507 g_swig_update_provider = swig_update_provider;
2508 g_swig_mighthavechildren_provider = swig_mighthavechildren_provider;
2509 g_swig_call_command = swig_call_command;
2510 g_swig_call_module_init = swig_call_module_init;
2511 g_swig_create_os_plugin = swig_create_os_plugin;
2512 g_swig_run_script_keyword_process = swig_run_script_keyword_process;
2513 g_swig_run_script_keyword_thread = swig_run_script_keyword_thread;
2514 g_swig_run_script_keyword_target = swig_run_script_keyword_target;
2515 g_swig_run_script_keyword_frame = swig_run_script_keyword_frame;
2516 g_swig_plugin_get = swig_plugin_get;
2520 ScriptInterpreterPython::InitializePrivate ()
2522 static int g_initialized = false;
2527 g_initialized = true;
2529 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2531 // Python will muck with STDIN terminal state, so save off any current TTY
2532 // settings so we can restore them.
2533 TerminalState stdin_tty_state;
2534 stdin_tty_state.Save(STDIN_FILENO, false);
2536 PyGILState_STATE gstate;
2537 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
2538 bool threads_already_initialized = false;
2539 if (PyEval_ThreadsInitialized ()) {
2540 gstate = PyGILState_Ensure ();
2542 log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2543 threads_already_initialized = true;
2545 // InitThreads acquires the GIL if it hasn't been called before.
2546 PyEval_InitThreads ();
2548 Py_InitializeEx (0);
2550 // Initialize SWIG after setting up python
2551 if (g_swig_init_callback)
2552 g_swig_init_callback ();
2554 // Update the path python uses to search for modules to include the current directory.
2556 PyRun_SimpleString ("import sys");
2557 PyRun_SimpleString ("sys.path.append ('.')");
2559 // Find the module that owns this code and use that path we get to
2560 // set the sys.path appropriately.
2563 char python_dir_path[PATH_MAX];
2564 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2566 std::string python_path("sys.path.insert(0,\"");
2567 size_t orig_len = python_path.length();
2568 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2570 python_path.append (python_dir_path);
2571 python_path.append ("\")");
2572 PyRun_SimpleString (python_path.c_str());
2573 python_path.resize (orig_len);
2576 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2578 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2580 python_path.append (python_dir_path);
2581 python_path.append ("\")");
2582 PyRun_SimpleString (python_path.c_str());
2583 python_path.resize (orig_len);
2588 PyRun_SimpleString ("sys.dont_write_bytecode = 1; import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line; from termios import *");
2590 if (threads_already_initialized) {
2592 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2593 PyGILState_Release (gstate);
2595 // We initialized the threads in this function, just unlock the GIL.
2596 PyEval_SaveThread();
2599 stdin_tty_state.Restore();
2603 //ScriptInterpreterPython::Terminate ()
2605 // // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2606 // // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2607 // // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2608 // // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2609 // // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2610 // // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2611 // // within Py_Finalize, which results in a seg fault.
2613 // // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2614 // // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2615 // // process exits).
2617 //// Py_Finalize ();
2620 #endif // #ifdef LLDB_DISABLE_PYTHON