10b57cec5SDimitry Andric //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 90b57cec5SDimitry Andric #ifdef LLDB_DISABLE_PYTHON 100b57cec5SDimitry Andric 110b57cec5SDimitry Andric // Python is disabled in this build 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #else 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric // LLDB Python header must be included first 160b57cec5SDimitry Andric #include "lldb-python.h" 170b57cec5SDimitry Andric 180b57cec5SDimitry Andric #include "PythonDataObjects.h" 190b57cec5SDimitry Andric #include "PythonExceptionState.h" 200b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h" 210b57cec5SDimitry Andric 220b57cec5SDimitry Andric #include "lldb/API/SBFrame.h" 230b57cec5SDimitry Andric #include "lldb/API/SBValue.h" 240b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h" 250b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h" 260b57cec5SDimitry Andric #include "lldb/Core/Communication.h" 270b57cec5SDimitry Andric #include "lldb/Core/Debugger.h" 280b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h" 290b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h" 300b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h" 310b57cec5SDimitry Andric #include "lldb/Host/ConnectionFileDescriptor.h" 320b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h" 330b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h" 340b57cec5SDimitry Andric #include "lldb/Host/Pipe.h" 350b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h" 360b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h" 370b57cec5SDimitry Andric #include "lldb/Target/Thread.h" 380b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h" 390b57cec5SDimitry Andric #include "lldb/Utility/Timer.h" 400b57cec5SDimitry Andric 410b57cec5SDimitry Andric #if defined(_WIN32) 420b57cec5SDimitry Andric #include "lldb/Host/windows/ConnectionGenericFileWindows.h" 430b57cec5SDimitry Andric #endif 440b57cec5SDimitry Andric 450b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 460b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 470b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h" 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric #include <memory> 500b57cec5SDimitry Andric #include <mutex> 510b57cec5SDimitry Andric #include <stdio.h> 520b57cec5SDimitry Andric #include <stdlib.h> 530b57cec5SDimitry Andric #include <string> 540b57cec5SDimitry Andric 550b57cec5SDimitry Andric using namespace lldb; 560b57cec5SDimitry Andric using namespace lldb_private; 570b57cec5SDimitry Andric 580b57cec5SDimitry Andric // Defined in the SWIG source file 590b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3 600b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void); 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric #else 650b57cec5SDimitry Andric extern "C" void init_lldb(void); 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric #define LLDBSwigPyInit init_lldb 680b57cec5SDimitry Andric #endif 690b57cec5SDimitry Andric 700b57cec5SDimitry Andric // These prototypes are the Pythonic implementations of the required callbacks. 710b57cec5SDimitry Andric // Although these are scripting-language specific, their definition depends on 720b57cec5SDimitry Andric // the public API. 730b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonBreakpointCallbackFunction( 740b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 750b57cec5SDimitry Andric const lldb::StackFrameSP &sb_frame, 760b57cec5SDimitry Andric const lldb::BreakpointLocationSP &sb_bp_loc); 770b57cec5SDimitry Andric 780b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( 790b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 800b57cec5SDimitry Andric const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonCallTypeScript( 830b57cec5SDimitry Andric const char *python_function_name, void *session_dictionary, 840b57cec5SDimitry Andric const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, 850b57cec5SDimitry Andric const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric extern "C" void * 880b57cec5SDimitry Andric LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, 890b57cec5SDimitry Andric const char *session_dictionary_name, 900b57cec5SDimitry Andric const lldb::ValueObjectSP &valobj_sp); 910b57cec5SDimitry Andric 920b57cec5SDimitry Andric extern "C" void * 930b57cec5SDimitry Andric LLDBSwigPythonCreateCommandObject(const char *python_class_name, 940b57cec5SDimitry Andric const char *session_dictionary_name, 950b57cec5SDimitry Andric const lldb::DebuggerSP debugger_sp); 960b57cec5SDimitry Andric 970b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( 980b57cec5SDimitry Andric const char *python_class_name, const char *session_dictionary_name, 990b57cec5SDimitry Andric const lldb::ThreadPlanSP &thread_plan_sp); 1000b57cec5SDimitry Andric 1010b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, 1020b57cec5SDimitry Andric const char *method_name, 1030b57cec5SDimitry Andric Event *event_sp, bool &got_error); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver( 1060b57cec5SDimitry Andric const char *python_class_name, const char *session_dictionary_name, 1070b57cec5SDimitry Andric lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp); 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric extern "C" unsigned int 1100b57cec5SDimitry Andric LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name, 1110b57cec5SDimitry Andric lldb_private::SymbolContext *sym_ctx); 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, 1140b57cec5SDimitry Andric uint32_t max); 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, 1170b57cec5SDimitry Andric uint32_t idx); 1180b57cec5SDimitry Andric 1190b57cec5SDimitry Andric extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, 1200b57cec5SDimitry Andric const char *child_name); 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric extern lldb::ValueObjectSP 1250b57cec5SDimitry Andric LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); 1280b57cec5SDimitry Andric 1290b57cec5SDimitry Andric extern "C" bool 1300b57cec5SDimitry Andric LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); 1310b57cec5SDimitry Andric 1320b57cec5SDimitry Andric extern "C" void * 1330b57cec5SDimitry Andric LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); 1340b57cec5SDimitry Andric 1350b57cec5SDimitry Andric extern "C" bool 1360b57cec5SDimitry Andric LLDBSwigPythonCallCommand(const char *python_function_name, 1370b57cec5SDimitry Andric const char *session_dictionary_name, 1380b57cec5SDimitry Andric lldb::DebuggerSP &debugger, const char *args, 1390b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, 1400b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp); 1410b57cec5SDimitry Andric 1420b57cec5SDimitry Andric extern "C" bool 1430b57cec5SDimitry Andric LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, 1440b57cec5SDimitry Andric const char *args, 1450b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, 1460b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp); 1470b57cec5SDimitry Andric 1480b57cec5SDimitry Andric extern "C" bool 1490b57cec5SDimitry Andric LLDBSwigPythonCallModuleInit(const char *python_module_name, 1500b57cec5SDimitry Andric const char *session_dictionary_name, 1510b57cec5SDimitry Andric lldb::DebuggerSP &debugger); 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric extern "C" void * 1540b57cec5SDimitry Andric LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, 1550b57cec5SDimitry Andric const char *session_dictionary_name, 1560b57cec5SDimitry Andric const lldb::ProcessSP &process_sp); 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric extern "C" void * 1590b57cec5SDimitry Andric LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, 1600b57cec5SDimitry Andric const char *session_dictionary_name); 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric extern "C" void * 1630b57cec5SDimitry Andric LLDBSwigPython_GetRecognizedArguments(void *implementor, 1640b57cec5SDimitry Andric const lldb::StackFrameSP &frame_sp); 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( 1670b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 1680b57cec5SDimitry Andric lldb::ProcessSP &process, std::string &output); 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( 1710b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 1720b57cec5SDimitry Andric lldb::ThreadSP &thread, std::string &output); 1730b57cec5SDimitry Andric 1740b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( 1750b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 1760b57cec5SDimitry Andric lldb::TargetSP &target, std::string &output); 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( 1790b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 1800b57cec5SDimitry Andric lldb::StackFrameSP &frame, std::string &output); 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( 1830b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name, 1840b57cec5SDimitry Andric lldb::ValueObjectSP &value, std::string &output); 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric extern "C" void * 1870b57cec5SDimitry Andric LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, 1880b57cec5SDimitry Andric const lldb::TargetSP &target_sp); 1890b57cec5SDimitry Andric 1900b57cec5SDimitry Andric static bool g_initialized = false; 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric namespace { 1930b57cec5SDimitry Andric 1940b57cec5SDimitry Andric // Initializing Python is not a straightforward process. We cannot control 1950b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB, 1960b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a 1970b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained 1980b57cec5SDimitry Andric // across our initialization. We do this by using an RAII pattern where we 1990b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end 2000b57cec5SDimitry Andric struct InitializePythonRAII { 2010b57cec5SDimitry Andric public: 2020b57cec5SDimitry Andric InitializePythonRAII() 2030b57cec5SDimitry Andric : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) { 2040b57cec5SDimitry Andric // Python will muck with STDIN terminal state, so save off any current TTY 2050b57cec5SDimitry Andric // settings so we can restore them. 2060b57cec5SDimitry Andric m_stdin_tty_state.Save(STDIN_FILENO, false); 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric InitializePythonHome(); 2090b57cec5SDimitry Andric 2100b57cec5SDimitry Andric // Register _lldb as a built-in module. 2110b57cec5SDimitry Andric PyImport_AppendInittab("_lldb", LLDBSwigPyInit); 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 2140b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 2150b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 2160b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 2170b57cec5SDimitry Andric Py_InitializeEx(0); 2180b57cec5SDimitry Andric InitializeThreadsPrivate(); 2190b57cec5SDimitry Andric #else 2200b57cec5SDimitry Andric InitializeThreadsPrivate(); 2210b57cec5SDimitry Andric Py_InitializeEx(0); 2220b57cec5SDimitry Andric #endif 2230b57cec5SDimitry Andric } 2240b57cec5SDimitry Andric 2250b57cec5SDimitry Andric ~InitializePythonRAII() { 2260b57cec5SDimitry Andric if (m_was_already_initialized) { 2270b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 2280b57cec5SDimitry Andric LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 2290b57cec5SDimitry Andric m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 2300b57cec5SDimitry Andric PyGILState_Release(m_gil_state); 2310b57cec5SDimitry Andric } else { 2320b57cec5SDimitry Andric // We initialized the threads in this function, just unlock the GIL. 2330b57cec5SDimitry Andric PyEval_SaveThread(); 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric m_stdin_tty_state.Restore(); 2370b57cec5SDimitry Andric } 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric private: 2400b57cec5SDimitry Andric void InitializePythonHome() { 2410b57cec5SDimitry Andric #if defined(LLDB_PYTHON_HOME) 2420b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3 2430b57cec5SDimitry Andric size_t size = 0; 2440b57cec5SDimitry Andric static wchar_t *g_python_home = Py_DecodeLocale(LLDB_PYTHON_HOME, &size); 2450b57cec5SDimitry Andric #else 2460b57cec5SDimitry Andric static char g_python_home[] = LLDB_PYTHON_HOME; 2470b57cec5SDimitry Andric #endif 2480b57cec5SDimitry Andric Py_SetPythonHome(g_python_home); 2490b57cec5SDimitry Andric #else 2500b57cec5SDimitry Andric #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 2510b57cec5SDimitry Andric // For Darwin, the only Python version supported is the one shipped in the 2520b57cec5SDimitry Andric // OS OS and linked with lldb. Other installation of Python may have higher 2530b57cec5SDimitry Andric // priorities in the path, overriding PYTHONHOME and causing 2540b57cec5SDimitry Andric // problems/incompatibilities. In order to avoid confusion, always hardcode 2550b57cec5SDimitry Andric // the PythonHome to be right, as it's not going to change. 2560b57cec5SDimitry Andric static char path[] = 2570b57cec5SDimitry Andric "/System/Library/Frameworks/Python.framework/Versions/2.7"; 2580b57cec5SDimitry Andric Py_SetPythonHome(path); 2590b57cec5SDimitry Andric #endif 2600b57cec5SDimitry Andric #endif 2610b57cec5SDimitry Andric } 2620b57cec5SDimitry Andric 2630b57cec5SDimitry Andric void InitializeThreadsPrivate() { 2640b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, 2650b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter 2660b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized` 2670b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be 2680b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When 2690b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. 2700b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) 2710b57cec5SDimitry Andric // The only case we should go further and acquire the GIL: it is unlocked. 2720b57cec5SDimitry Andric if (PyGILState_Check()) 2730b57cec5SDimitry Andric return; 2740b57cec5SDimitry Andric #endif 2750b57cec5SDimitry Andric 2760b57cec5SDimitry Andric if (PyEval_ThreadsInitialized()) { 2770b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 2780b57cec5SDimitry Andric 2790b57cec5SDimitry Andric m_was_already_initialized = true; 2800b57cec5SDimitry Andric m_gil_state = PyGILState_Ensure(); 2810b57cec5SDimitry Andric LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n", 2820b57cec5SDimitry Andric m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 2830b57cec5SDimitry Andric return; 2840b57cec5SDimitry Andric } 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric // InitThreads acquires the GIL if it hasn't been called before. 2870b57cec5SDimitry Andric PyEval_InitThreads(); 2880b57cec5SDimitry Andric } 2890b57cec5SDimitry Andric 2900b57cec5SDimitry Andric TerminalState m_stdin_tty_state; 2910b57cec5SDimitry Andric PyGILState_STATE m_gil_state; 2920b57cec5SDimitry Andric bool m_was_already_initialized; 2930b57cec5SDimitry Andric }; 2940b57cec5SDimitry Andric } // namespace 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple( 2970b57cec5SDimitry Andric llvm::SmallVectorImpl<char> &path) { 2980b57cec5SDimitry Andric auto style = llvm::sys::path::Style::posix; 2990b57cec5SDimitry Andric 3000b57cec5SDimitry Andric llvm::StringRef path_ref(path.begin(), path.size()); 3010b57cec5SDimitry Andric auto rbegin = llvm::sys::path::rbegin(path_ref, style); 3020b57cec5SDimitry Andric auto rend = llvm::sys::path::rend(path_ref); 3030b57cec5SDimitry Andric auto framework = std::find(rbegin, rend, "LLDB.framework"); 3040b57cec5SDimitry Andric if (framework == rend) { 3050b57cec5SDimitry Andric ComputePythonDirForPosix(path); 3060b57cec5SDimitry Andric return; 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric path.resize(framework - rend); 3090b57cec5SDimitry Andric llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python"); 3100b57cec5SDimitry Andric } 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForPosix( 3130b57cec5SDimitry Andric llvm::SmallVectorImpl<char> &path) { 3140b57cec5SDimitry Andric auto style = llvm::sys::path::Style::posix; 3150b57cec5SDimitry Andric #if defined(LLDB_PYTHON_RELATIVE_LIBDIR) 3160b57cec5SDimitry Andric // Build the path by backing out of the lib dir, then building with whatever 3170b57cec5SDimitry Andric // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL 3180b57cec5SDimitry Andric // x86_64). 3190b57cec5SDimitry Andric llvm::sys::path::remove_filename(path, style); 3200b57cec5SDimitry Andric llvm::sys::path::append(path, style, LLDB_PYTHON_RELATIVE_LIBDIR); 3210b57cec5SDimitry Andric #else 3220b57cec5SDimitry Andric llvm::sys::path::append(path, style, 3230b57cec5SDimitry Andric "python" + llvm::Twine(PY_MAJOR_VERSION) + "." + 3240b57cec5SDimitry Andric llvm::Twine(PY_MINOR_VERSION), 3250b57cec5SDimitry Andric "site-packages"); 3260b57cec5SDimitry Andric #endif 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric 3290b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForWindows( 3300b57cec5SDimitry Andric llvm::SmallVectorImpl<char> &path) { 3310b57cec5SDimitry Andric auto style = llvm::sys::path::Style::windows; 3320b57cec5SDimitry Andric llvm::sys::path::remove_filename(path, style); 3330b57cec5SDimitry Andric llvm::sys::path::append(path, style, "lib", "site-packages"); 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric // This will be injected directly through FileSpec.GetDirectory().SetString(), 3360b57cec5SDimitry Andric // so we need to normalize manually. 3370b57cec5SDimitry Andric std::replace(path.begin(), path.end(), '\\', '/'); 3380b57cec5SDimitry Andric } 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() { 3410b57cec5SDimitry Andric static FileSpec g_spec = []() { 3420b57cec5SDimitry Andric FileSpec spec = HostInfo::GetShlibDir(); 3430b57cec5SDimitry Andric if (!spec) 3440b57cec5SDimitry Andric return FileSpec(); 3450b57cec5SDimitry Andric llvm::SmallString<64> path; 3460b57cec5SDimitry Andric spec.GetPath(path); 3470b57cec5SDimitry Andric 3480b57cec5SDimitry Andric #if defined(__APPLE__) 3490b57cec5SDimitry Andric ComputePythonDirForApple(path); 3500b57cec5SDimitry Andric #elif defined(_WIN32) 3510b57cec5SDimitry Andric ComputePythonDirForWindows(path); 3520b57cec5SDimitry Andric #else 3530b57cec5SDimitry Andric ComputePythonDirForPosix(path); 3540b57cec5SDimitry Andric #endif 3550b57cec5SDimitry Andric spec.GetDirectory().SetString(path); 3560b57cec5SDimitry Andric return spec; 3570b57cec5SDimitry Andric }(); 3580b57cec5SDimitry Andric return g_spec; 3590b57cec5SDimitry Andric } 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() { 3620b57cec5SDimitry Andric static ConstString g_name("script-python"); 3630b57cec5SDimitry Andric return g_name; 3640b57cec5SDimitry Andric } 3650b57cec5SDimitry Andric 3660b57cec5SDimitry Andric const char *ScriptInterpreterPython::GetPluginDescriptionStatic() { 3670b57cec5SDimitry Andric return "Embedded Python interpreter"; 3680b57cec5SDimitry Andric } 3690b57cec5SDimitry Andric 3700b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() { 3710b57cec5SDimitry Andric static llvm::once_flag g_once_flag; 3720b57cec5SDimitry Andric 3730b57cec5SDimitry Andric llvm::call_once(g_once_flag, []() { 3740b57cec5SDimitry Andric PluginManager::RegisterPlugin(GetPluginNameStatic(), 3750b57cec5SDimitry Andric GetPluginDescriptionStatic(), 3760b57cec5SDimitry Andric lldb::eScriptLanguagePython, 3770b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance); 3780b57cec5SDimitry Andric }); 3790b57cec5SDimitry Andric } 3800b57cec5SDimitry Andric 3810b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {} 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker( 3840b57cec5SDimitry Andric ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, 3850b57cec5SDimitry Andric uint16_t on_leave, FILE *in, FILE *out, FILE *err) 3860b57cec5SDimitry Andric : ScriptInterpreterLocker(), 3870b57cec5SDimitry Andric m_teardown_session((on_leave & TearDownSession) == TearDownSession), 3880b57cec5SDimitry Andric m_python_interpreter(py_interpreter) { 3890b57cec5SDimitry Andric DoAcquireLock(); 3900b57cec5SDimitry Andric if ((on_entry & InitSession) == InitSession) { 3910b57cec5SDimitry Andric if (!DoInitSession(on_entry, in, out, err)) { 3920b57cec5SDimitry Andric // Don't teardown the session if we didn't init it. 3930b57cec5SDimitry Andric m_teardown_session = false; 3940b57cec5SDimitry Andric } 3950b57cec5SDimitry Andric } 3960b57cec5SDimitry Andric } 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { 3990b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 4000b57cec5SDimitry Andric m_GILState = PyGILState_Ensure(); 4010b57cec5SDimitry Andric LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", 4020b57cec5SDimitry Andric m_GILState == PyGILState_UNLOCKED ? "un" : ""); 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric // we need to save the thread state when we first start the command because 4050b57cec5SDimitry Andric // we might decide to interrupt it while some action is taking place outside 4060b57cec5SDimitry Andric // of Python (e.g. printing to screen, waiting for the network, ...) in that 4070b57cec5SDimitry Andric // case, _PyThreadState_Current will be NULL - and we would be unable to set 4080b57cec5SDimitry Andric // the asynchronous exception - not a desirable situation 4090b57cec5SDimitry Andric m_python_interpreter->SetThreadState(PyThreadState_Get()); 4100b57cec5SDimitry Andric m_python_interpreter->IncrementLockCount(); 4110b57cec5SDimitry Andric return true; 4120b57cec5SDimitry Andric } 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, 4150b57cec5SDimitry Andric FILE *in, FILE *out, 4160b57cec5SDimitry Andric FILE *err) { 4170b57cec5SDimitry Andric if (!m_python_interpreter) 4180b57cec5SDimitry Andric return false; 4190b57cec5SDimitry Andric return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); 4200b57cec5SDimitry Andric } 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { 4230b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 4240b57cec5SDimitry Andric LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 4250b57cec5SDimitry Andric m_GILState == PyGILState_UNLOCKED ? "un" : ""); 4260b57cec5SDimitry Andric PyGILState_Release(m_GILState); 4270b57cec5SDimitry Andric m_python_interpreter->DecrementLockCount(); 4280b57cec5SDimitry Andric return true; 4290b57cec5SDimitry Andric } 4300b57cec5SDimitry Andric 4310b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { 4320b57cec5SDimitry Andric if (!m_python_interpreter) 4330b57cec5SDimitry Andric return false; 4340b57cec5SDimitry Andric m_python_interpreter->LeaveSession(); 4350b57cec5SDimitry Andric return true; 4360b57cec5SDimitry Andric } 4370b57cec5SDimitry Andric 4380b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() { 4390b57cec5SDimitry Andric if (m_teardown_session) 4400b57cec5SDimitry Andric DoTearDownSession(); 4410b57cec5SDimitry Andric DoFreeLock(); 4420b57cec5SDimitry Andric } 4430b57cec5SDimitry Andric 4440b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) 4450b57cec5SDimitry Andric : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), 4460b57cec5SDimitry Andric m_saved_stderr(), m_main_module(), 4470b57cec5SDimitry Andric m_session_dict(PyInitialValue::Invalid), 4480b57cec5SDimitry Andric m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), 4490b57cec5SDimitry Andric m_run_one_line_str_global(), 4500b57cec5SDimitry Andric m_dictionary_name(m_debugger.GetInstanceName().AsCString()), 4510b57cec5SDimitry Andric m_terminal_state(), m_active_io_handler(eIOHandlerNone), 4520b57cec5SDimitry Andric m_session_is_active(false), m_pty_slave_is_open(false), 4530b57cec5SDimitry Andric m_valid_session(true), m_lock_count(0), m_command_thread_state(nullptr) { 4540b57cec5SDimitry Andric InitializePrivate(); 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric m_dictionary_name.append("_dict"); 4570b57cec5SDimitry Andric StreamString run_string; 4580b57cec5SDimitry Andric run_string.Printf("%s = dict()", m_dictionary_name.c_str()); 4590b57cec5SDimitry Andric 4600b57cec5SDimitry Andric Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 4610b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric run_string.Clear(); 4640b57cec5SDimitry Andric run_string.Printf( 4650b57cec5SDimitry Andric "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", 4660b57cec5SDimitry Andric m_dictionary_name.c_str()); 4670b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric // Reloading modules requires a different syntax in Python 2 and Python 3. 4700b57cec5SDimitry Andric // This provides a consistent syntax no matter what version of Python. 4710b57cec5SDimitry Andric run_string.Clear(); 4720b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", 4730b57cec5SDimitry Andric m_dictionary_name.c_str()); 4740b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric // WARNING: temporary code that loads Cocoa formatters - this should be done 4770b57cec5SDimitry Andric // on a per-platform basis rather than loading the whole set and letting the 4780b57cec5SDimitry Andric // individual formatter classes exploit APIs to check whether they can/cannot 4790b57cec5SDimitry Andric // do their task 4800b57cec5SDimitry Andric run_string.Clear(); 4810b57cec5SDimitry Andric run_string.Printf( 4820b57cec5SDimitry Andric "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", 4830b57cec5SDimitry Andric m_dictionary_name.c_str()); 4840b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4850b57cec5SDimitry Andric run_string.Clear(); 4860b57cec5SDimitry Andric 4870b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " 4880b57cec5SDimitry Andric "lldb.embedded_interpreter import run_python_interpreter; " 4890b57cec5SDimitry Andric "from lldb.embedded_interpreter import run_one_line')", 4900b57cec5SDimitry Andric m_dictionary_name.c_str()); 4910b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4920b57cec5SDimitry Andric run_string.Clear(); 4930b57cec5SDimitry Andric 4940b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 4950b57cec5SDimitry Andric "; pydoc.pager = pydoc.plainpager')", 4960b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID()); 4970b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 4980b57cec5SDimitry Andric } 4990b57cec5SDimitry Andric 5000b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { 5010b57cec5SDimitry Andric // the session dictionary may hold objects with complex state which means 5020b57cec5SDimitry Andric // that they may need to be torn down with some level of smarts and that, in 5030b57cec5SDimitry Andric // turn, requires a valid thread state force Python to procure itself such a 5040b57cec5SDimitry Andric // thread state, nuke the session dictionary and then release it for others 5050b57cec5SDimitry Andric // to use and proceed with the rest of the shutdown 5060b57cec5SDimitry Andric auto gil_state = PyGILState_Ensure(); 5070b57cec5SDimitry Andric m_session_dict.Reset(); 5080b57cec5SDimitry Andric PyGILState_Release(gil_state); 5090b57cec5SDimitry Andric } 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() { 5120b57cec5SDimitry Andric return GetPluginNameStatic(); 5130b57cec5SDimitry Andric } 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; } 5160b57cec5SDimitry Andric 5170b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, 5180b57cec5SDimitry Andric bool interactive) { 5190b57cec5SDimitry Andric const char *instructions = nullptr; 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric switch (m_active_io_handler) { 5220b57cec5SDimitry Andric case eIOHandlerNone: 5230b57cec5SDimitry Andric break; 5240b57cec5SDimitry Andric case eIOHandlerBreakpoint: 5250b57cec5SDimitry Andric instructions = R"(Enter your Python command(s). Type 'DONE' to end. 5260b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict): 5270b57cec5SDimitry Andric """frame: the lldb.SBFrame for the location at which you stopped 5280b57cec5SDimitry Andric bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 5290b57cec5SDimitry Andric internal_dict: an LLDB support object not to be used""" 5300b57cec5SDimitry Andric )"; 5310b57cec5SDimitry Andric break; 5320b57cec5SDimitry Andric case eIOHandlerWatchpoint: 5330b57cec5SDimitry Andric instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 5340b57cec5SDimitry Andric break; 5350b57cec5SDimitry Andric } 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric if (instructions) { 5380b57cec5SDimitry Andric StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 5390b57cec5SDimitry Andric if (output_sp && interactive) { 5400b57cec5SDimitry Andric output_sp->PutCString(instructions); 5410b57cec5SDimitry Andric output_sp->Flush(); 5420b57cec5SDimitry Andric } 5430b57cec5SDimitry Andric } 5440b57cec5SDimitry Andric } 5450b57cec5SDimitry Andric 5460b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, 5470b57cec5SDimitry Andric std::string &data) { 5480b57cec5SDimitry Andric io_handler.SetIsDone(true); 5490b57cec5SDimitry Andric bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); 5500b57cec5SDimitry Andric 5510b57cec5SDimitry Andric switch (m_active_io_handler) { 5520b57cec5SDimitry Andric case eIOHandlerNone: 5530b57cec5SDimitry Andric break; 5540b57cec5SDimitry Andric case eIOHandlerBreakpoint: { 5550b57cec5SDimitry Andric std::vector<BreakpointOptions *> *bp_options_vec = 5560b57cec5SDimitry Andric (std::vector<BreakpointOptions *> *)io_handler.GetUserData(); 5570b57cec5SDimitry Andric for (auto bp_options : *bp_options_vec) { 5580b57cec5SDimitry Andric if (!bp_options) 5590b57cec5SDimitry Andric continue; 5600b57cec5SDimitry Andric 5610b57cec5SDimitry Andric auto data_up = llvm::make_unique<CommandDataPython>(); 5620b57cec5SDimitry Andric if (!data_up) 5630b57cec5SDimitry Andric break; 5640b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(data); 5650b57cec5SDimitry Andric 5660b57cec5SDimitry Andric if (GenerateBreakpointCommandCallbackData(data_up->user_source, 5670b57cec5SDimitry Andric data_up->script_source) 5680b57cec5SDimitry Andric .Success()) { 5690b57cec5SDimitry Andric auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( 5700b57cec5SDimitry Andric std::move(data_up)); 5710b57cec5SDimitry Andric bp_options->SetCallback( 5720b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 5730b57cec5SDimitry Andric } else if (!batch_mode) { 5740b57cec5SDimitry Andric StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 5750b57cec5SDimitry Andric if (error_sp) { 5760b57cec5SDimitry Andric error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5770b57cec5SDimitry Andric error_sp->Flush(); 5780b57cec5SDimitry Andric } 5790b57cec5SDimitry Andric } 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric m_active_io_handler = eIOHandlerNone; 5820b57cec5SDimitry Andric } break; 5830b57cec5SDimitry Andric case eIOHandlerWatchpoint: { 5840b57cec5SDimitry Andric WatchpointOptions *wp_options = 5850b57cec5SDimitry Andric (WatchpointOptions *)io_handler.GetUserData(); 5860b57cec5SDimitry Andric auto data_up = llvm::make_unique<WatchpointOptions::CommandData>(); 5870b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(data); 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric if (GenerateWatchpointCommandCallbackData(data_up->user_source, 5900b57cec5SDimitry Andric data_up->script_source)) { 5910b57cec5SDimitry Andric auto baton_sp = 5920b57cec5SDimitry Andric std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 5930b57cec5SDimitry Andric wp_options->SetCallback( 5940b57cec5SDimitry Andric ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 5950b57cec5SDimitry Andric } else if (!batch_mode) { 5960b57cec5SDimitry Andric StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 5970b57cec5SDimitry Andric if (error_sp) { 5980b57cec5SDimitry Andric error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5990b57cec5SDimitry Andric error_sp->Flush(); 6000b57cec5SDimitry Andric } 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric m_active_io_handler = eIOHandlerNone; 6030b57cec5SDimitry Andric } break; 6040b57cec5SDimitry Andric } 6050b57cec5SDimitry Andric } 6060b57cec5SDimitry Andric 6070b57cec5SDimitry Andric lldb::ScriptInterpreterSP 6080b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { 6090b57cec5SDimitry Andric return std::make_shared<ScriptInterpreterPythonImpl>(debugger); 6100b57cec5SDimitry Andric } 6110b57cec5SDimitry Andric 6120b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ResetOutputFileHandle(FILE *fh) {} 6130b57cec5SDimitry Andric 6140b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SaveTerminalState(int fd) { 6150b57cec5SDimitry Andric // Python mucks with the terminal state of STDIN. If we can possibly avoid 6160b57cec5SDimitry Andric // this by setting the file handles up correctly prior to entering the 6170b57cec5SDimitry Andric // interpreter we should. For now we save and restore the terminal state on 6180b57cec5SDimitry Andric // the input file handle. 6190b57cec5SDimitry Andric m_terminal_state.Save(fd, false); 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::RestoreTerminalState() { 6230b57cec5SDimitry Andric // Python mucks with the terminal state of STDIN. If we can possibly avoid 6240b57cec5SDimitry Andric // this by setting the file handles up correctly prior to entering the 6250b57cec5SDimitry Andric // interpreter we should. For now we save and restore the terminal state on 6260b57cec5SDimitry Andric // the input file handle. 6270b57cec5SDimitry Andric m_terminal_state.Restore(); 6280b57cec5SDimitry Andric } 6290b57cec5SDimitry Andric 6300b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() { 6310b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 6320b57cec5SDimitry Andric if (log) 6330b57cec5SDimitry Andric log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); 6340b57cec5SDimitry Andric 6350b57cec5SDimitry Andric // checking that we have a valid thread state - since we use our own 6360b57cec5SDimitry Andric // threading and locking in some (rare) cases during cleanup Python may end 6370b57cec5SDimitry Andric // up believing we have no thread state and PyImport_AddModule will crash if 6380b57cec5SDimitry Andric // that is the case - since that seems to only happen when destroying the 6390b57cec5SDimitry Andric // SBDebugger, we can make do without clearing up stdout and stderr 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric // rdar://problem/11292882 6420b57cec5SDimitry Andric // When the current thread state is NULL, PyThreadState_Get() issues a fatal 6430b57cec5SDimitry Andric // error. 6440b57cec5SDimitry Andric if (PyThreadState_GetDict()) { 6450b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 6460b57cec5SDimitry Andric if (sys_module_dict.IsValid()) { 6470b57cec5SDimitry Andric if (m_saved_stdin.IsValid()) { 6480b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 6490b57cec5SDimitry Andric m_saved_stdin.Reset(); 6500b57cec5SDimitry Andric } 6510b57cec5SDimitry Andric if (m_saved_stdout.IsValid()) { 6520b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 6530b57cec5SDimitry Andric m_saved_stdout.Reset(); 6540b57cec5SDimitry Andric } 6550b57cec5SDimitry Andric if (m_saved_stderr.IsValid()) { 6560b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 6570b57cec5SDimitry Andric m_saved_stderr.Reset(); 6580b57cec5SDimitry Andric } 6590b57cec5SDimitry Andric } 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric m_session_is_active = false; 6630b57cec5SDimitry Andric } 6640b57cec5SDimitry Andric 6650b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(File &file, const char *py_name, 6660b57cec5SDimitry Andric PythonFile &save_file, 6670b57cec5SDimitry Andric const char *mode) { 6680b57cec5SDimitry Andric if (file.IsValid()) { 6690b57cec5SDimitry Andric // Flush the file before giving it to python to avoid interleaved output. 6700b57cec5SDimitry Andric file.Flush(); 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 6730b57cec5SDimitry Andric 6740b57cec5SDimitry Andric save_file = sys_module_dict.GetItemForKey(PythonString(py_name)) 6750b57cec5SDimitry Andric .AsType<PythonFile>(); 6760b57cec5SDimitry Andric 6770b57cec5SDimitry Andric PythonFile new_file(file, mode); 6780b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString(py_name), new_file); 6790b57cec5SDimitry Andric return true; 6800b57cec5SDimitry Andric } else 6810b57cec5SDimitry Andric save_file.Reset(); 6820b57cec5SDimitry Andric return false; 6830b57cec5SDimitry Andric } 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, 6860b57cec5SDimitry Andric FILE *in, FILE *out, FILE *err) { 6870b57cec5SDimitry Andric // If we have already entered the session, without having officially 'left' 6880b57cec5SDimitry Andric // it, then there is no need to 'enter' it again. 6890b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 6900b57cec5SDimitry Andric if (m_session_is_active) { 6910b57cec5SDimitry Andric if (log) 6920b57cec5SDimitry Andric log->Printf( 6930b57cec5SDimitry Andric "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 6940b57cec5SDimitry Andric ") session is already active, returning without doing anything", 6950b57cec5SDimitry Andric on_entry_flags); 6960b57cec5SDimitry Andric return false; 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric 6990b57cec5SDimitry Andric if (log) 7000b57cec5SDimitry Andric log->Printf( 7010b57cec5SDimitry Andric "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 7020b57cec5SDimitry Andric ")", 7030b57cec5SDimitry Andric on_entry_flags); 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric m_session_is_active = true; 7060b57cec5SDimitry Andric 7070b57cec5SDimitry Andric StreamString run_string; 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric if (on_entry_flags & Locker::InitGlobals) { 7100b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 7110b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID()); 7120b57cec5SDimitry Andric run_string.Printf( 7130b57cec5SDimitry Andric "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 7140b57cec5SDimitry Andric m_debugger.GetID()); 7150b57cec5SDimitry Andric run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); 7160b57cec5SDimitry Andric run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); 7170b57cec5SDimitry Andric run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); 7180b57cec5SDimitry Andric run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 7190b57cec5SDimitry Andric run_string.PutCString("')"); 7200b57cec5SDimitry Andric } else { 7210b57cec5SDimitry Andric // If we aren't initing the globals, we should still always set the 7220b57cec5SDimitry Andric // debugger (since that is always unique.) 7230b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 7240b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID()); 7250b57cec5SDimitry Andric run_string.Printf( 7260b57cec5SDimitry Andric "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 7270b57cec5SDimitry Andric m_debugger.GetID()); 7280b57cec5SDimitry Andric run_string.PutCString("')"); 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric 7310b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData()); 7320b57cec5SDimitry Andric run_string.Clear(); 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 7350b57cec5SDimitry Andric if (sys_module_dict.IsValid()) { 7360b57cec5SDimitry Andric File in_file(in, false); 7370b57cec5SDimitry Andric File out_file(out, false); 7380b57cec5SDimitry Andric File err_file(err, false); 7390b57cec5SDimitry Andric 7400b57cec5SDimitry Andric lldb::StreamFileSP in_sp; 7410b57cec5SDimitry Andric lldb::StreamFileSP out_sp; 7420b57cec5SDimitry Andric lldb::StreamFileSP err_sp; 7430b57cec5SDimitry Andric if (!in_file.IsValid() || !out_file.IsValid() || !err_file.IsValid()) 7440b57cec5SDimitry Andric m_debugger.AdoptTopIOHandlerFilesIfInvalid(in_sp, out_sp, err_sp); 7450b57cec5SDimitry Andric 7460b57cec5SDimitry Andric if (on_entry_flags & Locker::NoSTDIN) { 7470b57cec5SDimitry Andric m_saved_stdin.Reset(); 7480b57cec5SDimitry Andric } else { 7490b57cec5SDimitry Andric if (!SetStdHandle(in_file, "stdin", m_saved_stdin, "r")) { 7500b57cec5SDimitry Andric if (in_sp) 7510b57cec5SDimitry Andric SetStdHandle(in_sp->GetFile(), "stdin", m_saved_stdin, "r"); 7520b57cec5SDimitry Andric } 7530b57cec5SDimitry Andric } 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric if (!SetStdHandle(out_file, "stdout", m_saved_stdout, "w")) { 7560b57cec5SDimitry Andric if (out_sp) 7570b57cec5SDimitry Andric SetStdHandle(out_sp->GetFile(), "stdout", m_saved_stdout, "w"); 7580b57cec5SDimitry Andric } 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric if (!SetStdHandle(err_file, "stderr", m_saved_stderr, "w")) { 7610b57cec5SDimitry Andric if (err_sp) 7620b57cec5SDimitry Andric SetStdHandle(err_sp->GetFile(), "stderr", m_saved_stderr, "w"); 7630b57cec5SDimitry Andric } 7640b57cec5SDimitry Andric } 7650b57cec5SDimitry Andric 7660b57cec5SDimitry Andric if (PyErr_Occurred()) 7670b57cec5SDimitry Andric PyErr_Clear(); 7680b57cec5SDimitry Andric 7690b57cec5SDimitry Andric return true; 7700b57cec5SDimitry Andric } 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric PythonObject &ScriptInterpreterPythonImpl::GetMainModule() { 7730b57cec5SDimitry Andric if (!m_main_module.IsValid()) 7740b57cec5SDimitry Andric m_main_module.Reset(PyRefType::Borrowed, PyImport_AddModule("__main__")); 7750b57cec5SDimitry Andric return m_main_module; 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { 7790b57cec5SDimitry Andric if (m_session_dict.IsValid()) 7800b57cec5SDimitry Andric return m_session_dict; 7810b57cec5SDimitry Andric 7820b57cec5SDimitry Andric PythonObject &main_module = GetMainModule(); 7830b57cec5SDimitry Andric if (!main_module.IsValid()) 7840b57cec5SDimitry Andric return m_session_dict; 7850b57cec5SDimitry Andric 7860b57cec5SDimitry Andric PythonDictionary main_dict(PyRefType::Borrowed, 7870b57cec5SDimitry Andric PyModule_GetDict(main_module.get())); 7880b57cec5SDimitry Andric if (!main_dict.IsValid()) 7890b57cec5SDimitry Andric return m_session_dict; 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric PythonObject item = main_dict.GetItemForKey(PythonString(m_dictionary_name)); 7920b57cec5SDimitry Andric m_session_dict.Reset(PyRefType::Borrowed, item.get()); 7930b57cec5SDimitry Andric return m_session_dict; 7940b57cec5SDimitry Andric } 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { 7970b57cec5SDimitry Andric if (m_sys_module_dict.IsValid()) 7980b57cec5SDimitry Andric return m_sys_module_dict; 7990b57cec5SDimitry Andric 8000b57cec5SDimitry Andric PythonObject sys_module(PyRefType::Borrowed, PyImport_AddModule("sys")); 8010b57cec5SDimitry Andric if (sys_module.IsValid()) 8020b57cec5SDimitry Andric m_sys_module_dict.Reset(PyRefType::Borrowed, 8030b57cec5SDimitry Andric PyModule_GetDict(sys_module.get())); 8040b57cec5SDimitry Andric return m_sys_module_dict; 8050b57cec5SDimitry Andric } 8060b57cec5SDimitry Andric 8070b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted, 8080b57cec5SDimitry Andric uint32_t &functions_counter, 8090b57cec5SDimitry Andric const void *name_token = nullptr) { 8100b57cec5SDimitry Andric StreamString sstr; 8110b57cec5SDimitry Andric 8120b57cec5SDimitry Andric if (!base_name_wanted) 8130b57cec5SDimitry Andric return std::string(); 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric if (!name_token) 8160b57cec5SDimitry Andric sstr.Printf("%s_%d", base_name_wanted, functions_counter++); 8170b57cec5SDimitry Andric else 8180b57cec5SDimitry Andric sstr.Printf("%s_%p", base_name_wanted, name_token); 8190b57cec5SDimitry Andric 8200b57cec5SDimitry Andric return sstr.GetString(); 8210b57cec5SDimitry Andric } 8220b57cec5SDimitry Andric 8230b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { 8240b57cec5SDimitry Andric if (m_run_one_line_function.IsValid()) 8250b57cec5SDimitry Andric return true; 8260b57cec5SDimitry Andric 8270b57cec5SDimitry Andric PythonObject module(PyRefType::Borrowed, 8280b57cec5SDimitry Andric PyImport_AddModule("lldb.embedded_interpreter")); 8290b57cec5SDimitry Andric if (!module.IsValid()) 8300b57cec5SDimitry Andric return false; 8310b57cec5SDimitry Andric 8320b57cec5SDimitry Andric PythonDictionary module_dict(PyRefType::Borrowed, 8330b57cec5SDimitry Andric PyModule_GetDict(module.get())); 8340b57cec5SDimitry Andric if (!module_dict.IsValid()) 8350b57cec5SDimitry Andric return false; 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric m_run_one_line_function = 8380b57cec5SDimitry Andric module_dict.GetItemForKey(PythonString("run_one_line")); 8390b57cec5SDimitry Andric m_run_one_line_str_global = 8400b57cec5SDimitry Andric module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 8410b57cec5SDimitry Andric return m_run_one_line_function.IsValid(); 8420b57cec5SDimitry Andric } 8430b57cec5SDimitry Andric 8440b57cec5SDimitry Andric static void ReadThreadBytesReceived(void *baton, const void *src, 8450b57cec5SDimitry Andric size_t src_len) { 8460b57cec5SDimitry Andric if (src && src_len) { 8470b57cec5SDimitry Andric Stream *strm = (Stream *)baton; 8480b57cec5SDimitry Andric strm->Write(src, src_len); 8490b57cec5SDimitry Andric strm->Flush(); 8500b57cec5SDimitry Andric } 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine( 8540b57cec5SDimitry Andric llvm::StringRef command, CommandReturnObject *result, 8550b57cec5SDimitry Andric const ExecuteScriptOptions &options) { 8560b57cec5SDimitry Andric std::string command_str = command.str(); 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric if (!m_valid_session) 8590b57cec5SDimitry Andric return false; 8600b57cec5SDimitry Andric 8610b57cec5SDimitry Andric if (!command.empty()) { 8620b57cec5SDimitry Andric // We want to call run_one_line, passing in the dictionary and the command 8630b57cec5SDimitry Andric // string. We cannot do this through PyRun_SimpleString here because the 8640b57cec5SDimitry Andric // command string may contain escaped characters, and putting it inside 8650b57cec5SDimitry Andric // another string to pass to PyRun_SimpleString messes up the escaping. So 8660b57cec5SDimitry Andric // we use the following more complicated method to pass the command string 8670b57cec5SDimitry Andric // directly down to Python. 8680b57cec5SDimitry Andric Debugger &debugger = m_debugger; 8690b57cec5SDimitry Andric 8700b57cec5SDimitry Andric StreamFileSP input_file_sp; 8710b57cec5SDimitry Andric StreamFileSP output_file_sp; 8720b57cec5SDimitry Andric StreamFileSP error_file_sp; 8730b57cec5SDimitry Andric Communication output_comm( 8740b57cec5SDimitry Andric "lldb.ScriptInterpreterPythonImpl.ExecuteOneLine.comm"); 8750b57cec5SDimitry Andric bool join_read_thread = false; 8760b57cec5SDimitry Andric if (options.GetEnableIO()) { 8770b57cec5SDimitry Andric if (result) { 8780b57cec5SDimitry Andric input_file_sp = debugger.GetInputFile(); 8790b57cec5SDimitry Andric // Set output to a temporary file so we can forward the results on to 8800b57cec5SDimitry Andric // the result object 8810b57cec5SDimitry Andric 8820b57cec5SDimitry Andric Pipe pipe; 8830b57cec5SDimitry Andric Status pipe_result = pipe.CreateNew(false); 8840b57cec5SDimitry Andric if (pipe_result.Success()) { 8850b57cec5SDimitry Andric #if defined(_WIN32) 8860b57cec5SDimitry Andric lldb::file_t read_file = pipe.GetReadNativeHandle(); 8870b57cec5SDimitry Andric pipe.ReleaseReadFileDescriptor(); 8880b57cec5SDimitry Andric std::unique_ptr<ConnectionGenericFile> conn_up( 8890b57cec5SDimitry Andric new ConnectionGenericFile(read_file, true)); 8900b57cec5SDimitry Andric #else 8910b57cec5SDimitry Andric std::unique_ptr<ConnectionFileDescriptor> conn_up( 8920b57cec5SDimitry Andric new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(), 8930b57cec5SDimitry Andric true)); 8940b57cec5SDimitry Andric #endif 8950b57cec5SDimitry Andric if (conn_up->IsConnected()) { 8960b57cec5SDimitry Andric output_comm.SetConnection(conn_up.release()); 8970b57cec5SDimitry Andric output_comm.SetReadThreadBytesReceivedCallback( 8980b57cec5SDimitry Andric ReadThreadBytesReceived, &result->GetOutputStream()); 8990b57cec5SDimitry Andric output_comm.StartReadThread(); 9000b57cec5SDimitry Andric join_read_thread = true; 9010b57cec5SDimitry Andric FILE *outfile_handle = 9020b57cec5SDimitry Andric fdopen(pipe.ReleaseWriteFileDescriptor(), "w"); 9030b57cec5SDimitry Andric output_file_sp = std::make_shared<StreamFile>(outfile_handle, true); 9040b57cec5SDimitry Andric error_file_sp = output_file_sp; 9050b57cec5SDimitry Andric if (outfile_handle) 9060b57cec5SDimitry Andric ::setbuf(outfile_handle, nullptr); 9070b57cec5SDimitry Andric 9080b57cec5SDimitry Andric result->SetImmediateOutputFile( 9090b57cec5SDimitry Andric debugger.GetOutputFile()->GetFile().GetStream()); 9100b57cec5SDimitry Andric result->SetImmediateErrorFile( 9110b57cec5SDimitry Andric debugger.GetErrorFile()->GetFile().GetStream()); 9120b57cec5SDimitry Andric } 9130b57cec5SDimitry Andric } 9140b57cec5SDimitry Andric } 9150b57cec5SDimitry Andric if (!input_file_sp || !output_file_sp || !error_file_sp) 9160b57cec5SDimitry Andric debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, 9170b57cec5SDimitry Andric error_file_sp); 9180b57cec5SDimitry Andric } else { 9190b57cec5SDimitry Andric input_file_sp = std::make_shared<StreamFile>(); 9200b57cec5SDimitry Andric FileSystem::Instance().Open(input_file_sp->GetFile(), 9210b57cec5SDimitry Andric FileSpec(FileSystem::DEV_NULL), 9220b57cec5SDimitry Andric File::eOpenOptionRead); 9230b57cec5SDimitry Andric 9240b57cec5SDimitry Andric output_file_sp = std::make_shared<StreamFile>(); 9250b57cec5SDimitry Andric FileSystem::Instance().Open(output_file_sp->GetFile(), 9260b57cec5SDimitry Andric FileSpec(FileSystem::DEV_NULL), 9270b57cec5SDimitry Andric File::eOpenOptionWrite); 9280b57cec5SDimitry Andric 9290b57cec5SDimitry Andric error_file_sp = output_file_sp; 9300b57cec5SDimitry Andric } 9310b57cec5SDimitry Andric 9320b57cec5SDimitry Andric FILE *in_file = input_file_sp->GetFile().GetStream(); 9330b57cec5SDimitry Andric FILE *out_file = output_file_sp->GetFile().GetStream(); 9340b57cec5SDimitry Andric FILE *err_file = error_file_sp->GetFile().GetStream(); 9350b57cec5SDimitry Andric bool success = false; 9360b57cec5SDimitry Andric { 9370b57cec5SDimitry Andric // WARNING! It's imperative that this RAII scope be as tight as 9380b57cec5SDimitry Andric // possible. In particular, the scope must end *before* we try to join 9390b57cec5SDimitry Andric // the read thread. The reason for this is that a pre-requisite for 9400b57cec5SDimitry Andric // joining the read thread is that we close the write handle (to break 9410b57cec5SDimitry Andric // the pipe and cause it to wake up and exit). But acquiring the GIL as 9420b57cec5SDimitry Andric // below will redirect Python's stdio to use this same handle. If we 9430b57cec5SDimitry Andric // close the handle while Python is still using it, bad things will 9440b57cec5SDimitry Andric // happen. 9450b57cec5SDimitry Andric Locker locker( 9460b57cec5SDimitry Andric this, 9470b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | 9480b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 9490b57cec5SDimitry Andric ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), 9500b57cec5SDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession, in_file, out_file, 9510b57cec5SDimitry Andric err_file); 9520b57cec5SDimitry Andric 9530b57cec5SDimitry Andric // Find the correct script interpreter dictionary in the main module. 9540b57cec5SDimitry Andric PythonDictionary &session_dict = GetSessionDictionary(); 9550b57cec5SDimitry Andric if (session_dict.IsValid()) { 9560b57cec5SDimitry Andric if (GetEmbeddedInterpreterModuleObjects()) { 9570b57cec5SDimitry Andric if (PyCallable_Check(m_run_one_line_function.get())) { 9580b57cec5SDimitry Andric PythonObject pargs( 9590b57cec5SDimitry Andric PyRefType::Owned, 9600b57cec5SDimitry Andric Py_BuildValue("(Os)", session_dict.get(), command_str.c_str())); 9610b57cec5SDimitry Andric if (pargs.IsValid()) { 9620b57cec5SDimitry Andric PythonObject return_value( 9630b57cec5SDimitry Andric PyRefType::Owned, 9640b57cec5SDimitry Andric PyObject_CallObject(m_run_one_line_function.get(), 9650b57cec5SDimitry Andric pargs.get())); 9660b57cec5SDimitry Andric if (return_value.IsValid()) 9670b57cec5SDimitry Andric success = true; 9680b57cec5SDimitry Andric else if (options.GetMaskoutErrors() && PyErr_Occurred()) { 9690b57cec5SDimitry Andric PyErr_Print(); 9700b57cec5SDimitry Andric PyErr_Clear(); 9710b57cec5SDimitry Andric } 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric } 9740b57cec5SDimitry Andric } 9750b57cec5SDimitry Andric } 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric // Flush our output and error file handles 9780b57cec5SDimitry Andric ::fflush(out_file); 9790b57cec5SDimitry Andric if (out_file != err_file) 9800b57cec5SDimitry Andric ::fflush(err_file); 9810b57cec5SDimitry Andric } 9820b57cec5SDimitry Andric 9830b57cec5SDimitry Andric if (join_read_thread) { 9840b57cec5SDimitry Andric // Close the write end of the pipe since we are done with our one line 9850b57cec5SDimitry Andric // script. This should cause the read thread that output_comm is using to 9860b57cec5SDimitry Andric // exit 9870b57cec5SDimitry Andric output_file_sp->GetFile().Close(); 9880b57cec5SDimitry Andric // The close above should cause this thread to exit when it gets to the 9890b57cec5SDimitry Andric // end of file, so let it get all its data 9900b57cec5SDimitry Andric output_comm.JoinReadThread(); 9910b57cec5SDimitry Andric // Now we can close the read end of the pipe 9920b57cec5SDimitry Andric output_comm.Disconnect(); 9930b57cec5SDimitry Andric } 9940b57cec5SDimitry Andric 9950b57cec5SDimitry Andric if (success) 9960b57cec5SDimitry Andric return true; 9970b57cec5SDimitry Andric 9980b57cec5SDimitry Andric // The one-liner failed. Append the error message. 9990b57cec5SDimitry Andric if (result) { 10000b57cec5SDimitry Andric result->AppendErrorWithFormat( 10010b57cec5SDimitry Andric "python failed attempting to evaluate '%s'\n", command_str.c_str()); 10020b57cec5SDimitry Andric } 10030b57cec5SDimitry Andric return false; 10040b57cec5SDimitry Andric } 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric if (result) 10070b57cec5SDimitry Andric result->AppendError("empty command passed to python\n"); 10080b57cec5SDimitry Andric return false; 10090b57cec5SDimitry Andric } 10100b57cec5SDimitry Andric 10110b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { 10120b57cec5SDimitry Andric static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 10130b57cec5SDimitry Andric Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 10140b57cec5SDimitry Andric 10150b57cec5SDimitry Andric Debugger &debugger = m_debugger; 10160b57cec5SDimitry Andric 10170b57cec5SDimitry Andric // At the moment, the only time the debugger does not have an input file 10180b57cec5SDimitry Andric // handle is when this is called directly from Python, in which case it is 10190b57cec5SDimitry Andric // both dangerous and unnecessary (not to mention confusing) to try to embed 10200b57cec5SDimitry Andric // a running interpreter loop inside the already running Python interpreter 10210b57cec5SDimitry Andric // loop, so we won't do it. 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric if (!debugger.GetInputFile()->GetFile().IsValid()) 10240b57cec5SDimitry Andric return; 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this)); 10270b57cec5SDimitry Andric if (io_handler_sp) { 10280b57cec5SDimitry Andric debugger.PushIOHandler(io_handler_sp); 10290b57cec5SDimitry Andric } 10300b57cec5SDimitry Andric } 10310b57cec5SDimitry Andric 10320b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() { 10330b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric if (IsExecutingPython()) { 10360b57cec5SDimitry Andric PyThreadState *state = PyThreadState_GET(); 10370b57cec5SDimitry Andric if (!state) 10380b57cec5SDimitry Andric state = GetThreadState(); 10390b57cec5SDimitry Andric if (state) { 10400b57cec5SDimitry Andric long tid = state->thread_id; 10410b57cec5SDimitry Andric PyThreadState_Swap(state); 10420b57cec5SDimitry Andric int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 10430b57cec5SDimitry Andric if (log) 10440b57cec5SDimitry Andric log->Printf("ScriptInterpreterPythonImpl::Interrupt() sending " 10450b57cec5SDimitry Andric "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", 10460b57cec5SDimitry Andric tid, num_threads); 10470b57cec5SDimitry Andric return true; 10480b57cec5SDimitry Andric } 10490b57cec5SDimitry Andric } 10500b57cec5SDimitry Andric if (log) 10510b57cec5SDimitry Andric log->Printf( 10520b57cec5SDimitry Andric "ScriptInterpreterPythonImpl::Interrupt() python code not running, " 10530b57cec5SDimitry Andric "can't interrupt"); 10540b57cec5SDimitry Andric return false; 10550b57cec5SDimitry Andric } 10560b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( 10570b57cec5SDimitry Andric llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, 10580b57cec5SDimitry Andric void *ret_value, const ExecuteScriptOptions &options) { 10590b57cec5SDimitry Andric 10600b57cec5SDimitry Andric Locker locker(this, 10610b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | 10620b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 10630b57cec5SDimitry Andric Locker::NoSTDIN, 10640b57cec5SDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession); 10650b57cec5SDimitry Andric 10660b57cec5SDimitry Andric PythonObject py_return; 10670b57cec5SDimitry Andric PythonObject &main_module = GetMainModule(); 10680b57cec5SDimitry Andric PythonDictionary globals(PyRefType::Borrowed, 10690b57cec5SDimitry Andric PyModule_GetDict(main_module.get())); 10700b57cec5SDimitry Andric PythonObject py_error; 10710b57cec5SDimitry Andric bool ret_success = false; 10720b57cec5SDimitry Andric int success; 10730b57cec5SDimitry Andric 10740b57cec5SDimitry Andric PythonDictionary locals = GetSessionDictionary(); 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric if (!locals.IsValid()) { 10770b57cec5SDimitry Andric locals.Reset( 10780b57cec5SDimitry Andric PyRefType::Owned, 10790b57cec5SDimitry Andric PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str())); 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric if (!locals.IsValid()) 10830b57cec5SDimitry Andric locals = globals; 10840b57cec5SDimitry Andric 10850b57cec5SDimitry Andric py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 10860b57cec5SDimitry Andric if (py_error.IsValid()) 10870b57cec5SDimitry Andric PyErr_Clear(); 10880b57cec5SDimitry Andric 10890b57cec5SDimitry Andric std::string as_string = in_string.str(); 10900b57cec5SDimitry Andric { // scope for PythonInputReaderManager 10910b57cec5SDimitry Andric // PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL); 10920b57cec5SDimitry Andric py_return.Reset(PyRefType::Owned, 10930b57cec5SDimitry Andric PyRun_String(as_string.c_str(), Py_eval_input, 10940b57cec5SDimitry Andric globals.get(), locals.get())); 10950b57cec5SDimitry Andric if (!py_return.IsValid()) { 10960b57cec5SDimitry Andric py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 10970b57cec5SDimitry Andric if (py_error.IsValid()) 10980b57cec5SDimitry Andric PyErr_Clear(); 10990b57cec5SDimitry Andric 11000b57cec5SDimitry Andric py_return.Reset(PyRefType::Owned, 11010b57cec5SDimitry Andric PyRun_String(as_string.c_str(), Py_single_input, 11020b57cec5SDimitry Andric globals.get(), locals.get())); 11030b57cec5SDimitry Andric } 11040b57cec5SDimitry Andric } 11050b57cec5SDimitry Andric 11060b57cec5SDimitry Andric if (py_return.IsValid()) { 11070b57cec5SDimitry Andric switch (return_type) { 11080b57cec5SDimitry Andric case eScriptReturnTypeCharPtr: // "char *" 11090b57cec5SDimitry Andric { 11100b57cec5SDimitry Andric const char format[3] = "s#"; 11110b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (char **)ret_value); 11120b57cec5SDimitry Andric break; 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == 11150b57cec5SDimitry Andric // Py_None 11160b57cec5SDimitry Andric { 11170b57cec5SDimitry Andric const char format[3] = "z"; 11180b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (char **)ret_value); 11190b57cec5SDimitry Andric break; 11200b57cec5SDimitry Andric } 11210b57cec5SDimitry Andric case eScriptReturnTypeBool: { 11220b57cec5SDimitry Andric const char format[2] = "b"; 11230b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (bool *)ret_value); 11240b57cec5SDimitry Andric break; 11250b57cec5SDimitry Andric } 11260b57cec5SDimitry Andric case eScriptReturnTypeShortInt: { 11270b57cec5SDimitry Andric const char format[2] = "h"; 11280b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (short *)ret_value); 11290b57cec5SDimitry Andric break; 11300b57cec5SDimitry Andric } 11310b57cec5SDimitry Andric case eScriptReturnTypeShortIntUnsigned: { 11320b57cec5SDimitry Andric const char format[2] = "H"; 11330b57cec5SDimitry Andric success = 11340b57cec5SDimitry Andric PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value); 11350b57cec5SDimitry Andric break; 11360b57cec5SDimitry Andric } 11370b57cec5SDimitry Andric case eScriptReturnTypeInt: { 11380b57cec5SDimitry Andric const char format[2] = "i"; 11390b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (int *)ret_value); 11400b57cec5SDimitry Andric break; 11410b57cec5SDimitry Andric } 11420b57cec5SDimitry Andric case eScriptReturnTypeIntUnsigned: { 11430b57cec5SDimitry Andric const char format[2] = "I"; 11440b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value); 11450b57cec5SDimitry Andric break; 11460b57cec5SDimitry Andric } 11470b57cec5SDimitry Andric case eScriptReturnTypeLongInt: { 11480b57cec5SDimitry Andric const char format[2] = "l"; 11490b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (long *)ret_value); 11500b57cec5SDimitry Andric break; 11510b57cec5SDimitry Andric } 11520b57cec5SDimitry Andric case eScriptReturnTypeLongIntUnsigned: { 11530b57cec5SDimitry Andric const char format[2] = "k"; 11540b57cec5SDimitry Andric success = 11550b57cec5SDimitry Andric PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value); 11560b57cec5SDimitry Andric break; 11570b57cec5SDimitry Andric } 11580b57cec5SDimitry Andric case eScriptReturnTypeLongLong: { 11590b57cec5SDimitry Andric const char format[2] = "L"; 11600b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (long long *)ret_value); 11610b57cec5SDimitry Andric break; 11620b57cec5SDimitry Andric } 11630b57cec5SDimitry Andric case eScriptReturnTypeLongLongUnsigned: { 11640b57cec5SDimitry Andric const char format[2] = "K"; 11650b57cec5SDimitry Andric success = 11660b57cec5SDimitry Andric PyArg_Parse(py_return.get(), format, (unsigned long long *)ret_value); 11670b57cec5SDimitry Andric break; 11680b57cec5SDimitry Andric } 11690b57cec5SDimitry Andric case eScriptReturnTypeFloat: { 11700b57cec5SDimitry Andric const char format[2] = "f"; 11710b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (float *)ret_value); 11720b57cec5SDimitry Andric break; 11730b57cec5SDimitry Andric } 11740b57cec5SDimitry Andric case eScriptReturnTypeDouble: { 11750b57cec5SDimitry Andric const char format[2] = "d"; 11760b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (double *)ret_value); 11770b57cec5SDimitry Andric break; 11780b57cec5SDimitry Andric } 11790b57cec5SDimitry Andric case eScriptReturnTypeChar: { 11800b57cec5SDimitry Andric const char format[2] = "c"; 11810b57cec5SDimitry Andric success = PyArg_Parse(py_return.get(), format, (char *)ret_value); 11820b57cec5SDimitry Andric break; 11830b57cec5SDimitry Andric } 11840b57cec5SDimitry Andric case eScriptReturnTypeOpaqueObject: { 11850b57cec5SDimitry Andric success = true; 11860b57cec5SDimitry Andric PyObject *saved_value = py_return.get(); 11870b57cec5SDimitry Andric Py_XINCREF(saved_value); 11880b57cec5SDimitry Andric *((PyObject **)ret_value) = saved_value; 11890b57cec5SDimitry Andric break; 11900b57cec5SDimitry Andric } 11910b57cec5SDimitry Andric } 11920b57cec5SDimitry Andric 11930b57cec5SDimitry Andric ret_success = success; 11940b57cec5SDimitry Andric } 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 11970b57cec5SDimitry Andric if (py_error.IsValid()) { 11980b57cec5SDimitry Andric ret_success = false; 11990b57cec5SDimitry Andric if (options.GetMaskoutErrors()) { 12000b57cec5SDimitry Andric if (PyErr_GivenExceptionMatches(py_error.get(), PyExc_SyntaxError)) 12010b57cec5SDimitry Andric PyErr_Print(); 12020b57cec5SDimitry Andric PyErr_Clear(); 12030b57cec5SDimitry Andric } 12040b57cec5SDimitry Andric } 12050b57cec5SDimitry Andric 12060b57cec5SDimitry Andric return ret_success; 12070b57cec5SDimitry Andric } 12080b57cec5SDimitry Andric 12090b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( 12100b57cec5SDimitry Andric const char *in_string, const ExecuteScriptOptions &options) { 12110b57cec5SDimitry Andric Status error; 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric Locker locker(this, 12140b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | 12150b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 12160b57cec5SDimitry Andric Locker::NoSTDIN, 12170b57cec5SDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession); 12180b57cec5SDimitry Andric 12190b57cec5SDimitry Andric PythonObject return_value; 12200b57cec5SDimitry Andric PythonObject &main_module = GetMainModule(); 12210b57cec5SDimitry Andric PythonDictionary globals(PyRefType::Borrowed, 12220b57cec5SDimitry Andric PyModule_GetDict(main_module.get())); 12230b57cec5SDimitry Andric PythonObject py_error; 12240b57cec5SDimitry Andric 12250b57cec5SDimitry Andric PythonDictionary locals = GetSessionDictionary(); 12260b57cec5SDimitry Andric 12270b57cec5SDimitry Andric if (!locals.IsValid()) 12280b57cec5SDimitry Andric locals.Reset( 12290b57cec5SDimitry Andric PyRefType::Owned, 12300b57cec5SDimitry Andric PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str())); 12310b57cec5SDimitry Andric 12320b57cec5SDimitry Andric if (!locals.IsValid()) 12330b57cec5SDimitry Andric locals = globals; 12340b57cec5SDimitry Andric 12350b57cec5SDimitry Andric py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 12360b57cec5SDimitry Andric if (py_error.IsValid()) 12370b57cec5SDimitry Andric PyErr_Clear(); 12380b57cec5SDimitry Andric 12390b57cec5SDimitry Andric if (in_string != nullptr) { 12400b57cec5SDimitry Andric PythonObject code_object; 12410b57cec5SDimitry Andric code_object.Reset(PyRefType::Owned, 12420b57cec5SDimitry Andric Py_CompileString(in_string, "temp.py", Py_file_input)); 12430b57cec5SDimitry Andric 12440b57cec5SDimitry Andric if (code_object.IsValid()) { 12450b57cec5SDimitry Andric // In Python 2.x, PyEval_EvalCode takes a PyCodeObject, but in Python 3.x, it 12460b57cec5SDimitry Andric // takes a PyObject. They are convertible (hence the function 12470b57cec5SDimitry Andric // PyCode_Check(PyObject*), so we have to do the cast for Python 2.x 12480b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3 12490b57cec5SDimitry Andric PyObject *py_code_obj = code_object.get(); 12500b57cec5SDimitry Andric #else 12510b57cec5SDimitry Andric PyCodeObject *py_code_obj = 12520b57cec5SDimitry Andric reinterpret_cast<PyCodeObject *>(code_object.get()); 12530b57cec5SDimitry Andric #endif 12540b57cec5SDimitry Andric return_value.Reset( 12550b57cec5SDimitry Andric PyRefType::Owned, 12560b57cec5SDimitry Andric PyEval_EvalCode(py_code_obj, globals.get(), locals.get())); 12570b57cec5SDimitry Andric } 12580b57cec5SDimitry Andric } 12590b57cec5SDimitry Andric 12600b57cec5SDimitry Andric PythonExceptionState exception_state(!options.GetMaskoutErrors()); 12610b57cec5SDimitry Andric if (exception_state.IsError()) 12620b57cec5SDimitry Andric error.SetErrorString(exception_state.Format().c_str()); 12630b57cec5SDimitry Andric 12640b57cec5SDimitry Andric return error; 12650b57cec5SDimitry Andric } 12660b57cec5SDimitry Andric 12670b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( 12680b57cec5SDimitry Andric std::vector<BreakpointOptions *> &bp_options_vec, 12690b57cec5SDimitry Andric CommandReturnObject &result) { 12700b57cec5SDimitry Andric m_active_io_handler = eIOHandlerBreakpoint; 12710b57cec5SDimitry Andric m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 12720b57cec5SDimitry Andric " ", *this, true, &bp_options_vec); 12730b57cec5SDimitry Andric } 12740b57cec5SDimitry Andric 12750b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( 12760b57cec5SDimitry Andric WatchpointOptions *wp_options, CommandReturnObject &result) { 12770b57cec5SDimitry Andric m_active_io_handler = eIOHandlerWatchpoint; 12780b57cec5SDimitry Andric m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 12790b57cec5SDimitry Andric " ", *this, true, wp_options); 12800b57cec5SDimitry Andric } 12810b57cec5SDimitry Andric 12820b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( 12830b57cec5SDimitry Andric BreakpointOptions *bp_options, const char *function_name) { 12840b57cec5SDimitry Andric // For now just cons up a oneliner that calls the provided function. 12850b57cec5SDimitry Andric std::string oneliner("return "); 12860b57cec5SDimitry Andric oneliner += function_name; 12870b57cec5SDimitry Andric oneliner += "(frame, bp_loc, internal_dict)"; 12880b57cec5SDimitry Andric m_debugger.GetScriptInterpreter()->SetBreakpointCommandCallback( 12890b57cec5SDimitry Andric bp_options, oneliner.c_str()); 12900b57cec5SDimitry Andric } 12910b57cec5SDimitry Andric 12920b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 12930b57cec5SDimitry Andric BreakpointOptions *bp_options, 12940b57cec5SDimitry Andric std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { 12950b57cec5SDimitry Andric Status error; 12960b57cec5SDimitry Andric error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, 12970b57cec5SDimitry Andric cmd_data_up->script_source); 12980b57cec5SDimitry Andric if (error.Fail()) { 12990b57cec5SDimitry Andric return error; 13000b57cec5SDimitry Andric } 13010b57cec5SDimitry Andric auto baton_sp = 13020b57cec5SDimitry Andric std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); 13030b57cec5SDimitry Andric bp_options->SetCallback( 13040b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 13050b57cec5SDimitry Andric return error; 13060b57cec5SDimitry Andric } 13070b57cec5SDimitry Andric 13080b57cec5SDimitry Andric // Set a Python one-liner as the callback for the breakpoint. 13090b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 13100b57cec5SDimitry Andric BreakpointOptions *bp_options, const char *command_body_text) { 13110b57cec5SDimitry Andric auto data_up = llvm::make_unique<CommandDataPython>(); 13120b57cec5SDimitry Andric 13130b57cec5SDimitry Andric // Split the command_body_text into lines, and pass that to 13140b57cec5SDimitry Andric // GenerateBreakpointCommandCallbackData. That will wrap the body in an 13150b57cec5SDimitry Andric // auto-generated function, and return the function name in script_source. 13160b57cec5SDimitry Andric // That is what the callback will actually invoke. 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(command_body_text); 13190b57cec5SDimitry Andric Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, 13200b57cec5SDimitry Andric data_up->script_source); 13210b57cec5SDimitry Andric if (error.Success()) { 13220b57cec5SDimitry Andric auto baton_sp = 13230b57cec5SDimitry Andric std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 13240b57cec5SDimitry Andric bp_options->SetCallback( 13250b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 13260b57cec5SDimitry Andric return error; 13270b57cec5SDimitry Andric } else 13280b57cec5SDimitry Andric return error; 13290b57cec5SDimitry Andric } 13300b57cec5SDimitry Andric 13310b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint. 13320b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( 13330b57cec5SDimitry Andric WatchpointOptions *wp_options, const char *oneliner) { 13340b57cec5SDimitry Andric auto data_up = llvm::make_unique<WatchpointOptions::CommandData>(); 13350b57cec5SDimitry Andric 13360b57cec5SDimitry Andric // It's necessary to set both user_source and script_source to the oneliner. 13370b57cec5SDimitry Andric // The former is used to generate callback description (as in watchpoint 13380b57cec5SDimitry Andric // command list) while the latter is used for Python to interpret during the 13390b57cec5SDimitry Andric // actual callback. 13400b57cec5SDimitry Andric 13410b57cec5SDimitry Andric data_up->user_source.AppendString(oneliner); 13420b57cec5SDimitry Andric data_up->script_source.assign(oneliner); 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric if (GenerateWatchpointCommandCallbackData(data_up->user_source, 13450b57cec5SDimitry Andric data_up->script_source)) { 13460b57cec5SDimitry Andric auto baton_sp = 13470b57cec5SDimitry Andric std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 13480b57cec5SDimitry Andric wp_options->SetCallback( 13490b57cec5SDimitry Andric ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 13500b57cec5SDimitry Andric } 13510b57cec5SDimitry Andric 13520b57cec5SDimitry Andric return; 13530b57cec5SDimitry Andric } 13540b57cec5SDimitry Andric 13550b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( 13560b57cec5SDimitry Andric StringList &function_def) { 13570b57cec5SDimitry Andric // Convert StringList to one long, newline delimited, const char *. 13580b57cec5SDimitry Andric std::string function_def_string(function_def.CopyList()); 13590b57cec5SDimitry Andric 13600b57cec5SDimitry Andric Status error = ExecuteMultipleLines( 13610b57cec5SDimitry Andric function_def_string.c_str(), 13620b57cec5SDimitry Andric ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)); 13630b57cec5SDimitry Andric return error; 13640b57cec5SDimitry Andric } 13650b57cec5SDimitry Andric 13660b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, 13670b57cec5SDimitry Andric const StringList &input) { 13680b57cec5SDimitry Andric Status error; 13690b57cec5SDimitry Andric int num_lines = input.GetSize(); 13700b57cec5SDimitry Andric if (num_lines == 0) { 13710b57cec5SDimitry Andric error.SetErrorString("No input data."); 13720b57cec5SDimitry Andric return error; 13730b57cec5SDimitry Andric } 13740b57cec5SDimitry Andric 13750b57cec5SDimitry Andric if (!signature || *signature == 0) { 13760b57cec5SDimitry Andric error.SetErrorString("No output function name."); 13770b57cec5SDimitry Andric return error; 13780b57cec5SDimitry Andric } 13790b57cec5SDimitry Andric 13800b57cec5SDimitry Andric StreamString sstr; 13810b57cec5SDimitry Andric StringList auto_generated_function; 13820b57cec5SDimitry Andric auto_generated_function.AppendString(signature); 13830b57cec5SDimitry Andric auto_generated_function.AppendString( 13840b57cec5SDimitry Andric " global_dict = globals()"); // Grab the global dictionary 13850b57cec5SDimitry Andric auto_generated_function.AppendString( 13860b57cec5SDimitry Andric " new_keys = internal_dict.keys()"); // Make a list of keys in the 13870b57cec5SDimitry Andric // session dict 13880b57cec5SDimitry Andric auto_generated_function.AppendString( 13890b57cec5SDimitry Andric " old_keys = global_dict.keys()"); // Save list of keys in global dict 13900b57cec5SDimitry Andric auto_generated_function.AppendString( 13910b57cec5SDimitry Andric " global_dict.update (internal_dict)"); // Add the session dictionary 13920b57cec5SDimitry Andric // to the 13930b57cec5SDimitry Andric // global dictionary. 13940b57cec5SDimitry Andric 13950b57cec5SDimitry Andric // Wrap everything up inside the function, increasing the indentation. 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric auto_generated_function.AppendString(" if True:"); 13980b57cec5SDimitry Andric for (int i = 0; i < num_lines; ++i) { 13990b57cec5SDimitry Andric sstr.Clear(); 14000b57cec5SDimitry Andric sstr.Printf(" %s", input.GetStringAtIndex(i)); 14010b57cec5SDimitry Andric auto_generated_function.AppendString(sstr.GetData()); 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric auto_generated_function.AppendString( 14040b57cec5SDimitry Andric " for key in new_keys:"); // Iterate over all the keys from session 14050b57cec5SDimitry Andric // dict 14060b57cec5SDimitry Andric auto_generated_function.AppendString( 14070b57cec5SDimitry Andric " internal_dict[key] = global_dict[key]"); // Update session dict 14080b57cec5SDimitry Andric // values 14090b57cec5SDimitry Andric auto_generated_function.AppendString( 14100b57cec5SDimitry Andric " if key not in old_keys:"); // If key was not originally in 14110b57cec5SDimitry Andric // global dict 14120b57cec5SDimitry Andric auto_generated_function.AppendString( 14130b57cec5SDimitry Andric " del global_dict[key]"); // ...then remove key/value from 14140b57cec5SDimitry Andric // global dict 14150b57cec5SDimitry Andric 14160b57cec5SDimitry Andric // Verify that the results are valid Python. 14170b57cec5SDimitry Andric 14180b57cec5SDimitry Andric error = ExportFunctionDefinitionToInterpreter(auto_generated_function); 14190b57cec5SDimitry Andric 14200b57cec5SDimitry Andric return error; 14210b57cec5SDimitry Andric } 14220b57cec5SDimitry Andric 14230b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 14240b57cec5SDimitry Andric StringList &user_input, std::string &output, const void *name_token) { 14250b57cec5SDimitry Andric static uint32_t num_created_functions = 0; 14260b57cec5SDimitry Andric user_input.RemoveBlankLines(); 14270b57cec5SDimitry Andric StreamString sstr; 14280b57cec5SDimitry Andric 14290b57cec5SDimitry Andric // Check to see if we have any data; if not, just return. 14300b57cec5SDimitry Andric if (user_input.GetSize() == 0) 14310b57cec5SDimitry Andric return false; 14320b57cec5SDimitry Andric 14330b57cec5SDimitry Andric // Take what the user wrote, wrap it all up inside one big auto-generated 14340b57cec5SDimitry Andric // Python function, passing in the ValueObject as parameter to the function. 14350b57cec5SDimitry Andric 14360b57cec5SDimitry Andric std::string auto_generated_function_name( 14370b57cec5SDimitry Andric GenerateUniqueName("lldb_autogen_python_type_print_func", 14380b57cec5SDimitry Andric num_created_functions, name_token)); 14390b57cec5SDimitry Andric sstr.Printf("def %s (valobj, internal_dict):", 14400b57cec5SDimitry Andric auto_generated_function_name.c_str()); 14410b57cec5SDimitry Andric 14420b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success()) 14430b57cec5SDimitry Andric return false; 14440b57cec5SDimitry Andric 14450b57cec5SDimitry Andric // Store the name of the auto-generated function to be called. 14460b57cec5SDimitry Andric output.assign(auto_generated_function_name); 14470b57cec5SDimitry Andric return true; 14480b57cec5SDimitry Andric } 14490b57cec5SDimitry Andric 14500b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( 14510b57cec5SDimitry Andric StringList &user_input, std::string &output) { 14520b57cec5SDimitry Andric static uint32_t num_created_functions = 0; 14530b57cec5SDimitry Andric user_input.RemoveBlankLines(); 14540b57cec5SDimitry Andric StreamString sstr; 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric // Check to see if we have any data; if not, just return. 14570b57cec5SDimitry Andric if (user_input.GetSize() == 0) 14580b57cec5SDimitry Andric return false; 14590b57cec5SDimitry Andric 14600b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName( 14610b57cec5SDimitry Andric "lldb_autogen_python_cmd_alias_func", num_created_functions)); 14620b57cec5SDimitry Andric 14630b57cec5SDimitry Andric sstr.Printf("def %s (debugger, args, result, internal_dict):", 14640b57cec5SDimitry Andric auto_generated_function_name.c_str()); 14650b57cec5SDimitry Andric 14660b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success()) 14670b57cec5SDimitry Andric return false; 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric // Store the name of the auto-generated function to be called. 14700b57cec5SDimitry Andric output.assign(auto_generated_function_name); 14710b57cec5SDimitry Andric return true; 14720b57cec5SDimitry Andric } 14730b57cec5SDimitry Andric 14740b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 14750b57cec5SDimitry Andric StringList &user_input, std::string &output, const void *name_token) { 14760b57cec5SDimitry Andric static uint32_t num_created_classes = 0; 14770b57cec5SDimitry Andric user_input.RemoveBlankLines(); 14780b57cec5SDimitry Andric int num_lines = user_input.GetSize(); 14790b57cec5SDimitry Andric StreamString sstr; 14800b57cec5SDimitry Andric 14810b57cec5SDimitry Andric // Check to see if we have any data; if not, just return. 14820b57cec5SDimitry Andric if (user_input.GetSize() == 0) 14830b57cec5SDimitry Andric return false; 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // Wrap all user input into a Python class 14860b57cec5SDimitry Andric 14870b57cec5SDimitry Andric std::string auto_generated_class_name(GenerateUniqueName( 14880b57cec5SDimitry Andric "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); 14890b57cec5SDimitry Andric 14900b57cec5SDimitry Andric StringList auto_generated_class; 14910b57cec5SDimitry Andric 14920b57cec5SDimitry Andric // Create the function name & definition string. 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric sstr.Printf("class %s:", auto_generated_class_name.c_str()); 14950b57cec5SDimitry Andric auto_generated_class.AppendString(sstr.GetString()); 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric // Wrap everything up inside the class, increasing the indentation. we don't 14980b57cec5SDimitry Andric // need to play any fancy indentation tricks here because there is no 14990b57cec5SDimitry Andric // surrounding code whose indentation we need to honor 15000b57cec5SDimitry Andric for (int i = 0; i < num_lines; ++i) { 15010b57cec5SDimitry Andric sstr.Clear(); 15020b57cec5SDimitry Andric sstr.Printf(" %s", user_input.GetStringAtIndex(i)); 15030b57cec5SDimitry Andric auto_generated_class.AppendString(sstr.GetString()); 15040b57cec5SDimitry Andric } 15050b57cec5SDimitry Andric 15060b57cec5SDimitry Andric // Verify that the results are valid Python. (even though the method is 15070b57cec5SDimitry Andric // ExportFunctionDefinitionToInterpreter, a class will actually be exported) 15080b57cec5SDimitry Andric // (TODO: rename that method to ExportDefinitionToInterpreter) 15090b57cec5SDimitry Andric if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) 15100b57cec5SDimitry Andric return false; 15110b57cec5SDimitry Andric 15120b57cec5SDimitry Andric // Store the name of the auto-generated class 15130b57cec5SDimitry Andric 15140b57cec5SDimitry Andric output.assign(auto_generated_class_name); 15150b57cec5SDimitry Andric return true; 15160b57cec5SDimitry Andric } 15170b57cec5SDimitry Andric 15180b57cec5SDimitry Andric StructuredData::GenericSP 15190b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { 15200b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 15210b57cec5SDimitry Andric return StructuredData::GenericSP(); 15220b57cec5SDimitry Andric 15230b57cec5SDimitry Andric void *ret_val; 15240b57cec5SDimitry Andric 15250b57cec5SDimitry Andric { 15260b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 15270b57cec5SDimitry Andric Locker::FreeLock); 15280b57cec5SDimitry Andric ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name, 15290b57cec5SDimitry Andric m_dictionary_name.c_str()); 15300b57cec5SDimitry Andric } 15310b57cec5SDimitry Andric 15320b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 15330b57cec5SDimitry Andric } 15340b57cec5SDimitry Andric 15350b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 15360b57cec5SDimitry Andric const StructuredData::ObjectSP &os_plugin_object_sp, 15370b57cec5SDimitry Andric lldb::StackFrameSP frame_sp) { 15380b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric if (!os_plugin_object_sp) 15410b57cec5SDimitry Andric return ValueObjectListSP(); 15420b57cec5SDimitry Andric 15430b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15440b57cec5SDimitry Andric if (!generic) 15450b57cec5SDimitry Andric return nullptr; 15460b57cec5SDimitry Andric 15470b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 15480b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 15490b57cec5SDimitry Andric 15500b57cec5SDimitry Andric if (!implementor.IsAllocated()) 15510b57cec5SDimitry Andric return ValueObjectListSP(); 15520b57cec5SDimitry Andric 15530b57cec5SDimitry Andric PythonObject py_return(PyRefType::Owned, 15540b57cec5SDimitry Andric (PyObject *)LLDBSwigPython_GetRecognizedArguments( 15550b57cec5SDimitry Andric implementor.get(), frame_sp)); 15560b57cec5SDimitry Andric 15570b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 15580b57cec5SDimitry Andric if (PyErr_Occurred()) { 15590b57cec5SDimitry Andric PyErr_Print(); 15600b57cec5SDimitry Andric PyErr_Clear(); 15610b57cec5SDimitry Andric } 15620b57cec5SDimitry Andric if (py_return.get()) { 15630b57cec5SDimitry Andric PythonList result_list(PyRefType::Borrowed, py_return.get()); 15640b57cec5SDimitry Andric ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 15650b57cec5SDimitry Andric for (size_t i = 0; i < result_list.GetSize(); i++) { 15660b57cec5SDimitry Andric PyObject *item = result_list.GetItemAtIndex(i).get(); 15670b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr = 15680b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 15690b57cec5SDimitry Andric auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 15700b57cec5SDimitry Andric if (valobj_sp) 15710b57cec5SDimitry Andric result->Append(valobj_sp); 15720b57cec5SDimitry Andric } 15730b57cec5SDimitry Andric return result; 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric return ValueObjectListSP(); 15760b57cec5SDimitry Andric } 15770b57cec5SDimitry Andric 15780b57cec5SDimitry Andric StructuredData::GenericSP 15790b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 15800b57cec5SDimitry Andric const char *class_name, lldb::ProcessSP process_sp) { 15810b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 15820b57cec5SDimitry Andric return StructuredData::GenericSP(); 15830b57cec5SDimitry Andric 15840b57cec5SDimitry Andric if (!process_sp) 15850b57cec5SDimitry Andric return StructuredData::GenericSP(); 15860b57cec5SDimitry Andric 15870b57cec5SDimitry Andric void *ret_val; 15880b57cec5SDimitry Andric 15890b57cec5SDimitry Andric { 15900b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 15910b57cec5SDimitry Andric Locker::FreeLock); 15920b57cec5SDimitry Andric ret_val = LLDBSWIGPythonCreateOSPlugin( 15930b57cec5SDimitry Andric class_name, m_dictionary_name.c_str(), process_sp); 15940b57cec5SDimitry Andric } 15950b57cec5SDimitry Andric 15960b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 15970b57cec5SDimitry Andric } 15980b57cec5SDimitry Andric 15990b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 16000b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp) { 16010b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16020b57cec5SDimitry Andric 16030b57cec5SDimitry Andric static char callee_name[] = "get_register_info"; 16040b57cec5SDimitry Andric 16050b57cec5SDimitry Andric if (!os_plugin_object_sp) 16060b57cec5SDimitry Andric return StructuredData::DictionarySP(); 16070b57cec5SDimitry Andric 16080b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16090b57cec5SDimitry Andric if (!generic) 16100b57cec5SDimitry Andric return nullptr; 16110b57cec5SDimitry Andric 16120b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 16130b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric if (!implementor.IsAllocated()) 16160b57cec5SDimitry Andric return StructuredData::DictionarySP(); 16170b57cec5SDimitry Andric 16180b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 16190b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric if (PyErr_Occurred()) 16220b57cec5SDimitry Andric PyErr_Clear(); 16230b57cec5SDimitry Andric 16240b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 16250b57cec5SDimitry Andric return StructuredData::DictionarySP(); 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 16280b57cec5SDimitry Andric if (PyErr_Occurred()) 16290b57cec5SDimitry Andric PyErr_Clear(); 16300b57cec5SDimitry Andric 16310b57cec5SDimitry Andric return StructuredData::DictionarySP(); 16320b57cec5SDimitry Andric } 16330b57cec5SDimitry Andric 16340b57cec5SDimitry Andric if (PyErr_Occurred()) 16350b57cec5SDimitry Andric PyErr_Clear(); 16360b57cec5SDimitry Andric 16370b57cec5SDimitry Andric // right now we know this function exists and is callable.. 16380b57cec5SDimitry Andric PythonObject py_return( 16390b57cec5SDimitry Andric PyRefType::Owned, 16400b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16410b57cec5SDimitry Andric 16420b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 16430b57cec5SDimitry Andric if (PyErr_Occurred()) { 16440b57cec5SDimitry Andric PyErr_Print(); 16450b57cec5SDimitry Andric PyErr_Clear(); 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric if (py_return.get()) { 16480b57cec5SDimitry Andric PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 16490b57cec5SDimitry Andric return result_dict.CreateStructuredDictionary(); 16500b57cec5SDimitry Andric } 16510b57cec5SDimitry Andric return StructuredData::DictionarySP(); 16520b57cec5SDimitry Andric } 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 16550b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp) { 16560b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric static char callee_name[] = "get_thread_info"; 16590b57cec5SDimitry Andric 16600b57cec5SDimitry Andric if (!os_plugin_object_sp) 16610b57cec5SDimitry Andric return StructuredData::ArraySP(); 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16640b57cec5SDimitry Andric if (!generic) 16650b57cec5SDimitry Andric return nullptr; 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 16680b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric if (!implementor.IsAllocated()) 16710b57cec5SDimitry Andric return StructuredData::ArraySP(); 16720b57cec5SDimitry Andric 16730b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 16740b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric if (PyErr_Occurred()) 16770b57cec5SDimitry Andric PyErr_Clear(); 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 16800b57cec5SDimitry Andric return StructuredData::ArraySP(); 16810b57cec5SDimitry Andric 16820b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 16830b57cec5SDimitry Andric if (PyErr_Occurred()) 16840b57cec5SDimitry Andric PyErr_Clear(); 16850b57cec5SDimitry Andric 16860b57cec5SDimitry Andric return StructuredData::ArraySP(); 16870b57cec5SDimitry Andric } 16880b57cec5SDimitry Andric 16890b57cec5SDimitry Andric if (PyErr_Occurred()) 16900b57cec5SDimitry Andric PyErr_Clear(); 16910b57cec5SDimitry Andric 16920b57cec5SDimitry Andric // right now we know this function exists and is callable.. 16930b57cec5SDimitry Andric PythonObject py_return( 16940b57cec5SDimitry Andric PyRefType::Owned, 16950b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16960b57cec5SDimitry Andric 16970b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 16980b57cec5SDimitry Andric if (PyErr_Occurred()) { 16990b57cec5SDimitry Andric PyErr_Print(); 17000b57cec5SDimitry Andric PyErr_Clear(); 17010b57cec5SDimitry Andric } 17020b57cec5SDimitry Andric 17030b57cec5SDimitry Andric if (py_return.get()) { 17040b57cec5SDimitry Andric PythonList result_list(PyRefType::Borrowed, py_return.get()); 17050b57cec5SDimitry Andric return result_list.CreateStructuredArray(); 17060b57cec5SDimitry Andric } 17070b57cec5SDimitry Andric return StructuredData::ArraySP(); 17080b57cec5SDimitry Andric } 17090b57cec5SDimitry Andric 17100b57cec5SDimitry Andric // GetPythonValueFormatString provides a system independent type safe way to 17110b57cec5SDimitry Andric // convert a variable's type into a python value format. Python value formats 17120b57cec5SDimitry Andric // are defined in terms of builtin C types and could change from system to as 17130b57cec5SDimitry Andric // the underlying typedef for uint* types, size_t, off_t and other values 17140b57cec5SDimitry Andric // change. 17150b57cec5SDimitry Andric 17160b57cec5SDimitry Andric template <typename T> const char *GetPythonValueFormatString(T t); 17170b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(char *) { return "s"; } 17180b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(char) { return "b"; } 17190b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned char) { 17200b57cec5SDimitry Andric return "B"; 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(short) { return "h"; } 17230b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned short) { 17240b57cec5SDimitry Andric return "H"; 17250b57cec5SDimitry Andric } 17260b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(int) { return "i"; } 17270b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; } 17280b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(long) { return "l"; } 17290b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned long) { 17300b57cec5SDimitry Andric return "k"; 17310b57cec5SDimitry Andric } 17320b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(long long) { return "L"; } 17330b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned long long) { 17340b57cec5SDimitry Andric return "K"; 17350b57cec5SDimitry Andric } 17360b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(float t) { return "f"; } 17370b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(double t) { return "d"; } 17380b57cec5SDimitry Andric 17390b57cec5SDimitry Andric StructuredData::StringSP 17400b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 17410b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 17420b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 17430b57cec5SDimitry Andric 17440b57cec5SDimitry Andric static char callee_name[] = "get_register_data"; 17450b57cec5SDimitry Andric static char *param_format = 17460b57cec5SDimitry Andric const_cast<char *>(GetPythonValueFormatString(tid)); 17470b57cec5SDimitry Andric 17480b57cec5SDimitry Andric if (!os_plugin_object_sp) 17490b57cec5SDimitry Andric return StructuredData::StringSP(); 17500b57cec5SDimitry Andric 17510b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 17520b57cec5SDimitry Andric if (!generic) 17530b57cec5SDimitry Andric return nullptr; 17540b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 17550b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric if (!implementor.IsAllocated()) 17580b57cec5SDimitry Andric return StructuredData::StringSP(); 17590b57cec5SDimitry Andric 17600b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 17610b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric if (PyErr_Occurred()) 17640b57cec5SDimitry Andric PyErr_Clear(); 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 17670b57cec5SDimitry Andric return StructuredData::StringSP(); 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 17700b57cec5SDimitry Andric if (PyErr_Occurred()) 17710b57cec5SDimitry Andric PyErr_Clear(); 17720b57cec5SDimitry Andric return StructuredData::StringSP(); 17730b57cec5SDimitry Andric } 17740b57cec5SDimitry Andric 17750b57cec5SDimitry Andric if (PyErr_Occurred()) 17760b57cec5SDimitry Andric PyErr_Clear(); 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric // right now we know this function exists and is callable.. 17790b57cec5SDimitry Andric PythonObject py_return( 17800b57cec5SDimitry Andric PyRefType::Owned, 17810b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 17820b57cec5SDimitry Andric 17830b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 17840b57cec5SDimitry Andric if (PyErr_Occurred()) { 17850b57cec5SDimitry Andric PyErr_Print(); 17860b57cec5SDimitry Andric PyErr_Clear(); 17870b57cec5SDimitry Andric } 17880b57cec5SDimitry Andric 17890b57cec5SDimitry Andric if (py_return.get()) { 17900b57cec5SDimitry Andric PythonBytes result(PyRefType::Borrowed, py_return.get()); 17910b57cec5SDimitry Andric return result.CreateStructuredString(); 17920b57cec5SDimitry Andric } 17930b57cec5SDimitry Andric return StructuredData::StringSP(); 17940b57cec5SDimitry Andric } 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 17970b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 17980b57cec5SDimitry Andric lldb::addr_t context) { 17990b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric static char callee_name[] = "create_thread"; 18020b57cec5SDimitry Andric std::string param_format; 18030b57cec5SDimitry Andric param_format += GetPythonValueFormatString(tid); 18040b57cec5SDimitry Andric param_format += GetPythonValueFormatString(context); 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric if (!os_plugin_object_sp) 18070b57cec5SDimitry Andric return StructuredData::DictionarySP(); 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 18100b57cec5SDimitry Andric if (!generic) 18110b57cec5SDimitry Andric return nullptr; 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 18140b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 18150b57cec5SDimitry Andric 18160b57cec5SDimitry Andric if (!implementor.IsAllocated()) 18170b57cec5SDimitry Andric return StructuredData::DictionarySP(); 18180b57cec5SDimitry Andric 18190b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 18200b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric if (PyErr_Occurred()) 18230b57cec5SDimitry Andric PyErr_Clear(); 18240b57cec5SDimitry Andric 18250b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 18260b57cec5SDimitry Andric return StructuredData::DictionarySP(); 18270b57cec5SDimitry Andric 18280b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 18290b57cec5SDimitry Andric if (PyErr_Occurred()) 18300b57cec5SDimitry Andric PyErr_Clear(); 18310b57cec5SDimitry Andric return StructuredData::DictionarySP(); 18320b57cec5SDimitry Andric } 18330b57cec5SDimitry Andric 18340b57cec5SDimitry Andric if (PyErr_Occurred()) 18350b57cec5SDimitry Andric PyErr_Clear(); 18360b57cec5SDimitry Andric 18370b57cec5SDimitry Andric // right now we know this function exists and is callable.. 18380b57cec5SDimitry Andric PythonObject py_return(PyRefType::Owned, 18390b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, 18400b57cec5SDimitry Andric ¶m_format[0], tid, context)); 18410b57cec5SDimitry Andric 18420b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 18430b57cec5SDimitry Andric if (PyErr_Occurred()) { 18440b57cec5SDimitry Andric PyErr_Print(); 18450b57cec5SDimitry Andric PyErr_Clear(); 18460b57cec5SDimitry Andric } 18470b57cec5SDimitry Andric 18480b57cec5SDimitry Andric if (py_return.get()) { 18490b57cec5SDimitry Andric PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 18500b57cec5SDimitry Andric return result_dict.CreateStructuredDictionary(); 18510b57cec5SDimitry Andric } 18520b57cec5SDimitry Andric return StructuredData::DictionarySP(); 18530b57cec5SDimitry Andric } 18540b57cec5SDimitry Andric 18550b57cec5SDimitry Andric StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 18560b57cec5SDimitry Andric const char *class_name, lldb::ThreadPlanSP thread_plan_sp) { 18570b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 18580b57cec5SDimitry Andric return StructuredData::ObjectSP(); 18590b57cec5SDimitry Andric 18600b57cec5SDimitry Andric if (!thread_plan_sp.get()) 18610b57cec5SDimitry Andric return StructuredData::ObjectSP(); 18620b57cec5SDimitry Andric 18630b57cec5SDimitry Andric Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 18640b57cec5SDimitry Andric ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 18650b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter = 18660b57cec5SDimitry Andric static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 18670b57cec5SDimitry Andric 18680b57cec5SDimitry Andric if (!script_interpreter) 18690b57cec5SDimitry Andric return StructuredData::ObjectSP(); 18700b57cec5SDimitry Andric 18710b57cec5SDimitry Andric void *ret_val; 18720b57cec5SDimitry Andric 18730b57cec5SDimitry Andric { 18740b57cec5SDimitry Andric Locker py_lock(this, 18750b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 18780b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(), 18790b57cec5SDimitry Andric thread_plan_sp); 18800b57cec5SDimitry Andric } 18810b57cec5SDimitry Andric 18820b57cec5SDimitry Andric return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 18830b57cec5SDimitry Andric } 18840b57cec5SDimitry Andric 18850b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 18860b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 18870b57cec5SDimitry Andric bool explains_stop = true; 18880b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr; 18890b57cec5SDimitry Andric if (implementor_sp) 18900b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric(); 18910b57cec5SDimitry Andric if (generic) { 18920b57cec5SDimitry Andric Locker py_lock(this, 18930b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 18940b57cec5SDimitry Andric explains_stop = LLDBSWIGPythonCallThreadPlan( 18950b57cec5SDimitry Andric generic->GetValue(), "explains_stop", event, script_error); 18960b57cec5SDimitry Andric if (script_error) 18970b57cec5SDimitry Andric return true; 18980b57cec5SDimitry Andric } 18990b57cec5SDimitry Andric return explains_stop; 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 19020b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 19030b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 19040b57cec5SDimitry Andric bool should_stop = true; 19050b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr; 19060b57cec5SDimitry Andric if (implementor_sp) 19070b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric(); 19080b57cec5SDimitry Andric if (generic) { 19090b57cec5SDimitry Andric Locker py_lock(this, 19100b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19110b57cec5SDimitry Andric should_stop = LLDBSWIGPythonCallThreadPlan( 19120b57cec5SDimitry Andric generic->GetValue(), "should_stop", event, script_error); 19130b57cec5SDimitry Andric if (script_error) 19140b57cec5SDimitry Andric return true; 19150b57cec5SDimitry Andric } 19160b57cec5SDimitry Andric return should_stop; 19170b57cec5SDimitry Andric } 19180b57cec5SDimitry Andric 19190b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 19200b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, bool &script_error) { 19210b57cec5SDimitry Andric bool is_stale = true; 19220b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr; 19230b57cec5SDimitry Andric if (implementor_sp) 19240b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric(); 19250b57cec5SDimitry Andric if (generic) { 19260b57cec5SDimitry Andric Locker py_lock(this, 19270b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19280b57cec5SDimitry Andric is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 19290b57cec5SDimitry Andric nullptr, script_error); 19300b57cec5SDimitry Andric if (script_error) 19310b57cec5SDimitry Andric return true; 19320b57cec5SDimitry Andric } 19330b57cec5SDimitry Andric return is_stale; 19340b57cec5SDimitry Andric } 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 19370b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, bool &script_error) { 19380b57cec5SDimitry Andric bool should_step = false; 19390b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr; 19400b57cec5SDimitry Andric if (implementor_sp) 19410b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric(); 19420b57cec5SDimitry Andric if (generic) { 19430b57cec5SDimitry Andric Locker py_lock(this, 19440b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19450b57cec5SDimitry Andric should_step = LLDBSWIGPythonCallThreadPlan( 19460b57cec5SDimitry Andric generic->GetValue(), "should_step", nullptr, script_error); 19470b57cec5SDimitry Andric if (script_error) 19480b57cec5SDimitry Andric should_step = true; 19490b57cec5SDimitry Andric } 19500b57cec5SDimitry Andric if (should_step) 19510b57cec5SDimitry Andric return lldb::eStateStepping; 19520b57cec5SDimitry Andric else 19530b57cec5SDimitry Andric return lldb::eStateRunning; 19540b57cec5SDimitry Andric } 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric StructuredData::GenericSP 19570b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 19580b57cec5SDimitry Andric const char *class_name, StructuredDataImpl *args_data, 19590b57cec5SDimitry Andric lldb::BreakpointSP &bkpt_sp) { 19600b57cec5SDimitry Andric 19610b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 19620b57cec5SDimitry Andric return StructuredData::GenericSP(); 19630b57cec5SDimitry Andric 19640b57cec5SDimitry Andric if (!bkpt_sp.get()) 19650b57cec5SDimitry Andric return StructuredData::GenericSP(); 19660b57cec5SDimitry Andric 19670b57cec5SDimitry Andric Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 19680b57cec5SDimitry Andric ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 19690b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter = 19700b57cec5SDimitry Andric static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 19710b57cec5SDimitry Andric 19720b57cec5SDimitry Andric if (!script_interpreter) 19730b57cec5SDimitry Andric return StructuredData::GenericSP(); 19740b57cec5SDimitry Andric 19750b57cec5SDimitry Andric void *ret_val; 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric { 19780b57cec5SDimitry Andric Locker py_lock(this, 19790b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19800b57cec5SDimitry Andric 19810b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 19820b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 19830b57cec5SDimitry Andric bkpt_sp); 19840b57cec5SDimitry Andric } 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 19870b57cec5SDimitry Andric } 19880b57cec5SDimitry Andric 19890b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 19900b57cec5SDimitry Andric StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 19910b57cec5SDimitry Andric bool should_continue = false; 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric if (implementor_sp) { 19940b57cec5SDimitry Andric Locker py_lock(this, 19950b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19960b57cec5SDimitry Andric should_continue = LLDBSwigPythonCallBreakpointResolver( 19970b57cec5SDimitry Andric implementor_sp->GetValue(), "__callback__", sym_ctx); 19980b57cec5SDimitry Andric if (PyErr_Occurred()) { 19990b57cec5SDimitry Andric PyErr_Print(); 20000b57cec5SDimitry Andric PyErr_Clear(); 20010b57cec5SDimitry Andric } 20020b57cec5SDimitry Andric } 20030b57cec5SDimitry Andric return should_continue; 20040b57cec5SDimitry Andric } 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric lldb::SearchDepth 20070b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 20080b57cec5SDimitry Andric StructuredData::GenericSP implementor_sp) { 20090b57cec5SDimitry Andric int depth_as_int = lldb::eSearchDepthModule; 20100b57cec5SDimitry Andric if (implementor_sp) { 20110b57cec5SDimitry Andric Locker py_lock(this, 20120b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20130b57cec5SDimitry Andric depth_as_int = LLDBSwigPythonCallBreakpointResolver( 20140b57cec5SDimitry Andric implementor_sp->GetValue(), "__get_depth__", nullptr); 20150b57cec5SDimitry Andric if (PyErr_Occurred()) { 20160b57cec5SDimitry Andric PyErr_Print(); 20170b57cec5SDimitry Andric PyErr_Clear(); 20180b57cec5SDimitry Andric } 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric if (depth_as_int == lldb::eSearchDepthInvalid) 20210b57cec5SDimitry Andric return lldb::eSearchDepthModule; 20220b57cec5SDimitry Andric 20230b57cec5SDimitry Andric if (depth_as_int <= lldb::kLastSearchDepthKind) 20240b57cec5SDimitry Andric return (lldb::SearchDepth)depth_as_int; 20250b57cec5SDimitry Andric else 20260b57cec5SDimitry Andric return lldb::eSearchDepthModule; 20270b57cec5SDimitry Andric } 20280b57cec5SDimitry Andric 20290b57cec5SDimitry Andric StructuredData::ObjectSP 20300b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 20310b57cec5SDimitry Andric lldb_private::Status &error) { 20320b57cec5SDimitry Andric if (!FileSystem::Instance().Exists(file_spec)) { 20330b57cec5SDimitry Andric error.SetErrorString("no such file"); 20340b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20350b57cec5SDimitry Andric } 20360b57cec5SDimitry Andric 20370b57cec5SDimitry Andric StructuredData::ObjectSP module_sp; 20380b57cec5SDimitry Andric 20390b57cec5SDimitry Andric if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error, 20400b57cec5SDimitry Andric &module_sp)) 20410b57cec5SDimitry Andric return module_sp; 20420b57cec5SDimitry Andric 20430b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20440b57cec5SDimitry Andric } 20450b57cec5SDimitry Andric 20460b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 20470b57cec5SDimitry Andric StructuredData::ObjectSP plugin_module_sp, Target *target, 20480b57cec5SDimitry Andric const char *setting_name, lldb_private::Status &error) { 20490b57cec5SDimitry Andric if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 20500b57cec5SDimitry Andric return StructuredData::DictionarySP(); 20510b57cec5SDimitry Andric StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 20520b57cec5SDimitry Andric if (!generic) 20530b57cec5SDimitry Andric return StructuredData::DictionarySP(); 20540b57cec5SDimitry Andric 20550b57cec5SDimitry Andric PythonObject reply_pyobj; 20560b57cec5SDimitry Andric Locker py_lock(this, 20570b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20580b57cec5SDimitry Andric TargetSP target_sp(target->shared_from_this()); 20590b57cec5SDimitry Andric reply_pyobj.Reset(PyRefType::Owned, 20600b57cec5SDimitry Andric (PyObject *)LLDBSWIGPython_GetDynamicSetting( 20610b57cec5SDimitry Andric generic->GetValue(), setting_name, target_sp)); 20620b57cec5SDimitry Andric 20630b57cec5SDimitry Andric PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get()); 20640b57cec5SDimitry Andric return py_dict.CreateStructuredDictionary(); 20650b57cec5SDimitry Andric } 20660b57cec5SDimitry Andric 20670b57cec5SDimitry Andric StructuredData::ObjectSP 20680b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 20690b57cec5SDimitry Andric const char *class_name, lldb::ValueObjectSP valobj) { 20700b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 20710b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20720b57cec5SDimitry Andric 20730b57cec5SDimitry Andric if (!valobj.get()) 20740b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20750b57cec5SDimitry Andric 20760b57cec5SDimitry Andric ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 20770b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr(); 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric if (!target) 20800b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20810b57cec5SDimitry Andric 20820b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger(); 20830b57cec5SDimitry Andric ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 20840b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter = 20850b57cec5SDimitry Andric (ScriptInterpreterPythonImpl *)script_interpreter; 20860b57cec5SDimitry Andric 20870b57cec5SDimitry Andric if (!script_interpreter) 20880b57cec5SDimitry Andric return StructuredData::ObjectSP(); 20890b57cec5SDimitry Andric 20900b57cec5SDimitry Andric void *ret_val = nullptr; 20910b57cec5SDimitry Andric 20920b57cec5SDimitry Andric { 20930b57cec5SDimitry Andric Locker py_lock(this, 20940b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20950b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateSyntheticProvider( 20960b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 20970b57cec5SDimitry Andric } 20980b57cec5SDimitry Andric 20990b57cec5SDimitry Andric return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 21000b57cec5SDimitry Andric } 21010b57cec5SDimitry Andric 21020b57cec5SDimitry Andric StructuredData::GenericSP 21030b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 21040b57cec5SDimitry Andric DebuggerSP debugger_sp(m_debugger.shared_from_this()); 21050b57cec5SDimitry Andric 21060b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') 21070b57cec5SDimitry Andric return StructuredData::GenericSP(); 21080b57cec5SDimitry Andric 21090b57cec5SDimitry Andric if (!debugger_sp.get()) 21100b57cec5SDimitry Andric return StructuredData::GenericSP(); 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric void *ret_val; 21130b57cec5SDimitry Andric 21140b57cec5SDimitry Andric { 21150b57cec5SDimitry Andric Locker py_lock(this, 21160b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 21170b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateCommandObject( 21180b57cec5SDimitry Andric class_name, m_dictionary_name.c_str(), debugger_sp); 21190b57cec5SDimitry Andric } 21200b57cec5SDimitry Andric 21210b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 21220b57cec5SDimitry Andric } 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 21250b57cec5SDimitry Andric const char *oneliner, std::string &output, const void *name_token) { 21260b57cec5SDimitry Andric StringList input; 21270b57cec5SDimitry Andric input.SplitIntoLines(oneliner, strlen(oneliner)); 21280b57cec5SDimitry Andric return GenerateTypeScriptFunction(input, output, name_token); 21290b57cec5SDimitry Andric } 21300b57cec5SDimitry Andric 21310b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 21320b57cec5SDimitry Andric const char *oneliner, std::string &output, const void *name_token) { 21330b57cec5SDimitry Andric StringList input; 21340b57cec5SDimitry Andric input.SplitIntoLines(oneliner, strlen(oneliner)); 21350b57cec5SDimitry Andric return GenerateTypeSynthClass(input, output, name_token); 21360b57cec5SDimitry Andric } 21370b57cec5SDimitry Andric 21380b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 21390b57cec5SDimitry Andric StringList &user_input, std::string &output) { 21400b57cec5SDimitry Andric static uint32_t num_created_functions = 0; 21410b57cec5SDimitry Andric user_input.RemoveBlankLines(); 21420b57cec5SDimitry Andric StreamString sstr; 21430b57cec5SDimitry Andric Status error; 21440b57cec5SDimitry Andric if (user_input.GetSize() == 0) { 21450b57cec5SDimitry Andric error.SetErrorString("No input data."); 21460b57cec5SDimitry Andric return error; 21470b57cec5SDimitry Andric } 21480b57cec5SDimitry Andric 21490b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName( 21500b57cec5SDimitry Andric "lldb_autogen_python_bp_callback_func_", num_created_functions)); 21510b57cec5SDimitry Andric sstr.Printf("def %s (frame, bp_loc, internal_dict):", 21520b57cec5SDimitry Andric auto_generated_function_name.c_str()); 21530b57cec5SDimitry Andric 21540b57cec5SDimitry Andric error = GenerateFunction(sstr.GetData(), user_input); 21550b57cec5SDimitry Andric if (!error.Success()) 21560b57cec5SDimitry Andric return error; 21570b57cec5SDimitry Andric 21580b57cec5SDimitry Andric // Store the name of the auto-generated function to be called. 21590b57cec5SDimitry Andric output.assign(auto_generated_function_name); 21600b57cec5SDimitry Andric return error; 21610b57cec5SDimitry Andric } 21620b57cec5SDimitry Andric 21630b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 21640b57cec5SDimitry Andric StringList &user_input, std::string &output) { 21650b57cec5SDimitry Andric static uint32_t num_created_functions = 0; 21660b57cec5SDimitry Andric user_input.RemoveBlankLines(); 21670b57cec5SDimitry Andric StreamString sstr; 21680b57cec5SDimitry Andric 21690b57cec5SDimitry Andric if (user_input.GetSize() == 0) 21700b57cec5SDimitry Andric return false; 21710b57cec5SDimitry Andric 21720b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName( 21730b57cec5SDimitry Andric "lldb_autogen_python_wp_callback_func_", num_created_functions)); 21740b57cec5SDimitry Andric sstr.Printf("def %s (frame, wp, internal_dict):", 21750b57cec5SDimitry Andric auto_generated_function_name.c_str()); 21760b57cec5SDimitry Andric 21770b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success()) 21780b57cec5SDimitry Andric return false; 21790b57cec5SDimitry Andric 21800b57cec5SDimitry Andric // Store the name of the auto-generated function to be called. 21810b57cec5SDimitry Andric output.assign(auto_generated_function_name); 21820b57cec5SDimitry Andric return true; 21830b57cec5SDimitry Andric } 21840b57cec5SDimitry Andric 21850b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary( 21860b57cec5SDimitry Andric const char *python_function_name, lldb::ValueObjectSP valobj, 21870b57cec5SDimitry Andric StructuredData::ObjectSP &callee_wrapper_sp, 21880b57cec5SDimitry Andric const TypeSummaryOptions &options, std::string &retval) { 21890b57cec5SDimitry Andric 21900b57cec5SDimitry Andric static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 21910b57cec5SDimitry Andric Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 21920b57cec5SDimitry Andric 21930b57cec5SDimitry Andric if (!valobj.get()) { 21940b57cec5SDimitry Andric retval.assign("<no object>"); 21950b57cec5SDimitry Andric return false; 21960b57cec5SDimitry Andric } 21970b57cec5SDimitry Andric 21980b57cec5SDimitry Andric void *old_callee = nullptr; 21990b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr; 22000b57cec5SDimitry Andric if (callee_wrapper_sp) { 22010b57cec5SDimitry Andric generic = callee_wrapper_sp->GetAsGeneric(); 22020b57cec5SDimitry Andric if (generic) 22030b57cec5SDimitry Andric old_callee = generic->GetValue(); 22040b57cec5SDimitry Andric } 22050b57cec5SDimitry Andric void *new_callee = old_callee; 22060b57cec5SDimitry Andric 22070b57cec5SDimitry Andric bool ret_val; 22080b57cec5SDimitry Andric if (python_function_name && *python_function_name) { 22090b57cec5SDimitry Andric { 22100b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 22110b57cec5SDimitry Andric Locker::NoSTDIN); 22120b57cec5SDimitry Andric { 22130b57cec5SDimitry Andric TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 22160b57cec5SDimitry Andric Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 22170b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallTypeScript( 22180b57cec5SDimitry Andric python_function_name, GetSessionDictionary().get(), valobj, 22190b57cec5SDimitry Andric &new_callee, options_sp, retval); 22200b57cec5SDimitry Andric } 22210b57cec5SDimitry Andric } 22220b57cec5SDimitry Andric } else { 22230b57cec5SDimitry Andric retval.assign("<no function name>"); 22240b57cec5SDimitry Andric return false; 22250b57cec5SDimitry Andric } 22260b57cec5SDimitry Andric 22270b57cec5SDimitry Andric if (new_callee && old_callee != new_callee) 22280b57cec5SDimitry Andric callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee); 22290b57cec5SDimitry Andric 22300b57cec5SDimitry Andric return ret_val; 22310b57cec5SDimitry Andric } 22320b57cec5SDimitry Andric 22330b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::Clear() { 22340b57cec5SDimitry Andric // Release any global variables that might have strong references to 22350b57cec5SDimitry Andric // LLDB objects when clearing the python script interpreter. 22360b57cec5SDimitry Andric Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 22370b57cec5SDimitry Andric 22380b57cec5SDimitry Andric // This may be called as part of Py_Finalize. In that case the modules are 22390b57cec5SDimitry Andric // destroyed in random order and we can't guarantee that we can access these. 22400b57cec5SDimitry Andric if (Py_IsInitialized()) 22410b57cec5SDimitry Andric PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process " 22420b57cec5SDimitry Andric "= None; lldb.thread = None; lldb.frame = None"); 22430b57cec5SDimitry Andric } 22440b57cec5SDimitry Andric 22450b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 22460b57cec5SDimitry Andric void *baton, StoppointCallbackContext *context, user_id_t break_id, 22470b57cec5SDimitry Andric user_id_t break_loc_id) { 22480b57cec5SDimitry Andric CommandDataPython *bp_option_data = (CommandDataPython *)baton; 22490b57cec5SDimitry Andric const char *python_function_name = bp_option_data->script_source.c_str(); 22500b57cec5SDimitry Andric 22510b57cec5SDimitry Andric if (!context) 22520b57cec5SDimitry Andric return true; 22530b57cec5SDimitry Andric 22540b57cec5SDimitry Andric ExecutionContext exe_ctx(context->exe_ctx_ref); 22550b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr(); 22560b57cec5SDimitry Andric 22570b57cec5SDimitry Andric if (!target) 22580b57cec5SDimitry Andric return true; 22590b57cec5SDimitry Andric 22600b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger(); 22610b57cec5SDimitry Andric ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 22620b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter = 22630b57cec5SDimitry Andric (ScriptInterpreterPythonImpl *)script_interpreter; 22640b57cec5SDimitry Andric 22650b57cec5SDimitry Andric if (!script_interpreter) 22660b57cec5SDimitry Andric return true; 22670b57cec5SDimitry Andric 22680b57cec5SDimitry Andric if (python_function_name && python_function_name[0]) { 22690b57cec5SDimitry Andric const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 22700b57cec5SDimitry Andric BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 22710b57cec5SDimitry Andric if (breakpoint_sp) { 22720b57cec5SDimitry Andric const BreakpointLocationSP bp_loc_sp( 22730b57cec5SDimitry Andric breakpoint_sp->FindLocationByID(break_loc_id)); 22740b57cec5SDimitry Andric 22750b57cec5SDimitry Andric if (stop_frame_sp && bp_loc_sp) { 22760b57cec5SDimitry Andric bool ret_val = true; 22770b57cec5SDimitry Andric { 22780b57cec5SDimitry Andric Locker py_lock(python_interpreter, Locker::AcquireLock | 22790b57cec5SDimitry Andric Locker::InitSession | 22800b57cec5SDimitry Andric Locker::NoSTDIN); 22810b57cec5SDimitry Andric ret_val = LLDBSwigPythonBreakpointCallbackFunction( 22820b57cec5SDimitry Andric python_function_name, 22830b57cec5SDimitry Andric python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 22840b57cec5SDimitry Andric bp_loc_sp); 22850b57cec5SDimitry Andric } 22860b57cec5SDimitry Andric return ret_val; 22870b57cec5SDimitry Andric } 22880b57cec5SDimitry Andric } 22890b57cec5SDimitry Andric } 22900b57cec5SDimitry Andric // We currently always true so we stop in case anything goes wrong when 22910b57cec5SDimitry Andric // trying to call the script function 22920b57cec5SDimitry Andric return true; 22930b57cec5SDimitry Andric } 22940b57cec5SDimitry Andric 22950b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 22960b57cec5SDimitry Andric void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 22970b57cec5SDimitry Andric WatchpointOptions::CommandData *wp_option_data = 22980b57cec5SDimitry Andric (WatchpointOptions::CommandData *)baton; 22990b57cec5SDimitry Andric const char *python_function_name = wp_option_data->script_source.c_str(); 23000b57cec5SDimitry Andric 23010b57cec5SDimitry Andric if (!context) 23020b57cec5SDimitry Andric return true; 23030b57cec5SDimitry Andric 23040b57cec5SDimitry Andric ExecutionContext exe_ctx(context->exe_ctx_ref); 23050b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr(); 23060b57cec5SDimitry Andric 23070b57cec5SDimitry Andric if (!target) 23080b57cec5SDimitry Andric return true; 23090b57cec5SDimitry Andric 23100b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger(); 23110b57cec5SDimitry Andric ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 23120b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter = 23130b57cec5SDimitry Andric (ScriptInterpreterPythonImpl *)script_interpreter; 23140b57cec5SDimitry Andric 23150b57cec5SDimitry Andric if (!script_interpreter) 23160b57cec5SDimitry Andric return true; 23170b57cec5SDimitry Andric 23180b57cec5SDimitry Andric if (python_function_name && python_function_name[0]) { 23190b57cec5SDimitry Andric const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 23200b57cec5SDimitry Andric WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 23210b57cec5SDimitry Andric if (wp_sp) { 23220b57cec5SDimitry Andric if (stop_frame_sp && wp_sp) { 23230b57cec5SDimitry Andric bool ret_val = true; 23240b57cec5SDimitry Andric { 23250b57cec5SDimitry Andric Locker py_lock(python_interpreter, Locker::AcquireLock | 23260b57cec5SDimitry Andric Locker::InitSession | 23270b57cec5SDimitry Andric Locker::NoSTDIN); 23280b57cec5SDimitry Andric ret_val = LLDBSwigPythonWatchpointCallbackFunction( 23290b57cec5SDimitry Andric python_function_name, 23300b57cec5SDimitry Andric python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 23310b57cec5SDimitry Andric wp_sp); 23320b57cec5SDimitry Andric } 23330b57cec5SDimitry Andric return ret_val; 23340b57cec5SDimitry Andric } 23350b57cec5SDimitry Andric } 23360b57cec5SDimitry Andric } 23370b57cec5SDimitry Andric // We currently always true so we stop in case anything goes wrong when 23380b57cec5SDimitry Andric // trying to call the script function 23390b57cec5SDimitry Andric return true; 23400b57cec5SDimitry Andric } 23410b57cec5SDimitry Andric 23420b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 23430b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 23440b57cec5SDimitry Andric if (!implementor_sp) 23450b57cec5SDimitry Andric return 0; 23460b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23470b57cec5SDimitry Andric if (!generic) 23480b57cec5SDimitry Andric return 0; 23490b57cec5SDimitry Andric void *implementor = generic->GetValue(); 23500b57cec5SDimitry Andric if (!implementor) 23510b57cec5SDimitry Andric return 0; 23520b57cec5SDimitry Andric 23530b57cec5SDimitry Andric size_t ret_val = 0; 23540b57cec5SDimitry Andric 23550b57cec5SDimitry Andric { 23560b57cec5SDimitry Andric Locker py_lock(this, 23570b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 23580b57cec5SDimitry Andric ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 23590b57cec5SDimitry Andric } 23600b57cec5SDimitry Andric 23610b57cec5SDimitry Andric return ret_val; 23620b57cec5SDimitry Andric } 23630b57cec5SDimitry Andric 23640b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 23650b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 23660b57cec5SDimitry Andric if (!implementor_sp) 23670b57cec5SDimitry Andric return lldb::ValueObjectSP(); 23680b57cec5SDimitry Andric 23690b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23700b57cec5SDimitry Andric if (!generic) 23710b57cec5SDimitry Andric return lldb::ValueObjectSP(); 23720b57cec5SDimitry Andric void *implementor = generic->GetValue(); 23730b57cec5SDimitry Andric if (!implementor) 23740b57cec5SDimitry Andric return lldb::ValueObjectSP(); 23750b57cec5SDimitry Andric 23760b57cec5SDimitry Andric lldb::ValueObjectSP ret_val; 23770b57cec5SDimitry Andric { 23780b57cec5SDimitry Andric Locker py_lock(this, 23790b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 23800b57cec5SDimitry Andric void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 23810b57cec5SDimitry Andric if (child_ptr != nullptr && child_ptr != Py_None) { 23820b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr = 23830b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 23840b57cec5SDimitry Andric if (sb_value_ptr == nullptr) 23850b57cec5SDimitry Andric Py_XDECREF(child_ptr); 23860b57cec5SDimitry Andric else 23870b57cec5SDimitry Andric ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 23880b57cec5SDimitry Andric } else { 23890b57cec5SDimitry Andric Py_XDECREF(child_ptr); 23900b57cec5SDimitry Andric } 23910b57cec5SDimitry Andric } 23920b57cec5SDimitry Andric 23930b57cec5SDimitry Andric return ret_val; 23940b57cec5SDimitry Andric } 23950b57cec5SDimitry Andric 23960b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 23970b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 23980b57cec5SDimitry Andric if (!implementor_sp) 23990b57cec5SDimitry Andric return UINT32_MAX; 24000b57cec5SDimitry Andric 24010b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24020b57cec5SDimitry Andric if (!generic) 24030b57cec5SDimitry Andric return UINT32_MAX; 24040b57cec5SDimitry Andric void *implementor = generic->GetValue(); 24050b57cec5SDimitry Andric if (!implementor) 24060b57cec5SDimitry Andric return UINT32_MAX; 24070b57cec5SDimitry Andric 24080b57cec5SDimitry Andric int ret_val = UINT32_MAX; 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric { 24110b57cec5SDimitry Andric Locker py_lock(this, 24120b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24130b57cec5SDimitry Andric ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 24140b57cec5SDimitry Andric } 24150b57cec5SDimitry Andric 24160b57cec5SDimitry Andric return ret_val; 24170b57cec5SDimitry Andric } 24180b57cec5SDimitry Andric 24190b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 24200b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) { 24210b57cec5SDimitry Andric bool ret_val = false; 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric if (!implementor_sp) 24240b57cec5SDimitry Andric return ret_val; 24250b57cec5SDimitry Andric 24260b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24270b57cec5SDimitry Andric if (!generic) 24280b57cec5SDimitry Andric return ret_val; 24290b57cec5SDimitry Andric void *implementor = generic->GetValue(); 24300b57cec5SDimitry Andric if (!implementor) 24310b57cec5SDimitry Andric return ret_val; 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric { 24340b57cec5SDimitry Andric Locker py_lock(this, 24350b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24360b57cec5SDimitry Andric ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 24370b57cec5SDimitry Andric } 24380b57cec5SDimitry Andric 24390b57cec5SDimitry Andric return ret_val; 24400b57cec5SDimitry Andric } 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 24430b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) { 24440b57cec5SDimitry Andric bool ret_val = false; 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric if (!implementor_sp) 24470b57cec5SDimitry Andric return ret_val; 24480b57cec5SDimitry Andric 24490b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24500b57cec5SDimitry Andric if (!generic) 24510b57cec5SDimitry Andric return ret_val; 24520b57cec5SDimitry Andric void *implementor = generic->GetValue(); 24530b57cec5SDimitry Andric if (!implementor) 24540b57cec5SDimitry Andric return ret_val; 24550b57cec5SDimitry Andric 24560b57cec5SDimitry Andric { 24570b57cec5SDimitry Andric Locker py_lock(this, 24580b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24590b57cec5SDimitry Andric ret_val = 24600b57cec5SDimitry Andric LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 24610b57cec5SDimitry Andric } 24620b57cec5SDimitry Andric 24630b57cec5SDimitry Andric return ret_val; 24640b57cec5SDimitry Andric } 24650b57cec5SDimitry Andric 24660b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 24670b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) { 24680b57cec5SDimitry Andric lldb::ValueObjectSP ret_val(nullptr); 24690b57cec5SDimitry Andric 24700b57cec5SDimitry Andric if (!implementor_sp) 24710b57cec5SDimitry Andric return ret_val; 24720b57cec5SDimitry Andric 24730b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24740b57cec5SDimitry Andric if (!generic) 24750b57cec5SDimitry Andric return ret_val; 24760b57cec5SDimitry Andric void *implementor = generic->GetValue(); 24770b57cec5SDimitry Andric if (!implementor) 24780b57cec5SDimitry Andric return ret_val; 24790b57cec5SDimitry Andric 24800b57cec5SDimitry Andric { 24810b57cec5SDimitry Andric Locker py_lock(this, 24820b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24830b57cec5SDimitry Andric void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor); 24840b57cec5SDimitry Andric if (child_ptr != nullptr && child_ptr != Py_None) { 24850b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr = 24860b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 24870b57cec5SDimitry Andric if (sb_value_ptr == nullptr) 24880b57cec5SDimitry Andric Py_XDECREF(child_ptr); 24890b57cec5SDimitry Andric else 24900b57cec5SDimitry Andric ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 24910b57cec5SDimitry Andric } else { 24920b57cec5SDimitry Andric Py_XDECREF(child_ptr); 24930b57cec5SDimitry Andric } 24940b57cec5SDimitry Andric } 24950b57cec5SDimitry Andric 24960b57cec5SDimitry Andric return ret_val; 24970b57cec5SDimitry Andric } 24980b57cec5SDimitry Andric 24990b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 25000b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) { 25010b57cec5SDimitry Andric Locker py_lock(this, 25020b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25030b57cec5SDimitry Andric 25040b57cec5SDimitry Andric static char callee_name[] = "get_type_name"; 25050b57cec5SDimitry Andric 25060b57cec5SDimitry Andric ConstString ret_val; 25070b57cec5SDimitry Andric bool got_string = false; 25080b57cec5SDimitry Andric std::string buffer; 25090b57cec5SDimitry Andric 25100b57cec5SDimitry Andric if (!implementor_sp) 25110b57cec5SDimitry Andric return ret_val; 25120b57cec5SDimitry Andric 25130b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 25140b57cec5SDimitry Andric if (!generic) 25150b57cec5SDimitry Andric return ret_val; 25160b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 25170b57cec5SDimitry Andric (PyObject *)generic->GetValue()); 25180b57cec5SDimitry Andric if (!implementor.IsAllocated()) 25190b57cec5SDimitry Andric return ret_val; 25200b57cec5SDimitry Andric 25210b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 25220b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 25230b57cec5SDimitry Andric 25240b57cec5SDimitry Andric if (PyErr_Occurred()) 25250b57cec5SDimitry Andric PyErr_Clear(); 25260b57cec5SDimitry Andric 25270b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 25280b57cec5SDimitry Andric return ret_val; 25290b57cec5SDimitry Andric 25300b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 25310b57cec5SDimitry Andric if (PyErr_Occurred()) 25320b57cec5SDimitry Andric PyErr_Clear(); 25330b57cec5SDimitry Andric return ret_val; 25340b57cec5SDimitry Andric } 25350b57cec5SDimitry Andric 25360b57cec5SDimitry Andric if (PyErr_Occurred()) 25370b57cec5SDimitry Andric PyErr_Clear(); 25380b57cec5SDimitry Andric 25390b57cec5SDimitry Andric // right now we know this function exists and is callable.. 25400b57cec5SDimitry Andric PythonObject py_return( 25410b57cec5SDimitry Andric PyRefType::Owned, 25420b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 25430b57cec5SDimitry Andric 25440b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 25450b57cec5SDimitry Andric if (PyErr_Occurred()) { 25460b57cec5SDimitry Andric PyErr_Print(); 25470b57cec5SDimitry Andric PyErr_Clear(); 25480b57cec5SDimitry Andric } 25490b57cec5SDimitry Andric 25500b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 25510b57cec5SDimitry Andric PythonString py_string(PyRefType::Borrowed, py_return.get()); 25520b57cec5SDimitry Andric llvm::StringRef return_data(py_string.GetString()); 25530b57cec5SDimitry Andric if (!return_data.empty()) { 25540b57cec5SDimitry Andric buffer.assign(return_data.data(), return_data.size()); 25550b57cec5SDimitry Andric got_string = true; 25560b57cec5SDimitry Andric } 25570b57cec5SDimitry Andric } 25580b57cec5SDimitry Andric 25590b57cec5SDimitry Andric if (got_string) 25600b57cec5SDimitry Andric ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 25610b57cec5SDimitry Andric 25620b57cec5SDimitry Andric return ret_val; 25630b57cec5SDimitry Andric } 25640b57cec5SDimitry Andric 25650b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 25660b57cec5SDimitry Andric const char *impl_function, Process *process, std::string &output, 25670b57cec5SDimitry Andric Status &error) { 25680b57cec5SDimitry Andric bool ret_val; 25690b57cec5SDimitry Andric if (!process) { 25700b57cec5SDimitry Andric error.SetErrorString("no process"); 25710b57cec5SDimitry Andric return false; 25720b57cec5SDimitry Andric } 25730b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) { 25740b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 25750b57cec5SDimitry Andric return false; 25760b57cec5SDimitry Andric } 25770b57cec5SDimitry Andric 25780b57cec5SDimitry Andric { 25790b57cec5SDimitry Andric ProcessSP process_sp(process->shared_from_this()); 25800b57cec5SDimitry Andric Locker py_lock(this, 25810b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25820b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 25830b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), process_sp, output); 25840b57cec5SDimitry Andric if (!ret_val) 25850b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed"); 25860b57cec5SDimitry Andric } 25870b57cec5SDimitry Andric return ret_val; 25880b57cec5SDimitry Andric } 25890b57cec5SDimitry Andric 25900b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 25910b57cec5SDimitry Andric const char *impl_function, Thread *thread, std::string &output, 25920b57cec5SDimitry Andric Status &error) { 25930b57cec5SDimitry Andric bool ret_val; 25940b57cec5SDimitry Andric if (!thread) { 25950b57cec5SDimitry Andric error.SetErrorString("no thread"); 25960b57cec5SDimitry Andric return false; 25970b57cec5SDimitry Andric } 25980b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) { 25990b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 26000b57cec5SDimitry Andric return false; 26010b57cec5SDimitry Andric } 26020b57cec5SDimitry Andric 26030b57cec5SDimitry Andric { 26040b57cec5SDimitry Andric ThreadSP thread_sp(thread->shared_from_this()); 26050b57cec5SDimitry Andric Locker py_lock(this, 26060b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 26070b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordThread( 26080b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), thread_sp, output); 26090b57cec5SDimitry Andric if (!ret_val) 26100b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed"); 26110b57cec5SDimitry Andric } 26120b57cec5SDimitry Andric return ret_val; 26130b57cec5SDimitry Andric } 26140b57cec5SDimitry Andric 26150b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 26160b57cec5SDimitry Andric const char *impl_function, Target *target, std::string &output, 26170b57cec5SDimitry Andric Status &error) { 26180b57cec5SDimitry Andric bool ret_val; 26190b57cec5SDimitry Andric if (!target) { 26200b57cec5SDimitry Andric error.SetErrorString("no thread"); 26210b57cec5SDimitry Andric return false; 26220b57cec5SDimitry Andric } 26230b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) { 26240b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 26250b57cec5SDimitry Andric return false; 26260b57cec5SDimitry Andric } 26270b57cec5SDimitry Andric 26280b57cec5SDimitry Andric { 26290b57cec5SDimitry Andric TargetSP target_sp(target->shared_from_this()); 26300b57cec5SDimitry Andric Locker py_lock(this, 26310b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 26320b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 26330b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), target_sp, output); 26340b57cec5SDimitry Andric if (!ret_val) 26350b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed"); 26360b57cec5SDimitry Andric } 26370b57cec5SDimitry Andric return ret_val; 26380b57cec5SDimitry Andric } 26390b57cec5SDimitry Andric 26400b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 26410b57cec5SDimitry Andric const char *impl_function, StackFrame *frame, std::string &output, 26420b57cec5SDimitry Andric Status &error) { 26430b57cec5SDimitry Andric bool ret_val; 26440b57cec5SDimitry Andric if (!frame) { 26450b57cec5SDimitry Andric error.SetErrorString("no frame"); 26460b57cec5SDimitry Andric return false; 26470b57cec5SDimitry Andric } 26480b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) { 26490b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 26500b57cec5SDimitry Andric return false; 26510b57cec5SDimitry Andric } 26520b57cec5SDimitry Andric 26530b57cec5SDimitry Andric { 26540b57cec5SDimitry Andric StackFrameSP frame_sp(frame->shared_from_this()); 26550b57cec5SDimitry Andric Locker py_lock(this, 26560b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 26570b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordFrame( 26580b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), frame_sp, output); 26590b57cec5SDimitry Andric if (!ret_val) 26600b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed"); 26610b57cec5SDimitry Andric } 26620b57cec5SDimitry Andric return ret_val; 26630b57cec5SDimitry Andric } 26640b57cec5SDimitry Andric 26650b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 26660b57cec5SDimitry Andric const char *impl_function, ValueObject *value, std::string &output, 26670b57cec5SDimitry Andric Status &error) { 26680b57cec5SDimitry Andric bool ret_val; 26690b57cec5SDimitry Andric if (!value) { 26700b57cec5SDimitry Andric error.SetErrorString("no value"); 26710b57cec5SDimitry Andric return false; 26720b57cec5SDimitry Andric } 26730b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) { 26740b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 26750b57cec5SDimitry Andric return false; 26760b57cec5SDimitry Andric } 26770b57cec5SDimitry Andric 26780b57cec5SDimitry Andric { 26790b57cec5SDimitry Andric ValueObjectSP value_sp(value->GetSP()); 26800b57cec5SDimitry Andric Locker py_lock(this, 26810b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 26820b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordValue( 26830b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), value_sp, output); 26840b57cec5SDimitry Andric if (!ret_val) 26850b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed"); 26860b57cec5SDimitry Andric } 26870b57cec5SDimitry Andric return ret_val; 26880b57cec5SDimitry Andric } 26890b57cec5SDimitry Andric 26900b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr, 26910b57cec5SDimitry Andric const std::string &newStr) { 26920b57cec5SDimitry Andric size_t pos = 0; 26930b57cec5SDimitry Andric uint64_t matches = 0; 26940b57cec5SDimitry Andric while ((pos = str.find(oldStr, pos)) != std::string::npos) { 26950b57cec5SDimitry Andric matches++; 26960b57cec5SDimitry Andric str.replace(pos, oldStr.length(), newStr); 26970b57cec5SDimitry Andric pos += newStr.length(); 26980b57cec5SDimitry Andric } 26990b57cec5SDimitry Andric return matches; 27000b57cec5SDimitry Andric } 27010b57cec5SDimitry Andric 27020b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule( 27030b57cec5SDimitry Andric const char *pathname, bool can_reload, bool init_session, 27040b57cec5SDimitry Andric lldb_private::Status &error, StructuredData::ObjectSP *module_sp) { 27050b57cec5SDimitry Andric if (!pathname || !pathname[0]) { 27060b57cec5SDimitry Andric error.SetErrorString("invalid pathname"); 27070b57cec5SDimitry Andric return false; 27080b57cec5SDimitry Andric } 27090b57cec5SDimitry Andric 27100b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 27110b57cec5SDimitry Andric 27120b57cec5SDimitry Andric { 27130b57cec5SDimitry Andric FileSpec target_file(pathname); 27140b57cec5SDimitry Andric FileSystem::Instance().Resolve(target_file); 27150b57cec5SDimitry Andric std::string basename(target_file.GetFilename().GetCString()); 27160b57cec5SDimitry Andric 27170b57cec5SDimitry Andric StreamString command_stream; 27180b57cec5SDimitry Andric 27190b57cec5SDimitry Andric // Before executing Python code, lock the GIL. 27200b57cec5SDimitry Andric Locker py_lock(this, 27210b57cec5SDimitry Andric Locker::AcquireLock | 27220b57cec5SDimitry Andric (init_session ? Locker::InitSession : 0) | 27230b57cec5SDimitry Andric Locker::NoSTDIN, 27240b57cec5SDimitry Andric Locker::FreeAcquiredLock | 27250b57cec5SDimitry Andric (init_session ? Locker::TearDownSession : 0)); 27260b57cec5SDimitry Andric namespace fs = llvm::sys::fs; 27270b57cec5SDimitry Andric fs::file_status st; 27280b57cec5SDimitry Andric std::error_code ec = status(target_file.GetPath(), st); 27290b57cec5SDimitry Andric 27300b57cec5SDimitry Andric if (ec || st.type() == fs::file_type::status_error || 27310b57cec5SDimitry Andric st.type() == fs::file_type::type_unknown || 27320b57cec5SDimitry Andric st.type() == fs::file_type::file_not_found) { 27330b57cec5SDimitry Andric // if not a valid file of any sort, check if it might be a filename still 27340b57cec5SDimitry Andric // dot can't be used but / and \ can, and if either is found, reject 27350b57cec5SDimitry Andric if (strchr(pathname, '\\') || strchr(pathname, '/')) { 27360b57cec5SDimitry Andric error.SetErrorString("invalid pathname"); 27370b57cec5SDimitry Andric return false; 27380b57cec5SDimitry Andric } 27390b57cec5SDimitry Andric basename = pathname; // not a filename, probably a package of some sort, 27400b57cec5SDimitry Andric // let it go through 27410b57cec5SDimitry Andric } else if (is_directory(st) || is_regular_file(st)) { 27420b57cec5SDimitry Andric if (target_file.GetDirectory().IsEmpty()) { 27430b57cec5SDimitry Andric error.SetErrorString("invalid directory name"); 27440b57cec5SDimitry Andric return false; 27450b57cec5SDimitry Andric } 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric std::string directory = target_file.GetDirectory().GetCString(); 27480b57cec5SDimitry Andric replace_all(directory, "\\", "\\\\"); 27490b57cec5SDimitry Andric replace_all(directory, "'", "\\'"); 27500b57cec5SDimitry Andric 27510b57cec5SDimitry Andric // now make sure that Python has "directory" in the search path 27520b57cec5SDimitry Andric StreamString command_stream; 27530b57cec5SDimitry Andric command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 27540b57cec5SDimitry Andric "sys.path.insert(1,'%s');\n\n", 27550b57cec5SDimitry Andric directory.c_str(), directory.c_str()); 27560b57cec5SDimitry Andric bool syspath_retval = 27570b57cec5SDimitry Andric ExecuteMultipleLines(command_stream.GetData(), 27580b57cec5SDimitry Andric ScriptInterpreter::ExecuteScriptOptions() 27590b57cec5SDimitry Andric .SetEnableIO(false) 27600b57cec5SDimitry Andric .SetSetLLDBGlobals(false)) 27610b57cec5SDimitry Andric .Success(); 27620b57cec5SDimitry Andric if (!syspath_retval) { 27630b57cec5SDimitry Andric error.SetErrorString("Python sys.path handling failed"); 27640b57cec5SDimitry Andric return false; 27650b57cec5SDimitry Andric } 27660b57cec5SDimitry Andric 27670b57cec5SDimitry Andric // strip .py or .pyc extension 27680b57cec5SDimitry Andric ConstString extension = target_file.GetFileNameExtension(); 27690b57cec5SDimitry Andric if (extension) { 27700b57cec5SDimitry Andric if (llvm::StringRef(extension.GetCString()) == ".py") 27710b57cec5SDimitry Andric basename.resize(basename.length() - 3); 27720b57cec5SDimitry Andric else if (llvm::StringRef(extension.GetCString()) == ".pyc") 27730b57cec5SDimitry Andric basename.resize(basename.length() - 4); 27740b57cec5SDimitry Andric } 27750b57cec5SDimitry Andric } else { 27760b57cec5SDimitry Andric error.SetErrorString("no known way to import this module specification"); 27770b57cec5SDimitry Andric return false; 27780b57cec5SDimitry Andric } 27790b57cec5SDimitry Andric 27800b57cec5SDimitry Andric // check if the module is already import-ed 27810b57cec5SDimitry Andric command_stream.Clear(); 27820b57cec5SDimitry Andric command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str()); 27830b57cec5SDimitry Andric bool does_contain = false; 27840b57cec5SDimitry Andric // this call will succeed if the module was ever imported in any Debugger 27850b57cec5SDimitry Andric // in the lifetime of the process in which this LLDB framework is living 27860b57cec5SDimitry Andric bool was_imported_globally = 27870b57cec5SDimitry Andric (ExecuteOneLineWithReturn( 27880b57cec5SDimitry Andric command_stream.GetData(), 27890b57cec5SDimitry Andric ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, 27900b57cec5SDimitry Andric ScriptInterpreter::ExecuteScriptOptions() 27910b57cec5SDimitry Andric .SetEnableIO(false) 27920b57cec5SDimitry Andric .SetSetLLDBGlobals(false)) && 27930b57cec5SDimitry Andric does_contain); 27940b57cec5SDimitry Andric // this call will fail if the module was not imported in this Debugger 27950b57cec5SDimitry Andric // before 27960b57cec5SDimitry Andric command_stream.Clear(); 27970b57cec5SDimitry Andric command_stream.Printf("sys.getrefcount(%s)", basename.c_str()); 27980b57cec5SDimitry Andric bool was_imported_locally = GetSessionDictionary() 27990b57cec5SDimitry Andric .GetItemForKey(PythonString(basename)) 28000b57cec5SDimitry Andric .IsAllocated(); 28010b57cec5SDimitry Andric 28020b57cec5SDimitry Andric bool was_imported = (was_imported_globally || was_imported_locally); 28030b57cec5SDimitry Andric 28040b57cec5SDimitry Andric if (was_imported && !can_reload) { 28050b57cec5SDimitry Andric error.SetErrorString("module already imported"); 28060b57cec5SDimitry Andric return false; 28070b57cec5SDimitry Andric } 28080b57cec5SDimitry Andric 28090b57cec5SDimitry Andric // now actually do the import 28100b57cec5SDimitry Andric command_stream.Clear(); 28110b57cec5SDimitry Andric 28120b57cec5SDimitry Andric if (was_imported) { 28130b57cec5SDimitry Andric if (!was_imported_locally) 28140b57cec5SDimitry Andric command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(), 28150b57cec5SDimitry Andric basename.c_str()); 28160b57cec5SDimitry Andric else 28170b57cec5SDimitry Andric command_stream.Printf("reload_module(%s)", basename.c_str()); 28180b57cec5SDimitry Andric } else 28190b57cec5SDimitry Andric command_stream.Printf("import %s", basename.c_str()); 28200b57cec5SDimitry Andric 28210b57cec5SDimitry Andric error = ExecuteMultipleLines(command_stream.GetData(), 28220b57cec5SDimitry Andric ScriptInterpreter::ExecuteScriptOptions() 28230b57cec5SDimitry Andric .SetEnableIO(false) 28240b57cec5SDimitry Andric .SetSetLLDBGlobals(false)); 28250b57cec5SDimitry Andric if (error.Fail()) 28260b57cec5SDimitry Andric return false; 28270b57cec5SDimitry Andric 28280b57cec5SDimitry Andric // if we are here, everything worked 28290b57cec5SDimitry Andric // call __lldb_init_module(debugger,dict) 28300b57cec5SDimitry Andric if (!LLDBSwigPythonCallModuleInit(basename.c_str(), 28310b57cec5SDimitry Andric m_dictionary_name.c_str(), debugger_sp)) { 28320b57cec5SDimitry Andric error.SetErrorString("calling __lldb_init_module failed"); 28330b57cec5SDimitry Andric return false; 28340b57cec5SDimitry Andric } 28350b57cec5SDimitry Andric 28360b57cec5SDimitry Andric if (module_sp) { 28370b57cec5SDimitry Andric // everything went just great, now set the module object 28380b57cec5SDimitry Andric command_stream.Clear(); 28390b57cec5SDimitry Andric command_stream.Printf("%s", basename.c_str()); 28400b57cec5SDimitry Andric void *module_pyobj = nullptr; 28410b57cec5SDimitry Andric if (ExecuteOneLineWithReturn( 28420b57cec5SDimitry Andric command_stream.GetData(), 28430b57cec5SDimitry Andric ScriptInterpreter::eScriptReturnTypeOpaqueObject, 28440b57cec5SDimitry Andric &module_pyobj) && 28450b57cec5SDimitry Andric module_pyobj) 28460b57cec5SDimitry Andric *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj); 28470b57cec5SDimitry Andric } 28480b57cec5SDimitry Andric 28490b57cec5SDimitry Andric return true; 28500b57cec5SDimitry Andric } 28510b57cec5SDimitry Andric } 28520b57cec5SDimitry Andric 28530b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 28540b57cec5SDimitry Andric if (!word || !word[0]) 28550b57cec5SDimitry Andric return false; 28560b57cec5SDimitry Andric 28570b57cec5SDimitry Andric llvm::StringRef word_sr(word); 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric // filter out a few characters that would just confuse us and that are 28600b57cec5SDimitry Andric // clearly not keyword material anyway 28610b57cec5SDimitry Andric if (word_sr.find('"') != llvm::StringRef::npos || 28620b57cec5SDimitry Andric word_sr.find('\'') != llvm::StringRef::npos) 28630b57cec5SDimitry Andric return false; 28640b57cec5SDimitry Andric 28650b57cec5SDimitry Andric StreamString command_stream; 28660b57cec5SDimitry Andric command_stream.Printf("keyword.iskeyword('%s')", word); 28670b57cec5SDimitry Andric bool result; 28680b57cec5SDimitry Andric ExecuteScriptOptions options; 28690b57cec5SDimitry Andric options.SetEnableIO(false); 28700b57cec5SDimitry Andric options.SetMaskoutErrors(true); 28710b57cec5SDimitry Andric options.SetSetLLDBGlobals(false); 28720b57cec5SDimitry Andric if (ExecuteOneLineWithReturn(command_stream.GetData(), 28730b57cec5SDimitry Andric ScriptInterpreter::eScriptReturnTypeBool, 28740b57cec5SDimitry Andric &result, options)) 28750b57cec5SDimitry Andric return result; 28760b57cec5SDimitry Andric return false; 28770b57cec5SDimitry Andric } 28780b57cec5SDimitry Andric 28790b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 28800b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 28810b57cec5SDimitry Andric : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 28820b57cec5SDimitry Andric m_old_asynch(debugger_sp->GetAsyncExecution()) { 28830b57cec5SDimitry Andric if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 28840b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(false); 28850b57cec5SDimitry Andric else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 28860b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(true); 28870b57cec5SDimitry Andric } 28880b57cec5SDimitry Andric 28890b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 28900b57cec5SDimitry Andric if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 28910b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(m_old_asynch); 28920b57cec5SDimitry Andric } 28930b57cec5SDimitry Andric 28940b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 28950b57cec5SDimitry Andric const char *impl_function, llvm::StringRef args, 28960b57cec5SDimitry Andric ScriptedCommandSynchronicity synchronicity, 28970b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, Status &error, 28980b57cec5SDimitry Andric const lldb_private::ExecutionContext &exe_ctx) { 28990b57cec5SDimitry Andric if (!impl_function) { 29000b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 29010b57cec5SDimitry Andric return false; 29020b57cec5SDimitry Andric } 29030b57cec5SDimitry Andric 29040b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29050b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29060b57cec5SDimitry Andric 29070b57cec5SDimitry Andric if (!debugger_sp.get()) { 29080b57cec5SDimitry Andric error.SetErrorString("invalid Debugger pointer"); 29090b57cec5SDimitry Andric return false; 29100b57cec5SDimitry Andric } 29110b57cec5SDimitry Andric 29120b57cec5SDimitry Andric bool ret_val = false; 29130b57cec5SDimitry Andric 29140b57cec5SDimitry Andric std::string err_msg; 29150b57cec5SDimitry Andric 29160b57cec5SDimitry Andric { 29170b57cec5SDimitry Andric Locker py_lock(this, 29180b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | 29190b57cec5SDimitry Andric (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29200b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession); 29210b57cec5SDimitry Andric 29220b57cec5SDimitry Andric SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29230b57cec5SDimitry Andric 29240b57cec5SDimitry Andric std::string args_str = args.str(); 29250b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallCommand( 29260b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 29270b57cec5SDimitry Andric cmd_retobj, exe_ctx_ref_sp); 29280b57cec5SDimitry Andric } 29290b57cec5SDimitry Andric 29300b57cec5SDimitry Andric if (!ret_val) 29310b57cec5SDimitry Andric error.SetErrorString("unable to execute script function"); 29320b57cec5SDimitry Andric else 29330b57cec5SDimitry Andric error.Clear(); 29340b57cec5SDimitry Andric 29350b57cec5SDimitry Andric return ret_val; 29360b57cec5SDimitry Andric } 29370b57cec5SDimitry Andric 29380b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 29390b57cec5SDimitry Andric StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 29400b57cec5SDimitry Andric ScriptedCommandSynchronicity synchronicity, 29410b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, Status &error, 29420b57cec5SDimitry Andric const lldb_private::ExecutionContext &exe_ctx) { 29430b57cec5SDimitry Andric if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 29440b57cec5SDimitry Andric error.SetErrorString("no function to execute"); 29450b57cec5SDimitry Andric return false; 29460b57cec5SDimitry Andric } 29470b57cec5SDimitry Andric 29480b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29490b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29500b57cec5SDimitry Andric 29510b57cec5SDimitry Andric if (!debugger_sp.get()) { 29520b57cec5SDimitry Andric error.SetErrorString("invalid Debugger pointer"); 29530b57cec5SDimitry Andric return false; 29540b57cec5SDimitry Andric } 29550b57cec5SDimitry Andric 29560b57cec5SDimitry Andric bool ret_val = false; 29570b57cec5SDimitry Andric 29580b57cec5SDimitry Andric std::string err_msg; 29590b57cec5SDimitry Andric 29600b57cec5SDimitry Andric { 29610b57cec5SDimitry Andric Locker py_lock(this, 29620b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | 29630b57cec5SDimitry Andric (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29640b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession); 29650b57cec5SDimitry Andric 29660b57cec5SDimitry Andric SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29670b57cec5SDimitry Andric 29680b57cec5SDimitry Andric std::string args_str = args.str(); 29690b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(), 29700b57cec5SDimitry Andric debugger_sp, args_str.c_str(), 29710b57cec5SDimitry Andric cmd_retobj, exe_ctx_ref_sp); 29720b57cec5SDimitry Andric } 29730b57cec5SDimitry Andric 29740b57cec5SDimitry Andric if (!ret_val) 29750b57cec5SDimitry Andric error.SetErrorString("unable to execute script function"); 29760b57cec5SDimitry Andric else 29770b57cec5SDimitry Andric error.Clear(); 29780b57cec5SDimitry Andric 29790b57cec5SDimitry Andric return ret_val; 29800b57cec5SDimitry Andric } 29810b57cec5SDimitry Andric 29820b57cec5SDimitry Andric // in Python, a special attribute __doc__ contains the docstring for an object 29830b57cec5SDimitry Andric // (function, method, class, ...) if any is defined Otherwise, the attribute's 29840b57cec5SDimitry Andric // value is None 29850b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 29860b57cec5SDimitry Andric std::string &dest) { 29870b57cec5SDimitry Andric dest.clear(); 29880b57cec5SDimitry Andric if (!item || !*item) 29890b57cec5SDimitry Andric return false; 29900b57cec5SDimitry Andric std::string command(item); 29910b57cec5SDimitry Andric command += ".__doc__"; 29920b57cec5SDimitry Andric 29930b57cec5SDimitry Andric char *result_ptr = nullptr; // Python is going to point this to valid data if 29940b57cec5SDimitry Andric // ExecuteOneLineWithReturn returns successfully 29950b57cec5SDimitry Andric 29960b57cec5SDimitry Andric if (ExecuteOneLineWithReturn( 29970b57cec5SDimitry Andric command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 29980b57cec5SDimitry Andric &result_ptr, 29990b57cec5SDimitry Andric ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) { 30000b57cec5SDimitry Andric if (result_ptr) 30010b57cec5SDimitry Andric dest.assign(result_ptr); 30020b57cec5SDimitry Andric return true; 30030b57cec5SDimitry Andric } else { 30040b57cec5SDimitry Andric StreamString str_stream; 30050b57cec5SDimitry Andric str_stream.Printf( 30060b57cec5SDimitry Andric "Function %s was not found. Containing module might be missing.", item); 30070b57cec5SDimitry Andric dest = str_stream.GetString(); 30080b57cec5SDimitry Andric return false; 30090b57cec5SDimitry Andric } 30100b57cec5SDimitry Andric } 30110b57cec5SDimitry Andric 30120b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 30130b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 30140b57cec5SDimitry Andric bool got_string = false; 30150b57cec5SDimitry Andric dest.clear(); 30160b57cec5SDimitry Andric 30170b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30180b57cec5SDimitry Andric 30190b57cec5SDimitry Andric static char callee_name[] = "get_short_help"; 30200b57cec5SDimitry Andric 30210b57cec5SDimitry Andric if (!cmd_obj_sp) 30220b57cec5SDimitry Andric return false; 30230b57cec5SDimitry Andric 30240b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 30250b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue()); 30260b57cec5SDimitry Andric 30270b57cec5SDimitry Andric if (!implementor.IsAllocated()) 30280b57cec5SDimitry Andric return false; 30290b57cec5SDimitry Andric 30300b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 30310b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 30320b57cec5SDimitry Andric 30330b57cec5SDimitry Andric if (PyErr_Occurred()) 30340b57cec5SDimitry Andric PyErr_Clear(); 30350b57cec5SDimitry Andric 30360b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 30370b57cec5SDimitry Andric return false; 30380b57cec5SDimitry Andric 30390b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 30400b57cec5SDimitry Andric if (PyErr_Occurred()) 30410b57cec5SDimitry Andric PyErr_Clear(); 30420b57cec5SDimitry Andric return false; 30430b57cec5SDimitry Andric } 30440b57cec5SDimitry Andric 30450b57cec5SDimitry Andric if (PyErr_Occurred()) 30460b57cec5SDimitry Andric PyErr_Clear(); 30470b57cec5SDimitry Andric 30480b57cec5SDimitry Andric // right now we know this function exists and is callable.. 30490b57cec5SDimitry Andric PythonObject py_return( 30500b57cec5SDimitry Andric PyRefType::Owned, 30510b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 30520b57cec5SDimitry Andric 30530b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 30540b57cec5SDimitry Andric if (PyErr_Occurred()) { 30550b57cec5SDimitry Andric PyErr_Print(); 30560b57cec5SDimitry Andric PyErr_Clear(); 30570b57cec5SDimitry Andric } 30580b57cec5SDimitry Andric 30590b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 30600b57cec5SDimitry Andric PythonString py_string(PyRefType::Borrowed, py_return.get()); 30610b57cec5SDimitry Andric llvm::StringRef return_data(py_string.GetString()); 30620b57cec5SDimitry Andric dest.assign(return_data.data(), return_data.size()); 30630b57cec5SDimitry Andric got_string = true; 30640b57cec5SDimitry Andric } 30650b57cec5SDimitry Andric return got_string; 30660b57cec5SDimitry Andric } 30670b57cec5SDimitry Andric 30680b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 30690b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp) { 30700b57cec5SDimitry Andric uint32_t result = 0; 30710b57cec5SDimitry Andric 30720b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30730b57cec5SDimitry Andric 30740b57cec5SDimitry Andric static char callee_name[] = "get_flags"; 30750b57cec5SDimitry Andric 30760b57cec5SDimitry Andric if (!cmd_obj_sp) 30770b57cec5SDimitry Andric return result; 30780b57cec5SDimitry Andric 30790b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 30800b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue()); 30810b57cec5SDimitry Andric 30820b57cec5SDimitry Andric if (!implementor.IsAllocated()) 30830b57cec5SDimitry Andric return result; 30840b57cec5SDimitry Andric 30850b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 30860b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 30870b57cec5SDimitry Andric 30880b57cec5SDimitry Andric if (PyErr_Occurred()) 30890b57cec5SDimitry Andric PyErr_Clear(); 30900b57cec5SDimitry Andric 30910b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 30920b57cec5SDimitry Andric return result; 30930b57cec5SDimitry Andric 30940b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 30950b57cec5SDimitry Andric if (PyErr_Occurred()) 30960b57cec5SDimitry Andric PyErr_Clear(); 30970b57cec5SDimitry Andric return result; 30980b57cec5SDimitry Andric } 30990b57cec5SDimitry Andric 31000b57cec5SDimitry Andric if (PyErr_Occurred()) 31010b57cec5SDimitry Andric PyErr_Clear(); 31020b57cec5SDimitry Andric 31030b57cec5SDimitry Andric // right now we know this function exists and is callable.. 31040b57cec5SDimitry Andric PythonObject py_return( 31050b57cec5SDimitry Andric PyRefType::Owned, 31060b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31070b57cec5SDimitry Andric 31080b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 31090b57cec5SDimitry Andric if (PyErr_Occurred()) { 31100b57cec5SDimitry Andric PyErr_Print(); 31110b57cec5SDimitry Andric PyErr_Clear(); 31120b57cec5SDimitry Andric } 31130b57cec5SDimitry Andric 31140b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) { 31150b57cec5SDimitry Andric PythonInteger int_value(PyRefType::Borrowed, py_return.get()); 31160b57cec5SDimitry Andric result = int_value.GetInteger(); 31170b57cec5SDimitry Andric } 31180b57cec5SDimitry Andric 31190b57cec5SDimitry Andric return result; 31200b57cec5SDimitry Andric } 31210b57cec5SDimitry Andric 31220b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 31230b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 31240b57cec5SDimitry Andric bool got_string = false; 31250b57cec5SDimitry Andric dest.clear(); 31260b57cec5SDimitry Andric 31270b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 31280b57cec5SDimitry Andric 31290b57cec5SDimitry Andric static char callee_name[] = "get_long_help"; 31300b57cec5SDimitry Andric 31310b57cec5SDimitry Andric if (!cmd_obj_sp) 31320b57cec5SDimitry Andric return false; 31330b57cec5SDimitry Andric 31340b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed, 31350b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue()); 31360b57cec5SDimitry Andric 31370b57cec5SDimitry Andric if (!implementor.IsAllocated()) 31380b57cec5SDimitry Andric return false; 31390b57cec5SDimitry Andric 31400b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned, 31410b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name)); 31420b57cec5SDimitry Andric 31430b57cec5SDimitry Andric if (PyErr_Occurred()) 31440b57cec5SDimitry Andric PyErr_Clear(); 31450b57cec5SDimitry Andric 31460b57cec5SDimitry Andric if (!pmeth.IsAllocated()) 31470b57cec5SDimitry Andric return false; 31480b57cec5SDimitry Andric 31490b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) { 31500b57cec5SDimitry Andric if (PyErr_Occurred()) 31510b57cec5SDimitry Andric PyErr_Clear(); 31520b57cec5SDimitry Andric 31530b57cec5SDimitry Andric return false; 31540b57cec5SDimitry Andric } 31550b57cec5SDimitry Andric 31560b57cec5SDimitry Andric if (PyErr_Occurred()) 31570b57cec5SDimitry Andric PyErr_Clear(); 31580b57cec5SDimitry Andric 31590b57cec5SDimitry Andric // right now we know this function exists and is callable.. 31600b57cec5SDimitry Andric PythonObject py_return( 31610b57cec5SDimitry Andric PyRefType::Owned, 31620b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31630b57cec5SDimitry Andric 31640b57cec5SDimitry Andric // if it fails, print the error but otherwise go on 31650b57cec5SDimitry Andric if (PyErr_Occurred()) { 31660b57cec5SDimitry Andric PyErr_Print(); 31670b57cec5SDimitry Andric PyErr_Clear(); 31680b57cec5SDimitry Andric } 31690b57cec5SDimitry Andric 31700b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 31710b57cec5SDimitry Andric PythonString str(PyRefType::Borrowed, py_return.get()); 31720b57cec5SDimitry Andric llvm::StringRef str_data(str.GetString()); 31730b57cec5SDimitry Andric dest.assign(str_data.data(), str_data.size()); 31740b57cec5SDimitry Andric got_string = true; 31750b57cec5SDimitry Andric } 31760b57cec5SDimitry Andric 31770b57cec5SDimitry Andric return got_string; 31780b57cec5SDimitry Andric } 31790b57cec5SDimitry Andric 31800b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker> 31810b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 31820b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 31830b57cec5SDimitry Andric this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 31840b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession)); 31850b57cec5SDimitry Andric return py_lock; 31860b57cec5SDimitry Andric } 31870b57cec5SDimitry Andric 31880b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::InitializePrivate() { 31890b57cec5SDimitry Andric if (g_initialized) 31900b57cec5SDimitry Andric return; 31910b57cec5SDimitry Andric 31920b57cec5SDimitry Andric g_initialized = true; 31930b57cec5SDimitry Andric 31940b57cec5SDimitry Andric static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 31950b57cec5SDimitry Andric Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 31960b57cec5SDimitry Andric 31970b57cec5SDimitry Andric // RAII-based initialization which correctly handles multiple-initialization, 31980b57cec5SDimitry Andric // version- specific differences among Python 2 and Python 3, and saving and 31990b57cec5SDimitry Andric // restoring various other pieces of state that can get mucked with during 32000b57cec5SDimitry Andric // initialization. 32010b57cec5SDimitry Andric InitializePythonRAII initialize_guard; 32020b57cec5SDimitry Andric 32030b57cec5SDimitry Andric LLDBSwigPyInit(); 32040b57cec5SDimitry Andric 32050b57cec5SDimitry Andric // Update the path python uses to search for modules to include the current 32060b57cec5SDimitry Andric // directory. 32070b57cec5SDimitry Andric 32080b57cec5SDimitry Andric PyRun_SimpleString("import sys"); 32090b57cec5SDimitry Andric AddToSysPath(AddLocation::End, "."); 32100b57cec5SDimitry Andric 32110b57cec5SDimitry Andric // Don't denormalize paths when calling file_spec.GetPath(). On platforms 32120b57cec5SDimitry Andric // that use a backslash as the path separator, this will result in executing 32130b57cec5SDimitry Andric // python code containing paths with unescaped backslashes. But Python also 32140b57cec5SDimitry Andric // accepts forward slashes, so to make life easier we just use that. 32150b57cec5SDimitry Andric if (FileSpec file_spec = GetPythonDir()) 32160b57cec5SDimitry Andric AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 32170b57cec5SDimitry Andric if (FileSpec file_spec = HostInfo::GetShlibDir()) 32180b57cec5SDimitry Andric AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 32190b57cec5SDimitry Andric 32200b57cec5SDimitry Andric PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 32210b57cec5SDimitry Andric "lldb.embedded_interpreter; from " 32220b57cec5SDimitry Andric "lldb.embedded_interpreter import run_python_interpreter; " 32230b57cec5SDimitry Andric "from lldb.embedded_interpreter import run_one_line"); 32240b57cec5SDimitry Andric } 32250b57cec5SDimitry Andric 32260b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 32270b57cec5SDimitry Andric std::string path) { 32280b57cec5SDimitry Andric std::string path_copy; 32290b57cec5SDimitry Andric 32300b57cec5SDimitry Andric std::string statement; 32310b57cec5SDimitry Andric if (location == AddLocation::Beginning) { 32320b57cec5SDimitry Andric statement.assign("sys.path.insert(0,\""); 32330b57cec5SDimitry Andric statement.append(path); 32340b57cec5SDimitry Andric statement.append("\")"); 32350b57cec5SDimitry Andric } else { 32360b57cec5SDimitry Andric statement.assign("sys.path.append(\""); 32370b57cec5SDimitry Andric statement.append(path); 32380b57cec5SDimitry Andric statement.append("\")"); 32390b57cec5SDimitry Andric } 32400b57cec5SDimitry Andric PyRun_SimpleString(statement.c_str()); 32410b57cec5SDimitry Andric } 32420b57cec5SDimitry Andric 32430b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical 32440b57cec5SDimitry Andric // place to call it). Calling Py_Finalize here causes test suite runs to seg 32450b57cec5SDimitry Andric // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 32460b57cec5SDimitry Andric // be called 'at_exit'. When the test suite Python harness finishes up, it 32470b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions. 32480b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 32490b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls 32500b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 32510b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results 32520b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting 32530b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize 32540b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway 32550b57cec5SDimitry Andric // when the process exits). 32560b57cec5SDimitry Andric // 32570b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 32580b57cec5SDimitry Andric 32590b57cec5SDimitry Andric #endif // LLDB_DISABLE_PYTHON 3260