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 882c1f46dcSZachary Turner static bool g_initialized = false; 892c1f46dcSZachary Turner 90b9c1b51eSKate Stone namespace { 9122c8efcdSZachary Turner 9205097246SAdrian Prantl // Initializing Python is not a straightforward process. We cannot control 9305097246SAdrian Prantl // what external code may have done before getting to this point in LLDB, 9405097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a 9505097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained 9605097246SAdrian Prantl // across our initialization. We do this by using an RAII pattern where we 9705097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end 98b9c1b51eSKate Stone struct InitializePythonRAII { 99079fe48aSZachary Turner public: 1009494c510SJonas Devlieghere InitializePythonRAII() { 101079fe48aSZachary Turner InitializePythonHome(); 102079fe48aSZachary Turner 1039357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE 1049357b5d0Sserge-sans-paille // Python's readline is incompatible with libedit being linked into lldb. 1059357b5d0Sserge-sans-paille // Provide a patched version local to the embedded interpreter. 1069357b5d0Sserge-sans-paille bool ReadlinePatched = false; 1079357b5d0Sserge-sans-paille for (auto *p = PyImport_Inittab; p->name != NULL; p++) { 1089357b5d0Sserge-sans-paille if (strcmp(p->name, "readline") == 0) { 1099357b5d0Sserge-sans-paille p->initfunc = initlldb_readline; 1109357b5d0Sserge-sans-paille break; 1119357b5d0Sserge-sans-paille } 1129357b5d0Sserge-sans-paille } 1139357b5d0Sserge-sans-paille if (!ReadlinePatched) { 1149357b5d0Sserge-sans-paille PyImport_AppendInittab("readline", initlldb_readline); 1159357b5d0Sserge-sans-paille ReadlinePatched = true; 1169357b5d0Sserge-sans-paille } 1179357b5d0Sserge-sans-paille #endif 1189357b5d0Sserge-sans-paille 11974587a0eSVadim Chugunov // Register _lldb as a built-in module. 12005495c5dSJonas Devlieghere PyImport_AppendInittab("_lldb", LLDBSwigPyInit); 12174587a0eSVadim Chugunov 122079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 123079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 124079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 125079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 126079fe48aSZachary Turner Py_InitializeEx(0); 127079fe48aSZachary Turner InitializeThreadsPrivate(); 128079fe48aSZachary Turner #else 129079fe48aSZachary Turner InitializeThreadsPrivate(); 130079fe48aSZachary Turner Py_InitializeEx(0); 131079fe48aSZachary Turner #endif 132079fe48aSZachary Turner } 133079fe48aSZachary Turner 134b9c1b51eSKate Stone ~InitializePythonRAII() { 135b9c1b51eSKate Stone if (m_was_already_initialized) { 1363b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 1373b7e1981SPavel Labath LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 1381b6700efSTatyana Krasnukha m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 139079fe48aSZachary Turner PyGILState_Release(m_gil_state); 140b9c1b51eSKate Stone } else { 141079fe48aSZachary Turner // We initialized the threads in this function, just unlock the GIL. 142079fe48aSZachary Turner PyEval_SaveThread(); 143079fe48aSZachary Turner } 144079fe48aSZachary Turner } 145079fe48aSZachary Turner 146079fe48aSZachary Turner private: 147b9c1b51eSKate Stone void InitializePythonHome() { 1483ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME 1493ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3 1503ec3f62fSHaibo Huang typedef wchar_t* str_type; 1513ec3f62fSHaibo Huang #else 1523ec3f62fSHaibo Huang typedef char* str_type; 1533ec3f62fSHaibo Huang #endif 1543ec3f62fSHaibo Huang static str_type g_python_home = []() -> str_type { 1553ec3f62fSHaibo Huang const char *lldb_python_home = LLDB_PYTHON_HOME; 1563ec3f62fSHaibo Huang const char *absolute_python_home = nullptr; 1573ec3f62fSHaibo Huang llvm::SmallString<64> path; 1583ec3f62fSHaibo Huang if (llvm::sys::path::is_absolute(lldb_python_home)) { 1593ec3f62fSHaibo Huang absolute_python_home = lldb_python_home; 1603ec3f62fSHaibo Huang } else { 1613ec3f62fSHaibo Huang FileSpec spec = HostInfo::GetShlibDir(); 1623ec3f62fSHaibo Huang if (!spec) 1633ec3f62fSHaibo Huang return nullptr; 1643ec3f62fSHaibo Huang spec.GetPath(path); 1653ec3f62fSHaibo Huang llvm::sys::path::append(path, lldb_python_home); 1663ec3f62fSHaibo Huang absolute_python_home = path.c_str(); 1673ec3f62fSHaibo Huang } 16822c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3 16922c8efcdSZachary Turner size_t size = 0; 1703ec3f62fSHaibo Huang return Py_DecodeLocale(absolute_python_home, &size); 17122c8efcdSZachary Turner #else 1723ec3f62fSHaibo Huang return strdup(absolute_python_home); 17322c8efcdSZachary Turner #endif 1743ec3f62fSHaibo Huang }(); 1753ec3f62fSHaibo Huang if (g_python_home != nullptr) { 176079fe48aSZachary Turner Py_SetPythonHome(g_python_home); 1773ec3f62fSHaibo Huang } 178386f00dbSDavide Italiano #else 179386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 18063dd5d25SJonas Devlieghere // For Darwin, the only Python version supported is the one shipped in the 18163dd5d25SJonas Devlieghere // OS OS and linked with lldb. Other installation of Python may have higher 1824f9cb260SDavide Italiano // priorities in the path, overriding PYTHONHOME and causing 1834f9cb260SDavide Italiano // problems/incompatibilities. In order to avoid confusion, always hardcode 1844f9cb260SDavide Italiano // the PythonHome to be right, as it's not going to change. 18563dd5d25SJonas Devlieghere static char path[] = 18663dd5d25SJonas Devlieghere "/System/Library/Frameworks/Python.framework/Versions/2.7"; 1874f9cb260SDavide Italiano Py_SetPythonHome(path); 188386f00dbSDavide Italiano #endif 189386f00dbSDavide Italiano #endif 19022c8efcdSZachary Turner } 19122c8efcdSZachary Turner 192b9c1b51eSKate Stone void InitializeThreadsPrivate() { 1931b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, 1941b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter 1951b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized` 1961b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be 1971b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When 1981b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. 1991b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) 2001b6700efSTatyana Krasnukha // The only case we should go further and acquire the GIL: it is unlocked. 2011b6700efSTatyana Krasnukha if (PyGILState_Check()) 2021b6700efSTatyana Krasnukha return; 2031b6700efSTatyana Krasnukha #endif 2041b6700efSTatyana Krasnukha 205b9c1b51eSKate Stone if (PyEval_ThreadsInitialized()) { 2063b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 207079fe48aSZachary Turner 208079fe48aSZachary Turner m_was_already_initialized = true; 209079fe48aSZachary Turner m_gil_state = PyGILState_Ensure(); 2103b7e1981SPavel Labath LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n", 211079fe48aSZachary Turner m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 212079fe48aSZachary Turner return; 213079fe48aSZachary Turner } 214079fe48aSZachary Turner 215079fe48aSZachary Turner // InitThreads acquires the GIL if it hasn't been called before. 216079fe48aSZachary Turner PyEval_InitThreads(); 217079fe48aSZachary Turner } 218079fe48aSZachary Turner 2199494c510SJonas Devlieghere PyGILState_STATE m_gil_state = PyGILState_UNLOCKED; 2209494c510SJonas Devlieghere bool m_was_already_initialized = false; 221079fe48aSZachary Turner }; 22263dd5d25SJonas Devlieghere } // namespace 2232c1f46dcSZachary Turner 2242df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple( 2252df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 2262df331b0SPavel Labath auto style = llvm::sys::path::Style::posix; 2272df331b0SPavel Labath 2282df331b0SPavel Labath llvm::StringRef path_ref(path.begin(), path.size()); 2292df331b0SPavel Labath auto rbegin = llvm::sys::path::rbegin(path_ref, style); 2302df331b0SPavel Labath auto rend = llvm::sys::path::rend(path_ref); 2312df331b0SPavel Labath auto framework = std::find(rbegin, rend, "LLDB.framework"); 2322df331b0SPavel Labath if (framework == rend) { 23361f471a7SHaibo Huang ComputePythonDir(path); 2342df331b0SPavel Labath return; 2352df331b0SPavel Labath } 2362df331b0SPavel Labath path.resize(framework - rend); 2372df331b0SPavel Labath llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python"); 2382df331b0SPavel Labath } 2392df331b0SPavel Labath 24061f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir( 2412df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 2422df331b0SPavel Labath // Build the path by backing out of the lib dir, then building with whatever 2432df331b0SPavel Labath // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL 24461f471a7SHaibo Huang // x86_64, or bin on Windows). 24561f471a7SHaibo Huang llvm::sys::path::remove_filename(path); 24661f471a7SHaibo Huang llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR); 2470016b450SHaibo Huang 2480016b450SHaibo Huang #if defined(_WIN32) 2490016b450SHaibo Huang // This will be injected directly through FileSpec.GetDirectory().SetString(), 2500016b450SHaibo Huang // so we need to normalize manually. 2510016b450SHaibo Huang std::replace(path.begin(), path.end(), '\\', '/'); 2520016b450SHaibo Huang #endif 2532df331b0SPavel Labath } 2542df331b0SPavel Labath 2552df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() { 2562df331b0SPavel Labath static FileSpec g_spec = []() { 2572df331b0SPavel Labath FileSpec spec = HostInfo::GetShlibDir(); 2582df331b0SPavel Labath if (!spec) 2592df331b0SPavel Labath return FileSpec(); 2602df331b0SPavel Labath llvm::SmallString<64> path; 2612df331b0SPavel Labath spec.GetPath(path); 2622df331b0SPavel Labath 2632df331b0SPavel Labath #if defined(__APPLE__) 2642df331b0SPavel Labath ComputePythonDirForApple(path); 2652df331b0SPavel Labath #else 26661f471a7SHaibo Huang ComputePythonDir(path); 2672df331b0SPavel Labath #endif 2682df331b0SPavel Labath spec.GetDirectory().SetString(path); 2692df331b0SPavel Labath return spec; 2702df331b0SPavel Labath }(); 2712df331b0SPavel Labath return g_spec; 2722df331b0SPavel Labath } 2732df331b0SPavel Labath 2744c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"( 2754c2cf3a3SLawrence D'Anna import os 2764c2cf3a3SLawrence D'Anna import sys 2774c2cf3a3SLawrence D'Anna 2784c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path): 2794c2cf3a3SLawrence D'Anna info = { 2804c2cf3a3SLawrence D'Anna "lldb-pythonpath": lldb_python_dir, 2814c2cf3a3SLawrence D'Anna "language": "python", 2824c2cf3a3SLawrence D'Anna "prefix": sys.prefix, 2834c2cf3a3SLawrence D'Anna "executable": os.path.join(sys.prefix, python_exe_relative_path) 2844c2cf3a3SLawrence D'Anna } 2854c2cf3a3SLawrence D'Anna return info 2864c2cf3a3SLawrence D'Anna )"; 2874c2cf3a3SLawrence D'Anna 2884c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH; 2894c2cf3a3SLawrence D'Anna 290bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() { 291bbef51ebSLawrence D'Anna GIL gil; 292bbef51ebSLawrence D'Anna FileSpec python_dir_spec = GetPythonDir(); 293bbef51ebSLawrence D'Anna if (!python_dir_spec) 294bbef51ebSLawrence D'Anna return nullptr; 2954c2cf3a3SLawrence D'Anna PythonScript get_info(GetInterpreterInfoScript); 2964c2cf3a3SLawrence D'Anna auto info_json = unwrapIgnoringErrors( 2974c2cf3a3SLawrence D'Anna As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()), 2984c2cf3a3SLawrence D'Anna PythonString(python_exe_relative_path)))); 299bbef51ebSLawrence D'Anna if (!info_json) 300bbef51ebSLawrence D'Anna return nullptr; 301bbef51ebSLawrence D'Anna return info_json.CreateStructuredDictionary(); 302bbef51ebSLawrence D'Anna } 303bbef51ebSLawrence D'Anna 304004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper( 305004a264fSPavel Labath FileSpec &this_file) { 306004a264fSPavel Labath // When we're loaded from python, this_file will point to the file inside the 307004a264fSPavel Labath // python package directory. Replace it with the one in the lib directory. 308004a264fSPavel Labath #ifdef _WIN32 309004a264fSPavel Labath // On windows, we need to manually back out of the python tree, and go into 310004a264fSPavel Labath // the bin directory. This is pretty much the inverse of what ComputePythonDir 311004a264fSPavel Labath // does. 312004a264fSPavel Labath if (this_file.GetFileNameExtension() == ConstString(".pyd")) { 313004a264fSPavel Labath this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd 314004a264fSPavel Labath this_file.RemoveLastPathComponent(); // lldb 3152e826088SPavel Labath llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR; 3162e826088SPavel Labath for (auto it = llvm::sys::path::begin(libdir), 3172e826088SPavel Labath end = llvm::sys::path::end(libdir); 318004a264fSPavel Labath it != end; ++it) 319004a264fSPavel Labath this_file.RemoveLastPathComponent(); 320004a264fSPavel Labath this_file.AppendPathComponent("bin"); 321004a264fSPavel Labath this_file.AppendPathComponent("liblldb.dll"); 322004a264fSPavel Labath } 323004a264fSPavel Labath #else 324004a264fSPavel Labath // The python file is a symlink, so we can find the real library by resolving 325004a264fSPavel Labath // it. We can do this unconditionally. 326004a264fSPavel Labath FileSystem::Instance().ResolveSymbolicLink(this_file, this_file); 327004a264fSPavel Labath #endif 328004a264fSPavel Labath } 329004a264fSPavel Labath 3305f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() { 33163dd5d25SJonas Devlieghere return "Embedded Python interpreter"; 33263dd5d25SJonas Devlieghere } 33363dd5d25SJonas Devlieghere 33463dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() { 33563dd5d25SJonas Devlieghere static llvm::once_flag g_once_flag; 33663dd5d25SJonas Devlieghere 33763dd5d25SJonas Devlieghere llvm::call_once(g_once_flag, []() { 33863dd5d25SJonas Devlieghere PluginManager::RegisterPlugin(GetPluginNameStatic(), 33963dd5d25SJonas Devlieghere GetPluginDescriptionStatic(), 34063dd5d25SJonas Devlieghere lldb::eScriptLanguagePython, 34163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance); 34263dd5d25SJonas Devlieghere }); 34363dd5d25SJonas Devlieghere } 34463dd5d25SJonas Devlieghere 34563dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {} 34663dd5d25SJonas Devlieghere 34763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker( 34863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, 349b07823f3SLawrence D'Anna uint16_t on_leave, FileSP in, FileSP out, FileSP err) 35063dd5d25SJonas Devlieghere : ScriptInterpreterLocker(), 35163dd5d25SJonas Devlieghere m_teardown_session((on_leave & TearDownSession) == TearDownSession), 35263dd5d25SJonas Devlieghere m_python_interpreter(py_interpreter) { 35363dd5d25SJonas Devlieghere DoAcquireLock(); 35463dd5d25SJonas Devlieghere if ((on_entry & InitSession) == InitSession) { 35563dd5d25SJonas Devlieghere if (!DoInitSession(on_entry, in, out, err)) { 35663dd5d25SJonas Devlieghere // Don't teardown the session if we didn't init it. 35763dd5d25SJonas Devlieghere m_teardown_session = false; 35863dd5d25SJonas Devlieghere } 35963dd5d25SJonas Devlieghere } 36063dd5d25SJonas Devlieghere } 36163dd5d25SJonas Devlieghere 36263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { 36363dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 36463dd5d25SJonas Devlieghere m_GILState = PyGILState_Ensure(); 36563dd5d25SJonas Devlieghere LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", 36663dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 36763dd5d25SJonas Devlieghere 36863dd5d25SJonas Devlieghere // we need to save the thread state when we first start the command because 36963dd5d25SJonas Devlieghere // we might decide to interrupt it while some action is taking place outside 37063dd5d25SJonas Devlieghere // of Python (e.g. printing to screen, waiting for the network, ...) in that 37163dd5d25SJonas Devlieghere // case, _PyThreadState_Current will be NULL - and we would be unable to set 37263dd5d25SJonas Devlieghere // the asynchronous exception - not a desirable situation 37363dd5d25SJonas Devlieghere m_python_interpreter->SetThreadState(PyThreadState_Get()); 37463dd5d25SJonas Devlieghere m_python_interpreter->IncrementLockCount(); 37563dd5d25SJonas Devlieghere return true; 37663dd5d25SJonas Devlieghere } 37763dd5d25SJonas Devlieghere 37863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, 379b07823f3SLawrence D'Anna FileSP in, FileSP out, 380b07823f3SLawrence D'Anna FileSP err) { 38163dd5d25SJonas Devlieghere if (!m_python_interpreter) 38263dd5d25SJonas Devlieghere return false; 38363dd5d25SJonas Devlieghere return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); 38463dd5d25SJonas Devlieghere } 38563dd5d25SJonas Devlieghere 38663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { 38763dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 38863dd5d25SJonas Devlieghere LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 38963dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 39063dd5d25SJonas Devlieghere PyGILState_Release(m_GILState); 39163dd5d25SJonas Devlieghere m_python_interpreter->DecrementLockCount(); 39263dd5d25SJonas Devlieghere return true; 39363dd5d25SJonas Devlieghere } 39463dd5d25SJonas Devlieghere 39563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { 39663dd5d25SJonas Devlieghere if (!m_python_interpreter) 39763dd5d25SJonas Devlieghere return false; 39863dd5d25SJonas Devlieghere m_python_interpreter->LeaveSession(); 39963dd5d25SJonas Devlieghere return true; 40063dd5d25SJonas Devlieghere } 40163dd5d25SJonas Devlieghere 40263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() { 40363dd5d25SJonas Devlieghere if (m_teardown_session) 40463dd5d25SJonas Devlieghere DoTearDownSession(); 40563dd5d25SJonas Devlieghere DoFreeLock(); 40663dd5d25SJonas Devlieghere } 40763dd5d25SJonas Devlieghere 4088d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) 4098d1fb843SJonas Devlieghere : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), 41063dd5d25SJonas Devlieghere m_saved_stderr(), m_main_module(), 41163dd5d25SJonas Devlieghere m_session_dict(PyInitialValue::Invalid), 41263dd5d25SJonas Devlieghere m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), 41363dd5d25SJonas Devlieghere m_run_one_line_str_global(), 4148d1fb843SJonas Devlieghere m_dictionary_name(m_debugger.GetInstanceName().AsCString()), 415ea1752a7SJonas Devlieghere m_active_io_handler(eIOHandlerNone), m_session_is_active(false), 41664ec505dSJonas Devlieghere m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0), 417ea1752a7SJonas Devlieghere m_command_thread_state(nullptr) { 41863dd5d25SJonas Devlieghere InitializePrivate(); 41963dd5d25SJonas Devlieghere 4201f6a57c1SMed Ismail Bennani m_scripted_process_interface_up = 4211f6a57c1SMed Ismail Bennani std::make_unique<ScriptedProcessPythonInterface>(*this); 4221f6a57c1SMed Ismail Bennani 42363dd5d25SJonas Devlieghere m_dictionary_name.append("_dict"); 42463dd5d25SJonas Devlieghere StreamString run_string; 42563dd5d25SJonas Devlieghere run_string.Printf("%s = dict()", m_dictionary_name.c_str()); 42663dd5d25SJonas Devlieghere 42763dd5d25SJonas Devlieghere Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 42863dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 42963dd5d25SJonas Devlieghere 43063dd5d25SJonas Devlieghere run_string.Clear(); 43163dd5d25SJonas Devlieghere run_string.Printf( 43263dd5d25SJonas Devlieghere "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", 43363dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 43463dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 43563dd5d25SJonas Devlieghere 43663dd5d25SJonas Devlieghere // Reloading modules requires a different syntax in Python 2 and Python 3. 43763dd5d25SJonas Devlieghere // This provides a consistent syntax no matter what version of Python. 43863dd5d25SJonas Devlieghere run_string.Clear(); 43963dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", 44063dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 44163dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 44263dd5d25SJonas Devlieghere 44363dd5d25SJonas Devlieghere // WARNING: temporary code that loads Cocoa formatters - this should be done 44463dd5d25SJonas Devlieghere // on a per-platform basis rather than loading the whole set and letting the 44563dd5d25SJonas Devlieghere // individual formatter classes exploit APIs to check whether they can/cannot 44663dd5d25SJonas Devlieghere // do their task 44763dd5d25SJonas Devlieghere run_string.Clear(); 44863dd5d25SJonas Devlieghere run_string.Printf( 44963dd5d25SJonas Devlieghere "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", 45063dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 45163dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 45263dd5d25SJonas Devlieghere run_string.Clear(); 45363dd5d25SJonas Devlieghere 45463dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " 45563dd5d25SJonas Devlieghere "lldb.embedded_interpreter import run_python_interpreter; " 45663dd5d25SJonas Devlieghere "from lldb.embedded_interpreter import run_one_line')", 45763dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 45863dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 45963dd5d25SJonas Devlieghere run_string.Clear(); 46063dd5d25SJonas Devlieghere 46163dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 46263dd5d25SJonas Devlieghere "; pydoc.pager = pydoc.plainpager')", 4638d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 46463dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 46563dd5d25SJonas Devlieghere } 46663dd5d25SJonas Devlieghere 46763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { 46863dd5d25SJonas Devlieghere // the session dictionary may hold objects with complex state which means 46963dd5d25SJonas Devlieghere // that they may need to be torn down with some level of smarts and that, in 47063dd5d25SJonas Devlieghere // turn, requires a valid thread state force Python to procure itself such a 47163dd5d25SJonas Devlieghere // thread state, nuke the session dictionary and then release it for others 47263dd5d25SJonas Devlieghere // to use and proceed with the rest of the shutdown 47363dd5d25SJonas Devlieghere auto gil_state = PyGILState_Ensure(); 47463dd5d25SJonas Devlieghere m_session_dict.Reset(); 47563dd5d25SJonas Devlieghere PyGILState_Release(gil_state); 47663dd5d25SJonas Devlieghere } 47763dd5d25SJonas Devlieghere 47863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, 47963dd5d25SJonas Devlieghere bool interactive) { 4802c1f46dcSZachary Turner const char *instructions = nullptr; 4812c1f46dcSZachary Turner 482b9c1b51eSKate Stone switch (m_active_io_handler) { 4832c1f46dcSZachary Turner case eIOHandlerNone: 4842c1f46dcSZachary Turner break; 4852c1f46dcSZachary Turner case eIOHandlerBreakpoint: 4862c1f46dcSZachary Turner instructions = R"(Enter your Python command(s). Type 'DONE' to end. 4872c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict): 4882c1f46dcSZachary Turner """frame: the lldb.SBFrame for the location at which you stopped 4892c1f46dcSZachary Turner bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 4902c1f46dcSZachary Turner internal_dict: an LLDB support object not to be used""" 4912c1f46dcSZachary Turner )"; 4922c1f46dcSZachary Turner break; 4932c1f46dcSZachary Turner case eIOHandlerWatchpoint: 4942c1f46dcSZachary Turner instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 4952c1f46dcSZachary Turner break; 4962c1f46dcSZachary Turner } 4972c1f46dcSZachary Turner 498b9c1b51eSKate Stone if (instructions) { 4997ca15ba7SLawrence D'Anna StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); 5000affb582SDave Lee if (output_sp && interactive) { 5012c1f46dcSZachary Turner output_sp->PutCString(instructions); 5022c1f46dcSZachary Turner output_sp->Flush(); 5032c1f46dcSZachary Turner } 5042c1f46dcSZachary Turner } 5052c1f46dcSZachary Turner } 5062c1f46dcSZachary Turner 50763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, 508b9c1b51eSKate Stone std::string &data) { 5092c1f46dcSZachary Turner io_handler.SetIsDone(true); 5108d1fb843SJonas Devlieghere bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); 5112c1f46dcSZachary Turner 512b9c1b51eSKate Stone switch (m_active_io_handler) { 5132c1f46dcSZachary Turner case eIOHandlerNone: 5142c1f46dcSZachary Turner break; 515b9c1b51eSKate Stone case eIOHandlerBreakpoint: { 516cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec = 517cfb96d84SJim Ingham (std::vector<std::reference_wrapper<BreakpointOptions>> *) 518cfb96d84SJim Ingham io_handler.GetUserData(); 519cfb96d84SJim Ingham for (BreakpointOptions &bp_options : *bp_options_vec) { 5202c1f46dcSZachary Turner 521a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<CommandDataPython>(); 522d5b44036SJonas Devlieghere if (!data_up) 5234e4fbe82SZachary Turner break; 524d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 5252c1f46dcSZachary Turner 526738af7a6SJim Ingham StructuredData::ObjectSP empty_args_sp; 527d5b44036SJonas Devlieghere if (GenerateBreakpointCommandCallbackData(data_up->user_source, 528738af7a6SJim Ingham data_up->script_source, 529738af7a6SJim Ingham false) 530b9c1b51eSKate Stone .Success()) { 5314e4fbe82SZachary Turner auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( 532d5b44036SJonas Devlieghere std::move(data_up)); 533cfb96d84SJim Ingham bp_options.SetCallback( 53463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 535b9c1b51eSKate Stone } else if (!batch_mode) { 5367ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 537b9c1b51eSKate Stone if (error_sp) { 5382c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5392c1f46dcSZachary Turner error_sp->Flush(); 5402c1f46dcSZachary Turner } 5412c1f46dcSZachary Turner } 5422c1f46dcSZachary Turner } 5432c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 544b9c1b51eSKate Stone } break; 545b9c1b51eSKate Stone case eIOHandlerWatchpoint: { 546b9c1b51eSKate Stone WatchpointOptions *wp_options = 547b9c1b51eSKate Stone (WatchpointOptions *)io_handler.GetUserData(); 548a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 549d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 5502c1f46dcSZachary Turner 551d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 552d5b44036SJonas Devlieghere data_up->script_source)) { 5534e4fbe82SZachary Turner auto baton_sp = 554d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 555b9c1b51eSKate Stone wp_options->SetCallback( 55663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 557b9c1b51eSKate Stone } else if (!batch_mode) { 5587ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 559b9c1b51eSKate Stone if (error_sp) { 5602c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 5612c1f46dcSZachary Turner error_sp->Flush(); 5622c1f46dcSZachary Turner } 5632c1f46dcSZachary Turner } 5642c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 565b9c1b51eSKate Stone } break; 5662c1f46dcSZachary Turner } 5672c1f46dcSZachary Turner } 5682c1f46dcSZachary Turner 56963dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP 5708d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { 5718d1fb843SJonas Devlieghere return std::make_shared<ScriptInterpreterPythonImpl>(debugger); 57263dd5d25SJonas Devlieghere } 5732c1f46dcSZachary Turner 57463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() { 5752c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 5762c1f46dcSZachary Turner if (log) 57763dd5d25SJonas Devlieghere log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); 5782c1f46dcSZachary Turner 57920b52c33SJonas Devlieghere // Unset the LLDB global variables. 58020b52c33SJonas Devlieghere PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process " 58120b52c33SJonas Devlieghere "= None; lldb.thread = None; lldb.frame = None"); 58220b52c33SJonas Devlieghere 58305097246SAdrian Prantl // checking that we have a valid thread state - since we use our own 58405097246SAdrian Prantl // threading and locking in some (rare) cases during cleanup Python may end 58505097246SAdrian Prantl // up believing we have no thread state and PyImport_AddModule will crash if 58605097246SAdrian Prantl // that is the case - since that seems to only happen when destroying the 58705097246SAdrian Prantl // SBDebugger, we can make do without clearing up stdout and stderr 5882c1f46dcSZachary Turner 5892c1f46dcSZachary Turner // rdar://problem/11292882 590b9c1b51eSKate Stone // When the current thread state is NULL, PyThreadState_Get() issues a fatal 591b9c1b51eSKate Stone // error. 592b9c1b51eSKate Stone if (PyThreadState_GetDict()) { 5932c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 594b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 595b9c1b51eSKate Stone if (m_saved_stdin.IsValid()) { 596f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 5972c1f46dcSZachary Turner m_saved_stdin.Reset(); 5982c1f46dcSZachary Turner } 599b9c1b51eSKate Stone if (m_saved_stdout.IsValid()) { 600f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 6012c1f46dcSZachary Turner m_saved_stdout.Reset(); 6022c1f46dcSZachary Turner } 603b9c1b51eSKate Stone if (m_saved_stderr.IsValid()) { 604f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 6052c1f46dcSZachary Turner m_saved_stderr.Reset(); 6062c1f46dcSZachary Turner } 6072c1f46dcSZachary Turner } 6082c1f46dcSZachary Turner } 6092c1f46dcSZachary Turner 6102c1f46dcSZachary Turner m_session_is_active = false; 6112c1f46dcSZachary Turner } 6122c1f46dcSZachary Turner 613b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp, 614b07823f3SLawrence D'Anna const char *py_name, 615b07823f3SLawrence D'Anna PythonObject &save_file, 616b9c1b51eSKate Stone const char *mode) { 617b07823f3SLawrence D'Anna if (!file_sp || !*file_sp) { 618b07823f3SLawrence D'Anna save_file.Reset(); 619b07823f3SLawrence D'Anna return false; 620b07823f3SLawrence D'Anna } 621b07823f3SLawrence D'Anna File &file = *file_sp; 622b07823f3SLawrence D'Anna 623a31baf08SGreg Clayton // Flush the file before giving it to python to avoid interleaved output. 624a31baf08SGreg Clayton file.Flush(); 625a31baf08SGreg Clayton 626a31baf08SGreg Clayton PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 627a31baf08SGreg Clayton 6280f783599SLawrence D'Anna auto new_file = PythonFile::FromFile(file, mode); 6290f783599SLawrence D'Anna if (!new_file) { 6300f783599SLawrence D'Anna llvm::consumeError(new_file.takeError()); 6310f783599SLawrence D'Anna return false; 6320f783599SLawrence D'Anna } 6330f783599SLawrence D'Anna 634b07823f3SLawrence D'Anna save_file = sys_module_dict.GetItemForKey(PythonString(py_name)); 635a31baf08SGreg Clayton 6360f783599SLawrence D'Anna sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get()); 637a31baf08SGreg Clayton return true; 638a31baf08SGreg Clayton } 639a31baf08SGreg Clayton 64063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, 641b07823f3SLawrence D'Anna FileSP in_sp, FileSP out_sp, 642b07823f3SLawrence D'Anna FileSP err_sp) { 643b9c1b51eSKate Stone // If we have already entered the session, without having officially 'left' 64405097246SAdrian Prantl // it, then there is no need to 'enter' it again. 6452c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 646b9c1b51eSKate Stone if (m_session_is_active) { 64763e5fb76SJonas Devlieghere LLDB_LOGF( 64863e5fb76SJonas Devlieghere log, 64963dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 650b9c1b51eSKate Stone ") session is already active, returning without doing anything", 651b9c1b51eSKate Stone on_entry_flags); 6522c1f46dcSZachary Turner return false; 6532c1f46dcSZachary Turner } 6542c1f46dcSZachary Turner 65563e5fb76SJonas Devlieghere LLDB_LOGF( 65663e5fb76SJonas Devlieghere log, 65763e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")", 658b9c1b51eSKate Stone on_entry_flags); 6592c1f46dcSZachary Turner 6602c1f46dcSZachary Turner m_session_is_active = true; 6612c1f46dcSZachary Turner 6622c1f46dcSZachary Turner StreamString run_string; 6632c1f46dcSZachary Turner 664b9c1b51eSKate Stone if (on_entry_flags & Locker::InitGlobals) { 665b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 6668d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 667b9c1b51eSKate Stone run_string.Printf( 668b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 6698d1fb843SJonas Devlieghere m_debugger.GetID()); 6702c1f46dcSZachary Turner run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); 6712c1f46dcSZachary Turner run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); 6722c1f46dcSZachary Turner run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); 6732c1f46dcSZachary Turner run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 6742c1f46dcSZachary Turner run_string.PutCString("')"); 675b9c1b51eSKate Stone } else { 67605097246SAdrian Prantl // If we aren't initing the globals, we should still always set the 67705097246SAdrian Prantl // debugger (since that is always unique.) 678b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 6798d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 680b9c1b51eSKate Stone run_string.Printf( 681b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 6828d1fb843SJonas Devlieghere m_debugger.GetID()); 6832c1f46dcSZachary Turner run_string.PutCString("')"); 6842c1f46dcSZachary Turner } 6852c1f46dcSZachary Turner 6862c1f46dcSZachary Turner PyRun_SimpleString(run_string.GetData()); 6872c1f46dcSZachary Turner run_string.Clear(); 6882c1f46dcSZachary Turner 6892c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 690b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 691b07823f3SLawrence D'Anna lldb::FileSP top_in_sp; 692b07823f3SLawrence D'Anna lldb::StreamFileSP top_out_sp, top_err_sp; 693b07823f3SLawrence D'Anna if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp) 694b07823f3SLawrence D'Anna m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp, 695b07823f3SLawrence D'Anna top_err_sp); 6962c1f46dcSZachary Turner 697b9c1b51eSKate Stone if (on_entry_flags & Locker::NoSTDIN) { 6982c1f46dcSZachary Turner m_saved_stdin.Reset(); 699b9c1b51eSKate Stone } else { 700b07823f3SLawrence D'Anna if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) { 701b07823f3SLawrence D'Anna if (top_in_sp) 702b07823f3SLawrence D'Anna SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r"); 7032c1f46dcSZachary Turner } 704a31baf08SGreg Clayton } 705a31baf08SGreg Clayton 706b07823f3SLawrence D'Anna if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) { 707b07823f3SLawrence D'Anna if (top_out_sp) 708b07823f3SLawrence D'Anna SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w"); 709a31baf08SGreg Clayton } 710a31baf08SGreg Clayton 711b07823f3SLawrence D'Anna if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) { 712b07823f3SLawrence D'Anna if (top_err_sp) 713b07823f3SLawrence D'Anna SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w"); 714a31baf08SGreg Clayton } 7152c1f46dcSZachary Turner } 7162c1f46dcSZachary Turner 7172c1f46dcSZachary Turner if (PyErr_Occurred()) 7182c1f46dcSZachary Turner PyErr_Clear(); 7192c1f46dcSZachary Turner 7202c1f46dcSZachary Turner return true; 7212c1f46dcSZachary Turner } 7222c1f46dcSZachary Turner 72304edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() { 724f8b22f8fSZachary Turner if (!m_main_module.IsValid()) 72504edd189SLawrence D'Anna m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__")); 7262c1f46dcSZachary Turner return m_main_module; 7272c1f46dcSZachary Turner } 7282c1f46dcSZachary Turner 72963dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { 730f8b22f8fSZachary Turner if (m_session_dict.IsValid()) 731f8b22f8fSZachary Turner return m_session_dict; 732f8b22f8fSZachary Turner 7332c1f46dcSZachary Turner PythonObject &main_module = GetMainModule(); 734f8b22f8fSZachary Turner if (!main_module.IsValid()) 735f8b22f8fSZachary Turner return m_session_dict; 736f8b22f8fSZachary Turner 737b9c1b51eSKate Stone PythonDictionary main_dict(PyRefType::Borrowed, 738b9c1b51eSKate Stone PyModule_GetDict(main_module.get())); 739f8b22f8fSZachary Turner if (!main_dict.IsValid()) 740f8b22f8fSZachary Turner return m_session_dict; 741f8b22f8fSZachary Turner 742722b6189SLawrence D'Anna m_session_dict = unwrapIgnoringErrors( 743722b6189SLawrence D'Anna As<PythonDictionary>(main_dict.GetItem(m_dictionary_name))); 7442c1f46dcSZachary Turner return m_session_dict; 7452c1f46dcSZachary Turner } 7462c1f46dcSZachary Turner 74763dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { 748f8b22f8fSZachary Turner if (m_sys_module_dict.IsValid()) 749f8b22f8fSZachary Turner return m_sys_module_dict; 750722b6189SLawrence D'Anna PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys")); 751722b6189SLawrence D'Anna m_sys_module_dict = sys_module.GetDictionary(); 7522c1f46dcSZachary Turner return m_sys_module_dict; 7532c1f46dcSZachary Turner } 7542c1f46dcSZachary Turner 755a69bbe02SLawrence D'Anna llvm::Expected<unsigned> 756a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable( 757a69bbe02SLawrence D'Anna const llvm::StringRef &callable_name) { 758738af7a6SJim Ingham if (callable_name.empty()) { 759738af7a6SJim Ingham return llvm::createStringError( 760738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 761738af7a6SJim Ingham "called with empty callable name."); 762738af7a6SJim Ingham } 763738af7a6SJim Ingham Locker py_lock(this, Locker::AcquireLock | 764738af7a6SJim Ingham Locker::InitSession | 765738af7a6SJim Ingham Locker::NoSTDIN); 766738af7a6SJim Ingham auto dict = PythonModule::MainModule() 767738af7a6SJim Ingham .ResolveName<PythonDictionary>(m_dictionary_name); 768a69bbe02SLawrence D'Anna auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>( 769a69bbe02SLawrence D'Anna callable_name, dict); 770738af7a6SJim Ingham if (!pfunc.IsAllocated()) { 771738af7a6SJim Ingham return llvm::createStringError( 772738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 773738af7a6SJim Ingham "can't find callable: %s", callable_name.str().c_str()); 774738af7a6SJim Ingham } 775adbf64ccSLawrence D'Anna llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo(); 776adbf64ccSLawrence D'Anna if (!arg_info) 777adbf64ccSLawrence D'Anna return arg_info.takeError(); 778adbf64ccSLawrence D'Anna return arg_info.get().max_positional_args; 779738af7a6SJim Ingham } 780738af7a6SJim Ingham 781b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted, 7822c1f46dcSZachary Turner uint32_t &functions_counter, 783b9c1b51eSKate Stone const void *name_token = nullptr) { 7842c1f46dcSZachary Turner StreamString sstr; 7852c1f46dcSZachary Turner 7862c1f46dcSZachary Turner if (!base_name_wanted) 7872c1f46dcSZachary Turner return std::string(); 7882c1f46dcSZachary Turner 7892c1f46dcSZachary Turner if (!name_token) 7902c1f46dcSZachary Turner sstr.Printf("%s_%d", base_name_wanted, functions_counter++); 7912c1f46dcSZachary Turner else 7922c1f46dcSZachary Turner sstr.Printf("%s_%p", base_name_wanted, name_token); 7932c1f46dcSZachary Turner 794adcd0268SBenjamin Kramer return std::string(sstr.GetString()); 7952c1f46dcSZachary Turner } 7962c1f46dcSZachary Turner 79763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { 798f8b22f8fSZachary Turner if (m_run_one_line_function.IsValid()) 799f8b22f8fSZachary Turner return true; 800f8b22f8fSZachary Turner 801b9c1b51eSKate Stone PythonObject module(PyRefType::Borrowed, 802b9c1b51eSKate Stone PyImport_AddModule("lldb.embedded_interpreter")); 803f8b22f8fSZachary Turner if (!module.IsValid()) 804f8b22f8fSZachary Turner return false; 805f8b22f8fSZachary Turner 806b9c1b51eSKate Stone PythonDictionary module_dict(PyRefType::Borrowed, 807b9c1b51eSKate Stone PyModule_GetDict(module.get())); 808f8b22f8fSZachary Turner if (!module_dict.IsValid()) 809f8b22f8fSZachary Turner return false; 810f8b22f8fSZachary Turner 811b9c1b51eSKate Stone m_run_one_line_function = 812b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("run_one_line")); 813b9c1b51eSKate Stone m_run_one_line_str_global = 814b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 815f8b22f8fSZachary Turner return m_run_one_line_function.IsValid(); 8162c1f46dcSZachary Turner } 8172c1f46dcSZachary Turner 81863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine( 8194d51a902SRaphael Isemann llvm::StringRef command, CommandReturnObject *result, 820b9c1b51eSKate Stone const ExecuteScriptOptions &options) { 821d6c062bcSRaphael Isemann std::string command_str = command.str(); 822d6c062bcSRaphael Isemann 8232c1f46dcSZachary Turner if (!m_valid_session) 8242c1f46dcSZachary Turner return false; 8252c1f46dcSZachary Turner 8264d51a902SRaphael Isemann if (!command.empty()) { 827b9c1b51eSKate Stone // We want to call run_one_line, passing in the dictionary and the command 82805097246SAdrian Prantl // string. We cannot do this through PyRun_SimpleString here because the 82905097246SAdrian Prantl // command string may contain escaped characters, and putting it inside 830b9c1b51eSKate Stone // another string to pass to PyRun_SimpleString messes up the escaping. So 83105097246SAdrian Prantl // we use the following more complicated method to pass the command string 83205097246SAdrian Prantl // directly down to Python. 833d79273c9SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 83484228365SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 83584228365SJonas Devlieghere options.GetEnableIO(), m_debugger, result); 836d79273c9SJonas Devlieghere if (!io_redirect_or_error) { 837d79273c9SJonas Devlieghere if (result) 838d79273c9SJonas Devlieghere result->AppendErrorWithFormatv( 839d79273c9SJonas Devlieghere "failed to redirect I/O: {0}\n", 840d79273c9SJonas Devlieghere llvm::fmt_consume(io_redirect_or_error.takeError())); 841d79273c9SJonas Devlieghere else 842d79273c9SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError()); 8432fce1137SLawrence D'Anna return false; 8442fce1137SLawrence D'Anna } 845d79273c9SJonas Devlieghere 846d79273c9SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 8472c1f46dcSZachary Turner 84832064024SZachary Turner bool success = false; 84932064024SZachary Turner { 85005097246SAdrian Prantl // WARNING! It's imperative that this RAII scope be as tight as 85105097246SAdrian Prantl // possible. In particular, the scope must end *before* we try to join 85205097246SAdrian Prantl // the read thread. The reason for this is that a pre-requisite for 85305097246SAdrian Prantl // joining the read thread is that we close the write handle (to break 85405097246SAdrian Prantl // the pipe and cause it to wake up and exit). But acquiring the GIL as 85505097246SAdrian Prantl // below will redirect Python's stdio to use this same handle. If we 85605097246SAdrian Prantl // close the handle while Python is still using it, bad things will 85705097246SAdrian Prantl // happen. 858b9c1b51eSKate Stone Locker locker( 859b9c1b51eSKate Stone this, 86063dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 86163dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 8622c1f46dcSZachary Turner ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), 863d79273c9SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 864d79273c9SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 865d79273c9SJonas Devlieghere io_redirect.GetErrorFile()); 8662c1f46dcSZachary Turner 8672c1f46dcSZachary Turner // Find the correct script interpreter dictionary in the main module. 8682c1f46dcSZachary Turner PythonDictionary &session_dict = GetSessionDictionary(); 869b9c1b51eSKate Stone if (session_dict.IsValid()) { 870b9c1b51eSKate Stone if (GetEmbeddedInterpreterModuleObjects()) { 871b9c1b51eSKate Stone if (PyCallable_Check(m_run_one_line_function.get())) { 872b9c1b51eSKate Stone PythonObject pargs( 873b9c1b51eSKate Stone PyRefType::Owned, 874d6c062bcSRaphael Isemann Py_BuildValue("(Os)", session_dict.get(), command_str.c_str())); 875b9c1b51eSKate Stone if (pargs.IsValid()) { 876b9c1b51eSKate Stone PythonObject return_value( 877b9c1b51eSKate Stone PyRefType::Owned, 878b9c1b51eSKate Stone PyObject_CallObject(m_run_one_line_function.get(), 879b9c1b51eSKate Stone pargs.get())); 880f8b22f8fSZachary Turner if (return_value.IsValid()) 8812c1f46dcSZachary Turner success = true; 882b9c1b51eSKate Stone else if (options.GetMaskoutErrors() && PyErr_Occurred()) { 8832c1f46dcSZachary Turner PyErr_Print(); 8842c1f46dcSZachary Turner PyErr_Clear(); 8852c1f46dcSZachary Turner } 8862c1f46dcSZachary Turner } 8872c1f46dcSZachary Turner } 8882c1f46dcSZachary Turner } 8892c1f46dcSZachary Turner } 8902c1f46dcSZachary Turner 891d79273c9SJonas Devlieghere io_redirect.Flush(); 8922c1f46dcSZachary Turner } 8932c1f46dcSZachary Turner 8942c1f46dcSZachary Turner if (success) 8952c1f46dcSZachary Turner return true; 8962c1f46dcSZachary Turner 8972c1f46dcSZachary Turner // The one-liner failed. Append the error message. 8984d51a902SRaphael Isemann if (result) { 899b9c1b51eSKate Stone result->AppendErrorWithFormat( 9004d51a902SRaphael Isemann "python failed attempting to evaluate '%s'\n", command_str.c_str()); 9014d51a902SRaphael Isemann } 9022c1f46dcSZachary Turner return false; 9032c1f46dcSZachary Turner } 9042c1f46dcSZachary Turner 9052c1f46dcSZachary Turner if (result) 9062c1f46dcSZachary Turner result->AppendError("empty command passed to python\n"); 9072c1f46dcSZachary Turner return false; 9082c1f46dcSZachary Turner } 9092c1f46dcSZachary Turner 91063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { 9115c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 9122c1f46dcSZachary Turner 9138d1fb843SJonas Devlieghere Debugger &debugger = m_debugger; 9142c1f46dcSZachary Turner 915b9c1b51eSKate Stone // At the moment, the only time the debugger does not have an input file 91605097246SAdrian Prantl // handle is when this is called directly from Python, in which case it is 91705097246SAdrian Prantl // both dangerous and unnecessary (not to mention confusing) to try to embed 91805097246SAdrian Prantl // a running interpreter loop inside the already running Python interpreter 91905097246SAdrian Prantl // loop, so we won't do it. 9202c1f46dcSZachary Turner 9217ca15ba7SLawrence D'Anna if (!debugger.GetInputFile().IsValid()) 9222c1f46dcSZachary Turner return; 9232c1f46dcSZachary Turner 9242c1f46dcSZachary Turner IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this)); 925b9c1b51eSKate Stone if (io_handler_sp) { 9267ce2de2cSJonas Devlieghere debugger.RunIOHandlerAsync(io_handler_sp); 9272c1f46dcSZachary Turner } 9282c1f46dcSZachary Turner } 9292c1f46dcSZachary Turner 93063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() { 931049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 932049ae930SJonas Devlieghere // If the interpreter isn't evaluating any Python at the moment then return 933049ae930SJonas Devlieghere // false to signal that this function didn't handle the interrupt and the 934049ae930SJonas Devlieghere // next component should try handling it. 935049ae930SJonas Devlieghere if (!IsExecutingPython()) 936049ae930SJonas Devlieghere return false; 937049ae930SJonas Devlieghere 938049ae930SJonas Devlieghere // Tell Python that it should pretend to have received a SIGINT. 939049ae930SJonas Devlieghere PyErr_SetInterrupt(); 940049ae930SJonas Devlieghere // PyErr_SetInterrupt has no way to return an error so we can only pretend the 941049ae930SJonas Devlieghere // signal got successfully handled and return true. 942049ae930SJonas Devlieghere // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but 943049ae930SJonas Devlieghere // the error handling is limited to checking the arguments which would be 944049ae930SJonas Devlieghere // just our (hardcoded) input signal code SIGINT, so that's not useful at all. 945049ae930SJonas Devlieghere return true; 946049ae930SJonas Devlieghere #else 9472c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 9482c1f46dcSZachary Turner 949b9c1b51eSKate Stone if (IsExecutingPython()) { 950b1cf558dSEnrico Granata PyThreadState *state = PyThreadState_GET(); 9512c1f46dcSZachary Turner if (!state) 9522c1f46dcSZachary Turner state = GetThreadState(); 953b9c1b51eSKate Stone if (state) { 9542c1f46dcSZachary Turner long tid = state->thread_id; 95522c8efcdSZachary Turner PyThreadState_Swap(state); 9562c1f46dcSZachary Turner int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 95763e5fb76SJonas Devlieghere LLDB_LOGF(log, 95863e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() sending " 959b9c1b51eSKate Stone "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", 960b9c1b51eSKate Stone tid, num_threads); 9612c1f46dcSZachary Turner return true; 9622c1f46dcSZachary Turner } 9632c1f46dcSZachary Turner } 96463e5fb76SJonas Devlieghere LLDB_LOGF(log, 96563dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() python code not running, " 966b9c1b51eSKate Stone "can't interrupt"); 9672c1f46dcSZachary Turner return false; 968049ae930SJonas Devlieghere #endif 9692c1f46dcSZachary Turner } 97004edd189SLawrence D'Anna 97163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( 9724d51a902SRaphael Isemann llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, 973b9c1b51eSKate Stone void *ret_value, const ExecuteScriptOptions &options) { 9742c1f46dcSZachary Turner 975f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 976f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 977f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr); 978f9517353SJonas Devlieghere 979f9517353SJonas Devlieghere if (!io_redirect_or_error) { 980f9517353SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError()); 981f9517353SJonas Devlieghere return false; 982f9517353SJonas Devlieghere } 983f9517353SJonas Devlieghere 984f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 985f9517353SJonas Devlieghere 98663dd5d25SJonas Devlieghere Locker locker(this, 98763dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 98863dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 989b9c1b51eSKate Stone Locker::NoSTDIN, 990f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 991f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 992f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 9932c1f46dcSZachary Turner 99404edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 99504edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 9962c1f46dcSZachary Turner 9972c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 99804edd189SLawrence D'Anna if (!locals.IsValid()) 999722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1000722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1001f8b22f8fSZachary Turner if (!locals.IsValid()) 10022c1f46dcSZachary Turner locals = globals; 10032c1f46dcSZachary Turner 100404edd189SLawrence D'Anna Expected<PythonObject> maybe_py_return = 100504edd189SLawrence D'Anna runStringOneLine(in_string, globals, locals); 10062c1f46dcSZachary Turner 100704edd189SLawrence D'Anna if (!maybe_py_return) { 100804edd189SLawrence D'Anna llvm::handleAllErrors( 100904edd189SLawrence D'Anna maybe_py_return.takeError(), 101004edd189SLawrence D'Anna [&](PythonException &E) { 101104edd189SLawrence D'Anna E.Restore(); 101204edd189SLawrence D'Anna if (options.GetMaskoutErrors()) { 101304edd189SLawrence D'Anna if (E.Matches(PyExc_SyntaxError)) { 101404edd189SLawrence D'Anna PyErr_Print(); 10152c1f46dcSZachary Turner } 101604edd189SLawrence D'Anna PyErr_Clear(); 101704edd189SLawrence D'Anna } 101804edd189SLawrence D'Anna }, 101904edd189SLawrence D'Anna [](const llvm::ErrorInfoBase &E) {}); 102004edd189SLawrence D'Anna return false; 10212c1f46dcSZachary Turner } 10222c1f46dcSZachary Turner 102304edd189SLawrence D'Anna PythonObject py_return = std::move(maybe_py_return.get()); 102404edd189SLawrence D'Anna assert(py_return.IsValid()); 102504edd189SLawrence D'Anna 1026b9c1b51eSKate Stone switch (return_type) { 10272c1f46dcSZachary Turner case eScriptReturnTypeCharPtr: // "char *" 10282c1f46dcSZachary Turner { 10292c1f46dcSZachary Turner const char format[3] = "s#"; 103004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 10312c1f46dcSZachary Turner } 1032b9c1b51eSKate Stone case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == 1033b9c1b51eSKate Stone // Py_None 10342c1f46dcSZachary Turner { 10352c1f46dcSZachary Turner const char format[3] = "z"; 103604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 10372c1f46dcSZachary Turner } 1038b9c1b51eSKate Stone case eScriptReturnTypeBool: { 10392c1f46dcSZachary Turner const char format[2] = "b"; 104004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (bool *)ret_value); 10412c1f46dcSZachary Turner } 1042b9c1b51eSKate Stone case eScriptReturnTypeShortInt: { 10432c1f46dcSZachary Turner const char format[2] = "h"; 104404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (short *)ret_value); 10452c1f46dcSZachary Turner } 1046b9c1b51eSKate Stone case eScriptReturnTypeShortIntUnsigned: { 10472c1f46dcSZachary Turner const char format[2] = "H"; 104804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value); 10492c1f46dcSZachary Turner } 1050b9c1b51eSKate Stone case eScriptReturnTypeInt: { 10512c1f46dcSZachary Turner const char format[2] = "i"; 105204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (int *)ret_value); 10532c1f46dcSZachary Turner } 1054b9c1b51eSKate Stone case eScriptReturnTypeIntUnsigned: { 10552c1f46dcSZachary Turner const char format[2] = "I"; 105604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value); 10572c1f46dcSZachary Turner } 1058b9c1b51eSKate Stone case eScriptReturnTypeLongInt: { 10592c1f46dcSZachary Turner const char format[2] = "l"; 106004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long *)ret_value); 10612c1f46dcSZachary Turner } 1062b9c1b51eSKate Stone case eScriptReturnTypeLongIntUnsigned: { 10632c1f46dcSZachary Turner const char format[2] = "k"; 106404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value); 10652c1f46dcSZachary Turner } 1066b9c1b51eSKate Stone case eScriptReturnTypeLongLong: { 10672c1f46dcSZachary Turner const char format[2] = "L"; 106804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long long *)ret_value); 10692c1f46dcSZachary Turner } 1070b9c1b51eSKate Stone case eScriptReturnTypeLongLongUnsigned: { 10712c1f46dcSZachary Turner const char format[2] = "K"; 107204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, 107304edd189SLawrence D'Anna (unsigned long long *)ret_value); 10742c1f46dcSZachary Turner } 1075b9c1b51eSKate Stone case eScriptReturnTypeFloat: { 10762c1f46dcSZachary Turner const char format[2] = "f"; 107704edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (float *)ret_value); 10782c1f46dcSZachary Turner } 1079b9c1b51eSKate Stone case eScriptReturnTypeDouble: { 10802c1f46dcSZachary Turner const char format[2] = "d"; 108104edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (double *)ret_value); 10822c1f46dcSZachary Turner } 1083b9c1b51eSKate Stone case eScriptReturnTypeChar: { 10842c1f46dcSZachary Turner const char format[2] = "c"; 108504edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char *)ret_value); 10862c1f46dcSZachary Turner } 1087b9c1b51eSKate Stone case eScriptReturnTypeOpaqueObject: { 108804edd189SLawrence D'Anna *((PyObject **)ret_value) = py_return.release(); 108904edd189SLawrence D'Anna return true; 10902c1f46dcSZachary Turner } 10912c1f46dcSZachary Turner } 10921dfb1a85SPavel Labath llvm_unreachable("Fully covered switch!"); 10932c1f46dcSZachary Turner } 10942c1f46dcSZachary Turner 109563dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( 1096b9c1b51eSKate Stone const char *in_string, const ExecuteScriptOptions &options) { 109704edd189SLawrence D'Anna 109804edd189SLawrence D'Anna if (in_string == nullptr) 109904edd189SLawrence D'Anna return Status(); 11002c1f46dcSZachary Turner 1101f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 1102f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 1103f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr); 1104f9517353SJonas Devlieghere 1105f9517353SJonas Devlieghere if (!io_redirect_or_error) 1106f9517353SJonas Devlieghere return Status(io_redirect_or_error.takeError()); 1107f9517353SJonas Devlieghere 1108f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 1109f9517353SJonas Devlieghere 111063dd5d25SJonas Devlieghere Locker locker(this, 111163dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 111263dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1113b9c1b51eSKate Stone Locker::NoSTDIN, 1114f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 1115f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 1116f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 11172c1f46dcSZachary Turner 111804edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 111904edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 11202c1f46dcSZachary Turner 11212c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 1122f8b22f8fSZachary Turner if (!locals.IsValid()) 1123722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1124722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1125f8b22f8fSZachary Turner if (!locals.IsValid()) 11262c1f46dcSZachary Turner locals = globals; 11272c1f46dcSZachary Turner 112804edd189SLawrence D'Anna Expected<PythonObject> return_value = 112904edd189SLawrence D'Anna runStringMultiLine(in_string, globals, locals); 11302c1f46dcSZachary Turner 113104edd189SLawrence D'Anna if (!return_value) { 113204edd189SLawrence D'Anna llvm::Error error = 113304edd189SLawrence D'Anna llvm::handleErrors(return_value.takeError(), [&](PythonException &E) { 113404edd189SLawrence D'Anna llvm::Error error = llvm::createStringError( 113504edd189SLawrence D'Anna llvm::inconvertibleErrorCode(), E.ReadBacktrace()); 113604edd189SLawrence D'Anna if (!options.GetMaskoutErrors()) 113704edd189SLawrence D'Anna E.Restore(); 11382c1f46dcSZachary Turner return error; 113904edd189SLawrence D'Anna }); 114004edd189SLawrence D'Anna return Status(std::move(error)); 114104edd189SLawrence D'Anna } 114204edd189SLawrence D'Anna 114304edd189SLawrence D'Anna return Status(); 11442c1f46dcSZachary Turner } 11452c1f46dcSZachary Turner 114663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( 1147cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, 1148b9c1b51eSKate Stone CommandReturnObject &result) { 11492c1f46dcSZachary Turner m_active_io_handler = eIOHandlerBreakpoint; 11508d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1151a6faf851SJonas Devlieghere " ", *this, &bp_options_vec); 11522c1f46dcSZachary Turner } 11532c1f46dcSZachary Turner 115463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( 1155b9c1b51eSKate Stone WatchpointOptions *wp_options, CommandReturnObject &result) { 11562c1f46dcSZachary Turner m_active_io_handler = eIOHandlerWatchpoint; 11578d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1158a6faf851SJonas Devlieghere " ", *this, wp_options); 11592c1f46dcSZachary Turner } 11602c1f46dcSZachary Turner 1161738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( 1162cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *function_name, 1163738af7a6SJim Ingham StructuredData::ObjectSP extra_args_sp) { 1164738af7a6SJim Ingham Status error; 11652c1f46dcSZachary Turner // For now just cons up a oneliner that calls the provided function. 11662c1f46dcSZachary Turner std::string oneliner("return "); 11672c1f46dcSZachary Turner oneliner += function_name; 1168738af7a6SJim Ingham 1169a69bbe02SLawrence D'Anna llvm::Expected<unsigned> maybe_args = 1170a69bbe02SLawrence D'Anna GetMaxPositionalArgumentsForCallable(function_name); 1171738af7a6SJim Ingham if (!maybe_args) { 1172a69bbe02SLawrence D'Anna error.SetErrorStringWithFormat( 1173a69bbe02SLawrence D'Anna "could not get num args: %s", 1174738af7a6SJim Ingham llvm::toString(maybe_args.takeError()).c_str()); 1175738af7a6SJim Ingham return error; 1176738af7a6SJim Ingham } 1177a69bbe02SLawrence D'Anna size_t max_args = *maybe_args; 1178738af7a6SJim Ingham 1179738af7a6SJim Ingham bool uses_extra_args = false; 1180a69bbe02SLawrence D'Anna if (max_args >= 4) { 1181738af7a6SJim Ingham uses_extra_args = true; 1182738af7a6SJim Ingham oneliner += "(frame, bp_loc, extra_args, internal_dict)"; 1183a69bbe02SLawrence D'Anna } else if (max_args >= 3) { 1184738af7a6SJim Ingham if (extra_args_sp) { 1185738af7a6SJim Ingham error.SetErrorString("cannot pass extra_args to a three argument callback" 1186738af7a6SJim Ingham ); 1187738af7a6SJim Ingham return error; 1188738af7a6SJim Ingham } 1189738af7a6SJim Ingham uses_extra_args = false; 11902c1f46dcSZachary Turner oneliner += "(frame, bp_loc, internal_dict)"; 1191738af7a6SJim Ingham } else { 1192738af7a6SJim Ingham error.SetErrorStringWithFormat("expected 3 or 4 argument " 1193a69bbe02SLawrence D'Anna "function, %s can only take %zu", 1194a69bbe02SLawrence D'Anna function_name, max_args); 1195738af7a6SJim Ingham return error; 1196738af7a6SJim Ingham } 1197738af7a6SJim Ingham 1198738af7a6SJim Ingham SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp, 1199738af7a6SJim Ingham uses_extra_args); 1200738af7a6SJim Ingham return error; 12012c1f46dcSZachary Turner } 12022c1f46dcSZachary Turner 120363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1204cfb96d84SJim Ingham BreakpointOptions &bp_options, 1205f7e07256SJim Ingham std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { 120697206d57SZachary Turner Status error; 1207f7e07256SJim Ingham error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, 1208738af7a6SJim Ingham cmd_data_up->script_source, 1209738af7a6SJim Ingham false); 1210f7e07256SJim Ingham if (error.Fail()) { 1211f7e07256SJim Ingham return error; 1212f7e07256SJim Ingham } 1213f7e07256SJim Ingham auto baton_sp = 1214f7e07256SJim Ingham std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); 1215cfb96d84SJim Ingham bp_options.SetCallback( 121663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 1217f7e07256SJim Ingham return error; 1218f7e07256SJim Ingham } 1219f7e07256SJim Ingham 122063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1221cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text) { 1222738af7a6SJim Ingham return SetBreakpointCommandCallback(bp_options, command_body_text, {},false); 1223738af7a6SJim Ingham } 12242c1f46dcSZachary Turner 1225738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint. 1226738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1227cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text, 1228cfb96d84SJim Ingham StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) { 1229738af7a6SJim Ingham auto data_up = std::make_unique<CommandDataPython>(extra_args_sp); 1230b9c1b51eSKate Stone // Split the command_body_text into lines, and pass that to 123105097246SAdrian Prantl // GenerateBreakpointCommandCallbackData. That will wrap the body in an 123205097246SAdrian Prantl // auto-generated function, and return the function name in script_source. 123305097246SAdrian Prantl // That is what the callback will actually invoke. 12342c1f46dcSZachary Turner 1235d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(command_body_text); 1236d5b44036SJonas Devlieghere Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, 1237738af7a6SJim Ingham data_up->script_source, 1238738af7a6SJim Ingham uses_extra_args); 1239b9c1b51eSKate Stone if (error.Success()) { 12404e4fbe82SZachary Turner auto baton_sp = 1241d5b44036SJonas Devlieghere std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 1242cfb96d84SJim Ingham bp_options.SetCallback( 124363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 12442c1f46dcSZachary Turner return error; 124593571c3cSJonas Devlieghere } 12462c1f46dcSZachary Turner return error; 12472c1f46dcSZachary Turner } 12482c1f46dcSZachary Turner 12492c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint. 125063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( 1251b9c1b51eSKate Stone WatchpointOptions *wp_options, const char *oneliner) { 1252a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 12532c1f46dcSZachary Turner 12542c1f46dcSZachary Turner // It's necessary to set both user_source and script_source to the oneliner. 1255b9c1b51eSKate Stone // The former is used to generate callback description (as in watchpoint 125605097246SAdrian Prantl // command list) while the latter is used for Python to interpret during the 125705097246SAdrian Prantl // actual callback. 12582c1f46dcSZachary Turner 1259d5b44036SJonas Devlieghere data_up->user_source.AppendString(oneliner); 1260d5b44036SJonas Devlieghere data_up->script_source.assign(oneliner); 12612c1f46dcSZachary Turner 1262d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 1263d5b44036SJonas Devlieghere data_up->script_source)) { 12644e4fbe82SZachary Turner auto baton_sp = 1265d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 126663dd5d25SJonas Devlieghere wp_options->SetCallback( 126763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 12682c1f46dcSZachary Turner } 12692c1f46dcSZachary Turner 12702c1f46dcSZachary Turner return; 12712c1f46dcSZachary Turner } 12722c1f46dcSZachary Turner 127363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( 1274b9c1b51eSKate Stone StringList &function_def) { 12752c1f46dcSZachary Turner // Convert StringList to one long, newline delimited, const char *. 12762c1f46dcSZachary Turner std::string function_def_string(function_def.CopyList()); 12772c1f46dcSZachary Turner 127897206d57SZachary Turner Status error = ExecuteMultipleLines( 1279b9c1b51eSKate Stone function_def_string.c_str(), 1280fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false)); 12812c1f46dcSZachary Turner return error; 12822c1f46dcSZachary Turner } 12832c1f46dcSZachary Turner 128463dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, 1285b9c1b51eSKate Stone const StringList &input) { 128697206d57SZachary Turner Status error; 12872c1f46dcSZachary Turner int num_lines = input.GetSize(); 1288b9c1b51eSKate Stone if (num_lines == 0) { 12892c1f46dcSZachary Turner error.SetErrorString("No input data."); 12902c1f46dcSZachary Turner return error; 12912c1f46dcSZachary Turner } 12922c1f46dcSZachary Turner 1293b9c1b51eSKate Stone if (!signature || *signature == 0) { 12942c1f46dcSZachary Turner error.SetErrorString("No output function name."); 12952c1f46dcSZachary Turner return error; 12962c1f46dcSZachary Turner } 12972c1f46dcSZachary Turner 12982c1f46dcSZachary Turner StreamString sstr; 12992c1f46dcSZachary Turner StringList auto_generated_function; 13002c1f46dcSZachary Turner auto_generated_function.AppendString(signature); 1301b9c1b51eSKate Stone auto_generated_function.AppendString( 1302b9c1b51eSKate Stone " global_dict = globals()"); // Grab the global dictionary 1303b9c1b51eSKate Stone auto_generated_function.AppendString( 1304b9c1b51eSKate Stone " new_keys = internal_dict.keys()"); // Make a list of keys in the 1305b9c1b51eSKate Stone // session dict 1306b9c1b51eSKate Stone auto_generated_function.AppendString( 1307b9c1b51eSKate Stone " old_keys = global_dict.keys()"); // Save list of keys in global dict 1308b9c1b51eSKate Stone auto_generated_function.AppendString( 1309b9c1b51eSKate Stone " global_dict.update (internal_dict)"); // Add the session dictionary 1310b9c1b51eSKate Stone // to the 13112c1f46dcSZachary Turner // global dictionary. 13122c1f46dcSZachary Turner 13132c1f46dcSZachary Turner // Wrap everything up inside the function, increasing the indentation. 13142c1f46dcSZachary Turner 13152c1f46dcSZachary Turner auto_generated_function.AppendString(" if True:"); 1316b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 13172c1f46dcSZachary Turner sstr.Clear(); 13182c1f46dcSZachary Turner sstr.Printf(" %s", input.GetStringAtIndex(i)); 13192c1f46dcSZachary Turner auto_generated_function.AppendString(sstr.GetData()); 13202c1f46dcSZachary Turner } 1321b9c1b51eSKate Stone auto_generated_function.AppendString( 1322b9c1b51eSKate Stone " for key in new_keys:"); // Iterate over all the keys from session 1323b9c1b51eSKate Stone // dict 1324b9c1b51eSKate Stone auto_generated_function.AppendString( 1325b9c1b51eSKate Stone " internal_dict[key] = global_dict[key]"); // Update session dict 1326b9c1b51eSKate Stone // values 1327b9c1b51eSKate Stone auto_generated_function.AppendString( 1328b9c1b51eSKate Stone " if key not in old_keys:"); // If key was not originally in 1329b9c1b51eSKate Stone // global dict 1330b9c1b51eSKate Stone auto_generated_function.AppendString( 1331b9c1b51eSKate Stone " del global_dict[key]"); // ...then remove key/value from 1332b9c1b51eSKate Stone // global dict 13332c1f46dcSZachary Turner 13342c1f46dcSZachary Turner // Verify that the results are valid Python. 13352c1f46dcSZachary Turner 13362c1f46dcSZachary Turner error = ExportFunctionDefinitionToInterpreter(auto_generated_function); 13372c1f46dcSZachary Turner 13382c1f46dcSZachary Turner return error; 13392c1f46dcSZachary Turner } 13402c1f46dcSZachary Turner 134163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 1342b9c1b51eSKate Stone StringList &user_input, std::string &output, const void *name_token) { 13432c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 13442c1f46dcSZachary Turner user_input.RemoveBlankLines(); 13452c1f46dcSZachary Turner StreamString sstr; 13462c1f46dcSZachary Turner 13472c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 13482c1f46dcSZachary Turner if (user_input.GetSize() == 0) 13492c1f46dcSZachary Turner return false; 13502c1f46dcSZachary Turner 1351b9c1b51eSKate Stone // Take what the user wrote, wrap it all up inside one big auto-generated 135205097246SAdrian Prantl // Python function, passing in the ValueObject as parameter to the function. 13532c1f46dcSZachary Turner 1354b9c1b51eSKate Stone std::string auto_generated_function_name( 1355b9c1b51eSKate Stone GenerateUniqueName("lldb_autogen_python_type_print_func", 1356b9c1b51eSKate Stone num_created_functions, name_token)); 1357b9c1b51eSKate Stone sstr.Printf("def %s (valobj, internal_dict):", 1358b9c1b51eSKate Stone auto_generated_function_name.c_str()); 13592c1f46dcSZachary Turner 13602c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 13612c1f46dcSZachary Turner return false; 13622c1f46dcSZachary Turner 13632c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 13642c1f46dcSZachary Turner output.assign(auto_generated_function_name); 13652c1f46dcSZachary Turner return true; 13662c1f46dcSZachary Turner } 13672c1f46dcSZachary Turner 136863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( 1369b9c1b51eSKate Stone StringList &user_input, std::string &output) { 13702c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 13712c1f46dcSZachary Turner user_input.RemoveBlankLines(); 13722c1f46dcSZachary Turner StreamString sstr; 13732c1f46dcSZachary Turner 13742c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 13752c1f46dcSZachary Turner if (user_input.GetSize() == 0) 13762c1f46dcSZachary Turner return false; 13772c1f46dcSZachary Turner 1378b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 1379b9c1b51eSKate Stone "lldb_autogen_python_cmd_alias_func", num_created_functions)); 13802c1f46dcSZachary Turner 1381b9c1b51eSKate Stone sstr.Printf("def %s (debugger, args, result, internal_dict):", 1382b9c1b51eSKate Stone auto_generated_function_name.c_str()); 13832c1f46dcSZachary Turner 13842c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 13852c1f46dcSZachary Turner return false; 13862c1f46dcSZachary Turner 13872c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 13882c1f46dcSZachary Turner output.assign(auto_generated_function_name); 13892c1f46dcSZachary Turner return true; 13902c1f46dcSZachary Turner } 13912c1f46dcSZachary Turner 139263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 139363dd5d25SJonas Devlieghere StringList &user_input, std::string &output, const void *name_token) { 13942c1f46dcSZachary Turner static uint32_t num_created_classes = 0; 13952c1f46dcSZachary Turner user_input.RemoveBlankLines(); 13962c1f46dcSZachary Turner int num_lines = user_input.GetSize(); 13972c1f46dcSZachary Turner StreamString sstr; 13982c1f46dcSZachary Turner 13992c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 14002c1f46dcSZachary Turner if (user_input.GetSize() == 0) 14012c1f46dcSZachary Turner return false; 14022c1f46dcSZachary Turner 14032c1f46dcSZachary Turner // Wrap all user input into a Python class 14042c1f46dcSZachary Turner 1405b9c1b51eSKate Stone std::string auto_generated_class_name(GenerateUniqueName( 1406b9c1b51eSKate Stone "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); 14072c1f46dcSZachary Turner 14082c1f46dcSZachary Turner StringList auto_generated_class; 14092c1f46dcSZachary Turner 14102c1f46dcSZachary Turner // Create the function name & definition string. 14112c1f46dcSZachary Turner 14122c1f46dcSZachary Turner sstr.Printf("class %s:", auto_generated_class_name.c_str()); 1413c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 14142c1f46dcSZachary Turner 141505097246SAdrian Prantl // Wrap everything up inside the class, increasing the indentation. we don't 141605097246SAdrian Prantl // need to play any fancy indentation tricks here because there is no 14172c1f46dcSZachary Turner // surrounding code whose indentation we need to honor 1418b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 14192c1f46dcSZachary Turner sstr.Clear(); 14202c1f46dcSZachary Turner sstr.Printf(" %s", user_input.GetStringAtIndex(i)); 1421c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 14222c1f46dcSZachary Turner } 14232c1f46dcSZachary Turner 142405097246SAdrian Prantl // Verify that the results are valid Python. (even though the method is 142505097246SAdrian Prantl // ExportFunctionDefinitionToInterpreter, a class will actually be exported) 14262c1f46dcSZachary Turner // (TODO: rename that method to ExportDefinitionToInterpreter) 14272c1f46dcSZachary Turner if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) 14282c1f46dcSZachary Turner return false; 14292c1f46dcSZachary Turner 14302c1f46dcSZachary Turner // Store the name of the auto-generated class 14312c1f46dcSZachary Turner 14322c1f46dcSZachary Turner output.assign(auto_generated_class_name); 14332c1f46dcSZachary Turner return true; 14342c1f46dcSZachary Turner } 14352c1f46dcSZachary Turner 143663dd5d25SJonas Devlieghere StructuredData::GenericSP 143763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { 143841ae8e74SKuba Mracek if (class_name == nullptr || class_name[0] == '\0') 143941ae8e74SKuba Mracek return StructuredData::GenericSP(); 144041ae8e74SKuba Mracek 1441*a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1442*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSWIGPython_CreateFrameRecognizer( 1443*a6598575SRalf Grosse-Kunstleve class_name, m_dictionary_name.c_str()); 144441ae8e74SKuba Mracek 144541ae8e74SKuba Mracek return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 144641ae8e74SKuba Mracek } 144741ae8e74SKuba Mracek 144863dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 144941ae8e74SKuba Mracek const StructuredData::ObjectSP &os_plugin_object_sp, 145041ae8e74SKuba Mracek lldb::StackFrameSP frame_sp) { 145141ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 145241ae8e74SKuba Mracek 145363dd5d25SJonas Devlieghere if (!os_plugin_object_sp) 145463dd5d25SJonas Devlieghere return ValueObjectListSP(); 145541ae8e74SKuba Mracek 145641ae8e74SKuba Mracek StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 145763dd5d25SJonas Devlieghere if (!generic) 145863dd5d25SJonas Devlieghere return nullptr; 145941ae8e74SKuba Mracek 146041ae8e74SKuba Mracek PythonObject implementor(PyRefType::Borrowed, 146141ae8e74SKuba Mracek (PyObject *)generic->GetValue()); 146241ae8e74SKuba Mracek 146363dd5d25SJonas Devlieghere if (!implementor.IsAllocated()) 146463dd5d25SJonas Devlieghere return ValueObjectListSP(); 146541ae8e74SKuba Mracek 14669a14adeaSPavel Labath PythonObject py_return( 14679a14adeaSPavel Labath PyRefType::Owned, 14689a14adeaSPavel Labath LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp)); 146941ae8e74SKuba Mracek 147041ae8e74SKuba Mracek // if it fails, print the error but otherwise go on 147141ae8e74SKuba Mracek if (PyErr_Occurred()) { 147241ae8e74SKuba Mracek PyErr_Print(); 147341ae8e74SKuba Mracek PyErr_Clear(); 147441ae8e74SKuba Mracek } 147541ae8e74SKuba Mracek if (py_return.get()) { 147641ae8e74SKuba Mracek PythonList result_list(PyRefType::Borrowed, py_return.get()); 147741ae8e74SKuba Mracek ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 14788f81aed1SDavid Bolvansky for (size_t i = 0; i < result_list.GetSize(); i++) { 147941ae8e74SKuba Mracek PyObject *item = result_list.GetItemAtIndex(i).get(); 148041ae8e74SKuba Mracek lldb::SBValue *sb_value_ptr = 148105495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 148205495c5dSJonas Devlieghere auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 148363dd5d25SJonas Devlieghere if (valobj_sp) 148463dd5d25SJonas Devlieghere result->Append(valobj_sp); 148541ae8e74SKuba Mracek } 148641ae8e74SKuba Mracek return result; 148741ae8e74SKuba Mracek } 148841ae8e74SKuba Mracek return ValueObjectListSP(); 148941ae8e74SKuba Mracek } 149041ae8e74SKuba Mracek 149163dd5d25SJonas Devlieghere StructuredData::GenericSP 149263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 1493b9c1b51eSKate Stone const char *class_name, lldb::ProcessSP process_sp) { 14942c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 14952c1f46dcSZachary Turner return StructuredData::GenericSP(); 14962c1f46dcSZachary Turner 14972c1f46dcSZachary Turner if (!process_sp) 14982c1f46dcSZachary Turner return StructuredData::GenericSP(); 14992c1f46dcSZachary Turner 1500*a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1501*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSWIGPythonCreateOSPlugin( 150205495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), process_sp); 15032c1f46dcSZachary Turner 15042c1f46dcSZachary Turner return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 15052c1f46dcSZachary Turner } 15062c1f46dcSZachary Turner 150763dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 1508b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1509b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15102c1f46dcSZachary Turner 15112c1f46dcSZachary Turner static char callee_name[] = "get_register_info"; 15122c1f46dcSZachary Turner 15132c1f46dcSZachary Turner if (!os_plugin_object_sp) 15142c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15152c1f46dcSZachary Turner 15162c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15172c1f46dcSZachary Turner if (!generic) 15182c1f46dcSZachary Turner return nullptr; 15192c1f46dcSZachary Turner 1520b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1521b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 15222c1f46dcSZachary Turner 1523f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15242c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15252c1f46dcSZachary Turner 1526b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1527b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 15282c1f46dcSZachary Turner 15292c1f46dcSZachary Turner if (PyErr_Occurred()) 15302c1f46dcSZachary Turner PyErr_Clear(); 15312c1f46dcSZachary Turner 1532f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 15332c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15342c1f46dcSZachary Turner 1535b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 15362c1f46dcSZachary Turner if (PyErr_Occurred()) 15372c1f46dcSZachary Turner PyErr_Clear(); 15382c1f46dcSZachary Turner 15392c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15402c1f46dcSZachary Turner } 15412c1f46dcSZachary Turner 15422c1f46dcSZachary Turner if (PyErr_Occurred()) 15432c1f46dcSZachary Turner PyErr_Clear(); 15442c1f46dcSZachary Turner 15452c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1546b9c1b51eSKate Stone PythonObject py_return( 1547b9c1b51eSKate Stone PyRefType::Owned, 1548b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 15492c1f46dcSZachary Turner 15502c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1551b9c1b51eSKate Stone if (PyErr_Occurred()) { 15522c1f46dcSZachary Turner PyErr_Print(); 15532c1f46dcSZachary Turner PyErr_Clear(); 15542c1f46dcSZachary Turner } 1555b9c1b51eSKate Stone if (py_return.get()) { 1556f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 15572c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 15582c1f46dcSZachary Turner } 155958b794aeSGreg Clayton return StructuredData::DictionarySP(); 156058b794aeSGreg Clayton } 15612c1f46dcSZachary Turner 156263dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 1563b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1564b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15652c1f46dcSZachary Turner 15662c1f46dcSZachary Turner static char callee_name[] = "get_thread_info"; 15672c1f46dcSZachary Turner 15682c1f46dcSZachary Turner if (!os_plugin_object_sp) 15692c1f46dcSZachary Turner return StructuredData::ArraySP(); 15702c1f46dcSZachary Turner 15712c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15722c1f46dcSZachary Turner if (!generic) 15732c1f46dcSZachary Turner return nullptr; 15742c1f46dcSZachary Turner 1575b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1576b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1577f8b22f8fSZachary Turner 1578f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15792c1f46dcSZachary Turner return StructuredData::ArraySP(); 15802c1f46dcSZachary Turner 1581b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1582b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 15832c1f46dcSZachary Turner 15842c1f46dcSZachary Turner if (PyErr_Occurred()) 15852c1f46dcSZachary Turner PyErr_Clear(); 15862c1f46dcSZachary Turner 1587f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 15882c1f46dcSZachary Turner return StructuredData::ArraySP(); 15892c1f46dcSZachary Turner 1590b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 15912c1f46dcSZachary Turner if (PyErr_Occurred()) 15922c1f46dcSZachary Turner PyErr_Clear(); 15932c1f46dcSZachary Turner 15942c1f46dcSZachary Turner return StructuredData::ArraySP(); 15952c1f46dcSZachary Turner } 15962c1f46dcSZachary Turner 15972c1f46dcSZachary Turner if (PyErr_Occurred()) 15982c1f46dcSZachary Turner PyErr_Clear(); 15992c1f46dcSZachary Turner 16002c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1601b9c1b51eSKate Stone PythonObject py_return( 1602b9c1b51eSKate Stone PyRefType::Owned, 1603b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16042c1f46dcSZachary Turner 16052c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1606b9c1b51eSKate Stone if (PyErr_Occurred()) { 16072c1f46dcSZachary Turner PyErr_Print(); 16082c1f46dcSZachary Turner PyErr_Clear(); 16092c1f46dcSZachary Turner } 16102c1f46dcSZachary Turner 1611b9c1b51eSKate Stone if (py_return.get()) { 1612f8b22f8fSZachary Turner PythonList result_list(PyRefType::Borrowed, py_return.get()); 1613f8b22f8fSZachary Turner return result_list.CreateStructuredArray(); 16142c1f46dcSZachary Turner } 161558b794aeSGreg Clayton return StructuredData::ArraySP(); 161658b794aeSGreg Clayton } 16172c1f46dcSZachary Turner 161863dd5d25SJonas Devlieghere StructuredData::StringSP 161963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 1620b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 1621b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16222c1f46dcSZachary Turner 16232c1f46dcSZachary Turner static char callee_name[] = "get_register_data"; 1624b9c1b51eSKate Stone static char *param_format = 1625b9c1b51eSKate Stone const_cast<char *>(GetPythonValueFormatString(tid)); 16262c1f46dcSZachary Turner 16272c1f46dcSZachary Turner if (!os_plugin_object_sp) 16282c1f46dcSZachary Turner return StructuredData::StringSP(); 16292c1f46dcSZachary Turner 16302c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16312c1f46dcSZachary Turner if (!generic) 16322c1f46dcSZachary Turner return nullptr; 1633b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1634b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 16352c1f46dcSZachary Turner 1636f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16372c1f46dcSZachary Turner return StructuredData::StringSP(); 16382c1f46dcSZachary Turner 1639b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1640b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16412c1f46dcSZachary Turner 16422c1f46dcSZachary Turner if (PyErr_Occurred()) 16432c1f46dcSZachary Turner PyErr_Clear(); 16442c1f46dcSZachary Turner 1645f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16462c1f46dcSZachary Turner return StructuredData::StringSP(); 16472c1f46dcSZachary Turner 1648b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16492c1f46dcSZachary Turner if (PyErr_Occurred()) 16502c1f46dcSZachary Turner PyErr_Clear(); 16512c1f46dcSZachary Turner return StructuredData::StringSP(); 16522c1f46dcSZachary Turner } 16532c1f46dcSZachary Turner 16542c1f46dcSZachary Turner if (PyErr_Occurred()) 16552c1f46dcSZachary Turner PyErr_Clear(); 16562c1f46dcSZachary Turner 16572c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1658b9c1b51eSKate Stone PythonObject py_return( 1659b9c1b51eSKate Stone PyRefType::Owned, 1660b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 16612c1f46dcSZachary Turner 16622c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1663b9c1b51eSKate Stone if (PyErr_Occurred()) { 16642c1f46dcSZachary Turner PyErr_Print(); 16652c1f46dcSZachary Turner PyErr_Clear(); 16662c1f46dcSZachary Turner } 1667f8b22f8fSZachary Turner 1668b9c1b51eSKate Stone if (py_return.get()) { 16697a76845cSZachary Turner PythonBytes result(PyRefType::Borrowed, py_return.get()); 16707a76845cSZachary Turner return result.CreateStructuredString(); 16712c1f46dcSZachary Turner } 167258b794aeSGreg Clayton return StructuredData::StringSP(); 167358b794aeSGreg Clayton } 16742c1f46dcSZachary Turner 167563dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 1676b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 1677b9c1b51eSKate Stone lldb::addr_t context) { 1678b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16792c1f46dcSZachary Turner 16802c1f46dcSZachary Turner static char callee_name[] = "create_thread"; 16812c1f46dcSZachary Turner std::string param_format; 16822c1f46dcSZachary Turner param_format += GetPythonValueFormatString(tid); 16832c1f46dcSZachary Turner param_format += GetPythonValueFormatString(context); 16842c1f46dcSZachary Turner 16852c1f46dcSZachary Turner if (!os_plugin_object_sp) 16862c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16872c1f46dcSZachary Turner 16882c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16892c1f46dcSZachary Turner if (!generic) 16902c1f46dcSZachary Turner return nullptr; 16912c1f46dcSZachary Turner 1692b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1693b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1694f8b22f8fSZachary Turner 1695f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16962c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16972c1f46dcSZachary Turner 1698b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1699b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 17002c1f46dcSZachary Turner 17012c1f46dcSZachary Turner if (PyErr_Occurred()) 17022c1f46dcSZachary Turner PyErr_Clear(); 17032c1f46dcSZachary Turner 1704f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 17052c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17062c1f46dcSZachary Turner 1707b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 17082c1f46dcSZachary Turner if (PyErr_Occurred()) 17092c1f46dcSZachary Turner PyErr_Clear(); 17102c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17112c1f46dcSZachary Turner } 17122c1f46dcSZachary Turner 17132c1f46dcSZachary Turner if (PyErr_Occurred()) 17142c1f46dcSZachary Turner PyErr_Clear(); 17152c1f46dcSZachary Turner 17162c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1717b9c1b51eSKate Stone PythonObject py_return(PyRefType::Owned, 1718b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, 1719b9c1b51eSKate Stone ¶m_format[0], tid, context)); 17202c1f46dcSZachary Turner 17212c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1722b9c1b51eSKate Stone if (PyErr_Occurred()) { 17232c1f46dcSZachary Turner PyErr_Print(); 17242c1f46dcSZachary Turner PyErr_Clear(); 17252c1f46dcSZachary Turner } 17262c1f46dcSZachary Turner 1727b9c1b51eSKate Stone if (py_return.get()) { 1728f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 17292c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 17302c1f46dcSZachary Turner } 173158b794aeSGreg Clayton return StructuredData::DictionarySP(); 173258b794aeSGreg Clayton } 17332c1f46dcSZachary Turner 173463dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 173582de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 1736a69bbe02SLawrence D'Anna std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) { 17372c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 17382c1f46dcSZachary Turner return StructuredData::ObjectSP(); 17392c1f46dcSZachary Turner 17402c1f46dcSZachary Turner if (!thread_plan_sp.get()) 174193c98346SJim Ingham return {}; 17422c1f46dcSZachary Turner 17432c1f46dcSZachary Turner Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 174463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1745d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 17462c1f46dcSZachary Turner 1747d055e3a0SPedro Tammela if (!python_interpreter) 174893c98346SJim Ingham return {}; 17492c1f46dcSZachary Turner 1750b9c1b51eSKate Stone Locker py_lock(this, 1751b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1752*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 1753*a6598575SRalf Grosse-Kunstleve class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 1754*a6598575SRalf Grosse-Kunstleve error_str, thread_plan_sp); 175593c98346SJim Ingham if (!ret_val) 175693c98346SJim Ingham return {}; 17572c1f46dcSZachary Turner 17582c1f46dcSZachary Turner return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 17592c1f46dcSZachary Turner } 17602c1f46dcSZachary Turner 176163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 1762b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 17632c1f46dcSZachary Turner bool explains_stop = true; 17642c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 17652c1f46dcSZachary Turner if (implementor_sp) 17662c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1767b9c1b51eSKate Stone if (generic) { 1768b9c1b51eSKate Stone Locker py_lock(this, 1769b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 177005495c5dSJonas Devlieghere explains_stop = LLDBSWIGPythonCallThreadPlan( 1771b9c1b51eSKate Stone generic->GetValue(), "explains_stop", event, script_error); 17722c1f46dcSZachary Turner if (script_error) 17732c1f46dcSZachary Turner return true; 17742c1f46dcSZachary Turner } 17752c1f46dcSZachary Turner return explains_stop; 17762c1f46dcSZachary Turner } 17772c1f46dcSZachary Turner 177863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 1779b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 17802c1f46dcSZachary Turner bool should_stop = true; 17812c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 17822c1f46dcSZachary Turner if (implementor_sp) 17832c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1784b9c1b51eSKate Stone if (generic) { 1785b9c1b51eSKate Stone Locker py_lock(this, 1786b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 178705495c5dSJonas Devlieghere should_stop = LLDBSWIGPythonCallThreadPlan( 178805495c5dSJonas Devlieghere generic->GetValue(), "should_stop", event, script_error); 17892c1f46dcSZachary Turner if (script_error) 17902c1f46dcSZachary Turner return true; 17912c1f46dcSZachary Turner } 17922c1f46dcSZachary Turner return should_stop; 17932c1f46dcSZachary Turner } 17942c1f46dcSZachary Turner 179563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 1796b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 1797c915a7d2SJim Ingham bool is_stale = true; 1798c915a7d2SJim Ingham StructuredData::Generic *generic = nullptr; 1799c915a7d2SJim Ingham if (implementor_sp) 1800c915a7d2SJim Ingham generic = implementor_sp->GetAsGeneric(); 1801b9c1b51eSKate Stone if (generic) { 1802b9c1b51eSKate Stone Locker py_lock(this, 1803b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 180405495c5dSJonas Devlieghere is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 180505495c5dSJonas Devlieghere nullptr, script_error); 1806c915a7d2SJim Ingham if (script_error) 1807c915a7d2SJim Ingham return true; 1808c915a7d2SJim Ingham } 1809c915a7d2SJim Ingham return is_stale; 1810c915a7d2SJim Ingham } 1811c915a7d2SJim Ingham 181263dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 1813b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 18142c1f46dcSZachary Turner bool should_step = false; 18152c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 18162c1f46dcSZachary Turner if (implementor_sp) 18172c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1818b9c1b51eSKate Stone if (generic) { 1819b9c1b51eSKate Stone Locker py_lock(this, 1820b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 182105495c5dSJonas Devlieghere should_step = LLDBSWIGPythonCallThreadPlan( 1822248a1305SKonrad Kleine generic->GetValue(), "should_step", nullptr, script_error); 18232c1f46dcSZachary Turner if (script_error) 18242c1f46dcSZachary Turner should_step = true; 18252c1f46dcSZachary Turner } 18262c1f46dcSZachary Turner if (should_step) 18272c1f46dcSZachary Turner return lldb::eStateStepping; 18282c1f46dcSZachary Turner return lldb::eStateRunning; 18292c1f46dcSZachary Turner } 18302c1f46dcSZachary Turner 18313815e702SJim Ingham StructuredData::GenericSP 183263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 183382de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 18343815e702SJim Ingham lldb::BreakpointSP &bkpt_sp) { 18353815e702SJim Ingham 18363815e702SJim Ingham if (class_name == nullptr || class_name[0] == '\0') 18373815e702SJim Ingham return StructuredData::GenericSP(); 18383815e702SJim Ingham 18393815e702SJim Ingham if (!bkpt_sp.get()) 18403815e702SJim Ingham return StructuredData::GenericSP(); 18413815e702SJim Ingham 18423815e702SJim Ingham Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 184363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1844d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 18453815e702SJim Ingham 1846d055e3a0SPedro Tammela if (!python_interpreter) 18473815e702SJim Ingham return StructuredData::GenericSP(); 18483815e702SJim Ingham 18493815e702SJim Ingham Locker py_lock(this, 18503815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 18513815e702SJim Ingham 1852*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 185305495c5dSJonas Devlieghere class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 185405495c5dSJonas Devlieghere bkpt_sp); 18553815e702SJim Ingham 18563815e702SJim Ingham return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 18573815e702SJim Ingham } 18583815e702SJim Ingham 185963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 186063dd5d25SJonas Devlieghere StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 18613815e702SJim Ingham bool should_continue = false; 18623815e702SJim Ingham 18633815e702SJim Ingham if (implementor_sp) { 18643815e702SJim Ingham Locker py_lock(this, 18653815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 186605495c5dSJonas Devlieghere should_continue = LLDBSwigPythonCallBreakpointResolver( 186705495c5dSJonas Devlieghere implementor_sp->GetValue(), "__callback__", sym_ctx); 18683815e702SJim Ingham if (PyErr_Occurred()) { 18693815e702SJim Ingham PyErr_Print(); 18703815e702SJim Ingham PyErr_Clear(); 18713815e702SJim Ingham } 18723815e702SJim Ingham } 18733815e702SJim Ingham return should_continue; 18743815e702SJim Ingham } 18753815e702SJim Ingham 18763815e702SJim Ingham lldb::SearchDepth 187763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 18783815e702SJim Ingham StructuredData::GenericSP implementor_sp) { 18793815e702SJim Ingham int depth_as_int = lldb::eSearchDepthModule; 18803815e702SJim Ingham if (implementor_sp) { 18813815e702SJim Ingham Locker py_lock(this, 18823815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 188305495c5dSJonas Devlieghere depth_as_int = LLDBSwigPythonCallBreakpointResolver( 188405495c5dSJonas Devlieghere implementor_sp->GetValue(), "__get_depth__", nullptr); 18853815e702SJim Ingham if (PyErr_Occurred()) { 18863815e702SJim Ingham PyErr_Print(); 18873815e702SJim Ingham PyErr_Clear(); 18883815e702SJim Ingham } 18893815e702SJim Ingham } 18903815e702SJim Ingham if (depth_as_int == lldb::eSearchDepthInvalid) 18913815e702SJim Ingham return lldb::eSearchDepthModule; 18923815e702SJim Ingham 18933815e702SJim Ingham if (depth_as_int <= lldb::kLastSearchDepthKind) 18943815e702SJim Ingham return (lldb::SearchDepth)depth_as_int; 18953815e702SJim Ingham return lldb::eSearchDepthModule; 18963815e702SJim Ingham } 18973815e702SJim Ingham 18981b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook( 189982de8df2SPavel Labath TargetSP target_sp, const char *class_name, 190082de8df2SPavel Labath const StructuredDataImpl &args_data, Status &error) { 19011b1d9815SJim Ingham 19021b1d9815SJim Ingham if (!target_sp) { 19031b1d9815SJim Ingham error.SetErrorString("No target for scripted stop-hook."); 19041b1d9815SJim Ingham return StructuredData::GenericSP(); 19051b1d9815SJim Ingham } 19061b1d9815SJim Ingham 19071b1d9815SJim Ingham if (class_name == nullptr || class_name[0] == '\0') { 19081b1d9815SJim Ingham error.SetErrorString("No class name for scripted stop-hook."); 19091b1d9815SJim Ingham return StructuredData::GenericSP(); 19101b1d9815SJim Ingham } 19111b1d9815SJim Ingham 19121b1d9815SJim Ingham ScriptInterpreterPythonImpl *python_interpreter = 1913d055e3a0SPedro Tammela GetPythonInterpreter(m_debugger); 19141b1d9815SJim Ingham 1915d055e3a0SPedro Tammela if (!python_interpreter) { 19161b1d9815SJim Ingham error.SetErrorString("No script interpreter for scripted stop-hook."); 19171b1d9815SJim Ingham return StructuredData::GenericSP(); 19181b1d9815SJim Ingham } 19191b1d9815SJim Ingham 19201b1d9815SJim Ingham Locker py_lock(this, 19211b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19221b1d9815SJim Ingham 1923*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSwigPythonCreateScriptedStopHook( 19241b1d9815SJim Ingham target_sp, class_name, python_interpreter->m_dictionary_name.c_str(), 19251b1d9815SJim Ingham args_data, error); 19261b1d9815SJim Ingham 19271b1d9815SJim Ingham return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 19281b1d9815SJim Ingham } 19291b1d9815SJim Ingham 19301b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop( 19311b1d9815SJim Ingham StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx, 19321b1d9815SJim Ingham lldb::StreamSP stream_sp) { 19331b1d9815SJim Ingham assert(implementor_sp && 19341b1d9815SJim Ingham "can't call a stop hook with an invalid implementor"); 19351b1d9815SJim Ingham assert(stream_sp && "can't call a stop hook with an invalid stream"); 19361b1d9815SJim Ingham 19371b1d9815SJim Ingham Locker py_lock(this, 19381b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19391b1d9815SJim Ingham 19401b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx)); 19411b1d9815SJim Ingham 19421b1d9815SJim Ingham bool ret_val = LLDBSwigPythonStopHookCallHandleStop( 19431b1d9815SJim Ingham implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp); 19441b1d9815SJim Ingham return ret_val; 19451b1d9815SJim Ingham } 19461b1d9815SJim Ingham 19472c1f46dcSZachary Turner StructuredData::ObjectSP 194863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 194997206d57SZachary Turner lldb_private::Status &error) { 1950dbd7fabaSJonas Devlieghere if (!FileSystem::Instance().Exists(file_spec)) { 19512c1f46dcSZachary Turner error.SetErrorString("no such file"); 19522c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19532c1f46dcSZachary Turner } 19542c1f46dcSZachary Turner 19552c1f46dcSZachary Turner StructuredData::ObjectSP module_sp; 19562c1f46dcSZachary Turner 1957f9517353SJonas Devlieghere LoadScriptOptions load_script_options = 1958f9517353SJonas Devlieghere LoadScriptOptions().SetInitSession(true).SetSilent(false); 1959f9517353SJonas Devlieghere if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options, 1960f9517353SJonas Devlieghere error, &module_sp)) 19612c1f46dcSZachary Turner return module_sp; 19622c1f46dcSZachary Turner 19632c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19642c1f46dcSZachary Turner } 19652c1f46dcSZachary Turner 196663dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 1967b9c1b51eSKate Stone StructuredData::ObjectSP plugin_module_sp, Target *target, 196897206d57SZachary Turner const char *setting_name, lldb_private::Status &error) { 196905495c5dSJonas Devlieghere if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 19702c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19712c1f46dcSZachary Turner StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 19722c1f46dcSZachary Turner if (!generic) 19732c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19742c1f46dcSZachary Turner 1975b9c1b51eSKate Stone Locker py_lock(this, 1976b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19772c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 19782c1f46dcSZachary Turner 197904edd189SLawrence D'Anna auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting( 198004edd189SLawrence D'Anna generic->GetValue(), setting_name, target_sp); 198104edd189SLawrence D'Anna 198204edd189SLawrence D'Anna if (!setting) 198304edd189SLawrence D'Anna return StructuredData::DictionarySP(); 198404edd189SLawrence D'Anna 198504edd189SLawrence D'Anna PythonDictionary py_dict = 198604edd189SLawrence D'Anna unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); 198704edd189SLawrence D'Anna 198804edd189SLawrence D'Anna if (!py_dict) 198904edd189SLawrence D'Anna return StructuredData::DictionarySP(); 199004edd189SLawrence D'Anna 19912c1f46dcSZachary Turner return py_dict.CreateStructuredDictionary(); 19922c1f46dcSZachary Turner } 19932c1f46dcSZachary Turner 19942c1f46dcSZachary Turner StructuredData::ObjectSP 199563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 1996b9c1b51eSKate Stone const char *class_name, lldb::ValueObjectSP valobj) { 19972c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 19982c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19992c1f46dcSZachary Turner 20002c1f46dcSZachary Turner if (!valobj.get()) 20012c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20022c1f46dcSZachary Turner 20032c1f46dcSZachary Turner ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 20042c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 20052c1f46dcSZachary Turner 20062c1f46dcSZachary Turner if (!target) 20072c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20082c1f46dcSZachary Turner 20092c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 201063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2011d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 20122c1f46dcSZachary Turner 2013d055e3a0SPedro Tammela if (!python_interpreter) 20142c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20152c1f46dcSZachary Turner 2016b9c1b51eSKate Stone Locker py_lock(this, 2017b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2018*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSwigPythonCreateSyntheticProvider( 2019b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 20202c1f46dcSZachary Turner 20212c1f46dcSZachary Turner return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 20222c1f46dcSZachary Turner } 20232c1f46dcSZachary Turner 20242c1f46dcSZachary Turner StructuredData::GenericSP 202563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 20268d1fb843SJonas Devlieghere DebuggerSP debugger_sp(m_debugger.shared_from_this()); 20272c1f46dcSZachary Turner 20282c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 20292c1f46dcSZachary Turner return StructuredData::GenericSP(); 20302c1f46dcSZachary Turner 20312c1f46dcSZachary Turner if (!debugger_sp.get()) 20322c1f46dcSZachary Turner return StructuredData::GenericSP(); 20332c1f46dcSZachary Turner 2034b9c1b51eSKate Stone Locker py_lock(this, 2035b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2036*a6598575SRalf Grosse-Kunstleve void *ret_val = LLDBSwigPythonCreateCommandObject( 203705495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), debugger_sp); 20382c1f46dcSZachary Turner 20392c1f46dcSZachary Turner return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 20402c1f46dcSZachary Turner } 20412c1f46dcSZachary Turner 204263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 2043b9c1b51eSKate Stone const char *oneliner, std::string &output, const void *name_token) { 20442c1f46dcSZachary Turner StringList input; 20452c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20462c1f46dcSZachary Turner return GenerateTypeScriptFunction(input, output, name_token); 20472c1f46dcSZachary Turner } 20482c1f46dcSZachary Turner 204963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 205063dd5d25SJonas Devlieghere const char *oneliner, std::string &output, const void *name_token) { 20512c1f46dcSZachary Turner StringList input; 20522c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20532c1f46dcSZachary Turner return GenerateTypeSynthClass(input, output, name_token); 20542c1f46dcSZachary Turner } 20552c1f46dcSZachary Turner 205663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 2057738af7a6SJim Ingham StringList &user_input, std::string &output, 2058738af7a6SJim Ingham bool has_extra_args) { 20592c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 20602c1f46dcSZachary Turner user_input.RemoveBlankLines(); 20612c1f46dcSZachary Turner StreamString sstr; 206297206d57SZachary Turner Status error; 2063b9c1b51eSKate Stone if (user_input.GetSize() == 0) { 20642c1f46dcSZachary Turner error.SetErrorString("No input data."); 20652c1f46dcSZachary Turner return error; 20662c1f46dcSZachary Turner } 20672c1f46dcSZachary Turner 2068b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2069b9c1b51eSKate Stone "lldb_autogen_python_bp_callback_func_", num_created_functions)); 2070738af7a6SJim Ingham if (has_extra_args) 2071738af7a6SJim Ingham sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", 2072738af7a6SJim Ingham auto_generated_function_name.c_str()); 2073738af7a6SJim Ingham else 2074b9c1b51eSKate Stone sstr.Printf("def %s (frame, bp_loc, internal_dict):", 2075b9c1b51eSKate Stone auto_generated_function_name.c_str()); 20762c1f46dcSZachary Turner 20772c1f46dcSZachary Turner error = GenerateFunction(sstr.GetData(), user_input); 20782c1f46dcSZachary Turner if (!error.Success()) 20792c1f46dcSZachary Turner return error; 20802c1f46dcSZachary Turner 20812c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 20822c1f46dcSZachary Turner output.assign(auto_generated_function_name); 20832c1f46dcSZachary Turner return error; 20842c1f46dcSZachary Turner } 20852c1f46dcSZachary Turner 208663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 2087b9c1b51eSKate Stone StringList &user_input, std::string &output) { 20882c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 20892c1f46dcSZachary Turner user_input.RemoveBlankLines(); 20902c1f46dcSZachary Turner StreamString sstr; 20912c1f46dcSZachary Turner 20922c1f46dcSZachary Turner if (user_input.GetSize() == 0) 20932c1f46dcSZachary Turner return false; 20942c1f46dcSZachary Turner 2095b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2096b9c1b51eSKate Stone "lldb_autogen_python_wp_callback_func_", num_created_functions)); 2097b9c1b51eSKate Stone sstr.Printf("def %s (frame, wp, internal_dict):", 2098b9c1b51eSKate Stone auto_generated_function_name.c_str()); 20992c1f46dcSZachary Turner 21002c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 21012c1f46dcSZachary Turner return false; 21022c1f46dcSZachary Turner 21032c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 21042c1f46dcSZachary Turner output.assign(auto_generated_function_name); 21052c1f46dcSZachary Turner return true; 21062c1f46dcSZachary Turner } 21072c1f46dcSZachary Turner 210863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary( 2109b9c1b51eSKate Stone const char *python_function_name, lldb::ValueObjectSP valobj, 2110b9c1b51eSKate Stone StructuredData::ObjectSP &callee_wrapper_sp, 2111b9c1b51eSKate Stone const TypeSummaryOptions &options, std::string &retval) { 21122c1f46dcSZachary Turner 21135c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 21142c1f46dcSZachary Turner 2115b9c1b51eSKate Stone if (!valobj.get()) { 21162c1f46dcSZachary Turner retval.assign("<no object>"); 21172c1f46dcSZachary Turner return false; 21182c1f46dcSZachary Turner } 21192c1f46dcSZachary Turner 21202c1f46dcSZachary Turner void *old_callee = nullptr; 21212c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 2122b9c1b51eSKate Stone if (callee_wrapper_sp) { 21232c1f46dcSZachary Turner generic = callee_wrapper_sp->GetAsGeneric(); 21242c1f46dcSZachary Turner if (generic) 21252c1f46dcSZachary Turner old_callee = generic->GetValue(); 21262c1f46dcSZachary Turner } 21272c1f46dcSZachary Turner void *new_callee = old_callee; 21282c1f46dcSZachary Turner 21292c1f46dcSZachary Turner bool ret_val; 2130b9c1b51eSKate Stone if (python_function_name && *python_function_name) { 21312c1f46dcSZachary Turner { 2132b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 2133b9c1b51eSKate Stone Locker::NoSTDIN); 21342c1f46dcSZachary Turner { 21352c1f46dcSZachary Turner TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 21362c1f46dcSZachary Turner 213705495c5dSJonas Devlieghere static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 213805495c5dSJonas Devlieghere Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 213905495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallTypeScript( 2140b9c1b51eSKate Stone python_function_name, GetSessionDictionary().get(), valobj, 2141b9c1b51eSKate Stone &new_callee, options_sp, retval); 21422c1f46dcSZachary Turner } 21432c1f46dcSZachary Turner } 2144b9c1b51eSKate Stone } else { 21452c1f46dcSZachary Turner retval.assign("<no function name>"); 21462c1f46dcSZachary Turner return false; 21472c1f46dcSZachary Turner } 21482c1f46dcSZachary Turner 2149*a6598575SRalf Grosse-Kunstleve if (new_callee && old_callee != new_callee) { 2150*a6598575SRalf Grosse-Kunstleve Locker py_lock(this, 2151*a6598575SRalf Grosse-Kunstleve Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2152796ac80bSJonas Devlieghere callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee); 2153*a6598575SRalf Grosse-Kunstleve } 21542c1f46dcSZachary Turner 21552c1f46dcSZachary Turner return ret_val; 21562c1f46dcSZachary Turner } 21572c1f46dcSZachary Turner 215863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 2159b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t break_id, 2160b9c1b51eSKate Stone user_id_t break_loc_id) { 2161f7e07256SJim Ingham CommandDataPython *bp_option_data = (CommandDataPython *)baton; 21622c1f46dcSZachary Turner const char *python_function_name = bp_option_data->script_source.c_str(); 21632c1f46dcSZachary Turner 21642c1f46dcSZachary Turner if (!context) 21652c1f46dcSZachary Turner return true; 21662c1f46dcSZachary Turner 21672c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 21682c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 21692c1f46dcSZachary Turner 21702c1f46dcSZachary Turner if (!target) 21712c1f46dcSZachary Turner return true; 21722c1f46dcSZachary Turner 21732c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 217463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2175d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 21762c1f46dcSZachary Turner 2177d055e3a0SPedro Tammela if (!python_interpreter) 21782c1f46dcSZachary Turner return true; 21792c1f46dcSZachary Turner 2180b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 21812c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 21822c1f46dcSZachary Turner BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 2183b9c1b51eSKate Stone if (breakpoint_sp) { 2184b9c1b51eSKate Stone const BreakpointLocationSP bp_loc_sp( 2185b9c1b51eSKate Stone breakpoint_sp->FindLocationByID(break_loc_id)); 21862c1f46dcSZachary Turner 2187b9c1b51eSKate Stone if (stop_frame_sp && bp_loc_sp) { 21882c1f46dcSZachary Turner bool ret_val = true; 21892c1f46dcSZachary Turner { 2190b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2191b9c1b51eSKate Stone Locker::InitSession | 2192b9c1b51eSKate Stone Locker::NoSTDIN); 2193a69bbe02SLawrence D'Anna Expected<bool> maybe_ret_val = 2194a69bbe02SLawrence D'Anna LLDBSwigPythonBreakpointCallbackFunction( 2195b9c1b51eSKate Stone python_function_name, 2196b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 219782de8df2SPavel Labath bp_loc_sp, bp_option_data->m_extra_args); 2198a69bbe02SLawrence D'Anna 2199a69bbe02SLawrence D'Anna if (!maybe_ret_val) { 2200a69bbe02SLawrence D'Anna 2201a69bbe02SLawrence D'Anna llvm::handleAllErrors( 2202a69bbe02SLawrence D'Anna maybe_ret_val.takeError(), 2203a69bbe02SLawrence D'Anna [&](PythonException &E) { 2204a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.ReadBacktrace(); 2205a69bbe02SLawrence D'Anna }, 2206a69bbe02SLawrence D'Anna [&](const llvm::ErrorInfoBase &E) { 2207a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.message(); 2208a69bbe02SLawrence D'Anna }); 2209a69bbe02SLawrence D'Anna 2210a69bbe02SLawrence D'Anna } else { 2211a69bbe02SLawrence D'Anna ret_val = maybe_ret_val.get(); 2212a69bbe02SLawrence D'Anna } 22132c1f46dcSZachary Turner } 22142c1f46dcSZachary Turner return ret_val; 22152c1f46dcSZachary Turner } 22162c1f46dcSZachary Turner } 22172c1f46dcSZachary Turner } 22182c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22192c1f46dcSZachary Turner // trying to call the script function 22202c1f46dcSZachary Turner return true; 22212c1f46dcSZachary Turner } 22222c1f46dcSZachary Turner 222363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 2224b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 2225b9c1b51eSKate Stone WatchpointOptions::CommandData *wp_option_data = 2226b9c1b51eSKate Stone (WatchpointOptions::CommandData *)baton; 22272c1f46dcSZachary Turner const char *python_function_name = wp_option_data->script_source.c_str(); 22282c1f46dcSZachary Turner 22292c1f46dcSZachary Turner if (!context) 22302c1f46dcSZachary Turner return true; 22312c1f46dcSZachary Turner 22322c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 22332c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 22342c1f46dcSZachary Turner 22352c1f46dcSZachary Turner if (!target) 22362c1f46dcSZachary Turner return true; 22372c1f46dcSZachary Turner 22382c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 223963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2240d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 22412c1f46dcSZachary Turner 2242d055e3a0SPedro Tammela if (!python_interpreter) 22432c1f46dcSZachary Turner return true; 22442c1f46dcSZachary Turner 2245b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 22462c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 22472c1f46dcSZachary Turner WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 2248b9c1b51eSKate Stone if (wp_sp) { 2249b9c1b51eSKate Stone if (stop_frame_sp && wp_sp) { 22502c1f46dcSZachary Turner bool ret_val = true; 22512c1f46dcSZachary Turner { 2252b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2253b9c1b51eSKate Stone Locker::InitSession | 2254b9c1b51eSKate Stone Locker::NoSTDIN); 225505495c5dSJonas Devlieghere ret_val = LLDBSwigPythonWatchpointCallbackFunction( 2256b9c1b51eSKate Stone python_function_name, 2257b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 22582c1f46dcSZachary Turner wp_sp); 22592c1f46dcSZachary Turner } 22602c1f46dcSZachary Turner return ret_val; 22612c1f46dcSZachary Turner } 22622c1f46dcSZachary Turner } 22632c1f46dcSZachary Turner } 22642c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22652c1f46dcSZachary Turner // trying to call the script function 22662c1f46dcSZachary Turner return true; 22672c1f46dcSZachary Turner } 22682c1f46dcSZachary Turner 226963dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 2270b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 22712c1f46dcSZachary Turner if (!implementor_sp) 22722c1f46dcSZachary Turner return 0; 22732c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 22742c1f46dcSZachary Turner if (!generic) 22752c1f46dcSZachary Turner return 0; 22769a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 22772c1f46dcSZachary Turner if (!implementor) 22782c1f46dcSZachary Turner return 0; 22792c1f46dcSZachary Turner 22802c1f46dcSZachary Turner size_t ret_val = 0; 22812c1f46dcSZachary Turner 22822c1f46dcSZachary Turner { 2283b9c1b51eSKate Stone Locker py_lock(this, 2284b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 228505495c5dSJonas Devlieghere ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 22862c1f46dcSZachary Turner } 22872c1f46dcSZachary Turner 22882c1f46dcSZachary Turner return ret_val; 22892c1f46dcSZachary Turner } 22902c1f46dcSZachary Turner 229163dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 2292b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 22932c1f46dcSZachary Turner if (!implementor_sp) 22942c1f46dcSZachary Turner return lldb::ValueObjectSP(); 22952c1f46dcSZachary Turner 22962c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 22972c1f46dcSZachary Turner if (!generic) 22982c1f46dcSZachary Turner return lldb::ValueObjectSP(); 22999a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23002c1f46dcSZachary Turner if (!implementor) 23012c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23022c1f46dcSZachary Turner 23032c1f46dcSZachary Turner lldb::ValueObjectSP ret_val; 23042c1f46dcSZachary Turner { 2305b9c1b51eSKate Stone Locker py_lock(this, 2306b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 23079a14adeaSPavel Labath PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 2308b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2309b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 231005495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 23112c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 23122c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23132c1f46dcSZachary Turner else 231405495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2315b9c1b51eSKate Stone } else { 23162c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23172c1f46dcSZachary Turner } 23182c1f46dcSZachary Turner } 23192c1f46dcSZachary Turner 23202c1f46dcSZachary Turner return ret_val; 23212c1f46dcSZachary Turner } 23222c1f46dcSZachary Turner 232363dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 2324b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 23252c1f46dcSZachary Turner if (!implementor_sp) 23262c1f46dcSZachary Turner return UINT32_MAX; 23272c1f46dcSZachary Turner 23282c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23292c1f46dcSZachary Turner if (!generic) 23302c1f46dcSZachary Turner return UINT32_MAX; 23319a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23322c1f46dcSZachary Turner if (!implementor) 23332c1f46dcSZachary Turner return UINT32_MAX; 23342c1f46dcSZachary Turner 23352c1f46dcSZachary Turner int ret_val = UINT32_MAX; 23362c1f46dcSZachary Turner 23372c1f46dcSZachary Turner { 2338b9c1b51eSKate Stone Locker py_lock(this, 2339b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 234005495c5dSJonas Devlieghere ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 23412c1f46dcSZachary Turner } 23422c1f46dcSZachary Turner 23432c1f46dcSZachary Turner return ret_val; 23442c1f46dcSZachary Turner } 23452c1f46dcSZachary Turner 234663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 2347b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23482c1f46dcSZachary Turner bool ret_val = false; 23492c1f46dcSZachary Turner 23502c1f46dcSZachary Turner if (!implementor_sp) 23512c1f46dcSZachary Turner return ret_val; 23522c1f46dcSZachary Turner 23532c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23542c1f46dcSZachary Turner if (!generic) 23552c1f46dcSZachary Turner return ret_val; 23569a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23572c1f46dcSZachary Turner if (!implementor) 23582c1f46dcSZachary Turner return ret_val; 23592c1f46dcSZachary Turner 23602c1f46dcSZachary Turner { 2361b9c1b51eSKate Stone Locker py_lock(this, 2362b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 236305495c5dSJonas Devlieghere ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 23642c1f46dcSZachary Turner } 23652c1f46dcSZachary Turner 23662c1f46dcSZachary Turner return ret_val; 23672c1f46dcSZachary Turner } 23682c1f46dcSZachary Turner 236963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 2370b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23712c1f46dcSZachary Turner bool ret_val = false; 23722c1f46dcSZachary Turner 23732c1f46dcSZachary Turner if (!implementor_sp) 23742c1f46dcSZachary Turner return ret_val; 23752c1f46dcSZachary Turner 23762c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23772c1f46dcSZachary Turner if (!generic) 23782c1f46dcSZachary Turner return ret_val; 23799a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23802c1f46dcSZachary Turner if (!implementor) 23812c1f46dcSZachary Turner return ret_val; 23822c1f46dcSZachary Turner 23832c1f46dcSZachary Turner { 2384b9c1b51eSKate Stone Locker py_lock(this, 2385b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 238605495c5dSJonas Devlieghere ret_val = 238705495c5dSJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 23882c1f46dcSZachary Turner } 23892c1f46dcSZachary Turner 23902c1f46dcSZachary Turner return ret_val; 23912c1f46dcSZachary Turner } 23922c1f46dcSZachary Turner 239363dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 2394b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23952c1f46dcSZachary Turner lldb::ValueObjectSP ret_val(nullptr); 23962c1f46dcSZachary Turner 23972c1f46dcSZachary Turner if (!implementor_sp) 23982c1f46dcSZachary Turner return ret_val; 23992c1f46dcSZachary Turner 24002c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24012c1f46dcSZachary Turner if (!generic) 24022c1f46dcSZachary Turner return ret_val; 24039a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 24042c1f46dcSZachary Turner if (!implementor) 24052c1f46dcSZachary Turner return ret_val; 24062c1f46dcSZachary Turner 24072c1f46dcSZachary Turner { 2408b9c1b51eSKate Stone Locker py_lock(this, 2409b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24109a14adeaSPavel Labath PyObject *child_ptr = 24119a14adeaSPavel Labath LLDBSwigPython_GetValueSynthProviderInstance(implementor); 2412b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2413b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 241405495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 24152c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 24162c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24172c1f46dcSZachary Turner else 241805495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2419b9c1b51eSKate Stone } else { 24202c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24212c1f46dcSZachary Turner } 24222c1f46dcSZachary Turner } 24232c1f46dcSZachary Turner 24242c1f46dcSZachary Turner return ret_val; 24252c1f46dcSZachary Turner } 24262c1f46dcSZachary Turner 242763dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 2428b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 2429b9c1b51eSKate Stone Locker py_lock(this, 2430b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24316eec8d6cSEnrico Granata 24326eec8d6cSEnrico Granata static char callee_name[] = "get_type_name"; 24336eec8d6cSEnrico Granata 24346eec8d6cSEnrico Granata ConstString ret_val; 24356eec8d6cSEnrico Granata bool got_string = false; 24366eec8d6cSEnrico Granata std::string buffer; 24376eec8d6cSEnrico Granata 24386eec8d6cSEnrico Granata if (!implementor_sp) 24396eec8d6cSEnrico Granata return ret_val; 24406eec8d6cSEnrico Granata 24416eec8d6cSEnrico Granata StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24426eec8d6cSEnrico Granata if (!generic) 24436eec8d6cSEnrico Granata return ret_val; 2444b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2445b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 24466eec8d6cSEnrico Granata if (!implementor.IsAllocated()) 24476eec8d6cSEnrico Granata return ret_val; 24486eec8d6cSEnrico Granata 2449b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 2450b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 24516eec8d6cSEnrico Granata 24526eec8d6cSEnrico Granata if (PyErr_Occurred()) 24536eec8d6cSEnrico Granata PyErr_Clear(); 24546eec8d6cSEnrico Granata 24556eec8d6cSEnrico Granata if (!pmeth.IsAllocated()) 24566eec8d6cSEnrico Granata return ret_val; 24576eec8d6cSEnrico Granata 2458b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 24596eec8d6cSEnrico Granata if (PyErr_Occurred()) 24606eec8d6cSEnrico Granata PyErr_Clear(); 24616eec8d6cSEnrico Granata return ret_val; 24626eec8d6cSEnrico Granata } 24636eec8d6cSEnrico Granata 24646eec8d6cSEnrico Granata if (PyErr_Occurred()) 24656eec8d6cSEnrico Granata PyErr_Clear(); 24666eec8d6cSEnrico Granata 24676eec8d6cSEnrico Granata // right now we know this function exists and is callable.. 2468b9c1b51eSKate Stone PythonObject py_return( 2469b9c1b51eSKate Stone PyRefType::Owned, 2470b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 24716eec8d6cSEnrico Granata 24726eec8d6cSEnrico Granata // if it fails, print the error but otherwise go on 2473b9c1b51eSKate Stone if (PyErr_Occurred()) { 24746eec8d6cSEnrico Granata PyErr_Print(); 24756eec8d6cSEnrico Granata PyErr_Clear(); 24766eec8d6cSEnrico Granata } 24776eec8d6cSEnrico Granata 2478b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 24796eec8d6cSEnrico Granata PythonString py_string(PyRefType::Borrowed, py_return.get()); 24806eec8d6cSEnrico Granata llvm::StringRef return_data(py_string.GetString()); 2481b9c1b51eSKate Stone if (!return_data.empty()) { 24826eec8d6cSEnrico Granata buffer.assign(return_data.data(), return_data.size()); 24836eec8d6cSEnrico Granata got_string = true; 24846eec8d6cSEnrico Granata } 24856eec8d6cSEnrico Granata } 24866eec8d6cSEnrico Granata 24876eec8d6cSEnrico Granata if (got_string) 24886eec8d6cSEnrico Granata ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 24896eec8d6cSEnrico Granata 24906eec8d6cSEnrico Granata return ret_val; 24916eec8d6cSEnrico Granata } 24926eec8d6cSEnrico Granata 249363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 249463dd5d25SJonas Devlieghere const char *impl_function, Process *process, std::string &output, 249597206d57SZachary Turner Status &error) { 24962c1f46dcSZachary Turner bool ret_val; 2497b9c1b51eSKate Stone if (!process) { 24982c1f46dcSZachary Turner error.SetErrorString("no process"); 24992c1f46dcSZachary Turner return false; 25002c1f46dcSZachary Turner } 2501b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25022c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25032c1f46dcSZachary Turner return false; 25042c1f46dcSZachary Turner } 250505495c5dSJonas Devlieghere 25062c1f46dcSZachary Turner { 2507b9c1b51eSKate Stone Locker py_lock(this, 2508b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 250905495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 25107f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), process->shared_from_this(), 25117f09ab08SPavel Labath output); 25122c1f46dcSZachary Turner if (!ret_val) 25132c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25142c1f46dcSZachary Turner } 25152c1f46dcSZachary Turner return ret_val; 25162c1f46dcSZachary Turner } 25172c1f46dcSZachary Turner 251863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 251963dd5d25SJonas Devlieghere const char *impl_function, Thread *thread, std::string &output, 252097206d57SZachary Turner Status &error) { 2521b9c1b51eSKate Stone if (!thread) { 25222c1f46dcSZachary Turner error.SetErrorString("no thread"); 25232c1f46dcSZachary Turner return false; 25242c1f46dcSZachary Turner } 2525b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25262c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25272c1f46dcSZachary Turner return false; 25282c1f46dcSZachary Turner } 252905495c5dSJonas Devlieghere 2530b9c1b51eSKate Stone Locker py_lock(this, 2531b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25327406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread( 25337406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 25347406d236SPavel Labath thread->shared_from_this())) { 25357406d236SPavel Labath output = std::move(*result); 25367406d236SPavel Labath return true; 25372c1f46dcSZachary Turner } 25387406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 25397406d236SPavel Labath return false; 25402c1f46dcSZachary Turner } 25412c1f46dcSZachary Turner 254263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 254363dd5d25SJonas Devlieghere const char *impl_function, Target *target, std::string &output, 254497206d57SZachary Turner Status &error) { 25452c1f46dcSZachary Turner bool ret_val; 2546b9c1b51eSKate Stone if (!target) { 25472c1f46dcSZachary Turner error.SetErrorString("no thread"); 25482c1f46dcSZachary Turner return false; 25492c1f46dcSZachary Turner } 2550b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25512c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25522c1f46dcSZachary Turner return false; 25532c1f46dcSZachary Turner } 255405495c5dSJonas Devlieghere 25552c1f46dcSZachary Turner { 25562c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 2557b9c1b51eSKate Stone Locker py_lock(this, 2558b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 255905495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 2560b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), target_sp, output); 25612c1f46dcSZachary Turner if (!ret_val) 25622c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25632c1f46dcSZachary Turner } 25642c1f46dcSZachary Turner return ret_val; 25652c1f46dcSZachary Turner } 25662c1f46dcSZachary Turner 256763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 256863dd5d25SJonas Devlieghere const char *impl_function, StackFrame *frame, std::string &output, 256997206d57SZachary Turner Status &error) { 2570b9c1b51eSKate Stone if (!frame) { 25712c1f46dcSZachary Turner error.SetErrorString("no frame"); 25722c1f46dcSZachary Turner return false; 25732c1f46dcSZachary Turner } 2574b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25752c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25762c1f46dcSZachary Turner return false; 25772c1f46dcSZachary Turner } 257805495c5dSJonas Devlieghere 2579b9c1b51eSKate Stone Locker py_lock(this, 2580b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25817406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame( 25827406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 25837406d236SPavel Labath frame->shared_from_this())) { 25847406d236SPavel Labath output = std::move(*result); 25857406d236SPavel Labath return true; 25862c1f46dcSZachary Turner } 25877406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 25887406d236SPavel Labath return false; 25892c1f46dcSZachary Turner } 25902c1f46dcSZachary Turner 259163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 259263dd5d25SJonas Devlieghere const char *impl_function, ValueObject *value, std::string &output, 259397206d57SZachary Turner Status &error) { 25942c1f46dcSZachary Turner bool ret_val; 2595b9c1b51eSKate Stone if (!value) { 25962c1f46dcSZachary Turner error.SetErrorString("no value"); 25972c1f46dcSZachary Turner return false; 25982c1f46dcSZachary Turner } 2599b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26002c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26012c1f46dcSZachary Turner return false; 26022c1f46dcSZachary Turner } 260305495c5dSJonas Devlieghere 26042c1f46dcSZachary Turner { 2605b9c1b51eSKate Stone Locker py_lock(this, 2606b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 260705495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordValue( 26087f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), value->GetSP(), output); 26092c1f46dcSZachary Turner if (!ret_val) 26102c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26112c1f46dcSZachary Turner } 26122c1f46dcSZachary Turner return ret_val; 26132c1f46dcSZachary Turner } 26142c1f46dcSZachary Turner 2615b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr, 2616b9c1b51eSKate Stone const std::string &newStr) { 26172c1f46dcSZachary Turner size_t pos = 0; 26182c1f46dcSZachary Turner uint64_t matches = 0; 2619b9c1b51eSKate Stone while ((pos = str.find(oldStr, pos)) != std::string::npos) { 26202c1f46dcSZachary Turner matches++; 26212c1f46dcSZachary Turner str.replace(pos, oldStr.length(), newStr); 26222c1f46dcSZachary Turner pos += newStr.length(); 26232c1f46dcSZachary Turner } 26242c1f46dcSZachary Turner return matches; 26252c1f46dcSZachary Turner } 26262c1f46dcSZachary Turner 262763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule( 2628f9517353SJonas Devlieghere const char *pathname, const LoadScriptOptions &options, 2629f9517353SJonas Devlieghere lldb_private::Status &error, StructuredData::ObjectSP *module_sp, 2630f9517353SJonas Devlieghere FileSpec extra_search_dir) { 26313b33b416SJonas Devlieghere namespace fs = llvm::sys::fs; 263200bb397bSJonas Devlieghere namespace path = llvm::sys::path; 26333b33b416SJonas Devlieghere 2634f9517353SJonas Devlieghere ExecuteScriptOptions exc_options = ExecuteScriptOptions() 2635f9517353SJonas Devlieghere .SetEnableIO(!options.GetSilent()) 2636f9517353SJonas Devlieghere .SetSetLLDBGlobals(false); 2637f9517353SJonas Devlieghere 2638b9c1b51eSKate Stone if (!pathname || !pathname[0]) { 26392c1f46dcSZachary Turner error.SetErrorString("invalid pathname"); 26402c1f46dcSZachary Turner return false; 26412c1f46dcSZachary Turner } 26422c1f46dcSZachary Turner 2643f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 2644f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 2645f9517353SJonas Devlieghere exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr); 2646f9517353SJonas Devlieghere 2647f9517353SJonas Devlieghere if (!io_redirect_or_error) { 2648f9517353SJonas Devlieghere error = io_redirect_or_error.takeError(); 2649f9517353SJonas Devlieghere return false; 2650f9517353SJonas Devlieghere } 2651f9517353SJonas Devlieghere 2652f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 26532c1f46dcSZachary Turner 2654f9f36097SAdrian McCarthy // Before executing Python code, lock the GIL. 265520b52c33SJonas Devlieghere Locker py_lock(this, 265620b52c33SJonas Devlieghere Locker::AcquireLock | 2657f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::InitSession : 0) | 2658f9517353SJonas Devlieghere Locker::NoSTDIN, 2659b9c1b51eSKate Stone Locker::FreeAcquiredLock | 2660f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::TearDownSession : 0), 2661f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 2662f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 26632c1f46dcSZachary Turner 2664f9517353SJonas Devlieghere auto ExtendSysPath = [&](std::string directory) -> llvm::Error { 266500bb397bSJonas Devlieghere if (directory.empty()) { 266600bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 266700bb397bSJonas Devlieghere "invalid directory name", llvm::inconvertibleErrorCode()); 266842a9da7bSStefan Granitz } 266942a9da7bSStefan Granitz 2670f9f36097SAdrian McCarthy replace_all(directory, "\\", "\\\\"); 26712c1f46dcSZachary Turner replace_all(directory, "'", "\\'"); 26722c1f46dcSZachary Turner 267300bb397bSJonas Devlieghere // Make sure that Python has "directory" in the search path. 26742c1f46dcSZachary Turner StreamString command_stream; 2675b9c1b51eSKate Stone command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 2676b9c1b51eSKate Stone "sys.path.insert(1,'%s');\n\n", 2677b9c1b51eSKate Stone directory.c_str(), directory.c_str()); 2678b9c1b51eSKate Stone bool syspath_retval = 2679f9517353SJonas Devlieghere ExecuteMultipleLines(command_stream.GetData(), exc_options).Success(); 2680b9c1b51eSKate Stone if (!syspath_retval) { 268100bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 268200bb397bSJonas Devlieghere "Python sys.path handling failed", llvm::inconvertibleErrorCode()); 26832c1f46dcSZachary Turner } 26842c1f46dcSZachary Turner 268500bb397bSJonas Devlieghere return llvm::Error::success(); 268600bb397bSJonas Devlieghere }; 268700bb397bSJonas Devlieghere 268800bb397bSJonas Devlieghere std::string module_name(pathname); 2689d6e80578SJonas Devlieghere bool possible_package = false; 269000bb397bSJonas Devlieghere 269100bb397bSJonas Devlieghere if (extra_search_dir) { 269200bb397bSJonas Devlieghere if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) { 269300bb397bSJonas Devlieghere error = std::move(e); 269400bb397bSJonas Devlieghere return false; 269500bb397bSJonas Devlieghere } 269600bb397bSJonas Devlieghere } else { 269700bb397bSJonas Devlieghere FileSpec module_file(pathname); 269800bb397bSJonas Devlieghere FileSystem::Instance().Resolve(module_file); 269900bb397bSJonas Devlieghere FileSystem::Instance().Collect(module_file); 270000bb397bSJonas Devlieghere 270100bb397bSJonas Devlieghere fs::file_status st; 270200bb397bSJonas Devlieghere std::error_code ec = status(module_file.GetPath(), st); 270300bb397bSJonas Devlieghere 270400bb397bSJonas Devlieghere if (ec || st.type() == fs::file_type::status_error || 270500bb397bSJonas Devlieghere st.type() == fs::file_type::type_unknown || 270600bb397bSJonas Devlieghere st.type() == fs::file_type::file_not_found) { 270700bb397bSJonas Devlieghere // if not a valid file of any sort, check if it might be a filename still 270800bb397bSJonas Devlieghere // dot can't be used but / and \ can, and if either is found, reject 270900bb397bSJonas Devlieghere if (strchr(pathname, '\\') || strchr(pathname, '/')) { 271000bb397bSJonas Devlieghere error.SetErrorString("invalid pathname"); 271100bb397bSJonas Devlieghere return false; 271200bb397bSJonas Devlieghere } 271300bb397bSJonas Devlieghere // Not a filename, probably a package of some sort, let it go through. 2714d6e80578SJonas Devlieghere possible_package = true; 271500bb397bSJonas Devlieghere } else if (is_directory(st) || is_regular_file(st)) { 271600bb397bSJonas Devlieghere if (module_file.GetDirectory().IsEmpty()) { 271700bb397bSJonas Devlieghere error.SetErrorString("invalid directory name"); 271800bb397bSJonas Devlieghere return false; 271900bb397bSJonas Devlieghere } 272000bb397bSJonas Devlieghere if (llvm::Error e = 272100bb397bSJonas Devlieghere ExtendSysPath(module_file.GetDirectory().GetCString())) { 272200bb397bSJonas Devlieghere error = std::move(e); 272300bb397bSJonas Devlieghere return false; 272400bb397bSJonas Devlieghere } 272500bb397bSJonas Devlieghere module_name = module_file.GetFilename().GetCString(); 2726b9c1b51eSKate Stone } else { 27272c1f46dcSZachary Turner error.SetErrorString("no known way to import this module specification"); 27282c1f46dcSZachary Turner return false; 27292c1f46dcSZachary Turner } 273000bb397bSJonas Devlieghere } 27312c1f46dcSZachary Turner 27321197ee35SJonas Devlieghere // Strip .py or .pyc extension 273300bb397bSJonas Devlieghere llvm::StringRef extension = llvm::sys::path::extension(module_name); 27341197ee35SJonas Devlieghere if (!extension.empty()) { 27351197ee35SJonas Devlieghere if (extension == ".py") 273600bb397bSJonas Devlieghere module_name.resize(module_name.length() - 3); 27371197ee35SJonas Devlieghere else if (extension == ".pyc") 273800bb397bSJonas Devlieghere module_name.resize(module_name.length() - 4); 27391197ee35SJonas Devlieghere } 27401197ee35SJonas Devlieghere 2741d6e80578SJonas Devlieghere if (!possible_package && module_name.find('.') != llvm::StringRef::npos) { 2742d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2743d6e80578SJonas Devlieghere "Python does not allow dots in module names: %s", module_name.c_str()); 2744d6e80578SJonas Devlieghere return false; 2745d6e80578SJonas Devlieghere } 2746d6e80578SJonas Devlieghere 2747d6e80578SJonas Devlieghere if (module_name.find('-') != llvm::StringRef::npos) { 2748d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2749d6e80578SJonas Devlieghere "Python discourages dashes in module names: %s", module_name.c_str()); 2750d6e80578SJonas Devlieghere return false; 2751d6e80578SJonas Devlieghere } 2752d6e80578SJonas Devlieghere 2753f9517353SJonas Devlieghere // Check if the module is already imported. 275400bb397bSJonas Devlieghere StreamString command_stream; 27552c1f46dcSZachary Turner command_stream.Clear(); 275600bb397bSJonas Devlieghere command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str()); 27572c1f46dcSZachary Turner bool does_contain = false; 2758f9517353SJonas Devlieghere // This call will succeed if the module was ever imported in any Debugger in 2759f9517353SJonas Devlieghere // the lifetime of the process in which this LLDB framework is living. 2760f9517353SJonas Devlieghere const bool does_contain_executed = ExecuteOneLineWithReturn( 2761b9c1b51eSKate Stone command_stream.GetData(), 2762f9517353SJonas Devlieghere ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options); 2763f9517353SJonas Devlieghere 2764f9517353SJonas Devlieghere const bool was_imported_globally = does_contain_executed && does_contain; 2765612384f6SJonas Devlieghere const bool was_imported_locally = 2766612384f6SJonas Devlieghere GetSessionDictionary() 276700bb397bSJonas Devlieghere .GetItemForKey(PythonString(module_name)) 2768b9c1b51eSKate Stone .IsAllocated(); 27692c1f46dcSZachary Turner 27702c1f46dcSZachary Turner // now actually do the import 27712c1f46dcSZachary Turner command_stream.Clear(); 27722c1f46dcSZachary Turner 2773612384f6SJonas Devlieghere if (was_imported_globally || was_imported_locally) { 27742c1f46dcSZachary Turner if (!was_imported_locally) 277500bb397bSJonas Devlieghere command_stream.Printf("import %s ; reload_module(%s)", 277600bb397bSJonas Devlieghere module_name.c_str(), module_name.c_str()); 27772c1f46dcSZachary Turner else 277800bb397bSJonas Devlieghere command_stream.Printf("reload_module(%s)", module_name.c_str()); 2779b9c1b51eSKate Stone } else 278000bb397bSJonas Devlieghere command_stream.Printf("import %s", module_name.c_str()); 27812c1f46dcSZachary Turner 2782f9517353SJonas Devlieghere error = ExecuteMultipleLines(command_stream.GetData(), exc_options); 27832c1f46dcSZachary Turner if (error.Fail()) 27842c1f46dcSZachary Turner return false; 27852c1f46dcSZachary Turner 27862c1f46dcSZachary Turner // if we are here, everything worked 27872c1f46dcSZachary Turner // call __lldb_init_module(debugger,dict) 278800bb397bSJonas Devlieghere if (!LLDBSwigPythonCallModuleInit(module_name.c_str(), 27897406d236SPavel Labath m_dictionary_name.c_str(), 27907406d236SPavel Labath m_debugger.shared_from_this())) { 27912c1f46dcSZachary Turner error.SetErrorString("calling __lldb_init_module failed"); 27922c1f46dcSZachary Turner return false; 27932c1f46dcSZachary Turner } 27942c1f46dcSZachary Turner 2795b9c1b51eSKate Stone if (module_sp) { 27962c1f46dcSZachary Turner // everything went just great, now set the module object 27972c1f46dcSZachary Turner command_stream.Clear(); 279800bb397bSJonas Devlieghere command_stream.Printf("%s", module_name.c_str()); 27992c1f46dcSZachary Turner void *module_pyobj = nullptr; 2800b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 2801b9c1b51eSKate Stone command_stream.GetData(), 2802f9517353SJonas Devlieghere ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj, 2803f9517353SJonas Devlieghere exc_options) && 2804b9c1b51eSKate Stone module_pyobj) 2805796ac80bSJonas Devlieghere *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj); 28062c1f46dcSZachary Turner } 28072c1f46dcSZachary Turner 28082c1f46dcSZachary Turner return true; 28092c1f46dcSZachary Turner } 28102c1f46dcSZachary Turner 281163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 28122c1f46dcSZachary Turner if (!word || !word[0]) 28132c1f46dcSZachary Turner return false; 28142c1f46dcSZachary Turner 28152c1f46dcSZachary Turner llvm::StringRef word_sr(word); 28162c1f46dcSZachary Turner 281705097246SAdrian Prantl // filter out a few characters that would just confuse us and that are 281805097246SAdrian Prantl // clearly not keyword material anyway 281910b113e8SJonas Devlieghere if (word_sr.find('"') != llvm::StringRef::npos || 282010b113e8SJonas Devlieghere word_sr.find('\'') != llvm::StringRef::npos) 28212c1f46dcSZachary Turner return false; 28222c1f46dcSZachary Turner 28232c1f46dcSZachary Turner StreamString command_stream; 28242c1f46dcSZachary Turner command_stream.Printf("keyword.iskeyword('%s')", word); 28252c1f46dcSZachary Turner bool result; 28262c1f46dcSZachary Turner ExecuteScriptOptions options; 28272c1f46dcSZachary Turner options.SetEnableIO(false); 28282c1f46dcSZachary Turner options.SetMaskoutErrors(true); 28292c1f46dcSZachary Turner options.SetSetLLDBGlobals(false); 2830b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(command_stream.GetData(), 2831b9c1b51eSKate Stone ScriptInterpreter::eScriptReturnTypeBool, 2832b9c1b51eSKate Stone &result, options)) 28332c1f46dcSZachary Turner return result; 28342c1f46dcSZachary Turner return false; 28352c1f46dcSZachary Turner } 28362c1f46dcSZachary Turner 283763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 2838b9c1b51eSKate Stone lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 2839b9c1b51eSKate Stone : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 2840b9c1b51eSKate Stone m_old_asynch(debugger_sp->GetAsyncExecution()) { 28412c1f46dcSZachary Turner if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 28422c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(false); 28432c1f46dcSZachary Turner else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 28442c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(true); 28452c1f46dcSZachary Turner } 28462c1f46dcSZachary Turner 284763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 28482c1f46dcSZachary Turner if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 28492c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(m_old_asynch); 28502c1f46dcSZachary Turner } 28512c1f46dcSZachary Turner 285263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 28534d51a902SRaphael Isemann const char *impl_function, llvm::StringRef args, 28542c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 285597206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2856b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2857b9c1b51eSKate Stone if (!impl_function) { 28582c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 28592c1f46dcSZachary Turner return false; 28602c1f46dcSZachary Turner } 28612c1f46dcSZachary Turner 28628d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 28632c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 28642c1f46dcSZachary Turner 2865b9c1b51eSKate Stone if (!debugger_sp.get()) { 28662c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 28672c1f46dcSZachary Turner return false; 28682c1f46dcSZachary Turner } 28692c1f46dcSZachary Turner 28702c1f46dcSZachary Turner bool ret_val = false; 28712c1f46dcSZachary Turner 28722c1f46dcSZachary Turner std::string err_msg; 28732c1f46dcSZachary Turner 28742c1f46dcSZachary Turner { 28752c1f46dcSZachary Turner Locker py_lock(this, 2876b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2877b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 28782c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 28792c1f46dcSZachary Turner 2880b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 28812c1f46dcSZachary Turner 28824d51a902SRaphael Isemann std::string args_str = args.str(); 288305495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommand( 288405495c5dSJonas Devlieghere impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 288505495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp); 28862c1f46dcSZachary Turner } 28872c1f46dcSZachary Turner 28882c1f46dcSZachary Turner if (!ret_val) 28892c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 28902c1f46dcSZachary Turner else 28912c1f46dcSZachary Turner error.Clear(); 28922c1f46dcSZachary Turner 28932c1f46dcSZachary Turner return ret_val; 28942c1f46dcSZachary Turner } 28952c1f46dcSZachary Turner 289663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 28974d51a902SRaphael Isemann StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 28982c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 289997206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2900b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2901b9c1b51eSKate Stone if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 29022c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 29032c1f46dcSZachary Turner return false; 29042c1f46dcSZachary Turner } 29052c1f46dcSZachary Turner 29068d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29072c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29082c1f46dcSZachary Turner 2909b9c1b51eSKate Stone if (!debugger_sp.get()) { 29102c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 29112c1f46dcSZachary Turner return false; 29122c1f46dcSZachary Turner } 29132c1f46dcSZachary Turner 29142c1f46dcSZachary Turner bool ret_val = false; 29152c1f46dcSZachary Turner 29162c1f46dcSZachary Turner std::string err_msg; 29172c1f46dcSZachary Turner 29182c1f46dcSZachary Turner { 29192c1f46dcSZachary Turner Locker py_lock(this, 2920b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2921b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29222c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 29232c1f46dcSZachary Turner 2924b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29252c1f46dcSZachary Turner 29264d51a902SRaphael Isemann std::string args_str = args.str(); 29279a14adeaSPavel Labath ret_val = LLDBSwigPythonCallCommandObject( 29289a14adeaSPavel Labath static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp, 29299a14adeaSPavel Labath args_str.c_str(), cmd_retobj, exe_ctx_ref_sp); 29302c1f46dcSZachary Turner } 29312c1f46dcSZachary Turner 29322c1f46dcSZachary Turner if (!ret_val) 29332c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 29342c1f46dcSZachary Turner else 29352c1f46dcSZachary Turner error.Clear(); 29362c1f46dcSZachary Turner 29372c1f46dcSZachary Turner return ret_val; 29382c1f46dcSZachary Turner } 29392c1f46dcSZachary Turner 294093571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object 294193571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's 294293571c3cSJonas Devlieghere /// value is None. 294363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 2944b9c1b51eSKate Stone std::string &dest) { 29452c1f46dcSZachary Turner dest.clear(); 294693571c3cSJonas Devlieghere 29472c1f46dcSZachary Turner if (!item || !*item) 29482c1f46dcSZachary Turner return false; 294993571c3cSJonas Devlieghere 29502c1f46dcSZachary Turner std::string command(item); 29512c1f46dcSZachary Turner command += ".__doc__"; 29522c1f46dcSZachary Turner 295393571c3cSJonas Devlieghere // Python is going to point this to valid data if ExecuteOneLineWithReturn 295493571c3cSJonas Devlieghere // returns successfully. 295593571c3cSJonas Devlieghere char *result_ptr = nullptr; 29562c1f46dcSZachary Turner 2957b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 295893571c3cSJonas Devlieghere command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 29592c1f46dcSZachary Turner &result_ptr, 2960fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false))) { 29612c1f46dcSZachary Turner if (result_ptr) 29622c1f46dcSZachary Turner dest.assign(result_ptr); 29632c1f46dcSZachary Turner return true; 29642c1f46dcSZachary Turner } 296593571c3cSJonas Devlieghere 296693571c3cSJonas Devlieghere StreamString str_stream; 296793571c3cSJonas Devlieghere str_stream << "Function " << item 296893571c3cSJonas Devlieghere << " was not found. Containing module might be missing."; 296993571c3cSJonas Devlieghere dest = std::string(str_stream.GetString()); 297093571c3cSJonas Devlieghere 297193571c3cSJonas Devlieghere return false; 29722c1f46dcSZachary Turner } 29732c1f46dcSZachary Turner 297463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 2975b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 29762c1f46dcSZachary Turner dest.clear(); 29772c1f46dcSZachary Turner 2978b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 29792c1f46dcSZachary Turner 29802c1f46dcSZachary Turner static char callee_name[] = "get_short_help"; 29812c1f46dcSZachary Turner 29822c1f46dcSZachary Turner if (!cmd_obj_sp) 29832c1f46dcSZachary Turner return false; 29842c1f46dcSZachary Turner 2985b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2986b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 29872c1f46dcSZachary Turner 2988f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 29892c1f46dcSZachary Turner return false; 29902c1f46dcSZachary Turner 2991b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 2992b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 29932c1f46dcSZachary Turner 29942c1f46dcSZachary Turner if (PyErr_Occurred()) 29952c1f46dcSZachary Turner PyErr_Clear(); 29962c1f46dcSZachary Turner 2997f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 29982c1f46dcSZachary Turner return false; 29992c1f46dcSZachary Turner 3000b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30012c1f46dcSZachary Turner if (PyErr_Occurred()) 30022c1f46dcSZachary Turner PyErr_Clear(); 30032c1f46dcSZachary Turner return false; 30042c1f46dcSZachary Turner } 30052c1f46dcSZachary Turner 30062c1f46dcSZachary Turner if (PyErr_Occurred()) 30072c1f46dcSZachary Turner PyErr_Clear(); 30082c1f46dcSZachary Turner 300993571c3cSJonas Devlieghere // Right now we know this function exists and is callable. 3010b9c1b51eSKate Stone PythonObject py_return( 3011b9c1b51eSKate Stone PyRefType::Owned, 3012b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 30132c1f46dcSZachary Turner 301493571c3cSJonas Devlieghere // If it fails, print the error but otherwise go on. 3015b9c1b51eSKate Stone if (PyErr_Occurred()) { 30162c1f46dcSZachary Turner PyErr_Print(); 30172c1f46dcSZachary Turner PyErr_Clear(); 30182c1f46dcSZachary Turner } 30192c1f46dcSZachary Turner 3020b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3021f8b22f8fSZachary Turner PythonString py_string(PyRefType::Borrowed, py_return.get()); 302222c8efcdSZachary Turner llvm::StringRef return_data(py_string.GetString()); 302322c8efcdSZachary Turner dest.assign(return_data.data(), return_data.size()); 302493571c3cSJonas Devlieghere return true; 30252c1f46dcSZachary Turner } 302693571c3cSJonas Devlieghere 302793571c3cSJonas Devlieghere return false; 30282c1f46dcSZachary Turner } 30292c1f46dcSZachary Turner 303063dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 3031b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp) { 30322c1f46dcSZachary Turner uint32_t result = 0; 30332c1f46dcSZachary Turner 3034b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30352c1f46dcSZachary Turner 30362c1f46dcSZachary Turner static char callee_name[] = "get_flags"; 30372c1f46dcSZachary Turner 30382c1f46dcSZachary Turner if (!cmd_obj_sp) 30392c1f46dcSZachary Turner return result; 30402c1f46dcSZachary Turner 3041b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3042b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 30432c1f46dcSZachary Turner 3044f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 30452c1f46dcSZachary Turner return result; 30462c1f46dcSZachary Turner 3047b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3048b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30492c1f46dcSZachary Turner 30502c1f46dcSZachary Turner if (PyErr_Occurred()) 30512c1f46dcSZachary Turner PyErr_Clear(); 30522c1f46dcSZachary Turner 3053f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 30542c1f46dcSZachary Turner return result; 30552c1f46dcSZachary Turner 3056b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30572c1f46dcSZachary Turner if (PyErr_Occurred()) 30582c1f46dcSZachary Turner PyErr_Clear(); 30592c1f46dcSZachary Turner return result; 30602c1f46dcSZachary Turner } 30612c1f46dcSZachary Turner 30622c1f46dcSZachary Turner if (PyErr_Occurred()) 30632c1f46dcSZachary Turner PyErr_Clear(); 30642c1f46dcSZachary Turner 306552712d3fSLawrence D'Anna long long py_return = unwrapOrSetPythonException( 306652712d3fSLawrence D'Anna As<long long>(implementor.CallMethod(callee_name))); 30672c1f46dcSZachary Turner 30682c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3069b9c1b51eSKate Stone if (PyErr_Occurred()) { 30702c1f46dcSZachary Turner PyErr_Print(); 30712c1f46dcSZachary Turner PyErr_Clear(); 307252712d3fSLawrence D'Anna } else { 307352712d3fSLawrence D'Anna result = py_return; 30742c1f46dcSZachary Turner } 30752c1f46dcSZachary Turner 30762c1f46dcSZachary Turner return result; 30772c1f46dcSZachary Turner } 30782c1f46dcSZachary Turner 307963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 3080b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 30812c1f46dcSZachary Turner bool got_string = false; 30822c1f46dcSZachary Turner dest.clear(); 30832c1f46dcSZachary Turner 3084b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30852c1f46dcSZachary Turner 30862c1f46dcSZachary Turner static char callee_name[] = "get_long_help"; 30872c1f46dcSZachary Turner 30882c1f46dcSZachary Turner if (!cmd_obj_sp) 30892c1f46dcSZachary Turner return false; 30902c1f46dcSZachary Turner 3091b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3092b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 30932c1f46dcSZachary Turner 3094f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 30952c1f46dcSZachary Turner return false; 30962c1f46dcSZachary Turner 3097b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3098b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30992c1f46dcSZachary Turner 31002c1f46dcSZachary Turner if (PyErr_Occurred()) 31012c1f46dcSZachary Turner PyErr_Clear(); 31022c1f46dcSZachary Turner 3103f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 31042c1f46dcSZachary Turner return false; 31052c1f46dcSZachary Turner 3106b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 31072c1f46dcSZachary Turner if (PyErr_Occurred()) 31082c1f46dcSZachary Turner PyErr_Clear(); 31092c1f46dcSZachary Turner 31102c1f46dcSZachary Turner return false; 31112c1f46dcSZachary Turner } 31122c1f46dcSZachary Turner 31132c1f46dcSZachary Turner if (PyErr_Occurred()) 31142c1f46dcSZachary Turner PyErr_Clear(); 31152c1f46dcSZachary Turner 31162c1f46dcSZachary Turner // right now we know this function exists and is callable.. 3117b9c1b51eSKate Stone PythonObject py_return( 3118b9c1b51eSKate Stone PyRefType::Owned, 3119b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31202c1f46dcSZachary Turner 31212c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3122b9c1b51eSKate Stone if (PyErr_Occurred()) { 31232c1f46dcSZachary Turner PyErr_Print(); 31242c1f46dcSZachary Turner PyErr_Clear(); 31252c1f46dcSZachary Turner } 31262c1f46dcSZachary Turner 3127b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3128f8b22f8fSZachary Turner PythonString str(PyRefType::Borrowed, py_return.get()); 312922c8efcdSZachary Turner llvm::StringRef str_data(str.GetString()); 313022c8efcdSZachary Turner dest.assign(str_data.data(), str_data.size()); 31312c1f46dcSZachary Turner got_string = true; 31322c1f46dcSZachary Turner } 31332c1f46dcSZachary Turner 31342c1f46dcSZachary Turner return got_string; 31352c1f46dcSZachary Turner } 31362c1f46dcSZachary Turner 31372c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker> 313863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 3139b9c1b51eSKate Stone std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 3140b9c1b51eSKate Stone this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 31412c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession)); 31422c1f46dcSZachary Turner return py_lock; 31432c1f46dcSZachary Turner } 31442c1f46dcSZachary Turner 3145049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 3146049ae930SJonas Devlieghere namespace { 3147049ae930SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores 3148049ae930SJonas Devlieghere /// it at the end of the current scope. 3149049ae930SJonas Devlieghere struct RestoreSignalHandlerScope { 3150049ae930SJonas Devlieghere /// The signal handler. 3151049ae930SJonas Devlieghere struct sigaction m_prev_handler; 3152049ae930SJonas Devlieghere int m_signal_code; 3153049ae930SJonas Devlieghere RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) { 3154049ae930SJonas Devlieghere // Initialize sigaction to their default state. 3155049ae930SJonas Devlieghere std::memset(&m_prev_handler, 0, sizeof(m_prev_handler)); 3156049ae930SJonas Devlieghere // Don't install a new handler, just read back the old one. 3157049ae930SJonas Devlieghere struct sigaction *new_handler = nullptr; 3158049ae930SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler); 3159049ae930SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to read handler"); 3160049ae930SJonas Devlieghere } 3161049ae930SJonas Devlieghere ~RestoreSignalHandlerScope() { 3162049ae930SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr); 3163049ae930SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to restore old handler"); 3164049ae930SJonas Devlieghere } 3165049ae930SJonas Devlieghere }; 3166049ae930SJonas Devlieghere } // namespace 3167049ae930SJonas Devlieghere #endif 3168049ae930SJonas Devlieghere 316963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() { 317015d1b4e2SEnrico Granata if (g_initialized) 317115d1b4e2SEnrico Granata return; 317215d1b4e2SEnrico Granata 31732c1f46dcSZachary Turner g_initialized = true; 31742c1f46dcSZachary Turner 31755c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 31762c1f46dcSZachary Turner 3177b9c1b51eSKate Stone // RAII-based initialization which correctly handles multiple-initialization, 317805097246SAdrian Prantl // version- specific differences among Python 2 and Python 3, and saving and 317905097246SAdrian Prantl // restoring various other pieces of state that can get mucked with during 318005097246SAdrian Prantl // initialization. 3181079fe48aSZachary Turner InitializePythonRAII initialize_guard; 31822c1f46dcSZachary Turner 318305495c5dSJonas Devlieghere LLDBSwigPyInit(); 31842c1f46dcSZachary Turner 3185b9c1b51eSKate Stone // Update the path python uses to search for modules to include the current 3186b9c1b51eSKate Stone // directory. 31872c1f46dcSZachary Turner 31882c1f46dcSZachary Turner PyRun_SimpleString("import sys"); 31892c1f46dcSZachary Turner AddToSysPath(AddLocation::End, "."); 31902c1f46dcSZachary Turner 3191b9c1b51eSKate Stone // Don't denormalize paths when calling file_spec.GetPath(). On platforms 319205097246SAdrian Prantl // that use a backslash as the path separator, this will result in executing 319305097246SAdrian Prantl // python code containing paths with unescaped backslashes. But Python also 319405097246SAdrian Prantl // accepts forward slashes, so to make life easier we just use that. 31952df331b0SPavel Labath if (FileSpec file_spec = GetPythonDir()) 31962c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 319760f028ffSPavel Labath if (FileSpec file_spec = HostInfo::GetShlibDir()) 31982c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 31992c1f46dcSZachary Turner 3200b9c1b51eSKate Stone PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 3201b9c1b51eSKate Stone "lldb.embedded_interpreter; from " 3202b9c1b51eSKate Stone "lldb.embedded_interpreter import run_python_interpreter; " 3203b9c1b51eSKate Stone "from lldb.embedded_interpreter import run_one_line"); 3204049ae930SJonas Devlieghere 3205049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 3206049ae930SJonas Devlieghere // Python will not just overwrite its internal SIGINT handler but also the 3207049ae930SJonas Devlieghere // one from the process. Backup the current SIGINT handler to prevent that 3208049ae930SJonas Devlieghere // Python deletes it. 3209049ae930SJonas Devlieghere RestoreSignalHandlerScope save_sigint(SIGINT); 3210049ae930SJonas Devlieghere 3211049ae930SJonas Devlieghere // Setup a default SIGINT signal handler that works the same way as the 3212049ae930SJonas Devlieghere // normal Python REPL signal handler which raises a KeyboardInterrupt. 3213049ae930SJonas Devlieghere // Also make sure to not pollute the user's REPL with the signal module nor 3214049ae930SJonas Devlieghere // our utility function. 3215049ae930SJonas Devlieghere PyRun_SimpleString("def lldb_setup_sigint_handler():\n" 3216049ae930SJonas Devlieghere " import signal;\n" 3217049ae930SJonas Devlieghere " def signal_handler(sig, frame):\n" 3218049ae930SJonas Devlieghere " raise KeyboardInterrupt()\n" 3219049ae930SJonas Devlieghere " signal.signal(signal.SIGINT, signal_handler);\n" 3220049ae930SJonas Devlieghere "lldb_setup_sigint_handler();\n" 3221049ae930SJonas Devlieghere "del lldb_setup_sigint_handler\n"); 3222049ae930SJonas Devlieghere #endif 32232c1f46dcSZachary Turner } 32242c1f46dcSZachary Turner 322563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 3226b9c1b51eSKate Stone std::string path) { 32272c1f46dcSZachary Turner std::string path_copy; 32282c1f46dcSZachary Turner 32292c1f46dcSZachary Turner std::string statement; 3230b9c1b51eSKate Stone if (location == AddLocation::Beginning) { 32312c1f46dcSZachary Turner statement.assign("sys.path.insert(0,\""); 32322c1f46dcSZachary Turner statement.append(path); 32332c1f46dcSZachary Turner statement.append("\")"); 3234b9c1b51eSKate Stone } else { 32352c1f46dcSZachary Turner statement.assign("sys.path.append(\""); 32362c1f46dcSZachary Turner statement.append(path); 32372c1f46dcSZachary Turner statement.append("\")"); 32382c1f46dcSZachary Turner } 32392c1f46dcSZachary Turner PyRun_SimpleString(statement.c_str()); 32402c1f46dcSZachary Turner } 32412c1f46dcSZachary Turner 3242bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical 3243bcadb5a3SPavel Labath // place to call it). Calling Py_Finalize here causes test suite runs to seg 3244bcadb5a3SPavel Labath // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 3245bcadb5a3SPavel Labath // be called 'at_exit'. When the test suite Python harness finishes up, it 3246bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions. 3247bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 3248bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls 324963dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 325063dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results 325163dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting 325263dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize 3253bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway 3254bcadb5a3SPavel Labath // when the process exits). 3255bcadb5a3SPavel Labath // 325663dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 3257d68983e3SPavel Labath 32584e26cf2cSJonas Devlieghere #endif 3259