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"
401755f5b1SJonas Devlieghere #include "lldb/Utility/Instrumentation.h"
41c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
4238d0632eSPavel Labath #include "lldb/Utility/Timer.h"
4322c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
44b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
45d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
467d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
472fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
482c1f46dcSZachary Turner
4976e47d48SRaphael Isemann #include <cstdio>
5076e47d48SRaphael Isemann #include <cstdlib>
519a6c7572SJonas Devlieghere #include <memory>
529a6c7572SJonas Devlieghere #include <mutex>
539a6c7572SJonas Devlieghere #include <string>
549a6c7572SJonas Devlieghere
552c1f46dcSZachary Turner using namespace lldb;
562c1f46dcSZachary Turner using namespace lldb_private;
57722b6189SLawrence D'Anna using namespace lldb_private::python;
5804edd189SLawrence D'Anna using llvm::Expected;
592c1f46dcSZachary Turner
60bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
61fbb4d1e4SJonas Devlieghere
62b01b1087SJonas Devlieghere // Defined in the SWIG source file
63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
64b01b1087SJonas Devlieghere
65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
66b01b1087SJonas Devlieghere
67049ae930SJonas Devlieghere #if defined(_WIN32)
68049ae930SJonas Devlieghere // Don't mess with the signal handlers on Windows.
69049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT 0
70049ae930SJonas Devlieghere #else
71049ae930SJonas Devlieghere // PyErr_SetInterrupt was introduced in 3.2.
72049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT \
73049ae930SJonas Devlieghere (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
74049ae930SJonas Devlieghere #endif
75b01b1087SJonas Devlieghere
GetPythonInterpreter(Debugger & debugger)76d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
77d055e3a0SPedro Tammela ScriptInterpreter *script_interpreter =
78d055e3a0SPedro Tammela debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
79d055e3a0SPedro Tammela return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
80d055e3a0SPedro Tammela }
81d055e3a0SPedro Tammela
82b9c1b51eSKate Stone namespace {
8322c8efcdSZachary Turner
8405097246SAdrian Prantl // Initializing Python is not a straightforward process. We cannot control
8505097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
8605097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
8705097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
8805097246SAdrian Prantl // across our initialization. We do this by using an RAII pattern where we
8905097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
90b9c1b51eSKate Stone struct InitializePythonRAII {
91079fe48aSZachary Turner public:
InitializePythonRAII__anonfc67c2220111::InitializePythonRAII929494c510SJonas Devlieghere InitializePythonRAII() {
93079fe48aSZachary Turner InitializePythonHome();
94079fe48aSZachary Turner
959357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
969357b5d0Sserge-sans-paille // Python's readline is incompatible with libedit being linked into lldb.
979357b5d0Sserge-sans-paille // Provide a patched version local to the embedded interpreter.
989357b5d0Sserge-sans-paille bool ReadlinePatched = false;
999357b5d0Sserge-sans-paille for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
1009357b5d0Sserge-sans-paille if (strcmp(p->name, "readline") == 0) {
1019357b5d0Sserge-sans-paille p->initfunc = initlldb_readline;
1029357b5d0Sserge-sans-paille break;
1039357b5d0Sserge-sans-paille }
1049357b5d0Sserge-sans-paille }
1059357b5d0Sserge-sans-paille if (!ReadlinePatched) {
1069357b5d0Sserge-sans-paille PyImport_AppendInittab("readline", initlldb_readline);
1079357b5d0Sserge-sans-paille ReadlinePatched = true;
1089357b5d0Sserge-sans-paille }
1099357b5d0Sserge-sans-paille #endif
1109357b5d0Sserge-sans-paille
11174587a0eSVadim Chugunov // Register _lldb as a built-in module.
11205495c5dSJonas Devlieghere PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
11374587a0eSVadim Chugunov
114079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
115079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
116079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
117079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
118079fe48aSZachary Turner Py_InitializeEx(0);
119079fe48aSZachary Turner InitializeThreadsPrivate();
120079fe48aSZachary Turner #else
121079fe48aSZachary Turner InitializeThreadsPrivate();
122079fe48aSZachary Turner Py_InitializeEx(0);
123079fe48aSZachary Turner #endif
124079fe48aSZachary Turner }
125079fe48aSZachary Turner
~InitializePythonRAII__anonfc67c2220111::InitializePythonRAII126b9c1b51eSKate Stone ~InitializePythonRAII() {
127b9c1b51eSKate Stone if (m_was_already_initialized) {
128a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
1293b7e1981SPavel Labath LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1301b6700efSTatyana Krasnukha m_gil_state == PyGILState_UNLOCKED ? "un" : "");
131079fe48aSZachary Turner PyGILState_Release(m_gil_state);
132b9c1b51eSKate Stone } else {
133079fe48aSZachary Turner // We initialized the threads in this function, just unlock the GIL.
134079fe48aSZachary Turner PyEval_SaveThread();
135079fe48aSZachary Turner }
136079fe48aSZachary Turner }
137079fe48aSZachary Turner
138079fe48aSZachary Turner private:
InitializePythonHome__anonfc67c2220111::InitializePythonRAII139b9c1b51eSKate Stone void InitializePythonHome() {
1403ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
1413ec3f62fSHaibo Huang typedef wchar_t *str_type;
1423ec3f62fSHaibo Huang static str_type g_python_home = []() -> str_type {
1433ec3f62fSHaibo Huang const char *lldb_python_home = LLDB_PYTHON_HOME;
1443ec3f62fSHaibo Huang const char *absolute_python_home = nullptr;
1453ec3f62fSHaibo Huang llvm::SmallString<64> path;
1463ec3f62fSHaibo Huang if (llvm::sys::path::is_absolute(lldb_python_home)) {
1473ec3f62fSHaibo Huang absolute_python_home = lldb_python_home;
1483ec3f62fSHaibo Huang } else {
1493ec3f62fSHaibo Huang FileSpec spec = HostInfo::GetShlibDir();
1503ec3f62fSHaibo Huang if (!spec)
1513ec3f62fSHaibo Huang return nullptr;
1523ec3f62fSHaibo Huang spec.GetPath(path);
1533ec3f62fSHaibo Huang llvm::sys::path::append(path, lldb_python_home);
1543ec3f62fSHaibo Huang absolute_python_home = path.c_str();
1553ec3f62fSHaibo Huang }
15622c8efcdSZachary Turner size_t size = 0;
1573ec3f62fSHaibo Huang return Py_DecodeLocale(absolute_python_home, &size);
1583ec3f62fSHaibo Huang }();
1593ec3f62fSHaibo Huang if (g_python_home != nullptr) {
160079fe48aSZachary Turner Py_SetPythonHome(g_python_home);
1613ec3f62fSHaibo Huang }
162386f00dbSDavide Italiano #endif
16322c8efcdSZachary Turner }
16422c8efcdSZachary Turner
InitializeThreadsPrivate__anonfc67c2220111::InitializePythonRAII165b9c1b51eSKate Stone void InitializeThreadsPrivate() {
1661b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1671b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
1681b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
1691b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
1701b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1711b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1721b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
1731b6700efSTatyana Krasnukha // The only case we should go further and acquire the GIL: it is unlocked.
1741b6700efSTatyana Krasnukha if (PyGILState_Check())
1751b6700efSTatyana Krasnukha return;
1761b6700efSTatyana Krasnukha #endif
1771b6700efSTatyana Krasnukha
178b9c1b51eSKate Stone if (PyEval_ThreadsInitialized()) {
179a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
180079fe48aSZachary Turner
181079fe48aSZachary Turner m_was_already_initialized = true;
182079fe48aSZachary Turner m_gil_state = PyGILState_Ensure();
1833b7e1981SPavel Labath LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
184079fe48aSZachary Turner m_gil_state == PyGILState_UNLOCKED ? "un" : "");
185079fe48aSZachary Turner return;
186079fe48aSZachary Turner }
187079fe48aSZachary Turner
188079fe48aSZachary Turner // InitThreads acquires the GIL if it hasn't been called before.
189079fe48aSZachary Turner PyEval_InitThreads();
190079fe48aSZachary Turner }
191079fe48aSZachary Turner
1929494c510SJonas Devlieghere PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
1939494c510SJonas Devlieghere bool m_was_already_initialized = false;
194079fe48aSZachary Turner };
195eb5c0ea6SJonas Devlieghere
196eb5c0ea6SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
197eb5c0ea6SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores
198eb5c0ea6SJonas Devlieghere /// it at the end of the current scope.
199eb5c0ea6SJonas Devlieghere struct RestoreSignalHandlerScope {
200eb5c0ea6SJonas Devlieghere /// The signal handler.
201eb5c0ea6SJonas Devlieghere struct sigaction m_prev_handler;
202eb5c0ea6SJonas Devlieghere int m_signal_code;
RestoreSignalHandlerScope__anonfc67c2220111::RestoreSignalHandlerScope203eb5c0ea6SJonas Devlieghere RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
204eb5c0ea6SJonas Devlieghere // Initialize sigaction to their default state.
205eb5c0ea6SJonas Devlieghere std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
206eb5c0ea6SJonas Devlieghere // Don't install a new handler, just read back the old one.
207eb5c0ea6SJonas Devlieghere struct sigaction *new_handler = nullptr;
208eb5c0ea6SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
209eb5c0ea6SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to read handler");
210eb5c0ea6SJonas Devlieghere }
~RestoreSignalHandlerScope__anonfc67c2220111::RestoreSignalHandlerScope211eb5c0ea6SJonas Devlieghere ~RestoreSignalHandlerScope() {
212eb5c0ea6SJonas Devlieghere int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
213eb5c0ea6SJonas Devlieghere lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
214eb5c0ea6SJonas Devlieghere }
215eb5c0ea6SJonas Devlieghere };
216eb5c0ea6SJonas Devlieghere #endif
21763dd5d25SJonas Devlieghere } // namespace
2182c1f46dcSZachary Turner
ComputePythonDirForApple(llvm::SmallVectorImpl<char> & path)2192df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
2202df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) {
2212df331b0SPavel Labath auto style = llvm::sys::path::Style::posix;
2222df331b0SPavel Labath
2232df331b0SPavel Labath llvm::StringRef path_ref(path.begin(), path.size());
2242df331b0SPavel Labath auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2252df331b0SPavel Labath auto rend = llvm::sys::path::rend(path_ref);
2262df331b0SPavel Labath auto framework = std::find(rbegin, rend, "LLDB.framework");
2272df331b0SPavel Labath if (framework == rend) {
22861f471a7SHaibo Huang ComputePythonDir(path);
2292df331b0SPavel Labath return;
2302df331b0SPavel Labath }
2312df331b0SPavel Labath path.resize(framework - rend);
2322df331b0SPavel Labath llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2332df331b0SPavel Labath }
2342df331b0SPavel Labath
ComputePythonDir(llvm::SmallVectorImpl<char> & path)23561f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
2362df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) {
2372df331b0SPavel Labath // Build the path by backing out of the lib dir, then building with whatever
2382df331b0SPavel Labath // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
23961f471a7SHaibo Huang // x86_64, or bin on Windows).
24061f471a7SHaibo Huang llvm::sys::path::remove_filename(path);
24161f471a7SHaibo Huang llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2420016b450SHaibo Huang
2430016b450SHaibo Huang #if defined(_WIN32)
244*1b4b12a3SNico Weber // This will be injected directly through FileSpec.GetDirectory().SetString(),
2450016b450SHaibo Huang // so we need to normalize manually.
2460016b450SHaibo Huang std::replace(path.begin(), path.end(), '\\', '/');
2470016b450SHaibo Huang #endif
2482df331b0SPavel Labath }
2492df331b0SPavel Labath
GetPythonDir()2502df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
2512df331b0SPavel Labath static FileSpec g_spec = []() {
2522df331b0SPavel Labath FileSpec spec = HostInfo::GetShlibDir();
2532df331b0SPavel Labath if (!spec)
2542df331b0SPavel Labath return FileSpec();
2552df331b0SPavel Labath llvm::SmallString<64> path;
2562df331b0SPavel Labath spec.GetPath(path);
2572df331b0SPavel Labath
2582df331b0SPavel Labath #if defined(__APPLE__)
2592df331b0SPavel Labath ComputePythonDirForApple(path);
2602df331b0SPavel Labath #else
26161f471a7SHaibo Huang ComputePythonDir(path);
2622df331b0SPavel Labath #endif
263*1b4b12a3SNico Weber spec.GetDirectory().SetString(path);
2642df331b0SPavel Labath return spec;
2652df331b0SPavel Labath }();
2662df331b0SPavel Labath return g_spec;
2672df331b0SPavel Labath }
2682df331b0SPavel Labath
2694c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"(
2704c2cf3a3SLawrence D'Anna import os
2714c2cf3a3SLawrence D'Anna import sys
2724c2cf3a3SLawrence D'Anna
2734c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path):
2744c2cf3a3SLawrence D'Anna info = {
2754c2cf3a3SLawrence D'Anna "lldb-pythonpath": lldb_python_dir,
2764c2cf3a3SLawrence D'Anna "language": "python",
2774c2cf3a3SLawrence D'Anna "prefix": sys.prefix,
2784c2cf3a3SLawrence D'Anna "executable": os.path.join(sys.prefix, python_exe_relative_path)
2794c2cf3a3SLawrence D'Anna }
2804c2cf3a3SLawrence D'Anna return info
2814c2cf3a3SLawrence D'Anna )";
2824c2cf3a3SLawrence D'Anna
2834c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
2844c2cf3a3SLawrence D'Anna
GetInterpreterInfo()285bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
286bbef51ebSLawrence D'Anna GIL gil;
287bbef51ebSLawrence D'Anna FileSpec python_dir_spec = GetPythonDir();
288bbef51ebSLawrence D'Anna if (!python_dir_spec)
289bbef51ebSLawrence D'Anna return nullptr;
2904c2cf3a3SLawrence D'Anna PythonScript get_info(GetInterpreterInfoScript);
2914c2cf3a3SLawrence D'Anna auto info_json = unwrapIgnoringErrors(
2924c2cf3a3SLawrence D'Anna As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
2934c2cf3a3SLawrence D'Anna PythonString(python_exe_relative_path))));
294bbef51ebSLawrence D'Anna if (!info_json)
295bbef51ebSLawrence D'Anna return nullptr;
296bbef51ebSLawrence D'Anna return info_json.CreateStructuredDictionary();
297bbef51ebSLawrence D'Anna }
298bbef51ebSLawrence D'Anna
SharedLibraryDirectoryHelper(FileSpec & this_file)299004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
300004a264fSPavel Labath FileSpec &this_file) {
301004a264fSPavel Labath // When we're loaded from python, this_file will point to the file inside the
302004a264fSPavel Labath // python package directory. Replace it with the one in the lib directory.
303004a264fSPavel Labath #ifdef _WIN32
304004a264fSPavel Labath // On windows, we need to manually back out of the python tree, and go into
305004a264fSPavel Labath // the bin directory. This is pretty much the inverse of what ComputePythonDir
306004a264fSPavel Labath // does.
307004a264fSPavel Labath if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
308004a264fSPavel Labath this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
309004a264fSPavel Labath this_file.RemoveLastPathComponent(); // lldb
3102e826088SPavel Labath llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
3112e826088SPavel Labath for (auto it = llvm::sys::path::begin(libdir),
3122e826088SPavel Labath end = llvm::sys::path::end(libdir);
313004a264fSPavel Labath it != end; ++it)
314004a264fSPavel Labath this_file.RemoveLastPathComponent();
315004a264fSPavel Labath this_file.AppendPathComponent("bin");
316004a264fSPavel Labath this_file.AppendPathComponent("liblldb.dll");
317004a264fSPavel Labath }
318004a264fSPavel Labath #else
319004a264fSPavel Labath // The python file is a symlink, so we can find the real library by resolving
320004a264fSPavel Labath // it. We can do this unconditionally.
321004a264fSPavel Labath FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
322004a264fSPavel Labath #endif
323004a264fSPavel Labath }
324004a264fSPavel Labath
GetPluginDescriptionStatic()3255f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
32663dd5d25SJonas Devlieghere return "Embedded Python interpreter";
32763dd5d25SJonas Devlieghere }
32863dd5d25SJonas Devlieghere
Initialize()32963dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
33063dd5d25SJonas Devlieghere static llvm::once_flag g_once_flag;
33163dd5d25SJonas Devlieghere llvm::call_once(g_once_flag, []() {
33263dd5d25SJonas Devlieghere PluginManager::RegisterPlugin(GetPluginNameStatic(),
33363dd5d25SJonas Devlieghere GetPluginDescriptionStatic(),
33463dd5d25SJonas Devlieghere lldb::eScriptLanguagePython,
33563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance);
336eb5c0ea6SJonas Devlieghere ScriptInterpreterPythonImpl::Initialize();
33763dd5d25SJonas Devlieghere });
33863dd5d25SJonas Devlieghere }
33963dd5d25SJonas Devlieghere
Terminate()34063dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
34163dd5d25SJonas Devlieghere
Locker(ScriptInterpreterPythonImpl * py_interpreter,uint16_t on_entry,uint16_t on_leave,FileSP in,FileSP out,FileSP err)34263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
34363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
344b07823f3SLawrence D'Anna uint16_t on_leave, FileSP in, FileSP out, FileSP err)
34563dd5d25SJonas Devlieghere : ScriptInterpreterLocker(),
34663dd5d25SJonas Devlieghere m_teardown_session((on_leave & TearDownSession) == TearDownSession),
34763dd5d25SJonas Devlieghere m_python_interpreter(py_interpreter) {
34863dd5d25SJonas Devlieghere DoAcquireLock();
34963dd5d25SJonas Devlieghere if ((on_entry & InitSession) == InitSession) {
35063dd5d25SJonas Devlieghere if (!DoInitSession(on_entry, in, out, err)) {
35163dd5d25SJonas Devlieghere // Don't teardown the session if we didn't init it.
35263dd5d25SJonas Devlieghere m_teardown_session = false;
35363dd5d25SJonas Devlieghere }
35463dd5d25SJonas Devlieghere }
35563dd5d25SJonas Devlieghere }
35663dd5d25SJonas Devlieghere
DoAcquireLock()35763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
358a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
35963dd5d25SJonas Devlieghere m_GILState = PyGILState_Ensure();
36063dd5d25SJonas Devlieghere LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
36163dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : "");
36263dd5d25SJonas Devlieghere
36363dd5d25SJonas Devlieghere // we need to save the thread state when we first start the command because
36463dd5d25SJonas Devlieghere // we might decide to interrupt it while some action is taking place outside
36563dd5d25SJonas Devlieghere // of Python (e.g. printing to screen, waiting for the network, ...) in that
36663dd5d25SJonas Devlieghere // case, _PyThreadState_Current will be NULL - and we would be unable to set
36763dd5d25SJonas Devlieghere // the asynchronous exception - not a desirable situation
36863dd5d25SJonas Devlieghere m_python_interpreter->SetThreadState(PyThreadState_Get());
36963dd5d25SJonas Devlieghere m_python_interpreter->IncrementLockCount();
37063dd5d25SJonas Devlieghere return true;
37163dd5d25SJonas Devlieghere }
37263dd5d25SJonas Devlieghere
DoInitSession(uint16_t on_entry_flags,FileSP in,FileSP out,FileSP err)37363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
374b07823f3SLawrence D'Anna FileSP in, FileSP out,
375b07823f3SLawrence D'Anna FileSP err) {
37663dd5d25SJonas Devlieghere if (!m_python_interpreter)
37763dd5d25SJonas Devlieghere return false;
37863dd5d25SJonas Devlieghere return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
37963dd5d25SJonas Devlieghere }
38063dd5d25SJonas Devlieghere
DoFreeLock()38163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
382a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
38363dd5d25SJonas Devlieghere LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
38463dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : "");
38563dd5d25SJonas Devlieghere PyGILState_Release(m_GILState);
38663dd5d25SJonas Devlieghere m_python_interpreter->DecrementLockCount();
38763dd5d25SJonas Devlieghere return true;
38863dd5d25SJonas Devlieghere }
38963dd5d25SJonas Devlieghere
DoTearDownSession()39063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
39163dd5d25SJonas Devlieghere if (!m_python_interpreter)
39263dd5d25SJonas Devlieghere return false;
39363dd5d25SJonas Devlieghere m_python_interpreter->LeaveSession();
39463dd5d25SJonas Devlieghere return true;
39563dd5d25SJonas Devlieghere }
39663dd5d25SJonas Devlieghere
~Locker()39763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
39863dd5d25SJonas Devlieghere if (m_teardown_session)
39963dd5d25SJonas Devlieghere DoTearDownSession();
40063dd5d25SJonas Devlieghere DoFreeLock();
40163dd5d25SJonas Devlieghere }
40263dd5d25SJonas Devlieghere
ScriptInterpreterPythonImpl(Debugger & debugger)4038d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4048d1fb843SJonas Devlieghere : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
40563dd5d25SJonas Devlieghere m_saved_stderr(), m_main_module(),
40663dd5d25SJonas Devlieghere m_session_dict(PyInitialValue::Invalid),
40763dd5d25SJonas Devlieghere m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
40863dd5d25SJonas Devlieghere m_run_one_line_str_global(),
4098d1fb843SJonas Devlieghere m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
410ea1752a7SJonas Devlieghere m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
41164ec505dSJonas Devlieghere m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
412ea1752a7SJonas Devlieghere m_command_thread_state(nullptr) {
4131f6a57c1SMed Ismail Bennani m_scripted_process_interface_up =
4141f6a57c1SMed Ismail Bennani std::make_unique<ScriptedProcessPythonInterface>(*this);
4151f6a57c1SMed Ismail Bennani
41663dd5d25SJonas Devlieghere m_dictionary_name.append("_dict");
41763dd5d25SJonas Devlieghere StreamString run_string;
41863dd5d25SJonas Devlieghere run_string.Printf("%s = dict()", m_dictionary_name.c_str());
41963dd5d25SJonas Devlieghere
42063dd5d25SJonas Devlieghere Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
42163dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData());
42263dd5d25SJonas Devlieghere
42363dd5d25SJonas Devlieghere run_string.Clear();
42463dd5d25SJonas Devlieghere run_string.Printf(
42563dd5d25SJonas Devlieghere "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
42663dd5d25SJonas Devlieghere m_dictionary_name.c_str());
42763dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData());
42863dd5d25SJonas Devlieghere
42963dd5d25SJonas Devlieghere // Reloading modules requires a different syntax in Python 2 and Python 3.
43063dd5d25SJonas Devlieghere // This provides a consistent syntax no matter what version of Python.
43163dd5d25SJonas Devlieghere run_string.Clear();
43263dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
43363dd5d25SJonas Devlieghere m_dictionary_name.c_str());
43463dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData());
43563dd5d25SJonas Devlieghere
43663dd5d25SJonas Devlieghere // WARNING: temporary code that loads Cocoa formatters - this should be done
43763dd5d25SJonas Devlieghere // on a per-platform basis rather than loading the whole set and letting the
43863dd5d25SJonas Devlieghere // individual formatter classes exploit APIs to check whether they can/cannot
43963dd5d25SJonas Devlieghere // do their task
44063dd5d25SJonas Devlieghere run_string.Clear();
44163dd5d25SJonas Devlieghere run_string.Printf(
44263dd5d25SJonas Devlieghere "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
44363dd5d25SJonas Devlieghere m_dictionary_name.c_str());
44463dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData());
44563dd5d25SJonas Devlieghere run_string.Clear();
44663dd5d25SJonas Devlieghere
44763dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
44863dd5d25SJonas Devlieghere "lldb.embedded_interpreter import run_python_interpreter; "
44963dd5d25SJonas Devlieghere "from lldb.embedded_interpreter import run_one_line')",
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, 'lldb.debugger_unique_id = %" PRIu64
45563dd5d25SJonas Devlieghere "; pydoc.pager = pydoc.plainpager')",
4568d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID());
45763dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData());
45863dd5d25SJonas Devlieghere }
45963dd5d25SJonas Devlieghere
~ScriptInterpreterPythonImpl()46063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
46163dd5d25SJonas Devlieghere // the session dictionary may hold objects with complex state which means
46263dd5d25SJonas Devlieghere // that they may need to be torn down with some level of smarts and that, in
46363dd5d25SJonas Devlieghere // turn, requires a valid thread state force Python to procure itself such a
46463dd5d25SJonas Devlieghere // thread state, nuke the session dictionary and then release it for others
46563dd5d25SJonas Devlieghere // to use and proceed with the rest of the shutdown
46663dd5d25SJonas Devlieghere auto gil_state = PyGILState_Ensure();
46763dd5d25SJonas Devlieghere m_session_dict.Reset();
46863dd5d25SJonas Devlieghere PyGILState_Release(gil_state);
46963dd5d25SJonas Devlieghere }
47063dd5d25SJonas Devlieghere
IOHandlerActivated(IOHandler & io_handler,bool interactive)47163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
47263dd5d25SJonas Devlieghere bool interactive) {
4732c1f46dcSZachary Turner const char *instructions = nullptr;
4742c1f46dcSZachary Turner
475b9c1b51eSKate Stone switch (m_active_io_handler) {
4762c1f46dcSZachary Turner case eIOHandlerNone:
4772c1f46dcSZachary Turner break;
4782c1f46dcSZachary Turner case eIOHandlerBreakpoint:
4792c1f46dcSZachary Turner instructions = R"(Enter your Python command(s). Type 'DONE' to end.
4802c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
4812c1f46dcSZachary Turner """frame: the lldb.SBFrame for the location at which you stopped
4822c1f46dcSZachary Turner bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
4832c1f46dcSZachary Turner internal_dict: an LLDB support object not to be used"""
4842c1f46dcSZachary Turner )";
4852c1f46dcSZachary Turner break;
4862c1f46dcSZachary Turner case eIOHandlerWatchpoint:
4872c1f46dcSZachary Turner instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
4882c1f46dcSZachary Turner break;
4892c1f46dcSZachary Turner }
4902c1f46dcSZachary Turner
491b9c1b51eSKate Stone if (instructions) {
4927ca15ba7SLawrence D'Anna StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4930affb582SDave Lee if (output_sp && interactive) {
4942c1f46dcSZachary Turner output_sp->PutCString(instructions);
4952c1f46dcSZachary Turner output_sp->Flush();
4962c1f46dcSZachary Turner }
4972c1f46dcSZachary Turner }
4982c1f46dcSZachary Turner }
4992c1f46dcSZachary Turner
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)50063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
501b9c1b51eSKate Stone std::string &data) {
5022c1f46dcSZachary Turner io_handler.SetIsDone(true);
5038d1fb843SJonas Devlieghere bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5042c1f46dcSZachary Turner
505b9c1b51eSKate Stone switch (m_active_io_handler) {
5062c1f46dcSZachary Turner case eIOHandlerNone:
5072c1f46dcSZachary Turner break;
508b9c1b51eSKate Stone case eIOHandlerBreakpoint: {
509cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
510cfb96d84SJim Ingham (std::vector<std::reference_wrapper<BreakpointOptions>> *)
511cfb96d84SJim Ingham io_handler.GetUserData();
512cfb96d84SJim Ingham for (BreakpointOptions &bp_options : *bp_options_vec) {
5132c1f46dcSZachary Turner
514a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<CommandDataPython>();
515d5b44036SJonas Devlieghere if (!data_up)
5164e4fbe82SZachary Turner break;
517d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data);
5182c1f46dcSZachary Turner
519738af7a6SJim Ingham StructuredData::ObjectSP empty_args_sp;
520d5b44036SJonas Devlieghere if (GenerateBreakpointCommandCallbackData(data_up->user_source,
521738af7a6SJim Ingham data_up->script_source,
522738af7a6SJim Ingham false)
523b9c1b51eSKate Stone .Success()) {
5244e4fbe82SZachary Turner auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
525d5b44036SJonas Devlieghere std::move(data_up));
526cfb96d84SJim Ingham bp_options.SetCallback(
52763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
528b9c1b51eSKate Stone } else if (!batch_mode) {
5297ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
530b9c1b51eSKate Stone if (error_sp) {
5312c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n");
5322c1f46dcSZachary Turner error_sp->Flush();
5332c1f46dcSZachary Turner }
5342c1f46dcSZachary Turner }
5352c1f46dcSZachary Turner }
5362c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone;
537b9c1b51eSKate Stone } break;
538b9c1b51eSKate Stone case eIOHandlerWatchpoint: {
539b9c1b51eSKate Stone WatchpointOptions *wp_options =
540b9c1b51eSKate Stone (WatchpointOptions *)io_handler.GetUserData();
541a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>();
542d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data);
5432c1f46dcSZachary Turner
544d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source,
545d5b44036SJonas Devlieghere data_up->script_source)) {
5464e4fbe82SZachary Turner auto baton_sp =
547d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
548b9c1b51eSKate Stone wp_options->SetCallback(
54963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
550b9c1b51eSKate Stone } else if (!batch_mode) {
5517ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
552b9c1b51eSKate Stone if (error_sp) {
5532c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n");
5542c1f46dcSZachary Turner error_sp->Flush();
5552c1f46dcSZachary Turner }
5562c1f46dcSZachary Turner }
5572c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone;
558b9c1b51eSKate Stone } break;
5592c1f46dcSZachary Turner }
5602c1f46dcSZachary Turner }
5612c1f46dcSZachary Turner
56263dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)5638d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5648d1fb843SJonas Devlieghere return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
56563dd5d25SJonas Devlieghere }
5662c1f46dcSZachary Turner
LeaveSession()56763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
568a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
5692c1f46dcSZachary Turner if (log)
57063dd5d25SJonas Devlieghere log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5712c1f46dcSZachary Turner
57220b52c33SJonas Devlieghere // Unset the LLDB global variables.
57320b52c33SJonas Devlieghere PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
57420b52c33SJonas Devlieghere "= None; lldb.thread = None; lldb.frame = None");
57520b52c33SJonas Devlieghere
57605097246SAdrian Prantl // checking that we have a valid thread state - since we use our own
57705097246SAdrian Prantl // threading and locking in some (rare) cases during cleanup Python may end
57805097246SAdrian Prantl // up believing we have no thread state and PyImport_AddModule will crash if
57905097246SAdrian Prantl // that is the case - since that seems to only happen when destroying the
58005097246SAdrian Prantl // SBDebugger, we can make do without clearing up stdout and stderr
5812c1f46dcSZachary Turner
5822c1f46dcSZachary Turner // rdar://problem/11292882
583b9c1b51eSKate Stone // When the current thread state is NULL, PyThreadState_Get() issues a fatal
584b9c1b51eSKate Stone // error.
585b9c1b51eSKate Stone if (PyThreadState_GetDict()) {
5862c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary();
587b9c1b51eSKate Stone if (sys_module_dict.IsValid()) {
588b9c1b51eSKate Stone if (m_saved_stdin.IsValid()) {
589f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
5902c1f46dcSZachary Turner m_saved_stdin.Reset();
5912c1f46dcSZachary Turner }
592b9c1b51eSKate Stone if (m_saved_stdout.IsValid()) {
593f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
5942c1f46dcSZachary Turner m_saved_stdout.Reset();
5952c1f46dcSZachary Turner }
596b9c1b51eSKate Stone if (m_saved_stderr.IsValid()) {
597f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
5982c1f46dcSZachary Turner m_saved_stderr.Reset();
5992c1f46dcSZachary Turner }
6002c1f46dcSZachary Turner }
6012c1f46dcSZachary Turner }
6022c1f46dcSZachary Turner
6032c1f46dcSZachary Turner m_session_is_active = false;
6042c1f46dcSZachary Turner }
6052c1f46dcSZachary Turner
SetStdHandle(FileSP file_sp,const char * py_name,PythonObject & save_file,const char * mode)606b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
607b07823f3SLawrence D'Anna const char *py_name,
608b07823f3SLawrence D'Anna PythonObject &save_file,
609b9c1b51eSKate Stone const char *mode) {
610b07823f3SLawrence D'Anna if (!file_sp || !*file_sp) {
611b07823f3SLawrence D'Anna save_file.Reset();
612b07823f3SLawrence D'Anna return false;
613b07823f3SLawrence D'Anna }
614b07823f3SLawrence D'Anna File &file = *file_sp;
615b07823f3SLawrence D'Anna
616a31baf08SGreg Clayton // Flush the file before giving it to python to avoid interleaved output.
617a31baf08SGreg Clayton file.Flush();
618a31baf08SGreg Clayton
619a31baf08SGreg Clayton PythonDictionary &sys_module_dict = GetSysModuleDictionary();
620a31baf08SGreg Clayton
6210f783599SLawrence D'Anna auto new_file = PythonFile::FromFile(file, mode);
6220f783599SLawrence D'Anna if (!new_file) {
6230f783599SLawrence D'Anna llvm::consumeError(new_file.takeError());
6240f783599SLawrence D'Anna return false;
6250f783599SLawrence D'Anna }
6260f783599SLawrence D'Anna
627b07823f3SLawrence D'Anna save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
628a31baf08SGreg Clayton
6290f783599SLawrence D'Anna sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
630a31baf08SGreg Clayton return true;
631a31baf08SGreg Clayton }
632a31baf08SGreg Clayton
EnterSession(uint16_t on_entry_flags,FileSP in_sp,FileSP out_sp,FileSP err_sp)63363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
634b07823f3SLawrence D'Anna FileSP in_sp, FileSP out_sp,
635b07823f3SLawrence D'Anna FileSP err_sp) {
636b9c1b51eSKate Stone // If we have already entered the session, without having officially 'left'
63705097246SAdrian Prantl // it, then there is no need to 'enter' it again.
638a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
639b9c1b51eSKate Stone if (m_session_is_active) {
64063e5fb76SJonas Devlieghere LLDB_LOGF(
64163e5fb76SJonas Devlieghere log,
64263dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
643b9c1b51eSKate Stone ") session is already active, returning without doing anything",
644b9c1b51eSKate Stone on_entry_flags);
6452c1f46dcSZachary Turner return false;
6462c1f46dcSZachary Turner }
6472c1f46dcSZachary Turner
64863e5fb76SJonas Devlieghere LLDB_LOGF(
64963e5fb76SJonas Devlieghere log,
65063e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
651b9c1b51eSKate Stone on_entry_flags);
6522c1f46dcSZachary Turner
6532c1f46dcSZachary Turner m_session_is_active = true;
6542c1f46dcSZachary Turner
6552c1f46dcSZachary Turner StreamString run_string;
6562c1f46dcSZachary Turner
657b9c1b51eSKate Stone if (on_entry_flags & Locker::InitGlobals) {
658b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6598d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID());
660b9c1b51eSKate Stone run_string.Printf(
661b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6628d1fb843SJonas Devlieghere m_debugger.GetID());
6632c1f46dcSZachary Turner run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6642c1f46dcSZachary Turner run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6652c1f46dcSZachary Turner run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6662c1f46dcSZachary Turner run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6672c1f46dcSZachary Turner run_string.PutCString("')");
668b9c1b51eSKate Stone } else {
66905097246SAdrian Prantl // If we aren't initing the globals, we should still always set the
67005097246SAdrian Prantl // debugger (since that is always unique.)
671b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6728d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID());
673b9c1b51eSKate Stone run_string.Printf(
674b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6758d1fb843SJonas Devlieghere m_debugger.GetID());
6762c1f46dcSZachary Turner run_string.PutCString("')");
6772c1f46dcSZachary Turner }
6782c1f46dcSZachary Turner
6792c1f46dcSZachary Turner PyRun_SimpleString(run_string.GetData());
6802c1f46dcSZachary Turner run_string.Clear();
6812c1f46dcSZachary Turner
6822c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary();
683b9c1b51eSKate Stone if (sys_module_dict.IsValid()) {
684b07823f3SLawrence D'Anna lldb::FileSP top_in_sp;
685b07823f3SLawrence D'Anna lldb::StreamFileSP top_out_sp, top_err_sp;
686b07823f3SLawrence D'Anna if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
687b07823f3SLawrence D'Anna m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
688b07823f3SLawrence D'Anna top_err_sp);
6892c1f46dcSZachary Turner
690b9c1b51eSKate Stone if (on_entry_flags & Locker::NoSTDIN) {
6912c1f46dcSZachary Turner m_saved_stdin.Reset();
692b9c1b51eSKate Stone } else {
693b07823f3SLawrence D'Anna if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
694b07823f3SLawrence D'Anna if (top_in_sp)
695b07823f3SLawrence D'Anna SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
6962c1f46dcSZachary Turner }
697a31baf08SGreg Clayton }
698a31baf08SGreg Clayton
699b07823f3SLawrence D'Anna if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
700b07823f3SLawrence D'Anna if (top_out_sp)
701b07823f3SLawrence D'Anna SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
702a31baf08SGreg Clayton }
703a31baf08SGreg Clayton
704b07823f3SLawrence D'Anna if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
705b07823f3SLawrence D'Anna if (top_err_sp)
706b07823f3SLawrence D'Anna SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
707a31baf08SGreg Clayton }
7082c1f46dcSZachary Turner }
7092c1f46dcSZachary Turner
7102c1f46dcSZachary Turner if (PyErr_Occurred())
7112c1f46dcSZachary Turner PyErr_Clear();
7122c1f46dcSZachary Turner
7132c1f46dcSZachary Turner return true;
7142c1f46dcSZachary Turner }
7152c1f46dcSZachary Turner
GetMainModule()71604edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
717f8b22f8fSZachary Turner if (!m_main_module.IsValid())
71804edd189SLawrence D'Anna m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7192c1f46dcSZachary Turner return m_main_module;
7202c1f46dcSZachary Turner }
7212c1f46dcSZachary Turner
GetSessionDictionary()72263dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
723f8b22f8fSZachary Turner if (m_session_dict.IsValid())
724f8b22f8fSZachary Turner return m_session_dict;
725f8b22f8fSZachary Turner
7262c1f46dcSZachary Turner PythonObject &main_module = GetMainModule();
727f8b22f8fSZachary Turner if (!main_module.IsValid())
728f8b22f8fSZachary Turner return m_session_dict;
729f8b22f8fSZachary Turner
730b9c1b51eSKate Stone PythonDictionary main_dict(PyRefType::Borrowed,
731b9c1b51eSKate Stone PyModule_GetDict(main_module.get()));
732f8b22f8fSZachary Turner if (!main_dict.IsValid())
733f8b22f8fSZachary Turner return m_session_dict;
734f8b22f8fSZachary Turner
735722b6189SLawrence D'Anna m_session_dict = unwrapIgnoringErrors(
736722b6189SLawrence D'Anna As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7372c1f46dcSZachary Turner return m_session_dict;
7382c1f46dcSZachary Turner }
7392c1f46dcSZachary Turner
GetSysModuleDictionary()74063dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
741f8b22f8fSZachary Turner if (m_sys_module_dict.IsValid())
742f8b22f8fSZachary Turner return m_sys_module_dict;
743722b6189SLawrence D'Anna PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
744722b6189SLawrence D'Anna m_sys_module_dict = sys_module.GetDictionary();
7452c1f46dcSZachary Turner return m_sys_module_dict;
7462c1f46dcSZachary Turner }
7472c1f46dcSZachary Turner
748a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
GetMaxPositionalArgumentsForCallable(const llvm::StringRef & callable_name)749a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
750a69bbe02SLawrence D'Anna const llvm::StringRef &callable_name) {
751738af7a6SJim Ingham if (callable_name.empty()) {
752738af7a6SJim Ingham return llvm::createStringError(
753738af7a6SJim Ingham llvm::inconvertibleErrorCode(),
754738af7a6SJim Ingham "called with empty callable name.");
755738af7a6SJim Ingham }
756738af7a6SJim Ingham Locker py_lock(this, Locker::AcquireLock |
757738af7a6SJim Ingham Locker::InitSession |
758738af7a6SJim Ingham Locker::NoSTDIN);
759738af7a6SJim Ingham auto dict = PythonModule::MainModule()
760738af7a6SJim Ingham .ResolveName<PythonDictionary>(m_dictionary_name);
761a69bbe02SLawrence D'Anna auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
762a69bbe02SLawrence D'Anna callable_name, dict);
763738af7a6SJim Ingham if (!pfunc.IsAllocated()) {
764738af7a6SJim Ingham return llvm::createStringError(
765738af7a6SJim Ingham llvm::inconvertibleErrorCode(),
766738af7a6SJim Ingham "can't find callable: %s", callable_name.str().c_str());
767738af7a6SJim Ingham }
768adbf64ccSLawrence D'Anna llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
769adbf64ccSLawrence D'Anna if (!arg_info)
770adbf64ccSLawrence D'Anna return arg_info.takeError();
771adbf64ccSLawrence D'Anna return arg_info.get().max_positional_args;
772738af7a6SJim Ingham }
773738af7a6SJim Ingham
GenerateUniqueName(const char * base_name_wanted,uint32_t & functions_counter,const void * name_token=nullptr)774b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
7752c1f46dcSZachary Turner uint32_t &functions_counter,
776b9c1b51eSKate Stone const void *name_token = nullptr) {
7772c1f46dcSZachary Turner StreamString sstr;
7782c1f46dcSZachary Turner
7792c1f46dcSZachary Turner if (!base_name_wanted)
7802c1f46dcSZachary Turner return std::string();
7812c1f46dcSZachary Turner
7822c1f46dcSZachary Turner if (!name_token)
7832c1f46dcSZachary Turner sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
7842c1f46dcSZachary Turner else
7852c1f46dcSZachary Turner sstr.Printf("%s_%p", base_name_wanted, name_token);
7862c1f46dcSZachary Turner
787adcd0268SBenjamin Kramer return std::string(sstr.GetString());
7882c1f46dcSZachary Turner }
7892c1f46dcSZachary Turner
GetEmbeddedInterpreterModuleObjects()79063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
791f8b22f8fSZachary Turner if (m_run_one_line_function.IsValid())
792f8b22f8fSZachary Turner return true;
793f8b22f8fSZachary Turner
794b9c1b51eSKate Stone PythonObject module(PyRefType::Borrowed,
795b9c1b51eSKate Stone PyImport_AddModule("lldb.embedded_interpreter"));
796f8b22f8fSZachary Turner if (!module.IsValid())
797f8b22f8fSZachary Turner return false;
798f8b22f8fSZachary Turner
799b9c1b51eSKate Stone PythonDictionary module_dict(PyRefType::Borrowed,
800b9c1b51eSKate Stone PyModule_GetDict(module.get()));
801f8b22f8fSZachary Turner if (!module_dict.IsValid())
802f8b22f8fSZachary Turner return false;
803f8b22f8fSZachary Turner
804b9c1b51eSKate Stone m_run_one_line_function =
805b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("run_one_line"));
806b9c1b51eSKate Stone m_run_one_line_str_global =
807b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
808f8b22f8fSZachary Turner return m_run_one_line_function.IsValid();
8092c1f46dcSZachary Turner }
8102c1f46dcSZachary Turner
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)81163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8124d51a902SRaphael Isemann llvm::StringRef command, CommandReturnObject *result,
813b9c1b51eSKate Stone const ExecuteScriptOptions &options) {
814d6c062bcSRaphael Isemann std::string command_str = command.str();
815d6c062bcSRaphael Isemann
8162c1f46dcSZachary Turner if (!m_valid_session)
8172c1f46dcSZachary Turner return false;
8182c1f46dcSZachary Turner
8194d51a902SRaphael Isemann if (!command.empty()) {
820b9c1b51eSKate Stone // We want to call run_one_line, passing in the dictionary and the command
82105097246SAdrian Prantl // string. We cannot do this through PyRun_SimpleString here because the
82205097246SAdrian Prantl // command string may contain escaped characters, and putting it inside
823b9c1b51eSKate Stone // another string to pass to PyRun_SimpleString messes up the escaping. So
82405097246SAdrian Prantl // we use the following more complicated method to pass the command string
82505097246SAdrian Prantl // directly down to Python.
826d79273c9SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
82784228365SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create(
82884228365SJonas Devlieghere options.GetEnableIO(), m_debugger, result);
829d79273c9SJonas Devlieghere if (!io_redirect_or_error) {
830d79273c9SJonas Devlieghere if (result)
831d79273c9SJonas Devlieghere result->AppendErrorWithFormatv(
832d79273c9SJonas Devlieghere "failed to redirect I/O: {0}\n",
833d79273c9SJonas Devlieghere llvm::fmt_consume(io_redirect_or_error.takeError()));
834d79273c9SJonas Devlieghere else
835d79273c9SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError());
8362fce1137SLawrence D'Anna return false;
8372fce1137SLawrence D'Anna }
838d79273c9SJonas Devlieghere
839d79273c9SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8402c1f46dcSZachary Turner
84132064024SZachary Turner bool success = false;
84232064024SZachary Turner {
84305097246SAdrian Prantl // WARNING! It's imperative that this RAII scope be as tight as
84405097246SAdrian Prantl // possible. In particular, the scope must end *before* we try to join
84505097246SAdrian Prantl // the read thread. The reason for this is that a pre-requisite for
84605097246SAdrian Prantl // joining the read thread is that we close the write handle (to break
84705097246SAdrian Prantl // the pipe and cause it to wake up and exit). But acquiring the GIL as
84805097246SAdrian Prantl // below will redirect Python's stdio to use this same handle. If we
84905097246SAdrian Prantl // close the handle while Python is still using it, bad things will
85005097246SAdrian Prantl // happen.
851b9c1b51eSKate Stone Locker locker(
852b9c1b51eSKate Stone this,
85363dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession |
85463dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8552c1f46dcSZachary Turner ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
856d79273c9SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession,
857d79273c9SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
858d79273c9SJonas Devlieghere io_redirect.GetErrorFile());
8592c1f46dcSZachary Turner
8602c1f46dcSZachary Turner // Find the correct script interpreter dictionary in the main module.
8612c1f46dcSZachary Turner PythonDictionary &session_dict = GetSessionDictionary();
862b9c1b51eSKate Stone if (session_dict.IsValid()) {
863b9c1b51eSKate Stone if (GetEmbeddedInterpreterModuleObjects()) {
864b9c1b51eSKate Stone if (PyCallable_Check(m_run_one_line_function.get())) {
865b9c1b51eSKate Stone PythonObject pargs(
866b9c1b51eSKate Stone PyRefType::Owned,
867d6c062bcSRaphael Isemann Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
868b9c1b51eSKate Stone if (pargs.IsValid()) {
869b9c1b51eSKate Stone PythonObject return_value(
870b9c1b51eSKate Stone PyRefType::Owned,
871b9c1b51eSKate Stone PyObject_CallObject(m_run_one_line_function.get(),
872b9c1b51eSKate Stone pargs.get()));
873f8b22f8fSZachary Turner if (return_value.IsValid())
8742c1f46dcSZachary Turner success = true;
875b9c1b51eSKate Stone else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
8762c1f46dcSZachary Turner PyErr_Print();
8772c1f46dcSZachary Turner PyErr_Clear();
8782c1f46dcSZachary Turner }
8792c1f46dcSZachary Turner }
8802c1f46dcSZachary Turner }
8812c1f46dcSZachary Turner }
8822c1f46dcSZachary Turner }
8832c1f46dcSZachary Turner
884d79273c9SJonas Devlieghere io_redirect.Flush();
8852c1f46dcSZachary Turner }
8862c1f46dcSZachary Turner
8872c1f46dcSZachary Turner if (success)
8882c1f46dcSZachary Turner return true;
8892c1f46dcSZachary Turner
8902c1f46dcSZachary Turner // The one-liner failed. Append the error message.
8914d51a902SRaphael Isemann if (result) {
892b9c1b51eSKate Stone result->AppendErrorWithFormat(
8934d51a902SRaphael Isemann "python failed attempting to evaluate '%s'\n", command_str.c_str());
8944d51a902SRaphael Isemann }
8952c1f46dcSZachary Turner return false;
8962c1f46dcSZachary Turner }
8972c1f46dcSZachary Turner
8982c1f46dcSZachary Turner if (result)
8992c1f46dcSZachary Turner result->AppendError("empty command passed to python\n");
9002c1f46dcSZachary Turner return false;
9012c1f46dcSZachary Turner }
9022c1f46dcSZachary Turner
ExecuteInterpreterLoop()90363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
9045c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER();
9052c1f46dcSZachary Turner
9068d1fb843SJonas Devlieghere Debugger &debugger = m_debugger;
9072c1f46dcSZachary Turner
908b9c1b51eSKate Stone // At the moment, the only time the debugger does not have an input file
90905097246SAdrian Prantl // handle is when this is called directly from Python, in which case it is
91005097246SAdrian Prantl // both dangerous and unnecessary (not to mention confusing) to try to embed
91105097246SAdrian Prantl // a running interpreter loop inside the already running Python interpreter
91205097246SAdrian Prantl // loop, so we won't do it.
9132c1f46dcSZachary Turner
9147ca15ba7SLawrence D'Anna if (!debugger.GetInputFile().IsValid())
9152c1f46dcSZachary Turner return;
9162c1f46dcSZachary Turner
9172c1f46dcSZachary Turner IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
918b9c1b51eSKate Stone if (io_handler_sp) {
9197ce2de2cSJonas Devlieghere debugger.RunIOHandlerAsync(io_handler_sp);
9202c1f46dcSZachary Turner }
9212c1f46dcSZachary Turner }
9222c1f46dcSZachary Turner
Interrupt()92363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
924049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
925049ae930SJonas Devlieghere // If the interpreter isn't evaluating any Python at the moment then return
926049ae930SJonas Devlieghere // false to signal that this function didn't handle the interrupt and the
927049ae930SJonas Devlieghere // next component should try handling it.
928049ae930SJonas Devlieghere if (!IsExecutingPython())
929049ae930SJonas Devlieghere return false;
930049ae930SJonas Devlieghere
931049ae930SJonas Devlieghere // Tell Python that it should pretend to have received a SIGINT.
932049ae930SJonas Devlieghere PyErr_SetInterrupt();
933049ae930SJonas Devlieghere // PyErr_SetInterrupt has no way to return an error so we can only pretend the
934049ae930SJonas Devlieghere // signal got successfully handled and return true.
935049ae930SJonas Devlieghere // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
936049ae930SJonas Devlieghere // the error handling is limited to checking the arguments which would be
937049ae930SJonas Devlieghere // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
938049ae930SJonas Devlieghere return true;
939049ae930SJonas Devlieghere #else
940a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Script);
9412c1f46dcSZachary Turner
942b9c1b51eSKate Stone if (IsExecutingPython()) {
943b1cf558dSEnrico Granata PyThreadState *state = PyThreadState_GET();
9442c1f46dcSZachary Turner if (!state)
9452c1f46dcSZachary Turner state = GetThreadState();
946b9c1b51eSKate Stone if (state) {
9472c1f46dcSZachary Turner long tid = state->thread_id;
94822c8efcdSZachary Turner PyThreadState_Swap(state);
9492c1f46dcSZachary Turner int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
95063e5fb76SJonas Devlieghere LLDB_LOGF(log,
95163e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() sending "
952b9c1b51eSKate Stone "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
953b9c1b51eSKate Stone tid, num_threads);
9542c1f46dcSZachary Turner return true;
9552c1f46dcSZachary Turner }
9562c1f46dcSZachary Turner }
95763e5fb76SJonas Devlieghere LLDB_LOGF(log,
95863dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
959b9c1b51eSKate Stone "can't interrupt");
9602c1f46dcSZachary Turner return false;
961049ae930SJonas Devlieghere #endif
9622c1f46dcSZachary Turner }
96304edd189SLawrence D'Anna
ExecuteOneLineWithReturn(llvm::StringRef in_string,ScriptInterpreter::ScriptReturnType return_type,void * ret_value,const ExecuteScriptOptions & options)96463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9654d51a902SRaphael Isemann llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
966b9c1b51eSKate Stone void *ret_value, const ExecuteScriptOptions &options) {
9672c1f46dcSZachary Turner
968f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
969f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create(
970f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr);
971f9517353SJonas Devlieghere
972f9517353SJonas Devlieghere if (!io_redirect_or_error) {
973f9517353SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError());
974f9517353SJonas Devlieghere return false;
975f9517353SJonas Devlieghere }
976f9517353SJonas Devlieghere
977f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
978f9517353SJonas Devlieghere
97963dd5d25SJonas Devlieghere Locker locker(this,
98063dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession |
98163dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
982b9c1b51eSKate Stone Locker::NoSTDIN,
983f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession,
984f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
985f9517353SJonas Devlieghere io_redirect.GetErrorFile());
9862c1f46dcSZachary Turner
98704edd189SLawrence D'Anna PythonModule &main_module = GetMainModule();
98804edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary();
9892c1f46dcSZachary Turner
9902c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary();
99104edd189SLawrence D'Anna if (!locals.IsValid())
992722b6189SLawrence D'Anna locals = unwrapIgnoringErrors(
993722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
994f8b22f8fSZachary Turner if (!locals.IsValid())
9952c1f46dcSZachary Turner locals = globals;
9962c1f46dcSZachary Turner
99704edd189SLawrence D'Anna Expected<PythonObject> maybe_py_return =
99804edd189SLawrence D'Anna runStringOneLine(in_string, globals, locals);
9992c1f46dcSZachary Turner
100004edd189SLawrence D'Anna if (!maybe_py_return) {
100104edd189SLawrence D'Anna llvm::handleAllErrors(
100204edd189SLawrence D'Anna maybe_py_return.takeError(),
100304edd189SLawrence D'Anna [&](PythonException &E) {
100404edd189SLawrence D'Anna E.Restore();
100504edd189SLawrence D'Anna if (options.GetMaskoutErrors()) {
100604edd189SLawrence D'Anna if (E.Matches(PyExc_SyntaxError)) {
100704edd189SLawrence D'Anna PyErr_Print();
10082c1f46dcSZachary Turner }
100904edd189SLawrence D'Anna PyErr_Clear();
101004edd189SLawrence D'Anna }
101104edd189SLawrence D'Anna },
101204edd189SLawrence D'Anna [](const llvm::ErrorInfoBase &E) {});
101304edd189SLawrence D'Anna return false;
10142c1f46dcSZachary Turner }
10152c1f46dcSZachary Turner
101604edd189SLawrence D'Anna PythonObject py_return = std::move(maybe_py_return.get());
101704edd189SLawrence D'Anna assert(py_return.IsValid());
101804edd189SLawrence D'Anna
1019b9c1b51eSKate Stone switch (return_type) {
10202c1f46dcSZachary Turner case eScriptReturnTypeCharPtr: // "char *"
10212c1f46dcSZachary Turner {
10222c1f46dcSZachary Turner const char format[3] = "s#";
102304edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10242c1f46dcSZachary Turner }
1025b9c1b51eSKate Stone case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1026b9c1b51eSKate Stone // Py_None
10272c1f46dcSZachary Turner {
10282c1f46dcSZachary Turner const char format[3] = "z";
102904edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10302c1f46dcSZachary Turner }
1031b9c1b51eSKate Stone case eScriptReturnTypeBool: {
10322c1f46dcSZachary Turner const char format[2] = "b";
103304edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10342c1f46dcSZachary Turner }
1035b9c1b51eSKate Stone case eScriptReturnTypeShortInt: {
10362c1f46dcSZachary Turner const char format[2] = "h";
103704edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10382c1f46dcSZachary Turner }
1039b9c1b51eSKate Stone case eScriptReturnTypeShortIntUnsigned: {
10402c1f46dcSZachary Turner const char format[2] = "H";
104104edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10422c1f46dcSZachary Turner }
1043b9c1b51eSKate Stone case eScriptReturnTypeInt: {
10442c1f46dcSZachary Turner const char format[2] = "i";
104504edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10462c1f46dcSZachary Turner }
1047b9c1b51eSKate Stone case eScriptReturnTypeIntUnsigned: {
10482c1f46dcSZachary Turner const char format[2] = "I";
104904edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10502c1f46dcSZachary Turner }
1051b9c1b51eSKate Stone case eScriptReturnTypeLongInt: {
10522c1f46dcSZachary Turner const char format[2] = "l";
105304edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10542c1f46dcSZachary Turner }
1055b9c1b51eSKate Stone case eScriptReturnTypeLongIntUnsigned: {
10562c1f46dcSZachary Turner const char format[2] = "k";
105704edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10582c1f46dcSZachary Turner }
1059b9c1b51eSKate Stone case eScriptReturnTypeLongLong: {
10602c1f46dcSZachary Turner const char format[2] = "L";
106104edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10622c1f46dcSZachary Turner }
1063b9c1b51eSKate Stone case eScriptReturnTypeLongLongUnsigned: {
10642c1f46dcSZachary Turner const char format[2] = "K";
106504edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format,
106604edd189SLawrence D'Anna (unsigned long long *)ret_value);
10672c1f46dcSZachary Turner }
1068b9c1b51eSKate Stone case eScriptReturnTypeFloat: {
10692c1f46dcSZachary Turner const char format[2] = "f";
107004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10712c1f46dcSZachary Turner }
1072b9c1b51eSKate Stone case eScriptReturnTypeDouble: {
10732c1f46dcSZachary Turner const char format[2] = "d";
107404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (double *)ret_value);
10752c1f46dcSZachary Turner }
1076b9c1b51eSKate Stone case eScriptReturnTypeChar: {
10772c1f46dcSZachary Turner const char format[2] = "c";
107804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char *)ret_value);
10792c1f46dcSZachary Turner }
1080b9c1b51eSKate Stone case eScriptReturnTypeOpaqueObject: {
108104edd189SLawrence D'Anna *((PyObject **)ret_value) = py_return.release();
108204edd189SLawrence D'Anna return true;
10832c1f46dcSZachary Turner }
10842c1f46dcSZachary Turner }
10851dfb1a85SPavel Labath llvm_unreachable("Fully covered switch!");
10862c1f46dcSZachary Turner }
10872c1f46dcSZachary Turner
ExecuteMultipleLines(const char * in_string,const ExecuteScriptOptions & options)108863dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1089b9c1b51eSKate Stone const char *in_string, const ExecuteScriptOptions &options) {
109004edd189SLawrence D'Anna
109104edd189SLawrence D'Anna if (in_string == nullptr)
109204edd189SLawrence D'Anna return Status();
10932c1f46dcSZachary Turner
1094f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1095f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1096f9517353SJonas Devlieghere options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1097f9517353SJonas Devlieghere
1098f9517353SJonas Devlieghere if (!io_redirect_or_error)
1099f9517353SJonas Devlieghere return Status(io_redirect_or_error.takeError());
1100f9517353SJonas Devlieghere
1101f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1102f9517353SJonas Devlieghere
110363dd5d25SJonas Devlieghere Locker locker(this,
110463dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession |
110563dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1106b9c1b51eSKate Stone Locker::NoSTDIN,
1107f9517353SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession,
1108f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1109f9517353SJonas Devlieghere io_redirect.GetErrorFile());
11102c1f46dcSZachary Turner
111104edd189SLawrence D'Anna PythonModule &main_module = GetMainModule();
111204edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary();
11132c1f46dcSZachary Turner
11142c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary();
1115f8b22f8fSZachary Turner if (!locals.IsValid())
1116722b6189SLawrence D'Anna locals = unwrapIgnoringErrors(
1117722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1118f8b22f8fSZachary Turner if (!locals.IsValid())
11192c1f46dcSZachary Turner locals = globals;
11202c1f46dcSZachary Turner
112104edd189SLawrence D'Anna Expected<PythonObject> return_value =
112204edd189SLawrence D'Anna runStringMultiLine(in_string, globals, locals);
11232c1f46dcSZachary Turner
112404edd189SLawrence D'Anna if (!return_value) {
112504edd189SLawrence D'Anna llvm::Error error =
112604edd189SLawrence D'Anna llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
112704edd189SLawrence D'Anna llvm::Error error = llvm::createStringError(
112804edd189SLawrence D'Anna llvm::inconvertibleErrorCode(), E.ReadBacktrace());
112904edd189SLawrence D'Anna if (!options.GetMaskoutErrors())
113004edd189SLawrence D'Anna E.Restore();
11312c1f46dcSZachary Turner return error;
113204edd189SLawrence D'Anna });
113304edd189SLawrence D'Anna return Status(std::move(error));
113404edd189SLawrence D'Anna }
113504edd189SLawrence D'Anna
113604edd189SLawrence D'Anna return Status();
11372c1f46dcSZachary Turner }
11382c1f46dcSZachary Turner
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)113963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1140cfb96d84SJim Ingham std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1141b9c1b51eSKate Stone CommandReturnObject &result) {
11422c1f46dcSZachary Turner m_active_io_handler = eIOHandlerBreakpoint;
11438d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1144a6faf851SJonas Devlieghere " ", *this, &bp_options_vec);
11452c1f46dcSZachary Turner }
11462c1f46dcSZachary Turner
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)114763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1148b9c1b51eSKate Stone WatchpointOptions *wp_options, CommandReturnObject &result) {
11492c1f46dcSZachary Turner m_active_io_handler = eIOHandlerWatchpoint;
11508d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1151a6faf851SJonas Devlieghere " ", *this, wp_options);
11522c1f46dcSZachary Turner }
11532c1f46dcSZachary Turner
SetBreakpointCommandCallbackFunction(BreakpointOptions & bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)1154738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1155cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *function_name,
1156738af7a6SJim Ingham StructuredData::ObjectSP extra_args_sp) {
1157738af7a6SJim Ingham Status error;
11582c1f46dcSZachary Turner // For now just cons up a oneliner that calls the provided function.
11592c1f46dcSZachary Turner std::string oneliner("return ");
11602c1f46dcSZachary Turner oneliner += function_name;
1161738af7a6SJim Ingham
1162a69bbe02SLawrence D'Anna llvm::Expected<unsigned> maybe_args =
1163a69bbe02SLawrence D'Anna GetMaxPositionalArgumentsForCallable(function_name);
1164738af7a6SJim Ingham if (!maybe_args) {
1165a69bbe02SLawrence D'Anna error.SetErrorStringWithFormat(
1166a69bbe02SLawrence D'Anna "could not get num args: %s",
1167738af7a6SJim Ingham llvm::toString(maybe_args.takeError()).c_str());
1168738af7a6SJim Ingham return error;
1169738af7a6SJim Ingham }
1170a69bbe02SLawrence D'Anna size_t max_args = *maybe_args;
1171738af7a6SJim Ingham
1172738af7a6SJim Ingham bool uses_extra_args = false;
1173a69bbe02SLawrence D'Anna if (max_args >= 4) {
1174738af7a6SJim Ingham uses_extra_args = true;
1175738af7a6SJim Ingham oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1176a69bbe02SLawrence D'Anna } else if (max_args >= 3) {
1177738af7a6SJim Ingham if (extra_args_sp) {
1178738af7a6SJim Ingham error.SetErrorString("cannot pass extra_args to a three argument callback"
1179738af7a6SJim Ingham );
1180738af7a6SJim Ingham return error;
1181738af7a6SJim Ingham }
1182738af7a6SJim Ingham uses_extra_args = false;
11832c1f46dcSZachary Turner oneliner += "(frame, bp_loc, internal_dict)";
1184738af7a6SJim Ingham } else {
1185738af7a6SJim Ingham error.SetErrorStringWithFormat("expected 3 or 4 argument "
1186a69bbe02SLawrence D'Anna "function, %s can only take %zu",
1187a69bbe02SLawrence D'Anna function_name, max_args);
1188738af7a6SJim Ingham return error;
1189738af7a6SJim Ingham }
1190738af7a6SJim Ingham
1191738af7a6SJim Ingham SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1192738af7a6SJim Ingham uses_extra_args);
1193738af7a6SJim Ingham return error;
11942c1f46dcSZachary Turner }
11952c1f46dcSZachary Turner
SetBreakpointCommandCallback(BreakpointOptions & bp_options,std::unique_ptr<BreakpointOptions::CommandData> & cmd_data_up)119663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1197cfb96d84SJim Ingham BreakpointOptions &bp_options,
1198f7e07256SJim Ingham std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
119997206d57SZachary Turner Status error;
1200f7e07256SJim Ingham error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1201738af7a6SJim Ingham cmd_data_up->script_source,
1202738af7a6SJim Ingham false);
1203f7e07256SJim Ingham if (error.Fail()) {
1204f7e07256SJim Ingham return error;
1205f7e07256SJim Ingham }
1206f7e07256SJim Ingham auto baton_sp =
1207f7e07256SJim Ingham std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1208cfb96d84SJim Ingham bp_options.SetCallback(
120963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1210f7e07256SJim Ingham return error;
1211f7e07256SJim Ingham }
1212f7e07256SJim Ingham
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text)121363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1214cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text) {
1215738af7a6SJim Ingham return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1216738af7a6SJim Ingham }
12172c1f46dcSZachary Turner
1218738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp,bool uses_extra_args)1219738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1220cfb96d84SJim Ingham BreakpointOptions &bp_options, const char *command_body_text,
1221cfb96d84SJim Ingham StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1222738af7a6SJim Ingham auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1223b9c1b51eSKate Stone // Split the command_body_text into lines, and pass that to
122405097246SAdrian Prantl // GenerateBreakpointCommandCallbackData. That will wrap the body in an
122505097246SAdrian Prantl // auto-generated function, and return the function name in script_source.
122605097246SAdrian Prantl // That is what the callback will actually invoke.
12272c1f46dcSZachary Turner
1228d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(command_body_text);
1229d5b44036SJonas Devlieghere Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1230738af7a6SJim Ingham data_up->script_source,
1231738af7a6SJim Ingham uses_extra_args);
1232b9c1b51eSKate Stone if (error.Success()) {
12334e4fbe82SZachary Turner auto baton_sp =
1234d5b44036SJonas Devlieghere std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1235cfb96d84SJim Ingham bp_options.SetCallback(
123663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12372c1f46dcSZachary Turner return error;
123893571c3cSJonas Devlieghere }
12392c1f46dcSZachary Turner return error;
12402c1f46dcSZachary Turner }
12412c1f46dcSZachary Turner
12422c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * oneliner)124363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1244b9c1b51eSKate Stone WatchpointOptions *wp_options, const char *oneliner) {
1245a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12462c1f46dcSZachary Turner
12472c1f46dcSZachary Turner // It's necessary to set both user_source and script_source to the oneliner.
1248b9c1b51eSKate Stone // The former is used to generate callback description (as in watchpoint
124905097246SAdrian Prantl // command list) while the latter is used for Python to interpret during the
125005097246SAdrian Prantl // actual callback.
12512c1f46dcSZachary Turner
1252d5b44036SJonas Devlieghere data_up->user_source.AppendString(oneliner);
1253d5b44036SJonas Devlieghere data_up->script_source.assign(oneliner);
12542c1f46dcSZachary Turner
1255d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1256d5b44036SJonas Devlieghere data_up->script_source)) {
12574e4fbe82SZachary Turner auto baton_sp =
1258d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
125963dd5d25SJonas Devlieghere wp_options->SetCallback(
126063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12612c1f46dcSZachary Turner }
12622c1f46dcSZachary Turner
12632c1f46dcSZachary Turner return;
12642c1f46dcSZachary Turner }
12652c1f46dcSZachary Turner
ExportFunctionDefinitionToInterpreter(StringList & function_def)126663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1267b9c1b51eSKate Stone StringList &function_def) {
12682c1f46dcSZachary Turner // Convert StringList to one long, newline delimited, const char *.
12692c1f46dcSZachary Turner std::string function_def_string(function_def.CopyList());
12702c1f46dcSZachary Turner
127197206d57SZachary Turner Status error = ExecuteMultipleLines(
1272b9c1b51eSKate Stone function_def_string.c_str(),
1273fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false));
12742c1f46dcSZachary Turner return error;
12752c1f46dcSZachary Turner }
12762c1f46dcSZachary Turner
GenerateFunction(const char * signature,const StringList & input)127763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1278b9c1b51eSKate Stone const StringList &input) {
127997206d57SZachary Turner Status error;
12802c1f46dcSZachary Turner int num_lines = input.GetSize();
1281b9c1b51eSKate Stone if (num_lines == 0) {
12822c1f46dcSZachary Turner error.SetErrorString("No input data.");
12832c1f46dcSZachary Turner return error;
12842c1f46dcSZachary Turner }
12852c1f46dcSZachary Turner
1286b9c1b51eSKate Stone if (!signature || *signature == 0) {
12872c1f46dcSZachary Turner error.SetErrorString("No output function name.");
12882c1f46dcSZachary Turner return error;
12892c1f46dcSZachary Turner }
12902c1f46dcSZachary Turner
12912c1f46dcSZachary Turner StreamString sstr;
12922c1f46dcSZachary Turner StringList auto_generated_function;
12932c1f46dcSZachary Turner auto_generated_function.AppendString(signature);
1294b9c1b51eSKate Stone auto_generated_function.AppendString(
1295b9c1b51eSKate Stone " global_dict = globals()"); // Grab the global dictionary
1296b9c1b51eSKate Stone auto_generated_function.AppendString(
1297b9c1b51eSKate Stone " new_keys = internal_dict.keys()"); // Make a list of keys in the
1298b9c1b51eSKate Stone // session dict
1299b9c1b51eSKate Stone auto_generated_function.AppendString(
1300b9c1b51eSKate Stone " old_keys = global_dict.keys()"); // Save list of keys in global dict
1301b9c1b51eSKate Stone auto_generated_function.AppendString(
1302b9c1b51eSKate Stone " global_dict.update (internal_dict)"); // Add the session dictionary
1303b9c1b51eSKate Stone // to the
13042c1f46dcSZachary Turner // global dictionary.
13052c1f46dcSZachary Turner
13062c1f46dcSZachary Turner // Wrap everything up inside the function, increasing the indentation.
13072c1f46dcSZachary Turner
13082c1f46dcSZachary Turner auto_generated_function.AppendString(" if True:");
1309b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) {
13102c1f46dcSZachary Turner sstr.Clear();
13112c1f46dcSZachary Turner sstr.Printf(" %s", input.GetStringAtIndex(i));
13122c1f46dcSZachary Turner auto_generated_function.AppendString(sstr.GetData());
13132c1f46dcSZachary Turner }
1314b9c1b51eSKate Stone auto_generated_function.AppendString(
1315b9c1b51eSKate Stone " for key in new_keys:"); // Iterate over all the keys from session
1316b9c1b51eSKate Stone // dict
1317b9c1b51eSKate Stone auto_generated_function.AppendString(
1318b9c1b51eSKate Stone " internal_dict[key] = global_dict[key]"); // Update session dict
1319b9c1b51eSKate Stone // values
1320b9c1b51eSKate Stone auto_generated_function.AppendString(
1321b9c1b51eSKate Stone " if key not in old_keys:"); // If key was not originally in
1322b9c1b51eSKate Stone // global dict
1323b9c1b51eSKate Stone auto_generated_function.AppendString(
1324b9c1b51eSKate Stone " del global_dict[key]"); // ...then remove key/value from
1325b9c1b51eSKate Stone // global dict
13262c1f46dcSZachary Turner
13272c1f46dcSZachary Turner // Verify that the results are valid Python.
13282c1f46dcSZachary Turner
13292c1f46dcSZachary Turner error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13302c1f46dcSZachary Turner
13312c1f46dcSZachary Turner return error;
13322c1f46dcSZachary Turner }
13332c1f46dcSZachary Turner
GenerateTypeScriptFunction(StringList & user_input,std::string & output,const void * name_token)133463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1335b9c1b51eSKate Stone StringList &user_input, std::string &output, const void *name_token) {
13362c1f46dcSZachary Turner static uint32_t num_created_functions = 0;
13372c1f46dcSZachary Turner user_input.RemoveBlankLines();
13382c1f46dcSZachary Turner StreamString sstr;
13392c1f46dcSZachary Turner
13402c1f46dcSZachary Turner // Check to see if we have any data; if not, just return.
13412c1f46dcSZachary Turner if (user_input.GetSize() == 0)
13422c1f46dcSZachary Turner return false;
13432c1f46dcSZachary Turner
1344b9c1b51eSKate Stone // Take what the user wrote, wrap it all up inside one big auto-generated
134505097246SAdrian Prantl // Python function, passing in the ValueObject as parameter to the function.
13462c1f46dcSZachary Turner
1347b9c1b51eSKate Stone std::string auto_generated_function_name(
1348b9c1b51eSKate Stone GenerateUniqueName("lldb_autogen_python_type_print_func",
1349b9c1b51eSKate Stone num_created_functions, name_token));
1350b9c1b51eSKate Stone sstr.Printf("def %s (valobj, internal_dict):",
1351b9c1b51eSKate Stone auto_generated_function_name.c_str());
13522c1f46dcSZachary Turner
13532c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success())
13542c1f46dcSZachary Turner return false;
13552c1f46dcSZachary Turner
13562c1f46dcSZachary Turner // Store the name of the auto-generated function to be called.
13572c1f46dcSZachary Turner output.assign(auto_generated_function_name);
13582c1f46dcSZachary Turner return true;
13592c1f46dcSZachary Turner }
13602c1f46dcSZachary Turner
GenerateScriptAliasFunction(StringList & user_input,std::string & output)136163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1362b9c1b51eSKate Stone StringList &user_input, std::string &output) {
13632c1f46dcSZachary Turner static uint32_t num_created_functions = 0;
13642c1f46dcSZachary Turner user_input.RemoveBlankLines();
13652c1f46dcSZachary Turner StreamString sstr;
13662c1f46dcSZachary Turner
13672c1f46dcSZachary Turner // Check to see if we have any data; if not, just return.
13682c1f46dcSZachary Turner if (user_input.GetSize() == 0)
13692c1f46dcSZachary Turner return false;
13702c1f46dcSZachary Turner
1371b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName(
1372b9c1b51eSKate Stone "lldb_autogen_python_cmd_alias_func", num_created_functions));
13732c1f46dcSZachary Turner
1374b9c1b51eSKate Stone sstr.Printf("def %s (debugger, args, result, internal_dict):",
1375b9c1b51eSKate Stone auto_generated_function_name.c_str());
13762c1f46dcSZachary Turner
13772c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success())
13782c1f46dcSZachary Turner return false;
13792c1f46dcSZachary Turner
13802c1f46dcSZachary Turner // Store the name of the auto-generated function to be called.
13812c1f46dcSZachary Turner output.assign(auto_generated_function_name);
13822c1f46dcSZachary Turner return true;
13832c1f46dcSZachary Turner }
13842c1f46dcSZachary Turner
GenerateTypeSynthClass(StringList & user_input,std::string & output,const void * name_token)138563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
138663dd5d25SJonas Devlieghere StringList &user_input, std::string &output, const void *name_token) {
13872c1f46dcSZachary Turner static uint32_t num_created_classes = 0;
13882c1f46dcSZachary Turner user_input.RemoveBlankLines();
13892c1f46dcSZachary Turner int num_lines = user_input.GetSize();
13902c1f46dcSZachary Turner StreamString sstr;
13912c1f46dcSZachary Turner
13922c1f46dcSZachary Turner // Check to see if we have any data; if not, just return.
13932c1f46dcSZachary Turner if (user_input.GetSize() == 0)
13942c1f46dcSZachary Turner return false;
13952c1f46dcSZachary Turner
13962c1f46dcSZachary Turner // Wrap all user input into a Python class
13972c1f46dcSZachary Turner
1398b9c1b51eSKate Stone std::string auto_generated_class_name(GenerateUniqueName(
1399b9c1b51eSKate Stone "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14002c1f46dcSZachary Turner
14012c1f46dcSZachary Turner StringList auto_generated_class;
14022c1f46dcSZachary Turner
14032c1f46dcSZachary Turner // Create the function name & definition string.
14042c1f46dcSZachary Turner
14052c1f46dcSZachary Turner sstr.Printf("class %s:", auto_generated_class_name.c_str());
1406c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString());
14072c1f46dcSZachary Turner
140805097246SAdrian Prantl // Wrap everything up inside the class, increasing the indentation. we don't
140905097246SAdrian Prantl // need to play any fancy indentation tricks here because there is no
14102c1f46dcSZachary Turner // surrounding code whose indentation we need to honor
1411b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) {
14122c1f46dcSZachary Turner sstr.Clear();
14132c1f46dcSZachary Turner sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1414c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString());
14152c1f46dcSZachary Turner }
14162c1f46dcSZachary Turner
141705097246SAdrian Prantl // Verify that the results are valid Python. (even though the method is
141805097246SAdrian Prantl // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14192c1f46dcSZachary Turner // (TODO: rename that method to ExportDefinitionToInterpreter)
14202c1f46dcSZachary Turner if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14212c1f46dcSZachary Turner return false;
14222c1f46dcSZachary Turner
14232c1f46dcSZachary Turner // Store the name of the auto-generated class
14242c1f46dcSZachary Turner
14252c1f46dcSZachary Turner output.assign(auto_generated_class_name);
14262c1f46dcSZachary Turner return true;
14272c1f46dcSZachary Turner }
14282c1f46dcSZachary Turner
142963dd5d25SJonas Devlieghere StructuredData::GenericSP
CreateFrameRecognizer(const char * class_name)143063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
143141ae8e74SKuba Mracek if (class_name == nullptr || class_name[0] == '\0')
143241ae8e74SKuba Mracek return StructuredData::GenericSP();
143341ae8e74SKuba Mracek
1434a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1435c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
1436a6598575SRalf Grosse-Kunstleve class_name, m_dictionary_name.c_str());
143741ae8e74SKuba Mracek
1438c154f397SPavel Labath return StructuredData::GenericSP(
1439c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
144041ae8e74SKuba Mracek }
144141ae8e74SKuba Mracek
GetRecognizedArguments(const StructuredData::ObjectSP & os_plugin_object_sp,lldb::StackFrameSP frame_sp)144263dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
144341ae8e74SKuba Mracek const StructuredData::ObjectSP &os_plugin_object_sp,
144441ae8e74SKuba Mracek lldb::StackFrameSP frame_sp) {
144541ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
144641ae8e74SKuba Mracek
144763dd5d25SJonas Devlieghere if (!os_plugin_object_sp)
144863dd5d25SJonas Devlieghere return ValueObjectListSP();
144941ae8e74SKuba Mracek
145041ae8e74SKuba Mracek StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
145163dd5d25SJonas Devlieghere if (!generic)
145263dd5d25SJonas Devlieghere return nullptr;
145341ae8e74SKuba Mracek
145441ae8e74SKuba Mracek PythonObject implementor(PyRefType::Borrowed,
145541ae8e74SKuba Mracek (PyObject *)generic->GetValue());
145641ae8e74SKuba Mracek
145763dd5d25SJonas Devlieghere if (!implementor.IsAllocated())
145863dd5d25SJonas Devlieghere return ValueObjectListSP();
145941ae8e74SKuba Mracek
14609a14adeaSPavel Labath PythonObject py_return(
14619a14adeaSPavel Labath PyRefType::Owned,
14629a14adeaSPavel Labath LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
146341ae8e74SKuba Mracek
146441ae8e74SKuba Mracek // if it fails, print the error but otherwise go on
146541ae8e74SKuba Mracek if (PyErr_Occurred()) {
146641ae8e74SKuba Mracek PyErr_Print();
146741ae8e74SKuba Mracek PyErr_Clear();
146841ae8e74SKuba Mracek }
146941ae8e74SKuba Mracek if (py_return.get()) {
147041ae8e74SKuba Mracek PythonList result_list(PyRefType::Borrowed, py_return.get());
147141ae8e74SKuba Mracek ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
14728f81aed1SDavid Bolvansky for (size_t i = 0; i < result_list.GetSize(); i++) {
147341ae8e74SKuba Mracek PyObject *item = result_list.GetItemAtIndex(i).get();
147441ae8e74SKuba Mracek lldb::SBValue *sb_value_ptr =
147505495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
147605495c5dSJonas Devlieghere auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
147763dd5d25SJonas Devlieghere if (valobj_sp)
147863dd5d25SJonas Devlieghere result->Append(valobj_sp);
147941ae8e74SKuba Mracek }
148041ae8e74SKuba Mracek return result;
148141ae8e74SKuba Mracek }
148241ae8e74SKuba Mracek return ValueObjectListSP();
148341ae8e74SKuba Mracek }
148441ae8e74SKuba Mracek
148563dd5d25SJonas Devlieghere StructuredData::GenericSP
OSPlugin_CreatePluginObject(const char * class_name,lldb::ProcessSP process_sp)148663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1487b9c1b51eSKate Stone const char *class_name, lldb::ProcessSP process_sp) {
14882c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0')
14892c1f46dcSZachary Turner return StructuredData::GenericSP();
14902c1f46dcSZachary Turner
14912c1f46dcSZachary Turner if (!process_sp)
14922c1f46dcSZachary Turner return StructuredData::GenericSP();
14932c1f46dcSZachary Turner
1494a6598575SRalf Grosse-Kunstleve Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1495c154f397SPavel Labath PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
149605495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), process_sp);
14972c1f46dcSZachary Turner
1498c154f397SPavel Labath return StructuredData::GenericSP(
1499c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
15002c1f46dcSZachary Turner }
15012c1f46dcSZachary Turner
OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp)150263dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1503b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) {
1504b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15052c1f46dcSZachary Turner
15062c1f46dcSZachary Turner static char callee_name[] = "get_register_info";
15072c1f46dcSZachary Turner
15082c1f46dcSZachary Turner if (!os_plugin_object_sp)
15092c1f46dcSZachary Turner return StructuredData::DictionarySP();
15102c1f46dcSZachary Turner
15112c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15122c1f46dcSZachary Turner if (!generic)
15132c1f46dcSZachary Turner return nullptr;
15142c1f46dcSZachary Turner
1515b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
1516b9c1b51eSKate Stone (PyObject *)generic->GetValue());
15172c1f46dcSZachary Turner
1518f8b22f8fSZachary Turner if (!implementor.IsAllocated())
15192c1f46dcSZachary Turner return StructuredData::DictionarySP();
15202c1f46dcSZachary Turner
1521b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
1522b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
15232c1f46dcSZachary Turner
15242c1f46dcSZachary Turner if (PyErr_Occurred())
15252c1f46dcSZachary Turner PyErr_Clear();
15262c1f46dcSZachary Turner
1527f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
15282c1f46dcSZachary Turner return StructuredData::DictionarySP();
15292c1f46dcSZachary Turner
1530b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
15312c1f46dcSZachary Turner if (PyErr_Occurred())
15322c1f46dcSZachary Turner PyErr_Clear();
15332c1f46dcSZachary Turner
15342c1f46dcSZachary Turner return StructuredData::DictionarySP();
15352c1f46dcSZachary Turner }
15362c1f46dcSZachary Turner
15372c1f46dcSZachary Turner if (PyErr_Occurred())
15382c1f46dcSZachary Turner PyErr_Clear();
15392c1f46dcSZachary Turner
15402c1f46dcSZachary Turner // right now we know this function exists and is callable..
1541b9c1b51eSKate Stone PythonObject py_return(
1542b9c1b51eSKate Stone PyRefType::Owned,
1543b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15442c1f46dcSZachary Turner
15452c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
1546b9c1b51eSKate Stone if (PyErr_Occurred()) {
15472c1f46dcSZachary Turner PyErr_Print();
15482c1f46dcSZachary Turner PyErr_Clear();
15492c1f46dcSZachary Turner }
1550b9c1b51eSKate Stone if (py_return.get()) {
1551f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
15522c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary();
15532c1f46dcSZachary Turner }
155458b794aeSGreg Clayton return StructuredData::DictionarySP();
155558b794aeSGreg Clayton }
15562c1f46dcSZachary Turner
OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp)155763dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1558b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) {
1559b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15602c1f46dcSZachary Turner
15612c1f46dcSZachary Turner static char callee_name[] = "get_thread_info";
15622c1f46dcSZachary Turner
15632c1f46dcSZachary Turner if (!os_plugin_object_sp)
15642c1f46dcSZachary Turner return StructuredData::ArraySP();
15652c1f46dcSZachary Turner
15662c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15672c1f46dcSZachary Turner if (!generic)
15682c1f46dcSZachary Turner return nullptr;
15692c1f46dcSZachary Turner
1570b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
1571b9c1b51eSKate Stone (PyObject *)generic->GetValue());
1572f8b22f8fSZachary Turner
1573f8b22f8fSZachary Turner if (!implementor.IsAllocated())
15742c1f46dcSZachary Turner return StructuredData::ArraySP();
15752c1f46dcSZachary Turner
1576b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
1577b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
15782c1f46dcSZachary Turner
15792c1f46dcSZachary Turner if (PyErr_Occurred())
15802c1f46dcSZachary Turner PyErr_Clear();
15812c1f46dcSZachary Turner
1582f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
15832c1f46dcSZachary Turner return StructuredData::ArraySP();
15842c1f46dcSZachary Turner
1585b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
15862c1f46dcSZachary Turner if (PyErr_Occurred())
15872c1f46dcSZachary Turner PyErr_Clear();
15882c1f46dcSZachary Turner
15892c1f46dcSZachary Turner return StructuredData::ArraySP();
15902c1f46dcSZachary Turner }
15912c1f46dcSZachary Turner
15922c1f46dcSZachary Turner if (PyErr_Occurred())
15932c1f46dcSZachary Turner PyErr_Clear();
15942c1f46dcSZachary Turner
15952c1f46dcSZachary Turner // right now we know this function exists and is callable..
1596b9c1b51eSKate Stone PythonObject py_return(
1597b9c1b51eSKate Stone PyRefType::Owned,
1598b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15992c1f46dcSZachary Turner
16002c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
1601b9c1b51eSKate Stone if (PyErr_Occurred()) {
16022c1f46dcSZachary Turner PyErr_Print();
16032c1f46dcSZachary Turner PyErr_Clear();
16042c1f46dcSZachary Turner }
16052c1f46dcSZachary Turner
1606b9c1b51eSKate Stone if (py_return.get()) {
1607f8b22f8fSZachary Turner PythonList result_list(PyRefType::Borrowed, py_return.get());
1608f8b22f8fSZachary Turner return result_list.CreateStructuredArray();
16092c1f46dcSZachary Turner }
161058b794aeSGreg Clayton return StructuredData::ArraySP();
161158b794aeSGreg Clayton }
16122c1f46dcSZachary Turner
161363dd5d25SJonas Devlieghere StructuredData::StringSP
OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid)161463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1615b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1616b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16172c1f46dcSZachary Turner
16182c1f46dcSZachary Turner static char callee_name[] = "get_register_data";
1619b9c1b51eSKate Stone static char *param_format =
1620b9c1b51eSKate Stone const_cast<char *>(GetPythonValueFormatString(tid));
16212c1f46dcSZachary Turner
16222c1f46dcSZachary Turner if (!os_plugin_object_sp)
16232c1f46dcSZachary Turner return StructuredData::StringSP();
16242c1f46dcSZachary Turner
16252c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16262c1f46dcSZachary Turner if (!generic)
16272c1f46dcSZachary Turner return nullptr;
1628b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
1629b9c1b51eSKate Stone (PyObject *)generic->GetValue());
16302c1f46dcSZachary Turner
1631f8b22f8fSZachary Turner if (!implementor.IsAllocated())
16322c1f46dcSZachary Turner return StructuredData::StringSP();
16332c1f46dcSZachary Turner
1634b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
1635b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
16362c1f46dcSZachary Turner
16372c1f46dcSZachary Turner if (PyErr_Occurred())
16382c1f46dcSZachary Turner PyErr_Clear();
16392c1f46dcSZachary Turner
1640f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
16412c1f46dcSZachary Turner return StructuredData::StringSP();
16422c1f46dcSZachary Turner
1643b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
16442c1f46dcSZachary Turner if (PyErr_Occurred())
16452c1f46dcSZachary Turner PyErr_Clear();
16462c1f46dcSZachary Turner return StructuredData::StringSP();
16472c1f46dcSZachary Turner }
16482c1f46dcSZachary Turner
16492c1f46dcSZachary Turner if (PyErr_Occurred())
16502c1f46dcSZachary Turner PyErr_Clear();
16512c1f46dcSZachary Turner
16522c1f46dcSZachary Turner // right now we know this function exists and is callable..
1653b9c1b51eSKate Stone PythonObject py_return(
1654b9c1b51eSKate Stone PyRefType::Owned,
1655b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
16562c1f46dcSZachary Turner
16572c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
1658b9c1b51eSKate Stone if (PyErr_Occurred()) {
16592c1f46dcSZachary Turner PyErr_Print();
16602c1f46dcSZachary Turner PyErr_Clear();
16612c1f46dcSZachary Turner }
1662f8b22f8fSZachary Turner
1663b9c1b51eSKate Stone if (py_return.get()) {
16647a76845cSZachary Turner PythonBytes result(PyRefType::Borrowed, py_return.get());
16657a76845cSZachary Turner return result.CreateStructuredString();
16662c1f46dcSZachary Turner }
166758b794aeSGreg Clayton return StructuredData::StringSP();
166858b794aeSGreg Clayton }
16692c1f46dcSZachary Turner
OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid,lldb::addr_t context)167063dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1671b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1672b9c1b51eSKate Stone lldb::addr_t context) {
1673b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16742c1f46dcSZachary Turner
16752c1f46dcSZachary Turner static char callee_name[] = "create_thread";
16762c1f46dcSZachary Turner std::string param_format;
16772c1f46dcSZachary Turner param_format += GetPythonValueFormatString(tid);
16782c1f46dcSZachary Turner param_format += GetPythonValueFormatString(context);
16792c1f46dcSZachary Turner
16802c1f46dcSZachary Turner if (!os_plugin_object_sp)
16812c1f46dcSZachary Turner return StructuredData::DictionarySP();
16822c1f46dcSZachary Turner
16832c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16842c1f46dcSZachary Turner if (!generic)
16852c1f46dcSZachary Turner return nullptr;
16862c1f46dcSZachary Turner
1687b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
1688b9c1b51eSKate Stone (PyObject *)generic->GetValue());
1689f8b22f8fSZachary Turner
1690f8b22f8fSZachary Turner if (!implementor.IsAllocated())
16912c1f46dcSZachary Turner return StructuredData::DictionarySP();
16922c1f46dcSZachary Turner
1693b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
1694b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
16952c1f46dcSZachary Turner
16962c1f46dcSZachary Turner if (PyErr_Occurred())
16972c1f46dcSZachary Turner PyErr_Clear();
16982c1f46dcSZachary Turner
1699f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
17002c1f46dcSZachary Turner return StructuredData::DictionarySP();
17012c1f46dcSZachary Turner
1702b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
17032c1f46dcSZachary Turner if (PyErr_Occurred())
17042c1f46dcSZachary Turner PyErr_Clear();
17052c1f46dcSZachary Turner return StructuredData::DictionarySP();
17062c1f46dcSZachary Turner }
17072c1f46dcSZachary Turner
17082c1f46dcSZachary Turner if (PyErr_Occurred())
17092c1f46dcSZachary Turner PyErr_Clear();
17102c1f46dcSZachary Turner
17112c1f46dcSZachary Turner // right now we know this function exists and is callable..
1712b9c1b51eSKate Stone PythonObject py_return(PyRefType::Owned,
1713b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name,
1714b9c1b51eSKate Stone ¶m_format[0], tid, context));
17152c1f46dcSZachary Turner
17162c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
1717b9c1b51eSKate Stone if (PyErr_Occurred()) {
17182c1f46dcSZachary Turner PyErr_Print();
17192c1f46dcSZachary Turner PyErr_Clear();
17202c1f46dcSZachary Turner }
17212c1f46dcSZachary Turner
1722b9c1b51eSKate Stone if (py_return.get()) {
1723f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
17242c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary();
17252c1f46dcSZachary Turner }
172658b794aeSGreg Clayton return StructuredData::DictionarySP();
172758b794aeSGreg Clayton }
17282c1f46dcSZachary Turner
CreateScriptedThreadPlan(const char * class_name,const StructuredDataImpl & args_data,std::string & error_str,lldb::ThreadPlanSP thread_plan_sp)172963dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
173082de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data,
1731a69bbe02SLawrence D'Anna std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
17322c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0')
17332c1f46dcSZachary Turner return StructuredData::ObjectSP();
17342c1f46dcSZachary Turner
17352c1f46dcSZachary Turner if (!thread_plan_sp.get())
173693c98346SJim Ingham return {};
17372c1f46dcSZachary Turner
17382c1f46dcSZachary Turner Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
173963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter =
1740d055e3a0SPedro Tammela GetPythonInterpreter(debugger);
17412c1f46dcSZachary Turner
1742d055e3a0SPedro Tammela if (!python_interpreter)
174393c98346SJim Ingham return {};
17442c1f46dcSZachary Turner
1745b9c1b51eSKate Stone Locker py_lock(this,
1746b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1747c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1748a6598575SRalf Grosse-Kunstleve class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1749a6598575SRalf Grosse-Kunstleve error_str, thread_plan_sp);
175093c98346SJim Ingham if (!ret_val)
175193c98346SJim Ingham return {};
17522c1f46dcSZachary Turner
1753c154f397SPavel Labath return StructuredData::ObjectSP(
1754c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
17552c1f46dcSZachary Turner }
17562c1f46dcSZachary Turner
ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)175763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1758b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17592c1f46dcSZachary Turner bool explains_stop = true;
17602c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr;
17612c1f46dcSZachary Turner if (implementor_sp)
17622c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric();
1763b9c1b51eSKate Stone if (generic) {
1764b9c1b51eSKate Stone Locker py_lock(this,
1765b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
176605495c5dSJonas Devlieghere explains_stop = LLDBSWIGPythonCallThreadPlan(
1767b9c1b51eSKate Stone generic->GetValue(), "explains_stop", event, script_error);
17682c1f46dcSZachary Turner if (script_error)
17692c1f46dcSZachary Turner return true;
17702c1f46dcSZachary Turner }
17712c1f46dcSZachary Turner return explains_stop;
17722c1f46dcSZachary Turner }
17732c1f46dcSZachary Turner
ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)177463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1775b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17762c1f46dcSZachary Turner bool should_stop = true;
17772c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr;
17782c1f46dcSZachary Turner if (implementor_sp)
17792c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric();
1780b9c1b51eSKate Stone if (generic) {
1781b9c1b51eSKate Stone Locker py_lock(this,
1782b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
178305495c5dSJonas Devlieghere should_stop = LLDBSWIGPythonCallThreadPlan(
178405495c5dSJonas Devlieghere generic->GetValue(), "should_stop", event, script_error);
17852c1f46dcSZachary Turner if (script_error)
17862c1f46dcSZachary Turner return true;
17872c1f46dcSZachary Turner }
17882c1f46dcSZachary Turner return should_stop;
17892c1f46dcSZachary Turner }
17902c1f46dcSZachary Turner
ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,bool & script_error)179163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1792b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) {
1793c915a7d2SJim Ingham bool is_stale = true;
1794c915a7d2SJim Ingham StructuredData::Generic *generic = nullptr;
1795c915a7d2SJim Ingham if (implementor_sp)
1796c915a7d2SJim Ingham generic = implementor_sp->GetAsGeneric();
1797b9c1b51eSKate Stone if (generic) {
1798b9c1b51eSKate Stone Locker py_lock(this,
1799b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
180005495c5dSJonas Devlieghere is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
180105495c5dSJonas Devlieghere nullptr, script_error);
1802c915a7d2SJim Ingham if (script_error)
1803c915a7d2SJim Ingham return true;
1804c915a7d2SJim Ingham }
1805c915a7d2SJim Ingham return is_stale;
1806c915a7d2SJim Ingham }
1807c915a7d2SJim Ingham
ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,bool & script_error)180863dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1809b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) {
18102c1f46dcSZachary Turner bool should_step = false;
18112c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr;
18122c1f46dcSZachary Turner if (implementor_sp)
18132c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric();
1814b9c1b51eSKate Stone if (generic) {
1815b9c1b51eSKate Stone Locker py_lock(this,
1816b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
181705495c5dSJonas Devlieghere should_step = LLDBSWIGPythonCallThreadPlan(
1818248a1305SKonrad Kleine generic->GetValue(), "should_step", nullptr, script_error);
18192c1f46dcSZachary Turner if (script_error)
18202c1f46dcSZachary Turner should_step = true;
18212c1f46dcSZachary Turner }
18222c1f46dcSZachary Turner if (should_step)
18232c1f46dcSZachary Turner return lldb::eStateStepping;
18242c1f46dcSZachary Turner return lldb::eStateRunning;
18252c1f46dcSZachary Turner }
18262c1f46dcSZachary Turner
18273815e702SJim Ingham StructuredData::GenericSP
CreateScriptedBreakpointResolver(const char * class_name,const StructuredDataImpl & args_data,lldb::BreakpointSP & bkpt_sp)182863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
182982de8df2SPavel Labath const char *class_name, const StructuredDataImpl &args_data,
18303815e702SJim Ingham lldb::BreakpointSP &bkpt_sp) {
18313815e702SJim Ingham
18323815e702SJim Ingham if (class_name == nullptr || class_name[0] == '\0')
18333815e702SJim Ingham return StructuredData::GenericSP();
18343815e702SJim Ingham
18353815e702SJim Ingham if (!bkpt_sp.get())
18363815e702SJim Ingham return StructuredData::GenericSP();
18373815e702SJim Ingham
18383815e702SJim Ingham Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
183963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter =
1840d055e3a0SPedro Tammela GetPythonInterpreter(debugger);
18413815e702SJim Ingham
1842d055e3a0SPedro Tammela if (!python_interpreter)
18433815e702SJim Ingham return StructuredData::GenericSP();
18443815e702SJim Ingham
18453815e702SJim Ingham Locker py_lock(this,
18463815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18473815e702SJim Ingham
1848c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
184905495c5dSJonas Devlieghere class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
185005495c5dSJonas Devlieghere bkpt_sp);
18513815e702SJim Ingham
1852c154f397SPavel Labath return StructuredData::GenericSP(
1853c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
18543815e702SJim Ingham }
18553815e702SJim Ingham
ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP implementor_sp,SymbolContext * sym_ctx)185663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
185763dd5d25SJonas Devlieghere StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
18583815e702SJim Ingham bool should_continue = false;
18593815e702SJim Ingham
18603815e702SJim Ingham if (implementor_sp) {
18613815e702SJim Ingham Locker py_lock(this,
18623815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
186305495c5dSJonas Devlieghere should_continue = LLDBSwigPythonCallBreakpointResolver(
186405495c5dSJonas Devlieghere implementor_sp->GetValue(), "__callback__", sym_ctx);
18653815e702SJim Ingham if (PyErr_Occurred()) {
18663815e702SJim Ingham PyErr_Print();
18673815e702SJim Ingham PyErr_Clear();
18683815e702SJim Ingham }
18693815e702SJim Ingham }
18703815e702SJim Ingham return should_continue;
18713815e702SJim Ingham }
18723815e702SJim Ingham
18733815e702SJim Ingham lldb::SearchDepth
ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP implementor_sp)187463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
18753815e702SJim Ingham StructuredData::GenericSP implementor_sp) {
18763815e702SJim Ingham int depth_as_int = lldb::eSearchDepthModule;
18773815e702SJim Ingham if (implementor_sp) {
18783815e702SJim Ingham Locker py_lock(this,
18793815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
188005495c5dSJonas Devlieghere depth_as_int = LLDBSwigPythonCallBreakpointResolver(
188105495c5dSJonas Devlieghere implementor_sp->GetValue(), "__get_depth__", nullptr);
18823815e702SJim Ingham if (PyErr_Occurred()) {
18833815e702SJim Ingham PyErr_Print();
18843815e702SJim Ingham PyErr_Clear();
18853815e702SJim Ingham }
18863815e702SJim Ingham }
18873815e702SJim Ingham if (depth_as_int == lldb::eSearchDepthInvalid)
18883815e702SJim Ingham return lldb::eSearchDepthModule;
18893815e702SJim Ingham
18903815e702SJim Ingham if (depth_as_int <= lldb::kLastSearchDepthKind)
18913815e702SJim Ingham return (lldb::SearchDepth)depth_as_int;
18923815e702SJim Ingham return lldb::eSearchDepthModule;
18933815e702SJim Ingham }
18943815e702SJim Ingham
CreateScriptedStopHook(TargetSP target_sp,const char * class_name,const StructuredDataImpl & args_data,Status & error)18951b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
189682de8df2SPavel Labath TargetSP target_sp, const char *class_name,
189782de8df2SPavel Labath const StructuredDataImpl &args_data, Status &error) {
18981b1d9815SJim Ingham
18991b1d9815SJim Ingham if (!target_sp) {
19001b1d9815SJim Ingham error.SetErrorString("No target for scripted stop-hook.");
19011b1d9815SJim Ingham return StructuredData::GenericSP();
19021b1d9815SJim Ingham }
19031b1d9815SJim Ingham
19041b1d9815SJim Ingham if (class_name == nullptr || class_name[0] == '\0') {
19051b1d9815SJim Ingham error.SetErrorString("No class name for scripted stop-hook.");
19061b1d9815SJim Ingham return StructuredData::GenericSP();
19071b1d9815SJim Ingham }
19081b1d9815SJim Ingham
19091b1d9815SJim Ingham ScriptInterpreterPythonImpl *python_interpreter =
1910d055e3a0SPedro Tammela GetPythonInterpreter(m_debugger);
19111b1d9815SJim Ingham
1912d055e3a0SPedro Tammela if (!python_interpreter) {
19131b1d9815SJim Ingham error.SetErrorString("No script interpreter for scripted stop-hook.");
19141b1d9815SJim Ingham return StructuredData::GenericSP();
19151b1d9815SJim Ingham }
19161b1d9815SJim Ingham
19171b1d9815SJim Ingham Locker py_lock(this,
19181b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19191b1d9815SJim Ingham
1920c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
19211b1d9815SJim Ingham target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
19221b1d9815SJim Ingham args_data, error);
19231b1d9815SJim Ingham
1924c154f397SPavel Labath return StructuredData::GenericSP(
1925c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
19261b1d9815SJim Ingham }
19271b1d9815SJim Ingham
ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,ExecutionContext & exc_ctx,lldb::StreamSP stream_sp)19281b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
19291b1d9815SJim Ingham StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
19301b1d9815SJim Ingham lldb::StreamSP stream_sp) {
19311b1d9815SJim Ingham assert(implementor_sp &&
19321b1d9815SJim Ingham "can't call a stop hook with an invalid implementor");
19331b1d9815SJim Ingham assert(stream_sp && "can't call a stop hook with an invalid stream");
19341b1d9815SJim Ingham
19351b1d9815SJim Ingham Locker py_lock(this,
19361b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19371b1d9815SJim Ingham
19381b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
19391b1d9815SJim Ingham
19401b1d9815SJim Ingham bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
19411b1d9815SJim Ingham implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
19421b1d9815SJim Ingham return ret_val;
19431b1d9815SJim Ingham }
19441b1d9815SJim Ingham
19452c1f46dcSZachary Turner StructuredData::ObjectSP
LoadPluginModule(const FileSpec & file_spec,lldb_private::Status & error)194663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
194797206d57SZachary Turner lldb_private::Status &error) {
1948dbd7fabaSJonas Devlieghere if (!FileSystem::Instance().Exists(file_spec)) {
19492c1f46dcSZachary Turner error.SetErrorString("no such file");
19502c1f46dcSZachary Turner return StructuredData::ObjectSP();
19512c1f46dcSZachary Turner }
19522c1f46dcSZachary Turner
19532c1f46dcSZachary Turner StructuredData::ObjectSP module_sp;
19542c1f46dcSZachary Turner
1955f9517353SJonas Devlieghere LoadScriptOptions load_script_options =
1956f9517353SJonas Devlieghere LoadScriptOptions().SetInitSession(true).SetSilent(false);
1957f9517353SJonas Devlieghere if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1958f9517353SJonas Devlieghere error, &module_sp))
19592c1f46dcSZachary Turner return module_sp;
19602c1f46dcSZachary Turner
19612c1f46dcSZachary Turner return StructuredData::ObjectSP();
19622c1f46dcSZachary Turner }
19632c1f46dcSZachary Turner
GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp,Target * target,const char * setting_name,lldb_private::Status & error)196463dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1965b9c1b51eSKate Stone StructuredData::ObjectSP plugin_module_sp, Target *target,
196697206d57SZachary Turner const char *setting_name, lldb_private::Status &error) {
196705495c5dSJonas Devlieghere if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
19682c1f46dcSZachary Turner return StructuredData::DictionarySP();
19692c1f46dcSZachary Turner StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
19702c1f46dcSZachary Turner if (!generic)
19712c1f46dcSZachary Turner return StructuredData::DictionarySP();
19722c1f46dcSZachary Turner
1973b9c1b51eSKate Stone Locker py_lock(this,
1974b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19752c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this());
19762c1f46dcSZachary Turner
197704edd189SLawrence D'Anna auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
197804edd189SLawrence D'Anna generic->GetValue(), setting_name, target_sp);
197904edd189SLawrence D'Anna
198004edd189SLawrence D'Anna if (!setting)
198104edd189SLawrence D'Anna return StructuredData::DictionarySP();
198204edd189SLawrence D'Anna
198304edd189SLawrence D'Anna PythonDictionary py_dict =
198404edd189SLawrence D'Anna unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
198504edd189SLawrence D'Anna
198604edd189SLawrence D'Anna if (!py_dict)
198704edd189SLawrence D'Anna return StructuredData::DictionarySP();
198804edd189SLawrence D'Anna
19892c1f46dcSZachary Turner return py_dict.CreateStructuredDictionary();
19902c1f46dcSZachary Turner }
19912c1f46dcSZachary Turner
19922c1f46dcSZachary Turner StructuredData::ObjectSP
CreateSyntheticScriptedProvider(const char * class_name,lldb::ValueObjectSP valobj)199363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1994b9c1b51eSKate Stone const char *class_name, lldb::ValueObjectSP valobj) {
19952c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0')
19962c1f46dcSZachary Turner return StructuredData::ObjectSP();
19972c1f46dcSZachary Turner
19982c1f46dcSZachary Turner if (!valobj.get())
19992c1f46dcSZachary Turner return StructuredData::ObjectSP();
20002c1f46dcSZachary Turner
20012c1f46dcSZachary Turner ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
20022c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr();
20032c1f46dcSZachary Turner
20042c1f46dcSZachary Turner if (!target)
20052c1f46dcSZachary Turner return StructuredData::ObjectSP();
20062c1f46dcSZachary Turner
20072c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger();
200863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter =
2009d055e3a0SPedro Tammela GetPythonInterpreter(debugger);
20102c1f46dcSZachary Turner
2011d055e3a0SPedro Tammela if (!python_interpreter)
20122c1f46dcSZachary Turner return StructuredData::ObjectSP();
20132c1f46dcSZachary Turner
2014b9c1b51eSKate Stone Locker py_lock(this,
2015b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2016c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
2017b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
20182c1f46dcSZachary Turner
2019c154f397SPavel Labath return StructuredData::ObjectSP(
2020c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
20212c1f46dcSZachary Turner }
20222c1f46dcSZachary Turner
20232c1f46dcSZachary Turner StructuredData::GenericSP
CreateScriptCommandObject(const char * class_name)202463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
20258d1fb843SJonas Devlieghere DebuggerSP debugger_sp(m_debugger.shared_from_this());
20262c1f46dcSZachary Turner
20272c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0')
20282c1f46dcSZachary Turner return StructuredData::GenericSP();
20292c1f46dcSZachary Turner
20302c1f46dcSZachary Turner if (!debugger_sp.get())
20312c1f46dcSZachary Turner return StructuredData::GenericSP();
20322c1f46dcSZachary Turner
2033b9c1b51eSKate Stone Locker py_lock(this,
2034b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2035c154f397SPavel Labath PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
203605495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), debugger_sp);
20372c1f46dcSZachary Turner
2038c154f397SPavel Labath return StructuredData::GenericSP(
2039c154f397SPavel Labath new StructuredPythonObject(std::move(ret_val)));
20402c1f46dcSZachary Turner }
20412c1f46dcSZachary Turner
GenerateTypeScriptFunction(const char * oneliner,std::string & output,const void * name_token)204263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2043b9c1b51eSKate Stone const char *oneliner, std::string &output, const void *name_token) {
20442c1f46dcSZachary Turner StringList input;
20452c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner));
20462c1f46dcSZachary Turner return GenerateTypeScriptFunction(input, output, name_token);
20472c1f46dcSZachary Turner }
20482c1f46dcSZachary Turner
GenerateTypeSynthClass(const char * oneliner,std::string & output,const void * name_token)204963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
205063dd5d25SJonas Devlieghere const char *oneliner, std::string &output, const void *name_token) {
20512c1f46dcSZachary Turner StringList input;
20522c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner));
20532c1f46dcSZachary Turner return GenerateTypeSynthClass(input, output, name_token);
20542c1f46dcSZachary Turner }
20552c1f46dcSZachary Turner
GenerateBreakpointCommandCallbackData(StringList & user_input,std::string & output,bool has_extra_args)205663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2057738af7a6SJim Ingham StringList &user_input, std::string &output,
2058738af7a6SJim Ingham bool has_extra_args) {
20592c1f46dcSZachary Turner static uint32_t num_created_functions = 0;
20602c1f46dcSZachary Turner user_input.RemoveBlankLines();
20612c1f46dcSZachary Turner StreamString sstr;
206297206d57SZachary Turner Status error;
2063b9c1b51eSKate Stone if (user_input.GetSize() == 0) {
20642c1f46dcSZachary Turner error.SetErrorString("No input data.");
20652c1f46dcSZachary Turner return error;
20662c1f46dcSZachary Turner }
20672c1f46dcSZachary Turner
2068b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName(
2069b9c1b51eSKate Stone "lldb_autogen_python_bp_callback_func_", num_created_functions));
2070738af7a6SJim Ingham if (has_extra_args)
2071738af7a6SJim Ingham sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2072738af7a6SJim Ingham auto_generated_function_name.c_str());
2073738af7a6SJim Ingham else
2074b9c1b51eSKate Stone sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2075b9c1b51eSKate Stone auto_generated_function_name.c_str());
20762c1f46dcSZachary Turner
20772c1f46dcSZachary Turner error = GenerateFunction(sstr.GetData(), user_input);
20782c1f46dcSZachary Turner if (!error.Success())
20792c1f46dcSZachary Turner return error;
20802c1f46dcSZachary Turner
20812c1f46dcSZachary Turner // Store the name of the auto-generated function to be called.
20822c1f46dcSZachary Turner output.assign(auto_generated_function_name);
20832c1f46dcSZachary Turner return error;
20842c1f46dcSZachary Turner }
20852c1f46dcSZachary Turner
GenerateWatchpointCommandCallbackData(StringList & user_input,std::string & output)208663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2087b9c1b51eSKate Stone StringList &user_input, std::string &output) {
20882c1f46dcSZachary Turner static uint32_t num_created_functions = 0;
20892c1f46dcSZachary Turner user_input.RemoveBlankLines();
20902c1f46dcSZachary Turner StreamString sstr;
20912c1f46dcSZachary Turner
20922c1f46dcSZachary Turner if (user_input.GetSize() == 0)
20932c1f46dcSZachary Turner return false;
20942c1f46dcSZachary Turner
2095b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName(
2096b9c1b51eSKate Stone "lldb_autogen_python_wp_callback_func_", num_created_functions));
2097b9c1b51eSKate Stone sstr.Printf("def %s (frame, wp, internal_dict):",
2098b9c1b51eSKate Stone auto_generated_function_name.c_str());
20992c1f46dcSZachary Turner
21002c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success())
21012c1f46dcSZachary Turner return false;
21022c1f46dcSZachary Turner
21032c1f46dcSZachary Turner // Store the name of the auto-generated function to be called.
21042c1f46dcSZachary Turner output.assign(auto_generated_function_name);
21052c1f46dcSZachary Turner return true;
21062c1f46dcSZachary Turner }
21072c1f46dcSZachary Turner
GetScriptedSummary(const char * python_function_name,lldb::ValueObjectSP valobj,StructuredData::ObjectSP & callee_wrapper_sp,const TypeSummaryOptions & options,std::string & retval)210863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2109b9c1b51eSKate Stone const char *python_function_name, lldb::ValueObjectSP valobj,
2110b9c1b51eSKate Stone StructuredData::ObjectSP &callee_wrapper_sp,
2111b9c1b51eSKate Stone const TypeSummaryOptions &options, std::string &retval) {
21122c1f46dcSZachary Turner
21135c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER();
21142c1f46dcSZachary Turner
2115b9c1b51eSKate Stone if (!valobj.get()) {
21162c1f46dcSZachary Turner retval.assign("<no object>");
21172c1f46dcSZachary Turner return false;
21182c1f46dcSZachary Turner }
21192c1f46dcSZachary Turner
21202c1f46dcSZachary Turner void *old_callee = nullptr;
21212c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr;
2122b9c1b51eSKate Stone if (callee_wrapper_sp) {
21232c1f46dcSZachary Turner generic = callee_wrapper_sp->GetAsGeneric();
21242c1f46dcSZachary Turner if (generic)
21252c1f46dcSZachary Turner old_callee = generic->GetValue();
21262c1f46dcSZachary Turner }
21272c1f46dcSZachary Turner void *new_callee = old_callee;
21282c1f46dcSZachary Turner
21292c1f46dcSZachary Turner bool ret_val;
2130b9c1b51eSKate Stone if (python_function_name && *python_function_name) {
21312c1f46dcSZachary Turner {
2132b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2133b9c1b51eSKate Stone Locker::NoSTDIN);
21342c1f46dcSZachary Turner {
21352c1f46dcSZachary Turner TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
21362c1f46dcSZachary Turner
213705495c5dSJonas Devlieghere static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
213805495c5dSJonas Devlieghere Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
213905495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallTypeScript(
2140b9c1b51eSKate Stone python_function_name, GetSessionDictionary().get(), valobj,
2141b9c1b51eSKate Stone &new_callee, options_sp, retval);
21422c1f46dcSZachary Turner }
21432c1f46dcSZachary Turner }
2144b9c1b51eSKate Stone } else {
21452c1f46dcSZachary Turner retval.assign("<no function name>");
21462c1f46dcSZachary Turner return false;
21472c1f46dcSZachary Turner }
21482c1f46dcSZachary Turner
2149a6598575SRalf Grosse-Kunstleve if (new_callee && old_callee != new_callee) {
2150a6598575SRalf Grosse-Kunstleve Locker py_lock(this,
2151a6598575SRalf Grosse-Kunstleve Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2152c154f397SPavel Labath callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2153c154f397SPavel Labath PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2154a6598575SRalf Grosse-Kunstleve }
21552c1f46dcSZachary Turner
21562c1f46dcSZachary Turner return ret_val;
21572c1f46dcSZachary Turner }
21582c1f46dcSZachary Turner
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)215963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2160b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t break_id,
2161b9c1b51eSKate Stone user_id_t break_loc_id) {
2162f7e07256SJim Ingham CommandDataPython *bp_option_data = (CommandDataPython *)baton;
21632c1f46dcSZachary Turner const char *python_function_name = bp_option_data->script_source.c_str();
21642c1f46dcSZachary Turner
21652c1f46dcSZachary Turner if (!context)
21662c1f46dcSZachary Turner return true;
21672c1f46dcSZachary Turner
21682c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref);
21692c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr();
21702c1f46dcSZachary Turner
21712c1f46dcSZachary Turner if (!target)
21722c1f46dcSZachary Turner return true;
21732c1f46dcSZachary Turner
21742c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger();
217563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter =
2176d055e3a0SPedro Tammela GetPythonInterpreter(debugger);
21772c1f46dcSZachary Turner
2178d055e3a0SPedro Tammela if (!python_interpreter)
21792c1f46dcSZachary Turner return true;
21802c1f46dcSZachary Turner
2181b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) {
21822c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
21832c1f46dcSZachary Turner BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2184b9c1b51eSKate Stone if (breakpoint_sp) {
2185b9c1b51eSKate Stone const BreakpointLocationSP bp_loc_sp(
2186b9c1b51eSKate Stone breakpoint_sp->FindLocationByID(break_loc_id));
21872c1f46dcSZachary Turner
2188b9c1b51eSKate Stone if (stop_frame_sp && bp_loc_sp) {
21892c1f46dcSZachary Turner bool ret_val = true;
21902c1f46dcSZachary Turner {
2191b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock |
2192b9c1b51eSKate Stone Locker::InitSession |
2193b9c1b51eSKate Stone Locker::NoSTDIN);
2194a69bbe02SLawrence D'Anna Expected<bool> maybe_ret_val =
2195a69bbe02SLawrence D'Anna LLDBSwigPythonBreakpointCallbackFunction(
2196b9c1b51eSKate Stone python_function_name,
2197b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
219882de8df2SPavel Labath bp_loc_sp, bp_option_data->m_extra_args);
2199a69bbe02SLawrence D'Anna
2200a69bbe02SLawrence D'Anna if (!maybe_ret_val) {
2201a69bbe02SLawrence D'Anna
2202a69bbe02SLawrence D'Anna llvm::handleAllErrors(
2203a69bbe02SLawrence D'Anna maybe_ret_val.takeError(),
2204a69bbe02SLawrence D'Anna [&](PythonException &E) {
2205a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.ReadBacktrace();
2206a69bbe02SLawrence D'Anna },
2207a69bbe02SLawrence D'Anna [&](const llvm::ErrorInfoBase &E) {
2208a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.message();
2209a69bbe02SLawrence D'Anna });
2210a69bbe02SLawrence D'Anna
2211a69bbe02SLawrence D'Anna } else {
2212a69bbe02SLawrence D'Anna ret_val = maybe_ret_val.get();
2213a69bbe02SLawrence D'Anna }
22142c1f46dcSZachary Turner }
22152c1f46dcSZachary Turner return ret_val;
22162c1f46dcSZachary Turner }
22172c1f46dcSZachary Turner }
22182c1f46dcSZachary Turner }
22192c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when
22202c1f46dcSZachary Turner // trying to call the script function
22212c1f46dcSZachary Turner return true;
22222c1f46dcSZachary Turner }
22232c1f46dcSZachary Turner
WatchpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t watch_id)222463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2225b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2226b9c1b51eSKate Stone WatchpointOptions::CommandData *wp_option_data =
2227b9c1b51eSKate Stone (WatchpointOptions::CommandData *)baton;
22282c1f46dcSZachary Turner const char *python_function_name = wp_option_data->script_source.c_str();
22292c1f46dcSZachary Turner
22302c1f46dcSZachary Turner if (!context)
22312c1f46dcSZachary Turner return true;
22322c1f46dcSZachary Turner
22332c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref);
22342c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr();
22352c1f46dcSZachary Turner
22362c1f46dcSZachary Turner if (!target)
22372c1f46dcSZachary Turner return true;
22382c1f46dcSZachary Turner
22392c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger();
224063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter =
2241d055e3a0SPedro Tammela GetPythonInterpreter(debugger);
22422c1f46dcSZachary Turner
2243d055e3a0SPedro Tammela if (!python_interpreter)
22442c1f46dcSZachary Turner return true;
22452c1f46dcSZachary Turner
2246b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) {
22472c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22482c1f46dcSZachary Turner WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2249b9c1b51eSKate Stone if (wp_sp) {
2250b9c1b51eSKate Stone if (stop_frame_sp && wp_sp) {
22512c1f46dcSZachary Turner bool ret_val = true;
22522c1f46dcSZachary Turner {
2253b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock |
2254b9c1b51eSKate Stone Locker::InitSession |
2255b9c1b51eSKate Stone Locker::NoSTDIN);
225605495c5dSJonas Devlieghere ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2257b9c1b51eSKate Stone python_function_name,
2258b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
22592c1f46dcSZachary Turner wp_sp);
22602c1f46dcSZachary Turner }
22612c1f46dcSZachary Turner return ret_val;
22622c1f46dcSZachary Turner }
22632c1f46dcSZachary Turner }
22642c1f46dcSZachary Turner }
22652c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when
22662c1f46dcSZachary Turner // trying to call the script function
22672c1f46dcSZachary Turner return true;
22682c1f46dcSZachary Turner }
22692c1f46dcSZachary Turner
CalculateNumChildren(const StructuredData::ObjectSP & implementor_sp,uint32_t max)227063dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2271b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
22722c1f46dcSZachary Turner if (!implementor_sp)
22732c1f46dcSZachary Turner return 0;
22742c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22752c1f46dcSZachary Turner if (!generic)
22762c1f46dcSZachary Turner return 0;
22779a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
22782c1f46dcSZachary Turner if (!implementor)
22792c1f46dcSZachary Turner return 0;
22802c1f46dcSZachary Turner
22812c1f46dcSZachary Turner size_t ret_val = 0;
22822c1f46dcSZachary Turner
22832c1f46dcSZachary Turner {
2284b9c1b51eSKate Stone Locker py_lock(this,
2285b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
228605495c5dSJonas Devlieghere ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
22872c1f46dcSZachary Turner }
22882c1f46dcSZachary Turner
22892c1f46dcSZachary Turner return ret_val;
22902c1f46dcSZachary Turner }
22912c1f46dcSZachary Turner
GetChildAtIndex(const StructuredData::ObjectSP & implementor_sp,uint32_t idx)229263dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2293b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
22942c1f46dcSZachary Turner if (!implementor_sp)
22952c1f46dcSZachary Turner return lldb::ValueObjectSP();
22962c1f46dcSZachary Turner
22972c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22982c1f46dcSZachary Turner if (!generic)
22992c1f46dcSZachary Turner return lldb::ValueObjectSP();
23009a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
23012c1f46dcSZachary Turner if (!implementor)
23022c1f46dcSZachary Turner return lldb::ValueObjectSP();
23032c1f46dcSZachary Turner
23042c1f46dcSZachary Turner lldb::ValueObjectSP ret_val;
23052c1f46dcSZachary Turner {
2306b9c1b51eSKate Stone Locker py_lock(this,
2307b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23089a14adeaSPavel Labath PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2309b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) {
2310b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr =
231105495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
23122c1f46dcSZachary Turner if (sb_value_ptr == nullptr)
23132c1f46dcSZachary Turner Py_XDECREF(child_ptr);
23142c1f46dcSZachary Turner else
231505495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2316b9c1b51eSKate Stone } else {
23172c1f46dcSZachary Turner Py_XDECREF(child_ptr);
23182c1f46dcSZachary Turner }
23192c1f46dcSZachary Turner }
23202c1f46dcSZachary Turner
23212c1f46dcSZachary Turner return ret_val;
23222c1f46dcSZachary Turner }
23232c1f46dcSZachary Turner
GetIndexOfChildWithName(const StructuredData::ObjectSP & implementor_sp,const char * child_name)232463dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2325b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
23262c1f46dcSZachary Turner if (!implementor_sp)
23272c1f46dcSZachary Turner return UINT32_MAX;
23282c1f46dcSZachary Turner
23292c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23302c1f46dcSZachary Turner if (!generic)
23312c1f46dcSZachary Turner return UINT32_MAX;
23329a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
23332c1f46dcSZachary Turner if (!implementor)
23342c1f46dcSZachary Turner return UINT32_MAX;
23352c1f46dcSZachary Turner
23362c1f46dcSZachary Turner int ret_val = UINT32_MAX;
23372c1f46dcSZachary Turner
23382c1f46dcSZachary Turner {
2339b9c1b51eSKate Stone Locker py_lock(this,
2340b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
234105495c5dSJonas Devlieghere ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
23422c1f46dcSZachary Turner }
23432c1f46dcSZachary Turner
23442c1f46dcSZachary Turner return ret_val;
23452c1f46dcSZachary Turner }
23462c1f46dcSZachary Turner
UpdateSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)234763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2348b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) {
23492c1f46dcSZachary Turner bool ret_val = false;
23502c1f46dcSZachary Turner
23512c1f46dcSZachary Turner if (!implementor_sp)
23522c1f46dcSZachary Turner return ret_val;
23532c1f46dcSZachary Turner
23542c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23552c1f46dcSZachary Turner if (!generic)
23562c1f46dcSZachary Turner return ret_val;
23579a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
23582c1f46dcSZachary Turner if (!implementor)
23592c1f46dcSZachary Turner return ret_val;
23602c1f46dcSZachary Turner
23612c1f46dcSZachary Turner {
2362b9c1b51eSKate Stone Locker py_lock(this,
2363b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
236405495c5dSJonas Devlieghere ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
23652c1f46dcSZachary Turner }
23662c1f46dcSZachary Turner
23672c1f46dcSZachary Turner return ret_val;
23682c1f46dcSZachary Turner }
23692c1f46dcSZachary Turner
MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)237063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2371b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) {
23722c1f46dcSZachary Turner bool ret_val = false;
23732c1f46dcSZachary Turner
23742c1f46dcSZachary Turner if (!implementor_sp)
23752c1f46dcSZachary Turner return ret_val;
23762c1f46dcSZachary Turner
23772c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23782c1f46dcSZachary Turner if (!generic)
23792c1f46dcSZachary Turner return ret_val;
23809a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
23812c1f46dcSZachary Turner if (!implementor)
23822c1f46dcSZachary Turner return ret_val;
23832c1f46dcSZachary Turner
23842c1f46dcSZachary Turner {
2385b9c1b51eSKate Stone Locker py_lock(this,
2386b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
238705495c5dSJonas Devlieghere ret_val =
238805495c5dSJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
23892c1f46dcSZachary Turner }
23902c1f46dcSZachary Turner
23912c1f46dcSZachary Turner return ret_val;
23922c1f46dcSZachary Turner }
23932c1f46dcSZachary Turner
GetSyntheticValue(const StructuredData::ObjectSP & implementor_sp)239463dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2395b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) {
23962c1f46dcSZachary Turner lldb::ValueObjectSP ret_val(nullptr);
23972c1f46dcSZachary Turner
23982c1f46dcSZachary Turner if (!implementor_sp)
23992c1f46dcSZachary Turner return ret_val;
24002c1f46dcSZachary Turner
24012c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24022c1f46dcSZachary Turner if (!generic)
24032c1f46dcSZachary Turner return ret_val;
24049a14adeaSPavel Labath auto *implementor = static_cast<PyObject *>(generic->GetValue());
24052c1f46dcSZachary Turner if (!implementor)
24062c1f46dcSZachary Turner return ret_val;
24072c1f46dcSZachary Turner
24082c1f46dcSZachary Turner {
2409b9c1b51eSKate Stone Locker py_lock(this,
2410b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24119a14adeaSPavel Labath PyObject *child_ptr =
24129a14adeaSPavel Labath LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2413b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) {
2414b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr =
241505495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24162c1f46dcSZachary Turner if (sb_value_ptr == nullptr)
24172c1f46dcSZachary Turner Py_XDECREF(child_ptr);
24182c1f46dcSZachary Turner else
241905495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2420b9c1b51eSKate Stone } else {
24212c1f46dcSZachary Turner Py_XDECREF(child_ptr);
24222c1f46dcSZachary Turner }
24232c1f46dcSZachary Turner }
24242c1f46dcSZachary Turner
24252c1f46dcSZachary Turner return ret_val;
24262c1f46dcSZachary Turner }
24272c1f46dcSZachary Turner
GetSyntheticTypeName(const StructuredData::ObjectSP & implementor_sp)242863dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2429b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) {
2430b9c1b51eSKate Stone Locker py_lock(this,
2431b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24326eec8d6cSEnrico Granata
24336eec8d6cSEnrico Granata static char callee_name[] = "get_type_name";
24346eec8d6cSEnrico Granata
24356eec8d6cSEnrico Granata ConstString ret_val;
24366eec8d6cSEnrico Granata bool got_string = false;
24376eec8d6cSEnrico Granata std::string buffer;
24386eec8d6cSEnrico Granata
24396eec8d6cSEnrico Granata if (!implementor_sp)
24406eec8d6cSEnrico Granata return ret_val;
24416eec8d6cSEnrico Granata
24426eec8d6cSEnrico Granata StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24436eec8d6cSEnrico Granata if (!generic)
24446eec8d6cSEnrico Granata return ret_val;
2445b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
2446b9c1b51eSKate Stone (PyObject *)generic->GetValue());
24476eec8d6cSEnrico Granata if (!implementor.IsAllocated())
24486eec8d6cSEnrico Granata return ret_val;
24496eec8d6cSEnrico Granata
2450b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
2451b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
24526eec8d6cSEnrico Granata
24536eec8d6cSEnrico Granata if (PyErr_Occurred())
24546eec8d6cSEnrico Granata PyErr_Clear();
24556eec8d6cSEnrico Granata
24566eec8d6cSEnrico Granata if (!pmeth.IsAllocated())
24576eec8d6cSEnrico Granata return ret_val;
24586eec8d6cSEnrico Granata
2459b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
24606eec8d6cSEnrico Granata if (PyErr_Occurred())
24616eec8d6cSEnrico Granata PyErr_Clear();
24626eec8d6cSEnrico Granata return ret_val;
24636eec8d6cSEnrico Granata }
24646eec8d6cSEnrico Granata
24656eec8d6cSEnrico Granata if (PyErr_Occurred())
24666eec8d6cSEnrico Granata PyErr_Clear();
24676eec8d6cSEnrico Granata
24686eec8d6cSEnrico Granata // right now we know this function exists and is callable..
2469b9c1b51eSKate Stone PythonObject py_return(
2470b9c1b51eSKate Stone PyRefType::Owned,
2471b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr));
24726eec8d6cSEnrico Granata
24736eec8d6cSEnrico Granata // if it fails, print the error but otherwise go on
2474b9c1b51eSKate Stone if (PyErr_Occurred()) {
24756eec8d6cSEnrico Granata PyErr_Print();
24766eec8d6cSEnrico Granata PyErr_Clear();
24776eec8d6cSEnrico Granata }
24786eec8d6cSEnrico Granata
2479b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
24806eec8d6cSEnrico Granata PythonString py_string(PyRefType::Borrowed, py_return.get());
24816eec8d6cSEnrico Granata llvm::StringRef return_data(py_string.GetString());
2482b9c1b51eSKate Stone if (!return_data.empty()) {
24836eec8d6cSEnrico Granata buffer.assign(return_data.data(), return_data.size());
24846eec8d6cSEnrico Granata got_string = true;
24856eec8d6cSEnrico Granata }
24866eec8d6cSEnrico Granata }
24876eec8d6cSEnrico Granata
24886eec8d6cSEnrico Granata if (got_string)
24896eec8d6cSEnrico Granata ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
24906eec8d6cSEnrico Granata
24916eec8d6cSEnrico Granata return ret_val;
24926eec8d6cSEnrico Granata }
24936eec8d6cSEnrico Granata
RunScriptFormatKeyword(const char * impl_function,Process * process,std::string & output,Status & error)249463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
249563dd5d25SJonas Devlieghere const char *impl_function, Process *process, std::string &output,
249697206d57SZachary Turner Status &error) {
24972c1f46dcSZachary Turner bool ret_val;
2498b9c1b51eSKate Stone if (!process) {
24992c1f46dcSZachary Turner error.SetErrorString("no process");
25002c1f46dcSZachary Turner return false;
25012c1f46dcSZachary Turner }
2502b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) {
25032c1f46dcSZachary Turner error.SetErrorString("no function to execute");
25042c1f46dcSZachary Turner return false;
25052c1f46dcSZachary Turner }
250605495c5dSJonas Devlieghere
25072c1f46dcSZachary Turner {
2508b9c1b51eSKate Stone Locker py_lock(this,
2509b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
251005495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
25117f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
25127f09ab08SPavel Labath output);
25132c1f46dcSZachary Turner if (!ret_val)
25142c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed");
25152c1f46dcSZachary Turner }
25162c1f46dcSZachary Turner return ret_val;
25172c1f46dcSZachary Turner }
25182c1f46dcSZachary Turner
RunScriptFormatKeyword(const char * impl_function,Thread * thread,std::string & output,Status & error)251963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
252063dd5d25SJonas Devlieghere const char *impl_function, Thread *thread, std::string &output,
252197206d57SZachary Turner Status &error) {
2522b9c1b51eSKate Stone if (!thread) {
25232c1f46dcSZachary Turner error.SetErrorString("no thread");
25242c1f46dcSZachary Turner return false;
25252c1f46dcSZachary Turner }
2526b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) {
25272c1f46dcSZachary Turner error.SetErrorString("no function to execute");
25282c1f46dcSZachary Turner return false;
25292c1f46dcSZachary Turner }
253005495c5dSJonas Devlieghere
2531b9c1b51eSKate Stone Locker py_lock(this,
2532b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25337406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
25347406d236SPavel Labath impl_function, m_dictionary_name.c_str(),
25357406d236SPavel Labath thread->shared_from_this())) {
25367406d236SPavel Labath output = std::move(*result);
25377406d236SPavel Labath return true;
25382c1f46dcSZachary Turner }
25397406d236SPavel Labath error.SetErrorString("python script evaluation failed");
25407406d236SPavel Labath return false;
25412c1f46dcSZachary Turner }
25422c1f46dcSZachary Turner
RunScriptFormatKeyword(const char * impl_function,Target * target,std::string & output,Status & error)254363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
254463dd5d25SJonas Devlieghere const char *impl_function, Target *target, std::string &output,
254597206d57SZachary Turner Status &error) {
25462c1f46dcSZachary Turner bool ret_val;
2547b9c1b51eSKate Stone if (!target) {
25482c1f46dcSZachary Turner error.SetErrorString("no thread");
25492c1f46dcSZachary Turner return false;
25502c1f46dcSZachary Turner }
2551b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) {
25522c1f46dcSZachary Turner error.SetErrorString("no function to execute");
25532c1f46dcSZachary Turner return false;
25542c1f46dcSZachary Turner }
255505495c5dSJonas Devlieghere
25562c1f46dcSZachary Turner {
25572c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this());
2558b9c1b51eSKate Stone Locker py_lock(this,
2559b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
256005495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2561b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), target_sp, output);
25622c1f46dcSZachary Turner if (!ret_val)
25632c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed");
25642c1f46dcSZachary Turner }
25652c1f46dcSZachary Turner return ret_val;
25662c1f46dcSZachary Turner }
25672c1f46dcSZachary Turner
RunScriptFormatKeyword(const char * impl_function,StackFrame * frame,std::string & output,Status & error)256863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
256963dd5d25SJonas Devlieghere const char *impl_function, StackFrame *frame, std::string &output,
257097206d57SZachary Turner Status &error) {
2571b9c1b51eSKate Stone if (!frame) {
25722c1f46dcSZachary Turner error.SetErrorString("no frame");
25732c1f46dcSZachary Turner return false;
25742c1f46dcSZachary Turner }
2575b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) {
25762c1f46dcSZachary Turner error.SetErrorString("no function to execute");
25772c1f46dcSZachary Turner return false;
25782c1f46dcSZachary Turner }
257905495c5dSJonas Devlieghere
2580b9c1b51eSKate Stone Locker py_lock(this,
2581b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25827406d236SPavel Labath if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
25837406d236SPavel Labath impl_function, m_dictionary_name.c_str(),
25847406d236SPavel Labath frame->shared_from_this())) {
25857406d236SPavel Labath output = std::move(*result);
25867406d236SPavel Labath return true;
25872c1f46dcSZachary Turner }
25887406d236SPavel Labath error.SetErrorString("python script evaluation failed");
25897406d236SPavel Labath return false;
25902c1f46dcSZachary Turner }
25912c1f46dcSZachary Turner
RunScriptFormatKeyword(const char * impl_function,ValueObject * value,std::string & output,Status & error)259263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
259363dd5d25SJonas Devlieghere const char *impl_function, ValueObject *value, std::string &output,
259497206d57SZachary Turner Status &error) {
25952c1f46dcSZachary Turner bool ret_val;
2596b9c1b51eSKate Stone if (!value) {
25972c1f46dcSZachary Turner error.SetErrorString("no value");
25982c1f46dcSZachary Turner return false;
25992c1f46dcSZachary Turner }
2600b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) {
26012c1f46dcSZachary Turner error.SetErrorString("no function to execute");
26022c1f46dcSZachary Turner return false;
26032c1f46dcSZachary Turner }
260405495c5dSJonas Devlieghere
26052c1f46dcSZachary Turner {
2606b9c1b51eSKate Stone Locker py_lock(this,
2607b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
260805495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordValue(
26097f09ab08SPavel Labath impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
26102c1f46dcSZachary Turner if (!ret_val)
26112c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed");
26122c1f46dcSZachary Turner }
26132c1f46dcSZachary Turner return ret_val;
26142c1f46dcSZachary Turner }
26152c1f46dcSZachary Turner
replace_all(std::string & str,const std::string & oldStr,const std::string & newStr)2616b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2617b9c1b51eSKate Stone const std::string &newStr) {
26182c1f46dcSZachary Turner size_t pos = 0;
26192c1f46dcSZachary Turner uint64_t matches = 0;
2620b9c1b51eSKate Stone while ((pos = str.find(oldStr, pos)) != std::string::npos) {
26212c1f46dcSZachary Turner matches++;
26222c1f46dcSZachary Turner str.replace(pos, oldStr.length(), newStr);
26232c1f46dcSZachary Turner pos += newStr.length();
26242c1f46dcSZachary Turner }
26252c1f46dcSZachary Turner return matches;
26262c1f46dcSZachary Turner }
26272c1f46dcSZachary Turner
LoadScriptingModule(const char * pathname,const LoadScriptOptions & options,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)262863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2629f9517353SJonas Devlieghere const char *pathname, const LoadScriptOptions &options,
2630f9517353SJonas Devlieghere lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2631f9517353SJonas Devlieghere FileSpec extra_search_dir) {
26323b33b416SJonas Devlieghere namespace fs = llvm::sys::fs;
263300bb397bSJonas Devlieghere namespace path = llvm::sys::path;
26343b33b416SJonas Devlieghere
2635f9517353SJonas Devlieghere ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2636f9517353SJonas Devlieghere .SetEnableIO(!options.GetSilent())
2637f9517353SJonas Devlieghere .SetSetLLDBGlobals(false);
2638f9517353SJonas Devlieghere
2639b9c1b51eSKate Stone if (!pathname || !pathname[0]) {
2640e83d47f6SJim Ingham error.SetErrorString("empty path");
26412c1f46dcSZachary Turner return false;
26422c1f46dcSZachary Turner }
26432c1f46dcSZachary Turner
2644f9517353SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2645f9517353SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2646f9517353SJonas Devlieghere exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2647f9517353SJonas Devlieghere
2648f9517353SJonas Devlieghere if (!io_redirect_or_error) {
2649f9517353SJonas Devlieghere error = io_redirect_or_error.takeError();
2650f9517353SJonas Devlieghere return false;
2651f9517353SJonas Devlieghere }
2652f9517353SJonas Devlieghere
2653f9517353SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
26542c1f46dcSZachary Turner
2655f9f36097SAdrian McCarthy // Before executing Python code, lock the GIL.
265620b52c33SJonas Devlieghere Locker py_lock(this,
265720b52c33SJonas Devlieghere Locker::AcquireLock |
2658f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::InitSession : 0) |
2659f9517353SJonas Devlieghere Locker::NoSTDIN,
2660b9c1b51eSKate Stone Locker::FreeAcquiredLock |
2661f9517353SJonas Devlieghere (options.GetInitSession() ? Locker::TearDownSession : 0),
2662f9517353SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2663f9517353SJonas Devlieghere io_redirect.GetErrorFile());
26642c1f46dcSZachary Turner
2665f9517353SJonas Devlieghere auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
266600bb397bSJonas Devlieghere if (directory.empty()) {
266700bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>(
266800bb397bSJonas Devlieghere "invalid directory name", llvm::inconvertibleErrorCode());
266942a9da7bSStefan Granitz }
267042a9da7bSStefan Granitz
2671f9f36097SAdrian McCarthy replace_all(directory, "\\", "\\\\");
26722c1f46dcSZachary Turner replace_all(directory, "'", "\\'");
26732c1f46dcSZachary Turner
267400bb397bSJonas Devlieghere // Make sure that Python has "directory" in the search path.
26752c1f46dcSZachary Turner StreamString command_stream;
2676b9c1b51eSKate Stone command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2677b9c1b51eSKate Stone "sys.path.insert(1,'%s');\n\n",
2678b9c1b51eSKate Stone directory.c_str(), directory.c_str());
2679b9c1b51eSKate Stone bool syspath_retval =
2680f9517353SJonas Devlieghere ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2681b9c1b51eSKate Stone if (!syspath_retval) {
268200bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>(
268300bb397bSJonas Devlieghere "Python sys.path handling failed", llvm::inconvertibleErrorCode());
26842c1f46dcSZachary Turner }
26852c1f46dcSZachary Turner
268600bb397bSJonas Devlieghere return llvm::Error::success();
268700bb397bSJonas Devlieghere };
268800bb397bSJonas Devlieghere
268900bb397bSJonas Devlieghere std::string module_name(pathname);
2690d6e80578SJonas Devlieghere bool possible_package = false;
269100bb397bSJonas Devlieghere
269200bb397bSJonas Devlieghere if (extra_search_dir) {
269300bb397bSJonas Devlieghere if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
269400bb397bSJonas Devlieghere error = std::move(e);
269500bb397bSJonas Devlieghere return false;
269600bb397bSJonas Devlieghere }
269700bb397bSJonas Devlieghere } else {
269800bb397bSJonas Devlieghere FileSpec module_file(pathname);
269900bb397bSJonas Devlieghere FileSystem::Instance().Resolve(module_file);
270000bb397bSJonas Devlieghere
270100bb397bSJonas Devlieghere fs::file_status st;
270200bb397bSJonas Devlieghere std::error_code ec = status(module_file.GetPath(), st);
270300bb397bSJonas Devlieghere
270400bb397bSJonas Devlieghere if (ec || st.type() == fs::file_type::status_error ||
270500bb397bSJonas Devlieghere st.type() == fs::file_type::type_unknown ||
270600bb397bSJonas Devlieghere st.type() == fs::file_type::file_not_found) {
270700bb397bSJonas Devlieghere // if not a valid file of any sort, check if it might be a filename still
270800bb397bSJonas Devlieghere // dot can't be used but / and \ can, and if either is found, reject
270900bb397bSJonas Devlieghere if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2710e83d47f6SJim Ingham error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
271100bb397bSJonas Devlieghere return false;
271200bb397bSJonas Devlieghere }
271300bb397bSJonas Devlieghere // Not a filename, probably a package of some sort, let it go through.
2714d6e80578SJonas Devlieghere possible_package = true;
271500bb397bSJonas Devlieghere } else if (is_directory(st) || is_regular_file(st)) {
271600bb397bSJonas Devlieghere if (module_file.GetDirectory().IsEmpty()) {
2717e83d47f6SJim Ingham error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
271800bb397bSJonas Devlieghere return false;
271900bb397bSJonas Devlieghere }
272000bb397bSJonas Devlieghere if (llvm::Error e =
272100bb397bSJonas Devlieghere ExtendSysPath(module_file.GetDirectory().GetCString())) {
272200bb397bSJonas Devlieghere error = std::move(e);
272300bb397bSJonas Devlieghere return false;
272400bb397bSJonas Devlieghere }
272500bb397bSJonas Devlieghere module_name = module_file.GetFilename().GetCString();
2726b9c1b51eSKate Stone } else {
27272c1f46dcSZachary Turner error.SetErrorString("no known way to import this module specification");
27282c1f46dcSZachary Turner return false;
27292c1f46dcSZachary Turner }
273000bb397bSJonas Devlieghere }
27312c1f46dcSZachary Turner
27321197ee35SJonas Devlieghere // Strip .py or .pyc extension
273300bb397bSJonas Devlieghere llvm::StringRef extension = llvm::sys::path::extension(module_name);
27341197ee35SJonas Devlieghere if (!extension.empty()) {
27351197ee35SJonas Devlieghere if (extension == ".py")
273600bb397bSJonas Devlieghere module_name.resize(module_name.length() - 3);
27371197ee35SJonas Devlieghere else if (extension == ".pyc")
273800bb397bSJonas Devlieghere module_name.resize(module_name.length() - 4);
27391197ee35SJonas Devlieghere }
27401197ee35SJonas Devlieghere
2741d6e80578SJonas Devlieghere if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2742d6e80578SJonas Devlieghere error.SetErrorStringWithFormat(
2743d6e80578SJonas Devlieghere "Python does not allow dots in module names: %s", module_name.c_str());
2744d6e80578SJonas Devlieghere return false;
2745d6e80578SJonas Devlieghere }
2746d6e80578SJonas Devlieghere
2747d6e80578SJonas Devlieghere if (module_name.find('-') != llvm::StringRef::npos) {
2748d6e80578SJonas Devlieghere error.SetErrorStringWithFormat(
2749d6e80578SJonas Devlieghere "Python discourages dashes in module names: %s", module_name.c_str());
2750d6e80578SJonas Devlieghere return false;
2751d6e80578SJonas Devlieghere }
2752d6e80578SJonas Devlieghere
2753f9517353SJonas Devlieghere // Check if the module is already imported.
275400bb397bSJonas Devlieghere StreamString command_stream;
27552c1f46dcSZachary Turner command_stream.Clear();
275600bb397bSJonas Devlieghere command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
27572c1f46dcSZachary Turner bool does_contain = false;
2758f9517353SJonas Devlieghere // This call will succeed if the module was ever imported in any Debugger in
2759f9517353SJonas Devlieghere // the lifetime of the process in which this LLDB framework is living.
2760f9517353SJonas Devlieghere const bool does_contain_executed = ExecuteOneLineWithReturn(
2761b9c1b51eSKate Stone command_stream.GetData(),
2762f9517353SJonas Devlieghere ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2763f9517353SJonas Devlieghere
2764f9517353SJonas Devlieghere const bool was_imported_globally = does_contain_executed && does_contain;
2765612384f6SJonas Devlieghere const bool was_imported_locally =
2766612384f6SJonas Devlieghere GetSessionDictionary()
276700bb397bSJonas Devlieghere .GetItemForKey(PythonString(module_name))
2768b9c1b51eSKate Stone .IsAllocated();
27692c1f46dcSZachary Turner
27702c1f46dcSZachary Turner // now actually do the import
27712c1f46dcSZachary Turner command_stream.Clear();
27722c1f46dcSZachary Turner
2773612384f6SJonas Devlieghere if (was_imported_globally || was_imported_locally) {
27742c1f46dcSZachary Turner if (!was_imported_locally)
277500bb397bSJonas Devlieghere command_stream.Printf("import %s ; reload_module(%s)",
277600bb397bSJonas Devlieghere module_name.c_str(), module_name.c_str());
27772c1f46dcSZachary Turner else
277800bb397bSJonas Devlieghere command_stream.Printf("reload_module(%s)", module_name.c_str());
2779b9c1b51eSKate Stone } else
278000bb397bSJonas Devlieghere command_stream.Printf("import %s", module_name.c_str());
27812c1f46dcSZachary Turner
2782f9517353SJonas Devlieghere error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
27832c1f46dcSZachary Turner if (error.Fail())
27842c1f46dcSZachary Turner return false;
27852c1f46dcSZachary Turner
27862c1f46dcSZachary Turner // if we are here, everything worked
27872c1f46dcSZachary Turner // call __lldb_init_module(debugger,dict)
278800bb397bSJonas Devlieghere if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
27897406d236SPavel Labath m_dictionary_name.c_str(),
27907406d236SPavel Labath m_debugger.shared_from_this())) {
27912c1f46dcSZachary Turner error.SetErrorString("calling __lldb_init_module failed");
27922c1f46dcSZachary Turner return false;
27932c1f46dcSZachary Turner }
27942c1f46dcSZachary Turner
2795b9c1b51eSKate Stone if (module_sp) {
27962c1f46dcSZachary Turner // everything went just great, now set the module object
27972c1f46dcSZachary Turner command_stream.Clear();
279800bb397bSJonas Devlieghere command_stream.Printf("%s", module_name.c_str());
27992c1f46dcSZachary Turner void *module_pyobj = nullptr;
2800b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(
2801b9c1b51eSKate Stone command_stream.GetData(),
2802f9517353SJonas Devlieghere ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2803f9517353SJonas Devlieghere exc_options) &&
2804b9c1b51eSKate Stone module_pyobj)
2805c154f397SPavel Labath *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2806c154f397SPavel Labath PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
28072c1f46dcSZachary Turner }
28082c1f46dcSZachary Turner
28092c1f46dcSZachary Turner return true;
28102c1f46dcSZachary Turner }
28112c1f46dcSZachary Turner
IsReservedWord(const char * word)281263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
28132c1f46dcSZachary Turner if (!word || !word[0])
28142c1f46dcSZachary Turner return false;
28152c1f46dcSZachary Turner
28162c1f46dcSZachary Turner llvm::StringRef word_sr(word);
28172c1f46dcSZachary Turner
281805097246SAdrian Prantl // filter out a few characters that would just confuse us and that are
281905097246SAdrian Prantl // clearly not keyword material anyway
282010b113e8SJonas Devlieghere if (word_sr.find('"') != llvm::StringRef::npos ||
282110b113e8SJonas Devlieghere word_sr.find('\'') != llvm::StringRef::npos)
28222c1f46dcSZachary Turner return false;
28232c1f46dcSZachary Turner
28242c1f46dcSZachary Turner StreamString command_stream;
28252c1f46dcSZachary Turner command_stream.Printf("keyword.iskeyword('%s')", word);
28262c1f46dcSZachary Turner bool result;
28272c1f46dcSZachary Turner ExecuteScriptOptions options;
28282c1f46dcSZachary Turner options.SetEnableIO(false);
28292c1f46dcSZachary Turner options.SetMaskoutErrors(true);
28302c1f46dcSZachary Turner options.SetSetLLDBGlobals(false);
2831b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(command_stream.GetData(),
2832b9c1b51eSKate Stone ScriptInterpreter::eScriptReturnTypeBool,
2833b9c1b51eSKate Stone &result, options))
28342c1f46dcSZachary Turner return result;
28352c1f46dcSZachary Turner return false;
28362c1f46dcSZachary Turner }
28372c1f46dcSZachary Turner
SynchronicityHandler(lldb::DebuggerSP debugger_sp,ScriptedCommandSynchronicity synchro)283863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2839b9c1b51eSKate Stone lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2840b9c1b51eSKate Stone : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2841b9c1b51eSKate Stone m_old_asynch(debugger_sp->GetAsyncExecution()) {
28422c1f46dcSZachary Turner if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
28432c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(false);
28442c1f46dcSZachary Turner else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
28452c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(true);
28462c1f46dcSZachary Turner }
28472c1f46dcSZachary Turner
~SynchronicityHandler()284863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
28492c1f46dcSZachary Turner if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
28502c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(m_old_asynch);
28512c1f46dcSZachary Turner }
28522c1f46dcSZachary Turner
RunScriptBasedCommand(const char * impl_function,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)285363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28544d51a902SRaphael Isemann const char *impl_function, llvm::StringRef args,
28552c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity,
285697206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2857b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) {
2858b9c1b51eSKate Stone if (!impl_function) {
28592c1f46dcSZachary Turner error.SetErrorString("no function to execute");
28602c1f46dcSZachary Turner return false;
28612c1f46dcSZachary Turner }
28622c1f46dcSZachary Turner
28638d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28642c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28652c1f46dcSZachary Turner
2866b9c1b51eSKate Stone if (!debugger_sp.get()) {
28672c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer");
28682c1f46dcSZachary Turner return false;
28692c1f46dcSZachary Turner }
28702c1f46dcSZachary Turner
28712c1f46dcSZachary Turner bool ret_val = false;
28722c1f46dcSZachary Turner
28732c1f46dcSZachary Turner std::string err_msg;
28742c1f46dcSZachary Turner
28752c1f46dcSZachary Turner {
28762c1f46dcSZachary Turner Locker py_lock(this,
2877b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession |
2878b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
28792c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession);
28802c1f46dcSZachary Turner
2881b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity);
28822c1f46dcSZachary Turner
28834d51a902SRaphael Isemann std::string args_str = args.str();
288405495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommand(
288505495c5dSJonas Devlieghere impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
288605495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp);
28872c1f46dcSZachary Turner }
28882c1f46dcSZachary Turner
28892c1f46dcSZachary Turner if (!ret_val)
28902c1f46dcSZachary Turner error.SetErrorString("unable to execute script function");
28912c1f46dcSZachary Turner else
28922c1f46dcSZachary Turner error.Clear();
28932c1f46dcSZachary Turner
28942c1f46dcSZachary Turner return ret_val;
28952c1f46dcSZachary Turner }
28962c1f46dcSZachary Turner
RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)289763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28984d51a902SRaphael Isemann StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
28992c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity,
290097206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2901b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) {
2902b9c1b51eSKate Stone if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
29032c1f46dcSZachary Turner error.SetErrorString("no function to execute");
29042c1f46dcSZachary Turner return false;
29052c1f46dcSZachary Turner }
29062c1f46dcSZachary Turner
29078d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29082c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29092c1f46dcSZachary Turner
2910b9c1b51eSKate Stone if (!debugger_sp.get()) {
29112c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer");
29122c1f46dcSZachary Turner return false;
29132c1f46dcSZachary Turner }
29142c1f46dcSZachary Turner
29152c1f46dcSZachary Turner bool ret_val = false;
29162c1f46dcSZachary Turner
29172c1f46dcSZachary Turner std::string err_msg;
29182c1f46dcSZachary Turner
29192c1f46dcSZachary Turner {
29202c1f46dcSZachary Turner Locker py_lock(this,
2921b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession |
2922b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29232c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession);
29242c1f46dcSZachary Turner
2925b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29262c1f46dcSZachary Turner
29274d51a902SRaphael Isemann std::string args_str = args.str();
29289a14adeaSPavel Labath ret_val = LLDBSwigPythonCallCommandObject(
29299a14adeaSPavel Labath static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
29309a14adeaSPavel Labath args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
29312c1f46dcSZachary Turner }
29322c1f46dcSZachary Turner
29332c1f46dcSZachary Turner if (!ret_val)
29342c1f46dcSZachary Turner error.SetErrorString("unable to execute script function");
29352c1f46dcSZachary Turner else
29362c1f46dcSZachary Turner error.Clear();
29372c1f46dcSZachary Turner
29382c1f46dcSZachary Turner return ret_val;
29392c1f46dcSZachary Turner }
29402c1f46dcSZachary Turner
294193571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
294293571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
294393571c3cSJonas Devlieghere /// value is None.
GetDocumentationForItem(const char * item,std::string & dest)294463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2945b9c1b51eSKate Stone std::string &dest) {
29462c1f46dcSZachary Turner dest.clear();
294793571c3cSJonas Devlieghere
29482c1f46dcSZachary Turner if (!item || !*item)
29492c1f46dcSZachary Turner return false;
295093571c3cSJonas Devlieghere
29512c1f46dcSZachary Turner std::string command(item);
29522c1f46dcSZachary Turner command += ".__doc__";
29532c1f46dcSZachary Turner
295493571c3cSJonas Devlieghere // Python is going to point this to valid data if ExecuteOneLineWithReturn
295593571c3cSJonas Devlieghere // returns successfully.
295693571c3cSJonas Devlieghere char *result_ptr = nullptr;
29572c1f46dcSZachary Turner
2958b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(
295993571c3cSJonas Devlieghere command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
29602c1f46dcSZachary Turner &result_ptr,
2961fd2433e1SJonas Devlieghere ExecuteScriptOptions().SetEnableIO(false))) {
29622c1f46dcSZachary Turner if (result_ptr)
29632c1f46dcSZachary Turner dest.assign(result_ptr);
29642c1f46dcSZachary Turner return true;
29652c1f46dcSZachary Turner }
296693571c3cSJonas Devlieghere
296793571c3cSJonas Devlieghere StreamString str_stream;
296893571c3cSJonas Devlieghere str_stream << "Function " << item
296993571c3cSJonas Devlieghere << " was not found. Containing module might be missing.";
297093571c3cSJonas Devlieghere dest = std::string(str_stream.GetString());
297193571c3cSJonas Devlieghere
297293571c3cSJonas Devlieghere return false;
29732c1f46dcSZachary Turner }
29742c1f46dcSZachary Turner
GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)297563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2976b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
29772c1f46dcSZachary Turner dest.clear();
29782c1f46dcSZachary Turner
2979b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
29802c1f46dcSZachary Turner
29812c1f46dcSZachary Turner static char callee_name[] = "get_short_help";
29822c1f46dcSZachary Turner
29832c1f46dcSZachary Turner if (!cmd_obj_sp)
29842c1f46dcSZachary Turner return false;
29852c1f46dcSZachary Turner
2986b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
2987b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue());
29882c1f46dcSZachary Turner
2989f8b22f8fSZachary Turner if (!implementor.IsAllocated())
29902c1f46dcSZachary Turner return false;
29912c1f46dcSZachary Turner
2992b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
2993b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
29942c1f46dcSZachary Turner
29952c1f46dcSZachary Turner if (PyErr_Occurred())
29962c1f46dcSZachary Turner PyErr_Clear();
29972c1f46dcSZachary Turner
2998f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
29992c1f46dcSZachary Turner return false;
30002c1f46dcSZachary Turner
3001b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
30022c1f46dcSZachary Turner if (PyErr_Occurred())
30032c1f46dcSZachary Turner PyErr_Clear();
30042c1f46dcSZachary Turner return false;
30052c1f46dcSZachary Turner }
30062c1f46dcSZachary Turner
30072c1f46dcSZachary Turner if (PyErr_Occurred())
30082c1f46dcSZachary Turner PyErr_Clear();
30092c1f46dcSZachary Turner
301093571c3cSJonas Devlieghere // Right now we know this function exists and is callable.
3011b9c1b51eSKate Stone PythonObject py_return(
3012b9c1b51eSKate Stone PyRefType::Owned,
3013b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30142c1f46dcSZachary Turner
301593571c3cSJonas Devlieghere // If it fails, print the error but otherwise go on.
3016b9c1b51eSKate Stone if (PyErr_Occurred()) {
30172c1f46dcSZachary Turner PyErr_Print();
30182c1f46dcSZachary Turner PyErr_Clear();
30192c1f46dcSZachary Turner }
30202c1f46dcSZachary Turner
3021b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3022f8b22f8fSZachary Turner PythonString py_string(PyRefType::Borrowed, py_return.get());
302322c8efcdSZachary Turner llvm::StringRef return_data(py_string.GetString());
302422c8efcdSZachary Turner dest.assign(return_data.data(), return_data.size());
302593571c3cSJonas Devlieghere return true;
30262c1f46dcSZachary Turner }
302793571c3cSJonas Devlieghere
302893571c3cSJonas Devlieghere return false;
30292c1f46dcSZachary Turner }
30302c1f46dcSZachary Turner
GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp)303163dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3032b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp) {
30332c1f46dcSZachary Turner uint32_t result = 0;
30342c1f46dcSZachary Turner
3035b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30362c1f46dcSZachary Turner
30372c1f46dcSZachary Turner static char callee_name[] = "get_flags";
30382c1f46dcSZachary Turner
30392c1f46dcSZachary Turner if (!cmd_obj_sp)
30402c1f46dcSZachary Turner return result;
30412c1f46dcSZachary Turner
3042b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
3043b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue());
30442c1f46dcSZachary Turner
3045f8b22f8fSZachary Turner if (!implementor.IsAllocated())
30462c1f46dcSZachary Turner return result;
30472c1f46dcSZachary Turner
3048b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
3049b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
30502c1f46dcSZachary Turner
30512c1f46dcSZachary Turner if (PyErr_Occurred())
30522c1f46dcSZachary Turner PyErr_Clear();
30532c1f46dcSZachary Turner
3054f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
30552c1f46dcSZachary Turner return result;
30562c1f46dcSZachary Turner
3057b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
30582c1f46dcSZachary Turner if (PyErr_Occurred())
30592c1f46dcSZachary Turner PyErr_Clear();
30602c1f46dcSZachary Turner return result;
30612c1f46dcSZachary Turner }
30622c1f46dcSZachary Turner
30632c1f46dcSZachary Turner if (PyErr_Occurred())
30642c1f46dcSZachary Turner PyErr_Clear();
30652c1f46dcSZachary Turner
306652712d3fSLawrence D'Anna long long py_return = unwrapOrSetPythonException(
306752712d3fSLawrence D'Anna As<long long>(implementor.CallMethod(callee_name)));
30682c1f46dcSZachary Turner
30692c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
3070b9c1b51eSKate Stone if (PyErr_Occurred()) {
30712c1f46dcSZachary Turner PyErr_Print();
30722c1f46dcSZachary Turner PyErr_Clear();
307352712d3fSLawrence D'Anna } else {
307452712d3fSLawrence D'Anna result = py_return;
30752c1f46dcSZachary Turner }
30762c1f46dcSZachary Turner
30772c1f46dcSZachary Turner return result;
30782c1f46dcSZachary Turner }
30792c1f46dcSZachary Turner
GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)308063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3081b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30822c1f46dcSZachary Turner bool got_string = false;
30832c1f46dcSZachary Turner dest.clear();
30842c1f46dcSZachary Turner
3085b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30862c1f46dcSZachary Turner
30872c1f46dcSZachary Turner static char callee_name[] = "get_long_help";
30882c1f46dcSZachary Turner
30892c1f46dcSZachary Turner if (!cmd_obj_sp)
30902c1f46dcSZachary Turner return false;
30912c1f46dcSZachary Turner
3092b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed,
3093b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue());
30942c1f46dcSZachary Turner
3095f8b22f8fSZachary Turner if (!implementor.IsAllocated())
30962c1f46dcSZachary Turner return false;
30972c1f46dcSZachary Turner
3098b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned,
3099b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name));
31002c1f46dcSZachary Turner
31012c1f46dcSZachary Turner if (PyErr_Occurred())
31022c1f46dcSZachary Turner PyErr_Clear();
31032c1f46dcSZachary Turner
3104f8b22f8fSZachary Turner if (!pmeth.IsAllocated())
31052c1f46dcSZachary Turner return false;
31062c1f46dcSZachary Turner
3107b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) {
31082c1f46dcSZachary Turner if (PyErr_Occurred())
31092c1f46dcSZachary Turner PyErr_Clear();
31102c1f46dcSZachary Turner
31112c1f46dcSZachary Turner return false;
31122c1f46dcSZachary Turner }
31132c1f46dcSZachary Turner
31142c1f46dcSZachary Turner if (PyErr_Occurred())
31152c1f46dcSZachary Turner PyErr_Clear();
31162c1f46dcSZachary Turner
31172c1f46dcSZachary Turner // right now we know this function exists and is callable..
3118b9c1b51eSKate Stone PythonObject py_return(
3119b9c1b51eSKate Stone PyRefType::Owned,
3120b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31212c1f46dcSZachary Turner
31222c1f46dcSZachary Turner // if it fails, print the error but otherwise go on
3123b9c1b51eSKate Stone if (PyErr_Occurred()) {
31242c1f46dcSZachary Turner PyErr_Print();
31252c1f46dcSZachary Turner PyErr_Clear();
31262c1f46dcSZachary Turner }
31272c1f46dcSZachary Turner
3128b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3129f8b22f8fSZachary Turner PythonString str(PyRefType::Borrowed, py_return.get());
313022c8efcdSZachary Turner llvm::StringRef str_data(str.GetString());
313122c8efcdSZachary Turner dest.assign(str_data.data(), str_data.size());
31322c1f46dcSZachary Turner got_string = true;
31332c1f46dcSZachary Turner }
31342c1f46dcSZachary Turner
31352c1f46dcSZachary Turner return got_string;
31362c1f46dcSZachary Turner }
31372c1f46dcSZachary Turner
31382c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
AcquireInterpreterLock()313963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3140b9c1b51eSKate Stone std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3141b9c1b51eSKate Stone this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
31422c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession));
31432c1f46dcSZachary Turner return py_lock;
31442c1f46dcSZachary Turner }
31452c1f46dcSZachary Turner
Initialize()3146eb5c0ea6SJonas Devlieghere void ScriptInterpreterPythonImpl::Initialize() {
31475c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER();
31482c1f46dcSZachary Turner
3149b9c1b51eSKate Stone // RAII-based initialization which correctly handles multiple-initialization,
315005097246SAdrian Prantl // version- specific differences among Python 2 and Python 3, and saving and
315105097246SAdrian Prantl // restoring various other pieces of state that can get mucked with during
315205097246SAdrian Prantl // initialization.
3153079fe48aSZachary Turner InitializePythonRAII initialize_guard;
31542c1f46dcSZachary Turner
315505495c5dSJonas Devlieghere LLDBSwigPyInit();
31562c1f46dcSZachary Turner
3157b9c1b51eSKate Stone // Update the path python uses to search for modules to include the current
3158b9c1b51eSKate Stone // directory.
31592c1f46dcSZachary Turner
31602c1f46dcSZachary Turner PyRun_SimpleString("import sys");
31612c1f46dcSZachary Turner AddToSysPath(AddLocation::End, ".");
31622c1f46dcSZachary Turner
3163b9c1b51eSKate Stone // Don't denormalize paths when calling file_spec.GetPath(). On platforms
316405097246SAdrian Prantl // that use a backslash as the path separator, this will result in executing
316505097246SAdrian Prantl // python code containing paths with unescaped backslashes. But Python also
316605097246SAdrian Prantl // accepts forward slashes, so to make life easier we just use that.
31672df331b0SPavel Labath if (FileSpec file_spec = GetPythonDir())
31682c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
316960f028ffSPavel Labath if (FileSpec file_spec = HostInfo::GetShlibDir())
31702c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31712c1f46dcSZachary Turner
3172b9c1b51eSKate Stone PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3173b9c1b51eSKate Stone "lldb.embedded_interpreter; from "
3174b9c1b51eSKate Stone "lldb.embedded_interpreter import run_python_interpreter; "
3175b9c1b51eSKate Stone "from lldb.embedded_interpreter import run_one_line");
3176049ae930SJonas Devlieghere
3177049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
3178049ae930SJonas Devlieghere // Python will not just overwrite its internal SIGINT handler but also the
3179049ae930SJonas Devlieghere // one from the process. Backup the current SIGINT handler to prevent that
3180049ae930SJonas Devlieghere // Python deletes it.
3181049ae930SJonas Devlieghere RestoreSignalHandlerScope save_sigint(SIGINT);
3182049ae930SJonas Devlieghere
3183049ae930SJonas Devlieghere // Setup a default SIGINT signal handler that works the same way as the
3184049ae930SJonas Devlieghere // normal Python REPL signal handler which raises a KeyboardInterrupt.
3185049ae930SJonas Devlieghere // Also make sure to not pollute the user's REPL with the signal module nor
3186049ae930SJonas Devlieghere // our utility function.
3187049ae930SJonas Devlieghere PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3188049ae930SJonas Devlieghere " import signal;\n"
3189049ae930SJonas Devlieghere " def signal_handler(sig, frame):\n"
3190049ae930SJonas Devlieghere " raise KeyboardInterrupt()\n"
3191049ae930SJonas Devlieghere " signal.signal(signal.SIGINT, signal_handler);\n"
3192049ae930SJonas Devlieghere "lldb_setup_sigint_handler();\n"
3193049ae930SJonas Devlieghere "del lldb_setup_sigint_handler\n");
3194049ae930SJonas Devlieghere #endif
31952c1f46dcSZachary Turner }
31962c1f46dcSZachary Turner
AddToSysPath(AddLocation location,std::string path)319763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3198b9c1b51eSKate Stone std::string path) {
31992c1f46dcSZachary Turner std::string path_copy;
32002c1f46dcSZachary Turner
32012c1f46dcSZachary Turner std::string statement;
3202b9c1b51eSKate Stone if (location == AddLocation::Beginning) {
32032c1f46dcSZachary Turner statement.assign("sys.path.insert(0,\"");
32042c1f46dcSZachary Turner statement.append(path);
32052c1f46dcSZachary Turner statement.append("\")");
3206b9c1b51eSKate Stone } else {
32072c1f46dcSZachary Turner statement.assign("sys.path.append(\"");
32082c1f46dcSZachary Turner statement.append(path);
32092c1f46dcSZachary Turner statement.append("\")");
32102c1f46dcSZachary Turner }
32112c1f46dcSZachary Turner PyRun_SimpleString(statement.c_str());
32122c1f46dcSZachary Turner }
32132c1f46dcSZachary Turner
3214bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3215bcadb5a3SPavel Labath // place to call it). Calling Py_Finalize here causes test suite runs to seg
3216bcadb5a3SPavel Labath // fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3217bcadb5a3SPavel Labath // be called 'at_exit'. When the test suite Python harness finishes up, it
3218bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3219bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3220bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
322163dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
322263dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
322363dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
322463dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3225bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3226bcadb5a3SPavel Labath // when the process exits).
3227bcadb5a3SPavel Labath //
322863dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3229d68983e3SPavel Labath
32304e26cf2cSJonas Devlieghere #endif
3231