180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===// 22c1f46dcSZachary Turner // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 62c1f46dcSZachary Turner // 72c1f46dcSZachary Turner //===----------------------------------------------------------------------===// 82c1f46dcSZachary Turner 959998b7bSJonas Devlieghere #include "lldb/Host/Config.h" 10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h" 11d68983e3SPavel Labath 124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON 13d68983e3SPavel Labath 1441de9a97SKate Stone // LLDB Python header must be included first 152c1f46dcSZachary Turner #include "lldb-python.h" 1641de9a97SKate Stone 172c1f46dcSZachary Turner #include "PythonDataObjects.h" 189357b5d0Sserge-sans-paille #include "PythonReadline.h" 191f6a57c1SMed Ismail Bennani #include "SWIGPythonBridge.h" 2063dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h" 211f6a57c1SMed Ismail Bennani #include "ScriptedProcessPythonInterface.h" 221f6a57c1SMed Ismail Bennani 231f6a57c1SMed Ismail Bennani #include "lldb/API/SBError.h" 2441ae8e74SKuba Mracek #include "lldb/API/SBFrame.h" 2563dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h" 262c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h" 272c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h" 282c1f46dcSZachary Turner #include "lldb/Core/Communication.h" 292c1f46dcSZachary Turner #include "lldb/Core/Debugger.h" 302c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h" 312c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h" 322c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h" 334eff2d31SZachary Turner #include "lldb/Host/FileSystem.h" 342c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h" 352c1f46dcSZachary Turner #include "lldb/Host/Pipe.h" 362c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h" 372c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h" 382c1f46dcSZachary Turner #include "lldb/Target/Thread.h" 392c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h" 405861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h" 4138d0632eSPavel Labath #include "lldb/Utility/Timer.h" 4222c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h" 43b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h" 44d79273c9SJonas Devlieghere #include "llvm/Support/Error.h" 457d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h" 462fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h" 472c1f46dcSZachary Turner 4876e47d48SRaphael Isemann #include <cstdio> 4976e47d48SRaphael Isemann #include <cstdlib> 509a6c7572SJonas Devlieghere #include <memory> 519a6c7572SJonas Devlieghere #include <mutex> 529a6c7572SJonas Devlieghere #include <string> 539a6c7572SJonas Devlieghere 542c1f46dcSZachary Turner using namespace lldb; 552c1f46dcSZachary Turner using namespace lldb_private; 56722b6189SLawrence D'Anna using namespace lldb_private::python; 5704edd189SLawrence D'Anna using llvm::Expected; 582c1f46dcSZachary Turner 59bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython) 60fbb4d1e4SJonas Devlieghere 61b01b1087SJonas Devlieghere // Defined in the SWIG source file 62b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3 63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void); 64b01b1087SJonas Devlieghere 65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb 66b01b1087SJonas Devlieghere 67b01b1087SJonas Devlieghere #else 68b01b1087SJonas Devlieghere extern "C" void init_lldb(void); 69b01b1087SJonas Devlieghere 70b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb 71b01b1087SJonas Devlieghere #endif 72b01b1087SJonas Devlieghere 73049ae930SJonas Devlieghere #if defined(_WIN32) 74049ae930SJonas Devlieghere // Don't mess with the signal handlers on Windows. 75049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT 0 76049ae930SJonas Devlieghere #else 77049ae930SJonas Devlieghere // PyErr_SetInterrupt was introduced in 3.2. 78049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT \ 79049ae930SJonas Devlieghere (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 80049ae930SJonas Devlieghere #endif 81b01b1087SJonas Devlieghere 82d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) { 83d055e3a0SPedro Tammela ScriptInterpreter *script_interpreter = 84d055e3a0SPedro Tammela debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython); 85d055e3a0SPedro Tammela return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 86d055e3a0SPedro Tammela } 87d055e3a0SPedro Tammela 88b9c1b51eSKate Stone namespace { 8922c8efcdSZachary Turner 9005097246SAdrian Prantl // Initializing Python is not a straightforward process. We cannot control 9105097246SAdrian Prantl // what external code may have done before getting to this point in LLDB, 9205097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a 9305097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained 9405097246SAdrian Prantl // across our initialization. We do this by using an RAII pattern where we 9505097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end 96b9c1b51eSKate Stone struct InitializePythonRAII { 97079fe48aSZachary Turner public: 989494c510SJonas Devlieghere InitializePythonRAII() { 99079fe48aSZachary Turner InitializePythonHome(); 100079fe48aSZachary Turner 1019357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE 1029357b5d0Sserge-sans-paille // Python's readline is incompatible with libedit being linked into lldb. 1039357b5d0Sserge-sans-paille // Provide a patched version local to the embedded interpreter. 1049357b5d0Sserge-sans-paille bool ReadlinePatched = false; 1059357b5d0Sserge-sans-paille for (auto *p = PyImport_Inittab; p->name != NULL; p++) { 1069357b5d0Sserge-sans-paille if (strcmp(p->name, "readline") == 0) { 1079357b5d0Sserge-sans-paille p->initfunc = initlldb_readline; 1089357b5d0Sserge-sans-paille break; 1099357b5d0Sserge-sans-paille } 1109357b5d0Sserge-sans-paille } 1119357b5d0Sserge-sans-paille if (!ReadlinePatched) { 1129357b5d0Sserge-sans-paille PyImport_AppendInittab("readline", initlldb_readline); 1139357b5d0Sserge-sans-paille ReadlinePatched = true; 1149357b5d0Sserge-sans-paille } 1159357b5d0Sserge-sans-paille #endif 1169357b5d0Sserge-sans-paille 11774587a0eSVadim Chugunov // Register _lldb as a built-in module. 11805495c5dSJonas Devlieghere PyImport_AppendInittab("_lldb", LLDBSwigPyInit); 11974587a0eSVadim Chugunov 120079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 121079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 122079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 123079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 124079fe48aSZachary Turner Py_InitializeEx(0); 125079fe48aSZachary Turner InitializeThreadsPrivate(); 126079fe48aSZachary Turner #else 127079fe48aSZachary Turner InitializeThreadsPrivate(); 128079fe48aSZachary Turner Py_InitializeEx(0); 129079fe48aSZachary Turner #endif 130079fe48aSZachary Turner } 131079fe48aSZachary Turner 132b9c1b51eSKate Stone ~InitializePythonRAII() { 133b9c1b51eSKate Stone if (m_was_already_initialized) { 1343b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 1353b7e1981SPavel Labath LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 1361b6700efSTatyana Krasnukha m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 137079fe48aSZachary Turner PyGILState_Release(m_gil_state); 138b9c1b51eSKate Stone } else { 139079fe48aSZachary Turner // We initialized the threads in this function, just unlock the GIL. 140079fe48aSZachary Turner PyEval_SaveThread(); 141079fe48aSZachary Turner } 142079fe48aSZachary Turner } 143079fe48aSZachary Turner 144079fe48aSZachary Turner private: 145b9c1b51eSKate Stone void InitializePythonHome() { 1463ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME 1473ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3 1483ec3f62fSHaibo Huang typedef wchar_t* str_type; 1493ec3f62fSHaibo Huang #else 1503ec3f62fSHaibo Huang typedef char* str_type; 1513ec3f62fSHaibo Huang #endif 1523ec3f62fSHaibo Huang static str_type g_python_home = []() -> str_type { 1533ec3f62fSHaibo Huang const char *lldb_python_home = LLDB_PYTHON_HOME; 1543ec3f62fSHaibo Huang const char *absolute_python_home = nullptr; 1553ec3f62fSHaibo Huang llvm::SmallString<64> path; 1563ec3f62fSHaibo Huang if (llvm::sys::path::is_absolute(lldb_python_home)) { 1573ec3f62fSHaibo Huang absolute_python_home = lldb_python_home; 1583ec3f62fSHaibo Huang } else { 1593ec3f62fSHaibo Huang FileSpec spec = HostInfo::GetShlibDir(); 1603ec3f62fSHaibo Huang if (!spec) 1613ec3f62fSHaibo Huang return nullptr; 1623ec3f62fSHaibo Huang spec.GetPath(path); 1633ec3f62fSHaibo Huang llvm::sys::path::append(path, lldb_python_home); 1643ec3f62fSHaibo Huang absolute_python_home = path.c_str(); 1653ec3f62fSHaibo Huang } 16622c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3 16722c8efcdSZachary Turner size_t size = 0; 1683ec3f62fSHaibo Huang return Py_DecodeLocale(absolute_python_home, &size); 16922c8efcdSZachary Turner #else 1703ec3f62fSHaibo Huang return strdup(absolute_python_home); 17122c8efcdSZachary Turner #endif 1723ec3f62fSHaibo Huang }(); 1733ec3f62fSHaibo Huang if (g_python_home != nullptr) { 174079fe48aSZachary Turner Py_SetPythonHome(g_python_home); 1753ec3f62fSHaibo Huang } 176386f00dbSDavide Italiano #else 177386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 17863dd5d25SJonas Devlieghere // For Darwin, the only Python version supported is the one shipped in the 17963dd5d25SJonas Devlieghere // OS OS and linked with lldb. Other installation of Python may have higher 1804f9cb260SDavide Italiano // priorities in the path, overriding PYTHONHOME and causing 1814f9cb260SDavide Italiano // problems/incompatibilities. In order to avoid confusion, always hardcode 1824f9cb260SDavide Italiano // the PythonHome to be right, as it's not going to change. 18363dd5d25SJonas Devlieghere static char path[] = 18463dd5d25SJonas Devlieghere "/System/Library/Frameworks/Python.framework/Versions/2.7"; 1854f9cb260SDavide Italiano Py_SetPythonHome(path); 186386f00dbSDavide Italiano #endif 187386f00dbSDavide Italiano #endif 18822c8efcdSZachary Turner } 18922c8efcdSZachary Turner 190b9c1b51eSKate Stone void InitializeThreadsPrivate() { 1911b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, 1921b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter 1931b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized` 1941b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be 1951b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When 1961b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. 1971b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) 1981b6700efSTatyana Krasnukha // The only case we should go further and acquire the GIL: it is unlocked. 1991b6700efSTatyana Krasnukha if (PyGILState_Check()) 2001b6700efSTatyana Krasnukha return; 2011b6700efSTatyana Krasnukha #endif 2021b6700efSTatyana Krasnukha 203b9c1b51eSKate Stone if (PyEval_ThreadsInitialized()) { 2043b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 205079fe48aSZachary Turner 206079fe48aSZachary Turner m_was_already_initialized = true; 207079fe48aSZachary Turner m_gil_state = PyGILState_Ensure(); 2083b7e1981SPavel Labath LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n", 209079fe48aSZachary Turner m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 210079fe48aSZachary Turner return; 211079fe48aSZachary Turner } 212079fe48aSZachary Turner 213079fe48aSZachary Turner // InitThreads acquires the GIL if it hasn't been called before. 214079fe48aSZachary Turner PyEval_InitThreads(); 215079fe48aSZachary Turner } 216079fe48aSZachary Turner 2179494c510SJonas Devlieghere PyGILState_STATE m_gil_state = PyGILState_UNLOCKED; 2189494c510SJonas Devlieghere bool m_was_already_initialized = false; 219079fe48aSZachary Turner }; 220*eb5c0ea6SJonas Devlieghere 221*eb5c0ea6SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 222*eb5c0ea6SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores 223*eb5c0ea6SJonas Devlieghere /// it at the end of the current scope. 224*eb5c0ea6SJonas Devlieghere struct RestoreSignalHandlerScope { 225*eb5c0ea6SJonas Devlieghere /// The signal handler. 226*eb5c0ea6SJonas Devlieghere struct sigaction m_prev_handler; 227*eb5c0ea6SJonas Devlieghere int m_signal_code; 228*eb5c0ea6SJonas Devlieghere RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) { 229*eb5c0ea6SJonas Devlieghere // Initialize sigaction to their default state. 230*eb5c0ea6SJonas Devlieghere std::memset(&m_prev_handler, 0, sizeof(m_prev_handler)); 231*eb5c0ea6SJonas Devlieghere // Don't install a new handler, just read back the old one. 232*eb5c0ea6SJonas Devlieghere struct sigaction *new_handler = nullptr; 233*eb5c0ea6SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler); 234*eb5c0ea6SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to read handler"); 235*eb5c0ea6SJonas Devlieghere } 236*eb5c0ea6SJonas Devlieghere ~RestoreSignalHandlerScope() { 237*eb5c0ea6SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr); 238*eb5c0ea6SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to restore old handler"); 239*eb5c0ea6SJonas Devlieghere } 240*eb5c0ea6SJonas Devlieghere }; 241*eb5c0ea6SJonas Devlieghere #endif 24263dd5d25SJonas Devlieghere } // namespace 2432c1f46dcSZachary Turner 2442df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple( 2452df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 2462df331b0SPavel Labath auto style = llvm::sys::path::Style::posix; 2472df331b0SPavel Labath 2482df331b0SPavel Labath llvm::StringRef path_ref(path.begin(), path.size()); 2492df331b0SPavel Labath auto rbegin = llvm::sys::path::rbegin(path_ref, style); 2502df331b0SPavel Labath auto rend = llvm::sys::path::rend(path_ref); 2512df331b0SPavel Labath auto framework = std::find(rbegin, rend, "LLDB.framework"); 2522df331b0SPavel Labath if (framework == rend) { 25361f471a7SHaibo Huang ComputePythonDir(path); 2542df331b0SPavel Labath return; 2552df331b0SPavel Labath } 2562df331b0SPavel Labath path.resize(framework - rend); 2572df331b0SPavel Labath llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python"); 2582df331b0SPavel Labath } 2592df331b0SPavel Labath 26061f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir( 2612df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 2622df331b0SPavel Labath // Build the path by backing out of the lib dir, then building with whatever 2632df331b0SPavel Labath // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL 26461f471a7SHaibo Huang // x86_64, or bin on Windows). 26561f471a7SHaibo Huang llvm::sys::path::remove_filename(path); 26661f471a7SHaibo Huang llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR); 2670016b450SHaibo Huang 2680016b450SHaibo Huang #if defined(_WIN32) 2690016b450SHaibo Huang // This will be injected directly through FileSpec.GetDirectory().SetString(), 2700016b450SHaibo Huang // so we need to normalize manually. 2710016b450SHaibo Huang std::replace(path.begin(), path.end(), '\\', '/'); 2720016b450SHaibo Huang #endif 2732df331b0SPavel Labath } 2742df331b0SPavel Labath 2752df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() { 2762df331b0SPavel Labath static FileSpec g_spec = []() { 2772df331b0SPavel Labath FileSpec spec = HostInfo::GetShlibDir(); 2782df331b0SPavel Labath if (!spec) 2792df331b0SPavel Labath return FileSpec(); 2802df331b0SPavel Labath llvm::SmallString<64> path; 2812df331b0SPavel Labath spec.GetPath(path); 2822df331b0SPavel Labath 2832df331b0SPavel Labath #if defined(__APPLE__) 2842df331b0SPavel Labath ComputePythonDirForApple(path); 2852df331b0SPavel Labath #else 28661f471a7SHaibo Huang ComputePythonDir(path); 2872df331b0SPavel Labath #endif 2882df331b0SPavel Labath spec.GetDirectory().SetString(path); 2892df331b0SPavel Labath return spec; 2902df331b0SPavel Labath }(); 2912df331b0SPavel Labath return g_spec; 2922df331b0SPavel Labath } 2932df331b0SPavel Labath 2944c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"( 2954c2cf3a3SLawrence D'Anna import os 2964c2cf3a3SLawrence D'Anna import sys 2974c2cf3a3SLawrence D'Anna 2984c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path): 2994c2cf3a3SLawrence D'Anna info = { 3004c2cf3a3SLawrence D'Anna "lldb-pythonpath": lldb_python_dir, 3014c2cf3a3SLawrence D'Anna "language": "python", 3024c2cf3a3SLawrence D'Anna "prefix": sys.prefix, 3034c2cf3a3SLawrence D'Anna "executable": os.path.join(sys.prefix, python_exe_relative_path) 3044c2cf3a3SLawrence D'Anna } 3054c2cf3a3SLawrence D'Anna return info 3064c2cf3a3SLawrence D'Anna )"; 3074c2cf3a3SLawrence D'Anna 3084c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH; 3094c2cf3a3SLawrence D'Anna 310bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() { 311bbef51ebSLawrence D'Anna GIL gil; 312bbef51ebSLawrence D'Anna FileSpec python_dir_spec = GetPythonDir(); 313bbef51ebSLawrence D'Anna if (!python_dir_spec) 314bbef51ebSLawrence D'Anna return nullptr; 3154c2cf3a3SLawrence D'Anna PythonScript get_info(GetInterpreterInfoScript); 3164c2cf3a3SLawrence D'Anna auto info_json = unwrapIgnoringErrors( 3174c2cf3a3SLawrence D'Anna As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()), 3184c2cf3a3SLawrence D'Anna PythonString(python_exe_relative_path)))); 319bbef51ebSLawrence D'Anna if (!info_json) 320bbef51ebSLawrence D'Anna return nullptr; 321bbef51ebSLawrence D'Anna return info_json.CreateStructuredDictionary(); 322bbef51ebSLawrence D'Anna } 323bbef51ebSLawrence D'Anna 324004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper( 325004a264fSPavel Labath FileSpec &this_file) { 326004a264fSPavel Labath // When we're loaded from python, this_file will point to the file inside the 327004a264fSPavel Labath // python package directory. Replace it with the one in the lib directory. 328004a264fSPavel Labath #ifdef _WIN32 329004a264fSPavel Labath // On windows, we need to manually back out of the python tree, and go into 330004a264fSPavel Labath // the bin directory. This is pretty much the inverse of what ComputePythonDir 331004a264fSPavel Labath // does. 332004a264fSPavel Labath if (this_file.GetFileNameExtension() == ConstString(".pyd")) { 333004a264fSPavel Labath this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd 334004a264fSPavel Labath this_file.RemoveLastPathComponent(); // lldb 3352e826088SPavel Labath llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR; 3362e826088SPavel Labath for (auto it = llvm::sys::path::begin(libdir), 3372e826088SPavel Labath end = llvm::sys::path::end(libdir); 338004a264fSPavel Labath it != end; ++it) 339004a264fSPavel Labath this_file.RemoveLastPathComponent(); 340004a264fSPavel Labath this_file.AppendPathComponent("bin"); 341004a264fSPavel Labath this_file.AppendPathComponent("liblldb.dll"); 342004a264fSPavel Labath } 343004a264fSPavel Labath #else 344004a264fSPavel Labath // The python file is a symlink, so we can find the real library by resolving 345004a264fSPavel Labath // it. We can do this unconditionally. 346004a264fSPavel Labath FileSystem::Instance().ResolveSymbolicLink(this_file, this_file); 347004a264fSPavel Labath #endif 348004a264fSPavel Labath } 349004a264fSPavel Labath 3505f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() { 35163dd5d25SJonas Devlieghere return "Embedded Python interpreter"; 35263dd5d25SJonas Devlieghere } 35363dd5d25SJonas Devlieghere 35463dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() { 35563dd5d25SJonas Devlieghere static llvm::once_flag g_once_flag; 35663dd5d25SJonas Devlieghere llvm::call_once(g_once_flag, []() { 35763dd5d25SJonas Devlieghere PluginManager::RegisterPlugin(GetPluginNameStatic(), 35863dd5d25SJonas Devlieghere GetPluginDescriptionStatic(), 35963dd5d25SJonas Devlieghere lldb::eScriptLanguagePython, 36063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance); 361*eb5c0ea6SJonas Devlieghere ScriptInterpreterPythonImpl::Initialize(); 36263dd5d25SJonas Devlieghere }); 36363dd5d25SJonas Devlieghere } 36463dd5d25SJonas Devlieghere 36563dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {} 36663dd5d25SJonas Devlieghere 36763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker( 36863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, 369b07823f3SLawrence D'Anna uint16_t on_leave, FileSP in, FileSP out, FileSP err) 37063dd5d25SJonas Devlieghere : ScriptInterpreterLocker(), 37163dd5d25SJonas Devlieghere m_teardown_session((on_leave & TearDownSession) == TearDownSession), 37263dd5d25SJonas Devlieghere m_python_interpreter(py_interpreter) { 37363dd5d25SJonas Devlieghere DoAcquireLock(); 37463dd5d25SJonas Devlieghere if ((on_entry & InitSession) == InitSession) { 37563dd5d25SJonas Devlieghere if (!DoInitSession(on_entry, in, out, err)) { 37663dd5d25SJonas Devlieghere // Don't teardown the session if we didn't init it. 37763dd5d25SJonas Devlieghere m_teardown_session = false; 37863dd5d25SJonas Devlieghere } 37963dd5d25SJonas Devlieghere } 38063dd5d25SJonas Devlieghere } 38163dd5d25SJonas Devlieghere 38263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { 38363dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 38463dd5d25SJonas Devlieghere m_GILState = PyGILState_Ensure(); 38563dd5d25SJonas Devlieghere LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", 38663dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 38763dd5d25SJonas Devlieghere 38863dd5d25SJonas Devlieghere // we need to save the thread state when we first start the command because 38963dd5d25SJonas Devlieghere // we might decide to interrupt it while some action is taking place outside 39063dd5d25SJonas Devlieghere // of Python (e.g. printing to screen, waiting for the network, ...) in that 39163dd5d25SJonas Devlieghere // case, _PyThreadState_Current will be NULL - and we would be unable to set 39263dd5d25SJonas Devlieghere // the asynchronous exception - not a desirable situation 39363dd5d25SJonas Devlieghere m_python_interpreter->SetThreadState(PyThreadState_Get()); 39463dd5d25SJonas Devlieghere m_python_interpreter->IncrementLockCount(); 39563dd5d25SJonas Devlieghere return true; 39663dd5d25SJonas Devlieghere } 39763dd5d25SJonas Devlieghere 39863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, 399b07823f3SLawrence D'Anna FileSP in, FileSP out, 400b07823f3SLawrence D'Anna FileSP err) { 40163dd5d25SJonas Devlieghere if (!m_python_interpreter) 40263dd5d25SJonas Devlieghere return false; 40363dd5d25SJonas Devlieghere return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); 40463dd5d25SJonas Devlieghere } 40563dd5d25SJonas Devlieghere 40663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { 40763dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 40863dd5d25SJonas Devlieghere LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 40963dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 41063dd5d25SJonas Devlieghere PyGILState_Release(m_GILState); 41163dd5d25SJonas Devlieghere m_python_interpreter->DecrementLockCount(); 41263dd5d25SJonas Devlieghere return true; 41363dd5d25SJonas Devlieghere } 41463dd5d25SJonas Devlieghere 41563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { 41663dd5d25SJonas Devlieghere if (!m_python_interpreter) 41763dd5d25SJonas Devlieghere return false; 41863dd5d25SJonas Devlieghere m_python_interpreter->LeaveSession(); 41963dd5d25SJonas Devlieghere return true; 42063dd5d25SJonas Devlieghere } 42163dd5d25SJonas Devlieghere 42263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() { 42363dd5d25SJonas Devlieghere if (m_teardown_session) 42463dd5d25SJonas Devlieghere DoTearDownSession(); 42563dd5d25SJonas Devlieghere DoFreeLock(); 42663dd5d25SJonas Devlieghere } 42763dd5d25SJonas Devlieghere 4288d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) 4298d1fb843SJonas Devlieghere : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), 43063dd5d25SJonas Devlieghere m_saved_stderr(), m_main_module(), 43163dd5d25SJonas Devlieghere m_session_dict(PyInitialValue::Invalid), 43263dd5d25SJonas Devlieghere m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), 43363dd5d25SJonas Devlieghere m_run_one_line_str_global(), 4348d1fb843SJonas Devlieghere m_dictionary_name(m_debugger.GetInstanceName().AsCString()), 435ea1752a7SJonas Devlieghere m_active_io_handler(eIOHandlerNone), m_session_is_active(false), 43664ec505dSJonas Devlieghere m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0), 437ea1752a7SJonas Devlieghere m_command_thread_state(nullptr) { 4381f6a57c1SMed Ismail Bennani m_scripted_process_interface_up = 4391f6a57c1SMed Ismail Bennani std::make_unique<ScriptedProcessPythonInterface>(*this); 4401f6a57c1SMed Ismail Bennani 44163dd5d25SJonas Devlieghere m_dictionary_name.append("_dict"); 44263dd5d25SJonas Devlieghere StreamString run_string; 44363dd5d25SJonas Devlieghere run_string.Printf("%s = dict()", m_dictionary_name.c_str()); 44463dd5d25SJonas Devlieghere 44563dd5d25SJonas Devlieghere Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 44663dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 44763dd5d25SJonas Devlieghere 44863dd5d25SJonas Devlieghere run_string.Clear(); 44963dd5d25SJonas Devlieghere run_string.Printf( 45063dd5d25SJonas Devlieghere "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", 45163dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 45263dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 45363dd5d25SJonas Devlieghere 45463dd5d25SJonas Devlieghere // Reloading modules requires a different syntax in Python 2 and Python 3. 45563dd5d25SJonas Devlieghere // This provides a consistent syntax no matter what version of Python. 45663dd5d25SJonas Devlieghere run_string.Clear(); 45763dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", 45863dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 45963dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 46063dd5d25SJonas Devlieghere 46163dd5d25SJonas Devlieghere // WARNING: temporary code that loads Cocoa formatters - this should be done 46263dd5d25SJonas Devlieghere // on a per-platform basis rather than loading the whole set and letting the 46363dd5d25SJonas Devlieghere // individual formatter classes exploit APIs to check whether they can/cannot 46463dd5d25SJonas Devlieghere // do their task 46563dd5d25SJonas Devlieghere run_string.Clear(); 46663dd5d25SJonas Devlieghere run_string.Printf( 46763dd5d25SJonas Devlieghere "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", 46863dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 46963dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 47063dd5d25SJonas Devlieghere run_string.Clear(); 47163dd5d25SJonas Devlieghere 47263dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " 47363dd5d25SJonas Devlieghere "lldb.embedded_interpreter import run_python_interpreter; " 47463dd5d25SJonas Devlieghere "from lldb.embedded_interpreter import run_one_line')", 47563dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 47663dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 47763dd5d25SJonas Devlieghere run_string.Clear(); 47863dd5d25SJonas Devlieghere 47963dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 48063dd5d25SJonas Devlieghere "; pydoc.pager = pydoc.plainpager')", 4818d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 48263dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 48363dd5d25SJonas Devlieghere } 48463dd5d25SJonas Devlieghere 48563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { 48663dd5d25SJonas Devlieghere // the session dictionary may hold objects with complex state which means 48763dd5d25SJonas Devlieghere // that they may need to be torn down with some level of smarts and that, in 48863dd5d25SJonas Devlieghere // turn, requires a valid thread state force Python to procure itself such a 48963dd5d25SJonas Devlieghere // thread state, nuke the session dictionary and then release it for others 49063dd5d25SJonas Devlieghere // to use and proceed with the rest of the shutdown 49163dd5d25SJonas Devlieghere auto gil_state = PyGILState_Ensure(); 49263dd5d25SJonas Devlieghere m_session_dict.Reset(); 49363dd5d25SJonas Devlieghere PyGILState_Release(gil_state); 49463dd5d25SJonas Devlieghere } 49563dd5d25SJonas Devlieghere 49663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, 49763dd5d25SJonas Devlieghere bool interactive) { 4982c1f46dcSZachary Turner const char *instructions = nullptr; 4992c1f46dcSZachary Turner 500b9c1b51eSKate Stone switch (m_active_io_handler) { 5012c1f46dcSZachary Turner case eIOHandlerNone: 5022c1f46dcSZachary Turner break; 5032c1f46dcSZachary Turner case eIOHandlerBreakpoint: 5042c1f46dcSZachary Turner instructions = R"(Enter your Python command(s). Type 'DONE' to end. 5052c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict): 5062c1f46dcSZachary Turner """frame: the lldb.SBFrame for the location at which you stopped 5072c1f46dcSZachary Turner bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 5082c1f46dcSZachary Turner internal_dict: an LLDB support object not to be used""" 5092c1f46dcSZachary Turner )"; 5102c1f46dcSZachary Turner break; 5112c1f46dcSZachary Turner case eIOHandlerWatchpoint: 5122c1f46dcSZachary Turner instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 5132c1f46dcSZachary Turner break; 5142c1f46dcSZachary Turner } 5152c1f46dcSZachary Turner 516b9c1b51eSKate Stone if (instructions) { 5177ca15ba7SLawrence D'Anna StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); 5180affb582SDave Lee if (output_sp && interactive) { 5192c1f46dcSZachary Turner output_sp->PutCString(instructions); 5202c1f46dcSZachary Turner output_sp->Flush(); 5212c1f46dcSZachary Turner } 5222c1f46dcSZachary Turner } 5232c1f46dcSZachary Turner } 5242c1f46dcSZachary Turner 52563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, 526b9c1b51eSKate Stone std::string &data) { 5272c1f46dcSZachary Turner io_handler.SetIsDone(true); 5288d1fb843SJonas Devlieghere bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); 5292c1f46dcSZachary Turner 530b9c1b51eSKate Stone switch (m_active_io_handler) { 5312c1f46dcSZachary Turner case eIOHandlerNone: 5322c1f46dcSZachary Turner break; 533b9c1b51eSKate Stone case eIOHandlerBreakpoint: { 534cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec = 535cfb96d84SJim Ingham (std::vector<std::reference_wrapper<BreakpointOptions>> *) 536cfb96d84SJim Ingham io_handler.GetUserData(); 537cfb96d84SJim Ingham for (BreakpointOptions &bp_options : *bp_options_vec) { 5382c1f46dcSZachary Turner 539a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<CommandDataPython>(); 540d5b44036SJonas Devlieghere if (!data_up) 5414e4fbe82SZachary Turner break; 542d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 5432c1f46dcSZachary Turner 544738af7a6SJim Ingham StructuredData::ObjectSP empty_args_sp; 545d5b44036SJonas Devlieghere if (GenerateBreakpointCommandCallbackData(data_up->user_source, 546738af7a6SJim Ingham data_up->script_source, 547738af7a6SJim Ingham false) 548b9c1b51eSKate Stone .Success()) { 5494e4fbe82SZachary Turner auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( 550d5b44036SJonas Devlieghere std::move(data_up)); 551cfb96d84SJim Ingham bp_options.SetCallback( 55263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 553b9c1b51eSKate Stone } else if (!batch_mode) { 5547ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 555b9c1b51eSKate Stone if (error_sp) { 5562c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5572c1f46dcSZachary Turner error_sp->Flush(); 5582c1f46dcSZachary Turner } 5592c1f46dcSZachary Turner } 5602c1f46dcSZachary Turner } 5612c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 562b9c1b51eSKate Stone } break; 563b9c1b51eSKate Stone case eIOHandlerWatchpoint: { 564b9c1b51eSKate Stone WatchpointOptions *wp_options = 565b9c1b51eSKate Stone (WatchpointOptions *)io_handler.GetUserData(); 566a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 567d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 5682c1f46dcSZachary Turner 569d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 570d5b44036SJonas Devlieghere data_up->script_source)) { 5714e4fbe82SZachary Turner auto baton_sp = 572d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 573b9c1b51eSKate Stone wp_options->SetCallback( 57463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 575b9c1b51eSKate Stone } else if (!batch_mode) { 5767ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 577b9c1b51eSKate Stone if (error_sp) { 5782c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5792c1f46dcSZachary Turner error_sp->Flush(); 5802c1f46dcSZachary Turner } 5812c1f46dcSZachary Turner } 5822c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 583b9c1b51eSKate Stone } break; 5842c1f46dcSZachary Turner } 5852c1f46dcSZachary Turner } 5862c1f46dcSZachary Turner 58763dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP 5888d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { 5898d1fb843SJonas Devlieghere return std::make_shared<ScriptInterpreterPythonImpl>(debugger); 59063dd5d25SJonas Devlieghere } 5912c1f46dcSZachary Turner 59263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() { 5932c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 5942c1f46dcSZachary Turner if (log) 59563dd5d25SJonas Devlieghere log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); 5962c1f46dcSZachary Turner 59720b52c33SJonas Devlieghere // Unset the LLDB global variables. 59820b52c33SJonas Devlieghere PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process " 59920b52c33SJonas Devlieghere "= None; lldb.thread = None; lldb.frame = None"); 60020b52c33SJonas Devlieghere 60105097246SAdrian Prantl // checking that we have a valid thread state - since we use our own 60205097246SAdrian Prantl // threading and locking in some (rare) cases during cleanup Python may end 60305097246SAdrian Prantl // up believing we have no thread state and PyImport_AddModule will crash if 60405097246SAdrian Prantl // that is the case - since that seems to only happen when destroying the 60505097246SAdrian Prantl // SBDebugger, we can make do without clearing up stdout and stderr 6062c1f46dcSZachary Turner 6072c1f46dcSZachary Turner // rdar://problem/11292882 608b9c1b51eSKate Stone // When the current thread state is NULL, PyThreadState_Get() issues a fatal 609b9c1b51eSKate Stone // error. 610b9c1b51eSKate Stone if (PyThreadState_GetDict()) { 6112c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 612b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 613b9c1b51eSKate Stone if (m_saved_stdin.IsValid()) { 614f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 6152c1f46dcSZachary Turner m_saved_stdin.Reset(); 6162c1f46dcSZachary Turner } 617b9c1b51eSKate Stone if (m_saved_stdout.IsValid()) { 618f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 6192c1f46dcSZachary Turner m_saved_stdout.Reset(); 6202c1f46dcSZachary Turner } 621b9c1b51eSKate Stone if (m_saved_stderr.IsValid()) { 622f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 6232c1f46dcSZachary Turner m_saved_stderr.Reset(); 6242c1f46dcSZachary Turner } 6252c1f46dcSZachary Turner } 6262c1f46dcSZachary Turner } 6272c1f46dcSZachary Turner 6282c1f46dcSZachary Turner m_session_is_active = false; 6292c1f46dcSZachary Turner } 6302c1f46dcSZachary Turner 631b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp, 632b07823f3SLawrence D'Anna const char *py_name, 633b07823f3SLawrence D'Anna PythonObject &save_file, 634b9c1b51eSKate Stone const char *mode) { 635b07823f3SLawrence D'Anna if (!file_sp || !*file_sp) { 636b07823f3SLawrence D'Anna save_file.Reset(); 637b07823f3SLawrence D'Anna return false; 638b07823f3SLawrence D'Anna } 639b07823f3SLawrence D'Anna File &file = *file_sp; 640b07823f3SLawrence D'Anna 641a31baf08SGreg Clayton // Flush the file before giving it to python to avoid interleaved output. 642a31baf08SGreg Clayton file.Flush(); 643a31baf08SGreg Clayton 644a31baf08SGreg Clayton PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 645a31baf08SGreg Clayton 6460f783599SLawrence D'Anna auto new_file = PythonFile::FromFile(file, mode); 6470f783599SLawrence D'Anna if (!new_file) { 6480f783599SLawrence D'Anna llvm::consumeError(new_file.takeError()); 6490f783599SLawrence D'Anna return false; 6500f783599SLawrence D'Anna } 6510f783599SLawrence D'Anna 652b07823f3SLawrence D'Anna save_file = sys_module_dict.GetItemForKey(PythonString(py_name)); 653a31baf08SGreg Clayton 6540f783599SLawrence D'Anna sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get()); 655a31baf08SGreg Clayton return true; 656a31baf08SGreg Clayton } 657a31baf08SGreg Clayton 65863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, 659b07823f3SLawrence D'Anna FileSP in_sp, FileSP out_sp, 660b07823f3SLawrence D'Anna FileSP err_sp) { 661b9c1b51eSKate Stone // If we have already entered the session, without having officially 'left' 66205097246SAdrian Prantl // it, then there is no need to 'enter' it again. 6632c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 664b9c1b51eSKate Stone if (m_session_is_active) { 66563e5fb76SJonas Devlieghere LLDB_LOGF( 66663e5fb76SJonas Devlieghere log, 66763dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 668b9c1b51eSKate Stone ") session is already active, returning without doing anything", 669b9c1b51eSKate Stone on_entry_flags); 6702c1f46dcSZachary Turner return false; 6712c1f46dcSZachary Turner } 6722c1f46dcSZachary Turner 67363e5fb76SJonas Devlieghere LLDB_LOGF( 67463e5fb76SJonas Devlieghere log, 67563e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")", 676b9c1b51eSKate Stone on_entry_flags); 6772c1f46dcSZachary Turner 6782c1f46dcSZachary Turner m_session_is_active = true; 6792c1f46dcSZachary Turner 6802c1f46dcSZachary Turner StreamString run_string; 6812c1f46dcSZachary Turner 682b9c1b51eSKate Stone if (on_entry_flags & Locker::InitGlobals) { 683b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 6848d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 685b9c1b51eSKate Stone run_string.Printf( 686b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 6878d1fb843SJonas Devlieghere m_debugger.GetID()); 6882c1f46dcSZachary Turner run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); 6892c1f46dcSZachary Turner run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); 6902c1f46dcSZachary Turner run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); 6912c1f46dcSZachary Turner run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 6922c1f46dcSZachary Turner run_string.PutCString("')"); 693b9c1b51eSKate Stone } else { 69405097246SAdrian Prantl // If we aren't initing the globals, we should still always set the 69505097246SAdrian Prantl // debugger (since that is always unique.) 696b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 6978d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 698b9c1b51eSKate Stone run_string.Printf( 699b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 7008d1fb843SJonas Devlieghere m_debugger.GetID()); 7012c1f46dcSZachary Turner run_string.PutCString("')"); 7022c1f46dcSZachary Turner } 7032c1f46dcSZachary Turner 7042c1f46dcSZachary Turner PyRun_SimpleString(run_string.GetData()); 7052c1f46dcSZachary Turner run_string.Clear(); 7062c1f46dcSZachary Turner 7072c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 708b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 709b07823f3SLawrence D'Anna lldb::FileSP top_in_sp; 710b07823f3SLawrence D'Anna lldb::StreamFileSP top_out_sp, top_err_sp; 711b07823f3SLawrence D'Anna if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp) 712b07823f3SLawrence D'Anna m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp, 713b07823f3SLawrence D'Anna top_err_sp); 7142c1f46dcSZachary Turner 715b9c1b51eSKate Stone if (on_entry_flags & Locker::NoSTDIN) { 7162c1f46dcSZachary Turner m_saved_stdin.Reset(); 717b9c1b51eSKate Stone } else { 718b07823f3SLawrence D'Anna if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) { 719b07823f3SLawrence D'Anna if (top_in_sp) 720b07823f3SLawrence D'Anna SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r"); 7212c1f46dcSZachary Turner } 722a31baf08SGreg Clayton } 723a31baf08SGreg Clayton 724b07823f3SLawrence D'Anna if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) { 725b07823f3SLawrence D'Anna if (top_out_sp) 726b07823f3SLawrence D'Anna SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w"); 727a31baf08SGreg Clayton } 728a31baf08SGreg Clayton 729b07823f3SLawrence D'Anna if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) { 730b07823f3SLawrence D'Anna if (top_err_sp) 731b07823f3SLawrence D'Anna SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w"); 732a31baf08SGreg Clayton } 7332c1f46dcSZachary Turner } 7342c1f46dcSZachary Turner 7352c1f46dcSZachary Turner if (PyErr_Occurred()) 7362c1f46dcSZachary Turner PyErr_Clear(); 7372c1f46dcSZachary Turner 7382c1f46dcSZachary Turner return true; 7392c1f46dcSZachary Turner } 7402c1f46dcSZachary Turner 74104edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() { 742f8b22f8fSZachary Turner if (!m_main_module.IsValid()) 74304edd189SLawrence D'Anna m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__")); 7442c1f46dcSZachary Turner return m_main_module; 7452c1f46dcSZachary Turner } 7462c1f46dcSZachary Turner 74763dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { 748f8b22f8fSZachary Turner if (m_session_dict.IsValid()) 749f8b22f8fSZachary Turner return m_session_dict; 750f8b22f8fSZachary Turner 7512c1f46dcSZachary Turner PythonObject &main_module = GetMainModule(); 752f8b22f8fSZachary Turner if (!main_module.IsValid()) 753f8b22f8fSZachary Turner return m_session_dict; 754f8b22f8fSZachary Turner 755b9c1b51eSKate Stone PythonDictionary main_dict(PyRefType::Borrowed, 756b9c1b51eSKate Stone PyModule_GetDict(main_module.get())); 757f8b22f8fSZachary Turner if (!main_dict.IsValid()) 758f8b22f8fSZachary Turner return m_session_dict; 759f8b22f8fSZachary Turner 760722b6189SLawrence D'Anna m_session_dict = unwrapIgnoringErrors( 761722b6189SLawrence D'Anna As<PythonDictionary>(main_dict.GetItem(m_dictionary_name))); 7622c1f46dcSZachary Turner return m_session_dict; 7632c1f46dcSZachary Turner } 7642c1f46dcSZachary Turner 76563dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { 766f8b22f8fSZachary Turner if (m_sys_module_dict.IsValid()) 767f8b22f8fSZachary Turner return m_sys_module_dict; 768722b6189SLawrence D'Anna PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys")); 769722b6189SLawrence D'Anna m_sys_module_dict = sys_module.GetDictionary(); 7702c1f46dcSZachary Turner return m_sys_module_dict; 7712c1f46dcSZachary Turner } 7722c1f46dcSZachary Turner 773a69bbe02SLawrence D'Anna llvm::Expected<unsigned> 774a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable( 775a69bbe02SLawrence D'Anna const llvm::StringRef &callable_name) { 776738af7a6SJim Ingham if (callable_name.empty()) { 777738af7a6SJim Ingham return llvm::createStringError( 778738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 779738af7a6SJim Ingham "called with empty callable name."); 780738af7a6SJim Ingham } 781738af7a6SJim Ingham Locker py_lock(this, Locker::AcquireLock | 782738af7a6SJim Ingham Locker::InitSession | 783738af7a6SJim Ingham Locker::NoSTDIN); 784738af7a6SJim Ingham auto dict = PythonModule::MainModule() 785738af7a6SJim Ingham .ResolveName<PythonDictionary>(m_dictionary_name); 786a69bbe02SLawrence D'Anna auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>( 787a69bbe02SLawrence D'Anna callable_name, dict); 788738af7a6SJim Ingham if (!pfunc.IsAllocated()) { 789738af7a6SJim Ingham return llvm::createStringError( 790738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 791738af7a6SJim Ingham "can't find callable: %s", callable_name.str().c_str()); 792738af7a6SJim Ingham } 793adbf64ccSLawrence D'Anna llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo(); 794adbf64ccSLawrence D'Anna if (!arg_info) 795adbf64ccSLawrence D'Anna return arg_info.takeError(); 796adbf64ccSLawrence D'Anna return arg_info.get().max_positional_args; 797738af7a6SJim Ingham } 798738af7a6SJim Ingham 799b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted, 8002c1f46dcSZachary Turner uint32_t &functions_counter, 801b9c1b51eSKate Stone const void *name_token = nullptr) { 8022c1f46dcSZachary Turner StreamString sstr; 8032c1f46dcSZachary Turner 8042c1f46dcSZachary Turner if (!base_name_wanted) 8052c1f46dcSZachary Turner return std::string(); 8062c1f46dcSZachary Turner 8072c1f46dcSZachary Turner if (!name_token) 8082c1f46dcSZachary Turner sstr.Printf("%s_%d", base_name_wanted, functions_counter++); 8092c1f46dcSZachary Turner else 8102c1f46dcSZachary Turner sstr.Printf("%s_%p", base_name_wanted, name_token); 8112c1f46dcSZachary Turner 812adcd0268SBenjamin Kramer return std::string(sstr.GetString()); 8132c1f46dcSZachary Turner } 8142c1f46dcSZachary Turner 81563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { 816f8b22f8fSZachary Turner if (m_run_one_line_function.IsValid()) 817f8b22f8fSZachary Turner return true; 818f8b22f8fSZachary Turner 819b9c1b51eSKate Stone PythonObject module(PyRefType::Borrowed, 820b9c1b51eSKate Stone PyImport_AddModule("lldb.embedded_interpreter")); 821f8b22f8fSZachary Turner if (!module.IsValid()) 822f8b22f8fSZachary Turner return false; 823f8b22f8fSZachary Turner 824b9c1b51eSKate Stone PythonDictionary module_dict(PyRefType::Borrowed, 825b9c1b51eSKate Stone PyModule_GetDict(module.get())); 826f8b22f8fSZachary Turner if (!module_dict.IsValid()) 827f8b22f8fSZachary Turner return false; 828f8b22f8fSZachary Turner 829b9c1b51eSKate Stone m_run_one_line_function = 830b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("run_one_line")); 831b9c1b51eSKate Stone m_run_one_line_str_global = 832b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 833f8b22f8fSZachary Turner return m_run_one_line_function.IsValid(); 8342c1f46dcSZachary Turner } 8352c1f46dcSZachary Turner 83663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine( 8374d51a902SRaphael Isemann llvm::StringRef command, CommandReturnObject *result, 838b9c1b51eSKate Stone const ExecuteScriptOptions &options) { 839d6c062bcSRaphael Isemann std::string command_str = command.str(); 840d6c062bcSRaphael Isemann 8412c1f46dcSZachary Turner if (!m_valid_session) 8422c1f46dcSZachary Turner return false; 8432c1f46dcSZachary Turner 8444d51a902SRaphael Isemann if (!command.empty()) { 845b9c1b51eSKate Stone // We want to call run_one_line, passing in the dictionary and the command 84605097246SAdrian Prantl // string. We cannot do this through PyRun_SimpleString here because the 84705097246SAdrian Prantl // command string may contain escaped characters, and putting it inside 848b9c1b51eSKate Stone // another string to pass to PyRun_SimpleString messes up the escaping. So 84905097246SAdrian Prantl // we use the following more complicated method to pass the command string 85005097246SAdrian Prantl // directly down to Python. 851d79273c9SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 85284228365SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 85384228365SJonas Devlieghere options.GetEnableIO(), m_debugger, result); 854d79273c9SJonas Devlieghere if (!io_redirect_or_error) { 855d79273c9SJonas Devlieghere if (result) 856d79273c9SJonas Devlieghere result->AppendErrorWithFormatv( 857d79273c9SJonas Devlieghere "failed to redirect I/O: {0}\n", 858d79273c9SJonas Devlieghere llvm::fmt_consume(io_redirect_or_error.takeError())); 859d79273c9SJonas Devlieghere else 860d79273c9SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError()); 8612fce1137SLawrence D'Anna return false; 8622fce1137SLawrence D'Anna } 863d79273c9SJonas Devlieghere 864d79273c9SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 8652c1f46dcSZachary Turner 86632064024SZachary Turner bool success = false; 86732064024SZachary Turner { 86805097246SAdrian Prantl // WARNING! It's imperative that this RAII scope be as tight as 86905097246SAdrian Prantl // possible. In particular, the scope must end *before* we try to join 87005097246SAdrian Prantl // the read thread. The reason for this is that a pre-requisite for 87105097246SAdrian Prantl // joining the read thread is that we close the write handle (to break 87205097246SAdrian Prantl // the pipe and cause it to wake up and exit). But acquiring the GIL as 87305097246SAdrian Prantl // below will redirect Python's stdio to use this same handle. If we 87405097246SAdrian Prantl // close the handle while Python is still using it, bad things will 87505097246SAdrian Prantl // happen. 876b9c1b51eSKate Stone Locker locker( 877b9c1b51eSKate Stone this, 87863dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 87963dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 8802c1f46dcSZachary Turner ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), 881d79273c9SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 882d79273c9SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 883d79273c9SJonas Devlieghere io_redirect.GetErrorFile()); 8842c1f46dcSZachary Turner 8852c1f46dcSZachary Turner // Find the correct script interpreter dictionary in the main module. 8862c1f46dcSZachary Turner PythonDictionary &session_dict = GetSessionDictionary(); 887b9c1b51eSKate Stone if (session_dict.IsValid()) { 888b9c1b51eSKate Stone if (GetEmbeddedInterpreterModuleObjects()) { 889b9c1b51eSKate Stone if (PyCallable_Check(m_run_one_line_function.get())) { 890b9c1b51eSKate Stone PythonObject pargs( 891b9c1b51eSKate Stone PyRefType::Owned, 892d6c062bcSRaphael Isemann Py_BuildValue("(Os)", session_dict.get(), command_str.c_str())); 893b9c1b51eSKate Stone if (pargs.IsValid()) { 894b9c1b51eSKate Stone PythonObject return_value( 895b9c1b51eSKate Stone PyRefType::Owned, 896b9c1b51eSKate Stone PyObject_CallObject(m_run_one_line_function.get(), 897b9c1b51eSKate Stone pargs.get())); 898f8b22f8fSZachary Turner if (return_value.IsValid()) 8992c1f46dcSZachary Turner success = true; 900b9c1b51eSKate Stone else if (options.GetMaskoutErrors() && PyErr_Occurred()) { 9012c1f46dcSZachary Turner PyErr_Print(); 9022c1f46dcSZachary Turner PyErr_Clear(); 9032c1f46dcSZachary Turner } 9042c1f46dcSZachary Turner } 9052c1f46dcSZachary Turner } 9062c1f46dcSZachary Turner } 9072c1f46dcSZachary Turner } 9082c1f46dcSZachary Turner 909d79273c9SJonas Devlieghere io_redirect.Flush(); 9102c1f46dcSZachary Turner } 9112c1f46dcSZachary Turner 9122c1f46dcSZachary Turner if (success) 9132c1f46dcSZachary Turner return true; 9142c1f46dcSZachary Turner 9152c1f46dcSZachary Turner // The one-liner failed. Append the error message. 9164d51a902SRaphael Isemann if (result) { 917b9c1b51eSKate Stone result->AppendErrorWithFormat( 9184d51a902SRaphael Isemann "python failed attempting to evaluate '%s'\n", command_str.c_str()); 9194d51a902SRaphael Isemann } 9202c1f46dcSZachary Turner return false; 9212c1f46dcSZachary Turner } 9222c1f46dcSZachary Turner 9232c1f46dcSZachary Turner if (result) 9242c1f46dcSZachary Turner result->AppendError("empty command passed to python\n"); 9252c1f46dcSZachary Turner return false; 9262c1f46dcSZachary Turner } 9272c1f46dcSZachary Turner 92863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { 9295c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 9302c1f46dcSZachary Turner 9318d1fb843SJonas Devlieghere Debugger &debugger = m_debugger; 9322c1f46dcSZachary Turner 933b9c1b51eSKate Stone // At the moment, the only time the debugger does not have an input file 93405097246SAdrian Prantl // handle is when this is called directly from Python, in which case it is 93505097246SAdrian Prantl // both dangerous and unnecessary (not to mention confusing) to try to embed 93605097246SAdrian Prantl // a running interpreter loop inside the already running Python interpreter 93705097246SAdrian Prantl // loop, so we won't do it. 9382c1f46dcSZachary Turner 9397ca15ba7SLawrence D'Anna if (!debugger.GetInputFile().IsValid()) 9402c1f46dcSZachary Turner return; 9412c1f46dcSZachary Turner 9422c1f46dcSZachary Turner IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this)); 943b9c1b51eSKate Stone if (io_handler_sp) { 9447ce2de2cSJonas Devlieghere debugger.RunIOHandlerAsync(io_handler_sp); 9452c1f46dcSZachary Turner } 9462c1f46dcSZachary Turner } 9472c1f46dcSZachary Turner 94863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() { 949049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 950049ae930SJonas Devlieghere // If the interpreter isn't evaluating any Python at the moment then return 951049ae930SJonas Devlieghere // false to signal that this function didn't handle the interrupt and the 952049ae930SJonas Devlieghere // next component should try handling it. 953049ae930SJonas Devlieghere if (!IsExecutingPython()) 954049ae930SJonas Devlieghere return false; 955049ae930SJonas Devlieghere 956049ae930SJonas Devlieghere // Tell Python that it should pretend to have received a SIGINT. 957049ae930SJonas Devlieghere PyErr_SetInterrupt(); 958049ae930SJonas Devlieghere // PyErr_SetInterrupt has no way to return an error so we can only pretend the 959049ae930SJonas Devlieghere // signal got successfully handled and return true. 960049ae930SJonas Devlieghere // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but 961049ae930SJonas Devlieghere // the error handling is limited to checking the arguments which would be 962049ae930SJonas Devlieghere // just our (hardcoded) input signal code SIGINT, so that's not useful at all. 963049ae930SJonas Devlieghere return true; 964049ae930SJonas Devlieghere #else 9652c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 9662c1f46dcSZachary Turner 967b9c1b51eSKate Stone if (IsExecutingPython()) { 968b1cf558dSEnrico Granata PyThreadState *state = PyThreadState_GET(); 9692c1f46dcSZachary Turner if (!state) 9702c1f46dcSZachary Turner state = GetThreadState(); 971b9c1b51eSKate Stone if (state) { 9722c1f46dcSZachary Turner long tid = state->thread_id; 97322c8efcdSZachary Turner PyThreadState_Swap(state); 9742c1f46dcSZachary Turner int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 97563e5fb76SJonas Devlieghere LLDB_LOGF(log, 97663e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() sending " 977b9c1b51eSKate Stone "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", 978b9c1b51eSKate Stone tid, num_threads); 9792c1f46dcSZachary Turner return true; 9802c1f46dcSZachary Turner } 9812c1f46dcSZachary Turner } 98263e5fb76SJonas Devlieghere LLDB_LOGF(log, 98363dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() python code not running, " 984b9c1b51eSKate Stone "can't interrupt"); 9852c1f46dcSZachary Turner return false; 986049ae930SJonas Devlieghere #endif 9872c1f46dcSZachary Turner } 98804edd189SLawrence D'Anna 98963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( 9904d51a902SRaphael Isemann llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, 991b9c1b51eSKate Stone void *ret_value, const ExecuteScriptOptions &options) { 9922c1f46dcSZachary Turner 993f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 994f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 995f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr); 996f9517353SJonas Devlieghere 997f9517353SJonas Devlieghere if (!io_redirect_or_error) { 998f9517353SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError()); 999f9517353SJonas Devlieghere return false; 1000f9517353SJonas Devlieghere } 1001f9517353SJonas Devlieghere 1002f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 1003f9517353SJonas Devlieghere 100463dd5d25SJonas Devlieghere Locker locker(this, 100563dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 100663dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1007b9c1b51eSKate Stone Locker::NoSTDIN, 1008f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 1009f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 1010f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 10112c1f46dcSZachary Turner 101204edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 101304edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 10142c1f46dcSZachary Turner 10152c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 101604edd189SLawrence D'Anna if (!locals.IsValid()) 1017722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1018722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1019f8b22f8fSZachary Turner if (!locals.IsValid()) 10202c1f46dcSZachary Turner locals = globals; 10212c1f46dcSZachary Turner 102204edd189SLawrence D'Anna Expected<PythonObject> maybe_py_return = 102304edd189SLawrence D'Anna runStringOneLine(in_string, globals, locals); 10242c1f46dcSZachary Turner 102504edd189SLawrence D'Anna if (!maybe_py_return) { 102604edd189SLawrence D'Anna llvm::handleAllErrors( 102704edd189SLawrence D'Anna maybe_py_return.takeError(), 102804edd189SLawrence D'Anna [&](PythonException &E) { 102904edd189SLawrence D'Anna E.Restore(); 103004edd189SLawrence D'Anna if (options.GetMaskoutErrors()) { 103104edd189SLawrence D'Anna if (E.Matches(PyExc_SyntaxError)) { 103204edd189SLawrence D'Anna PyErr_Print(); 10332c1f46dcSZachary Turner } 103404edd189SLawrence D'Anna PyErr_Clear(); 103504edd189SLawrence D'Anna } 103604edd189SLawrence D'Anna }, 103704edd189SLawrence D'Anna [](const llvm::ErrorInfoBase &E) {}); 103804edd189SLawrence D'Anna return false; 10392c1f46dcSZachary Turner } 10402c1f46dcSZachary Turner 104104edd189SLawrence D'Anna PythonObject py_return = std::move(maybe_py_return.get()); 104204edd189SLawrence D'Anna assert(py_return.IsValid()); 104304edd189SLawrence D'Anna 1044b9c1b51eSKate Stone switch (return_type) { 10452c1f46dcSZachary Turner case eScriptReturnTypeCharPtr: // "char *" 10462c1f46dcSZachary Turner { 10472c1f46dcSZachary Turner const char format[3] = "s#"; 104804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 10492c1f46dcSZachary Turner } 1050b9c1b51eSKate Stone case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == 1051b9c1b51eSKate Stone // Py_None 10522c1f46dcSZachary Turner { 10532c1f46dcSZachary Turner const char format[3] = "z"; 105404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 10552c1f46dcSZachary Turner } 1056b9c1b51eSKate Stone case eScriptReturnTypeBool: { 10572c1f46dcSZachary Turner const char format[2] = "b"; 105804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (bool *)ret_value); 10592c1f46dcSZachary Turner } 1060b9c1b51eSKate Stone case eScriptReturnTypeShortInt: { 10612c1f46dcSZachary Turner const char format[2] = "h"; 106204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (short *)ret_value); 10632c1f46dcSZachary Turner } 1064b9c1b51eSKate Stone case eScriptReturnTypeShortIntUnsigned: { 10652c1f46dcSZachary Turner const char format[2] = "H"; 106604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value); 10672c1f46dcSZachary Turner } 1068b9c1b51eSKate Stone case eScriptReturnTypeInt: { 10692c1f46dcSZachary Turner const char format[2] = "i"; 107004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (int *)ret_value); 10712c1f46dcSZachary Turner } 1072b9c1b51eSKate Stone case eScriptReturnTypeIntUnsigned: { 10732c1f46dcSZachary Turner const char format[2] = "I"; 107404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value); 10752c1f46dcSZachary Turner } 1076b9c1b51eSKate Stone case eScriptReturnTypeLongInt: { 10772c1f46dcSZachary Turner const char format[2] = "l"; 107804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long *)ret_value); 10792c1f46dcSZachary Turner } 1080b9c1b51eSKate Stone case eScriptReturnTypeLongIntUnsigned: { 10812c1f46dcSZachary Turner const char format[2] = "k"; 108204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value); 10832c1f46dcSZachary Turner } 1084b9c1b51eSKate Stone case eScriptReturnTypeLongLong: { 10852c1f46dcSZachary Turner const char format[2] = "L"; 108604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long long *)ret_value); 10872c1f46dcSZachary Turner } 1088b9c1b51eSKate Stone case eScriptReturnTypeLongLongUnsigned: { 10892c1f46dcSZachary Turner const char format[2] = "K"; 109004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, 109104edd189SLawrence D'Anna (unsigned long long *)ret_value); 10922c1f46dcSZachary Turner } 1093b9c1b51eSKate Stone case eScriptReturnTypeFloat: { 10942c1f46dcSZachary Turner const char format[2] = "f"; 109504edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (float *)ret_value); 10962c1f46dcSZachary Turner } 1097b9c1b51eSKate Stone case eScriptReturnTypeDouble: { 10982c1f46dcSZachary Turner const char format[2] = "d"; 109904edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (double *)ret_value); 11002c1f46dcSZachary Turner } 1101b9c1b51eSKate Stone case eScriptReturnTypeChar: { 11022c1f46dcSZachary Turner const char format[2] = "c"; 110304edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char *)ret_value); 11042c1f46dcSZachary Turner } 1105b9c1b51eSKate Stone case eScriptReturnTypeOpaqueObject: { 110604edd189SLawrence D'Anna *((PyObject **)ret_value) = py_return.release(); 110704edd189SLawrence D'Anna return true; 11082c1f46dcSZachary Turner } 11092c1f46dcSZachary Turner } 11101dfb1a85SPavel Labath llvm_unreachable("Fully covered switch!"); 11112c1f46dcSZachary Turner } 11122c1f46dcSZachary Turner 111363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( 1114b9c1b51eSKate Stone const char *in_string, const ExecuteScriptOptions &options) { 111504edd189SLawrence D'Anna 111604edd189SLawrence D'Anna if (in_string == nullptr) 111704edd189SLawrence D'Anna return Status(); 11182c1f46dcSZachary Turner 1119f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 1120f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 1121f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr); 1122f9517353SJonas Devlieghere 1123f9517353SJonas Devlieghere if (!io_redirect_or_error) 1124f9517353SJonas Devlieghere return Status(io_redirect_or_error.takeError()); 1125f9517353SJonas Devlieghere 1126f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 1127f9517353SJonas Devlieghere 112863dd5d25SJonas Devlieghere Locker locker(this, 112963dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 113063dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1131b9c1b51eSKate Stone Locker::NoSTDIN, 1132f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 1133f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 1134f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 11352c1f46dcSZachary Turner 113604edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 113704edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 11382c1f46dcSZachary Turner 11392c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 1140f8b22f8fSZachary Turner if (!locals.IsValid()) 1141722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1142722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1143f8b22f8fSZachary Turner if (!locals.IsValid()) 11442c1f46dcSZachary Turner locals = globals; 11452c1f46dcSZachary Turner 114604edd189SLawrence D'Anna Expected<PythonObject> return_value = 114704edd189SLawrence D'Anna runStringMultiLine(in_string, globals, locals); 11482c1f46dcSZachary Turner 114904edd189SLawrence D'Anna if (!return_value) { 115004edd189SLawrence D'Anna llvm::Error error = 115104edd189SLawrence D'Anna llvm::handleErrors(return_value.takeError(), [&](PythonException &E) { 115204edd189SLawrence D'Anna llvm::Error error = llvm::createStringError( 115304edd189SLawrence D'Anna llvm::inconvertibleErrorCode(), E.ReadBacktrace()); 115404edd189SLawrence D'Anna if (!options.GetMaskoutErrors()) 115504edd189SLawrence D'Anna E.Restore(); 11562c1f46dcSZachary Turner return error; 115704edd189SLawrence D'Anna }); 115804edd189SLawrence D'Anna return Status(std::move(error)); 115904edd189SLawrence D'Anna } 116004edd189SLawrence D'Anna 116104edd189SLawrence D'Anna return Status(); 11622c1f46dcSZachary Turner } 11632c1f46dcSZachary Turner 116463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( 1165cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, 1166b9c1b51eSKate Stone CommandReturnObject &result) { 11672c1f46dcSZachary Turner m_active_io_handler = eIOHandlerBreakpoint; 11688d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1169a6faf851SJonas Devlieghere " ", *this, &bp_options_vec); 11702c1f46dcSZachary Turner } 11712c1f46dcSZachary Turner 117263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( 1173b9c1b51eSKate Stone WatchpointOptions *wp_options, CommandReturnObject &result) { 11742c1f46dcSZachary Turner m_active_io_handler = eIOHandlerWatchpoint; 11758d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1176a6faf851SJonas Devlieghere " ", *this, wp_options); 11772c1f46dcSZachary Turner } 11782c1f46dcSZachary Turner 1179738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( 1180cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *function_name, 1181738af7a6SJim Ingham StructuredData::ObjectSP extra_args_sp) { 1182738af7a6SJim Ingham Status error; 11832c1f46dcSZachary Turner // For now just cons up a oneliner that calls the provided function. 11842c1f46dcSZachary Turner std::string oneliner("return "); 11852c1f46dcSZachary Turner oneliner += function_name; 1186738af7a6SJim Ingham 1187a69bbe02SLawrence D'Anna llvm::Expected<unsigned> maybe_args = 1188a69bbe02SLawrence D'Anna GetMaxPositionalArgumentsForCallable(function_name); 1189738af7a6SJim Ingham if (!maybe_args) { 1190a69bbe02SLawrence D'Anna error.SetErrorStringWithFormat( 1191a69bbe02SLawrence D'Anna "could not get num args: %s", 1192738af7a6SJim Ingham llvm::toString(maybe_args.takeError()).c_str()); 1193738af7a6SJim Ingham return error; 1194738af7a6SJim Ingham } 1195a69bbe02SLawrence D'Anna size_t max_args = *maybe_args; 1196738af7a6SJim Ingham 1197738af7a6SJim Ingham bool uses_extra_args = false; 1198a69bbe02SLawrence D'Anna if (max_args >= 4) { 1199738af7a6SJim Ingham uses_extra_args = true; 1200738af7a6SJim Ingham oneliner += "(frame, bp_loc, extra_args, internal_dict)"; 1201a69bbe02SLawrence D'Anna } else if (max_args >= 3) { 1202738af7a6SJim Ingham if (extra_args_sp) { 1203738af7a6SJim Ingham error.SetErrorString("cannot pass extra_args to a three argument callback" 1204738af7a6SJim Ingham ); 1205738af7a6SJim Ingham return error; 1206738af7a6SJim Ingham } 1207738af7a6SJim Ingham uses_extra_args = false; 12082c1f46dcSZachary Turner oneliner += "(frame, bp_loc, internal_dict)"; 1209738af7a6SJim Ingham } else { 1210738af7a6SJim Ingham error.SetErrorStringWithFormat("expected 3 or 4 argument " 1211a69bbe02SLawrence D'Anna "function, %s can only take %zu", 1212a69bbe02SLawrence D'Anna function_name, max_args); 1213738af7a6SJim Ingham return error; 1214738af7a6SJim Ingham } 1215738af7a6SJim Ingham 1216738af7a6SJim Ingham SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp, 1217738af7a6SJim Ingham uses_extra_args); 1218738af7a6SJim Ingham return error; 12192c1f46dcSZachary Turner } 12202c1f46dcSZachary Turner 122163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1222cfb96d84SJim Ingham BreakpointOptions &bp_options, 1223f7e07256SJim Ingham std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { 122497206d57SZachary Turner Status error; 1225f7e07256SJim Ingham error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, 1226738af7a6SJim Ingham cmd_data_up->script_source, 1227738af7a6SJim Ingham false); 1228f7e07256SJim Ingham if (error.Fail()) { 1229f7e07256SJim Ingham return error; 1230f7e07256SJim Ingham } 1231f7e07256SJim Ingham auto baton_sp = 1232f7e07256SJim Ingham std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); 1233cfb96d84SJim Ingham bp_options.SetCallback( 123463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 1235f7e07256SJim Ingham return error; 1236f7e07256SJim Ingham } 1237f7e07256SJim Ingham 123863dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1239cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text) { 1240738af7a6SJim Ingham return SetBreakpointCommandCallback(bp_options, command_body_text, {},false); 1241738af7a6SJim Ingham } 12422c1f46dcSZachary Turner 1243738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint. 1244738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1245cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text, 1246cfb96d84SJim Ingham StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) { 1247738af7a6SJim Ingham auto data_up = std::make_unique<CommandDataPython>(extra_args_sp); 1248b9c1b51eSKate Stone // Split the command_body_text into lines, and pass that to 124905097246SAdrian Prantl // GenerateBreakpointCommandCallbackData. That will wrap the body in an 125005097246SAdrian Prantl // auto-generated function, and return the function name in script_source. 125105097246SAdrian Prantl // That is what the callback will actually invoke. 12522c1f46dcSZachary Turner 1253d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(command_body_text); 1254d5b44036SJonas Devlieghere Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, 1255738af7a6SJim Ingham data_up->script_source, 1256738af7a6SJim Ingham uses_extra_args); 1257b9c1b51eSKate Stone if (error.Success()) { 12584e4fbe82SZachary Turner auto baton_sp = 1259d5b44036SJonas Devlieghere std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 1260cfb96d84SJim Ingham bp_options.SetCallback( 126163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 12622c1f46dcSZachary Turner return error; 126393571c3cSJonas Devlieghere } 12642c1f46dcSZachary Turner return error; 12652c1f46dcSZachary Turner } 12662c1f46dcSZachary Turner 12672c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint. 126863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( 1269b9c1b51eSKate Stone WatchpointOptions *wp_options, const char *oneliner) { 1270a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 12712c1f46dcSZachary Turner 12722c1f46dcSZachary Turner // It's necessary to set both user_source and script_source to the oneliner. 1273b9c1b51eSKate Stone // The former is used to generate callback description (as in watchpoint 127405097246SAdrian Prantl // command list) while the latter is used for Python to interpret during the 127505097246SAdrian Prantl // actual callback. 12762c1f46dcSZachary Turner 1277d5b44036SJonas Devlieghere data_up->user_source.AppendString(oneliner); 1278d5b44036SJonas Devlieghere data_up->script_source.assign(oneliner); 12792c1f46dcSZachary Turner 1280d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 1281d5b44036SJonas Devlieghere data_up->script_source)) { 12824e4fbe82SZachary Turner auto baton_sp = 1283d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 128463dd5d25SJonas Devlieghere wp_options->SetCallback( 128563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 12862c1f46dcSZachary Turner } 12872c1f46dcSZachary Turner 12882c1f46dcSZachary Turner return; 12892c1f46dcSZachary Turner } 12902c1f46dcSZachary Turner 129163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( 1292b9c1b51eSKate Stone StringList &function_def) { 12932c1f46dcSZachary Turner // Convert StringList to one long, newline delimited, const char *. 12942c1f46dcSZachary Turner std::string function_def_string(function_def.CopyList()); 12952c1f46dcSZachary Turner 129697206d57SZachary Turner Status error = ExecuteMultipleLines( 1297b9c1b51eSKate Stone function_def_string.c_str(), 1298fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false)); 12992c1f46dcSZachary Turner return error; 13002c1f46dcSZachary Turner } 13012c1f46dcSZachary Turner 130263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, 1303b9c1b51eSKate Stone const StringList &input) { 130497206d57SZachary Turner Status error; 13052c1f46dcSZachary Turner int num_lines = input.GetSize(); 1306b9c1b51eSKate Stone if (num_lines == 0) { 13072c1f46dcSZachary Turner error.SetErrorString("No input data."); 13082c1f46dcSZachary Turner return error; 13092c1f46dcSZachary Turner } 13102c1f46dcSZachary Turner 1311b9c1b51eSKate Stone if (!signature || *signature == 0) { 13122c1f46dcSZachary Turner error.SetErrorString("No output function name."); 13132c1f46dcSZachary Turner return error; 13142c1f46dcSZachary Turner } 13152c1f46dcSZachary Turner 13162c1f46dcSZachary Turner StreamString sstr; 13172c1f46dcSZachary Turner StringList auto_generated_function; 13182c1f46dcSZachary Turner auto_generated_function.AppendString(signature); 1319b9c1b51eSKate Stone auto_generated_function.AppendString( 1320b9c1b51eSKate Stone " global_dict = globals()"); // Grab the global dictionary 1321b9c1b51eSKate Stone auto_generated_function.AppendString( 1322b9c1b51eSKate Stone " new_keys = internal_dict.keys()"); // Make a list of keys in the 1323b9c1b51eSKate Stone // session dict 1324b9c1b51eSKate Stone auto_generated_function.AppendString( 1325b9c1b51eSKate Stone " old_keys = global_dict.keys()"); // Save list of keys in global dict 1326b9c1b51eSKate Stone auto_generated_function.AppendString( 1327b9c1b51eSKate Stone " global_dict.update (internal_dict)"); // Add the session dictionary 1328b9c1b51eSKate Stone // to the 13292c1f46dcSZachary Turner // global dictionary. 13302c1f46dcSZachary Turner 13312c1f46dcSZachary Turner // Wrap everything up inside the function, increasing the indentation. 13322c1f46dcSZachary Turner 13332c1f46dcSZachary Turner auto_generated_function.AppendString(" if True:"); 1334b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 13352c1f46dcSZachary Turner sstr.Clear(); 13362c1f46dcSZachary Turner sstr.Printf(" %s", input.GetStringAtIndex(i)); 13372c1f46dcSZachary Turner auto_generated_function.AppendString(sstr.GetData()); 13382c1f46dcSZachary Turner } 1339b9c1b51eSKate Stone auto_generated_function.AppendString( 1340b9c1b51eSKate Stone " for key in new_keys:"); // Iterate over all the keys from session 1341b9c1b51eSKate Stone // dict 1342b9c1b51eSKate Stone auto_generated_function.AppendString( 1343b9c1b51eSKate Stone " internal_dict[key] = global_dict[key]"); // Update session dict 1344b9c1b51eSKate Stone // values 1345b9c1b51eSKate Stone auto_generated_function.AppendString( 1346b9c1b51eSKate Stone " if key not in old_keys:"); // If key was not originally in 1347b9c1b51eSKate Stone // global dict 1348b9c1b51eSKate Stone auto_generated_function.AppendString( 1349b9c1b51eSKate Stone " del global_dict[key]"); // ...then remove key/value from 1350b9c1b51eSKate Stone // global dict 13512c1f46dcSZachary Turner 13522c1f46dcSZachary Turner // Verify that the results are valid Python. 13532c1f46dcSZachary Turner 13542c1f46dcSZachary Turner error = ExportFunctionDefinitionToInterpreter(auto_generated_function); 13552c1f46dcSZachary Turner 13562c1f46dcSZachary Turner return error; 13572c1f46dcSZachary Turner } 13582c1f46dcSZachary Turner 135963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 1360b9c1b51eSKate Stone StringList &user_input, std::string &output, const void *name_token) { 13612c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 13622c1f46dcSZachary Turner user_input.RemoveBlankLines(); 13632c1f46dcSZachary Turner StreamString sstr; 13642c1f46dcSZachary Turner 13652c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 13662c1f46dcSZachary Turner if (user_input.GetSize() == 0) 13672c1f46dcSZachary Turner return false; 13682c1f46dcSZachary Turner 1369b9c1b51eSKate Stone // Take what the user wrote, wrap it all up inside one big auto-generated 137005097246SAdrian Prantl // Python function, passing in the ValueObject as parameter to the function. 13712c1f46dcSZachary Turner 1372b9c1b51eSKate Stone std::string auto_generated_function_name( 1373b9c1b51eSKate Stone GenerateUniqueName("lldb_autogen_python_type_print_func", 1374b9c1b51eSKate Stone num_created_functions, name_token)); 1375b9c1b51eSKate Stone sstr.Printf("def %s (valobj, internal_dict):", 1376b9c1b51eSKate Stone auto_generated_function_name.c_str()); 13772c1f46dcSZachary Turner 13782c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 13792c1f46dcSZachary Turner return false; 13802c1f46dcSZachary Turner 13812c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 13822c1f46dcSZachary Turner output.assign(auto_generated_function_name); 13832c1f46dcSZachary Turner return true; 13842c1f46dcSZachary Turner } 13852c1f46dcSZachary Turner 138663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( 1387b9c1b51eSKate Stone StringList &user_input, std::string &output) { 13882c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 13892c1f46dcSZachary Turner user_input.RemoveBlankLines(); 13902c1f46dcSZachary Turner StreamString sstr; 13912c1f46dcSZachary Turner 13922c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 13932c1f46dcSZachary Turner if (user_input.GetSize() == 0) 13942c1f46dcSZachary Turner return false; 13952c1f46dcSZachary Turner 1396b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 1397b9c1b51eSKate Stone "lldb_autogen_python_cmd_alias_func", num_created_functions)); 13982c1f46dcSZachary Turner 1399b9c1b51eSKate Stone sstr.Printf("def %s (debugger, args, result, internal_dict):", 1400b9c1b51eSKate Stone auto_generated_function_name.c_str()); 14012c1f46dcSZachary Turner 14022c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 14032c1f46dcSZachary Turner return false; 14042c1f46dcSZachary Turner 14052c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 14062c1f46dcSZachary Turner output.assign(auto_generated_function_name); 14072c1f46dcSZachary Turner return true; 14082c1f46dcSZachary Turner } 14092c1f46dcSZachary Turner 141063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 141163dd5d25SJonas Devlieghere StringList &user_input, std::string &output, const void *name_token) { 14122c1f46dcSZachary Turner static uint32_t num_created_classes = 0; 14132c1f46dcSZachary Turner user_input.RemoveBlankLines(); 14142c1f46dcSZachary Turner int num_lines = user_input.GetSize(); 14152c1f46dcSZachary Turner StreamString sstr; 14162c1f46dcSZachary Turner 14172c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 14182c1f46dcSZachary Turner if (user_input.GetSize() == 0) 14192c1f46dcSZachary Turner return false; 14202c1f46dcSZachary Turner 14212c1f46dcSZachary Turner // Wrap all user input into a Python class 14222c1f46dcSZachary Turner 1423b9c1b51eSKate Stone std::string auto_generated_class_name(GenerateUniqueName( 1424b9c1b51eSKate Stone "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); 14252c1f46dcSZachary Turner 14262c1f46dcSZachary Turner StringList auto_generated_class; 14272c1f46dcSZachary Turner 14282c1f46dcSZachary Turner // Create the function name & definition string. 14292c1f46dcSZachary Turner 14302c1f46dcSZachary Turner sstr.Printf("class %s:", auto_generated_class_name.c_str()); 1431c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 14322c1f46dcSZachary Turner 143305097246SAdrian Prantl // Wrap everything up inside the class, increasing the indentation. we don't 143405097246SAdrian Prantl // need to play any fancy indentation tricks here because there is no 14352c1f46dcSZachary Turner // surrounding code whose indentation we need to honor 1436b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 14372c1f46dcSZachary Turner sstr.Clear(); 14382c1f46dcSZachary Turner sstr.Printf(" %s", user_input.GetStringAtIndex(i)); 1439c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 14402c1f46dcSZachary Turner } 14412c1f46dcSZachary Turner 144205097246SAdrian Prantl // Verify that the results are valid Python. (even though the method is 144305097246SAdrian Prantl // ExportFunctionDefinitionToInterpreter, a class will actually be exported) 14442c1f46dcSZachary Turner // (TODO: rename that method to ExportDefinitionToInterpreter) 14452c1f46dcSZachary Turner if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) 14462c1f46dcSZachary Turner return false; 14472c1f46dcSZachary Turner 14482c1f46dcSZachary Turner // Store the name of the auto-generated class 14492c1f46dcSZachary Turner 14502c1f46dcSZachary Turner output.assign(auto_generated_class_name); 14512c1f46dcSZachary Turner return true; 14522c1f46dcSZachary Turner } 14532c1f46dcSZachary Turner 145463dd5d25SJonas Devlieghere StructuredData::GenericSP 145563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { 145641ae8e74SKuba Mracek if (class_name == nullptr || class_name[0] == '\0') 145741ae8e74SKuba Mracek return StructuredData::GenericSP(); 145841ae8e74SKuba Mracek 1459a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1460c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer( 1461a6598575SRalf Grosse-Kunstleve class_name, m_dictionary_name.c_str()); 146241ae8e74SKuba Mracek 1463c154f397SPavel Labath return StructuredData::GenericSP( 1464c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 146541ae8e74SKuba Mracek } 146641ae8e74SKuba Mracek 146763dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 146841ae8e74SKuba Mracek const StructuredData::ObjectSP &os_plugin_object_sp, 146941ae8e74SKuba Mracek lldb::StackFrameSP frame_sp) { 147041ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 147141ae8e74SKuba Mracek 147263dd5d25SJonas Devlieghere if (!os_plugin_object_sp) 147363dd5d25SJonas Devlieghere return ValueObjectListSP(); 147441ae8e74SKuba Mracek 147541ae8e74SKuba Mracek StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 147663dd5d25SJonas Devlieghere if (!generic) 147763dd5d25SJonas Devlieghere return nullptr; 147841ae8e74SKuba Mracek 147941ae8e74SKuba Mracek PythonObject implementor(PyRefType::Borrowed, 148041ae8e74SKuba Mracek (PyObject *)generic->GetValue()); 148141ae8e74SKuba Mracek 148263dd5d25SJonas Devlieghere if (!implementor.IsAllocated()) 148363dd5d25SJonas Devlieghere return ValueObjectListSP(); 148441ae8e74SKuba Mracek 14859a14adeaSPavel Labath PythonObject py_return( 14869a14adeaSPavel Labath PyRefType::Owned, 14879a14adeaSPavel Labath LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp)); 148841ae8e74SKuba Mracek 148941ae8e74SKuba Mracek // if it fails, print the error but otherwise go on 149041ae8e74SKuba Mracek if (PyErr_Occurred()) { 149141ae8e74SKuba Mracek PyErr_Print(); 149241ae8e74SKuba Mracek PyErr_Clear(); 149341ae8e74SKuba Mracek } 149441ae8e74SKuba Mracek if (py_return.get()) { 149541ae8e74SKuba Mracek PythonList result_list(PyRefType::Borrowed, py_return.get()); 149641ae8e74SKuba Mracek ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 14978f81aed1SDavid Bolvansky for (size_t i = 0; i < result_list.GetSize(); i++) { 149841ae8e74SKuba Mracek PyObject *item = result_list.GetItemAtIndex(i).get(); 149941ae8e74SKuba Mracek lldb::SBValue *sb_value_ptr = 150005495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 150105495c5dSJonas Devlieghere auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 150263dd5d25SJonas Devlieghere if (valobj_sp) 150363dd5d25SJonas Devlieghere result->Append(valobj_sp); 150441ae8e74SKuba Mracek } 150541ae8e74SKuba Mracek return result; 150641ae8e74SKuba Mracek } 150741ae8e74SKuba Mracek return ValueObjectListSP(); 150841ae8e74SKuba Mracek } 150941ae8e74SKuba Mracek 151063dd5d25SJonas Devlieghere StructuredData::GenericSP 151163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 1512b9c1b51eSKate Stone const char *class_name, lldb::ProcessSP process_sp) { 15132c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 15142c1f46dcSZachary Turner return StructuredData::GenericSP(); 15152c1f46dcSZachary Turner 15162c1f46dcSZachary Turner if (!process_sp) 15172c1f46dcSZachary Turner return StructuredData::GenericSP(); 15182c1f46dcSZachary Turner 1519a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1520c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin( 152105495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), process_sp); 15222c1f46dcSZachary Turner 1523c154f397SPavel Labath return StructuredData::GenericSP( 1524c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 15252c1f46dcSZachary Turner } 15262c1f46dcSZachary Turner 152763dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 1528b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1529b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15302c1f46dcSZachary Turner 15312c1f46dcSZachary Turner static char callee_name[] = "get_register_info"; 15322c1f46dcSZachary Turner 15332c1f46dcSZachary Turner if (!os_plugin_object_sp) 15342c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15352c1f46dcSZachary Turner 15362c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15372c1f46dcSZachary Turner if (!generic) 15382c1f46dcSZachary Turner return nullptr; 15392c1f46dcSZachary Turner 1540b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1541b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 15422c1f46dcSZachary Turner 1543f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15442c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15452c1f46dcSZachary Turner 1546b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1547b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 15482c1f46dcSZachary Turner 15492c1f46dcSZachary Turner if (PyErr_Occurred()) 15502c1f46dcSZachary Turner PyErr_Clear(); 15512c1f46dcSZachary Turner 1552f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 15532c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15542c1f46dcSZachary Turner 1555b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 15562c1f46dcSZachary Turner if (PyErr_Occurred()) 15572c1f46dcSZachary Turner PyErr_Clear(); 15582c1f46dcSZachary Turner 15592c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15602c1f46dcSZachary Turner } 15612c1f46dcSZachary Turner 15622c1f46dcSZachary Turner if (PyErr_Occurred()) 15632c1f46dcSZachary Turner PyErr_Clear(); 15642c1f46dcSZachary Turner 15652c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1566b9c1b51eSKate Stone PythonObject py_return( 1567b9c1b51eSKate Stone PyRefType::Owned, 1568b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 15692c1f46dcSZachary Turner 15702c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1571b9c1b51eSKate Stone if (PyErr_Occurred()) { 15722c1f46dcSZachary Turner PyErr_Print(); 15732c1f46dcSZachary Turner PyErr_Clear(); 15742c1f46dcSZachary Turner } 1575b9c1b51eSKate Stone if (py_return.get()) { 1576f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 15772c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 15782c1f46dcSZachary Turner } 157958b794aeSGreg Clayton return StructuredData::DictionarySP(); 158058b794aeSGreg Clayton } 15812c1f46dcSZachary Turner 158263dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 1583b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1584b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15852c1f46dcSZachary Turner 15862c1f46dcSZachary Turner static char callee_name[] = "get_thread_info"; 15872c1f46dcSZachary Turner 15882c1f46dcSZachary Turner if (!os_plugin_object_sp) 15892c1f46dcSZachary Turner return StructuredData::ArraySP(); 15902c1f46dcSZachary Turner 15912c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15922c1f46dcSZachary Turner if (!generic) 15932c1f46dcSZachary Turner return nullptr; 15942c1f46dcSZachary Turner 1595b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1596b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1597f8b22f8fSZachary Turner 1598f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15992c1f46dcSZachary Turner return StructuredData::ArraySP(); 16002c1f46dcSZachary Turner 1601b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1602b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16032c1f46dcSZachary Turner 16042c1f46dcSZachary Turner if (PyErr_Occurred()) 16052c1f46dcSZachary Turner PyErr_Clear(); 16062c1f46dcSZachary Turner 1607f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16082c1f46dcSZachary Turner return StructuredData::ArraySP(); 16092c1f46dcSZachary Turner 1610b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16112c1f46dcSZachary Turner if (PyErr_Occurred()) 16122c1f46dcSZachary Turner PyErr_Clear(); 16132c1f46dcSZachary Turner 16142c1f46dcSZachary Turner return StructuredData::ArraySP(); 16152c1f46dcSZachary Turner } 16162c1f46dcSZachary Turner 16172c1f46dcSZachary Turner if (PyErr_Occurred()) 16182c1f46dcSZachary Turner PyErr_Clear(); 16192c1f46dcSZachary Turner 16202c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1621b9c1b51eSKate Stone PythonObject py_return( 1622b9c1b51eSKate Stone PyRefType::Owned, 1623b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16242c1f46dcSZachary Turner 16252c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1626b9c1b51eSKate Stone if (PyErr_Occurred()) { 16272c1f46dcSZachary Turner PyErr_Print(); 16282c1f46dcSZachary Turner PyErr_Clear(); 16292c1f46dcSZachary Turner } 16302c1f46dcSZachary Turner 1631b9c1b51eSKate Stone if (py_return.get()) { 1632f8b22f8fSZachary Turner PythonList result_list(PyRefType::Borrowed, py_return.get()); 1633f8b22f8fSZachary Turner return result_list.CreateStructuredArray(); 16342c1f46dcSZachary Turner } 163558b794aeSGreg Clayton return StructuredData::ArraySP(); 163658b794aeSGreg Clayton } 16372c1f46dcSZachary Turner 163863dd5d25SJonas Devlieghere StructuredData::StringSP 163963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 1640b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 1641b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16422c1f46dcSZachary Turner 16432c1f46dcSZachary Turner static char callee_name[] = "get_register_data"; 1644b9c1b51eSKate Stone static char *param_format = 1645b9c1b51eSKate Stone const_cast<char *>(GetPythonValueFormatString(tid)); 16462c1f46dcSZachary Turner 16472c1f46dcSZachary Turner if (!os_plugin_object_sp) 16482c1f46dcSZachary Turner return StructuredData::StringSP(); 16492c1f46dcSZachary Turner 16502c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16512c1f46dcSZachary Turner if (!generic) 16522c1f46dcSZachary Turner return nullptr; 1653b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1654b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 16552c1f46dcSZachary Turner 1656f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16572c1f46dcSZachary Turner return StructuredData::StringSP(); 16582c1f46dcSZachary Turner 1659b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1660b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16612c1f46dcSZachary Turner 16622c1f46dcSZachary Turner if (PyErr_Occurred()) 16632c1f46dcSZachary Turner PyErr_Clear(); 16642c1f46dcSZachary Turner 1665f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16662c1f46dcSZachary Turner return StructuredData::StringSP(); 16672c1f46dcSZachary Turner 1668b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16692c1f46dcSZachary Turner if (PyErr_Occurred()) 16702c1f46dcSZachary Turner PyErr_Clear(); 16712c1f46dcSZachary Turner return StructuredData::StringSP(); 16722c1f46dcSZachary Turner } 16732c1f46dcSZachary Turner 16742c1f46dcSZachary Turner if (PyErr_Occurred()) 16752c1f46dcSZachary Turner PyErr_Clear(); 16762c1f46dcSZachary Turner 16772c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1678b9c1b51eSKate Stone PythonObject py_return( 1679b9c1b51eSKate Stone PyRefType::Owned, 1680b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 16812c1f46dcSZachary Turner 16822c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1683b9c1b51eSKate Stone if (PyErr_Occurred()) { 16842c1f46dcSZachary Turner PyErr_Print(); 16852c1f46dcSZachary Turner PyErr_Clear(); 16862c1f46dcSZachary Turner } 1687f8b22f8fSZachary Turner 1688b9c1b51eSKate Stone if (py_return.get()) { 16897a76845cSZachary Turner PythonBytes result(PyRefType::Borrowed, py_return.get()); 16907a76845cSZachary Turner return result.CreateStructuredString(); 16912c1f46dcSZachary Turner } 169258b794aeSGreg Clayton return StructuredData::StringSP(); 169358b794aeSGreg Clayton } 16942c1f46dcSZachary Turner 169563dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 1696b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 1697b9c1b51eSKate Stone lldb::addr_t context) { 1698b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16992c1f46dcSZachary Turner 17002c1f46dcSZachary Turner static char callee_name[] = "create_thread"; 17012c1f46dcSZachary Turner std::string param_format; 17022c1f46dcSZachary Turner param_format += GetPythonValueFormatString(tid); 17032c1f46dcSZachary Turner param_format += GetPythonValueFormatString(context); 17042c1f46dcSZachary Turner 17052c1f46dcSZachary Turner if (!os_plugin_object_sp) 17062c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17072c1f46dcSZachary Turner 17082c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 17092c1f46dcSZachary Turner if (!generic) 17102c1f46dcSZachary Turner return nullptr; 17112c1f46dcSZachary Turner 1712b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1713b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1714f8b22f8fSZachary Turner 1715f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 17162c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17172c1f46dcSZachary Turner 1718b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1719b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 17202c1f46dcSZachary Turner 17212c1f46dcSZachary Turner if (PyErr_Occurred()) 17222c1f46dcSZachary Turner PyErr_Clear(); 17232c1f46dcSZachary Turner 1724f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 17252c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17262c1f46dcSZachary Turner 1727b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 17282c1f46dcSZachary Turner if (PyErr_Occurred()) 17292c1f46dcSZachary Turner PyErr_Clear(); 17302c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17312c1f46dcSZachary Turner } 17322c1f46dcSZachary Turner 17332c1f46dcSZachary Turner if (PyErr_Occurred()) 17342c1f46dcSZachary Turner PyErr_Clear(); 17352c1f46dcSZachary Turner 17362c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1737b9c1b51eSKate Stone PythonObject py_return(PyRefType::Owned, 1738b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, 1739b9c1b51eSKate Stone ¶m_format[0], tid, context)); 17402c1f46dcSZachary Turner 17412c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1742b9c1b51eSKate Stone if (PyErr_Occurred()) { 17432c1f46dcSZachary Turner PyErr_Print(); 17442c1f46dcSZachary Turner PyErr_Clear(); 17452c1f46dcSZachary Turner } 17462c1f46dcSZachary Turner 1747b9c1b51eSKate Stone if (py_return.get()) { 1748f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 17492c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 17502c1f46dcSZachary Turner } 175158b794aeSGreg Clayton return StructuredData::DictionarySP(); 175258b794aeSGreg Clayton } 17532c1f46dcSZachary Turner 175463dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 175582de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 1756a69bbe02SLawrence D'Anna std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) { 17572c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 17582c1f46dcSZachary Turner return StructuredData::ObjectSP(); 17592c1f46dcSZachary Turner 17602c1f46dcSZachary Turner if (!thread_plan_sp.get()) 176193c98346SJim Ingham return {}; 17622c1f46dcSZachary Turner 17632c1f46dcSZachary Turner Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 176463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1765d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 17662c1f46dcSZachary Turner 1767d055e3a0SPedro Tammela if (!python_interpreter) 176893c98346SJim Ingham return {}; 17692c1f46dcSZachary Turner 1770b9c1b51eSKate Stone Locker py_lock(this, 1771b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1772c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 1773a6598575SRalf Grosse-Kunstleve class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 1774a6598575SRalf Grosse-Kunstleve error_str, thread_plan_sp); 177593c98346SJim Ingham if (!ret_val) 177693c98346SJim Ingham return {}; 17772c1f46dcSZachary Turner 1778c154f397SPavel Labath return StructuredData::ObjectSP( 1779c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 17802c1f46dcSZachary Turner } 17812c1f46dcSZachary Turner 178263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 1783b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 17842c1f46dcSZachary Turner bool explains_stop = true; 17852c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 17862c1f46dcSZachary Turner if (implementor_sp) 17872c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1788b9c1b51eSKate Stone if (generic) { 1789b9c1b51eSKate Stone Locker py_lock(this, 1790b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 179105495c5dSJonas Devlieghere explains_stop = LLDBSWIGPythonCallThreadPlan( 1792b9c1b51eSKate Stone generic->GetValue(), "explains_stop", event, script_error); 17932c1f46dcSZachary Turner if (script_error) 17942c1f46dcSZachary Turner return true; 17952c1f46dcSZachary Turner } 17962c1f46dcSZachary Turner return explains_stop; 17972c1f46dcSZachary Turner } 17982c1f46dcSZachary Turner 179963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 1800b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 18012c1f46dcSZachary Turner bool should_stop = true; 18022c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 18032c1f46dcSZachary Turner if (implementor_sp) 18042c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1805b9c1b51eSKate Stone if (generic) { 1806b9c1b51eSKate Stone Locker py_lock(this, 1807b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 180805495c5dSJonas Devlieghere should_stop = LLDBSWIGPythonCallThreadPlan( 180905495c5dSJonas Devlieghere generic->GetValue(), "should_stop", event, script_error); 18102c1f46dcSZachary Turner if (script_error) 18112c1f46dcSZachary Turner return true; 18122c1f46dcSZachary Turner } 18132c1f46dcSZachary Turner return should_stop; 18142c1f46dcSZachary Turner } 18152c1f46dcSZachary Turner 181663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 1817b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 1818c915a7d2SJim Ingham bool is_stale = true; 1819c915a7d2SJim Ingham StructuredData::Generic *generic = nullptr; 1820c915a7d2SJim Ingham if (implementor_sp) 1821c915a7d2SJim Ingham generic = implementor_sp->GetAsGeneric(); 1822b9c1b51eSKate Stone if (generic) { 1823b9c1b51eSKate Stone Locker py_lock(this, 1824b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 182505495c5dSJonas Devlieghere is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 182605495c5dSJonas Devlieghere nullptr, script_error); 1827c915a7d2SJim Ingham if (script_error) 1828c915a7d2SJim Ingham return true; 1829c915a7d2SJim Ingham } 1830c915a7d2SJim Ingham return is_stale; 1831c915a7d2SJim Ingham } 1832c915a7d2SJim Ingham 183363dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 1834b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 18352c1f46dcSZachary Turner bool should_step = false; 18362c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 18372c1f46dcSZachary Turner if (implementor_sp) 18382c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1839b9c1b51eSKate Stone if (generic) { 1840b9c1b51eSKate Stone Locker py_lock(this, 1841b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 184205495c5dSJonas Devlieghere should_step = LLDBSWIGPythonCallThreadPlan( 1843248a1305SKonrad Kleine generic->GetValue(), "should_step", nullptr, script_error); 18442c1f46dcSZachary Turner if (script_error) 18452c1f46dcSZachary Turner should_step = true; 18462c1f46dcSZachary Turner } 18472c1f46dcSZachary Turner if (should_step) 18482c1f46dcSZachary Turner return lldb::eStateStepping; 18492c1f46dcSZachary Turner return lldb::eStateRunning; 18502c1f46dcSZachary Turner } 18512c1f46dcSZachary Turner 18523815e702SJim Ingham StructuredData::GenericSP 185363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 185482de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 18553815e702SJim Ingham lldb::BreakpointSP &bkpt_sp) { 18563815e702SJim Ingham 18573815e702SJim Ingham if (class_name == nullptr || class_name[0] == '\0') 18583815e702SJim Ingham return StructuredData::GenericSP(); 18593815e702SJim Ingham 18603815e702SJim Ingham if (!bkpt_sp.get()) 18613815e702SJim Ingham return StructuredData::GenericSP(); 18623815e702SJim Ingham 18633815e702SJim Ingham Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 186463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1865d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 18663815e702SJim Ingham 1867d055e3a0SPedro Tammela if (!python_interpreter) 18683815e702SJim Ingham return StructuredData::GenericSP(); 18693815e702SJim Ingham 18703815e702SJim Ingham Locker py_lock(this, 18713815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 18723815e702SJim Ingham 1873c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 187405495c5dSJonas Devlieghere class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 187505495c5dSJonas Devlieghere bkpt_sp); 18763815e702SJim Ingham 1877c154f397SPavel Labath return StructuredData::GenericSP( 1878c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 18793815e702SJim Ingham } 18803815e702SJim Ingham 188163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 188263dd5d25SJonas Devlieghere StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 18833815e702SJim Ingham bool should_continue = false; 18843815e702SJim Ingham 18853815e702SJim Ingham if (implementor_sp) { 18863815e702SJim Ingham Locker py_lock(this, 18873815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 188805495c5dSJonas Devlieghere should_continue = LLDBSwigPythonCallBreakpointResolver( 188905495c5dSJonas Devlieghere implementor_sp->GetValue(), "__callback__", sym_ctx); 18903815e702SJim Ingham if (PyErr_Occurred()) { 18913815e702SJim Ingham PyErr_Print(); 18923815e702SJim Ingham PyErr_Clear(); 18933815e702SJim Ingham } 18943815e702SJim Ingham } 18953815e702SJim Ingham return should_continue; 18963815e702SJim Ingham } 18973815e702SJim Ingham 18983815e702SJim Ingham lldb::SearchDepth 189963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 19003815e702SJim Ingham StructuredData::GenericSP implementor_sp) { 19013815e702SJim Ingham int depth_as_int = lldb::eSearchDepthModule; 19023815e702SJim Ingham if (implementor_sp) { 19033815e702SJim Ingham Locker py_lock(this, 19043815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 190505495c5dSJonas Devlieghere depth_as_int = LLDBSwigPythonCallBreakpointResolver( 190605495c5dSJonas Devlieghere implementor_sp->GetValue(), "__get_depth__", nullptr); 19073815e702SJim Ingham if (PyErr_Occurred()) { 19083815e702SJim Ingham PyErr_Print(); 19093815e702SJim Ingham PyErr_Clear(); 19103815e702SJim Ingham } 19113815e702SJim Ingham } 19123815e702SJim Ingham if (depth_as_int == lldb::eSearchDepthInvalid) 19133815e702SJim Ingham return lldb::eSearchDepthModule; 19143815e702SJim Ingham 19153815e702SJim Ingham if (depth_as_int <= lldb::kLastSearchDepthKind) 19163815e702SJim Ingham return (lldb::SearchDepth)depth_as_int; 19173815e702SJim Ingham return lldb::eSearchDepthModule; 19183815e702SJim Ingham } 19193815e702SJim Ingham 19201b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook( 192182de8df2SPavel Labath TargetSP target_sp, const char *class_name, 192282de8df2SPavel Labath const StructuredDataImpl &args_data, Status &error) { 19231b1d9815SJim Ingham 19241b1d9815SJim Ingham if (!target_sp) { 19251b1d9815SJim Ingham error.SetErrorString("No target for scripted stop-hook."); 19261b1d9815SJim Ingham return StructuredData::GenericSP(); 19271b1d9815SJim Ingham } 19281b1d9815SJim Ingham 19291b1d9815SJim Ingham if (class_name == nullptr || class_name[0] == '\0') { 19301b1d9815SJim Ingham error.SetErrorString("No class name for scripted stop-hook."); 19311b1d9815SJim Ingham return StructuredData::GenericSP(); 19321b1d9815SJim Ingham } 19331b1d9815SJim Ingham 19341b1d9815SJim Ingham ScriptInterpreterPythonImpl *python_interpreter = 1935d055e3a0SPedro Tammela GetPythonInterpreter(m_debugger); 19361b1d9815SJim Ingham 1937d055e3a0SPedro Tammela if (!python_interpreter) { 19381b1d9815SJim Ingham error.SetErrorString("No script interpreter for scripted stop-hook."); 19391b1d9815SJim Ingham return StructuredData::GenericSP(); 19401b1d9815SJim Ingham } 19411b1d9815SJim Ingham 19421b1d9815SJim Ingham Locker py_lock(this, 19431b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19441b1d9815SJim Ingham 1945c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook( 19461b1d9815SJim Ingham target_sp, class_name, python_interpreter->m_dictionary_name.c_str(), 19471b1d9815SJim Ingham args_data, error); 19481b1d9815SJim Ingham 1949c154f397SPavel Labath return StructuredData::GenericSP( 1950c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 19511b1d9815SJim Ingham } 19521b1d9815SJim Ingham 19531b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop( 19541b1d9815SJim Ingham StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx, 19551b1d9815SJim Ingham lldb::StreamSP stream_sp) { 19561b1d9815SJim Ingham assert(implementor_sp && 19571b1d9815SJim Ingham "can't call a stop hook with an invalid implementor"); 19581b1d9815SJim Ingham assert(stream_sp && "can't call a stop hook with an invalid stream"); 19591b1d9815SJim Ingham 19601b1d9815SJim Ingham Locker py_lock(this, 19611b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19621b1d9815SJim Ingham 19631b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx)); 19641b1d9815SJim Ingham 19651b1d9815SJim Ingham bool ret_val = LLDBSwigPythonStopHookCallHandleStop( 19661b1d9815SJim Ingham implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp); 19671b1d9815SJim Ingham return ret_val; 19681b1d9815SJim Ingham } 19691b1d9815SJim Ingham 19702c1f46dcSZachary Turner StructuredData::ObjectSP 197163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 197297206d57SZachary Turner lldb_private::Status &error) { 1973dbd7fabaSJonas Devlieghere if (!FileSystem::Instance().Exists(file_spec)) { 19742c1f46dcSZachary Turner error.SetErrorString("no such file"); 19752c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19762c1f46dcSZachary Turner } 19772c1f46dcSZachary Turner 19782c1f46dcSZachary Turner StructuredData::ObjectSP module_sp; 19792c1f46dcSZachary Turner 1980f9517353SJonas Devlieghere LoadScriptOptions load_script_options = 1981f9517353SJonas Devlieghere LoadScriptOptions().SetInitSession(true).SetSilent(false); 1982f9517353SJonas Devlieghere if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options, 1983f9517353SJonas Devlieghere error, &module_sp)) 19842c1f46dcSZachary Turner return module_sp; 19852c1f46dcSZachary Turner 19862c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19872c1f46dcSZachary Turner } 19882c1f46dcSZachary Turner 198963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 1990b9c1b51eSKate Stone StructuredData::ObjectSP plugin_module_sp, Target *target, 199197206d57SZachary Turner const char *setting_name, lldb_private::Status &error) { 199205495c5dSJonas Devlieghere if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 19932c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19942c1f46dcSZachary Turner StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 19952c1f46dcSZachary Turner if (!generic) 19962c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19972c1f46dcSZachary Turner 1998b9c1b51eSKate Stone Locker py_lock(this, 1999b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20002c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 20012c1f46dcSZachary Turner 200204edd189SLawrence D'Anna auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting( 200304edd189SLawrence D'Anna generic->GetValue(), setting_name, target_sp); 200404edd189SLawrence D'Anna 200504edd189SLawrence D'Anna if (!setting) 200604edd189SLawrence D'Anna return StructuredData::DictionarySP(); 200704edd189SLawrence D'Anna 200804edd189SLawrence D'Anna PythonDictionary py_dict = 200904edd189SLawrence D'Anna unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); 201004edd189SLawrence D'Anna 201104edd189SLawrence D'Anna if (!py_dict) 201204edd189SLawrence D'Anna return StructuredData::DictionarySP(); 201304edd189SLawrence D'Anna 20142c1f46dcSZachary Turner return py_dict.CreateStructuredDictionary(); 20152c1f46dcSZachary Turner } 20162c1f46dcSZachary Turner 20172c1f46dcSZachary Turner StructuredData::ObjectSP 201863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 2019b9c1b51eSKate Stone const char *class_name, lldb::ValueObjectSP valobj) { 20202c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 20212c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20222c1f46dcSZachary Turner 20232c1f46dcSZachary Turner if (!valobj.get()) 20242c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20252c1f46dcSZachary Turner 20262c1f46dcSZachary Turner ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 20272c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 20282c1f46dcSZachary Turner 20292c1f46dcSZachary Turner if (!target) 20302c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20312c1f46dcSZachary Turner 20322c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 203363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2034d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 20352c1f46dcSZachary Turner 2036d055e3a0SPedro Tammela if (!python_interpreter) 20372c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20382c1f46dcSZachary Turner 2039b9c1b51eSKate Stone Locker py_lock(this, 2040b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2041c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider( 2042b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 20432c1f46dcSZachary Turner 2044c154f397SPavel Labath return StructuredData::ObjectSP( 2045c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 20462c1f46dcSZachary Turner } 20472c1f46dcSZachary Turner 20482c1f46dcSZachary Turner StructuredData::GenericSP 204963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 20508d1fb843SJonas Devlieghere DebuggerSP debugger_sp(m_debugger.shared_from_this()); 20512c1f46dcSZachary Turner 20522c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 20532c1f46dcSZachary Turner return StructuredData::GenericSP(); 20542c1f46dcSZachary Turner 20552c1f46dcSZachary Turner if (!debugger_sp.get()) 20562c1f46dcSZachary Turner return StructuredData::GenericSP(); 20572c1f46dcSZachary Turner 2058b9c1b51eSKate Stone Locker py_lock(this, 2059b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2060c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateCommandObject( 206105495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), debugger_sp); 20622c1f46dcSZachary Turner 2063c154f397SPavel Labath return StructuredData::GenericSP( 2064c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 20652c1f46dcSZachary Turner } 20662c1f46dcSZachary Turner 206763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 2068b9c1b51eSKate Stone const char *oneliner, std::string &output, const void *name_token) { 20692c1f46dcSZachary Turner StringList input; 20702c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20712c1f46dcSZachary Turner return GenerateTypeScriptFunction(input, output, name_token); 20722c1f46dcSZachary Turner } 20732c1f46dcSZachary Turner 207463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 207563dd5d25SJonas Devlieghere const char *oneliner, std::string &output, const void *name_token) { 20762c1f46dcSZachary Turner StringList input; 20772c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20782c1f46dcSZachary Turner return GenerateTypeSynthClass(input, output, name_token); 20792c1f46dcSZachary Turner } 20802c1f46dcSZachary Turner 208163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 2082738af7a6SJim Ingham StringList &user_input, std::string &output, 2083738af7a6SJim Ingham bool has_extra_args) { 20842c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 20852c1f46dcSZachary Turner user_input.RemoveBlankLines(); 20862c1f46dcSZachary Turner StreamString sstr; 208797206d57SZachary Turner Status error; 2088b9c1b51eSKate Stone if (user_input.GetSize() == 0) { 20892c1f46dcSZachary Turner error.SetErrorString("No input data."); 20902c1f46dcSZachary Turner return error; 20912c1f46dcSZachary Turner } 20922c1f46dcSZachary Turner 2093b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2094b9c1b51eSKate Stone "lldb_autogen_python_bp_callback_func_", num_created_functions)); 2095738af7a6SJim Ingham if (has_extra_args) 2096738af7a6SJim Ingham sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", 2097738af7a6SJim Ingham auto_generated_function_name.c_str()); 2098738af7a6SJim Ingham else 2099b9c1b51eSKate Stone sstr.Printf("def %s (frame, bp_loc, internal_dict):", 2100b9c1b51eSKate Stone auto_generated_function_name.c_str()); 21012c1f46dcSZachary Turner 21022c1f46dcSZachary Turner error = GenerateFunction(sstr.GetData(), user_input); 21032c1f46dcSZachary Turner if (!error.Success()) 21042c1f46dcSZachary Turner return error; 21052c1f46dcSZachary Turner 21062c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 21072c1f46dcSZachary Turner output.assign(auto_generated_function_name); 21082c1f46dcSZachary Turner return error; 21092c1f46dcSZachary Turner } 21102c1f46dcSZachary Turner 211163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 2112b9c1b51eSKate Stone StringList &user_input, std::string &output) { 21132c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 21142c1f46dcSZachary Turner user_input.RemoveBlankLines(); 21152c1f46dcSZachary Turner StreamString sstr; 21162c1f46dcSZachary Turner 21172c1f46dcSZachary Turner if (user_input.GetSize() == 0) 21182c1f46dcSZachary Turner return false; 21192c1f46dcSZachary Turner 2120b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2121b9c1b51eSKate Stone "lldb_autogen_python_wp_callback_func_", num_created_functions)); 2122b9c1b51eSKate Stone sstr.Printf("def %s (frame, wp, internal_dict):", 2123b9c1b51eSKate Stone auto_generated_function_name.c_str()); 21242c1f46dcSZachary Turner 21252c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 21262c1f46dcSZachary Turner return false; 21272c1f46dcSZachary Turner 21282c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 21292c1f46dcSZachary Turner output.assign(auto_generated_function_name); 21302c1f46dcSZachary Turner return true; 21312c1f46dcSZachary Turner } 21322c1f46dcSZachary Turner 213363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary( 2134b9c1b51eSKate Stone const char *python_function_name, lldb::ValueObjectSP valobj, 2135b9c1b51eSKate Stone StructuredData::ObjectSP &callee_wrapper_sp, 2136b9c1b51eSKate Stone const TypeSummaryOptions &options, std::string &retval) { 21372c1f46dcSZachary Turner 21385c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 21392c1f46dcSZachary Turner 2140b9c1b51eSKate Stone if (!valobj.get()) { 21412c1f46dcSZachary Turner retval.assign("<no object>"); 21422c1f46dcSZachary Turner return false; 21432c1f46dcSZachary Turner } 21442c1f46dcSZachary Turner 21452c1f46dcSZachary Turner void *old_callee = nullptr; 21462c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 2147b9c1b51eSKate Stone if (callee_wrapper_sp) { 21482c1f46dcSZachary Turner generic = callee_wrapper_sp->GetAsGeneric(); 21492c1f46dcSZachary Turner if (generic) 21502c1f46dcSZachary Turner old_callee = generic->GetValue(); 21512c1f46dcSZachary Turner } 21522c1f46dcSZachary Turner void *new_callee = old_callee; 21532c1f46dcSZachary Turner 21542c1f46dcSZachary Turner bool ret_val; 2155b9c1b51eSKate Stone if (python_function_name && *python_function_name) { 21562c1f46dcSZachary Turner { 2157b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 2158b9c1b51eSKate Stone Locker::NoSTDIN); 21592c1f46dcSZachary Turner { 21602c1f46dcSZachary Turner TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 21612c1f46dcSZachary Turner 216205495c5dSJonas Devlieghere static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 216305495c5dSJonas Devlieghere Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 216405495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallTypeScript( 2165b9c1b51eSKate Stone python_function_name, GetSessionDictionary().get(), valobj, 2166b9c1b51eSKate Stone &new_callee, options_sp, retval); 21672c1f46dcSZachary Turner } 21682c1f46dcSZachary Turner } 2169b9c1b51eSKate Stone } else { 21702c1f46dcSZachary Turner retval.assign("<no function name>"); 21712c1f46dcSZachary Turner return false; 21722c1f46dcSZachary Turner } 21732c1f46dcSZachary Turner 2174a6598575SRalf Grosse-Kunstleve if (new_callee && old_callee != new_callee) { 2175a6598575SRalf Grosse-Kunstleve Locker py_lock(this, 2176a6598575SRalf Grosse-Kunstleve Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2177c154f397SPavel Labath callee_wrapper_sp = std::make_shared<StructuredPythonObject>( 2178c154f397SPavel Labath PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee))); 2179a6598575SRalf Grosse-Kunstleve } 21802c1f46dcSZachary Turner 21812c1f46dcSZachary Turner return ret_val; 21822c1f46dcSZachary Turner } 21832c1f46dcSZachary Turner 218463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 2185b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t break_id, 2186b9c1b51eSKate Stone user_id_t break_loc_id) { 2187f7e07256SJim Ingham CommandDataPython *bp_option_data = (CommandDataPython *)baton; 21882c1f46dcSZachary Turner const char *python_function_name = bp_option_data->script_source.c_str(); 21892c1f46dcSZachary Turner 21902c1f46dcSZachary Turner if (!context) 21912c1f46dcSZachary Turner return true; 21922c1f46dcSZachary Turner 21932c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 21942c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 21952c1f46dcSZachary Turner 21962c1f46dcSZachary Turner if (!target) 21972c1f46dcSZachary Turner return true; 21982c1f46dcSZachary Turner 21992c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 220063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2201d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 22022c1f46dcSZachary Turner 2203d055e3a0SPedro Tammela if (!python_interpreter) 22042c1f46dcSZachary Turner return true; 22052c1f46dcSZachary Turner 2206b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 22072c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 22082c1f46dcSZachary Turner BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 2209b9c1b51eSKate Stone if (breakpoint_sp) { 2210b9c1b51eSKate Stone const BreakpointLocationSP bp_loc_sp( 2211b9c1b51eSKate Stone breakpoint_sp->FindLocationByID(break_loc_id)); 22122c1f46dcSZachary Turner 2213b9c1b51eSKate Stone if (stop_frame_sp && bp_loc_sp) { 22142c1f46dcSZachary Turner bool ret_val = true; 22152c1f46dcSZachary Turner { 2216b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2217b9c1b51eSKate Stone Locker::InitSession | 2218b9c1b51eSKate Stone Locker::NoSTDIN); 2219a69bbe02SLawrence D'Anna Expected<bool> maybe_ret_val = 2220a69bbe02SLawrence D'Anna LLDBSwigPythonBreakpointCallbackFunction( 2221b9c1b51eSKate Stone python_function_name, 2222b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 222382de8df2SPavel Labath bp_loc_sp, bp_option_data->m_extra_args); 2224a69bbe02SLawrence D'Anna 2225a69bbe02SLawrence D'Anna if (!maybe_ret_val) { 2226a69bbe02SLawrence D'Anna 2227a69bbe02SLawrence D'Anna llvm::handleAllErrors( 2228a69bbe02SLawrence D'Anna maybe_ret_val.takeError(), 2229a69bbe02SLawrence D'Anna [&](PythonException &E) { 2230a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.ReadBacktrace(); 2231a69bbe02SLawrence D'Anna }, 2232a69bbe02SLawrence D'Anna [&](const llvm::ErrorInfoBase &E) { 2233a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.message(); 2234a69bbe02SLawrence D'Anna }); 2235a69bbe02SLawrence D'Anna 2236a69bbe02SLawrence D'Anna } else { 2237a69bbe02SLawrence D'Anna ret_val = maybe_ret_val.get(); 2238a69bbe02SLawrence D'Anna } 22392c1f46dcSZachary Turner } 22402c1f46dcSZachary Turner return ret_val; 22412c1f46dcSZachary Turner } 22422c1f46dcSZachary Turner } 22432c1f46dcSZachary Turner } 22442c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22452c1f46dcSZachary Turner // trying to call the script function 22462c1f46dcSZachary Turner return true; 22472c1f46dcSZachary Turner } 22482c1f46dcSZachary Turner 224963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 2250b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 2251b9c1b51eSKate Stone WatchpointOptions::CommandData *wp_option_data = 2252b9c1b51eSKate Stone (WatchpointOptions::CommandData *)baton; 22532c1f46dcSZachary Turner const char *python_function_name = wp_option_data->script_source.c_str(); 22542c1f46dcSZachary Turner 22552c1f46dcSZachary Turner if (!context) 22562c1f46dcSZachary Turner return true; 22572c1f46dcSZachary Turner 22582c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 22592c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 22602c1f46dcSZachary Turner 22612c1f46dcSZachary Turner if (!target) 22622c1f46dcSZachary Turner return true; 22632c1f46dcSZachary Turner 22642c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 226563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2266d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 22672c1f46dcSZachary Turner 2268d055e3a0SPedro Tammela if (!python_interpreter) 22692c1f46dcSZachary Turner return true; 22702c1f46dcSZachary Turner 2271b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 22722c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 22732c1f46dcSZachary Turner WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 2274b9c1b51eSKate Stone if (wp_sp) { 2275b9c1b51eSKate Stone if (stop_frame_sp && wp_sp) { 22762c1f46dcSZachary Turner bool ret_val = true; 22772c1f46dcSZachary Turner { 2278b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2279b9c1b51eSKate Stone Locker::InitSession | 2280b9c1b51eSKate Stone Locker::NoSTDIN); 228105495c5dSJonas Devlieghere ret_val = LLDBSwigPythonWatchpointCallbackFunction( 2282b9c1b51eSKate Stone python_function_name, 2283b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 22842c1f46dcSZachary Turner wp_sp); 22852c1f46dcSZachary Turner } 22862c1f46dcSZachary Turner return ret_val; 22872c1f46dcSZachary Turner } 22882c1f46dcSZachary Turner } 22892c1f46dcSZachary Turner } 22902c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22912c1f46dcSZachary Turner // trying to call the script function 22922c1f46dcSZachary Turner return true; 22932c1f46dcSZachary Turner } 22942c1f46dcSZachary Turner 229563dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 2296b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 22972c1f46dcSZachary Turner if (!implementor_sp) 22982c1f46dcSZachary Turner return 0; 22992c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23002c1f46dcSZachary Turner if (!generic) 23012c1f46dcSZachary Turner return 0; 23029a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23032c1f46dcSZachary Turner if (!implementor) 23042c1f46dcSZachary Turner return 0; 23052c1f46dcSZachary Turner 23062c1f46dcSZachary Turner size_t ret_val = 0; 23072c1f46dcSZachary Turner 23082c1f46dcSZachary Turner { 2309b9c1b51eSKate Stone Locker py_lock(this, 2310b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 231105495c5dSJonas Devlieghere ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 23122c1f46dcSZachary Turner } 23132c1f46dcSZachary Turner 23142c1f46dcSZachary Turner return ret_val; 23152c1f46dcSZachary Turner } 23162c1f46dcSZachary Turner 231763dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 2318b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 23192c1f46dcSZachary Turner if (!implementor_sp) 23202c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23212c1f46dcSZachary Turner 23222c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23232c1f46dcSZachary Turner if (!generic) 23242c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23259a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23262c1f46dcSZachary Turner if (!implementor) 23272c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23282c1f46dcSZachary Turner 23292c1f46dcSZachary Turner lldb::ValueObjectSP ret_val; 23302c1f46dcSZachary Turner { 2331b9c1b51eSKate Stone Locker py_lock(this, 2332b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 23339a14adeaSPavel Labath PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 2334b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2335b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 233605495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 23372c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 23382c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23392c1f46dcSZachary Turner else 234005495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2341b9c1b51eSKate Stone } else { 23422c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23432c1f46dcSZachary Turner } 23442c1f46dcSZachary Turner } 23452c1f46dcSZachary Turner 23462c1f46dcSZachary Turner return ret_val; 23472c1f46dcSZachary Turner } 23482c1f46dcSZachary Turner 234963dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 2350b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 23512c1f46dcSZachary Turner if (!implementor_sp) 23522c1f46dcSZachary Turner return UINT32_MAX; 23532c1f46dcSZachary Turner 23542c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23552c1f46dcSZachary Turner if (!generic) 23562c1f46dcSZachary Turner return UINT32_MAX; 23579a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23582c1f46dcSZachary Turner if (!implementor) 23592c1f46dcSZachary Turner return UINT32_MAX; 23602c1f46dcSZachary Turner 23612c1f46dcSZachary Turner int ret_val = UINT32_MAX; 23622c1f46dcSZachary Turner 23632c1f46dcSZachary Turner { 2364b9c1b51eSKate Stone Locker py_lock(this, 2365b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 236605495c5dSJonas Devlieghere ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 23672c1f46dcSZachary Turner } 23682c1f46dcSZachary Turner 23692c1f46dcSZachary Turner return ret_val; 23702c1f46dcSZachary Turner } 23712c1f46dcSZachary Turner 237263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 2373b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23742c1f46dcSZachary Turner bool ret_val = false; 23752c1f46dcSZachary Turner 23762c1f46dcSZachary Turner if (!implementor_sp) 23772c1f46dcSZachary Turner return ret_val; 23782c1f46dcSZachary Turner 23792c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23802c1f46dcSZachary Turner if (!generic) 23812c1f46dcSZachary Turner return ret_val; 23829a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23832c1f46dcSZachary Turner if (!implementor) 23842c1f46dcSZachary Turner return ret_val; 23852c1f46dcSZachary Turner 23862c1f46dcSZachary Turner { 2387b9c1b51eSKate Stone Locker py_lock(this, 2388b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 238905495c5dSJonas Devlieghere ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 23902c1f46dcSZachary Turner } 23912c1f46dcSZachary Turner 23922c1f46dcSZachary Turner return ret_val; 23932c1f46dcSZachary Turner } 23942c1f46dcSZachary Turner 239563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 2396b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23972c1f46dcSZachary Turner bool ret_val = false; 23982c1f46dcSZachary Turner 23992c1f46dcSZachary Turner if (!implementor_sp) 24002c1f46dcSZachary Turner return ret_val; 24012c1f46dcSZachary Turner 24022c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24032c1f46dcSZachary Turner if (!generic) 24042c1f46dcSZachary Turner return ret_val; 24059a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 24062c1f46dcSZachary Turner if (!implementor) 24072c1f46dcSZachary Turner return ret_val; 24082c1f46dcSZachary Turner 24092c1f46dcSZachary Turner { 2410b9c1b51eSKate Stone Locker py_lock(this, 2411b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 241205495c5dSJonas Devlieghere ret_val = 241305495c5dSJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 24142c1f46dcSZachary Turner } 24152c1f46dcSZachary Turner 24162c1f46dcSZachary Turner return ret_val; 24172c1f46dcSZachary Turner } 24182c1f46dcSZachary Turner 241963dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 2420b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 24212c1f46dcSZachary Turner lldb::ValueObjectSP ret_val(nullptr); 24222c1f46dcSZachary Turner 24232c1f46dcSZachary Turner if (!implementor_sp) 24242c1f46dcSZachary Turner return ret_val; 24252c1f46dcSZachary Turner 24262c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24272c1f46dcSZachary Turner if (!generic) 24282c1f46dcSZachary Turner return ret_val; 24299a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 24302c1f46dcSZachary Turner if (!implementor) 24312c1f46dcSZachary Turner return ret_val; 24322c1f46dcSZachary Turner 24332c1f46dcSZachary Turner { 2434b9c1b51eSKate Stone Locker py_lock(this, 2435b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24369a14adeaSPavel Labath PyObject *child_ptr = 24379a14adeaSPavel Labath LLDBSwigPython_GetValueSynthProviderInstance(implementor); 2438b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2439b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 244005495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 24412c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 24422c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24432c1f46dcSZachary Turner else 244405495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2445b9c1b51eSKate Stone } else { 24462c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24472c1f46dcSZachary Turner } 24482c1f46dcSZachary Turner } 24492c1f46dcSZachary Turner 24502c1f46dcSZachary Turner return ret_val; 24512c1f46dcSZachary Turner } 24522c1f46dcSZachary Turner 245363dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 2454b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 2455b9c1b51eSKate Stone Locker py_lock(this, 2456b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24576eec8d6cSEnrico Granata 24586eec8d6cSEnrico Granata static char callee_name[] = "get_type_name"; 24596eec8d6cSEnrico Granata 24606eec8d6cSEnrico Granata ConstString ret_val; 24616eec8d6cSEnrico Granata bool got_string = false; 24626eec8d6cSEnrico Granata std::string buffer; 24636eec8d6cSEnrico Granata 24646eec8d6cSEnrico Granata if (!implementor_sp) 24656eec8d6cSEnrico Granata return ret_val; 24666eec8d6cSEnrico Granata 24676eec8d6cSEnrico Granata StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24686eec8d6cSEnrico Granata if (!generic) 24696eec8d6cSEnrico Granata return ret_val; 2470b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2471b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 24726eec8d6cSEnrico Granata if (!implementor.IsAllocated()) 24736eec8d6cSEnrico Granata return ret_val; 24746eec8d6cSEnrico Granata 2475b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 2476b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 24776eec8d6cSEnrico Granata 24786eec8d6cSEnrico Granata if (PyErr_Occurred()) 24796eec8d6cSEnrico Granata PyErr_Clear(); 24806eec8d6cSEnrico Granata 24816eec8d6cSEnrico Granata if (!pmeth.IsAllocated()) 24826eec8d6cSEnrico Granata return ret_val; 24836eec8d6cSEnrico Granata 2484b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 24856eec8d6cSEnrico Granata if (PyErr_Occurred()) 24866eec8d6cSEnrico Granata PyErr_Clear(); 24876eec8d6cSEnrico Granata return ret_val; 24886eec8d6cSEnrico Granata } 24896eec8d6cSEnrico Granata 24906eec8d6cSEnrico Granata if (PyErr_Occurred()) 24916eec8d6cSEnrico Granata PyErr_Clear(); 24926eec8d6cSEnrico Granata 24936eec8d6cSEnrico Granata // right now we know this function exists and is callable.. 2494b9c1b51eSKate Stone PythonObject py_return( 2495b9c1b51eSKate Stone PyRefType::Owned, 2496b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 24976eec8d6cSEnrico Granata 24986eec8d6cSEnrico Granata // if it fails, print the error but otherwise go on 2499b9c1b51eSKate Stone if (PyErr_Occurred()) { 25006eec8d6cSEnrico Granata PyErr_Print(); 25016eec8d6cSEnrico Granata PyErr_Clear(); 25026eec8d6cSEnrico Granata } 25036eec8d6cSEnrico Granata 2504b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 25056eec8d6cSEnrico Granata PythonString py_string(PyRefType::Borrowed, py_return.get()); 25066eec8d6cSEnrico Granata llvm::StringRef return_data(py_string.GetString()); 2507b9c1b51eSKate Stone if (!return_data.empty()) { 25086eec8d6cSEnrico Granata buffer.assign(return_data.data(), return_data.size()); 25096eec8d6cSEnrico Granata got_string = true; 25106eec8d6cSEnrico Granata } 25116eec8d6cSEnrico Granata } 25126eec8d6cSEnrico Granata 25136eec8d6cSEnrico Granata if (got_string) 25146eec8d6cSEnrico Granata ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 25156eec8d6cSEnrico Granata 25166eec8d6cSEnrico Granata return ret_val; 25176eec8d6cSEnrico Granata } 25186eec8d6cSEnrico Granata 251963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 252063dd5d25SJonas Devlieghere const char *impl_function, Process *process, std::string &output, 252197206d57SZachary Turner Status &error) { 25222c1f46dcSZachary Turner bool ret_val; 2523b9c1b51eSKate Stone if (!process) { 25242c1f46dcSZachary Turner error.SetErrorString("no process"); 25252c1f46dcSZachary Turner return false; 25262c1f46dcSZachary Turner } 2527b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25282c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25292c1f46dcSZachary Turner return false; 25302c1f46dcSZachary Turner } 253105495c5dSJonas Devlieghere 25322c1f46dcSZachary Turner { 2533b9c1b51eSKate Stone Locker py_lock(this, 2534b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 253505495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 25367f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), process->shared_from_this(), 25377f09ab08SPavel Labath output); 25382c1f46dcSZachary Turner if (!ret_val) 25392c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25402c1f46dcSZachary Turner } 25412c1f46dcSZachary Turner return ret_val; 25422c1f46dcSZachary Turner } 25432c1f46dcSZachary Turner 254463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 254563dd5d25SJonas Devlieghere const char *impl_function, Thread *thread, std::string &output, 254697206d57SZachary Turner Status &error) { 2547b9c1b51eSKate Stone if (!thread) { 25482c1f46dcSZachary Turner error.SetErrorString("no thread"); 25492c1f46dcSZachary Turner return false; 25502c1f46dcSZachary Turner } 2551b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25522c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25532c1f46dcSZachary Turner return false; 25542c1f46dcSZachary Turner } 255505495c5dSJonas Devlieghere 2556b9c1b51eSKate Stone Locker py_lock(this, 2557b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25587406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread( 25597406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 25607406d236SPavel Labath thread->shared_from_this())) { 25617406d236SPavel Labath output = std::move(*result); 25627406d236SPavel Labath return true; 25632c1f46dcSZachary Turner } 25647406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 25657406d236SPavel Labath return false; 25662c1f46dcSZachary Turner } 25672c1f46dcSZachary Turner 256863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 256963dd5d25SJonas Devlieghere const char *impl_function, Target *target, std::string &output, 257097206d57SZachary Turner Status &error) { 25712c1f46dcSZachary Turner bool ret_val; 2572b9c1b51eSKate Stone if (!target) { 25732c1f46dcSZachary Turner error.SetErrorString("no thread"); 25742c1f46dcSZachary Turner return false; 25752c1f46dcSZachary Turner } 2576b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25772c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25782c1f46dcSZachary Turner return false; 25792c1f46dcSZachary Turner } 258005495c5dSJonas Devlieghere 25812c1f46dcSZachary Turner { 25822c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 2583b9c1b51eSKate Stone Locker py_lock(this, 2584b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 258505495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 2586b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), target_sp, output); 25872c1f46dcSZachary Turner if (!ret_val) 25882c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25892c1f46dcSZachary Turner } 25902c1f46dcSZachary Turner return ret_val; 25912c1f46dcSZachary Turner } 25922c1f46dcSZachary Turner 259363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 259463dd5d25SJonas Devlieghere const char *impl_function, StackFrame *frame, std::string &output, 259597206d57SZachary Turner Status &error) { 2596b9c1b51eSKate Stone if (!frame) { 25972c1f46dcSZachary Turner error.SetErrorString("no frame"); 25982c1f46dcSZachary Turner return false; 25992c1f46dcSZachary Turner } 2600b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26012c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26022c1f46dcSZachary Turner return false; 26032c1f46dcSZachary Turner } 260405495c5dSJonas Devlieghere 2605b9c1b51eSKate Stone Locker py_lock(this, 2606b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 26077406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame( 26087406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 26097406d236SPavel Labath frame->shared_from_this())) { 26107406d236SPavel Labath output = std::move(*result); 26117406d236SPavel Labath return true; 26122c1f46dcSZachary Turner } 26137406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 26147406d236SPavel Labath return false; 26152c1f46dcSZachary Turner } 26162c1f46dcSZachary Turner 261763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 261863dd5d25SJonas Devlieghere const char *impl_function, ValueObject *value, std::string &output, 261997206d57SZachary Turner Status &error) { 26202c1f46dcSZachary Turner bool ret_val; 2621b9c1b51eSKate Stone if (!value) { 26222c1f46dcSZachary Turner error.SetErrorString("no value"); 26232c1f46dcSZachary Turner return false; 26242c1f46dcSZachary Turner } 2625b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26262c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26272c1f46dcSZachary Turner return false; 26282c1f46dcSZachary Turner } 262905495c5dSJonas Devlieghere 26302c1f46dcSZachary Turner { 2631b9c1b51eSKate Stone Locker py_lock(this, 2632b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 263305495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordValue( 26347f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), value->GetSP(), output); 26352c1f46dcSZachary Turner if (!ret_val) 26362c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26372c1f46dcSZachary Turner } 26382c1f46dcSZachary Turner return ret_val; 26392c1f46dcSZachary Turner } 26402c1f46dcSZachary Turner 2641b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr, 2642b9c1b51eSKate Stone const std::string &newStr) { 26432c1f46dcSZachary Turner size_t pos = 0; 26442c1f46dcSZachary Turner uint64_t matches = 0; 2645b9c1b51eSKate Stone while ((pos = str.find(oldStr, pos)) != std::string::npos) { 26462c1f46dcSZachary Turner matches++; 26472c1f46dcSZachary Turner str.replace(pos, oldStr.length(), newStr); 26482c1f46dcSZachary Turner pos += newStr.length(); 26492c1f46dcSZachary Turner } 26502c1f46dcSZachary Turner return matches; 26512c1f46dcSZachary Turner } 26522c1f46dcSZachary Turner 265363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule( 2654f9517353SJonas Devlieghere const char *pathname, const LoadScriptOptions &options, 2655f9517353SJonas Devlieghere lldb_private::Status &error, StructuredData::ObjectSP *module_sp, 2656f9517353SJonas Devlieghere FileSpec extra_search_dir) { 26573b33b416SJonas Devlieghere namespace fs = llvm::sys::fs; 265800bb397bSJonas Devlieghere namespace path = llvm::sys::path; 26593b33b416SJonas Devlieghere 2660f9517353SJonas Devlieghere ExecuteScriptOptions exc_options = ExecuteScriptOptions() 2661f9517353SJonas Devlieghere .SetEnableIO(!options.GetSilent()) 2662f9517353SJonas Devlieghere .SetSetLLDBGlobals(false); 2663f9517353SJonas Devlieghere 2664b9c1b51eSKate Stone if (!pathname || !pathname[0]) { 26652c1f46dcSZachary Turner error.SetErrorString("invalid pathname"); 26662c1f46dcSZachary Turner return false; 26672c1f46dcSZachary Turner } 26682c1f46dcSZachary Turner 2669f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 2670f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 2671f9517353SJonas Devlieghere exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr); 2672f9517353SJonas Devlieghere 2673f9517353SJonas Devlieghere if (!io_redirect_or_error) { 2674f9517353SJonas Devlieghere error = io_redirect_or_error.takeError(); 2675f9517353SJonas Devlieghere return false; 2676f9517353SJonas Devlieghere } 2677f9517353SJonas Devlieghere 2678f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 26792c1f46dcSZachary Turner 2680f9f36097SAdrian McCarthy // Before executing Python code, lock the GIL. 268120b52c33SJonas Devlieghere Locker py_lock(this, 268220b52c33SJonas Devlieghere Locker::AcquireLock | 2683f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::InitSession : 0) | 2684f9517353SJonas Devlieghere Locker::NoSTDIN, 2685b9c1b51eSKate Stone Locker::FreeAcquiredLock | 2686f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::TearDownSession : 0), 2687f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 2688f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 26892c1f46dcSZachary Turner 2690f9517353SJonas Devlieghere auto ExtendSysPath = [&](std::string directory) -> llvm::Error { 269100bb397bSJonas Devlieghere if (directory.empty()) { 269200bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 269300bb397bSJonas Devlieghere "invalid directory name", llvm::inconvertibleErrorCode()); 269442a9da7bSStefan Granitz } 269542a9da7bSStefan Granitz 2696f9f36097SAdrian McCarthy replace_all(directory, "\\", "\\\\"); 26972c1f46dcSZachary Turner replace_all(directory, "'", "\\'"); 26982c1f46dcSZachary Turner 269900bb397bSJonas Devlieghere // Make sure that Python has "directory" in the search path. 27002c1f46dcSZachary Turner StreamString command_stream; 2701b9c1b51eSKate Stone command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 2702b9c1b51eSKate Stone "sys.path.insert(1,'%s');\n\n", 2703b9c1b51eSKate Stone directory.c_str(), directory.c_str()); 2704b9c1b51eSKate Stone bool syspath_retval = 2705f9517353SJonas Devlieghere ExecuteMultipleLines(command_stream.GetData(), exc_options).Success(); 2706b9c1b51eSKate Stone if (!syspath_retval) { 270700bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 270800bb397bSJonas Devlieghere "Python sys.path handling failed", llvm::inconvertibleErrorCode()); 27092c1f46dcSZachary Turner } 27102c1f46dcSZachary Turner 271100bb397bSJonas Devlieghere return llvm::Error::success(); 271200bb397bSJonas Devlieghere }; 271300bb397bSJonas Devlieghere 271400bb397bSJonas Devlieghere std::string module_name(pathname); 2715d6e80578SJonas Devlieghere bool possible_package = false; 271600bb397bSJonas Devlieghere 271700bb397bSJonas Devlieghere if (extra_search_dir) { 271800bb397bSJonas Devlieghere if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) { 271900bb397bSJonas Devlieghere error = std::move(e); 272000bb397bSJonas Devlieghere return false; 272100bb397bSJonas Devlieghere } 272200bb397bSJonas Devlieghere } else { 272300bb397bSJonas Devlieghere FileSpec module_file(pathname); 272400bb397bSJonas Devlieghere FileSystem::Instance().Resolve(module_file); 272500bb397bSJonas Devlieghere FileSystem::Instance().Collect(module_file); 272600bb397bSJonas Devlieghere 272700bb397bSJonas Devlieghere fs::file_status st; 272800bb397bSJonas Devlieghere std::error_code ec = status(module_file.GetPath(), st); 272900bb397bSJonas Devlieghere 273000bb397bSJonas Devlieghere if (ec || st.type() == fs::file_type::status_error || 273100bb397bSJonas Devlieghere st.type() == fs::file_type::type_unknown || 273200bb397bSJonas Devlieghere st.type() == fs::file_type::file_not_found) { 273300bb397bSJonas Devlieghere // if not a valid file of any sort, check if it might be a filename still 273400bb397bSJonas Devlieghere // dot can't be used but / and \ can, and if either is found, reject 273500bb397bSJonas Devlieghere if (strchr(pathname, '\\') || strchr(pathname, '/')) { 273600bb397bSJonas Devlieghere error.SetErrorString("invalid pathname"); 273700bb397bSJonas Devlieghere return false; 273800bb397bSJonas Devlieghere } 273900bb397bSJonas Devlieghere // Not a filename, probably a package of some sort, let it go through. 2740d6e80578SJonas Devlieghere possible_package = true; 274100bb397bSJonas Devlieghere } else if (is_directory(st) || is_regular_file(st)) { 274200bb397bSJonas Devlieghere if (module_file.GetDirectory().IsEmpty()) { 274300bb397bSJonas Devlieghere error.SetErrorString("invalid directory name"); 274400bb397bSJonas Devlieghere return false; 274500bb397bSJonas Devlieghere } 274600bb397bSJonas Devlieghere if (llvm::Error e = 274700bb397bSJonas Devlieghere ExtendSysPath(module_file.GetDirectory().GetCString())) { 274800bb397bSJonas Devlieghere error = std::move(e); 274900bb397bSJonas Devlieghere return false; 275000bb397bSJonas Devlieghere } 275100bb397bSJonas Devlieghere module_name = module_file.GetFilename().GetCString(); 2752b9c1b51eSKate Stone } else { 27532c1f46dcSZachary Turner error.SetErrorString("no known way to import this module specification"); 27542c1f46dcSZachary Turner return false; 27552c1f46dcSZachary Turner } 275600bb397bSJonas Devlieghere } 27572c1f46dcSZachary Turner 27581197ee35SJonas Devlieghere // Strip .py or .pyc extension 275900bb397bSJonas Devlieghere llvm::StringRef extension = llvm::sys::path::extension(module_name); 27601197ee35SJonas Devlieghere if (!extension.empty()) { 27611197ee35SJonas Devlieghere if (extension == ".py") 276200bb397bSJonas Devlieghere module_name.resize(module_name.length() - 3); 27631197ee35SJonas Devlieghere else if (extension == ".pyc") 276400bb397bSJonas Devlieghere module_name.resize(module_name.length() - 4); 27651197ee35SJonas Devlieghere } 27661197ee35SJonas Devlieghere 2767d6e80578SJonas Devlieghere if (!possible_package && module_name.find('.') != llvm::StringRef::npos) { 2768d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2769d6e80578SJonas Devlieghere "Python does not allow dots in module names: %s", module_name.c_str()); 2770d6e80578SJonas Devlieghere return false; 2771d6e80578SJonas Devlieghere } 2772d6e80578SJonas Devlieghere 2773d6e80578SJonas Devlieghere if (module_name.find('-') != llvm::StringRef::npos) { 2774d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2775d6e80578SJonas Devlieghere "Python discourages dashes in module names: %s", module_name.c_str()); 2776d6e80578SJonas Devlieghere return false; 2777d6e80578SJonas Devlieghere } 2778d6e80578SJonas Devlieghere 2779f9517353SJonas Devlieghere // Check if the module is already imported. 278000bb397bSJonas Devlieghere StreamString command_stream; 27812c1f46dcSZachary Turner command_stream.Clear(); 278200bb397bSJonas Devlieghere command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str()); 27832c1f46dcSZachary Turner bool does_contain = false; 2784f9517353SJonas Devlieghere // This call will succeed if the module was ever imported in any Debugger in 2785f9517353SJonas Devlieghere // the lifetime of the process in which this LLDB framework is living. 2786f9517353SJonas Devlieghere const bool does_contain_executed = ExecuteOneLineWithReturn( 2787b9c1b51eSKate Stone command_stream.GetData(), 2788f9517353SJonas Devlieghere ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options); 2789f9517353SJonas Devlieghere 2790f9517353SJonas Devlieghere const bool was_imported_globally = does_contain_executed && does_contain; 2791612384f6SJonas Devlieghere const bool was_imported_locally = 2792612384f6SJonas Devlieghere GetSessionDictionary() 279300bb397bSJonas Devlieghere .GetItemForKey(PythonString(module_name)) 2794b9c1b51eSKate Stone .IsAllocated(); 27952c1f46dcSZachary Turner 27962c1f46dcSZachary Turner // now actually do the import 27972c1f46dcSZachary Turner command_stream.Clear(); 27982c1f46dcSZachary Turner 2799612384f6SJonas Devlieghere if (was_imported_globally || was_imported_locally) { 28002c1f46dcSZachary Turner if (!was_imported_locally) 280100bb397bSJonas Devlieghere command_stream.Printf("import %s ; reload_module(%s)", 280200bb397bSJonas Devlieghere module_name.c_str(), module_name.c_str()); 28032c1f46dcSZachary Turner else 280400bb397bSJonas Devlieghere command_stream.Printf("reload_module(%s)", module_name.c_str()); 2805b9c1b51eSKate Stone } else 280600bb397bSJonas Devlieghere command_stream.Printf("import %s", module_name.c_str()); 28072c1f46dcSZachary Turner 2808f9517353SJonas Devlieghere error = ExecuteMultipleLines(command_stream.GetData(), exc_options); 28092c1f46dcSZachary Turner if (error.Fail()) 28102c1f46dcSZachary Turner return false; 28112c1f46dcSZachary Turner 28122c1f46dcSZachary Turner // if we are here, everything worked 28132c1f46dcSZachary Turner // call __lldb_init_module(debugger,dict) 281400bb397bSJonas Devlieghere if (!LLDBSwigPythonCallModuleInit(module_name.c_str(), 28157406d236SPavel Labath m_dictionary_name.c_str(), 28167406d236SPavel Labath m_debugger.shared_from_this())) { 28172c1f46dcSZachary Turner error.SetErrorString("calling __lldb_init_module failed"); 28182c1f46dcSZachary Turner return false; 28192c1f46dcSZachary Turner } 28202c1f46dcSZachary Turner 2821b9c1b51eSKate Stone if (module_sp) { 28222c1f46dcSZachary Turner // everything went just great, now set the module object 28232c1f46dcSZachary Turner command_stream.Clear(); 282400bb397bSJonas Devlieghere command_stream.Printf("%s", module_name.c_str()); 28252c1f46dcSZachary Turner void *module_pyobj = nullptr; 2826b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 2827b9c1b51eSKate Stone command_stream.GetData(), 2828f9517353SJonas Devlieghere ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj, 2829f9517353SJonas Devlieghere exc_options) && 2830b9c1b51eSKate Stone module_pyobj) 2831c154f397SPavel Labath *module_sp = std::make_shared<StructuredPythonObject>(PythonObject( 2832c154f397SPavel Labath PyRefType::Owned, static_cast<PyObject *>(module_pyobj))); 28332c1f46dcSZachary Turner } 28342c1f46dcSZachary Turner 28352c1f46dcSZachary Turner return true; 28362c1f46dcSZachary Turner } 28372c1f46dcSZachary Turner 283863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 28392c1f46dcSZachary Turner if (!word || !word[0]) 28402c1f46dcSZachary Turner return false; 28412c1f46dcSZachary Turner 28422c1f46dcSZachary Turner llvm::StringRef word_sr(word); 28432c1f46dcSZachary Turner 284405097246SAdrian Prantl // filter out a few characters that would just confuse us and that are 284505097246SAdrian Prantl // clearly not keyword material anyway 284610b113e8SJonas Devlieghere if (word_sr.find('"') != llvm::StringRef::npos || 284710b113e8SJonas Devlieghere word_sr.find('\'') != llvm::StringRef::npos) 28482c1f46dcSZachary Turner return false; 28492c1f46dcSZachary Turner 28502c1f46dcSZachary Turner StreamString command_stream; 28512c1f46dcSZachary Turner command_stream.Printf("keyword.iskeyword('%s')", word); 28522c1f46dcSZachary Turner bool result; 28532c1f46dcSZachary Turner ExecuteScriptOptions options; 28542c1f46dcSZachary Turner options.SetEnableIO(false); 28552c1f46dcSZachary Turner options.SetMaskoutErrors(true); 28562c1f46dcSZachary Turner options.SetSetLLDBGlobals(false); 2857b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(command_stream.GetData(), 2858b9c1b51eSKate Stone ScriptInterpreter::eScriptReturnTypeBool, 2859b9c1b51eSKate Stone &result, options)) 28602c1f46dcSZachary Turner return result; 28612c1f46dcSZachary Turner return false; 28622c1f46dcSZachary Turner } 28632c1f46dcSZachary Turner 286463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 2865b9c1b51eSKate Stone lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 2866b9c1b51eSKate Stone : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 2867b9c1b51eSKate Stone m_old_asynch(debugger_sp->GetAsyncExecution()) { 28682c1f46dcSZachary Turner if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 28692c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(false); 28702c1f46dcSZachary Turner else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 28712c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(true); 28722c1f46dcSZachary Turner } 28732c1f46dcSZachary Turner 287463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 28752c1f46dcSZachary Turner if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 28762c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(m_old_asynch); 28772c1f46dcSZachary Turner } 28782c1f46dcSZachary Turner 287963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 28804d51a902SRaphael Isemann const char *impl_function, llvm::StringRef args, 28812c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 288297206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2883b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2884b9c1b51eSKate Stone if (!impl_function) { 28852c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 28862c1f46dcSZachary Turner return false; 28872c1f46dcSZachary Turner } 28882c1f46dcSZachary Turner 28898d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 28902c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 28912c1f46dcSZachary Turner 2892b9c1b51eSKate Stone if (!debugger_sp.get()) { 28932c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 28942c1f46dcSZachary Turner return false; 28952c1f46dcSZachary Turner } 28962c1f46dcSZachary Turner 28972c1f46dcSZachary Turner bool ret_val = false; 28982c1f46dcSZachary Turner 28992c1f46dcSZachary Turner std::string err_msg; 29002c1f46dcSZachary Turner 29012c1f46dcSZachary Turner { 29022c1f46dcSZachary Turner Locker py_lock(this, 2903b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2904b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29052c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 29062c1f46dcSZachary Turner 2907b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29082c1f46dcSZachary Turner 29094d51a902SRaphael Isemann std::string args_str = args.str(); 291005495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommand( 291105495c5dSJonas Devlieghere impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 291205495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp); 29132c1f46dcSZachary Turner } 29142c1f46dcSZachary Turner 29152c1f46dcSZachary Turner if (!ret_val) 29162c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 29172c1f46dcSZachary Turner else 29182c1f46dcSZachary Turner error.Clear(); 29192c1f46dcSZachary Turner 29202c1f46dcSZachary Turner return ret_val; 29212c1f46dcSZachary Turner } 29222c1f46dcSZachary Turner 292363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 29244d51a902SRaphael Isemann StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 29252c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 292697206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2927b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2928b9c1b51eSKate Stone if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 29292c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 29302c1f46dcSZachary Turner return false; 29312c1f46dcSZachary Turner } 29322c1f46dcSZachary Turner 29338d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29342c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29352c1f46dcSZachary Turner 2936b9c1b51eSKate Stone if (!debugger_sp.get()) { 29372c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 29382c1f46dcSZachary Turner return false; 29392c1f46dcSZachary Turner } 29402c1f46dcSZachary Turner 29412c1f46dcSZachary Turner bool ret_val = false; 29422c1f46dcSZachary Turner 29432c1f46dcSZachary Turner std::string err_msg; 29442c1f46dcSZachary Turner 29452c1f46dcSZachary Turner { 29462c1f46dcSZachary Turner Locker py_lock(this, 2947b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2948b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29492c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 29502c1f46dcSZachary Turner 2951b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29522c1f46dcSZachary Turner 29534d51a902SRaphael Isemann std::string args_str = args.str(); 29549a14adeaSPavel Labath ret_val = LLDBSwigPythonCallCommandObject( 29559a14adeaSPavel Labath static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp, 29569a14adeaSPavel Labath args_str.c_str(), cmd_retobj, exe_ctx_ref_sp); 29572c1f46dcSZachary Turner } 29582c1f46dcSZachary Turner 29592c1f46dcSZachary Turner if (!ret_val) 29602c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 29612c1f46dcSZachary Turner else 29622c1f46dcSZachary Turner error.Clear(); 29632c1f46dcSZachary Turner 29642c1f46dcSZachary Turner return ret_val; 29652c1f46dcSZachary Turner } 29662c1f46dcSZachary Turner 296793571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object 296893571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's 296993571c3cSJonas Devlieghere /// value is None. 297063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 2971b9c1b51eSKate Stone std::string &dest) { 29722c1f46dcSZachary Turner dest.clear(); 297393571c3cSJonas Devlieghere 29742c1f46dcSZachary Turner if (!item || !*item) 29752c1f46dcSZachary Turner return false; 297693571c3cSJonas Devlieghere 29772c1f46dcSZachary Turner std::string command(item); 29782c1f46dcSZachary Turner command += ".__doc__"; 29792c1f46dcSZachary Turner 298093571c3cSJonas Devlieghere // Python is going to point this to valid data if ExecuteOneLineWithReturn 298193571c3cSJonas Devlieghere // returns successfully. 298293571c3cSJonas Devlieghere char *result_ptr = nullptr; 29832c1f46dcSZachary Turner 2984b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 298593571c3cSJonas Devlieghere command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 29862c1f46dcSZachary Turner &result_ptr, 2987fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false))) { 29882c1f46dcSZachary Turner if (result_ptr) 29892c1f46dcSZachary Turner dest.assign(result_ptr); 29902c1f46dcSZachary Turner return true; 29912c1f46dcSZachary Turner } 299293571c3cSJonas Devlieghere 299393571c3cSJonas Devlieghere StreamString str_stream; 299493571c3cSJonas Devlieghere str_stream << "Function " << item 299593571c3cSJonas Devlieghere << " was not found. Containing module might be missing."; 299693571c3cSJonas Devlieghere dest = std::string(str_stream.GetString()); 299793571c3cSJonas Devlieghere 299893571c3cSJonas Devlieghere return false; 29992c1f46dcSZachary Turner } 30002c1f46dcSZachary Turner 300163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 3002b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 30032c1f46dcSZachary Turner dest.clear(); 30042c1f46dcSZachary Turner 3005b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30062c1f46dcSZachary Turner 30072c1f46dcSZachary Turner static char callee_name[] = "get_short_help"; 30082c1f46dcSZachary Turner 30092c1f46dcSZachary Turner if (!cmd_obj_sp) 30102c1f46dcSZachary Turner return false; 30112c1f46dcSZachary Turner 3012b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3013b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 30142c1f46dcSZachary Turner 3015f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 30162c1f46dcSZachary Turner return false; 30172c1f46dcSZachary Turner 3018b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3019b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30202c1f46dcSZachary Turner 30212c1f46dcSZachary Turner if (PyErr_Occurred()) 30222c1f46dcSZachary Turner PyErr_Clear(); 30232c1f46dcSZachary Turner 3024f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 30252c1f46dcSZachary Turner return false; 30262c1f46dcSZachary Turner 3027b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30282c1f46dcSZachary Turner if (PyErr_Occurred()) 30292c1f46dcSZachary Turner PyErr_Clear(); 30302c1f46dcSZachary Turner return false; 30312c1f46dcSZachary Turner } 30322c1f46dcSZachary Turner 30332c1f46dcSZachary Turner if (PyErr_Occurred()) 30342c1f46dcSZachary Turner PyErr_Clear(); 30352c1f46dcSZachary Turner 303693571c3cSJonas Devlieghere // Right now we know this function exists and is callable. 3037b9c1b51eSKate Stone PythonObject py_return( 3038b9c1b51eSKate Stone PyRefType::Owned, 3039b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 30402c1f46dcSZachary Turner 304193571c3cSJonas Devlieghere // If it fails, print the error but otherwise go on. 3042b9c1b51eSKate Stone if (PyErr_Occurred()) { 30432c1f46dcSZachary Turner PyErr_Print(); 30442c1f46dcSZachary Turner PyErr_Clear(); 30452c1f46dcSZachary Turner } 30462c1f46dcSZachary Turner 3047b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3048f8b22f8fSZachary Turner PythonString py_string(PyRefType::Borrowed, py_return.get()); 304922c8efcdSZachary Turner llvm::StringRef return_data(py_string.GetString()); 305022c8efcdSZachary Turner dest.assign(return_data.data(), return_data.size()); 305193571c3cSJonas Devlieghere return true; 30522c1f46dcSZachary Turner } 305393571c3cSJonas Devlieghere 305493571c3cSJonas Devlieghere return false; 30552c1f46dcSZachary Turner } 30562c1f46dcSZachary Turner 305763dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 3058b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp) { 30592c1f46dcSZachary Turner uint32_t result = 0; 30602c1f46dcSZachary Turner 3061b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30622c1f46dcSZachary Turner 30632c1f46dcSZachary Turner static char callee_name[] = "get_flags"; 30642c1f46dcSZachary Turner 30652c1f46dcSZachary Turner if (!cmd_obj_sp) 30662c1f46dcSZachary Turner return result; 30672c1f46dcSZachary Turner 3068b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3069b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 30702c1f46dcSZachary Turner 3071f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 30722c1f46dcSZachary Turner return result; 30732c1f46dcSZachary Turner 3074b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3075b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30762c1f46dcSZachary Turner 30772c1f46dcSZachary Turner if (PyErr_Occurred()) 30782c1f46dcSZachary Turner PyErr_Clear(); 30792c1f46dcSZachary Turner 3080f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 30812c1f46dcSZachary Turner return result; 30822c1f46dcSZachary Turner 3083b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30842c1f46dcSZachary Turner if (PyErr_Occurred()) 30852c1f46dcSZachary Turner PyErr_Clear(); 30862c1f46dcSZachary Turner return result; 30872c1f46dcSZachary Turner } 30882c1f46dcSZachary Turner 30892c1f46dcSZachary Turner if (PyErr_Occurred()) 30902c1f46dcSZachary Turner PyErr_Clear(); 30912c1f46dcSZachary Turner 309252712d3fSLawrence D'Anna long long py_return = unwrapOrSetPythonException( 309352712d3fSLawrence D'Anna As<long long>(implementor.CallMethod(callee_name))); 30942c1f46dcSZachary Turner 30952c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3096b9c1b51eSKate Stone if (PyErr_Occurred()) { 30972c1f46dcSZachary Turner PyErr_Print(); 30982c1f46dcSZachary Turner PyErr_Clear(); 309952712d3fSLawrence D'Anna } else { 310052712d3fSLawrence D'Anna result = py_return; 31012c1f46dcSZachary Turner } 31022c1f46dcSZachary Turner 31032c1f46dcSZachary Turner return result; 31042c1f46dcSZachary Turner } 31052c1f46dcSZachary Turner 310663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 3107b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 31082c1f46dcSZachary Turner bool got_string = false; 31092c1f46dcSZachary Turner dest.clear(); 31102c1f46dcSZachary Turner 3111b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 31122c1f46dcSZachary Turner 31132c1f46dcSZachary Turner static char callee_name[] = "get_long_help"; 31142c1f46dcSZachary Turner 31152c1f46dcSZachary Turner if (!cmd_obj_sp) 31162c1f46dcSZachary Turner return false; 31172c1f46dcSZachary Turner 3118b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3119b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 31202c1f46dcSZachary Turner 3121f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 31222c1f46dcSZachary Turner return false; 31232c1f46dcSZachary Turner 3124b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3125b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 31262c1f46dcSZachary Turner 31272c1f46dcSZachary Turner if (PyErr_Occurred()) 31282c1f46dcSZachary Turner PyErr_Clear(); 31292c1f46dcSZachary Turner 3130f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 31312c1f46dcSZachary Turner return false; 31322c1f46dcSZachary Turner 3133b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 31342c1f46dcSZachary Turner if (PyErr_Occurred()) 31352c1f46dcSZachary Turner PyErr_Clear(); 31362c1f46dcSZachary Turner 31372c1f46dcSZachary Turner return false; 31382c1f46dcSZachary Turner } 31392c1f46dcSZachary Turner 31402c1f46dcSZachary Turner if (PyErr_Occurred()) 31412c1f46dcSZachary Turner PyErr_Clear(); 31422c1f46dcSZachary Turner 31432c1f46dcSZachary Turner // right now we know this function exists and is callable.. 3144b9c1b51eSKate Stone PythonObject py_return( 3145b9c1b51eSKate Stone PyRefType::Owned, 3146b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31472c1f46dcSZachary Turner 31482c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3149b9c1b51eSKate Stone if (PyErr_Occurred()) { 31502c1f46dcSZachary Turner PyErr_Print(); 31512c1f46dcSZachary Turner PyErr_Clear(); 31522c1f46dcSZachary Turner } 31532c1f46dcSZachary Turner 3154b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3155f8b22f8fSZachary Turner PythonString str(PyRefType::Borrowed, py_return.get()); 315622c8efcdSZachary Turner llvm::StringRef str_data(str.GetString()); 315722c8efcdSZachary Turner dest.assign(str_data.data(), str_data.size()); 31582c1f46dcSZachary Turner got_string = true; 31592c1f46dcSZachary Turner } 31602c1f46dcSZachary Turner 31612c1f46dcSZachary Turner return got_string; 31622c1f46dcSZachary Turner } 31632c1f46dcSZachary Turner 31642c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker> 316563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 3166b9c1b51eSKate Stone std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 3167b9c1b51eSKate Stone this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 31682c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession)); 31692c1f46dcSZachary Turner return py_lock; 31702c1f46dcSZachary Turner } 31712c1f46dcSZachary Turner 3172*eb5c0ea6SJonas Devlieghere void ScriptInterpreterPythonImpl::Initialize() { 31735c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 31742c1f46dcSZachary Turner 3175b9c1b51eSKate Stone // RAII-based initialization which correctly handles multiple-initialization, 317605097246SAdrian Prantl // version- specific differences among Python 2 and Python 3, and saving and 317705097246SAdrian Prantl // restoring various other pieces of state that can get mucked with during 317805097246SAdrian Prantl // initialization. 3179079fe48aSZachary Turner InitializePythonRAII initialize_guard; 31802c1f46dcSZachary Turner 318105495c5dSJonas Devlieghere LLDBSwigPyInit(); 31822c1f46dcSZachary Turner 3183b9c1b51eSKate Stone // Update the path python uses to search for modules to include the current 3184b9c1b51eSKate Stone // directory. 31852c1f46dcSZachary Turner 31862c1f46dcSZachary Turner PyRun_SimpleString("import sys"); 31872c1f46dcSZachary Turner AddToSysPath(AddLocation::End, "."); 31882c1f46dcSZachary Turner 3189b9c1b51eSKate Stone // Don't denormalize paths when calling file_spec.GetPath(). On platforms 319005097246SAdrian Prantl // that use a backslash as the path separator, this will result in executing 319105097246SAdrian Prantl // python code containing paths with unescaped backslashes. But Python also 319205097246SAdrian Prantl // accepts forward slashes, so to make life easier we just use that. 31932df331b0SPavel Labath if (FileSpec file_spec = GetPythonDir()) 31942c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 319560f028ffSPavel Labath if (FileSpec file_spec = HostInfo::GetShlibDir()) 31962c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 31972c1f46dcSZachary Turner 3198b9c1b51eSKate Stone PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 3199b9c1b51eSKate Stone "lldb.embedded_interpreter; from " 3200b9c1b51eSKate Stone "lldb.embedded_interpreter import run_python_interpreter; " 3201b9c1b51eSKate Stone "from lldb.embedded_interpreter import run_one_line"); 3202049ae930SJonas Devlieghere 3203049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 3204049ae930SJonas Devlieghere // Python will not just overwrite its internal SIGINT handler but also the 3205049ae930SJonas Devlieghere // one from the process. Backup the current SIGINT handler to prevent that 3206049ae930SJonas Devlieghere // Python deletes it. 3207049ae930SJonas Devlieghere RestoreSignalHandlerScope save_sigint(SIGINT); 3208049ae930SJonas Devlieghere 3209049ae930SJonas Devlieghere // Setup a default SIGINT signal handler that works the same way as the 3210049ae930SJonas Devlieghere // normal Python REPL signal handler which raises a KeyboardInterrupt. 3211049ae930SJonas Devlieghere // Also make sure to not pollute the user's REPL with the signal module nor 3212049ae930SJonas Devlieghere // our utility function. 3213049ae930SJonas Devlieghere PyRun_SimpleString("def lldb_setup_sigint_handler():\n" 3214049ae930SJonas Devlieghere " import signal;\n" 3215049ae930SJonas Devlieghere " def signal_handler(sig, frame):\n" 3216049ae930SJonas Devlieghere " raise KeyboardInterrupt()\n" 3217049ae930SJonas Devlieghere " signal.signal(signal.SIGINT, signal_handler);\n" 3218049ae930SJonas Devlieghere "lldb_setup_sigint_handler();\n" 3219049ae930SJonas Devlieghere "del lldb_setup_sigint_handler\n"); 3220049ae930SJonas Devlieghere #endif 32212c1f46dcSZachary Turner } 32222c1f46dcSZachary Turner 322363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 3224b9c1b51eSKate Stone std::string path) { 32252c1f46dcSZachary Turner std::string path_copy; 32262c1f46dcSZachary Turner 32272c1f46dcSZachary Turner std::string statement; 3228b9c1b51eSKate Stone if (location == AddLocation::Beginning) { 32292c1f46dcSZachary Turner statement.assign("sys.path.insert(0,\""); 32302c1f46dcSZachary Turner statement.append(path); 32312c1f46dcSZachary Turner statement.append("\")"); 3232b9c1b51eSKate Stone } else { 32332c1f46dcSZachary Turner statement.assign("sys.path.append(\""); 32342c1f46dcSZachary Turner statement.append(path); 32352c1f46dcSZachary Turner statement.append("\")"); 32362c1f46dcSZachary Turner } 32372c1f46dcSZachary Turner PyRun_SimpleString(statement.c_str()); 32382c1f46dcSZachary Turner } 32392c1f46dcSZachary Turner 3240bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical 3241bcadb5a3SPavel Labath // place to call it). Calling Py_Finalize here causes test suite runs to seg 3242bcadb5a3SPavel Labath // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 3243bcadb5a3SPavel Labath // be called 'at_exit'. When the test suite Python harness finishes up, it 3244bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions. 3245bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 3246bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls 324763dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 324863dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results 324963dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting 325063dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize 3251bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway 3252bcadb5a3SPavel Labath // when the process exits). 3253bcadb5a3SPavel Labath // 325463dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 3255d68983e3SPavel Labath 32564e26cf2cSJonas Devlieghere #endif 3257