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 #ifdef LLDB_DISABLE_PYTHON
12 // Python is disabled in this build
16 #include "lldb-python.h"
17 #include "ScriptInterpreterPython.h"
18 #include "PythonDataObjects.h"
19 #include "PythonExceptionState.h"
27 #include "lldb/API/SBValue.h"
28 #include "lldb/Breakpoint/BreakpointLocation.h"
29 #include "lldb/Breakpoint/StoppointCallbackContext.h"
30 #include "lldb/Breakpoint/WatchpointOptions.h"
31 #include "lldb/Core/Communication.h"
32 #include "lldb/Core/Debugger.h"
33 #include "lldb/Core/PluginManager.h"
34 #include "lldb/Core/Timer.h"
35 #include "lldb/Core/ValueObject.h"
36 #include "lldb/DataFormatters/TypeSummary.h"
37 #include "lldb/Host/ConnectionFileDescriptor.h"
38 #include "lldb/Host/FileSystem.h"
39 #include "lldb/Host/HostInfo.h"
40 #include "lldb/Host/Pipe.h"
41 #include "lldb/Interpreter/CommandInterpreter.h"
42 #include "lldb/Interpreter/CommandReturnObject.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/ThreadPlan.h"
47 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
50 #include "llvm/ADT/StringRef.h"
51 #include "llvm/ADT/STLExtras.h"
54 using namespace lldb_private;
56 static ScriptInterpreterPython::SWIGInitCallback g_swig_init_callback = nullptr;
57 static ScriptInterpreterPython::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = nullptr;
58 static ScriptInterpreterPython::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = nullptr;
59 static ScriptInterpreterPython::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = nullptr;
60 static ScriptInterpreterPython::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = nullptr;
61 static ScriptInterpreterPython::SWIGPythonCreateCommandObject g_swig_create_cmd = nullptr;
62 static ScriptInterpreterPython::SWIGPythonCalculateNumChildren g_swig_calc_children = nullptr;
63 static ScriptInterpreterPython::SWIGPythonGetChildAtIndex g_swig_get_child_index = nullptr;
64 static ScriptInterpreterPython::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = nullptr;
65 static ScriptInterpreterPython::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = nullptr;
66 static ScriptInterpreterPython::SWIGPythonGetValueObjectSPFromSBValue g_swig_get_valobj_sp_from_sbvalue = nullptr;
67 static ScriptInterpreterPython::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = nullptr;
68 static ScriptInterpreterPython::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = nullptr;
69 static ScriptInterpreterPython::SWIGPythonGetValueSynthProviderInstance g_swig_getvalue_provider = nullptr;
70 static ScriptInterpreterPython::SWIGPythonCallCommand g_swig_call_command = nullptr;
71 static ScriptInterpreterPython::SWIGPythonCallCommandObject g_swig_call_command_object = nullptr;
72 static ScriptInterpreterPython::SWIGPythonCallModuleInit g_swig_call_module_init = nullptr;
73 static ScriptInterpreterPython::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = nullptr;
74 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Process g_swig_run_script_keyword_process = nullptr;
75 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Thread g_swig_run_script_keyword_thread = nullptr;
76 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Target g_swig_run_script_keyword_target = nullptr;
77 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Frame g_swig_run_script_keyword_frame = nullptr;
78 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Value g_swig_run_script_keyword_value = nullptr;
79 static ScriptInterpreterPython::SWIGPython_GetDynamicSetting g_swig_plugin_get = nullptr;
80 static ScriptInterpreterPython::SWIGPythonCreateScriptedThreadPlan g_swig_thread_plan_script = nullptr;
81 static ScriptInterpreterPython::SWIGPythonCallThreadPlan g_swig_call_thread_plan = nullptr;
83 static bool g_initialized = false;
88 // Initializing Python is not a straightforward process. We cannot control what
89 // external code may have done before getting to this point in LLDB, including
90 // potentially having already initialized Python, so we need to do a lot of work
91 // to ensure that the existing state of the system is maintained across our
92 // initialization. We do this by using an RAII pattern where we save off initial
93 // state at the beginning, and restore it at the end
94 struct InitializePythonRAII
97 InitializePythonRAII() :
98 m_gil_state(PyGILState_UNLOCKED),
99 m_was_already_initialized(false)
101 // Python will muck with STDIN terminal state, so save off any current TTY
102 // settings so we can restore them.
103 m_stdin_tty_state.Save(STDIN_FILENO, false);
105 InitializePythonHome();
107 // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
108 // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
109 // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
110 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
112 InitializeThreadsPrivate();
114 InitializeThreadsPrivate();
119 ~InitializePythonRAII()
121 if (m_was_already_initialized)
123 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
127 log->Printf("Releasing PyGILState. Returning to state = %slocked\n",
128 m_was_already_initialized == PyGILState_UNLOCKED ? "un" : "");
130 PyGILState_Release(m_gil_state);
134 // We initialized the threads in this function, just unlock the GIL.
138 m_stdin_tty_state.Restore();
142 void InitializePythonHome()
144 #if defined(LLDB_PYTHON_HOME)
145 #if PY_MAJOR_VERSION >= 3
147 static wchar_t *g_python_home = Py_DecodeLocale(LLDB_PYTHON_HOME, &size);
149 static char g_python_home[] = LLDB_PYTHON_HOME;
151 Py_SetPythonHome(g_python_home);
155 void InitializeThreadsPrivate()
157 if (PyEval_ThreadsInitialized())
159 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
161 m_was_already_initialized = true;
162 m_gil_state = PyGILState_Ensure();
165 log->Printf("Ensured PyGILState. Previous state = %slocked\n",
166 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
171 // InitThreads acquires the GIL if it hasn't been called before.
172 PyEval_InitThreads();
175 TerminalState m_stdin_tty_state;
176 PyGILState_STATE m_gil_state;
177 bool m_was_already_initialized;
182 ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
188 ScriptInterpreterLocker (),
189 m_teardown_session( (on_leave & TearDownSession) == TearDownSession ),
190 m_python_interpreter(py_interpreter)
193 if ((on_entry & InitSession) == InitSession)
195 if (DoInitSession(on_entry, in, out, err) == false)
197 // Don't teardown the session if we didn't init it.
198 m_teardown_session = false;
204 ScriptInterpreterPython::Locker::DoAcquireLock()
206 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
207 m_GILState = PyGILState_Ensure();
209 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
211 // we need to save the thread state when we first start the command
212 // because we might decide to interrupt it while some action is taking
213 // place outside of Python (e.g. printing to screen, waiting for the network, ...)
214 // in that case, _PyThreadState_Current will be NULL - and we would be unable
215 // to set the asynchronous exception - not a desirable situation
216 m_python_interpreter->SetThreadState(PyThreadState_Get());
217 m_python_interpreter->IncrementLockCount();
222 ScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err)
224 if (!m_python_interpreter)
226 return m_python_interpreter->EnterSession (on_entry_flags, in, out, err);
230 ScriptInterpreterPython::Locker::DoFreeLock()
232 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
234 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
235 PyGILState_Release(m_GILState);
236 m_python_interpreter->DecrementLockCount();
241 ScriptInterpreterPython::Locker::DoTearDownSession()
243 if (!m_python_interpreter)
245 m_python_interpreter->LeaveSession ();
249 ScriptInterpreterPython::Locker::~Locker()
251 if (m_teardown_session)
256 ScriptInterpreterPython::ScriptInterpreterPython(CommandInterpreter &interpreter) :
257 ScriptInterpreter(interpreter, eScriptLanguagePython),
258 IOHandlerDelegateMultiline("DONE"),
264 m_session_dict(PyInitialValue::Invalid),
265 m_sys_module_dict(PyInitialValue::Invalid),
266 m_run_one_line_function(),
267 m_run_one_line_str_global(),
268 m_dictionary_name(interpreter.GetDebugger().GetInstanceName().AsCString()),
270 m_active_io_handler(eIOHandlerNone),
271 m_session_is_active(false),
272 m_pty_slave_is_open(false),
273 m_valid_session(true),
275 m_command_thread_state(nullptr)
279 m_dictionary_name.append("_dict");
280 StreamString run_string;
281 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
284 ScriptInterpreterPython::Locker::AcquireLock,
285 ScriptInterpreterPython::Locker::FreeAcquiredLock);
286 PyRun_SimpleString (run_string.GetData());
289 run_string.Printf ("run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", m_dictionary_name.c_str());
290 PyRun_SimpleString (run_string.GetData());
292 // Reloading modules requires a different syntax in Python 2 and Python 3. This provides
293 // a consistent syntax no matter what version of Python.
295 run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", m_dictionary_name.c_str());
296 PyRun_SimpleString(run_string.GetData());
298 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
299 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
301 run_string.Printf ("run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", m_dictionary_name.c_str());
302 PyRun_SimpleString (run_string.GetData());
305 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());
306 PyRun_SimpleString (run_string.GetData());
309 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(),
310 interpreter.GetDebugger().GetID());
311 PyRun_SimpleString (run_string.GetData());
314 ScriptInterpreterPython::~ScriptInterpreterPython ()
316 // the session dictionary may hold objects with complex state
317 // which means that they may need to be torn down with some level of smarts
318 // and that, in turn, requires a valid thread state
319 // force Python to procure itself such a thread state, nuke the session dictionary
320 // and then release it for others to use and proceed with the rest of the shutdown
321 auto gil_state = PyGILState_Ensure();
322 m_session_dict.Reset();
323 PyGILState_Release(gil_state);
327 ScriptInterpreterPython::Initialize()
329 static std::once_flag g_once_flag;
331 std::call_once(g_once_flag, []()
333 PluginManager::RegisterPlugin(GetPluginNameStatic(),
334 GetPluginDescriptionStatic(),
335 lldb::eScriptLanguagePython,
341 ScriptInterpreterPython::Terminate()
346 lldb::ScriptInterpreterSP
347 ScriptInterpreterPython::CreateInstance(CommandInterpreter &interpreter)
349 return std::make_shared<ScriptInterpreterPython>(interpreter);
352 lldb_private::ConstString
353 ScriptInterpreterPython::GetPluginNameStatic()
355 static ConstString g_name("script-python");
360 ScriptInterpreterPython::GetPluginDescriptionStatic()
362 return "Embedded Python interpreter";
365 lldb_private::ConstString
366 ScriptInterpreterPython::GetPluginName()
368 return GetPluginNameStatic();
372 ScriptInterpreterPython::GetPluginVersion()
378 ScriptInterpreterPython::IOHandlerActivated (IOHandler &io_handler)
380 const char *instructions = nullptr;
382 switch (m_active_io_handler)
386 case eIOHandlerBreakpoint:
387 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
388 def function (frame, bp_loc, internal_dict):
389 """frame: the lldb.SBFrame for the location at which you stopped
390 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
391 internal_dict: an LLDB support object not to be used"""
394 case eIOHandlerWatchpoint:
395 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
401 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
404 output_sp->PutCString(instructions);
411 ScriptInterpreterPython::IOHandlerInputComplete (IOHandler &io_handler, std::string &data)
413 io_handler.SetIsDone(true);
414 bool batch_mode = m_interpreter.GetBatchCommandMode();
416 switch (m_active_io_handler)
420 case eIOHandlerBreakpoint:
422 std::vector<BreakpointOptions *> *bp_options_vec = (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
423 for (auto bp_options : *bp_options_vec)
428 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
431 data_ap->user_source.SplitIntoLines(data);
433 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source).Success())
435 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
436 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
438 else if (!batch_mode)
440 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
443 error_sp->Printf ("Warning: No command attached to breakpoint.\n");
449 m_active_io_handler = eIOHandlerNone;
452 case eIOHandlerWatchpoint:
454 WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData();
455 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
458 data_ap->user_source.SplitIntoLines(data);
460 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
462 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
463 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
465 else if (!batch_mode)
467 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
470 error_sp->Printf ("Warning: No command attached to breakpoint.\n");
475 m_active_io_handler = eIOHandlerNone;
483 ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
488 ScriptInterpreterPython::SaveTerminalState (int fd)
490 // Python mucks with the terminal state of STDIN. If we can possibly avoid
491 // this by setting the file handles up correctly prior to entering the
492 // interpreter we should. For now we save and restore the terminal state
493 // on the input file handle.
494 m_terminal_state.Save (fd, false);
498 ScriptInterpreterPython::RestoreTerminalState ()
500 // Python mucks with the terminal state of STDIN. If we can possibly avoid
501 // this by setting the file handles up correctly prior to entering the
502 // interpreter we should. For now we save and restore the terminal state
503 // on the input file handle.
504 m_terminal_state.Restore();
508 ScriptInterpreterPython::LeaveSession ()
510 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
512 log->PutCString("ScriptInterpreterPython::LeaveSession()");
514 // checking that we have a valid thread state - since we use our own threading and locking
515 // in some (rare) cases during cleanup Python may end up believing we have no thread state
516 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
517 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
519 // rdar://problem/11292882
520 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
521 if (PyThreadState_GetDict())
523 PythonDictionary &sys_module_dict = GetSysModuleDictionary ();
524 if (sys_module_dict.IsValid())
526 if (m_saved_stdin.IsValid())
528 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
529 m_saved_stdin.Reset ();
531 if (m_saved_stdout.IsValid())
533 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
534 m_saved_stdout.Reset ();
536 if (m_saved_stderr.IsValid())
538 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
539 m_saved_stderr.Reset ();
544 m_session_is_active = false;
548 ScriptInterpreterPython::SetStdHandle(File &file, const char *py_name, PythonFile &save_file, const char *mode)
552 // Flush the file before giving it to python to avoid interleaved output.
555 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
557 save_file = sys_module_dict.GetItemForKey(PythonString(py_name)).AsType<PythonFile>();
559 PythonFile new_file(file, mode);
560 sys_module_dict.SetItemForKey(PythonString(py_name), new_file);
569 ScriptInterpreterPython::EnterSession (uint16_t on_entry_flags,
574 // If we have already entered the session, without having officially 'left' it, then there is no need to
576 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
577 if (m_session_is_active)
580 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ") session is already active, returning without doing anything", on_entry_flags);
585 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")", on_entry_flags);
588 m_session_is_active = true;
590 StreamString run_string;
592 if (on_entry_flags & Locker::InitGlobals)
594 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
595 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
596 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
597 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
598 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
599 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
600 run_string.PutCString ("')");
604 // If we aren't initing the globals, we should still always set the debugger (since that is always unique.)
605 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
606 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
607 run_string.PutCString ("')");
610 PyRun_SimpleString (run_string.GetData());
613 PythonDictionary &sys_module_dict = GetSysModuleDictionary ();
614 if (sys_module_dict.IsValid())
616 File in_file(in, false);
617 File out_file(out, false);
618 File err_file(err, false);
620 lldb::StreamFileSP in_sp;
621 lldb::StreamFileSP out_sp;
622 lldb::StreamFileSP err_sp;
623 if (!in_file.IsValid() || !out_file.IsValid() || !err_file.IsValid())
624 m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid (in_sp, out_sp, err_sp);
627 if (on_entry_flags & Locker::NoSTDIN)
629 m_saved_stdin.Reset();
633 if (!SetStdHandle(in_file, "stdin", m_saved_stdin, "r"))
636 SetStdHandle(in_sp->GetFile(), "stdin", m_saved_stdin, "r");
640 if (!SetStdHandle(out_file, "stdout", m_saved_stdout, "w"))
643 SetStdHandle(out_sp->GetFile(), "stdout", m_saved_stdout, "w");
646 if (!SetStdHandle(err_file, "stderr", m_saved_stderr, "w"))
649 SetStdHandle(err_sp->GetFile(), "stderr", m_saved_stderr, "w");
653 if (PyErr_Occurred())
660 ScriptInterpreterPython::GetMainModule()
662 if (!m_main_module.IsValid())
663 m_main_module.Reset(PyRefType::Borrowed, PyImport_AddModule("__main__"));
664 return m_main_module;
668 ScriptInterpreterPython::GetSessionDictionary ()
670 if (m_session_dict.IsValid())
671 return m_session_dict;
673 PythonObject &main_module = GetMainModule();
674 if (!main_module.IsValid())
675 return m_session_dict;
677 PythonDictionary main_dict(PyRefType::Borrowed, PyModule_GetDict(main_module.get()));
678 if (!main_dict.IsValid())
679 return m_session_dict;
681 PythonObject item = main_dict.GetItemForKey(PythonString(m_dictionary_name));
682 m_session_dict.Reset(PyRefType::Borrowed, item.get());
683 return m_session_dict;
687 ScriptInterpreterPython::GetSysModuleDictionary ()
689 if (m_sys_module_dict.IsValid())
690 return m_sys_module_dict;
692 PythonObject sys_module(PyRefType::Borrowed, PyImport_AddModule("sys"));
693 if (sys_module.IsValid())
694 m_sys_module_dict.Reset(PyRefType::Borrowed, PyModule_GetDict(sys_module.get()));
695 return m_sys_module_dict;
699 GenerateUniqueName (const char* base_name_wanted,
700 uint32_t& functions_counter,
701 const void* name_token = nullptr)
705 if (!base_name_wanted)
706 return std::string();
709 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
711 sstr.Printf ("%s_%p", base_name_wanted, name_token);
713 return sstr.GetString();
717 ScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects ()
719 if (m_run_one_line_function.IsValid())
722 PythonObject module(PyRefType::Borrowed, PyImport_AddModule ("lldb.embedded_interpreter"));
723 if (!module.IsValid())
726 PythonDictionary module_dict(PyRefType::Borrowed, PyModule_GetDict(module.get()));
727 if (!module_dict.IsValid())
730 m_run_one_line_function = module_dict.GetItemForKey(PythonString("run_one_line"));
731 m_run_one_line_str_global = module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
732 return m_run_one_line_function.IsValid();
736 ReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
740 Stream *strm = (Stream *)baton;
741 strm->Write(src, src_len);
747 ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options)
749 if (!m_valid_session)
752 if (command && command[0])
754 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
755 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
756 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
757 // method to pass the command string directly down to Python.
758 Debugger &debugger = m_interpreter.GetDebugger();
760 StreamFileSP input_file_sp;
761 StreamFileSP output_file_sp;
762 StreamFileSP error_file_sp;
763 Communication output_comm ("lldb.ScriptInterpreterPython.ExecuteOneLine.comm");
764 bool join_read_thread = false;
765 if (options.GetEnableIO())
769 input_file_sp = debugger.GetInputFile();
770 // Set output to a temporary file so we can forward the results on to the result object
773 Error pipe_result = pipe.CreateNew(false);
774 if (pipe_result.Success())
777 lldb::file_t read_file = pipe.GetReadNativeHandle();
778 pipe.ReleaseReadFileDescriptor();
779 std::unique_ptr<ConnectionGenericFile> conn_ap(new ConnectionGenericFile(read_file, true));
781 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(), true));
783 if (conn_ap->IsConnected())
785 output_comm.SetConnection(conn_ap.release());
786 output_comm.SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived, &result->GetOutputStream());
787 output_comm.StartReadThread();
788 join_read_thread = true;
789 FILE *outfile_handle = fdopen (pipe.ReleaseWriteFileDescriptor(), "w");
790 output_file_sp.reset(new StreamFile(outfile_handle, true));
791 error_file_sp = output_file_sp;
793 ::setbuf (outfile_handle, nullptr);
795 result->SetImmediateOutputFile(debugger.GetOutputFile()->GetFile().GetStream());
796 result->SetImmediateErrorFile(debugger.GetErrorFile()->GetFile().GetStream());
800 if (!input_file_sp || !output_file_sp || !error_file_sp)
801 debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, error_file_sp);
805 input_file_sp.reset (new StreamFile ());
806 input_file_sp->GetFile().Open(FileSystem::DEV_NULL, File::eOpenOptionRead);
807 output_file_sp.reset (new StreamFile ());
808 output_file_sp->GetFile().Open(FileSystem::DEV_NULL, File::eOpenOptionWrite);
809 error_file_sp = output_file_sp;
812 FILE *in_file = input_file_sp->GetFile().GetStream();
813 FILE *out_file = output_file_sp->GetFile().GetStream();
814 FILE *err_file = error_file_sp->GetFile().GetStream();
815 bool success = false;
817 // WARNING! It's imperative that this RAII scope be as tight as possible. In particular, the
818 // scope must end *before* we try to join the read thread. The reason for this is that a
819 // pre-requisite for joining the read thread is that we close the write handle (to break the
820 // pipe and cause it to wake up and exit). But acquiring the GIL as below will redirect Python's
821 // stdio to use this same handle. If we close the handle while Python is still using it, bad
822 // things will happen.
824 ScriptInterpreterPython::Locker::AcquireLock |
825 ScriptInterpreterPython::Locker::InitSession |
826 (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) |
827 ((result && result->GetInteractive()) ? 0: Locker::NoSTDIN),
828 ScriptInterpreterPython::Locker::FreeAcquiredLock |
829 ScriptInterpreterPython::Locker::TearDownSession,
834 // Find the correct script interpreter dictionary in the main module.
835 PythonDictionary &session_dict = GetSessionDictionary ();
836 if (session_dict.IsValid())
838 if (GetEmbeddedInterpreterModuleObjects ())
840 if (PyCallable_Check(m_run_one_line_function.get()))
842 PythonObject pargs(PyRefType::Owned, Py_BuildValue("(Os)", session_dict.get(), command));
845 PythonObject return_value(PyRefType::Owned,
846 PyObject_CallObject(m_run_one_line_function.get(), pargs.get()));
847 if (return_value.IsValid())
849 else if (options.GetMaskoutErrors() && PyErr_Occurred ())
859 // Flush our output and error file handles
861 if (out_file != err_file)
865 if (join_read_thread)
867 // Close the write end of the pipe since we are done with our
868 // one line script. This should cause the read thread that
869 // output_comm is using to exit
870 output_file_sp->GetFile().Close();
871 // The close above should cause this thread to exit when it gets
872 // to the end of file, so let it get all its data
873 output_comm.JoinReadThread();
874 // Now we can close the read end of the pipe
875 output_comm.Disconnect();
882 // The one-liner failed. Append the error message.
884 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
889 result->AppendError ("empty command passed to python\n");
894 class IOHandlerPythonInterpreter :
899 IOHandlerPythonInterpreter (Debugger &debugger,
900 ScriptInterpreterPython *python) :
901 IOHandler (debugger, IOHandler::Type::PythonInterpreter),
907 ~IOHandlerPythonInterpreter() override
913 GetControlSequence (char ch) override
916 return ConstString("quit()\n");
917 return ConstString();
925 int stdin_fd = GetInputFD();
928 Terminal terminal(stdin_fd);
929 TerminalState terminal_state;
930 const bool is_a_tty = terminal.IsATerminal();
934 terminal_state.Save (stdin_fd, false);
935 terminal.SetCanonical(false);
936 terminal.SetEcho(true);
939 ScriptInterpreterPython::Locker locker (m_python,
940 ScriptInterpreterPython::Locker::AcquireLock |
941 ScriptInterpreterPython::Locker::InitSession |
942 ScriptInterpreterPython::Locker::InitGlobals,
943 ScriptInterpreterPython::Locker::FreeAcquiredLock |
944 ScriptInterpreterPython::Locker::TearDownSession);
946 // The following call drops into the embedded interpreter loop and stays there until the
947 // user chooses to exit from the Python interpreter.
948 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
949 // a system call that can hang, and lock it when the syscall has returned.
951 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
952 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
953 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
954 // and things could hang (it's happened before).
956 StreamString run_string;
957 run_string.Printf ("run_python_interpreter (%s)", m_python->GetDictionaryName ());
958 PyRun_SimpleString (run_string.GetData());
961 terminal_state.Restore();
974 Interrupt () override
976 return m_python->Interrupt();
985 ScriptInterpreterPython *m_python;
990 ScriptInterpreterPython::ExecuteInterpreterLoop ()
992 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
994 Debugger &debugger = GetCommandInterpreter().GetDebugger();
996 // At the moment, the only time the debugger does not have an input file handle is when this is called
997 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
998 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
1001 if (!debugger.GetInputFile()->GetFile().IsValid())
1004 IOHandlerSP io_handler_sp (new IOHandlerPythonInterpreter (debugger, this));
1007 debugger.PushIOHandler(io_handler_sp);
1012 ScriptInterpreterPython::Interrupt()
1014 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1016 if (IsExecutingPython())
1018 PyThreadState *state = PyThreadState_GET();
1020 state = GetThreadState();
1023 long tid = state->thread_id;
1024 PyThreadState_Swap(state);
1025 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1027 log->Printf("ScriptInterpreterPython::Interrupt() sending PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid, num_threads);
1032 log->Printf("ScriptInterpreterPython::Interrupt() python code not running, can't interrupt");
1037 ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
1038 ScriptInterpreter::ScriptReturnType return_type,
1040 const ExecuteScriptOptions &options)
1044 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) | Locker::NoSTDIN,
1045 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1047 PythonObject py_return;
1048 PythonObject &main_module = GetMainModule();
1049 PythonDictionary globals(PyRefType::Borrowed, PyModule_GetDict(main_module.get()));
1050 PythonObject py_error;
1051 bool ret_success = false;
1054 PythonDictionary locals = GetSessionDictionary ();
1056 if (!locals.IsValid())
1058 locals.Reset(PyRefType::Owned, PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1061 if (!locals.IsValid())
1064 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1065 if (py_error.IsValid())
1068 if (in_string != nullptr)
1070 { // scope for PythonInputReaderManager
1071 //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
1072 py_return.Reset(PyRefType::Owned, PyRun_String(in_string, Py_eval_input, globals.get(), locals.get()));
1073 if (!py_return.IsValid())
1075 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1076 if (py_error.IsValid())
1079 py_return.Reset(PyRefType::Owned, PyRun_String(in_string, Py_single_input, globals.get(), locals.get()));
1083 if (py_return.IsValid())
1085 switch (return_type)
1087 case eScriptReturnTypeCharPtr: // "char *"
1089 const char format[3] = "s#";
1090 success = PyArg_Parse (py_return.get(), format, (char **) ret_value);
1093 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
1095 const char format[3] = "z";
1096 success = PyArg_Parse (py_return.get(), format, (char **) ret_value);
1099 case eScriptReturnTypeBool:
1101 const char format[2] = "b";
1102 success = PyArg_Parse (py_return.get(), format, (bool *) ret_value);
1105 case eScriptReturnTypeShortInt:
1107 const char format[2] = "h";
1108 success = PyArg_Parse (py_return.get(), format, (short *) ret_value);
1111 case eScriptReturnTypeShortIntUnsigned:
1113 const char format[2] = "H";
1114 success = PyArg_Parse (py_return.get(), format, (unsigned short *) ret_value);
1117 case eScriptReturnTypeInt:
1119 const char format[2] = "i";
1120 success = PyArg_Parse (py_return.get(), format, (int *) ret_value);
1123 case eScriptReturnTypeIntUnsigned:
1125 const char format[2] = "I";
1126 success = PyArg_Parse (py_return.get(), format, (unsigned int *) ret_value);
1129 case eScriptReturnTypeLongInt:
1131 const char format[2] = "l";
1132 success = PyArg_Parse (py_return.get(), format, (long *) ret_value);
1135 case eScriptReturnTypeLongIntUnsigned:
1137 const char format[2] = "k";
1138 success = PyArg_Parse (py_return.get(), format, (unsigned long *) ret_value);
1141 case eScriptReturnTypeLongLong:
1143 const char format[2] = "L";
1144 success = PyArg_Parse (py_return.get(), format, (long long *) ret_value);
1147 case eScriptReturnTypeLongLongUnsigned:
1149 const char format[2] = "K";
1150 success = PyArg_Parse (py_return.get(), format, (unsigned long long *) ret_value);
1153 case eScriptReturnTypeFloat:
1155 const char format[2] = "f";
1156 success = PyArg_Parse (py_return.get(), format, (float *) ret_value);
1159 case eScriptReturnTypeDouble:
1161 const char format[2] = "d";
1162 success = PyArg_Parse (py_return.get(), format, (double *) ret_value);
1165 case eScriptReturnTypeChar:
1167 const char format[2] = "c";
1168 success = PyArg_Parse (py_return.get(), format, (char *) ret_value);
1171 case eScriptReturnTypeOpaqueObject:
1174 PyObject *saved_value = py_return.get();
1175 Py_XINCREF(saved_value);
1176 *((PyObject **)ret_value) = saved_value;
1184 ret_success = false;
1188 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1189 if (py_error.IsValid())
1191 ret_success = false;
1192 if (options.GetMaskoutErrors())
1194 if (PyErr_GivenExceptionMatches (py_error.get(), PyExc_SyntaxError))
1204 ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options)
1209 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) | Locker::NoSTDIN,
1210 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1212 PythonObject return_value;
1213 PythonObject &main_module = GetMainModule();
1214 PythonDictionary globals(PyRefType::Borrowed, PyModule_GetDict(main_module.get()));
1215 PythonObject py_error;
1217 PythonDictionary locals = GetSessionDictionary();
1219 if (!locals.IsValid())
1220 locals.Reset(PyRefType::Owned, PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1222 if (!locals.IsValid())
1225 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1226 if (py_error.IsValid())
1229 if (in_string != nullptr)
1231 PythonObject code_object;
1232 code_object.Reset(PyRefType::Owned, Py_CompileString(in_string, "temp.py", Py_file_input));
1234 if (code_object.IsValid())
1236 // In Python 2.x, PyEval_EvalCode takes a PyCodeObject, but in Python 3.x, it takes
1237 // a PyObject. They are convertible (hence the function PyCode_Check(PyObject*), so
1238 // we have to do the cast for Python 2.x
1239 #if PY_MAJOR_VERSION >= 3
1240 PyObject *py_code_obj = code_object.get();
1242 PyCodeObject *py_code_obj = reinterpret_cast<PyCodeObject *>(code_object.get());
1244 return_value.Reset(PyRefType::Owned, PyEval_EvalCode(py_code_obj, globals.get(), locals.get()));
1248 PythonExceptionState exception_state(!options.GetMaskoutErrors());
1249 if (exception_state.IsError())
1250 error.SetErrorString(exception_state.Format().c_str());
1257 ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (std::vector<BreakpointOptions *> &bp_options_vec,
1258 CommandReturnObject &result)
1260 m_active_io_handler = eIOHandlerBreakpoint;
1261 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, &bp_options_vec);
1265 ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1266 CommandReturnObject &result)
1268 m_active_io_handler = eIOHandlerWatchpoint;
1269 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, wp_options);
1273 ScriptInterpreterPython::SetBreakpointCommandCallbackFunction (BreakpointOptions *bp_options,
1274 const char *function_name)
1276 // For now just cons up a oneliner that calls the provided function.
1277 std::string oneliner("return ");
1278 oneliner += function_name;
1279 oneliner += "(frame, bp_loc, internal_dict)";
1280 m_interpreter.GetScriptInterpreter()->SetBreakpointCommandCallback (bp_options,
1284 // Set a Python one-liner as the callback for the breakpoint.
1286 ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
1287 const char *command_body_text)
1289 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1291 // Split the command_body_text into lines, and pass that to GenerateBreakpointCommandCallbackData. That will
1292 // wrap the body in an auto-generated function, and return the function name in script_source. That is what
1293 // the callback will actually invoke.
1295 data_ap->user_source.SplitIntoLines(command_body_text);
1296 Error error = GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source);
1297 if (error.Success())
1299 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1300 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1307 // Set a Python one-liner as the callback for the watchpoint.
1309 ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1310 const char *oneliner)
1312 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1314 // It's necessary to set both user_source and script_source to the oneliner.
1315 // The former is used to generate callback description (as in watchpoint command list)
1316 // while the latter is used for Python to interpret during the actual callback.
1318 data_ap->user_source.AppendString (oneliner);
1319 data_ap->script_source.assign (oneliner);
1321 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1323 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1324 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1331 ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1333 // Convert StringList to one long, newline delimited, const char *.
1334 std::string function_def_string(function_def.CopyList());
1336 Error error = ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1341 ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
1344 int num_lines = input.GetSize ();
1347 error.SetErrorString ("No input data.");
1351 if (!signature || *signature == 0)
1353 error.SetErrorString("No output function name.");
1358 StringList auto_generated_function;
1359 auto_generated_function.AppendString (signature);
1360 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1361 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
1362 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1363 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
1364 // global dictionary.
1366 // Wrap everything up inside the function, increasing the indentation.
1368 auto_generated_function.AppendString(" if True:");
1369 for (int i = 0; i < num_lines; ++i)
1372 sstr.Printf (" %s", input.GetStringAtIndex (i));
1373 auto_generated_function.AppendString (sstr.GetData());
1375 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1376 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
1377 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1378 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1380 // Verify that the results are valid Python.
1382 error = ExportFunctionDefinitionToInterpreter (auto_generated_function);
1388 ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, const void* name_token)
1390 static uint32_t num_created_functions = 0;
1391 user_input.RemoveBlankLines ();
1394 // Check to see if we have any data; if not, just return.
1395 if (user_input.GetSize() == 0)
1398 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1399 // ValueObject as parameter to the function.
1401 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
1402 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
1404 if (!GenerateFunction(sstr.GetData(), user_input).Success())
1407 // Store the name of the auto-generated function to be called.
1408 output.assign(auto_generated_function_name);
1413 ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
1415 static uint32_t num_created_functions = 0;
1416 user_input.RemoveBlankLines ();
1419 // Check to see if we have any data; if not, just return.
1420 if (user_input.GetSize() == 0)
1423 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1425 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
1427 if (!GenerateFunction(sstr.GetData(),user_input).Success())
1430 // Store the name of the auto-generated function to be called.
1431 output.assign(auto_generated_function_name);
1437 ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, const void* name_token)
1439 static uint32_t num_created_classes = 0;
1440 user_input.RemoveBlankLines ();
1441 int num_lines = user_input.GetSize ();
1444 // Check to see if we have any data; if not, just return.
1445 if (user_input.GetSize() == 0)
1448 // Wrap all user input into a Python class
1450 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
1452 StringList auto_generated_class;
1454 // Create the function name & definition string.
1456 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1457 auto_generated_class.AppendString (sstr.GetData());
1459 // Wrap everything up inside the class, increasing the indentation.
1460 // we don't need to play any fancy indentation tricks here because there is no
1461 // surrounding code whose indentation we need to honor
1462 for (int i = 0; i < num_lines; ++i)
1465 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1466 auto_generated_class.AppendString (sstr.GetData());
1470 // Verify that the results are valid Python.
1471 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1472 // (TODO: rename that method to ExportDefinitionToInterpreter)
1473 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class).Success())
1476 // Store the name of the auto-generated class
1478 output.assign(auto_generated_class_name);
1482 StructuredData::GenericSP
1483 ScriptInterpreterPython::OSPlugin_CreatePluginObject(const char *class_name, lldb::ProcessSP process_sp)
1485 if (class_name == nullptr || class_name[0] == '\0')
1486 return StructuredData::GenericSP();
1489 return StructuredData::GenericSP();
1494 Locker py_lock (this,
1495 Locker::AcquireLock | Locker::NoSTDIN,
1497 ret_val = g_swig_create_os_plugin (class_name,
1498 m_dictionary_name.c_str(),
1502 return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1505 StructuredData::DictionarySP
1506 ScriptInterpreterPython::OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp)
1508 Locker py_lock(this,
1509 Locker::AcquireLock | Locker::NoSTDIN,
1512 static char callee_name[] = "get_register_info";
1514 if (!os_plugin_object_sp)
1515 return StructuredData::DictionarySP();
1517 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1521 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue());
1523 if (!implementor.IsAllocated())
1524 return StructuredData::DictionarySP();
1526 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
1528 if (PyErr_Occurred())
1531 if (!pmeth.IsAllocated())
1532 return StructuredData::DictionarySP();
1534 if (PyCallable_Check(pmeth.get()) == 0)
1536 if (PyErr_Occurred())
1539 return StructuredData::DictionarySP();
1542 if (PyErr_Occurred())
1545 // right now we know this function exists and is callable..
1546 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1548 // if it fails, print the error but otherwise go on
1549 if (PyErr_Occurred())
1554 if (py_return.get())
1556 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1557 return result_dict.CreateStructuredDictionary();
1559 return StructuredData::DictionarySP();
1562 StructuredData::ArraySP
1563 ScriptInterpreterPython::OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp)
1565 Locker py_lock (this,
1566 Locker::AcquireLock | Locker::NoSTDIN,
1569 static char callee_name[] = "get_thread_info";
1571 if (!os_plugin_object_sp)
1572 return StructuredData::ArraySP();
1574 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1578 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue());
1580 if (!implementor.IsAllocated())
1581 return StructuredData::ArraySP();
1583 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
1585 if (PyErr_Occurred())
1588 if (!pmeth.IsAllocated())
1589 return StructuredData::ArraySP();
1591 if (PyCallable_Check(pmeth.get()) == 0)
1593 if (PyErr_Occurred())
1596 return StructuredData::ArraySP();
1599 if (PyErr_Occurred())
1602 // right now we know this function exists and is callable..
1603 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1605 // if it fails, print the error but otherwise go on
1606 if (PyErr_Occurred())
1612 if (py_return.get())
1614 PythonList result_list(PyRefType::Borrowed, py_return.get());
1615 return result_list.CreateStructuredArray();
1617 return StructuredData::ArraySP();
1620 // GetPythonValueFormatString provides a system independent type safe way to
1621 // convert a variable's type into a python value format. Python value formats
1622 // are defined in terms of builtin C types and could change from system to
1623 // as the underlying typedef for uint* types, size_t, off_t and other values
1626 template <typename T>
1627 const char *GetPythonValueFormatString(T t)
1629 assert(!"Unhandled type passed to GetPythonValueFormatString(T), make a specialization of GetPythonValueFormatString() to support this type.");
1632 template <> const char *GetPythonValueFormatString (char *) { return "s"; }
1633 template <> const char *GetPythonValueFormatString (char) { return "b"; }
1634 template <> const char *GetPythonValueFormatString (unsigned char) { return "B"; }
1635 template <> const char *GetPythonValueFormatString (short) { return "h"; }
1636 template <> const char *GetPythonValueFormatString (unsigned short) { return "H"; }
1637 template <> const char *GetPythonValueFormatString (int) { return "i"; }
1638 template <> const char *GetPythonValueFormatString (unsigned int) { return "I"; }
1639 template <> const char *GetPythonValueFormatString (long) { return "l"; }
1640 template <> const char *GetPythonValueFormatString (unsigned long) { return "k"; }
1641 template <> const char *GetPythonValueFormatString (long long) { return "L"; }
1642 template <> const char *GetPythonValueFormatString (unsigned long long) { return "K"; }
1643 template <> const char *GetPythonValueFormatString (float t) { return "f"; }
1644 template <> const char *GetPythonValueFormatString (double t) { return "d"; }
1646 StructuredData::StringSP
1647 ScriptInterpreterPython::OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid)
1649 Locker py_lock (this,
1650 Locker::AcquireLock | Locker::NoSTDIN,
1653 static char callee_name[] = "get_register_data";
1654 static char *param_format = const_cast<char *>(GetPythonValueFormatString(tid));
1656 if (!os_plugin_object_sp)
1657 return StructuredData::StringSP();
1659 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1662 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue());
1664 if (!implementor.IsAllocated())
1665 return StructuredData::StringSP();
1667 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
1669 if (PyErr_Occurred())
1672 if (!pmeth.IsAllocated())
1673 return StructuredData::StringSP();
1675 if (PyCallable_Check(pmeth.get()) == 0)
1677 if (PyErr_Occurred())
1679 return StructuredData::StringSP();
1682 if (PyErr_Occurred())
1685 // right now we know this function exists and is callable..
1686 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1688 // if it fails, print the error but otherwise go on
1689 if (PyErr_Occurred())
1695 if (py_return.get())
1697 PythonBytes result(PyRefType::Borrowed, py_return.get());
1698 return result.CreateStructuredString();
1700 return StructuredData::StringSP();
1703 StructuredData::DictionarySP
1704 ScriptInterpreterPython::OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, lldb::addr_t context)
1706 Locker py_lock(this,
1707 Locker::AcquireLock | Locker::NoSTDIN,
1710 static char callee_name[] = "create_thread";
1711 std::string param_format;
1712 param_format += GetPythonValueFormatString(tid);
1713 param_format += GetPythonValueFormatString(context);
1715 if (!os_plugin_object_sp)
1716 return StructuredData::DictionarySP();
1718 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1722 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue());
1724 if (!implementor.IsAllocated())
1725 return StructuredData::DictionarySP();
1727 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
1729 if (PyErr_Occurred())
1732 if (!pmeth.IsAllocated())
1733 return StructuredData::DictionarySP();
1735 if (PyCallable_Check(pmeth.get()) == 0)
1737 if (PyErr_Occurred())
1739 return StructuredData::DictionarySP();
1742 if (PyErr_Occurred())
1745 // right now we know this function exists and is callable..
1746 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, ¶m_format[0], tid, context));
1748 // if it fails, print the error but otherwise go on
1749 if (PyErr_Occurred())
1755 if (py_return.get())
1757 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1758 return result_dict.CreateStructuredDictionary();
1760 return StructuredData::DictionarySP();
1763 StructuredData::ObjectSP
1764 ScriptInterpreterPython::CreateScriptedThreadPlan(const char *class_name, lldb::ThreadPlanSP thread_plan_sp)
1766 if (class_name == nullptr || class_name[0] == '\0')
1767 return StructuredData::ObjectSP();
1769 if (!thread_plan_sp.get())
1770 return StructuredData::ObjectSP();
1772 Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1773 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1774 ScriptInterpreterPython *python_interpreter = static_cast<ScriptInterpreterPython *>(script_interpreter);
1776 if (!script_interpreter)
1777 return StructuredData::ObjectSP();
1782 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1784 ret_val = g_swig_thread_plan_script (class_name,
1785 python_interpreter->m_dictionary_name.c_str(),
1789 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1793 ScriptInterpreterPython::ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error)
1795 bool explains_stop = true;
1796 StructuredData::Generic *generic = nullptr;
1798 generic = implementor_sp->GetAsGeneric();
1801 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1802 explains_stop = g_swig_call_thread_plan(generic->GetValue(), "explains_stop", event, script_error);
1806 return explains_stop;
1810 ScriptInterpreterPython::ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error)
1812 bool should_stop = true;
1813 StructuredData::Generic *generic = nullptr;
1815 generic = implementor_sp->GetAsGeneric();
1818 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1819 should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop", event, script_error);
1827 ScriptInterpreterPython::ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, bool &script_error)
1829 bool should_step = false;
1830 StructuredData::Generic *generic = nullptr;
1832 generic = implementor_sp->GetAsGeneric();
1835 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1836 should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step", NULL, script_error);
1841 return lldb::eStateStepping;
1843 return lldb::eStateRunning;
1846 StructuredData::ObjectSP
1847 ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec, lldb_private::Error &error)
1849 if (!file_spec.Exists())
1851 error.SetErrorString("no such file");
1852 return StructuredData::ObjectSP();
1855 StructuredData::ObjectSP module_sp;
1857 if (LoadScriptingModule(file_spec.GetPath().c_str(),true,true,error,&module_sp))
1860 return StructuredData::ObjectSP();
1863 StructuredData::DictionarySP
1864 ScriptInterpreterPython::GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name,
1865 lldb_private::Error &error)
1867 if (!plugin_module_sp || !target || !setting_name || !setting_name[0] || !g_swig_plugin_get)
1868 return StructuredData::DictionarySP();
1869 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1871 return StructuredData::DictionarySP();
1873 PythonObject reply_pyobj;
1875 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1876 TargetSP target_sp(target->shared_from_this());
1877 reply_pyobj.Reset(PyRefType::Owned,
1878 (PyObject *)g_swig_plugin_get(generic->GetValue(), setting_name, target_sp));
1881 PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get());
1882 return py_dict.CreateStructuredDictionary();
1885 StructuredData::ObjectSP
1886 ScriptInterpreterPython::CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj)
1888 if (class_name == nullptr || class_name[0] == '\0')
1889 return StructuredData::ObjectSP();
1892 return StructuredData::ObjectSP();
1894 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1895 Target *target = exe_ctx.GetTargetPtr();
1898 return StructuredData::ObjectSP();
1900 Debugger &debugger = target->GetDebugger();
1901 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1902 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1904 if (!script_interpreter)
1905 return StructuredData::ObjectSP();
1907 void *ret_val = nullptr;
1910 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1911 ret_val = g_swig_synthetic_script (class_name,
1912 python_interpreter->m_dictionary_name.c_str(),
1916 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1919 StructuredData::GenericSP
1920 ScriptInterpreterPython::CreateScriptCommandObject (const char *class_name)
1922 DebuggerSP debugger_sp(GetCommandInterpreter().GetDebugger().shared_from_this());
1924 if (class_name == nullptr || class_name[0] == '\0')
1925 return StructuredData::GenericSP();
1927 if (!debugger_sp.get())
1928 return StructuredData::GenericSP();
1933 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1934 ret_val = g_swig_create_cmd (class_name,
1935 m_dictionary_name.c_str(),
1939 return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1943 ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, const void* name_token)
1946 input.SplitIntoLines(oneliner, strlen(oneliner));
1947 return GenerateTypeScriptFunction(input, output, name_token);
1951 ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, const void* name_token)
1954 input.SplitIntoLines(oneliner, strlen(oneliner));
1955 return GenerateTypeSynthClass(input, output, name_token);
1960 ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
1962 static uint32_t num_created_functions = 0;
1963 user_input.RemoveBlankLines ();
1966 if (user_input.GetSize() == 0)
1968 error.SetErrorString("No input data.");
1972 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
1973 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
1975 error = GenerateFunction(sstr.GetData(), user_input);
1976 if (!error.Success())
1979 // Store the name of the auto-generated function to be called.
1980 output.assign(auto_generated_function_name);
1985 ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1987 static uint32_t num_created_functions = 0;
1988 user_input.RemoveBlankLines ();
1991 if (user_input.GetSize() == 0)
1994 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1995 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1997 if (!GenerateFunction(sstr.GetData(), user_input).Success())
2000 // Store the name of the auto-generated function to be called.
2001 output.assign(auto_generated_function_name);
2006 ScriptInterpreterPython::GetScriptedSummary(const char *python_function_name, lldb::ValueObjectSP valobj,
2007 StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options,
2008 std::string &retval)
2011 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2015 retval.assign("<no object>");
2019 void *old_callee = nullptr;
2020 StructuredData::Generic *generic = nullptr;
2021 if (callee_wrapper_sp)
2023 generic = callee_wrapper_sp->GetAsGeneric();
2025 old_callee = generic->GetValue();
2027 void* new_callee = old_callee;
2030 if (python_function_name && *python_function_name)
2033 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2035 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2037 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
2038 ret_val = g_swig_typescript_callback (python_function_name,
2039 GetSessionDictionary().get(),
2049 retval.assign("<no function name>");
2053 if (new_callee && old_callee != new_callee)
2054 callee_wrapper_sp.reset(new StructuredPythonObject(new_callee));
2060 ScriptInterpreterPython::Clear ()
2062 // Release any global variables that might have strong references to
2063 // LLDB objects when clearing the python script interpreter.
2065 ScriptInterpreterPython::Locker::AcquireLock,
2066 ScriptInterpreterPython::Locker::FreeAcquiredLock);
2068 // This may be called as part of Py_Finalize. In that case the modules are destroyed in random
2069 // order and we can't guarantee that we can access these.
2070 if (Py_IsInitialized())
2071 PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process = None; lldb.thread = None; lldb.frame = None");
2075 ScriptInterpreterPython::BreakpointCallbackFunction
2078 StoppointCallbackContext *context,
2080 user_id_t break_loc_id
2083 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
2084 const char *python_function_name = bp_option_data->script_source.c_str();
2089 ExecutionContext exe_ctx (context->exe_ctx_ref);
2090 Target *target = exe_ctx.GetTargetPtr();
2095 Debugger &debugger = target->GetDebugger();
2096 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2097 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2099 if (!script_interpreter)
2102 if (python_function_name && python_function_name[0])
2104 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
2105 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
2108 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
2110 if (stop_frame_sp && bp_loc_sp)
2112 bool ret_val = true;
2114 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2115 ret_val = g_swig_breakpoint_callback (python_function_name,
2116 python_interpreter->m_dictionary_name.c_str(),
2124 // We currently always true so we stop in case anything goes wrong when
2125 // trying to call the script function
2130 ScriptInterpreterPython::WatchpointCallbackFunction
2133 StoppointCallbackContext *context,
2137 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
2138 const char *python_function_name = wp_option_data->script_source.c_str();
2143 ExecutionContext exe_ctx (context->exe_ctx_ref);
2144 Target *target = exe_ctx.GetTargetPtr();
2149 Debugger &debugger = target->GetDebugger();
2150 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2151 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2153 if (!script_interpreter)
2156 if (python_function_name && python_function_name[0])
2158 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
2159 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
2162 if (stop_frame_sp && wp_sp)
2164 bool ret_val = true;
2166 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2167 ret_val = g_swig_watchpoint_callback (python_function_name,
2168 python_interpreter->m_dictionary_name.c_str(),
2176 // We currently always true so we stop in case anything goes wrong when
2177 // trying to call the script function
2182 ScriptInterpreterPython::CalculateNumChildren(const StructuredData::ObjectSP &implementor_sp, uint32_t max)
2184 if (!implementor_sp)
2186 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2189 void *implementor = generic->GetValue();
2193 if (!g_swig_calc_children)
2199 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2200 ret_val = g_swig_calc_children (implementor, max);
2207 ScriptInterpreterPython::GetChildAtIndex(const StructuredData::ObjectSP &implementor_sp, uint32_t idx)
2209 if (!implementor_sp)
2210 return lldb::ValueObjectSP();
2212 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2214 return lldb::ValueObjectSP();
2215 void *implementor = generic->GetValue();
2217 return lldb::ValueObjectSP();
2219 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2220 return lldb::ValueObjectSP();
2222 lldb::ValueObjectSP ret_val;
2225 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2226 void* child_ptr = g_swig_get_child_index (implementor,idx);
2227 if (child_ptr != nullptr && child_ptr != Py_None)
2229 lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2230 if (sb_value_ptr == nullptr)
2231 Py_XDECREF(child_ptr);
2233 ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr);
2237 Py_XDECREF(child_ptr);
2245 ScriptInterpreterPython::GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor_sp, const char *child_name)
2247 if (!implementor_sp)
2250 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2253 void *implementor = generic->GetValue();
2257 if (!g_swig_get_index_child)
2260 int ret_val = UINT32_MAX;
2263 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2264 ret_val = g_swig_get_index_child (implementor, child_name);
2271 ScriptInterpreterPython::UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor_sp)
2273 bool ret_val = false;
2275 if (!implementor_sp)
2278 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2281 void *implementor = generic->GetValue();
2285 if (!g_swig_update_provider)
2289 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2290 ret_val = g_swig_update_provider (implementor);
2297 ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor_sp)
2299 bool ret_val = false;
2301 if (!implementor_sp)
2304 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2307 void *implementor = generic->GetValue();
2311 if (!g_swig_mighthavechildren_provider)
2315 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2316 ret_val = g_swig_mighthavechildren_provider (implementor);
2323 ScriptInterpreterPython::GetSyntheticValue(const StructuredData::ObjectSP &implementor_sp)
2325 lldb::ValueObjectSP ret_val(nullptr);
2327 if (!implementor_sp)
2330 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2333 void *implementor = generic->GetValue();
2337 if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue || !g_swig_get_valobj_sp_from_sbvalue)
2341 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2342 void* child_ptr = g_swig_getvalue_provider (implementor);
2343 if (child_ptr != nullptr && child_ptr != Py_None)
2345 lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2346 if (sb_value_ptr == nullptr)
2347 Py_XDECREF(child_ptr);
2349 ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr);
2353 Py_XDECREF(child_ptr);
2361 ScriptInterpreterPython::GetSyntheticTypeName (const StructuredData::ObjectSP &implementor_sp)
2363 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2365 static char callee_name[] = "get_type_name";
2367 ConstString ret_val;
2368 bool got_string = false;
2371 if (!implementor_sp)
2374 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2377 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue());
2378 if (!implementor.IsAllocated())
2381 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
2383 if (PyErr_Occurred())
2386 if (!pmeth.IsAllocated())
2389 if (PyCallable_Check(pmeth.get()) == 0)
2391 if (PyErr_Occurred())
2396 if (PyErr_Occurred())
2399 // right now we know this function exists and is callable..
2400 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2402 // if it fails, print the error but otherwise go on
2403 if (PyErr_Occurred())
2409 if (py_return.IsAllocated() && PythonString::Check(py_return.get()))
2411 PythonString py_string(PyRefType::Borrowed, py_return.get());
2412 llvm::StringRef return_data(py_string.GetString());
2413 if (!return_data.empty())
2415 buffer.assign(return_data.data(), return_data.size());
2421 ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2427 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2429 std::string& output,
2435 error.SetErrorString("no process");
2438 if (!impl_function || !impl_function[0])
2440 error.SetErrorString("no function to execute");
2443 if (!g_swig_run_script_keyword_process)
2445 error.SetErrorString("internal helper function missing");
2449 ProcessSP process_sp(process->shared_from_this());
2450 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2451 ret_val = g_swig_run_script_keyword_process (impl_function, m_dictionary_name.c_str(), process_sp, output);
2453 error.SetErrorString("python script evaluation failed");
2459 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2461 std::string& output,
2467 error.SetErrorString("no thread");
2470 if (!impl_function || !impl_function[0])
2472 error.SetErrorString("no function to execute");
2475 if (!g_swig_run_script_keyword_thread)
2477 error.SetErrorString("internal helper function missing");
2481 ThreadSP thread_sp(thread->shared_from_this());
2482 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2483 ret_val = g_swig_run_script_keyword_thread (impl_function, m_dictionary_name.c_str(), thread_sp, output);
2485 error.SetErrorString("python script evaluation failed");
2491 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2493 std::string& output,
2499 error.SetErrorString("no thread");
2502 if (!impl_function || !impl_function[0])
2504 error.SetErrorString("no function to execute");
2507 if (!g_swig_run_script_keyword_target)
2509 error.SetErrorString("internal helper function missing");
2513 TargetSP target_sp(target->shared_from_this());
2514 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2515 ret_val = g_swig_run_script_keyword_target (impl_function, m_dictionary_name.c_str(), target_sp, output);
2517 error.SetErrorString("python script evaluation failed");
2523 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2525 std::string& output,
2531 error.SetErrorString("no frame");
2534 if (!impl_function || !impl_function[0])
2536 error.SetErrorString("no function to execute");
2539 if (!g_swig_run_script_keyword_frame)
2541 error.SetErrorString("internal helper function missing");
2545 StackFrameSP frame_sp(frame->shared_from_this());
2546 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2547 ret_val = g_swig_run_script_keyword_frame (impl_function, m_dictionary_name.c_str(), frame_sp, output);
2549 error.SetErrorString("python script evaluation failed");
2555 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function,
2557 std::string& output,
2563 error.SetErrorString("no value");
2566 if (!impl_function || !impl_function[0])
2568 error.SetErrorString("no function to execute");
2571 if (!g_swig_run_script_keyword_value)
2573 error.SetErrorString("internal helper function missing");
2577 ValueObjectSP value_sp(value->GetSP());
2578 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2579 ret_val = g_swig_run_script_keyword_value (impl_function, m_dictionary_name.c_str(), value_sp, output);
2581 error.SetErrorString("python script evaluation failed");
2586 uint64_t replace_all(std::string& str, const std::string& oldStr, const std::string& newStr)
2589 uint64_t matches = 0;
2590 while((pos = str.find(oldStr, pos)) != std::string::npos)
2593 str.replace(pos, oldStr.length(), newStr);
2594 pos += newStr.length();
2600 ScriptInterpreterPython::LoadScriptingModule(const char *pathname, bool can_reload, bool init_session, lldb_private::Error &error,
2601 StructuredData::ObjectSP *module_sp)
2603 if (!pathname || !pathname[0])
2605 error.SetErrorString("invalid pathname");
2609 if (!g_swig_call_module_init)
2611 error.SetErrorString("internal helper function missing");
2615 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2618 FileSpec target_file(pathname, true);
2619 std::string basename(target_file.GetFilename().GetCString());
2621 StreamString command_stream;
2623 // Before executing Python code, lock the GIL.
2624 Locker py_lock (this,
2625 Locker::AcquireLock | (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN,
2626 Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0));
2628 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2629 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2631 // if not a valid file of any sort, check if it might be a filename still
2632 // dot can't be used but / and \ can, and if either is found, reject
2633 if (strchr(pathname,'\\') || strchr(pathname,'/'))
2635 error.SetErrorString("invalid pathname");
2638 basename = pathname; // not a filename, probably a package of some sort, let it go through
2640 else if (target_file.GetFileType() == FileSpec::eFileTypeDirectory ||
2641 target_file.GetFileType() == FileSpec::eFileTypeRegular ||
2642 target_file.GetFileType() == FileSpec::eFileTypeSymbolicLink)
2644 std::string directory = target_file.GetDirectory().GetCString();
2645 replace_all(directory, "\\", "\\\\");
2646 replace_all(directory, "'", "\\'");
2648 // now make sure that Python has "directory" in the search path
2649 StreamString command_stream;
2650 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n",
2653 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)).Success();
2654 if (!syspath_retval)
2656 error.SetErrorString("Python sys.path handling failed");
2660 // strip .py or .pyc extension
2661 ConstString extension = target_file.GetFileNameExtension();
2664 if (::strcmp(extension.GetCString(), "py") == 0)
2665 basename.resize(basename.length()-3);
2666 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2667 basename.resize(basename.length()-4);
2672 error.SetErrorString("no known way to import this module specification");
2676 // check if the module is already import-ed
2677 command_stream.Clear();
2678 command_stream.Printf("sys.modules.__contains__('%s')",basename.c_str());
2679 bool does_contain = false;
2680 // this call will succeed if the module was ever imported in any Debugger in the lifetime of the process
2681 // in which this LLDB framework is living
2682 bool was_imported_globally = (ExecuteOneLineWithReturn(command_stream.GetData(),
2683 ScriptInterpreterPython::eScriptReturnTypeBool,
2685 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && does_contain);
2686 // this call will fail if the module was not imported in this Debugger before
2687 command_stream.Clear();
2688 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2689 bool was_imported_locally = GetSessionDictionary().GetItemForKey(PythonString(basename)).IsAllocated();
2691 bool was_imported = (was_imported_globally || was_imported_locally);
2693 if (was_imported == true && can_reload == false)
2695 error.SetErrorString("module already imported");
2699 // now actually do the import
2700 command_stream.Clear();
2704 if (!was_imported_locally)
2705 command_stream.Printf("import %s ; reload_module(%s)",basename.c_str(),basename.c_str());
2707 command_stream.Printf("reload_module(%s)",basename.c_str());
2710 command_stream.Printf("import %s", basename.c_str());
2712 error = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false));
2716 // if we are here, everything worked
2717 // call __lldb_init_module(debugger,dict)
2718 if (!g_swig_call_module_init (basename.c_str(),
2719 m_dictionary_name.c_str(),
2722 error.SetErrorString("calling __lldb_init_module failed");
2728 // everything went just great, now set the module object
2729 command_stream.Clear();
2730 command_stream.Printf("%s",basename.c_str());
2731 void* module_pyobj = nullptr;
2732 if (ExecuteOneLineWithReturn(command_stream.GetData(),ScriptInterpreter::eScriptReturnTypeOpaqueObject,&module_pyobj) && module_pyobj)
2733 module_sp->reset(new StructuredPythonObject(module_pyobj));
2741 ScriptInterpreterPython::IsReservedWord (const char* word)
2743 if (!word || !word[0])
2746 llvm::StringRef word_sr(word);
2748 // filter out a few characters that would just confuse us
2749 // and that are clearly not keyword material anyway
2750 if (word_sr.find_first_of("'\"") != llvm::StringRef::npos)
2753 StreamString command_stream;
2754 command_stream.Printf("keyword.iskeyword('%s')", word);
2756 ExecuteScriptOptions options;
2757 options.SetEnableIO(false);
2758 options.SetMaskoutErrors(true);
2759 options.SetSetLLDBGlobals(false);
2760 if (ExecuteOneLineWithReturn(command_stream.GetData(), ScriptInterpreter::eScriptReturnTypeBool, &result, options))
2765 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2766 ScriptedCommandSynchronicity synchro) :
2767 m_debugger_sp(debugger_sp),
2768 m_synch_wanted(synchro),
2769 m_old_asynch(debugger_sp->GetAsyncExecution())
2771 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2772 m_debugger_sp->SetAsyncExecution(false);
2773 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2774 m_debugger_sp->SetAsyncExecution(true);
2777 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2779 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2780 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2784 ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2786 ScriptedCommandSynchronicity synchronicity,
2787 lldb_private::CommandReturnObject& cmd_retobj,
2789 const lldb_private::ExecutionContext& exe_ctx)
2793 error.SetErrorString("no function to execute");
2797 if (!g_swig_call_command)
2799 error.SetErrorString("no helper function to run scripted commands");
2803 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2804 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2806 if (!debugger_sp.get())
2808 error.SetErrorString("invalid Debugger pointer");
2812 bool ret_val = false;
2814 std::string err_msg;
2817 Locker py_lock(this,
2818 Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2819 Locker::FreeLock | Locker::TearDownSession);
2821 SynchronicityHandler synch_handler(debugger_sp,
2824 ret_val = g_swig_call_command (impl_function,
2825 m_dictionary_name.c_str(),
2833 error.SetErrorString("unable to execute script function");
2841 ScriptInterpreterPython::RunScriptBasedCommand (StructuredData::GenericSP impl_obj_sp,
2843 ScriptedCommandSynchronicity synchronicity,
2844 lldb_private::CommandReturnObject& cmd_retobj,
2846 const lldb_private::ExecutionContext& exe_ctx)
2848 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2850 error.SetErrorString("no function to execute");
2854 if (!g_swig_call_command_object)
2856 error.SetErrorString("no helper function to run scripted commands");
2860 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2861 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2863 if (!debugger_sp.get())
2865 error.SetErrorString("invalid Debugger pointer");
2869 bool ret_val = false;
2871 std::string err_msg;
2874 Locker py_lock(this,
2875 Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2876 Locker::FreeLock | Locker::TearDownSession);
2878 SynchronicityHandler synch_handler(debugger_sp,
2881 ret_val = g_swig_call_command_object (impl_obj_sp->GetValue(),
2889 error.SetErrorString("unable to execute script function");
2896 // in Python, a special attribute __doc__ contains the docstring
2897 // for an object (function, method, class, ...) if any is defined
2898 // Otherwise, the attribute's value is None
2900 ScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest)
2903 if (!item || !*item)
2905 std::string command(item);
2906 command += ".__doc__";
2908 char* result_ptr = nullptr; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2910 if (ExecuteOneLineWithReturn (command.c_str(),
2911 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2913 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)))
2916 dest.assign(result_ptr);
2921 StreamString str_stream;
2922 str_stream.Printf("Function %s was not found. Containing module might be missing.",item);
2923 dest.assign(str_stream.GetData());
2929 ScriptInterpreterPython::GetShortHelpForCommandObject (StructuredData::GenericSP cmd_obj_sp,
2932 bool got_string = false;
2935 Locker py_lock (this,
2936 Locker::AcquireLock | Locker::NoSTDIN,
2939 static char callee_name[] = "get_short_help";
2944 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue());
2946 if (!implementor.IsAllocated())
2949 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
2951 if (PyErr_Occurred())
2954 if (!pmeth.IsAllocated())
2957 if (PyCallable_Check(pmeth.get()) == 0)
2959 if (PyErr_Occurred())
2964 if (PyErr_Occurred())
2967 // right now we know this function exists and is callable..
2968 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2970 // if it fails, print the error but otherwise go on
2971 if (PyErr_Occurred())
2977 if (py_return.IsAllocated() && PythonString::Check(py_return.get()))
2979 PythonString py_string(PyRefType::Borrowed, py_return.get());
2980 llvm::StringRef return_data(py_string.GetString());
2981 dest.assign(return_data.data(), return_data.size());
2988 ScriptInterpreterPython::GetFlagsForCommandObject (StructuredData::GenericSP cmd_obj_sp)
2990 uint32_t result = 0;
2992 Locker py_lock (this,
2993 Locker::AcquireLock | Locker::NoSTDIN,
2996 static char callee_name[] = "get_flags";
3001 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue());
3003 if (!implementor.IsAllocated())
3006 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
3008 if (PyErr_Occurred())
3011 if (!pmeth.IsAllocated())
3014 if (PyCallable_Check(pmeth.get()) == 0)
3016 if (PyErr_Occurred())
3021 if (PyErr_Occurred())
3024 // right now we know this function exists and is callable..
3025 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3027 // if it fails, print the error but otherwise go on
3028 if (PyErr_Occurred())
3034 if (py_return.IsAllocated() && PythonInteger::Check(py_return.get()))
3036 PythonInteger int_value(PyRefType::Borrowed, py_return.get());
3037 result = int_value.GetInteger();
3044 ScriptInterpreterPython::GetLongHelpForCommandObject (StructuredData::GenericSP cmd_obj_sp,
3047 bool got_string = false;
3050 Locker py_lock (this,
3051 Locker::AcquireLock | Locker::NoSTDIN,
3054 static char callee_name[] = "get_long_help";
3059 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue());
3061 if (!implementor.IsAllocated())
3064 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name));
3066 if (PyErr_Occurred())
3069 if (!pmeth.IsAllocated())
3072 if (PyCallable_Check(pmeth.get()) == 0)
3074 if (PyErr_Occurred())
3080 if (PyErr_Occurred())
3083 // right now we know this function exists and is callable..
3084 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3086 // if it fails, print the error but otherwise go on
3087 if (PyErr_Occurred())
3093 if (py_return.IsAllocated() && PythonString::Check(py_return.get()))
3095 PythonString str(PyRefType::Borrowed, py_return.get());
3096 llvm::StringRef str_data(str.GetString());
3097 dest.assign(str_data.data(), str_data.size());
3104 std::unique_ptr<ScriptInterpreterLocker>
3105 ScriptInterpreterPython::AcquireInterpreterLock ()
3107 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(this,
3108 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3109 Locker::FreeLock | Locker::TearDownSession));
3114 ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback swig_init_callback,
3115 SWIGBreakpointCallbackFunction swig_breakpoint_callback,
3116 SWIGWatchpointCallbackFunction swig_watchpoint_callback,
3117 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
3118 SWIGPythonCreateSyntheticProvider swig_synthetic_script,
3119 SWIGPythonCreateCommandObject swig_create_cmd,
3120 SWIGPythonCalculateNumChildren swig_calc_children,
3121 SWIGPythonGetChildAtIndex swig_get_child_index,
3122 SWIGPythonGetIndexOfChildWithName swig_get_index_child,
3123 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue ,
3124 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
3125 SWIGPythonUpdateSynthProviderInstance swig_update_provider,
3126 SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider,
3127 SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
3128 SWIGPythonCallCommand swig_call_command,
3129 SWIGPythonCallCommandObject swig_call_command_object,
3130 SWIGPythonCallModuleInit swig_call_module_init,
3131 SWIGPythonCreateOSPlugin swig_create_os_plugin,
3132 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
3133 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
3134 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
3135 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
3136 SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
3137 SWIGPython_GetDynamicSetting swig_plugin_get,
3138 SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
3139 SWIGPythonCallThreadPlan swig_call_thread_plan)
3141 g_swig_init_callback = swig_init_callback;
3142 g_swig_breakpoint_callback = swig_breakpoint_callback;
3143 g_swig_watchpoint_callback = swig_watchpoint_callback;
3144 g_swig_typescript_callback = swig_typescript_callback;
3145 g_swig_synthetic_script = swig_synthetic_script;
3146 g_swig_create_cmd = swig_create_cmd;
3147 g_swig_calc_children = swig_calc_children;
3148 g_swig_get_child_index = swig_get_child_index;
3149 g_swig_get_index_child = swig_get_index_child;
3150 g_swig_cast_to_sbvalue = swig_cast_to_sbvalue;
3151 g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue;
3152 g_swig_update_provider = swig_update_provider;
3153 g_swig_mighthavechildren_provider = swig_mighthavechildren_provider;
3154 g_swig_getvalue_provider = swig_getvalue_provider;
3155 g_swig_call_command = swig_call_command;
3156 g_swig_call_command_object = swig_call_command_object;
3157 g_swig_call_module_init = swig_call_module_init;
3158 g_swig_create_os_plugin = swig_create_os_plugin;
3159 g_swig_run_script_keyword_process = swig_run_script_keyword_process;
3160 g_swig_run_script_keyword_thread = swig_run_script_keyword_thread;
3161 g_swig_run_script_keyword_target = swig_run_script_keyword_target;
3162 g_swig_run_script_keyword_frame = swig_run_script_keyword_frame;
3163 g_swig_run_script_keyword_value = swig_run_script_keyword_value;
3164 g_swig_plugin_get = swig_plugin_get;
3165 g_swig_thread_plan_script = swig_thread_plan_script;
3166 g_swig_call_thread_plan = swig_call_thread_plan;
3170 ScriptInterpreterPython::InitializePrivate ()
3175 g_initialized = true;
3177 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
3179 // RAII-based initialization which correctly handles multiple-initialization, version-
3180 // specific differences among Python 2 and Python 3, and saving and restoring various
3181 // other pieces of state that can get mucked with during initialization.
3182 InitializePythonRAII initialize_guard;
3184 if (g_swig_init_callback)
3185 g_swig_init_callback ();
3187 // Update the path python uses to search for modules to include the current directory.
3189 PyRun_SimpleString ("import sys");
3190 AddToSysPath(AddLocation::End, ".");
3193 // Don't denormalize paths when calling file_spec.GetPath(). On platforms that use
3194 // a backslash as the path separator, this will result in executing python code containing
3195 // paths with unescaped backslashes. But Python also accepts forward slashes, so to make
3196 // life easier we just use that.
3197 if (HostInfo::GetLLDBPath(ePathTypePythonDir, file_spec))
3198 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3199 if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, file_spec))
3200 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3202 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");
3206 ScriptInterpreterPython::AddToSysPath(AddLocation location, std::string path)
3208 std::string path_copy;
3210 std::string statement;
3211 if (location == AddLocation::Beginning)
3213 statement.assign("sys.path.insert(0,\"");
3214 statement.append (path);
3215 statement.append ("\")");
3219 statement.assign("sys.path.append(\"");
3220 statement.append(path);
3221 statement.append("\")");
3223 PyRun_SimpleString (statement.c_str());
3228 //ScriptInterpreterPython::Terminate ()
3230 // // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
3231 // // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
3232 // // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
3233 // // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
3234 // // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
3235 // // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
3236 // // within Py_Finalize, which results in a seg fault.
3238 // // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
3239 // // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
3240 // // process exits).
3242 //// Py_Finalize ();
3245 #endif // #ifdef LLDB_DISABLE_PYTHON