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 1441a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1442*c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer( 1443a6598575SRalf Grosse-Kunstleve class_name, m_dictionary_name.c_str()); 144441ae8e74SKuba Mracek 1445*c154f397SPavel Labath return StructuredData::GenericSP( 1446*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 144741ae8e74SKuba Mracek } 144841ae8e74SKuba Mracek 144963dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 145041ae8e74SKuba Mracek const StructuredData::ObjectSP &os_plugin_object_sp, 145141ae8e74SKuba Mracek lldb::StackFrameSP frame_sp) { 145241ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 145341ae8e74SKuba Mracek 145463dd5d25SJonas Devlieghere if (!os_plugin_object_sp) 145563dd5d25SJonas Devlieghere return ValueObjectListSP(); 145641ae8e74SKuba Mracek 145741ae8e74SKuba Mracek StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 145863dd5d25SJonas Devlieghere if (!generic) 145963dd5d25SJonas Devlieghere return nullptr; 146041ae8e74SKuba Mracek 146141ae8e74SKuba Mracek PythonObject implementor(PyRefType::Borrowed, 146241ae8e74SKuba Mracek (PyObject *)generic->GetValue()); 146341ae8e74SKuba Mracek 146463dd5d25SJonas Devlieghere if (!implementor.IsAllocated()) 146563dd5d25SJonas Devlieghere return ValueObjectListSP(); 146641ae8e74SKuba Mracek 14679a14adeaSPavel Labath PythonObject py_return( 14689a14adeaSPavel Labath PyRefType::Owned, 14699a14adeaSPavel Labath LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp)); 147041ae8e74SKuba Mracek 147141ae8e74SKuba Mracek // if it fails, print the error but otherwise go on 147241ae8e74SKuba Mracek if (PyErr_Occurred()) { 147341ae8e74SKuba Mracek PyErr_Print(); 147441ae8e74SKuba Mracek PyErr_Clear(); 147541ae8e74SKuba Mracek } 147641ae8e74SKuba Mracek if (py_return.get()) { 147741ae8e74SKuba Mracek PythonList result_list(PyRefType::Borrowed, py_return.get()); 147841ae8e74SKuba Mracek ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 14798f81aed1SDavid Bolvansky for (size_t i = 0; i < result_list.GetSize(); i++) { 148041ae8e74SKuba Mracek PyObject *item = result_list.GetItemAtIndex(i).get(); 148141ae8e74SKuba Mracek lldb::SBValue *sb_value_ptr = 148205495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 148305495c5dSJonas Devlieghere auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 148463dd5d25SJonas Devlieghere if (valobj_sp) 148563dd5d25SJonas Devlieghere result->Append(valobj_sp); 148641ae8e74SKuba Mracek } 148741ae8e74SKuba Mracek return result; 148841ae8e74SKuba Mracek } 148941ae8e74SKuba Mracek return ValueObjectListSP(); 149041ae8e74SKuba Mracek } 149141ae8e74SKuba Mracek 149263dd5d25SJonas Devlieghere StructuredData::GenericSP 149363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 1494b9c1b51eSKate Stone const char *class_name, lldb::ProcessSP process_sp) { 14952c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 14962c1f46dcSZachary Turner return StructuredData::GenericSP(); 14972c1f46dcSZachary Turner 14982c1f46dcSZachary Turner if (!process_sp) 14992c1f46dcSZachary Turner return StructuredData::GenericSP(); 15002c1f46dcSZachary Turner 1501a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1502*c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin( 150305495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), process_sp); 15042c1f46dcSZachary Turner 1505*c154f397SPavel Labath return StructuredData::GenericSP( 1506*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 15072c1f46dcSZachary Turner } 15082c1f46dcSZachary Turner 150963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 1510b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1511b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15122c1f46dcSZachary Turner 15132c1f46dcSZachary Turner static char callee_name[] = "get_register_info"; 15142c1f46dcSZachary Turner 15152c1f46dcSZachary Turner if (!os_plugin_object_sp) 15162c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15172c1f46dcSZachary Turner 15182c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15192c1f46dcSZachary Turner if (!generic) 15202c1f46dcSZachary Turner return nullptr; 15212c1f46dcSZachary Turner 1522b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1523b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 15242c1f46dcSZachary Turner 1525f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15262c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15272c1f46dcSZachary Turner 1528b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1529b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 15302c1f46dcSZachary Turner 15312c1f46dcSZachary Turner if (PyErr_Occurred()) 15322c1f46dcSZachary Turner PyErr_Clear(); 15332c1f46dcSZachary Turner 1534f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 15352c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15362c1f46dcSZachary Turner 1537b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 15382c1f46dcSZachary Turner if (PyErr_Occurred()) 15392c1f46dcSZachary Turner PyErr_Clear(); 15402c1f46dcSZachary Turner 15412c1f46dcSZachary Turner return StructuredData::DictionarySP(); 15422c1f46dcSZachary Turner } 15432c1f46dcSZachary Turner 15442c1f46dcSZachary Turner if (PyErr_Occurred()) 15452c1f46dcSZachary Turner PyErr_Clear(); 15462c1f46dcSZachary Turner 15472c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1548b9c1b51eSKate Stone PythonObject py_return( 1549b9c1b51eSKate Stone PyRefType::Owned, 1550b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 15512c1f46dcSZachary Turner 15522c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1553b9c1b51eSKate Stone if (PyErr_Occurred()) { 15542c1f46dcSZachary Turner PyErr_Print(); 15552c1f46dcSZachary Turner PyErr_Clear(); 15562c1f46dcSZachary Turner } 1557b9c1b51eSKate Stone if (py_return.get()) { 1558f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 15592c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 15602c1f46dcSZachary Turner } 156158b794aeSGreg Clayton return StructuredData::DictionarySP(); 156258b794aeSGreg Clayton } 15632c1f46dcSZachary Turner 156463dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 1565b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1566b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15672c1f46dcSZachary Turner 15682c1f46dcSZachary Turner static char callee_name[] = "get_thread_info"; 15692c1f46dcSZachary Turner 15702c1f46dcSZachary Turner if (!os_plugin_object_sp) 15712c1f46dcSZachary Turner return StructuredData::ArraySP(); 15722c1f46dcSZachary Turner 15732c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 15742c1f46dcSZachary Turner if (!generic) 15752c1f46dcSZachary Turner return nullptr; 15762c1f46dcSZachary Turner 1577b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1578b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1579f8b22f8fSZachary Turner 1580f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 15812c1f46dcSZachary Turner return StructuredData::ArraySP(); 15822c1f46dcSZachary Turner 1583b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1584b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 15852c1f46dcSZachary Turner 15862c1f46dcSZachary Turner if (PyErr_Occurred()) 15872c1f46dcSZachary Turner PyErr_Clear(); 15882c1f46dcSZachary Turner 1589f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 15902c1f46dcSZachary Turner return StructuredData::ArraySP(); 15912c1f46dcSZachary Turner 1592b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 15932c1f46dcSZachary Turner if (PyErr_Occurred()) 15942c1f46dcSZachary Turner PyErr_Clear(); 15952c1f46dcSZachary Turner 15962c1f46dcSZachary Turner return StructuredData::ArraySP(); 15972c1f46dcSZachary Turner } 15982c1f46dcSZachary Turner 15992c1f46dcSZachary Turner if (PyErr_Occurred()) 16002c1f46dcSZachary Turner PyErr_Clear(); 16012c1f46dcSZachary Turner 16022c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1603b9c1b51eSKate Stone PythonObject py_return( 1604b9c1b51eSKate Stone PyRefType::Owned, 1605b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16062c1f46dcSZachary Turner 16072c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1608b9c1b51eSKate Stone if (PyErr_Occurred()) { 16092c1f46dcSZachary Turner PyErr_Print(); 16102c1f46dcSZachary Turner PyErr_Clear(); 16112c1f46dcSZachary Turner } 16122c1f46dcSZachary Turner 1613b9c1b51eSKate Stone if (py_return.get()) { 1614f8b22f8fSZachary Turner PythonList result_list(PyRefType::Borrowed, py_return.get()); 1615f8b22f8fSZachary Turner return result_list.CreateStructuredArray(); 16162c1f46dcSZachary Turner } 161758b794aeSGreg Clayton return StructuredData::ArraySP(); 161858b794aeSGreg Clayton } 16192c1f46dcSZachary Turner 162063dd5d25SJonas Devlieghere StructuredData::StringSP 162163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 1622b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 1623b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16242c1f46dcSZachary Turner 16252c1f46dcSZachary Turner static char callee_name[] = "get_register_data"; 1626b9c1b51eSKate Stone static char *param_format = 1627b9c1b51eSKate Stone const_cast<char *>(GetPythonValueFormatString(tid)); 16282c1f46dcSZachary Turner 16292c1f46dcSZachary Turner if (!os_plugin_object_sp) 16302c1f46dcSZachary Turner return StructuredData::StringSP(); 16312c1f46dcSZachary Turner 16322c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16332c1f46dcSZachary Turner if (!generic) 16342c1f46dcSZachary Turner return nullptr; 1635b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1636b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 16372c1f46dcSZachary Turner 1638f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16392c1f46dcSZachary Turner return StructuredData::StringSP(); 16402c1f46dcSZachary Turner 1641b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1642b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16432c1f46dcSZachary Turner 16442c1f46dcSZachary Turner if (PyErr_Occurred()) 16452c1f46dcSZachary Turner PyErr_Clear(); 16462c1f46dcSZachary Turner 1647f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16482c1f46dcSZachary Turner return StructuredData::StringSP(); 16492c1f46dcSZachary Turner 1650b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16512c1f46dcSZachary Turner if (PyErr_Occurred()) 16522c1f46dcSZachary Turner PyErr_Clear(); 16532c1f46dcSZachary Turner return StructuredData::StringSP(); 16542c1f46dcSZachary Turner } 16552c1f46dcSZachary Turner 16562c1f46dcSZachary Turner if (PyErr_Occurred()) 16572c1f46dcSZachary Turner PyErr_Clear(); 16582c1f46dcSZachary Turner 16592c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1660b9c1b51eSKate Stone PythonObject py_return( 1661b9c1b51eSKate Stone PyRefType::Owned, 1662b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 16632c1f46dcSZachary Turner 16642c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1665b9c1b51eSKate Stone if (PyErr_Occurred()) { 16662c1f46dcSZachary Turner PyErr_Print(); 16672c1f46dcSZachary Turner PyErr_Clear(); 16682c1f46dcSZachary Turner } 1669f8b22f8fSZachary Turner 1670b9c1b51eSKate Stone if (py_return.get()) { 16717a76845cSZachary Turner PythonBytes result(PyRefType::Borrowed, py_return.get()); 16727a76845cSZachary Turner return result.CreateStructuredString(); 16732c1f46dcSZachary Turner } 167458b794aeSGreg Clayton return StructuredData::StringSP(); 167558b794aeSGreg Clayton } 16762c1f46dcSZachary Turner 167763dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 1678b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 1679b9c1b51eSKate Stone lldb::addr_t context) { 1680b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16812c1f46dcSZachary Turner 16822c1f46dcSZachary Turner static char callee_name[] = "create_thread"; 16832c1f46dcSZachary Turner std::string param_format; 16842c1f46dcSZachary Turner param_format += GetPythonValueFormatString(tid); 16852c1f46dcSZachary Turner param_format += GetPythonValueFormatString(context); 16862c1f46dcSZachary Turner 16872c1f46dcSZachary Turner if (!os_plugin_object_sp) 16882c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16892c1f46dcSZachary Turner 16902c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16912c1f46dcSZachary Turner if (!generic) 16922c1f46dcSZachary Turner return nullptr; 16932c1f46dcSZachary Turner 1694b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1695b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1696f8b22f8fSZachary Turner 1697f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16982c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16992c1f46dcSZachary Turner 1700b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1701b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 17022c1f46dcSZachary Turner 17032c1f46dcSZachary Turner if (PyErr_Occurred()) 17042c1f46dcSZachary Turner PyErr_Clear(); 17052c1f46dcSZachary Turner 1706f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 17072c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17082c1f46dcSZachary Turner 1709b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 17102c1f46dcSZachary Turner if (PyErr_Occurred()) 17112c1f46dcSZachary Turner PyErr_Clear(); 17122c1f46dcSZachary Turner return StructuredData::DictionarySP(); 17132c1f46dcSZachary Turner } 17142c1f46dcSZachary Turner 17152c1f46dcSZachary Turner if (PyErr_Occurred()) 17162c1f46dcSZachary Turner PyErr_Clear(); 17172c1f46dcSZachary Turner 17182c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1719b9c1b51eSKate Stone PythonObject py_return(PyRefType::Owned, 1720b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, 1721b9c1b51eSKate Stone ¶m_format[0], tid, context)); 17222c1f46dcSZachary Turner 17232c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1724b9c1b51eSKate Stone if (PyErr_Occurred()) { 17252c1f46dcSZachary Turner PyErr_Print(); 17262c1f46dcSZachary Turner PyErr_Clear(); 17272c1f46dcSZachary Turner } 17282c1f46dcSZachary Turner 1729b9c1b51eSKate Stone if (py_return.get()) { 1730f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 17312c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 17322c1f46dcSZachary Turner } 173358b794aeSGreg Clayton return StructuredData::DictionarySP(); 173458b794aeSGreg Clayton } 17352c1f46dcSZachary Turner 173663dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 173782de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 1738a69bbe02SLawrence D'Anna std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) { 17392c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 17402c1f46dcSZachary Turner return StructuredData::ObjectSP(); 17412c1f46dcSZachary Turner 17422c1f46dcSZachary Turner if (!thread_plan_sp.get()) 174393c98346SJim Ingham return {}; 17442c1f46dcSZachary Turner 17452c1f46dcSZachary Turner Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 174663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1747d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 17482c1f46dcSZachary Turner 1749d055e3a0SPedro Tammela if (!python_interpreter) 175093c98346SJim Ingham return {}; 17512c1f46dcSZachary Turner 1752b9c1b51eSKate Stone Locker py_lock(this, 1753b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1754*c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 1755a6598575SRalf Grosse-Kunstleve class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 1756a6598575SRalf Grosse-Kunstleve error_str, thread_plan_sp); 175793c98346SJim Ingham if (!ret_val) 175893c98346SJim Ingham return {}; 17592c1f46dcSZachary Turner 1760*c154f397SPavel Labath return StructuredData::ObjectSP( 1761*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 17622c1f46dcSZachary Turner } 17632c1f46dcSZachary Turner 176463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 1765b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 17662c1f46dcSZachary Turner bool explains_stop = true; 17672c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 17682c1f46dcSZachary Turner if (implementor_sp) 17692c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1770b9c1b51eSKate Stone if (generic) { 1771b9c1b51eSKate Stone Locker py_lock(this, 1772b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 177305495c5dSJonas Devlieghere explains_stop = LLDBSWIGPythonCallThreadPlan( 1774b9c1b51eSKate Stone generic->GetValue(), "explains_stop", event, script_error); 17752c1f46dcSZachary Turner if (script_error) 17762c1f46dcSZachary Turner return true; 17772c1f46dcSZachary Turner } 17782c1f46dcSZachary Turner return explains_stop; 17792c1f46dcSZachary Turner } 17802c1f46dcSZachary Turner 178163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 1782b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 17832c1f46dcSZachary Turner bool should_stop = true; 17842c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 17852c1f46dcSZachary Turner if (implementor_sp) 17862c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1787b9c1b51eSKate Stone if (generic) { 1788b9c1b51eSKate Stone Locker py_lock(this, 1789b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 179005495c5dSJonas Devlieghere should_stop = LLDBSWIGPythonCallThreadPlan( 179105495c5dSJonas Devlieghere generic->GetValue(), "should_stop", event, script_error); 17922c1f46dcSZachary Turner if (script_error) 17932c1f46dcSZachary Turner return true; 17942c1f46dcSZachary Turner } 17952c1f46dcSZachary Turner return should_stop; 17962c1f46dcSZachary Turner } 17972c1f46dcSZachary Turner 179863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 1799b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 1800c915a7d2SJim Ingham bool is_stale = true; 1801c915a7d2SJim Ingham StructuredData::Generic *generic = nullptr; 1802c915a7d2SJim Ingham if (implementor_sp) 1803c915a7d2SJim Ingham generic = implementor_sp->GetAsGeneric(); 1804b9c1b51eSKate Stone if (generic) { 1805b9c1b51eSKate Stone Locker py_lock(this, 1806b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 180705495c5dSJonas Devlieghere is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 180805495c5dSJonas Devlieghere nullptr, script_error); 1809c915a7d2SJim Ingham if (script_error) 1810c915a7d2SJim Ingham return true; 1811c915a7d2SJim Ingham } 1812c915a7d2SJim Ingham return is_stale; 1813c915a7d2SJim Ingham } 1814c915a7d2SJim Ingham 181563dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 1816b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 18172c1f46dcSZachary Turner bool should_step = false; 18182c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 18192c1f46dcSZachary Turner if (implementor_sp) 18202c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1821b9c1b51eSKate Stone if (generic) { 1822b9c1b51eSKate Stone Locker py_lock(this, 1823b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 182405495c5dSJonas Devlieghere should_step = LLDBSWIGPythonCallThreadPlan( 1825248a1305SKonrad Kleine generic->GetValue(), "should_step", nullptr, script_error); 18262c1f46dcSZachary Turner if (script_error) 18272c1f46dcSZachary Turner should_step = true; 18282c1f46dcSZachary Turner } 18292c1f46dcSZachary Turner if (should_step) 18302c1f46dcSZachary Turner return lldb::eStateStepping; 18312c1f46dcSZachary Turner return lldb::eStateRunning; 18322c1f46dcSZachary Turner } 18332c1f46dcSZachary Turner 18343815e702SJim Ingham StructuredData::GenericSP 183563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 183682de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data, 18373815e702SJim Ingham lldb::BreakpointSP &bkpt_sp) { 18383815e702SJim Ingham 18393815e702SJim Ingham if (class_name == nullptr || class_name[0] == '\0') 18403815e702SJim Ingham return StructuredData::GenericSP(); 18413815e702SJim Ingham 18423815e702SJim Ingham if (!bkpt_sp.get()) 18433815e702SJim Ingham return StructuredData::GenericSP(); 18443815e702SJim Ingham 18453815e702SJim Ingham Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 184663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1847d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 18483815e702SJim Ingham 1849d055e3a0SPedro Tammela if (!python_interpreter) 18503815e702SJim Ingham return StructuredData::GenericSP(); 18513815e702SJim Ingham 18523815e702SJim Ingham Locker py_lock(this, 18533815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 18543815e702SJim Ingham 1855*c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 185605495c5dSJonas Devlieghere class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 185705495c5dSJonas Devlieghere bkpt_sp); 18583815e702SJim Ingham 1859*c154f397SPavel Labath return StructuredData::GenericSP( 1860*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 18613815e702SJim Ingham } 18623815e702SJim Ingham 186363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 186463dd5d25SJonas Devlieghere StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 18653815e702SJim Ingham bool should_continue = false; 18663815e702SJim Ingham 18673815e702SJim Ingham if (implementor_sp) { 18683815e702SJim Ingham Locker py_lock(this, 18693815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 187005495c5dSJonas Devlieghere should_continue = LLDBSwigPythonCallBreakpointResolver( 187105495c5dSJonas Devlieghere implementor_sp->GetValue(), "__callback__", sym_ctx); 18723815e702SJim Ingham if (PyErr_Occurred()) { 18733815e702SJim Ingham PyErr_Print(); 18743815e702SJim Ingham PyErr_Clear(); 18753815e702SJim Ingham } 18763815e702SJim Ingham } 18773815e702SJim Ingham return should_continue; 18783815e702SJim Ingham } 18793815e702SJim Ingham 18803815e702SJim Ingham lldb::SearchDepth 188163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 18823815e702SJim Ingham StructuredData::GenericSP implementor_sp) { 18833815e702SJim Ingham int depth_as_int = lldb::eSearchDepthModule; 18843815e702SJim Ingham if (implementor_sp) { 18853815e702SJim Ingham Locker py_lock(this, 18863815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 188705495c5dSJonas Devlieghere depth_as_int = LLDBSwigPythonCallBreakpointResolver( 188805495c5dSJonas Devlieghere implementor_sp->GetValue(), "__get_depth__", nullptr); 18893815e702SJim Ingham if (PyErr_Occurred()) { 18903815e702SJim Ingham PyErr_Print(); 18913815e702SJim Ingham PyErr_Clear(); 18923815e702SJim Ingham } 18933815e702SJim Ingham } 18943815e702SJim Ingham if (depth_as_int == lldb::eSearchDepthInvalid) 18953815e702SJim Ingham return lldb::eSearchDepthModule; 18963815e702SJim Ingham 18973815e702SJim Ingham if (depth_as_int <= lldb::kLastSearchDepthKind) 18983815e702SJim Ingham return (lldb::SearchDepth)depth_as_int; 18993815e702SJim Ingham return lldb::eSearchDepthModule; 19003815e702SJim Ingham } 19013815e702SJim Ingham 19021b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook( 190382de8df2SPavel Labath TargetSP target_sp, const char *class_name, 190482de8df2SPavel Labath const StructuredDataImpl &args_data, Status &error) { 19051b1d9815SJim Ingham 19061b1d9815SJim Ingham if (!target_sp) { 19071b1d9815SJim Ingham error.SetErrorString("No target for scripted stop-hook."); 19081b1d9815SJim Ingham return StructuredData::GenericSP(); 19091b1d9815SJim Ingham } 19101b1d9815SJim Ingham 19111b1d9815SJim Ingham if (class_name == nullptr || class_name[0] == '\0') { 19121b1d9815SJim Ingham error.SetErrorString("No class name for scripted stop-hook."); 19131b1d9815SJim Ingham return StructuredData::GenericSP(); 19141b1d9815SJim Ingham } 19151b1d9815SJim Ingham 19161b1d9815SJim Ingham ScriptInterpreterPythonImpl *python_interpreter = 1917d055e3a0SPedro Tammela GetPythonInterpreter(m_debugger); 19181b1d9815SJim Ingham 1919d055e3a0SPedro Tammela if (!python_interpreter) { 19201b1d9815SJim Ingham error.SetErrorString("No script interpreter for scripted stop-hook."); 19211b1d9815SJim Ingham return StructuredData::GenericSP(); 19221b1d9815SJim Ingham } 19231b1d9815SJim Ingham 19241b1d9815SJim Ingham Locker py_lock(this, 19251b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19261b1d9815SJim Ingham 1927*c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook( 19281b1d9815SJim Ingham target_sp, class_name, python_interpreter->m_dictionary_name.c_str(), 19291b1d9815SJim Ingham args_data, error); 19301b1d9815SJim Ingham 1931*c154f397SPavel Labath return StructuredData::GenericSP( 1932*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 19331b1d9815SJim Ingham } 19341b1d9815SJim Ingham 19351b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop( 19361b1d9815SJim Ingham StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx, 19371b1d9815SJim Ingham lldb::StreamSP stream_sp) { 19381b1d9815SJim Ingham assert(implementor_sp && 19391b1d9815SJim Ingham "can't call a stop hook with an invalid implementor"); 19401b1d9815SJim Ingham assert(stream_sp && "can't call a stop hook with an invalid stream"); 19411b1d9815SJim Ingham 19421b1d9815SJim Ingham Locker py_lock(this, 19431b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19441b1d9815SJim Ingham 19451b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx)); 19461b1d9815SJim Ingham 19471b1d9815SJim Ingham bool ret_val = LLDBSwigPythonStopHookCallHandleStop( 19481b1d9815SJim Ingham implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp); 19491b1d9815SJim Ingham return ret_val; 19501b1d9815SJim Ingham } 19511b1d9815SJim Ingham 19522c1f46dcSZachary Turner StructuredData::ObjectSP 195363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 195497206d57SZachary Turner lldb_private::Status &error) { 1955dbd7fabaSJonas Devlieghere if (!FileSystem::Instance().Exists(file_spec)) { 19562c1f46dcSZachary Turner error.SetErrorString("no such file"); 19572c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19582c1f46dcSZachary Turner } 19592c1f46dcSZachary Turner 19602c1f46dcSZachary Turner StructuredData::ObjectSP module_sp; 19612c1f46dcSZachary Turner 1962f9517353SJonas Devlieghere LoadScriptOptions load_script_options = 1963f9517353SJonas Devlieghere LoadScriptOptions().SetInitSession(true).SetSilent(false); 1964f9517353SJonas Devlieghere if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options, 1965f9517353SJonas Devlieghere error, &module_sp)) 19662c1f46dcSZachary Turner return module_sp; 19672c1f46dcSZachary Turner 19682c1f46dcSZachary Turner return StructuredData::ObjectSP(); 19692c1f46dcSZachary Turner } 19702c1f46dcSZachary Turner 197163dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 1972b9c1b51eSKate Stone StructuredData::ObjectSP plugin_module_sp, Target *target, 197397206d57SZachary Turner const char *setting_name, lldb_private::Status &error) { 197405495c5dSJonas Devlieghere if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 19752c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19762c1f46dcSZachary Turner StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 19772c1f46dcSZachary Turner if (!generic) 19782c1f46dcSZachary Turner return StructuredData::DictionarySP(); 19792c1f46dcSZachary Turner 1980b9c1b51eSKate Stone Locker py_lock(this, 1981b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19822c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 19832c1f46dcSZachary Turner 198404edd189SLawrence D'Anna auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting( 198504edd189SLawrence D'Anna generic->GetValue(), setting_name, target_sp); 198604edd189SLawrence D'Anna 198704edd189SLawrence D'Anna if (!setting) 198804edd189SLawrence D'Anna return StructuredData::DictionarySP(); 198904edd189SLawrence D'Anna 199004edd189SLawrence D'Anna PythonDictionary py_dict = 199104edd189SLawrence D'Anna unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); 199204edd189SLawrence D'Anna 199304edd189SLawrence D'Anna if (!py_dict) 199404edd189SLawrence D'Anna return StructuredData::DictionarySP(); 199504edd189SLawrence D'Anna 19962c1f46dcSZachary Turner return py_dict.CreateStructuredDictionary(); 19972c1f46dcSZachary Turner } 19982c1f46dcSZachary Turner 19992c1f46dcSZachary Turner StructuredData::ObjectSP 200063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 2001b9c1b51eSKate Stone const char *class_name, lldb::ValueObjectSP valobj) { 20022c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 20032c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20042c1f46dcSZachary Turner 20052c1f46dcSZachary Turner if (!valobj.get()) 20062c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20072c1f46dcSZachary Turner 20082c1f46dcSZachary Turner ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 20092c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 20102c1f46dcSZachary Turner 20112c1f46dcSZachary Turner if (!target) 20122c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20132c1f46dcSZachary Turner 20142c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 201563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2016d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 20172c1f46dcSZachary Turner 2018d055e3a0SPedro Tammela if (!python_interpreter) 20192c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20202c1f46dcSZachary Turner 2021b9c1b51eSKate Stone Locker py_lock(this, 2022b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2023*c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider( 2024b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 20252c1f46dcSZachary Turner 2026*c154f397SPavel Labath return StructuredData::ObjectSP( 2027*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 20282c1f46dcSZachary Turner } 20292c1f46dcSZachary Turner 20302c1f46dcSZachary Turner StructuredData::GenericSP 203163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 20328d1fb843SJonas Devlieghere DebuggerSP debugger_sp(m_debugger.shared_from_this()); 20332c1f46dcSZachary Turner 20342c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 20352c1f46dcSZachary Turner return StructuredData::GenericSP(); 20362c1f46dcSZachary Turner 20372c1f46dcSZachary Turner if (!debugger_sp.get()) 20382c1f46dcSZachary Turner return StructuredData::GenericSP(); 20392c1f46dcSZachary Turner 2040b9c1b51eSKate Stone Locker py_lock(this, 2041b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2042*c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateCommandObject( 204305495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), debugger_sp); 20442c1f46dcSZachary Turner 2045*c154f397SPavel Labath return StructuredData::GenericSP( 2046*c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val))); 20472c1f46dcSZachary Turner } 20482c1f46dcSZachary Turner 204963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 2050b9c1b51eSKate Stone const char *oneliner, std::string &output, const void *name_token) { 20512c1f46dcSZachary Turner StringList input; 20522c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20532c1f46dcSZachary Turner return GenerateTypeScriptFunction(input, output, name_token); 20542c1f46dcSZachary Turner } 20552c1f46dcSZachary Turner 205663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 205763dd5d25SJonas Devlieghere const char *oneliner, std::string &output, const void *name_token) { 20582c1f46dcSZachary Turner StringList input; 20592c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 20602c1f46dcSZachary Turner return GenerateTypeSynthClass(input, output, name_token); 20612c1f46dcSZachary Turner } 20622c1f46dcSZachary Turner 206363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 2064738af7a6SJim Ingham StringList &user_input, std::string &output, 2065738af7a6SJim Ingham bool has_extra_args) { 20662c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 20672c1f46dcSZachary Turner user_input.RemoveBlankLines(); 20682c1f46dcSZachary Turner StreamString sstr; 206997206d57SZachary Turner Status error; 2070b9c1b51eSKate Stone if (user_input.GetSize() == 0) { 20712c1f46dcSZachary Turner error.SetErrorString("No input data."); 20722c1f46dcSZachary Turner return error; 20732c1f46dcSZachary Turner } 20742c1f46dcSZachary Turner 2075b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2076b9c1b51eSKate Stone "lldb_autogen_python_bp_callback_func_", num_created_functions)); 2077738af7a6SJim Ingham if (has_extra_args) 2078738af7a6SJim Ingham sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", 2079738af7a6SJim Ingham auto_generated_function_name.c_str()); 2080738af7a6SJim Ingham else 2081b9c1b51eSKate Stone sstr.Printf("def %s (frame, bp_loc, internal_dict):", 2082b9c1b51eSKate Stone auto_generated_function_name.c_str()); 20832c1f46dcSZachary Turner 20842c1f46dcSZachary Turner error = GenerateFunction(sstr.GetData(), user_input); 20852c1f46dcSZachary Turner if (!error.Success()) 20862c1f46dcSZachary Turner return error; 20872c1f46dcSZachary Turner 20882c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 20892c1f46dcSZachary Turner output.assign(auto_generated_function_name); 20902c1f46dcSZachary Turner return error; 20912c1f46dcSZachary Turner } 20922c1f46dcSZachary Turner 209363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 2094b9c1b51eSKate Stone StringList &user_input, std::string &output) { 20952c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 20962c1f46dcSZachary Turner user_input.RemoveBlankLines(); 20972c1f46dcSZachary Turner StreamString sstr; 20982c1f46dcSZachary Turner 20992c1f46dcSZachary Turner if (user_input.GetSize() == 0) 21002c1f46dcSZachary Turner return false; 21012c1f46dcSZachary Turner 2102b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2103b9c1b51eSKate Stone "lldb_autogen_python_wp_callback_func_", num_created_functions)); 2104b9c1b51eSKate Stone sstr.Printf("def %s (frame, wp, internal_dict):", 2105b9c1b51eSKate Stone auto_generated_function_name.c_str()); 21062c1f46dcSZachary Turner 21072c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 21082c1f46dcSZachary Turner return false; 21092c1f46dcSZachary Turner 21102c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 21112c1f46dcSZachary Turner output.assign(auto_generated_function_name); 21122c1f46dcSZachary Turner return true; 21132c1f46dcSZachary Turner } 21142c1f46dcSZachary Turner 211563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary( 2116b9c1b51eSKate Stone const char *python_function_name, lldb::ValueObjectSP valobj, 2117b9c1b51eSKate Stone StructuredData::ObjectSP &callee_wrapper_sp, 2118b9c1b51eSKate Stone const TypeSummaryOptions &options, std::string &retval) { 21192c1f46dcSZachary Turner 21205c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 21212c1f46dcSZachary Turner 2122b9c1b51eSKate Stone if (!valobj.get()) { 21232c1f46dcSZachary Turner retval.assign("<no object>"); 21242c1f46dcSZachary Turner return false; 21252c1f46dcSZachary Turner } 21262c1f46dcSZachary Turner 21272c1f46dcSZachary Turner void *old_callee = nullptr; 21282c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 2129b9c1b51eSKate Stone if (callee_wrapper_sp) { 21302c1f46dcSZachary Turner generic = callee_wrapper_sp->GetAsGeneric(); 21312c1f46dcSZachary Turner if (generic) 21322c1f46dcSZachary Turner old_callee = generic->GetValue(); 21332c1f46dcSZachary Turner } 21342c1f46dcSZachary Turner void *new_callee = old_callee; 21352c1f46dcSZachary Turner 21362c1f46dcSZachary Turner bool ret_val; 2137b9c1b51eSKate Stone if (python_function_name && *python_function_name) { 21382c1f46dcSZachary Turner { 2139b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 2140b9c1b51eSKate Stone Locker::NoSTDIN); 21412c1f46dcSZachary Turner { 21422c1f46dcSZachary Turner TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 21432c1f46dcSZachary Turner 214405495c5dSJonas Devlieghere static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 214505495c5dSJonas Devlieghere Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 214605495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallTypeScript( 2147b9c1b51eSKate Stone python_function_name, GetSessionDictionary().get(), valobj, 2148b9c1b51eSKate Stone &new_callee, options_sp, retval); 21492c1f46dcSZachary Turner } 21502c1f46dcSZachary Turner } 2151b9c1b51eSKate Stone } else { 21522c1f46dcSZachary Turner retval.assign("<no function name>"); 21532c1f46dcSZachary Turner return false; 21542c1f46dcSZachary Turner } 21552c1f46dcSZachary Turner 2156a6598575SRalf Grosse-Kunstleve if (new_callee && old_callee != new_callee) { 2157a6598575SRalf Grosse-Kunstleve Locker py_lock(this, 2158a6598575SRalf Grosse-Kunstleve Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2159*c154f397SPavel Labath callee_wrapper_sp = std::make_shared<StructuredPythonObject>( 2160*c154f397SPavel Labath PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee))); 2161a6598575SRalf Grosse-Kunstleve } 21622c1f46dcSZachary Turner 21632c1f46dcSZachary Turner return ret_val; 21642c1f46dcSZachary Turner } 21652c1f46dcSZachary Turner 216663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 2167b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t break_id, 2168b9c1b51eSKate Stone user_id_t break_loc_id) { 2169f7e07256SJim Ingham CommandDataPython *bp_option_data = (CommandDataPython *)baton; 21702c1f46dcSZachary Turner const char *python_function_name = bp_option_data->script_source.c_str(); 21712c1f46dcSZachary Turner 21722c1f46dcSZachary Turner if (!context) 21732c1f46dcSZachary Turner return true; 21742c1f46dcSZachary Turner 21752c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 21762c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 21772c1f46dcSZachary Turner 21782c1f46dcSZachary Turner if (!target) 21792c1f46dcSZachary Turner return true; 21802c1f46dcSZachary Turner 21812c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 218263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2183d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 21842c1f46dcSZachary Turner 2185d055e3a0SPedro Tammela if (!python_interpreter) 21862c1f46dcSZachary Turner return true; 21872c1f46dcSZachary Turner 2188b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 21892c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 21902c1f46dcSZachary Turner BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 2191b9c1b51eSKate Stone if (breakpoint_sp) { 2192b9c1b51eSKate Stone const BreakpointLocationSP bp_loc_sp( 2193b9c1b51eSKate Stone breakpoint_sp->FindLocationByID(break_loc_id)); 21942c1f46dcSZachary Turner 2195b9c1b51eSKate Stone if (stop_frame_sp && bp_loc_sp) { 21962c1f46dcSZachary Turner bool ret_val = true; 21972c1f46dcSZachary Turner { 2198b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2199b9c1b51eSKate Stone Locker::InitSession | 2200b9c1b51eSKate Stone Locker::NoSTDIN); 2201a69bbe02SLawrence D'Anna Expected<bool> maybe_ret_val = 2202a69bbe02SLawrence D'Anna LLDBSwigPythonBreakpointCallbackFunction( 2203b9c1b51eSKate Stone python_function_name, 2204b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 220582de8df2SPavel Labath bp_loc_sp, bp_option_data->m_extra_args); 2206a69bbe02SLawrence D'Anna 2207a69bbe02SLawrence D'Anna if (!maybe_ret_val) { 2208a69bbe02SLawrence D'Anna 2209a69bbe02SLawrence D'Anna llvm::handleAllErrors( 2210a69bbe02SLawrence D'Anna maybe_ret_val.takeError(), 2211a69bbe02SLawrence D'Anna [&](PythonException &E) { 2212a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.ReadBacktrace(); 2213a69bbe02SLawrence D'Anna }, 2214a69bbe02SLawrence D'Anna [&](const llvm::ErrorInfoBase &E) { 2215a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.message(); 2216a69bbe02SLawrence D'Anna }); 2217a69bbe02SLawrence D'Anna 2218a69bbe02SLawrence D'Anna } else { 2219a69bbe02SLawrence D'Anna ret_val = maybe_ret_val.get(); 2220a69bbe02SLawrence D'Anna } 22212c1f46dcSZachary Turner } 22222c1f46dcSZachary Turner return ret_val; 22232c1f46dcSZachary Turner } 22242c1f46dcSZachary Turner } 22252c1f46dcSZachary Turner } 22262c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22272c1f46dcSZachary Turner // trying to call the script function 22282c1f46dcSZachary Turner return true; 22292c1f46dcSZachary Turner } 22302c1f46dcSZachary Turner 223163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 2232b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 2233b9c1b51eSKate Stone WatchpointOptions::CommandData *wp_option_data = 2234b9c1b51eSKate Stone (WatchpointOptions::CommandData *)baton; 22352c1f46dcSZachary Turner const char *python_function_name = wp_option_data->script_source.c_str(); 22362c1f46dcSZachary Turner 22372c1f46dcSZachary Turner if (!context) 22382c1f46dcSZachary Turner return true; 22392c1f46dcSZachary Turner 22402c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 22412c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 22422c1f46dcSZachary Turner 22432c1f46dcSZachary Turner if (!target) 22442c1f46dcSZachary Turner return true; 22452c1f46dcSZachary Turner 22462c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 224763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2248d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 22492c1f46dcSZachary Turner 2250d055e3a0SPedro Tammela if (!python_interpreter) 22512c1f46dcSZachary Turner return true; 22522c1f46dcSZachary Turner 2253b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 22542c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 22552c1f46dcSZachary Turner WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 2256b9c1b51eSKate Stone if (wp_sp) { 2257b9c1b51eSKate Stone if (stop_frame_sp && wp_sp) { 22582c1f46dcSZachary Turner bool ret_val = true; 22592c1f46dcSZachary Turner { 2260b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2261b9c1b51eSKate Stone Locker::InitSession | 2262b9c1b51eSKate Stone Locker::NoSTDIN); 226305495c5dSJonas Devlieghere ret_val = LLDBSwigPythonWatchpointCallbackFunction( 2264b9c1b51eSKate Stone python_function_name, 2265b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 22662c1f46dcSZachary Turner wp_sp); 22672c1f46dcSZachary Turner } 22682c1f46dcSZachary Turner return ret_val; 22692c1f46dcSZachary Turner } 22702c1f46dcSZachary Turner } 22712c1f46dcSZachary Turner } 22722c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 22732c1f46dcSZachary Turner // trying to call the script function 22742c1f46dcSZachary Turner return true; 22752c1f46dcSZachary Turner } 22762c1f46dcSZachary Turner 227763dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 2278b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 22792c1f46dcSZachary Turner if (!implementor_sp) 22802c1f46dcSZachary Turner return 0; 22812c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 22822c1f46dcSZachary Turner if (!generic) 22832c1f46dcSZachary Turner return 0; 22849a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 22852c1f46dcSZachary Turner if (!implementor) 22862c1f46dcSZachary Turner return 0; 22872c1f46dcSZachary Turner 22882c1f46dcSZachary Turner size_t ret_val = 0; 22892c1f46dcSZachary Turner 22902c1f46dcSZachary Turner { 2291b9c1b51eSKate Stone Locker py_lock(this, 2292b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 229305495c5dSJonas Devlieghere ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 22942c1f46dcSZachary Turner } 22952c1f46dcSZachary Turner 22962c1f46dcSZachary Turner return ret_val; 22972c1f46dcSZachary Turner } 22982c1f46dcSZachary Turner 229963dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 2300b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 23012c1f46dcSZachary Turner if (!implementor_sp) 23022c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23032c1f46dcSZachary Turner 23042c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23052c1f46dcSZachary Turner if (!generic) 23062c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23079a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23082c1f46dcSZachary Turner if (!implementor) 23092c1f46dcSZachary Turner return lldb::ValueObjectSP(); 23102c1f46dcSZachary Turner 23112c1f46dcSZachary Turner lldb::ValueObjectSP ret_val; 23122c1f46dcSZachary Turner { 2313b9c1b51eSKate Stone Locker py_lock(this, 2314b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 23159a14adeaSPavel Labath PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 2316b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2317b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 231805495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 23192c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 23202c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23212c1f46dcSZachary Turner else 232205495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2323b9c1b51eSKate Stone } else { 23242c1f46dcSZachary Turner Py_XDECREF(child_ptr); 23252c1f46dcSZachary Turner } 23262c1f46dcSZachary Turner } 23272c1f46dcSZachary Turner 23282c1f46dcSZachary Turner return ret_val; 23292c1f46dcSZachary Turner } 23302c1f46dcSZachary Turner 233163dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 2332b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 23332c1f46dcSZachary Turner if (!implementor_sp) 23342c1f46dcSZachary Turner return UINT32_MAX; 23352c1f46dcSZachary Turner 23362c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23372c1f46dcSZachary Turner if (!generic) 23382c1f46dcSZachary Turner return UINT32_MAX; 23399a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23402c1f46dcSZachary Turner if (!implementor) 23412c1f46dcSZachary Turner return UINT32_MAX; 23422c1f46dcSZachary Turner 23432c1f46dcSZachary Turner int ret_val = UINT32_MAX; 23442c1f46dcSZachary Turner 23452c1f46dcSZachary Turner { 2346b9c1b51eSKate Stone Locker py_lock(this, 2347b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 234805495c5dSJonas Devlieghere ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 23492c1f46dcSZachary Turner } 23502c1f46dcSZachary Turner 23512c1f46dcSZachary Turner return ret_val; 23522c1f46dcSZachary Turner } 23532c1f46dcSZachary Turner 235463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 2355b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23562c1f46dcSZachary Turner bool ret_val = false; 23572c1f46dcSZachary Turner 23582c1f46dcSZachary Turner if (!implementor_sp) 23592c1f46dcSZachary Turner return ret_val; 23602c1f46dcSZachary Turner 23612c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23622c1f46dcSZachary Turner if (!generic) 23632c1f46dcSZachary Turner return ret_val; 23649a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23652c1f46dcSZachary Turner if (!implementor) 23662c1f46dcSZachary Turner return ret_val; 23672c1f46dcSZachary Turner 23682c1f46dcSZachary Turner { 2369b9c1b51eSKate Stone Locker py_lock(this, 2370b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 237105495c5dSJonas Devlieghere ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 23722c1f46dcSZachary Turner } 23732c1f46dcSZachary Turner 23742c1f46dcSZachary Turner return ret_val; 23752c1f46dcSZachary Turner } 23762c1f46dcSZachary Turner 237763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 2378b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 23792c1f46dcSZachary Turner bool ret_val = false; 23802c1f46dcSZachary Turner 23812c1f46dcSZachary Turner if (!implementor_sp) 23822c1f46dcSZachary Turner return ret_val; 23832c1f46dcSZachary Turner 23842c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 23852c1f46dcSZachary Turner if (!generic) 23862c1f46dcSZachary Turner return ret_val; 23879a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 23882c1f46dcSZachary Turner if (!implementor) 23892c1f46dcSZachary Turner return ret_val; 23902c1f46dcSZachary Turner 23912c1f46dcSZachary Turner { 2392b9c1b51eSKate Stone Locker py_lock(this, 2393b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 239405495c5dSJonas Devlieghere ret_val = 239505495c5dSJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 23962c1f46dcSZachary Turner } 23972c1f46dcSZachary Turner 23982c1f46dcSZachary Turner return ret_val; 23992c1f46dcSZachary Turner } 24002c1f46dcSZachary Turner 240163dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 2402b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 24032c1f46dcSZachary Turner lldb::ValueObjectSP ret_val(nullptr); 24042c1f46dcSZachary Turner 24052c1f46dcSZachary Turner if (!implementor_sp) 24062c1f46dcSZachary Turner return ret_val; 24072c1f46dcSZachary Turner 24082c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24092c1f46dcSZachary Turner if (!generic) 24102c1f46dcSZachary Turner return ret_val; 24119a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue()); 24122c1f46dcSZachary Turner if (!implementor) 24132c1f46dcSZachary Turner return ret_val; 24142c1f46dcSZachary Turner 24152c1f46dcSZachary Turner { 2416b9c1b51eSKate Stone Locker py_lock(this, 2417b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24189a14adeaSPavel Labath PyObject *child_ptr = 24199a14adeaSPavel Labath LLDBSwigPython_GetValueSynthProviderInstance(implementor); 2420b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2421b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 242205495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 24232c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 24242c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24252c1f46dcSZachary Turner else 242605495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2427b9c1b51eSKate Stone } else { 24282c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24292c1f46dcSZachary Turner } 24302c1f46dcSZachary Turner } 24312c1f46dcSZachary Turner 24322c1f46dcSZachary Turner return ret_val; 24332c1f46dcSZachary Turner } 24342c1f46dcSZachary Turner 243563dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 2436b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 2437b9c1b51eSKate Stone Locker py_lock(this, 2438b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 24396eec8d6cSEnrico Granata 24406eec8d6cSEnrico Granata static char callee_name[] = "get_type_name"; 24416eec8d6cSEnrico Granata 24426eec8d6cSEnrico Granata ConstString ret_val; 24436eec8d6cSEnrico Granata bool got_string = false; 24446eec8d6cSEnrico Granata std::string buffer; 24456eec8d6cSEnrico Granata 24466eec8d6cSEnrico Granata if (!implementor_sp) 24476eec8d6cSEnrico Granata return ret_val; 24486eec8d6cSEnrico Granata 24496eec8d6cSEnrico Granata StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24506eec8d6cSEnrico Granata if (!generic) 24516eec8d6cSEnrico Granata return ret_val; 2452b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2453b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 24546eec8d6cSEnrico Granata if (!implementor.IsAllocated()) 24556eec8d6cSEnrico Granata return ret_val; 24566eec8d6cSEnrico Granata 2457b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 2458b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 24596eec8d6cSEnrico Granata 24606eec8d6cSEnrico Granata if (PyErr_Occurred()) 24616eec8d6cSEnrico Granata PyErr_Clear(); 24626eec8d6cSEnrico Granata 24636eec8d6cSEnrico Granata if (!pmeth.IsAllocated()) 24646eec8d6cSEnrico Granata return ret_val; 24656eec8d6cSEnrico Granata 2466b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 24676eec8d6cSEnrico Granata if (PyErr_Occurred()) 24686eec8d6cSEnrico Granata PyErr_Clear(); 24696eec8d6cSEnrico Granata return ret_val; 24706eec8d6cSEnrico Granata } 24716eec8d6cSEnrico Granata 24726eec8d6cSEnrico Granata if (PyErr_Occurred()) 24736eec8d6cSEnrico Granata PyErr_Clear(); 24746eec8d6cSEnrico Granata 24756eec8d6cSEnrico Granata // right now we know this function exists and is callable.. 2476b9c1b51eSKate Stone PythonObject py_return( 2477b9c1b51eSKate Stone PyRefType::Owned, 2478b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 24796eec8d6cSEnrico Granata 24806eec8d6cSEnrico Granata // if it fails, print the error but otherwise go on 2481b9c1b51eSKate Stone if (PyErr_Occurred()) { 24826eec8d6cSEnrico Granata PyErr_Print(); 24836eec8d6cSEnrico Granata PyErr_Clear(); 24846eec8d6cSEnrico Granata } 24856eec8d6cSEnrico Granata 2486b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 24876eec8d6cSEnrico Granata PythonString py_string(PyRefType::Borrowed, py_return.get()); 24886eec8d6cSEnrico Granata llvm::StringRef return_data(py_string.GetString()); 2489b9c1b51eSKate Stone if (!return_data.empty()) { 24906eec8d6cSEnrico Granata buffer.assign(return_data.data(), return_data.size()); 24916eec8d6cSEnrico Granata got_string = true; 24926eec8d6cSEnrico Granata } 24936eec8d6cSEnrico Granata } 24946eec8d6cSEnrico Granata 24956eec8d6cSEnrico Granata if (got_string) 24966eec8d6cSEnrico Granata ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 24976eec8d6cSEnrico Granata 24986eec8d6cSEnrico Granata return ret_val; 24996eec8d6cSEnrico Granata } 25006eec8d6cSEnrico Granata 250163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 250263dd5d25SJonas Devlieghere const char *impl_function, Process *process, std::string &output, 250397206d57SZachary Turner Status &error) { 25042c1f46dcSZachary Turner bool ret_val; 2505b9c1b51eSKate Stone if (!process) { 25062c1f46dcSZachary Turner error.SetErrorString("no process"); 25072c1f46dcSZachary Turner return false; 25082c1f46dcSZachary Turner } 2509b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25102c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25112c1f46dcSZachary Turner return false; 25122c1f46dcSZachary Turner } 251305495c5dSJonas Devlieghere 25142c1f46dcSZachary Turner { 2515b9c1b51eSKate Stone Locker py_lock(this, 2516b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 251705495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 25187f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), process->shared_from_this(), 25197f09ab08SPavel Labath output); 25202c1f46dcSZachary Turner if (!ret_val) 25212c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25222c1f46dcSZachary Turner } 25232c1f46dcSZachary Turner return ret_val; 25242c1f46dcSZachary Turner } 25252c1f46dcSZachary Turner 252663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 252763dd5d25SJonas Devlieghere const char *impl_function, Thread *thread, std::string &output, 252897206d57SZachary Turner Status &error) { 2529b9c1b51eSKate Stone if (!thread) { 25302c1f46dcSZachary Turner error.SetErrorString("no thread"); 25312c1f46dcSZachary Turner return false; 25322c1f46dcSZachary Turner } 2533b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25342c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25352c1f46dcSZachary Turner return false; 25362c1f46dcSZachary Turner } 253705495c5dSJonas Devlieghere 2538b9c1b51eSKate Stone Locker py_lock(this, 2539b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25407406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread( 25417406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 25427406d236SPavel Labath thread->shared_from_this())) { 25437406d236SPavel Labath output = std::move(*result); 25447406d236SPavel Labath return true; 25452c1f46dcSZachary Turner } 25467406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 25477406d236SPavel Labath return false; 25482c1f46dcSZachary Turner } 25492c1f46dcSZachary Turner 255063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 255163dd5d25SJonas Devlieghere const char *impl_function, Target *target, std::string &output, 255297206d57SZachary Turner Status &error) { 25532c1f46dcSZachary Turner bool ret_val; 2554b9c1b51eSKate Stone if (!target) { 25552c1f46dcSZachary Turner error.SetErrorString("no thread"); 25562c1f46dcSZachary Turner return false; 25572c1f46dcSZachary Turner } 2558b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25592c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25602c1f46dcSZachary Turner return false; 25612c1f46dcSZachary Turner } 256205495c5dSJonas Devlieghere 25632c1f46dcSZachary Turner { 25642c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 2565b9c1b51eSKate Stone Locker py_lock(this, 2566b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 256705495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 2568b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), target_sp, output); 25692c1f46dcSZachary Turner if (!ret_val) 25702c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 25712c1f46dcSZachary Turner } 25722c1f46dcSZachary Turner return ret_val; 25732c1f46dcSZachary Turner } 25742c1f46dcSZachary Turner 257563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 257663dd5d25SJonas Devlieghere const char *impl_function, StackFrame *frame, std::string &output, 257797206d57SZachary Turner Status &error) { 2578b9c1b51eSKate Stone if (!frame) { 25792c1f46dcSZachary Turner error.SetErrorString("no frame"); 25802c1f46dcSZachary Turner return false; 25812c1f46dcSZachary Turner } 2582b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 25832c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 25842c1f46dcSZachary Turner return false; 25852c1f46dcSZachary Turner } 258605495c5dSJonas Devlieghere 2587b9c1b51eSKate Stone Locker py_lock(this, 2588b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25897406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame( 25907406d236SPavel Labath impl_function, m_dictionary_name.c_str(), 25917406d236SPavel Labath frame->shared_from_this())) { 25927406d236SPavel Labath output = std::move(*result); 25937406d236SPavel Labath return true; 25942c1f46dcSZachary Turner } 25957406d236SPavel Labath error.SetErrorString("python script evaluation failed"); 25967406d236SPavel Labath return false; 25972c1f46dcSZachary Turner } 25982c1f46dcSZachary Turner 259963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 260063dd5d25SJonas Devlieghere const char *impl_function, ValueObject *value, std::string &output, 260197206d57SZachary Turner Status &error) { 26022c1f46dcSZachary Turner bool ret_val; 2603b9c1b51eSKate Stone if (!value) { 26042c1f46dcSZachary Turner error.SetErrorString("no value"); 26052c1f46dcSZachary Turner return false; 26062c1f46dcSZachary Turner } 2607b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26082c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26092c1f46dcSZachary Turner return false; 26102c1f46dcSZachary Turner } 261105495c5dSJonas Devlieghere 26122c1f46dcSZachary Turner { 2613b9c1b51eSKate Stone Locker py_lock(this, 2614b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 261505495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordValue( 26167f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), value->GetSP(), output); 26172c1f46dcSZachary Turner if (!ret_val) 26182c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26192c1f46dcSZachary Turner } 26202c1f46dcSZachary Turner return ret_val; 26212c1f46dcSZachary Turner } 26222c1f46dcSZachary Turner 2623b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr, 2624b9c1b51eSKate Stone const std::string &newStr) { 26252c1f46dcSZachary Turner size_t pos = 0; 26262c1f46dcSZachary Turner uint64_t matches = 0; 2627b9c1b51eSKate Stone while ((pos = str.find(oldStr, pos)) != std::string::npos) { 26282c1f46dcSZachary Turner matches++; 26292c1f46dcSZachary Turner str.replace(pos, oldStr.length(), newStr); 26302c1f46dcSZachary Turner pos += newStr.length(); 26312c1f46dcSZachary Turner } 26322c1f46dcSZachary Turner return matches; 26332c1f46dcSZachary Turner } 26342c1f46dcSZachary Turner 263563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule( 2636f9517353SJonas Devlieghere const char *pathname, const LoadScriptOptions &options, 2637f9517353SJonas Devlieghere lldb_private::Status &error, StructuredData::ObjectSP *module_sp, 2638f9517353SJonas Devlieghere FileSpec extra_search_dir) { 26393b33b416SJonas Devlieghere namespace fs = llvm::sys::fs; 264000bb397bSJonas Devlieghere namespace path = llvm::sys::path; 26413b33b416SJonas Devlieghere 2642f9517353SJonas Devlieghere ExecuteScriptOptions exc_options = ExecuteScriptOptions() 2643f9517353SJonas Devlieghere .SetEnableIO(!options.GetSilent()) 2644f9517353SJonas Devlieghere .SetSetLLDBGlobals(false); 2645f9517353SJonas Devlieghere 2646b9c1b51eSKate Stone if (!pathname || !pathname[0]) { 26472c1f46dcSZachary Turner error.SetErrorString("invalid pathname"); 26482c1f46dcSZachary Turner return false; 26492c1f46dcSZachary Turner } 26502c1f46dcSZachary Turner 2651f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 2652f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 2653f9517353SJonas Devlieghere exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr); 2654f9517353SJonas Devlieghere 2655f9517353SJonas Devlieghere if (!io_redirect_or_error) { 2656f9517353SJonas Devlieghere error = io_redirect_or_error.takeError(); 2657f9517353SJonas Devlieghere return false; 2658f9517353SJonas Devlieghere } 2659f9517353SJonas Devlieghere 2660f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 26612c1f46dcSZachary Turner 2662f9f36097SAdrian McCarthy // Before executing Python code, lock the GIL. 266320b52c33SJonas Devlieghere Locker py_lock(this, 266420b52c33SJonas Devlieghere Locker::AcquireLock | 2665f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::InitSession : 0) | 2666f9517353SJonas Devlieghere Locker::NoSTDIN, 2667b9c1b51eSKate Stone Locker::FreeAcquiredLock | 2668f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::TearDownSession : 0), 2669f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 2670f9517353SJonas Devlieghere io_redirect.GetErrorFile()); 26712c1f46dcSZachary Turner 2672f9517353SJonas Devlieghere auto ExtendSysPath = [&](std::string directory) -> llvm::Error { 267300bb397bSJonas Devlieghere if (directory.empty()) { 267400bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 267500bb397bSJonas Devlieghere "invalid directory name", llvm::inconvertibleErrorCode()); 267642a9da7bSStefan Granitz } 267742a9da7bSStefan Granitz 2678f9f36097SAdrian McCarthy replace_all(directory, "\\", "\\\\"); 26792c1f46dcSZachary Turner replace_all(directory, "'", "\\'"); 26802c1f46dcSZachary Turner 268100bb397bSJonas Devlieghere // Make sure that Python has "directory" in the search path. 26822c1f46dcSZachary Turner StreamString command_stream; 2683b9c1b51eSKate Stone command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 2684b9c1b51eSKate Stone "sys.path.insert(1,'%s');\n\n", 2685b9c1b51eSKate Stone directory.c_str(), directory.c_str()); 2686b9c1b51eSKate Stone bool syspath_retval = 2687f9517353SJonas Devlieghere ExecuteMultipleLines(command_stream.GetData(), exc_options).Success(); 2688b9c1b51eSKate Stone if (!syspath_retval) { 268900bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 269000bb397bSJonas Devlieghere "Python sys.path handling failed", llvm::inconvertibleErrorCode()); 26912c1f46dcSZachary Turner } 26922c1f46dcSZachary Turner 269300bb397bSJonas Devlieghere return llvm::Error::success(); 269400bb397bSJonas Devlieghere }; 269500bb397bSJonas Devlieghere 269600bb397bSJonas Devlieghere std::string module_name(pathname); 2697d6e80578SJonas Devlieghere bool possible_package = false; 269800bb397bSJonas Devlieghere 269900bb397bSJonas Devlieghere if (extra_search_dir) { 270000bb397bSJonas Devlieghere if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) { 270100bb397bSJonas Devlieghere error = std::move(e); 270200bb397bSJonas Devlieghere return false; 270300bb397bSJonas Devlieghere } 270400bb397bSJonas Devlieghere } else { 270500bb397bSJonas Devlieghere FileSpec module_file(pathname); 270600bb397bSJonas Devlieghere FileSystem::Instance().Resolve(module_file); 270700bb397bSJonas Devlieghere FileSystem::Instance().Collect(module_file); 270800bb397bSJonas Devlieghere 270900bb397bSJonas Devlieghere fs::file_status st; 271000bb397bSJonas Devlieghere std::error_code ec = status(module_file.GetPath(), st); 271100bb397bSJonas Devlieghere 271200bb397bSJonas Devlieghere if (ec || st.type() == fs::file_type::status_error || 271300bb397bSJonas Devlieghere st.type() == fs::file_type::type_unknown || 271400bb397bSJonas Devlieghere st.type() == fs::file_type::file_not_found) { 271500bb397bSJonas Devlieghere // if not a valid file of any sort, check if it might be a filename still 271600bb397bSJonas Devlieghere // dot can't be used but / and \ can, and if either is found, reject 271700bb397bSJonas Devlieghere if (strchr(pathname, '\\') || strchr(pathname, '/')) { 271800bb397bSJonas Devlieghere error.SetErrorString("invalid pathname"); 271900bb397bSJonas Devlieghere return false; 272000bb397bSJonas Devlieghere } 272100bb397bSJonas Devlieghere // Not a filename, probably a package of some sort, let it go through. 2722d6e80578SJonas Devlieghere possible_package = true; 272300bb397bSJonas Devlieghere } else if (is_directory(st) || is_regular_file(st)) { 272400bb397bSJonas Devlieghere if (module_file.GetDirectory().IsEmpty()) { 272500bb397bSJonas Devlieghere error.SetErrorString("invalid directory name"); 272600bb397bSJonas Devlieghere return false; 272700bb397bSJonas Devlieghere } 272800bb397bSJonas Devlieghere if (llvm::Error e = 272900bb397bSJonas Devlieghere ExtendSysPath(module_file.GetDirectory().GetCString())) { 273000bb397bSJonas Devlieghere error = std::move(e); 273100bb397bSJonas Devlieghere return false; 273200bb397bSJonas Devlieghere } 273300bb397bSJonas Devlieghere module_name = module_file.GetFilename().GetCString(); 2734b9c1b51eSKate Stone } else { 27352c1f46dcSZachary Turner error.SetErrorString("no known way to import this module specification"); 27362c1f46dcSZachary Turner return false; 27372c1f46dcSZachary Turner } 273800bb397bSJonas Devlieghere } 27392c1f46dcSZachary Turner 27401197ee35SJonas Devlieghere // Strip .py or .pyc extension 274100bb397bSJonas Devlieghere llvm::StringRef extension = llvm::sys::path::extension(module_name); 27421197ee35SJonas Devlieghere if (!extension.empty()) { 27431197ee35SJonas Devlieghere if (extension == ".py") 274400bb397bSJonas Devlieghere module_name.resize(module_name.length() - 3); 27451197ee35SJonas Devlieghere else if (extension == ".pyc") 274600bb397bSJonas Devlieghere module_name.resize(module_name.length() - 4); 27471197ee35SJonas Devlieghere } 27481197ee35SJonas Devlieghere 2749d6e80578SJonas Devlieghere if (!possible_package && module_name.find('.') != llvm::StringRef::npos) { 2750d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2751d6e80578SJonas Devlieghere "Python does not allow dots in module names: %s", module_name.c_str()); 2752d6e80578SJonas Devlieghere return false; 2753d6e80578SJonas Devlieghere } 2754d6e80578SJonas Devlieghere 2755d6e80578SJonas Devlieghere if (module_name.find('-') != llvm::StringRef::npos) { 2756d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2757d6e80578SJonas Devlieghere "Python discourages dashes in module names: %s", module_name.c_str()); 2758d6e80578SJonas Devlieghere return false; 2759d6e80578SJonas Devlieghere } 2760d6e80578SJonas Devlieghere 2761f9517353SJonas Devlieghere // Check if the module is already imported. 276200bb397bSJonas Devlieghere StreamString command_stream; 27632c1f46dcSZachary Turner command_stream.Clear(); 276400bb397bSJonas Devlieghere command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str()); 27652c1f46dcSZachary Turner bool does_contain = false; 2766f9517353SJonas Devlieghere // This call will succeed if the module was ever imported in any Debugger in 2767f9517353SJonas Devlieghere // the lifetime of the process in which this LLDB framework is living. 2768f9517353SJonas Devlieghere const bool does_contain_executed = ExecuteOneLineWithReturn( 2769b9c1b51eSKate Stone command_stream.GetData(), 2770f9517353SJonas Devlieghere ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options); 2771f9517353SJonas Devlieghere 2772f9517353SJonas Devlieghere const bool was_imported_globally = does_contain_executed && does_contain; 2773612384f6SJonas Devlieghere const bool was_imported_locally = 2774612384f6SJonas Devlieghere GetSessionDictionary() 277500bb397bSJonas Devlieghere .GetItemForKey(PythonString(module_name)) 2776b9c1b51eSKate Stone .IsAllocated(); 27772c1f46dcSZachary Turner 27782c1f46dcSZachary Turner // now actually do the import 27792c1f46dcSZachary Turner command_stream.Clear(); 27802c1f46dcSZachary Turner 2781612384f6SJonas Devlieghere if (was_imported_globally || was_imported_locally) { 27822c1f46dcSZachary Turner if (!was_imported_locally) 278300bb397bSJonas Devlieghere command_stream.Printf("import %s ; reload_module(%s)", 278400bb397bSJonas Devlieghere module_name.c_str(), module_name.c_str()); 27852c1f46dcSZachary Turner else 278600bb397bSJonas Devlieghere command_stream.Printf("reload_module(%s)", module_name.c_str()); 2787b9c1b51eSKate Stone } else 278800bb397bSJonas Devlieghere command_stream.Printf("import %s", module_name.c_str()); 27892c1f46dcSZachary Turner 2790f9517353SJonas Devlieghere error = ExecuteMultipleLines(command_stream.GetData(), exc_options); 27912c1f46dcSZachary Turner if (error.Fail()) 27922c1f46dcSZachary Turner return false; 27932c1f46dcSZachary Turner 27942c1f46dcSZachary Turner // if we are here, everything worked 27952c1f46dcSZachary Turner // call __lldb_init_module(debugger,dict) 279600bb397bSJonas Devlieghere if (!LLDBSwigPythonCallModuleInit(module_name.c_str(), 27977406d236SPavel Labath m_dictionary_name.c_str(), 27987406d236SPavel Labath m_debugger.shared_from_this())) { 27992c1f46dcSZachary Turner error.SetErrorString("calling __lldb_init_module failed"); 28002c1f46dcSZachary Turner return false; 28012c1f46dcSZachary Turner } 28022c1f46dcSZachary Turner 2803b9c1b51eSKate Stone if (module_sp) { 28042c1f46dcSZachary Turner // everything went just great, now set the module object 28052c1f46dcSZachary Turner command_stream.Clear(); 280600bb397bSJonas Devlieghere command_stream.Printf("%s", module_name.c_str()); 28072c1f46dcSZachary Turner void *module_pyobj = nullptr; 2808b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 2809b9c1b51eSKate Stone command_stream.GetData(), 2810f9517353SJonas Devlieghere ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj, 2811f9517353SJonas Devlieghere exc_options) && 2812b9c1b51eSKate Stone module_pyobj) 2813*c154f397SPavel Labath *module_sp = std::make_shared<StructuredPythonObject>(PythonObject( 2814*c154f397SPavel Labath PyRefType::Owned, static_cast<PyObject *>(module_pyobj))); 28152c1f46dcSZachary Turner } 28162c1f46dcSZachary Turner 28172c1f46dcSZachary Turner return true; 28182c1f46dcSZachary Turner } 28192c1f46dcSZachary Turner 282063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 28212c1f46dcSZachary Turner if (!word || !word[0]) 28222c1f46dcSZachary Turner return false; 28232c1f46dcSZachary Turner 28242c1f46dcSZachary Turner llvm::StringRef word_sr(word); 28252c1f46dcSZachary Turner 282605097246SAdrian Prantl // filter out a few characters that would just confuse us and that are 282705097246SAdrian Prantl // clearly not keyword material anyway 282810b113e8SJonas Devlieghere if (word_sr.find('"') != llvm::StringRef::npos || 282910b113e8SJonas Devlieghere word_sr.find('\'') != llvm::StringRef::npos) 28302c1f46dcSZachary Turner return false; 28312c1f46dcSZachary Turner 28322c1f46dcSZachary Turner StreamString command_stream; 28332c1f46dcSZachary Turner command_stream.Printf("keyword.iskeyword('%s')", word); 28342c1f46dcSZachary Turner bool result; 28352c1f46dcSZachary Turner ExecuteScriptOptions options; 28362c1f46dcSZachary Turner options.SetEnableIO(false); 28372c1f46dcSZachary Turner options.SetMaskoutErrors(true); 28382c1f46dcSZachary Turner options.SetSetLLDBGlobals(false); 2839b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(command_stream.GetData(), 2840b9c1b51eSKate Stone ScriptInterpreter::eScriptReturnTypeBool, 2841b9c1b51eSKate Stone &result, options)) 28422c1f46dcSZachary Turner return result; 28432c1f46dcSZachary Turner return false; 28442c1f46dcSZachary Turner } 28452c1f46dcSZachary Turner 284663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 2847b9c1b51eSKate Stone lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 2848b9c1b51eSKate Stone : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 2849b9c1b51eSKate Stone m_old_asynch(debugger_sp->GetAsyncExecution()) { 28502c1f46dcSZachary Turner if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 28512c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(false); 28522c1f46dcSZachary Turner else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 28532c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(true); 28542c1f46dcSZachary Turner } 28552c1f46dcSZachary Turner 285663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 28572c1f46dcSZachary Turner if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 28582c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(m_old_asynch); 28592c1f46dcSZachary Turner } 28602c1f46dcSZachary Turner 286163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 28624d51a902SRaphael Isemann const char *impl_function, llvm::StringRef args, 28632c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 286497206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2865b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2866b9c1b51eSKate Stone if (!impl_function) { 28672c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 28682c1f46dcSZachary Turner return false; 28692c1f46dcSZachary Turner } 28702c1f46dcSZachary Turner 28718d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 28722c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 28732c1f46dcSZachary Turner 2874b9c1b51eSKate Stone if (!debugger_sp.get()) { 28752c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 28762c1f46dcSZachary Turner return false; 28772c1f46dcSZachary Turner } 28782c1f46dcSZachary Turner 28792c1f46dcSZachary Turner bool ret_val = false; 28802c1f46dcSZachary Turner 28812c1f46dcSZachary Turner std::string err_msg; 28822c1f46dcSZachary Turner 28832c1f46dcSZachary Turner { 28842c1f46dcSZachary Turner Locker py_lock(this, 2885b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2886b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 28872c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 28882c1f46dcSZachary Turner 2889b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 28902c1f46dcSZachary Turner 28914d51a902SRaphael Isemann std::string args_str = args.str(); 289205495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommand( 289305495c5dSJonas Devlieghere impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 289405495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp); 28952c1f46dcSZachary Turner } 28962c1f46dcSZachary Turner 28972c1f46dcSZachary Turner if (!ret_val) 28982c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 28992c1f46dcSZachary Turner else 29002c1f46dcSZachary Turner error.Clear(); 29012c1f46dcSZachary Turner 29022c1f46dcSZachary Turner return ret_val; 29032c1f46dcSZachary Turner } 29042c1f46dcSZachary Turner 290563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 29064d51a902SRaphael Isemann StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 29072c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 290897206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2909b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2910b9c1b51eSKate Stone if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 29112c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 29122c1f46dcSZachary Turner return false; 29132c1f46dcSZachary Turner } 29142c1f46dcSZachary Turner 29158d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29162c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29172c1f46dcSZachary Turner 2918b9c1b51eSKate Stone if (!debugger_sp.get()) { 29192c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 29202c1f46dcSZachary Turner return false; 29212c1f46dcSZachary Turner } 29222c1f46dcSZachary Turner 29232c1f46dcSZachary Turner bool ret_val = false; 29242c1f46dcSZachary Turner 29252c1f46dcSZachary Turner std::string err_msg; 29262c1f46dcSZachary Turner 29272c1f46dcSZachary Turner { 29282c1f46dcSZachary Turner Locker py_lock(this, 2929b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 2930b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 29312c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 29322c1f46dcSZachary Turner 2933b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 29342c1f46dcSZachary Turner 29354d51a902SRaphael Isemann std::string args_str = args.str(); 29369a14adeaSPavel Labath ret_val = LLDBSwigPythonCallCommandObject( 29379a14adeaSPavel Labath static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp, 29389a14adeaSPavel Labath args_str.c_str(), cmd_retobj, exe_ctx_ref_sp); 29392c1f46dcSZachary Turner } 29402c1f46dcSZachary Turner 29412c1f46dcSZachary Turner if (!ret_val) 29422c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 29432c1f46dcSZachary Turner else 29442c1f46dcSZachary Turner error.Clear(); 29452c1f46dcSZachary Turner 29462c1f46dcSZachary Turner return ret_val; 29472c1f46dcSZachary Turner } 29482c1f46dcSZachary Turner 294993571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object 295093571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's 295193571c3cSJonas Devlieghere /// value is None. 295263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 2953b9c1b51eSKate Stone std::string &dest) { 29542c1f46dcSZachary Turner dest.clear(); 295593571c3cSJonas Devlieghere 29562c1f46dcSZachary Turner if (!item || !*item) 29572c1f46dcSZachary Turner return false; 295893571c3cSJonas Devlieghere 29592c1f46dcSZachary Turner std::string command(item); 29602c1f46dcSZachary Turner command += ".__doc__"; 29612c1f46dcSZachary Turner 296293571c3cSJonas Devlieghere // Python is going to point this to valid data if ExecuteOneLineWithReturn 296393571c3cSJonas Devlieghere // returns successfully. 296493571c3cSJonas Devlieghere char *result_ptr = nullptr; 29652c1f46dcSZachary Turner 2966b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 296793571c3cSJonas Devlieghere command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 29682c1f46dcSZachary Turner &result_ptr, 2969fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false))) { 29702c1f46dcSZachary Turner if (result_ptr) 29712c1f46dcSZachary Turner dest.assign(result_ptr); 29722c1f46dcSZachary Turner return true; 29732c1f46dcSZachary Turner } 297493571c3cSJonas Devlieghere 297593571c3cSJonas Devlieghere StreamString str_stream; 297693571c3cSJonas Devlieghere str_stream << "Function " << item 297793571c3cSJonas Devlieghere << " was not found. Containing module might be missing."; 297893571c3cSJonas Devlieghere dest = std::string(str_stream.GetString()); 297993571c3cSJonas Devlieghere 298093571c3cSJonas Devlieghere return false; 29812c1f46dcSZachary Turner } 29822c1f46dcSZachary Turner 298363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 2984b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 29852c1f46dcSZachary Turner dest.clear(); 29862c1f46dcSZachary Turner 2987b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 29882c1f46dcSZachary Turner 29892c1f46dcSZachary Turner static char callee_name[] = "get_short_help"; 29902c1f46dcSZachary Turner 29912c1f46dcSZachary Turner if (!cmd_obj_sp) 29922c1f46dcSZachary Turner return false; 29932c1f46dcSZachary Turner 2994b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2995b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 29962c1f46dcSZachary Turner 2997f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 29982c1f46dcSZachary Turner return false; 29992c1f46dcSZachary Turner 3000b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3001b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30022c1f46dcSZachary Turner 30032c1f46dcSZachary Turner if (PyErr_Occurred()) 30042c1f46dcSZachary Turner PyErr_Clear(); 30052c1f46dcSZachary Turner 3006f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 30072c1f46dcSZachary Turner return false; 30082c1f46dcSZachary Turner 3009b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30102c1f46dcSZachary Turner if (PyErr_Occurred()) 30112c1f46dcSZachary Turner PyErr_Clear(); 30122c1f46dcSZachary Turner return false; 30132c1f46dcSZachary Turner } 30142c1f46dcSZachary Turner 30152c1f46dcSZachary Turner if (PyErr_Occurred()) 30162c1f46dcSZachary Turner PyErr_Clear(); 30172c1f46dcSZachary Turner 301893571c3cSJonas Devlieghere // Right now we know this function exists and is callable. 3019b9c1b51eSKate Stone PythonObject py_return( 3020b9c1b51eSKate Stone PyRefType::Owned, 3021b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 30222c1f46dcSZachary Turner 302393571c3cSJonas Devlieghere // If it fails, print the error but otherwise go on. 3024b9c1b51eSKate Stone if (PyErr_Occurred()) { 30252c1f46dcSZachary Turner PyErr_Print(); 30262c1f46dcSZachary Turner PyErr_Clear(); 30272c1f46dcSZachary Turner } 30282c1f46dcSZachary Turner 3029b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3030f8b22f8fSZachary Turner PythonString py_string(PyRefType::Borrowed, py_return.get()); 303122c8efcdSZachary Turner llvm::StringRef return_data(py_string.GetString()); 303222c8efcdSZachary Turner dest.assign(return_data.data(), return_data.size()); 303393571c3cSJonas Devlieghere return true; 30342c1f46dcSZachary Turner } 303593571c3cSJonas Devlieghere 303693571c3cSJonas Devlieghere return false; 30372c1f46dcSZachary Turner } 30382c1f46dcSZachary Turner 303963dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 3040b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp) { 30412c1f46dcSZachary Turner uint32_t result = 0; 30422c1f46dcSZachary Turner 3043b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30442c1f46dcSZachary Turner 30452c1f46dcSZachary Turner static char callee_name[] = "get_flags"; 30462c1f46dcSZachary Turner 30472c1f46dcSZachary Turner if (!cmd_obj_sp) 30482c1f46dcSZachary Turner return result; 30492c1f46dcSZachary Turner 3050b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3051b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 30522c1f46dcSZachary Turner 3053f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 30542c1f46dcSZachary Turner return result; 30552c1f46dcSZachary Turner 3056b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3057b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 30582c1f46dcSZachary Turner 30592c1f46dcSZachary Turner if (PyErr_Occurred()) 30602c1f46dcSZachary Turner PyErr_Clear(); 30612c1f46dcSZachary Turner 3062f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 30632c1f46dcSZachary Turner return result; 30642c1f46dcSZachary Turner 3065b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 30662c1f46dcSZachary Turner if (PyErr_Occurred()) 30672c1f46dcSZachary Turner PyErr_Clear(); 30682c1f46dcSZachary Turner return result; 30692c1f46dcSZachary Turner } 30702c1f46dcSZachary Turner 30712c1f46dcSZachary Turner if (PyErr_Occurred()) 30722c1f46dcSZachary Turner PyErr_Clear(); 30732c1f46dcSZachary Turner 307452712d3fSLawrence D'Anna long long py_return = unwrapOrSetPythonException( 307552712d3fSLawrence D'Anna As<long long>(implementor.CallMethod(callee_name))); 30762c1f46dcSZachary Turner 30772c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3078b9c1b51eSKate Stone if (PyErr_Occurred()) { 30792c1f46dcSZachary Turner PyErr_Print(); 30802c1f46dcSZachary Turner PyErr_Clear(); 308152712d3fSLawrence D'Anna } else { 308252712d3fSLawrence D'Anna result = py_return; 30832c1f46dcSZachary Turner } 30842c1f46dcSZachary Turner 30852c1f46dcSZachary Turner return result; 30862c1f46dcSZachary Turner } 30872c1f46dcSZachary Turner 308863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 3089b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 30902c1f46dcSZachary Turner bool got_string = false; 30912c1f46dcSZachary Turner dest.clear(); 30922c1f46dcSZachary Turner 3093b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 30942c1f46dcSZachary Turner 30952c1f46dcSZachary Turner static char callee_name[] = "get_long_help"; 30962c1f46dcSZachary Turner 30972c1f46dcSZachary Turner if (!cmd_obj_sp) 30982c1f46dcSZachary Turner return false; 30992c1f46dcSZachary Turner 3100b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3101b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 31022c1f46dcSZachary Turner 3103f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 31042c1f46dcSZachary Turner return false; 31052c1f46dcSZachary Turner 3106b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3107b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 31082c1f46dcSZachary Turner 31092c1f46dcSZachary Turner if (PyErr_Occurred()) 31102c1f46dcSZachary Turner PyErr_Clear(); 31112c1f46dcSZachary Turner 3112f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 31132c1f46dcSZachary Turner return false; 31142c1f46dcSZachary Turner 3115b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 31162c1f46dcSZachary Turner if (PyErr_Occurred()) 31172c1f46dcSZachary Turner PyErr_Clear(); 31182c1f46dcSZachary Turner 31192c1f46dcSZachary Turner return false; 31202c1f46dcSZachary Turner } 31212c1f46dcSZachary Turner 31222c1f46dcSZachary Turner if (PyErr_Occurred()) 31232c1f46dcSZachary Turner PyErr_Clear(); 31242c1f46dcSZachary Turner 31252c1f46dcSZachary Turner // right now we know this function exists and is callable.. 3126b9c1b51eSKate Stone PythonObject py_return( 3127b9c1b51eSKate Stone PyRefType::Owned, 3128b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31292c1f46dcSZachary Turner 31302c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3131b9c1b51eSKate Stone if (PyErr_Occurred()) { 31322c1f46dcSZachary Turner PyErr_Print(); 31332c1f46dcSZachary Turner PyErr_Clear(); 31342c1f46dcSZachary Turner } 31352c1f46dcSZachary Turner 3136b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3137f8b22f8fSZachary Turner PythonString str(PyRefType::Borrowed, py_return.get()); 313822c8efcdSZachary Turner llvm::StringRef str_data(str.GetString()); 313922c8efcdSZachary Turner dest.assign(str_data.data(), str_data.size()); 31402c1f46dcSZachary Turner got_string = true; 31412c1f46dcSZachary Turner } 31422c1f46dcSZachary Turner 31432c1f46dcSZachary Turner return got_string; 31442c1f46dcSZachary Turner } 31452c1f46dcSZachary Turner 31462c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker> 314763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 3148b9c1b51eSKate Stone std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 3149b9c1b51eSKate Stone this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 31502c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession)); 31512c1f46dcSZachary Turner return py_lock; 31522c1f46dcSZachary Turner } 31532c1f46dcSZachary Turner 3154049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 3155049ae930SJonas Devlieghere namespace { 3156049ae930SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores 3157049ae930SJonas Devlieghere /// it at the end of the current scope. 3158049ae930SJonas Devlieghere struct RestoreSignalHandlerScope { 3159049ae930SJonas Devlieghere /// The signal handler. 3160049ae930SJonas Devlieghere struct sigaction m_prev_handler; 3161049ae930SJonas Devlieghere int m_signal_code; 3162049ae930SJonas Devlieghere RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) { 3163049ae930SJonas Devlieghere // Initialize sigaction to their default state. 3164049ae930SJonas Devlieghere std::memset(&m_prev_handler, 0, sizeof(m_prev_handler)); 3165049ae930SJonas Devlieghere // Don't install a new handler, just read back the old one. 3166049ae930SJonas Devlieghere struct sigaction *new_handler = nullptr; 3167049ae930SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler); 3168049ae930SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to read handler"); 3169049ae930SJonas Devlieghere } 3170049ae930SJonas Devlieghere ~RestoreSignalHandlerScope() { 3171049ae930SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr); 3172049ae930SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to restore old handler"); 3173049ae930SJonas Devlieghere } 3174049ae930SJonas Devlieghere }; 3175049ae930SJonas Devlieghere } // namespace 3176049ae930SJonas Devlieghere #endif 3177049ae930SJonas Devlieghere 317863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() { 317915d1b4e2SEnrico Granata if (g_initialized) 318015d1b4e2SEnrico Granata return; 318115d1b4e2SEnrico Granata 31822c1f46dcSZachary Turner g_initialized = true; 31832c1f46dcSZachary Turner 31845c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 31852c1f46dcSZachary Turner 3186b9c1b51eSKate Stone // RAII-based initialization which correctly handles multiple-initialization, 318705097246SAdrian Prantl // version- specific differences among Python 2 and Python 3, and saving and 318805097246SAdrian Prantl // restoring various other pieces of state that can get mucked with during 318905097246SAdrian Prantl // initialization. 3190079fe48aSZachary Turner InitializePythonRAII initialize_guard; 31912c1f46dcSZachary Turner 319205495c5dSJonas Devlieghere LLDBSwigPyInit(); 31932c1f46dcSZachary Turner 3194b9c1b51eSKate Stone // Update the path python uses to search for modules to include the current 3195b9c1b51eSKate Stone // directory. 31962c1f46dcSZachary Turner 31972c1f46dcSZachary Turner PyRun_SimpleString("import sys"); 31982c1f46dcSZachary Turner AddToSysPath(AddLocation::End, "."); 31992c1f46dcSZachary Turner 3200b9c1b51eSKate Stone // Don't denormalize paths when calling file_spec.GetPath(). On platforms 320105097246SAdrian Prantl // that use a backslash as the path separator, this will result in executing 320205097246SAdrian Prantl // python code containing paths with unescaped backslashes. But Python also 320305097246SAdrian Prantl // accepts forward slashes, so to make life easier we just use that. 32042df331b0SPavel Labath if (FileSpec file_spec = GetPythonDir()) 32052c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 320660f028ffSPavel Labath if (FileSpec file_spec = HostInfo::GetShlibDir()) 32072c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 32082c1f46dcSZachary Turner 3209b9c1b51eSKate Stone PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 3210b9c1b51eSKate Stone "lldb.embedded_interpreter; from " 3211b9c1b51eSKate Stone "lldb.embedded_interpreter import run_python_interpreter; " 3212b9c1b51eSKate Stone "from lldb.embedded_interpreter import run_one_line"); 3213049ae930SJonas Devlieghere 3214049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT 3215049ae930SJonas Devlieghere // Python will not just overwrite its internal SIGINT handler but also the 3216049ae930SJonas Devlieghere // one from the process. Backup the current SIGINT handler to prevent that 3217049ae930SJonas Devlieghere // Python deletes it. 3218049ae930SJonas Devlieghere RestoreSignalHandlerScope save_sigint(SIGINT); 3219049ae930SJonas Devlieghere 3220049ae930SJonas Devlieghere // Setup a default SIGINT signal handler that works the same way as the 3221049ae930SJonas Devlieghere // normal Python REPL signal handler which raises a KeyboardInterrupt. 3222049ae930SJonas Devlieghere // Also make sure to not pollute the user's REPL with the signal module nor 3223049ae930SJonas Devlieghere // our utility function. 3224049ae930SJonas Devlieghere PyRun_SimpleString("def lldb_setup_sigint_handler():\n" 3225049ae930SJonas Devlieghere " import signal;\n" 3226049ae930SJonas Devlieghere " def signal_handler(sig, frame):\n" 3227049ae930SJonas Devlieghere " raise KeyboardInterrupt()\n" 3228049ae930SJonas Devlieghere " signal.signal(signal.SIGINT, signal_handler);\n" 3229049ae930SJonas Devlieghere "lldb_setup_sigint_handler();\n" 3230049ae930SJonas Devlieghere "del lldb_setup_sigint_handler\n"); 3231049ae930SJonas Devlieghere #endif 32322c1f46dcSZachary Turner } 32332c1f46dcSZachary Turner 323463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 3235b9c1b51eSKate Stone std::string path) { 32362c1f46dcSZachary Turner std::string path_copy; 32372c1f46dcSZachary Turner 32382c1f46dcSZachary Turner std::string statement; 3239b9c1b51eSKate Stone if (location == AddLocation::Beginning) { 32402c1f46dcSZachary Turner statement.assign("sys.path.insert(0,\""); 32412c1f46dcSZachary Turner statement.append(path); 32422c1f46dcSZachary Turner statement.append("\")"); 3243b9c1b51eSKate Stone } else { 32442c1f46dcSZachary Turner statement.assign("sys.path.append(\""); 32452c1f46dcSZachary Turner statement.append(path); 32462c1f46dcSZachary Turner statement.append("\")"); 32472c1f46dcSZachary Turner } 32482c1f46dcSZachary Turner PyRun_SimpleString(statement.c_str()); 32492c1f46dcSZachary Turner } 32502c1f46dcSZachary Turner 3251bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical 3252bcadb5a3SPavel Labath // place to call it). Calling Py_Finalize here causes test suite runs to seg 3253bcadb5a3SPavel Labath // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 3254bcadb5a3SPavel Labath // be called 'at_exit'. When the test suite Python harness finishes up, it 3255bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions. 3256bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 3257bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls 325863dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 325963dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results 326063dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting 326163dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize 3262bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway 3263bcadb5a3SPavel Labath // when the process exits). 3264bcadb5a3SPavel Labath // 326563dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 3266d68983e3SPavel Labath 32674e26cf2cSJonas Devlieghere #endif 3268