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"
41*c34698a8SPavel 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 #if PY_MAJOR_VERSION >= 3
64b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
65b01b1087SJonas Devlieghere 
66b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
67b01b1087SJonas Devlieghere 
68b01b1087SJonas Devlieghere #else
69b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
70b01b1087SJonas Devlieghere 
71b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
72b01b1087SJonas Devlieghere #endif
73b01b1087SJonas Devlieghere 
74049ae930SJonas Devlieghere #if defined(_WIN32)
75049ae930SJonas Devlieghere // Don't mess with the signal handlers on Windows.
76049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT 0
77049ae930SJonas Devlieghere #else
78049ae930SJonas Devlieghere // PyErr_SetInterrupt was introduced in 3.2.
79049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
80049ae930SJonas Devlieghere   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
81049ae930SJonas Devlieghere #endif
82b01b1087SJonas Devlieghere 
83d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
84d055e3a0SPedro Tammela   ScriptInterpreter *script_interpreter =
85d055e3a0SPedro Tammela       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
86d055e3a0SPedro Tammela   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
87d055e3a0SPedro Tammela }
88d055e3a0SPedro Tammela 
89b9c1b51eSKate Stone namespace {
9022c8efcdSZachary Turner 
9105097246SAdrian Prantl // Initializing Python is not a straightforward process.  We cannot control
9205097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
9305097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
9405097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
9505097246SAdrian Prantl // across our initialization.  We do this by using an RAII pattern where we
9605097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
97b9c1b51eSKate Stone struct InitializePythonRAII {
98079fe48aSZachary Turner public:
999494c510SJonas Devlieghere   InitializePythonRAII() {
100079fe48aSZachary Turner     InitializePythonHome();
101079fe48aSZachary Turner 
1029357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
1039357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
1049357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
1059357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
1069357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
1079357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
1089357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
1099357b5d0Sserge-sans-paille         break;
1109357b5d0Sserge-sans-paille       }
1119357b5d0Sserge-sans-paille     }
1129357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
1139357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
1149357b5d0Sserge-sans-paille       ReadlinePatched = true;
1159357b5d0Sserge-sans-paille     }
1169357b5d0Sserge-sans-paille #endif
1179357b5d0Sserge-sans-paille 
11874587a0eSVadim Chugunov     // Register _lldb as a built-in module.
11905495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
12074587a0eSVadim Chugunov 
121079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
122079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
123079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
124079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
125079fe48aSZachary Turner     Py_InitializeEx(0);
126079fe48aSZachary Turner     InitializeThreadsPrivate();
127079fe48aSZachary Turner #else
128079fe48aSZachary Turner     InitializeThreadsPrivate();
129079fe48aSZachary Turner     Py_InitializeEx(0);
130079fe48aSZachary Turner #endif
131079fe48aSZachary Turner   }
132079fe48aSZachary Turner 
133b9c1b51eSKate Stone   ~InitializePythonRAII() {
134b9c1b51eSKate Stone     if (m_was_already_initialized) {
135a007a6d8SPavel Labath       Log *log = GetLog(LLDBLog::Script);
1363b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1371b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
138079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
139b9c1b51eSKate Stone     } else {
140079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
141079fe48aSZachary Turner       PyEval_SaveThread();
142079fe48aSZachary Turner     }
143079fe48aSZachary Turner   }
144079fe48aSZachary Turner 
145079fe48aSZachary Turner private:
146b9c1b51eSKate Stone   void InitializePythonHome() {
1473ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
1483ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
1493ec3f62fSHaibo Huang     typedef wchar_t* str_type;
1503ec3f62fSHaibo Huang #else
1513ec3f62fSHaibo Huang     typedef char* str_type;
1523ec3f62fSHaibo Huang #endif
1533ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
1543ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
1553ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
1563ec3f62fSHaibo Huang       llvm::SmallString<64> path;
1573ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1583ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
1593ec3f62fSHaibo Huang       } else {
1603ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
1613ec3f62fSHaibo Huang         if (!spec)
1623ec3f62fSHaibo Huang           return nullptr;
1633ec3f62fSHaibo Huang         spec.GetPath(path);
1643ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
1653ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
1663ec3f62fSHaibo Huang       }
16722c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
16822c8efcdSZachary Turner       size_t size = 0;
1693ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
17022c8efcdSZachary Turner #else
1713ec3f62fSHaibo Huang       return strdup(absolute_python_home);
17222c8efcdSZachary Turner #endif
1733ec3f62fSHaibo Huang     }();
1743ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
175079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
1763ec3f62fSHaibo Huang     }
177386f00dbSDavide Italiano #else
178386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
17963dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
18063dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
1814f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
1824f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
1834f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
18463dd5d25SJonas Devlieghere     static char path[] =
18563dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
1864f9cb260SDavide Italiano     Py_SetPythonHome(path);
187386f00dbSDavide Italiano #endif
188386f00dbSDavide Italiano #endif
18922c8efcdSZachary Turner   }
19022c8efcdSZachary Turner 
191b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
1921b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1931b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
1941b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
1951b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
1961b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1971b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1981b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
1991b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
2001b6700efSTatyana Krasnukha     if (PyGILState_Check())
2011b6700efSTatyana Krasnukha       return;
2021b6700efSTatyana Krasnukha #endif
2031b6700efSTatyana Krasnukha 
204b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
205a007a6d8SPavel Labath       Log *log = GetLog(LLDBLog::Script);
206079fe48aSZachary Turner 
207079fe48aSZachary Turner       m_was_already_initialized = true;
208079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
2093b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
210079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
211079fe48aSZachary Turner       return;
212079fe48aSZachary Turner     }
213079fe48aSZachary Turner 
214079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
215079fe48aSZachary Turner     PyEval_InitThreads();
216079fe48aSZachary Turner   }
217079fe48aSZachary Turner 
2189494c510SJonas Devlieghere   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
2199494c510SJonas Devlieghere   bool m_was_already_initialized = false;
220079fe48aSZachary Turner };
221eb5c0ea6SJonas Devlieghere 
222eb5c0ea6SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
223eb5c0ea6SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores
224eb5c0ea6SJonas Devlieghere /// it at the end of the current scope.
225eb5c0ea6SJonas Devlieghere struct RestoreSignalHandlerScope {
226eb5c0ea6SJonas Devlieghere   /// The signal handler.
227eb5c0ea6SJonas Devlieghere   struct sigaction m_prev_handler;
228eb5c0ea6SJonas Devlieghere   int m_signal_code;
229eb5c0ea6SJonas Devlieghere   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
230eb5c0ea6SJonas Devlieghere     // Initialize sigaction to their default state.
231eb5c0ea6SJonas Devlieghere     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
232eb5c0ea6SJonas Devlieghere     // Don't install a new handler, just read back the old one.
233eb5c0ea6SJonas Devlieghere     struct sigaction *new_handler = nullptr;
234eb5c0ea6SJonas Devlieghere     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
235eb5c0ea6SJonas Devlieghere     lldbassert(signal_err == 0 && "sigaction failed to read handler");
236eb5c0ea6SJonas Devlieghere   }
237eb5c0ea6SJonas Devlieghere   ~RestoreSignalHandlerScope() {
238eb5c0ea6SJonas Devlieghere     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
239eb5c0ea6SJonas Devlieghere     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
240eb5c0ea6SJonas Devlieghere   }
241eb5c0ea6SJonas Devlieghere };
242eb5c0ea6SJonas Devlieghere #endif
24363dd5d25SJonas Devlieghere } // namespace
2442c1f46dcSZachary Turner 
2452df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
2462df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2472df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
2482df331b0SPavel Labath 
2492df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
2502df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2512df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
2522df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
2532df331b0SPavel Labath   if (framework == rend) {
25461f471a7SHaibo Huang     ComputePythonDir(path);
2552df331b0SPavel Labath     return;
2562df331b0SPavel Labath   }
2572df331b0SPavel Labath   path.resize(framework - rend);
2582df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2592df331b0SPavel Labath }
2602df331b0SPavel Labath 
26161f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
2622df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2632df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
2642df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
26561f471a7SHaibo Huang   // x86_64, or bin on Windows).
26661f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
26761f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2680016b450SHaibo Huang 
2690016b450SHaibo Huang #if defined(_WIN32)
2700016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
2710016b450SHaibo Huang   // so we need to normalize manually.
2720016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
2730016b450SHaibo Huang #endif
2742df331b0SPavel Labath }
2752df331b0SPavel Labath 
2762df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
2772df331b0SPavel Labath   static FileSpec g_spec = []() {
2782df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
2792df331b0SPavel Labath     if (!spec)
2802df331b0SPavel Labath       return FileSpec();
2812df331b0SPavel Labath     llvm::SmallString<64> path;
2822df331b0SPavel Labath     spec.GetPath(path);
2832df331b0SPavel Labath 
2842df331b0SPavel Labath #if defined(__APPLE__)
2852df331b0SPavel Labath     ComputePythonDirForApple(path);
2862df331b0SPavel Labath #else
28761f471a7SHaibo Huang     ComputePythonDir(path);
2882df331b0SPavel Labath #endif
2892df331b0SPavel Labath     spec.GetDirectory().SetString(path);
2902df331b0SPavel Labath     return spec;
2912df331b0SPavel Labath   }();
2922df331b0SPavel Labath   return g_spec;
2932df331b0SPavel Labath }
2942df331b0SPavel Labath 
2954c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"(
2964c2cf3a3SLawrence D'Anna import os
2974c2cf3a3SLawrence D'Anna import sys
2984c2cf3a3SLawrence D'Anna 
2994c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path):
3004c2cf3a3SLawrence D'Anna   info = {
3014c2cf3a3SLawrence D'Anna     "lldb-pythonpath": lldb_python_dir,
3024c2cf3a3SLawrence D'Anna     "language": "python",
3034c2cf3a3SLawrence D'Anna     "prefix": sys.prefix,
3044c2cf3a3SLawrence D'Anna     "executable": os.path.join(sys.prefix, python_exe_relative_path)
3054c2cf3a3SLawrence D'Anna   }
3064c2cf3a3SLawrence D'Anna   return info
3074c2cf3a3SLawrence D'Anna )";
3084c2cf3a3SLawrence D'Anna 
3094c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
3104c2cf3a3SLawrence D'Anna 
311bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
312bbef51ebSLawrence D'Anna   GIL gil;
313bbef51ebSLawrence D'Anna   FileSpec python_dir_spec = GetPythonDir();
314bbef51ebSLawrence D'Anna   if (!python_dir_spec)
315bbef51ebSLawrence D'Anna     return nullptr;
3164c2cf3a3SLawrence D'Anna   PythonScript get_info(GetInterpreterInfoScript);
3174c2cf3a3SLawrence D'Anna   auto info_json = unwrapIgnoringErrors(
3184c2cf3a3SLawrence D'Anna       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
3194c2cf3a3SLawrence D'Anna                                     PythonString(python_exe_relative_path))));
320bbef51ebSLawrence D'Anna   if (!info_json)
321bbef51ebSLawrence D'Anna     return nullptr;
322bbef51ebSLawrence D'Anna   return info_json.CreateStructuredDictionary();
323bbef51ebSLawrence D'Anna }
324bbef51ebSLawrence D'Anna 
325004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
326004a264fSPavel Labath     FileSpec &this_file) {
327004a264fSPavel Labath   // When we're loaded from python, this_file will point to the file inside the
328004a264fSPavel Labath   // python package directory. Replace it with the one in the lib directory.
329004a264fSPavel Labath #ifdef _WIN32
330004a264fSPavel Labath   // On windows, we need to manually back out of the python tree, and go into
331004a264fSPavel Labath   // the bin directory. This is pretty much the inverse of what ComputePythonDir
332004a264fSPavel Labath   // does.
333004a264fSPavel Labath   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
334004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
335004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // lldb
3362e826088SPavel Labath     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
3372e826088SPavel Labath     for (auto it = llvm::sys::path::begin(libdir),
3382e826088SPavel Labath               end = llvm::sys::path::end(libdir);
339004a264fSPavel Labath          it != end; ++it)
340004a264fSPavel Labath       this_file.RemoveLastPathComponent();
341004a264fSPavel Labath     this_file.AppendPathComponent("bin");
342004a264fSPavel Labath     this_file.AppendPathComponent("liblldb.dll");
343004a264fSPavel Labath   }
344004a264fSPavel Labath #else
345004a264fSPavel Labath   // The python file is a symlink, so we can find the real library by resolving
346004a264fSPavel Labath   // it. We can do this unconditionally.
347004a264fSPavel Labath   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
348004a264fSPavel Labath #endif
349004a264fSPavel Labath }
350004a264fSPavel Labath 
3515f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
35263dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
35363dd5d25SJonas Devlieghere }
35463dd5d25SJonas Devlieghere 
35563dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
35663dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
35763dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
35863dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
35963dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
36063dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
36163dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
362eb5c0ea6SJonas Devlieghere     ScriptInterpreterPythonImpl::Initialize();
36363dd5d25SJonas Devlieghere   });
36463dd5d25SJonas Devlieghere }
36563dd5d25SJonas Devlieghere 
36663dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
36763dd5d25SJonas Devlieghere 
36863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
36963dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
370b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
37163dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
37263dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
37363dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
37463dd5d25SJonas Devlieghere   DoAcquireLock();
37563dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
37663dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
37763dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
37863dd5d25SJonas Devlieghere       m_teardown_session = false;
37963dd5d25SJonas Devlieghere     }
38063dd5d25SJonas Devlieghere   }
38163dd5d25SJonas Devlieghere }
38263dd5d25SJonas Devlieghere 
38363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
384a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Script);
38563dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
38663dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
38763dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
38863dd5d25SJonas Devlieghere 
38963dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
39063dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
39163dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
39263dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
39363dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
39463dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
39563dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
39663dd5d25SJonas Devlieghere   return true;
39763dd5d25SJonas Devlieghere }
39863dd5d25SJonas Devlieghere 
39963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
400b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
401b07823f3SLawrence D'Anna                                                         FileSP err) {
40263dd5d25SJonas Devlieghere   if (!m_python_interpreter)
40363dd5d25SJonas Devlieghere     return false;
40463dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
40563dd5d25SJonas Devlieghere }
40663dd5d25SJonas Devlieghere 
40763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
408a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Script);
40963dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
41063dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
41163dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
41263dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
41363dd5d25SJonas Devlieghere   return true;
41463dd5d25SJonas Devlieghere }
41563dd5d25SJonas Devlieghere 
41663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
41763dd5d25SJonas Devlieghere   if (!m_python_interpreter)
41863dd5d25SJonas Devlieghere     return false;
41963dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
42063dd5d25SJonas Devlieghere   return true;
42163dd5d25SJonas Devlieghere }
42263dd5d25SJonas Devlieghere 
42363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
42463dd5d25SJonas Devlieghere   if (m_teardown_session)
42563dd5d25SJonas Devlieghere     DoTearDownSession();
42663dd5d25SJonas Devlieghere   DoFreeLock();
42763dd5d25SJonas Devlieghere }
42863dd5d25SJonas Devlieghere 
4298d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4308d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
43163dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
43263dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
43363dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
43463dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
4358d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
436ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
43764ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
438ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
4391f6a57c1SMed Ismail Bennani   m_scripted_process_interface_up =
4401f6a57c1SMed Ismail Bennani       std::make_unique<ScriptedProcessPythonInterface>(*this);
4411f6a57c1SMed Ismail Bennani 
44263dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
44363dd5d25SJonas Devlieghere   StreamString run_string;
44463dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
44563dd5d25SJonas Devlieghere 
44663dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
44763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
44863dd5d25SJonas Devlieghere 
44963dd5d25SJonas Devlieghere   run_string.Clear();
45063dd5d25SJonas Devlieghere   run_string.Printf(
45163dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
45263dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
45363dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
45463dd5d25SJonas Devlieghere 
45563dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
45663dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
45763dd5d25SJonas Devlieghere   run_string.Clear();
45863dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
45963dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
46063dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
46163dd5d25SJonas Devlieghere 
46263dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
46363dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
46463dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
46563dd5d25SJonas Devlieghere   // do their task
46663dd5d25SJonas Devlieghere   run_string.Clear();
46763dd5d25SJonas Devlieghere   run_string.Printf(
46863dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
46963dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
47063dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
47163dd5d25SJonas Devlieghere   run_string.Clear();
47263dd5d25SJonas Devlieghere 
47363dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
47463dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
47563dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
47663dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
47763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
47863dd5d25SJonas Devlieghere   run_string.Clear();
47963dd5d25SJonas Devlieghere 
48063dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
48163dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
4828d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
48363dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
48463dd5d25SJonas Devlieghere }
48563dd5d25SJonas Devlieghere 
48663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
48763dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
48863dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
48963dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
49063dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
49163dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
49263dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
49363dd5d25SJonas Devlieghere   m_session_dict.Reset();
49463dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
49563dd5d25SJonas Devlieghere }
49663dd5d25SJonas Devlieghere 
49763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
49863dd5d25SJonas Devlieghere                                                      bool interactive) {
4992c1f46dcSZachary Turner   const char *instructions = nullptr;
5002c1f46dcSZachary Turner 
501b9c1b51eSKate Stone   switch (m_active_io_handler) {
5022c1f46dcSZachary Turner   case eIOHandlerNone:
5032c1f46dcSZachary Turner     break;
5042c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
5052c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
5062c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
5072c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
5082c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
5092c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
5102c1f46dcSZachary Turner )";
5112c1f46dcSZachary Turner     break;
5122c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
5132c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
5142c1f46dcSZachary Turner     break;
5152c1f46dcSZachary Turner   }
5162c1f46dcSZachary Turner 
517b9c1b51eSKate Stone   if (instructions) {
5187ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5190affb582SDave Lee     if (output_sp && interactive) {
5202c1f46dcSZachary Turner       output_sp->PutCString(instructions);
5212c1f46dcSZachary Turner       output_sp->Flush();
5222c1f46dcSZachary Turner     }
5232c1f46dcSZachary Turner   }
5242c1f46dcSZachary Turner }
5252c1f46dcSZachary Turner 
52663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
527b9c1b51eSKate Stone                                                          std::string &data) {
5282c1f46dcSZachary Turner   io_handler.SetIsDone(true);
5298d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5302c1f46dcSZachary Turner 
531b9c1b51eSKate Stone   switch (m_active_io_handler) {
5322c1f46dcSZachary Turner   case eIOHandlerNone:
5332c1f46dcSZachary Turner     break;
534b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
535cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
536cfb96d84SJim Ingham         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
537cfb96d84SJim Ingham             io_handler.GetUserData();
538cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : *bp_options_vec) {
5392c1f46dcSZachary Turner 
540a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
541d5b44036SJonas Devlieghere       if (!data_up)
5424e4fbe82SZachary Turner         break;
543d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
5442c1f46dcSZachary Turner 
545738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
546d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
547738af7a6SJim Ingham                                                 data_up->script_source,
548738af7a6SJim Ingham                                                 false)
549b9c1b51eSKate Stone               .Success()) {
5504e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
551d5b44036SJonas Devlieghere             std::move(data_up));
552cfb96d84SJim Ingham         bp_options.SetCallback(
55363dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
554b9c1b51eSKate Stone       } else if (!batch_mode) {
5557ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
556b9c1b51eSKate Stone         if (error_sp) {
5572c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5582c1f46dcSZachary Turner           error_sp->Flush();
5592c1f46dcSZachary Turner         }
5602c1f46dcSZachary Turner       }
5612c1f46dcSZachary Turner     }
5622c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
563b9c1b51eSKate Stone   } break;
564b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
565b9c1b51eSKate Stone     WatchpointOptions *wp_options =
566b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
567a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
568d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
5692c1f46dcSZachary Turner 
570d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
571d5b44036SJonas Devlieghere                                               data_up->script_source)) {
5724e4fbe82SZachary Turner       auto baton_sp =
573d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
574b9c1b51eSKate Stone       wp_options->SetCallback(
57563dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
576b9c1b51eSKate Stone     } else if (!batch_mode) {
5777ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
578b9c1b51eSKate Stone       if (error_sp) {
5792c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
5802c1f46dcSZachary Turner         error_sp->Flush();
5812c1f46dcSZachary Turner       }
5822c1f46dcSZachary Turner     }
5832c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
584b9c1b51eSKate Stone   } break;
5852c1f46dcSZachary Turner   }
5862c1f46dcSZachary Turner }
5872c1f46dcSZachary Turner 
58863dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
5898d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5908d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
59163dd5d25SJonas Devlieghere }
5922c1f46dcSZachary Turner 
59363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
594a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Script);
5952c1f46dcSZachary Turner   if (log)
59663dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5972c1f46dcSZachary Turner 
59820b52c33SJonas Devlieghere   // Unset the LLDB global variables.
59920b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
60020b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
60120b52c33SJonas Devlieghere 
60205097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
60305097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
60405097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
60505097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
60605097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
6072c1f46dcSZachary Turner 
6082c1f46dcSZachary Turner   // rdar://problem/11292882
609b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
610b9c1b51eSKate Stone   // error.
611b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
6122c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
613b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
614b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
615f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
6162c1f46dcSZachary Turner         m_saved_stdin.Reset();
6172c1f46dcSZachary Turner       }
618b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
619f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6202c1f46dcSZachary Turner         m_saved_stdout.Reset();
6212c1f46dcSZachary Turner       }
622b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
623f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6242c1f46dcSZachary Turner         m_saved_stderr.Reset();
6252c1f46dcSZachary Turner       }
6262c1f46dcSZachary Turner     }
6272c1f46dcSZachary Turner   }
6282c1f46dcSZachary Turner 
6292c1f46dcSZachary Turner   m_session_is_active = false;
6302c1f46dcSZachary Turner }
6312c1f46dcSZachary Turner 
632b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
633b07823f3SLawrence D'Anna                                                const char *py_name,
634b07823f3SLawrence D'Anna                                                PythonObject &save_file,
635b9c1b51eSKate Stone                                                const char *mode) {
636b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
637b07823f3SLawrence D'Anna     save_file.Reset();
638b07823f3SLawrence D'Anna     return false;
639b07823f3SLawrence D'Anna   }
640b07823f3SLawrence D'Anna   File &file = *file_sp;
641b07823f3SLawrence D'Anna 
642a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
643a31baf08SGreg Clayton   file.Flush();
644a31baf08SGreg Clayton 
645a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
646a31baf08SGreg Clayton 
6470f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
6480f783599SLawrence D'Anna   if (!new_file) {
6490f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
6500f783599SLawrence D'Anna     return false;
6510f783599SLawrence D'Anna   }
6520f783599SLawrence D'Anna 
653b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
654a31baf08SGreg Clayton 
6550f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
656a31baf08SGreg Clayton   return true;
657a31baf08SGreg Clayton }
658a31baf08SGreg Clayton 
65963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
660b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
661b07823f3SLawrence D'Anna                                                FileSP err_sp) {
662b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
66305097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
664a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Script);
665b9c1b51eSKate Stone   if (m_session_is_active) {
66663e5fb76SJonas Devlieghere     LLDB_LOGF(
66763e5fb76SJonas Devlieghere         log,
66863dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
669b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
670b9c1b51eSKate Stone         on_entry_flags);
6712c1f46dcSZachary Turner     return false;
6722c1f46dcSZachary Turner   }
6732c1f46dcSZachary Turner 
67463e5fb76SJonas Devlieghere   LLDB_LOGF(
67563e5fb76SJonas Devlieghere       log,
67663e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
677b9c1b51eSKate Stone       on_entry_flags);
6782c1f46dcSZachary Turner 
6792c1f46dcSZachary Turner   m_session_is_active = true;
6802c1f46dcSZachary Turner 
6812c1f46dcSZachary Turner   StreamString run_string;
6822c1f46dcSZachary Turner 
683b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
684b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6858d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
686b9c1b51eSKate Stone     run_string.Printf(
687b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6888d1fb843SJonas Devlieghere         m_debugger.GetID());
6892c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6902c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6912c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6922c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6932c1f46dcSZachary Turner     run_string.PutCString("')");
694b9c1b51eSKate Stone   } else {
69505097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
69605097246SAdrian Prantl     // debugger (since that is always unique.)
697b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6988d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
699b9c1b51eSKate Stone     run_string.Printf(
700b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7018d1fb843SJonas Devlieghere         m_debugger.GetID());
7022c1f46dcSZachary Turner     run_string.PutCString("')");
7032c1f46dcSZachary Turner   }
7042c1f46dcSZachary Turner 
7052c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
7062c1f46dcSZachary Turner   run_string.Clear();
7072c1f46dcSZachary Turner 
7082c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
709b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
710b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
711b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
712b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
713b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
714b07823f3SLawrence D'Anna                                                  top_err_sp);
7152c1f46dcSZachary Turner 
716b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
7172c1f46dcSZachary Turner       m_saved_stdin.Reset();
718b9c1b51eSKate Stone     } else {
719b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
720b07823f3SLawrence D'Anna         if (top_in_sp)
721b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7222c1f46dcSZachary Turner       }
723a31baf08SGreg Clayton     }
724a31baf08SGreg Clayton 
725b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
726b07823f3SLawrence D'Anna       if (top_out_sp)
727b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
728a31baf08SGreg Clayton     }
729a31baf08SGreg Clayton 
730b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
731b07823f3SLawrence D'Anna       if (top_err_sp)
732b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
733a31baf08SGreg Clayton     }
7342c1f46dcSZachary Turner   }
7352c1f46dcSZachary Turner 
7362c1f46dcSZachary Turner   if (PyErr_Occurred())
7372c1f46dcSZachary Turner     PyErr_Clear();
7382c1f46dcSZachary Turner 
7392c1f46dcSZachary Turner   return true;
7402c1f46dcSZachary Turner }
7412c1f46dcSZachary Turner 
74204edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
743f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
74404edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7452c1f46dcSZachary Turner   return m_main_module;
7462c1f46dcSZachary Turner }
7472c1f46dcSZachary Turner 
74863dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
749f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
750f8b22f8fSZachary Turner     return m_session_dict;
751f8b22f8fSZachary Turner 
7522c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
753f8b22f8fSZachary Turner   if (!main_module.IsValid())
754f8b22f8fSZachary Turner     return m_session_dict;
755f8b22f8fSZachary Turner 
756b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
757b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
758f8b22f8fSZachary Turner   if (!main_dict.IsValid())
759f8b22f8fSZachary Turner     return m_session_dict;
760f8b22f8fSZachary Turner 
761722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
762722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7632c1f46dcSZachary Turner   return m_session_dict;
7642c1f46dcSZachary Turner }
7652c1f46dcSZachary Turner 
76663dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
767f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
768f8b22f8fSZachary Turner     return m_sys_module_dict;
769722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
770722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
7712c1f46dcSZachary Turner   return m_sys_module_dict;
7722c1f46dcSZachary Turner }
7732c1f46dcSZachary Turner 
774a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
775a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
776a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
777738af7a6SJim Ingham   if (callable_name.empty()) {
778738af7a6SJim Ingham     return llvm::createStringError(
779738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
780738af7a6SJim Ingham         "called with empty callable name.");
781738af7a6SJim Ingham   }
782738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
783738af7a6SJim Ingham                  Locker::InitSession |
784738af7a6SJim Ingham                  Locker::NoSTDIN);
785738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
786738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
787a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
788a69bbe02SLawrence D'Anna       callable_name, dict);
789738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
790738af7a6SJim Ingham     return llvm::createStringError(
791738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
792738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
793738af7a6SJim Ingham   }
794adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
795adbf64ccSLawrence D'Anna   if (!arg_info)
796adbf64ccSLawrence D'Anna     return arg_info.takeError();
797adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
798738af7a6SJim Ingham }
799738af7a6SJim Ingham 
800b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
8012c1f46dcSZachary Turner                                       uint32_t &functions_counter,
802b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
8032c1f46dcSZachary Turner   StreamString sstr;
8042c1f46dcSZachary Turner 
8052c1f46dcSZachary Turner   if (!base_name_wanted)
8062c1f46dcSZachary Turner     return std::string();
8072c1f46dcSZachary Turner 
8082c1f46dcSZachary Turner   if (!name_token)
8092c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
8102c1f46dcSZachary Turner   else
8112c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
8122c1f46dcSZachary Turner 
813adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
8142c1f46dcSZachary Turner }
8152c1f46dcSZachary Turner 
81663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
817f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
818f8b22f8fSZachary Turner     return true;
819f8b22f8fSZachary Turner 
820b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
821b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
822f8b22f8fSZachary Turner   if (!module.IsValid())
823f8b22f8fSZachary Turner     return false;
824f8b22f8fSZachary Turner 
825b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
826b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
827f8b22f8fSZachary Turner   if (!module_dict.IsValid())
828f8b22f8fSZachary Turner     return false;
829f8b22f8fSZachary Turner 
830b9c1b51eSKate Stone   m_run_one_line_function =
831b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
832b9c1b51eSKate Stone   m_run_one_line_str_global =
833b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
834f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
8352c1f46dcSZachary Turner }
8362c1f46dcSZachary Turner 
83763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8384d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
839b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
840d6c062bcSRaphael Isemann   std::string command_str = command.str();
841d6c062bcSRaphael Isemann 
8422c1f46dcSZachary Turner   if (!m_valid_session)
8432c1f46dcSZachary Turner     return false;
8442c1f46dcSZachary Turner 
8454d51a902SRaphael Isemann   if (!command.empty()) {
846b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
84705097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
84805097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
849b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
85005097246SAdrian Prantl     // we use the following more complicated method to pass the command string
85105097246SAdrian Prantl     // directly down to Python.
852d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
85384228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
85484228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
855d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
856d79273c9SJonas Devlieghere       if (result)
857d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
858d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
859d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
860d79273c9SJonas Devlieghere       else
861d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
8622fce1137SLawrence D'Anna       return false;
8632fce1137SLawrence D'Anna     }
864d79273c9SJonas Devlieghere 
865d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8662c1f46dcSZachary Turner 
86732064024SZachary Turner     bool success = false;
86832064024SZachary Turner     {
86905097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
87005097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
87105097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
87205097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
87305097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
87405097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
87505097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
87605097246SAdrian Prantl       // happen.
877b9c1b51eSKate Stone       Locker locker(
878b9c1b51eSKate Stone           this,
87963dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
88063dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8812c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
882d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
883d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
884d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
8852c1f46dcSZachary Turner 
8862c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
8872c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
888b9c1b51eSKate Stone       if (session_dict.IsValid()) {
889b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
890b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
891b9c1b51eSKate Stone             PythonObject pargs(
892b9c1b51eSKate Stone                 PyRefType::Owned,
893d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
894b9c1b51eSKate Stone             if (pargs.IsValid()) {
895b9c1b51eSKate Stone               PythonObject return_value(
896b9c1b51eSKate Stone                   PyRefType::Owned,
897b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
898b9c1b51eSKate Stone                                       pargs.get()));
899f8b22f8fSZachary Turner               if (return_value.IsValid())
9002c1f46dcSZachary Turner                 success = true;
901b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
9022c1f46dcSZachary Turner                 PyErr_Print();
9032c1f46dcSZachary Turner                 PyErr_Clear();
9042c1f46dcSZachary Turner               }
9052c1f46dcSZachary Turner             }
9062c1f46dcSZachary Turner           }
9072c1f46dcSZachary Turner         }
9082c1f46dcSZachary Turner       }
9092c1f46dcSZachary Turner 
910d79273c9SJonas Devlieghere       io_redirect.Flush();
9112c1f46dcSZachary Turner     }
9122c1f46dcSZachary Turner 
9132c1f46dcSZachary Turner     if (success)
9142c1f46dcSZachary Turner       return true;
9152c1f46dcSZachary Turner 
9162c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
9174d51a902SRaphael Isemann     if (result) {
918b9c1b51eSKate Stone       result->AppendErrorWithFormat(
9194d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9204d51a902SRaphael Isemann     }
9212c1f46dcSZachary Turner     return false;
9222c1f46dcSZachary Turner   }
9232c1f46dcSZachary Turner 
9242c1f46dcSZachary Turner   if (result)
9252c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
9262c1f46dcSZachary Turner   return false;
9272c1f46dcSZachary Turner }
9282c1f46dcSZachary Turner 
92963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
9305c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
9312c1f46dcSZachary Turner 
9328d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
9332c1f46dcSZachary Turner 
934b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
93505097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
93605097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
93705097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
93805097246SAdrian Prantl   // loop, so we won't do it.
9392c1f46dcSZachary Turner 
9407ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
9412c1f46dcSZachary Turner     return;
9422c1f46dcSZachary Turner 
9432c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
944b9c1b51eSKate Stone   if (io_handler_sp) {
9457ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
9462c1f46dcSZachary Turner   }
9472c1f46dcSZachary Turner }
9482c1f46dcSZachary Turner 
94963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
950049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
951049ae930SJonas Devlieghere   // If the interpreter isn't evaluating any Python at the moment then return
952049ae930SJonas Devlieghere   // false to signal that this function didn't handle the interrupt and the
953049ae930SJonas Devlieghere   // next component should try handling it.
954049ae930SJonas Devlieghere   if (!IsExecutingPython())
955049ae930SJonas Devlieghere     return false;
956049ae930SJonas Devlieghere 
957049ae930SJonas Devlieghere   // Tell Python that it should pretend to have received a SIGINT.
958049ae930SJonas Devlieghere   PyErr_SetInterrupt();
959049ae930SJonas Devlieghere   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
960049ae930SJonas Devlieghere   // signal got successfully handled and return true.
961049ae930SJonas Devlieghere   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
962049ae930SJonas Devlieghere   // the error handling is limited to checking the arguments which would be
963049ae930SJonas Devlieghere   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
964049ae930SJonas Devlieghere   return true;
965049ae930SJonas Devlieghere #else
966a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Script);
9672c1f46dcSZachary Turner 
968b9c1b51eSKate Stone   if (IsExecutingPython()) {
969b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
9702c1f46dcSZachary Turner     if (!state)
9712c1f46dcSZachary Turner       state = GetThreadState();
972b9c1b51eSKate Stone     if (state) {
9732c1f46dcSZachary Turner       long tid = state->thread_id;
97422c8efcdSZachary Turner       PyThreadState_Swap(state);
9752c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
97663e5fb76SJonas Devlieghere       LLDB_LOGF(log,
97763e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
978b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
979b9c1b51eSKate Stone                 tid, num_threads);
9802c1f46dcSZachary Turner       return true;
9812c1f46dcSZachary Turner     }
9822c1f46dcSZachary Turner   }
98363e5fb76SJonas Devlieghere   LLDB_LOGF(log,
98463dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
985b9c1b51eSKate Stone             "can't interrupt");
9862c1f46dcSZachary Turner   return false;
987049ae930SJonas Devlieghere #endif
9882c1f46dcSZachary Turner }
98904edd189SLawrence D'Anna 
99063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9914d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
992b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
9932c1f46dcSZachary Turner 
994f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
995f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
996f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
997f9517353SJonas Devlieghere 
998f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
999f9517353SJonas Devlieghere     llvm::consumeError(io_redirect_or_error.takeError());
1000f9517353SJonas Devlieghere     return false;
1001f9517353SJonas Devlieghere   }
1002f9517353SJonas Devlieghere 
1003f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1004f9517353SJonas Devlieghere 
100563dd5d25SJonas Devlieghere   Locker locker(this,
100663dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
100763dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1008b9c1b51eSKate Stone                     Locker::NoSTDIN,
1009f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1010f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1011f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
10122c1f46dcSZachary Turner 
101304edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
101404edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
10152c1f46dcSZachary Turner 
10162c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
101704edd189SLawrence D'Anna   if (!locals.IsValid())
1018722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1019722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1020f8b22f8fSZachary Turner   if (!locals.IsValid())
10212c1f46dcSZachary Turner     locals = globals;
10222c1f46dcSZachary Turner 
102304edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
102404edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
10252c1f46dcSZachary Turner 
102604edd189SLawrence D'Anna   if (!maybe_py_return) {
102704edd189SLawrence D'Anna     llvm::handleAllErrors(
102804edd189SLawrence D'Anna         maybe_py_return.takeError(),
102904edd189SLawrence D'Anna         [&](PythonException &E) {
103004edd189SLawrence D'Anna           E.Restore();
103104edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
103204edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
103304edd189SLawrence D'Anna               PyErr_Print();
10342c1f46dcSZachary Turner             }
103504edd189SLawrence D'Anna             PyErr_Clear();
103604edd189SLawrence D'Anna           }
103704edd189SLawrence D'Anna         },
103804edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
103904edd189SLawrence D'Anna     return false;
10402c1f46dcSZachary Turner   }
10412c1f46dcSZachary Turner 
104204edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
104304edd189SLawrence D'Anna   assert(py_return.IsValid());
104404edd189SLawrence D'Anna 
1045b9c1b51eSKate Stone   switch (return_type) {
10462c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
10472c1f46dcSZachary Turner   {
10482c1f46dcSZachary Turner     const char format[3] = "s#";
104904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10502c1f46dcSZachary Turner   }
1051b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1052b9c1b51eSKate Stone                                        // Py_None
10532c1f46dcSZachary Turner   {
10542c1f46dcSZachary Turner     const char format[3] = "z";
105504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10562c1f46dcSZachary Turner   }
1057b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
10582c1f46dcSZachary Turner     const char format[2] = "b";
105904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10602c1f46dcSZachary Turner   }
1061b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
10622c1f46dcSZachary Turner     const char format[2] = "h";
106304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10642c1f46dcSZachary Turner   }
1065b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
10662c1f46dcSZachary Turner     const char format[2] = "H";
106704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10682c1f46dcSZachary Turner   }
1069b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
10702c1f46dcSZachary Turner     const char format[2] = "i";
107104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10722c1f46dcSZachary Turner   }
1073b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
10742c1f46dcSZachary Turner     const char format[2] = "I";
107504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10762c1f46dcSZachary Turner   }
1077b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
10782c1f46dcSZachary Turner     const char format[2] = "l";
107904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10802c1f46dcSZachary Turner   }
1081b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
10822c1f46dcSZachary Turner     const char format[2] = "k";
108304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10842c1f46dcSZachary Turner   }
1085b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
10862c1f46dcSZachary Turner     const char format[2] = "L";
108704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10882c1f46dcSZachary Turner   }
1089b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
10902c1f46dcSZachary Turner     const char format[2] = "K";
109104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
109204edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
10932c1f46dcSZachary Turner   }
1094b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
10952c1f46dcSZachary Turner     const char format[2] = "f";
109604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10972c1f46dcSZachary Turner   }
1098b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
10992c1f46dcSZachary Turner     const char format[2] = "d";
110004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
11012c1f46dcSZachary Turner   }
1102b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
11032c1f46dcSZachary Turner     const char format[2] = "c";
110404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
11052c1f46dcSZachary Turner   }
1106b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
110704edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
110804edd189SLawrence D'Anna     return true;
11092c1f46dcSZachary Turner   }
11102c1f46dcSZachary Turner   }
11111dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
11122c1f46dcSZachary Turner }
11132c1f46dcSZachary Turner 
111463dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1115b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
111604edd189SLawrence D'Anna 
111704edd189SLawrence D'Anna   if (in_string == nullptr)
111804edd189SLawrence D'Anna     return Status();
11192c1f46dcSZachary Turner 
1120f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1121f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1122f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1123f9517353SJonas Devlieghere 
1124f9517353SJonas Devlieghere   if (!io_redirect_or_error)
1125f9517353SJonas Devlieghere     return Status(io_redirect_or_error.takeError());
1126f9517353SJonas Devlieghere 
1127f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1128f9517353SJonas Devlieghere 
112963dd5d25SJonas Devlieghere   Locker locker(this,
113063dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
113163dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1132b9c1b51eSKate Stone                     Locker::NoSTDIN,
1133f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1134f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1135f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
11362c1f46dcSZachary Turner 
113704edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
113804edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
11392c1f46dcSZachary Turner 
11402c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1141f8b22f8fSZachary Turner   if (!locals.IsValid())
1142722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1143722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1144f8b22f8fSZachary Turner   if (!locals.IsValid())
11452c1f46dcSZachary Turner     locals = globals;
11462c1f46dcSZachary Turner 
114704edd189SLawrence D'Anna   Expected<PythonObject> return_value =
114804edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
11492c1f46dcSZachary Turner 
115004edd189SLawrence D'Anna   if (!return_value) {
115104edd189SLawrence D'Anna     llvm::Error error =
115204edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
115304edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
115404edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
115504edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
115604edd189SLawrence D'Anna             E.Restore();
11572c1f46dcSZachary Turner           return error;
115804edd189SLawrence D'Anna         });
115904edd189SLawrence D'Anna     return Status(std::move(error));
116004edd189SLawrence D'Anna   }
116104edd189SLawrence D'Anna 
116204edd189SLawrence D'Anna   return Status();
11632c1f46dcSZachary Turner }
11642c1f46dcSZachary Turner 
116563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1166cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1167b9c1b51eSKate Stone     CommandReturnObject &result) {
11682c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
11698d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1170a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
11712c1f46dcSZachary Turner }
11722c1f46dcSZachary Turner 
117363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1174b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
11752c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
11768d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1177a6faf851SJonas Devlieghere       "    ", *this, wp_options);
11782c1f46dcSZachary Turner }
11792c1f46dcSZachary Turner 
1180738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1181cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *function_name,
1182738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1183738af7a6SJim Ingham   Status error;
11842c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
11852c1f46dcSZachary Turner   std::string oneliner("return ");
11862c1f46dcSZachary Turner   oneliner += function_name;
1187738af7a6SJim Ingham 
1188a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1189a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1190738af7a6SJim Ingham   if (!maybe_args) {
1191a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1192a69bbe02SLawrence D'Anna         "could not get num args: %s",
1193738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1194738af7a6SJim Ingham     return error;
1195738af7a6SJim Ingham   }
1196a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1197738af7a6SJim Ingham 
1198738af7a6SJim Ingham   bool uses_extra_args = false;
1199a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1200738af7a6SJim Ingham     uses_extra_args = true;
1201738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1202a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1203738af7a6SJim Ingham     if (extra_args_sp) {
1204738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1205738af7a6SJim Ingham                           );
1206738af7a6SJim Ingham       return error;
1207738af7a6SJim Ingham     }
1208738af7a6SJim Ingham     uses_extra_args = false;
12092c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1210738af7a6SJim Ingham   } else {
1211738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1212a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1213a69bbe02SLawrence D'Anna                                    function_name, max_args);
1214738af7a6SJim Ingham     return error;
1215738af7a6SJim Ingham   }
1216738af7a6SJim Ingham 
1217738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1218738af7a6SJim Ingham                                uses_extra_args);
1219738af7a6SJim Ingham   return error;
12202c1f46dcSZachary Turner }
12212c1f46dcSZachary Turner 
122263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1223cfb96d84SJim Ingham     BreakpointOptions &bp_options,
1224f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
122597206d57SZachary Turner   Status error;
1226f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1227738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1228738af7a6SJim Ingham                                                 false);
1229f7e07256SJim Ingham   if (error.Fail()) {
1230f7e07256SJim Ingham     return error;
1231f7e07256SJim Ingham   }
1232f7e07256SJim Ingham   auto baton_sp =
1233f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1234cfb96d84SJim Ingham   bp_options.SetCallback(
123563dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1236f7e07256SJim Ingham   return error;
1237f7e07256SJim Ingham }
1238f7e07256SJim Ingham 
123963dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1240cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text) {
1241738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1242738af7a6SJim Ingham }
12432c1f46dcSZachary Turner 
1244738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1245738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1246cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text,
1247cfb96d84SJim Ingham     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1248738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1249b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
125005097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
125105097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
125205097246SAdrian Prantl   // That is what the callback will actually invoke.
12532c1f46dcSZachary Turner 
1254d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1255d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1256738af7a6SJim Ingham                                                        data_up->script_source,
1257738af7a6SJim Ingham                                                        uses_extra_args);
1258b9c1b51eSKate Stone   if (error.Success()) {
12594e4fbe82SZachary Turner     auto baton_sp =
1260d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1261cfb96d84SJim Ingham     bp_options.SetCallback(
126263dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12632c1f46dcSZachary Turner     return error;
126493571c3cSJonas Devlieghere   }
12652c1f46dcSZachary Turner   return error;
12662c1f46dcSZachary Turner }
12672c1f46dcSZachary Turner 
12682c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
126963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1270b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1271a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12722c1f46dcSZachary Turner 
12732c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1274b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
127505097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
127605097246SAdrian Prantl   // actual callback.
12772c1f46dcSZachary Turner 
1278d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1279d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
12802c1f46dcSZachary Turner 
1281d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1282d5b44036SJonas Devlieghere                                             data_up->script_source)) {
12834e4fbe82SZachary Turner     auto baton_sp =
1284d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
128563dd5d25SJonas Devlieghere     wp_options->SetCallback(
128663dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12872c1f46dcSZachary Turner   }
12882c1f46dcSZachary Turner 
12892c1f46dcSZachary Turner   return;
12902c1f46dcSZachary Turner }
12912c1f46dcSZachary Turner 
129263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1293b9c1b51eSKate Stone     StringList &function_def) {
12942c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
12952c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
12962c1f46dcSZachary Turner 
129797206d57SZachary Turner   Status error = ExecuteMultipleLines(
1298b9c1b51eSKate Stone       function_def_string.c_str(),
1299fd2433e1SJonas Devlieghere       ExecuteScriptOptions().SetEnableIO(false));
13002c1f46dcSZachary Turner   return error;
13012c1f46dcSZachary Turner }
13022c1f46dcSZachary Turner 
130363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1304b9c1b51eSKate Stone                                                      const StringList &input) {
130597206d57SZachary Turner   Status error;
13062c1f46dcSZachary Turner   int num_lines = input.GetSize();
1307b9c1b51eSKate Stone   if (num_lines == 0) {
13082c1f46dcSZachary Turner     error.SetErrorString("No input data.");
13092c1f46dcSZachary Turner     return error;
13102c1f46dcSZachary Turner   }
13112c1f46dcSZachary Turner 
1312b9c1b51eSKate Stone   if (!signature || *signature == 0) {
13132c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
13142c1f46dcSZachary Turner     return error;
13152c1f46dcSZachary Turner   }
13162c1f46dcSZachary Turner 
13172c1f46dcSZachary Turner   StreamString sstr;
13182c1f46dcSZachary Turner   StringList auto_generated_function;
13192c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1320b9c1b51eSKate Stone   auto_generated_function.AppendString(
1321b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1322b9c1b51eSKate Stone   auto_generated_function.AppendString(
1323b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1324b9c1b51eSKate Stone                                                // session dict
1325b9c1b51eSKate Stone   auto_generated_function.AppendString(
1326b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1327b9c1b51eSKate Stone   auto_generated_function.AppendString(
1328b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1329b9c1b51eSKate Stone                                                   // to the
13302c1f46dcSZachary Turner   // global dictionary.
13312c1f46dcSZachary Turner 
13322c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
13332c1f46dcSZachary Turner 
13342c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1335b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
13362c1f46dcSZachary Turner     sstr.Clear();
13372c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
13382c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
13392c1f46dcSZachary Turner   }
1340b9c1b51eSKate Stone   auto_generated_function.AppendString(
1341b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1342b9c1b51eSKate Stone                                     // dict
1343b9c1b51eSKate Stone   auto_generated_function.AppendString(
1344b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1345b9c1b51eSKate Stone                                                          // values
1346b9c1b51eSKate Stone   auto_generated_function.AppendString(
1347b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1348b9c1b51eSKate Stone                                            // global dict
1349b9c1b51eSKate Stone   auto_generated_function.AppendString(
1350b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1351b9c1b51eSKate Stone                                             //  global dict
13522c1f46dcSZachary Turner 
13532c1f46dcSZachary Turner   // Verify that the results are valid Python.
13542c1f46dcSZachary Turner 
13552c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13562c1f46dcSZachary Turner 
13572c1f46dcSZachary Turner   return error;
13582c1f46dcSZachary Turner }
13592c1f46dcSZachary Turner 
136063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1361b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
13622c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13632c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13642c1f46dcSZachary Turner   StreamString sstr;
13652c1f46dcSZachary Turner 
13662c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13672c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13682c1f46dcSZachary Turner     return false;
13692c1f46dcSZachary Turner 
1370b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
137105097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
13722c1f46dcSZachary Turner 
1373b9c1b51eSKate Stone   std::string auto_generated_function_name(
1374b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1375b9c1b51eSKate Stone                          num_created_functions, name_token));
1376b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1377b9c1b51eSKate Stone               auto_generated_function_name.c_str());
13782c1f46dcSZachary Turner 
13792c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13802c1f46dcSZachary Turner     return false;
13812c1f46dcSZachary Turner 
13822c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
13832c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
13842c1f46dcSZachary Turner   return true;
13852c1f46dcSZachary Turner }
13862c1f46dcSZachary Turner 
138763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1388b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
13892c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13902c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13912c1f46dcSZachary Turner   StreamString sstr;
13922c1f46dcSZachary Turner 
13932c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13942c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13952c1f46dcSZachary Turner     return false;
13962c1f46dcSZachary Turner 
1397b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1398b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
13992c1f46dcSZachary Turner 
1400b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1401b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14022c1f46dcSZachary Turner 
14032c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14042c1f46dcSZachary Turner     return false;
14052c1f46dcSZachary Turner 
14062c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14072c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14082c1f46dcSZachary Turner   return true;
14092c1f46dcSZachary Turner }
14102c1f46dcSZachary Turner 
141163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
141263dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
14132c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
14142c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14152c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
14162c1f46dcSZachary Turner   StreamString sstr;
14172c1f46dcSZachary Turner 
14182c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14192c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14202c1f46dcSZachary Turner     return false;
14212c1f46dcSZachary Turner 
14222c1f46dcSZachary Turner   // Wrap all user input into a Python class
14232c1f46dcSZachary Turner 
1424b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1425b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14262c1f46dcSZachary Turner 
14272c1f46dcSZachary Turner   StringList auto_generated_class;
14282c1f46dcSZachary Turner 
14292c1f46dcSZachary Turner   // Create the function name & definition string.
14302c1f46dcSZachary Turner 
14312c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1432c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
14332c1f46dcSZachary Turner 
143405097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
143505097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
14362c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1437b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
14382c1f46dcSZachary Turner     sstr.Clear();
14392c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1440c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
14412c1f46dcSZachary Turner   }
14422c1f46dcSZachary Turner 
144305097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
144405097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14452c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
14462c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14472c1f46dcSZachary Turner     return false;
14482c1f46dcSZachary Turner 
14492c1f46dcSZachary Turner   // Store the name of the auto-generated class
14502c1f46dcSZachary Turner 
14512c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
14522c1f46dcSZachary Turner   return true;
14532c1f46dcSZachary Turner }
14542c1f46dcSZachary Turner 
145563dd5d25SJonas Devlieghere StructuredData::GenericSP
145663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
145741ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
145841ae8e74SKuba Mracek     return StructuredData::GenericSP();
145941ae8e74SKuba Mracek 
1460a6598575SRalf Grosse-Kunstleve   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1461c154f397SPavel Labath   PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
1462a6598575SRalf Grosse-Kunstleve       class_name, m_dictionary_name.c_str());
146341ae8e74SKuba Mracek 
1464c154f397SPavel Labath   return StructuredData::GenericSP(
1465c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
146641ae8e74SKuba Mracek }
146741ae8e74SKuba Mracek 
146863dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
146941ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
147041ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
147141ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
147241ae8e74SKuba Mracek 
147363dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
147463dd5d25SJonas Devlieghere     return ValueObjectListSP();
147541ae8e74SKuba Mracek 
147641ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
147763dd5d25SJonas Devlieghere   if (!generic)
147863dd5d25SJonas Devlieghere     return nullptr;
147941ae8e74SKuba Mracek 
148041ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
148141ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
148241ae8e74SKuba Mracek 
148363dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
148463dd5d25SJonas Devlieghere     return ValueObjectListSP();
148541ae8e74SKuba Mracek 
14869a14adeaSPavel Labath   PythonObject py_return(
14879a14adeaSPavel Labath       PyRefType::Owned,
14889a14adeaSPavel Labath       LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
148941ae8e74SKuba Mracek 
149041ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
149141ae8e74SKuba Mracek   if (PyErr_Occurred()) {
149241ae8e74SKuba Mracek     PyErr_Print();
149341ae8e74SKuba Mracek     PyErr_Clear();
149441ae8e74SKuba Mracek   }
149541ae8e74SKuba Mracek   if (py_return.get()) {
149641ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
149741ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
14988f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
149941ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
150041ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
150105495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
150205495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
150363dd5d25SJonas Devlieghere       if (valobj_sp)
150463dd5d25SJonas Devlieghere         result->Append(valobj_sp);
150541ae8e74SKuba Mracek     }
150641ae8e74SKuba Mracek     return result;
150741ae8e74SKuba Mracek   }
150841ae8e74SKuba Mracek   return ValueObjectListSP();
150941ae8e74SKuba Mracek }
151041ae8e74SKuba Mracek 
151163dd5d25SJonas Devlieghere StructuredData::GenericSP
151263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1513b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
15142c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
15152c1f46dcSZachary Turner     return StructuredData::GenericSP();
15162c1f46dcSZachary Turner 
15172c1f46dcSZachary Turner   if (!process_sp)
15182c1f46dcSZachary Turner     return StructuredData::GenericSP();
15192c1f46dcSZachary Turner 
1520a6598575SRalf Grosse-Kunstleve   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1521c154f397SPavel Labath   PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
152205495c5dSJonas Devlieghere       class_name, m_dictionary_name.c_str(), process_sp);
15232c1f46dcSZachary Turner 
1524c154f397SPavel Labath   return StructuredData::GenericSP(
1525c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
15262c1f46dcSZachary Turner }
15272c1f46dcSZachary Turner 
152863dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1529b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1530b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15312c1f46dcSZachary Turner 
15322c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
15332c1f46dcSZachary Turner 
15342c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15352c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15362c1f46dcSZachary Turner 
15372c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15382c1f46dcSZachary Turner   if (!generic)
15392c1f46dcSZachary Turner     return nullptr;
15402c1f46dcSZachary Turner 
1541b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1542b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
15432c1f46dcSZachary Turner 
1544f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15452c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15462c1f46dcSZachary Turner 
1547b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1548b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15492c1f46dcSZachary Turner 
15502c1f46dcSZachary Turner   if (PyErr_Occurred())
15512c1f46dcSZachary Turner     PyErr_Clear();
15522c1f46dcSZachary Turner 
1553f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15542c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15552c1f46dcSZachary Turner 
1556b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
15572c1f46dcSZachary Turner     if (PyErr_Occurred())
15582c1f46dcSZachary Turner       PyErr_Clear();
15592c1f46dcSZachary Turner 
15602c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15612c1f46dcSZachary Turner   }
15622c1f46dcSZachary Turner 
15632c1f46dcSZachary Turner   if (PyErr_Occurred())
15642c1f46dcSZachary Turner     PyErr_Clear();
15652c1f46dcSZachary Turner 
15662c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1567b9c1b51eSKate Stone   PythonObject py_return(
1568b9c1b51eSKate Stone       PyRefType::Owned,
1569b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15702c1f46dcSZachary Turner 
15712c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1572b9c1b51eSKate Stone   if (PyErr_Occurred()) {
15732c1f46dcSZachary Turner     PyErr_Print();
15742c1f46dcSZachary Turner     PyErr_Clear();
15752c1f46dcSZachary Turner   }
1576b9c1b51eSKate Stone   if (py_return.get()) {
1577f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
15782c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
15792c1f46dcSZachary Turner   }
158058b794aeSGreg Clayton   return StructuredData::DictionarySP();
158158b794aeSGreg Clayton }
15822c1f46dcSZachary Turner 
158363dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1584b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1585b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15862c1f46dcSZachary Turner 
15872c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
15882c1f46dcSZachary Turner 
15892c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15902c1f46dcSZachary Turner     return StructuredData::ArraySP();
15912c1f46dcSZachary Turner 
15922c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15932c1f46dcSZachary Turner   if (!generic)
15942c1f46dcSZachary Turner     return nullptr;
15952c1f46dcSZachary Turner 
1596b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1597b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1598f8b22f8fSZachary Turner 
1599f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16002c1f46dcSZachary Turner     return StructuredData::ArraySP();
16012c1f46dcSZachary Turner 
1602b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1603b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16042c1f46dcSZachary Turner 
16052c1f46dcSZachary Turner   if (PyErr_Occurred())
16062c1f46dcSZachary Turner     PyErr_Clear();
16072c1f46dcSZachary Turner 
1608f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16092c1f46dcSZachary Turner     return StructuredData::ArraySP();
16102c1f46dcSZachary Turner 
1611b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16122c1f46dcSZachary Turner     if (PyErr_Occurred())
16132c1f46dcSZachary Turner       PyErr_Clear();
16142c1f46dcSZachary Turner 
16152c1f46dcSZachary Turner     return StructuredData::ArraySP();
16162c1f46dcSZachary Turner   }
16172c1f46dcSZachary Turner 
16182c1f46dcSZachary Turner   if (PyErr_Occurred())
16192c1f46dcSZachary Turner     PyErr_Clear();
16202c1f46dcSZachary Turner 
16212c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1622b9c1b51eSKate Stone   PythonObject py_return(
1623b9c1b51eSKate Stone       PyRefType::Owned,
1624b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16252c1f46dcSZachary Turner 
16262c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1627b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16282c1f46dcSZachary Turner     PyErr_Print();
16292c1f46dcSZachary Turner     PyErr_Clear();
16302c1f46dcSZachary Turner   }
16312c1f46dcSZachary Turner 
1632b9c1b51eSKate Stone   if (py_return.get()) {
1633f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1634f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
16352c1f46dcSZachary Turner   }
163658b794aeSGreg Clayton   return StructuredData::ArraySP();
163758b794aeSGreg Clayton }
16382c1f46dcSZachary Turner 
163963dd5d25SJonas Devlieghere StructuredData::StringSP
164063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1641b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1642b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16432c1f46dcSZachary Turner 
16442c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1645b9c1b51eSKate Stone   static char *param_format =
1646b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
16472c1f46dcSZachary Turner 
16482c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16492c1f46dcSZachary Turner     return StructuredData::StringSP();
16502c1f46dcSZachary Turner 
16512c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16522c1f46dcSZachary Turner   if (!generic)
16532c1f46dcSZachary Turner     return nullptr;
1654b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1655b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
16562c1f46dcSZachary Turner 
1657f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16582c1f46dcSZachary Turner     return StructuredData::StringSP();
16592c1f46dcSZachary Turner 
1660b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1661b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16622c1f46dcSZachary Turner 
16632c1f46dcSZachary Turner   if (PyErr_Occurred())
16642c1f46dcSZachary Turner     PyErr_Clear();
16652c1f46dcSZachary Turner 
1666f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16672c1f46dcSZachary Turner     return StructuredData::StringSP();
16682c1f46dcSZachary Turner 
1669b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16702c1f46dcSZachary Turner     if (PyErr_Occurred())
16712c1f46dcSZachary Turner       PyErr_Clear();
16722c1f46dcSZachary Turner     return StructuredData::StringSP();
16732c1f46dcSZachary Turner   }
16742c1f46dcSZachary Turner 
16752c1f46dcSZachary Turner   if (PyErr_Occurred())
16762c1f46dcSZachary Turner     PyErr_Clear();
16772c1f46dcSZachary Turner 
16782c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1679b9c1b51eSKate Stone   PythonObject py_return(
1680b9c1b51eSKate Stone       PyRefType::Owned,
1681b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
16822c1f46dcSZachary Turner 
16832c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1684b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16852c1f46dcSZachary Turner     PyErr_Print();
16862c1f46dcSZachary Turner     PyErr_Clear();
16872c1f46dcSZachary Turner   }
1688f8b22f8fSZachary Turner 
1689b9c1b51eSKate Stone   if (py_return.get()) {
16907a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
16917a76845cSZachary Turner     return result.CreateStructuredString();
16922c1f46dcSZachary Turner   }
169358b794aeSGreg Clayton   return StructuredData::StringSP();
169458b794aeSGreg Clayton }
16952c1f46dcSZachary Turner 
169663dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1697b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1698b9c1b51eSKate Stone     lldb::addr_t context) {
1699b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17002c1f46dcSZachary Turner 
17012c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
17022c1f46dcSZachary Turner   std::string param_format;
17032c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
17042c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
17052c1f46dcSZachary Turner 
17062c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17072c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17082c1f46dcSZachary Turner 
17092c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17102c1f46dcSZachary Turner   if (!generic)
17112c1f46dcSZachary Turner     return nullptr;
17122c1f46dcSZachary Turner 
1713b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1714b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1715f8b22f8fSZachary Turner 
1716f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17172c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17182c1f46dcSZachary Turner 
1719b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1720b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17212c1f46dcSZachary Turner 
17222c1f46dcSZachary Turner   if (PyErr_Occurred())
17232c1f46dcSZachary Turner     PyErr_Clear();
17242c1f46dcSZachary Turner 
1725f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17262c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17272c1f46dcSZachary Turner 
1728b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17292c1f46dcSZachary Turner     if (PyErr_Occurred())
17302c1f46dcSZachary Turner       PyErr_Clear();
17312c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17322c1f46dcSZachary Turner   }
17332c1f46dcSZachary Turner 
17342c1f46dcSZachary Turner   if (PyErr_Occurred())
17352c1f46dcSZachary Turner     PyErr_Clear();
17362c1f46dcSZachary Turner 
17372c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1738b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1739b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1740b9c1b51eSKate Stone                                              &param_format[0], tid, context));
17412c1f46dcSZachary Turner 
17422c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1743b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17442c1f46dcSZachary Turner     PyErr_Print();
17452c1f46dcSZachary Turner     PyErr_Clear();
17462c1f46dcSZachary Turner   }
17472c1f46dcSZachary Turner 
1748b9c1b51eSKate Stone   if (py_return.get()) {
1749f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
17502c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
17512c1f46dcSZachary Turner   }
175258b794aeSGreg Clayton   return StructuredData::DictionarySP();
175358b794aeSGreg Clayton }
17542c1f46dcSZachary Turner 
175563dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
175682de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
1757a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
17582c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
17592c1f46dcSZachary Turner     return StructuredData::ObjectSP();
17602c1f46dcSZachary Turner 
17612c1f46dcSZachary Turner   if (!thread_plan_sp.get())
176293c98346SJim Ingham     return {};
17632c1f46dcSZachary Turner 
17642c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
176563dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1766d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
17672c1f46dcSZachary Turner 
1768d055e3a0SPedro Tammela   if (!python_interpreter)
176993c98346SJim Ingham     return {};
17702c1f46dcSZachary Turner 
1771b9c1b51eSKate Stone   Locker py_lock(this,
1772b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1773c154f397SPavel Labath   PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1774a6598575SRalf Grosse-Kunstleve       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1775a6598575SRalf Grosse-Kunstleve       error_str, thread_plan_sp);
177693c98346SJim Ingham   if (!ret_val)
177793c98346SJim Ingham     return {};
17782c1f46dcSZachary Turner 
1779c154f397SPavel Labath   return StructuredData::ObjectSP(
1780c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
17812c1f46dcSZachary Turner }
17822c1f46dcSZachary Turner 
178363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1784b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17852c1f46dcSZachary Turner   bool explains_stop = true;
17862c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
17872c1f46dcSZachary Turner   if (implementor_sp)
17882c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1789b9c1b51eSKate Stone   if (generic) {
1790b9c1b51eSKate Stone     Locker py_lock(this,
1791b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
179205495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1793b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
17942c1f46dcSZachary Turner     if (script_error)
17952c1f46dcSZachary Turner       return true;
17962c1f46dcSZachary Turner   }
17972c1f46dcSZachary Turner   return explains_stop;
17982c1f46dcSZachary Turner }
17992c1f46dcSZachary Turner 
180063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1801b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18022c1f46dcSZachary Turner   bool should_stop = true;
18032c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18042c1f46dcSZachary Turner   if (implementor_sp)
18052c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1806b9c1b51eSKate Stone   if (generic) {
1807b9c1b51eSKate Stone     Locker py_lock(this,
1808b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
180905495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
181005495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
18112c1f46dcSZachary Turner     if (script_error)
18122c1f46dcSZachary Turner       return true;
18132c1f46dcSZachary Turner   }
18142c1f46dcSZachary Turner   return should_stop;
18152c1f46dcSZachary Turner }
18162c1f46dcSZachary Turner 
181763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1818b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1819c915a7d2SJim Ingham   bool is_stale = true;
1820c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1821c915a7d2SJim Ingham   if (implementor_sp)
1822c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1823b9c1b51eSKate Stone   if (generic) {
1824b9c1b51eSKate Stone     Locker py_lock(this,
1825b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
182605495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
182705495c5dSJonas Devlieghere                                             nullptr, script_error);
1828c915a7d2SJim Ingham     if (script_error)
1829c915a7d2SJim Ingham       return true;
1830c915a7d2SJim Ingham   }
1831c915a7d2SJim Ingham   return is_stale;
1832c915a7d2SJim Ingham }
1833c915a7d2SJim Ingham 
183463dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1835b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
18362c1f46dcSZachary Turner   bool should_step = false;
18372c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18382c1f46dcSZachary Turner   if (implementor_sp)
18392c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1840b9c1b51eSKate Stone   if (generic) {
1841b9c1b51eSKate Stone     Locker py_lock(this,
1842b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
184305495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1844248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
18452c1f46dcSZachary Turner     if (script_error)
18462c1f46dcSZachary Turner       should_step = true;
18472c1f46dcSZachary Turner   }
18482c1f46dcSZachary Turner   if (should_step)
18492c1f46dcSZachary Turner     return lldb::eStateStepping;
18502c1f46dcSZachary Turner   return lldb::eStateRunning;
18512c1f46dcSZachary Turner }
18522c1f46dcSZachary Turner 
18533815e702SJim Ingham StructuredData::GenericSP
185463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
185582de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
18563815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
18573815e702SJim Ingham 
18583815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
18593815e702SJim Ingham     return StructuredData::GenericSP();
18603815e702SJim Ingham 
18613815e702SJim Ingham   if (!bkpt_sp.get())
18623815e702SJim Ingham     return StructuredData::GenericSP();
18633815e702SJim Ingham 
18643815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
186563dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1866d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
18673815e702SJim Ingham 
1868d055e3a0SPedro Tammela   if (!python_interpreter)
18693815e702SJim Ingham     return StructuredData::GenericSP();
18703815e702SJim Ingham 
18713815e702SJim Ingham   Locker py_lock(this,
18723815e702SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18733815e702SJim Ingham 
1874c154f397SPavel Labath   PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
187505495c5dSJonas Devlieghere       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
187605495c5dSJonas Devlieghere       bkpt_sp);
18773815e702SJim Ingham 
1878c154f397SPavel Labath   return StructuredData::GenericSP(
1879c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
18803815e702SJim Ingham }
18813815e702SJim Ingham 
188263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
188363dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
18843815e702SJim Ingham   bool should_continue = false;
18853815e702SJim Ingham 
18863815e702SJim Ingham   if (implementor_sp) {
18873815e702SJim Ingham     Locker py_lock(this,
18883815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
188905495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
189005495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
18913815e702SJim Ingham     if (PyErr_Occurred()) {
18923815e702SJim Ingham       PyErr_Print();
18933815e702SJim Ingham       PyErr_Clear();
18943815e702SJim Ingham     }
18953815e702SJim Ingham   }
18963815e702SJim Ingham   return should_continue;
18973815e702SJim Ingham }
18983815e702SJim Ingham 
18993815e702SJim Ingham lldb::SearchDepth
190063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
19013815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
19023815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
19033815e702SJim Ingham   if (implementor_sp) {
19043815e702SJim Ingham     Locker py_lock(this,
19053815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
190605495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
190705495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
19083815e702SJim Ingham     if (PyErr_Occurred()) {
19093815e702SJim Ingham       PyErr_Print();
19103815e702SJim Ingham       PyErr_Clear();
19113815e702SJim Ingham     }
19123815e702SJim Ingham   }
19133815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
19143815e702SJim Ingham     return lldb::eSearchDepthModule;
19153815e702SJim Ingham 
19163815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
19173815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
19183815e702SJim Ingham   return lldb::eSearchDepthModule;
19193815e702SJim Ingham }
19203815e702SJim Ingham 
19211b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
192282de8df2SPavel Labath     TargetSP target_sp, const char *class_name,
192382de8df2SPavel Labath     const StructuredDataImpl &args_data, Status &error) {
19241b1d9815SJim Ingham 
19251b1d9815SJim Ingham   if (!target_sp) {
19261b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
19271b1d9815SJim Ingham     return StructuredData::GenericSP();
19281b1d9815SJim Ingham   }
19291b1d9815SJim Ingham 
19301b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
19311b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
19321b1d9815SJim Ingham     return StructuredData::GenericSP();
19331b1d9815SJim Ingham   }
19341b1d9815SJim Ingham 
19351b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
1936d055e3a0SPedro Tammela       GetPythonInterpreter(m_debugger);
19371b1d9815SJim Ingham 
1938d055e3a0SPedro Tammela   if (!python_interpreter) {
19391b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
19401b1d9815SJim Ingham     return StructuredData::GenericSP();
19411b1d9815SJim Ingham   }
19421b1d9815SJim Ingham 
19431b1d9815SJim Ingham   Locker py_lock(this,
19441b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19451b1d9815SJim Ingham 
1946c154f397SPavel Labath   PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
19471b1d9815SJim Ingham       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
19481b1d9815SJim Ingham       args_data, error);
19491b1d9815SJim Ingham 
1950c154f397SPavel Labath   return StructuredData::GenericSP(
1951c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
19521b1d9815SJim Ingham }
19531b1d9815SJim Ingham 
19541b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
19551b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
19561b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
19571b1d9815SJim Ingham   assert(implementor_sp &&
19581b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
19591b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
19601b1d9815SJim Ingham 
19611b1d9815SJim Ingham   Locker py_lock(this,
19621b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19631b1d9815SJim Ingham 
19641b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
19651b1d9815SJim Ingham 
19661b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
19671b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
19681b1d9815SJim Ingham   return ret_val;
19691b1d9815SJim Ingham }
19701b1d9815SJim Ingham 
19712c1f46dcSZachary Turner StructuredData::ObjectSP
197263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
197397206d57SZachary Turner                                               lldb_private::Status &error) {
1974dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
19752c1f46dcSZachary Turner     error.SetErrorString("no such file");
19762c1f46dcSZachary Turner     return StructuredData::ObjectSP();
19772c1f46dcSZachary Turner   }
19782c1f46dcSZachary Turner 
19792c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
19802c1f46dcSZachary Turner 
1981f9517353SJonas Devlieghere   LoadScriptOptions load_script_options =
1982f9517353SJonas Devlieghere       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1983f9517353SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1984f9517353SJonas Devlieghere                           error, &module_sp))
19852c1f46dcSZachary Turner     return module_sp;
19862c1f46dcSZachary Turner 
19872c1f46dcSZachary Turner   return StructuredData::ObjectSP();
19882c1f46dcSZachary Turner }
19892c1f46dcSZachary Turner 
199063dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1991b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
199297206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
199305495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
19942c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19952c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
19962c1f46dcSZachary Turner   if (!generic)
19972c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19982c1f46dcSZachary Turner 
1999b9c1b51eSKate Stone   Locker py_lock(this,
2000b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20012c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
20022c1f46dcSZachary Turner 
200304edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
200404edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
200504edd189SLawrence D'Anna 
200604edd189SLawrence D'Anna   if (!setting)
200704edd189SLawrence D'Anna     return StructuredData::DictionarySP();
200804edd189SLawrence D'Anna 
200904edd189SLawrence D'Anna   PythonDictionary py_dict =
201004edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
201104edd189SLawrence D'Anna 
201204edd189SLawrence D'Anna   if (!py_dict)
201304edd189SLawrence D'Anna     return StructuredData::DictionarySP();
201404edd189SLawrence D'Anna 
20152c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
20162c1f46dcSZachary Turner }
20172c1f46dcSZachary Turner 
20182c1f46dcSZachary Turner StructuredData::ObjectSP
201963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2020b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
20212c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20222c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20232c1f46dcSZachary Turner 
20242c1f46dcSZachary Turner   if (!valobj.get())
20252c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20262c1f46dcSZachary Turner 
20272c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
20282c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
20292c1f46dcSZachary Turner 
20302c1f46dcSZachary Turner   if (!target)
20312c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20322c1f46dcSZachary Turner 
20332c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
203463dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2035d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
20362c1f46dcSZachary Turner 
2037d055e3a0SPedro Tammela   if (!python_interpreter)
20382c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20392c1f46dcSZachary Turner 
2040b9c1b51eSKate Stone   Locker py_lock(this,
2041b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2042c154f397SPavel Labath   PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
2043b9c1b51eSKate Stone       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
20442c1f46dcSZachary Turner 
2045c154f397SPavel Labath   return StructuredData::ObjectSP(
2046c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
20472c1f46dcSZachary Turner }
20482c1f46dcSZachary Turner 
20492c1f46dcSZachary Turner StructuredData::GenericSP
205063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
20518d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
20522c1f46dcSZachary Turner 
20532c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20542c1f46dcSZachary Turner     return StructuredData::GenericSP();
20552c1f46dcSZachary Turner 
20562c1f46dcSZachary Turner   if (!debugger_sp.get())
20572c1f46dcSZachary Turner     return StructuredData::GenericSP();
20582c1f46dcSZachary Turner 
2059b9c1b51eSKate Stone   Locker py_lock(this,
2060b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2061c154f397SPavel Labath   PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
206205495c5dSJonas Devlieghere       class_name, m_dictionary_name.c_str(), debugger_sp);
20632c1f46dcSZachary Turner 
2064c154f397SPavel Labath   return StructuredData::GenericSP(
2065c154f397SPavel Labath       new StructuredPythonObject(std::move(ret_val)));
20662c1f46dcSZachary Turner }
20672c1f46dcSZachary Turner 
206863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2069b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
20702c1f46dcSZachary Turner   StringList input;
20712c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20722c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
20732c1f46dcSZachary Turner }
20742c1f46dcSZachary Turner 
207563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
207663dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
20772c1f46dcSZachary Turner   StringList input;
20782c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20792c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
20802c1f46dcSZachary Turner }
20812c1f46dcSZachary Turner 
208263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2083738af7a6SJim Ingham     StringList &user_input, std::string &output,
2084738af7a6SJim Ingham     bool has_extra_args) {
20852c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
20862c1f46dcSZachary Turner   user_input.RemoveBlankLines();
20872c1f46dcSZachary Turner   StreamString sstr;
208897206d57SZachary Turner   Status error;
2089b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
20902c1f46dcSZachary Turner     error.SetErrorString("No input data.");
20912c1f46dcSZachary Turner     return error;
20922c1f46dcSZachary Turner   }
20932c1f46dcSZachary Turner 
2094b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2095b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2096738af7a6SJim Ingham   if (has_extra_args)
2097738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2098738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2099738af7a6SJim Ingham   else
2100b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2101b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
21022c1f46dcSZachary Turner 
21032c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
21042c1f46dcSZachary Turner   if (!error.Success())
21052c1f46dcSZachary Turner     return error;
21062c1f46dcSZachary Turner 
21072c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21082c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21092c1f46dcSZachary Turner   return error;
21102c1f46dcSZachary Turner }
21112c1f46dcSZachary Turner 
211263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2113b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
21142c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
21152c1f46dcSZachary Turner   user_input.RemoveBlankLines();
21162c1f46dcSZachary Turner   StreamString sstr;
21172c1f46dcSZachary Turner 
21182c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
21192c1f46dcSZachary Turner     return false;
21202c1f46dcSZachary Turner 
2121b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2122b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2123b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2124b9c1b51eSKate Stone               auto_generated_function_name.c_str());
21252c1f46dcSZachary Turner 
21262c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
21272c1f46dcSZachary Turner     return false;
21282c1f46dcSZachary Turner 
21292c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21302c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21312c1f46dcSZachary Turner   return true;
21322c1f46dcSZachary Turner }
21332c1f46dcSZachary Turner 
213463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2135b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2136b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2137b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
21382c1f46dcSZachary Turner 
21395c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
21402c1f46dcSZachary Turner 
2141b9c1b51eSKate Stone   if (!valobj.get()) {
21422c1f46dcSZachary Turner     retval.assign("<no object>");
21432c1f46dcSZachary Turner     return false;
21442c1f46dcSZachary Turner   }
21452c1f46dcSZachary Turner 
21462c1f46dcSZachary Turner   void *old_callee = nullptr;
21472c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2148b9c1b51eSKate Stone   if (callee_wrapper_sp) {
21492c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
21502c1f46dcSZachary Turner     if (generic)
21512c1f46dcSZachary Turner       old_callee = generic->GetValue();
21522c1f46dcSZachary Turner   }
21532c1f46dcSZachary Turner   void *new_callee = old_callee;
21542c1f46dcSZachary Turner 
21552c1f46dcSZachary Turner   bool ret_val;
2156b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
21572c1f46dcSZachary Turner     {
2158b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2159b9c1b51eSKate Stone                                Locker::NoSTDIN);
21602c1f46dcSZachary Turner       {
21612c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
21622c1f46dcSZachary Turner 
216305495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
216405495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
216505495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2166b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2167b9c1b51eSKate Stone             &new_callee, options_sp, retval);
21682c1f46dcSZachary Turner       }
21692c1f46dcSZachary Turner     }
2170b9c1b51eSKate Stone   } else {
21712c1f46dcSZachary Turner     retval.assign("<no function name>");
21722c1f46dcSZachary Turner     return false;
21732c1f46dcSZachary Turner   }
21742c1f46dcSZachary Turner 
2175a6598575SRalf Grosse-Kunstleve   if (new_callee && old_callee != new_callee) {
2176a6598575SRalf Grosse-Kunstleve     Locker py_lock(this,
2177a6598575SRalf Grosse-Kunstleve                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2178c154f397SPavel Labath     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2179c154f397SPavel Labath         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2180a6598575SRalf Grosse-Kunstleve   }
21812c1f46dcSZachary Turner 
21822c1f46dcSZachary Turner   return ret_val;
21832c1f46dcSZachary Turner }
21842c1f46dcSZachary Turner 
218563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2186b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2187b9c1b51eSKate Stone     user_id_t break_loc_id) {
2188f7e07256SJim Ingham   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
21892c1f46dcSZachary Turner   const char *python_function_name = bp_option_data->script_source.c_str();
21902c1f46dcSZachary Turner 
21912c1f46dcSZachary Turner   if (!context)
21922c1f46dcSZachary Turner     return true;
21932c1f46dcSZachary Turner 
21942c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
21952c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
21962c1f46dcSZachary Turner 
21972c1f46dcSZachary Turner   if (!target)
21982c1f46dcSZachary Turner     return true;
21992c1f46dcSZachary Turner 
22002c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
220163dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2202d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
22032c1f46dcSZachary Turner 
2204d055e3a0SPedro Tammela   if (!python_interpreter)
22052c1f46dcSZachary Turner     return true;
22062c1f46dcSZachary Turner 
2207b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
22082c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22092c1f46dcSZachary Turner     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2210b9c1b51eSKate Stone     if (breakpoint_sp) {
2211b9c1b51eSKate Stone       const BreakpointLocationSP bp_loc_sp(
2212b9c1b51eSKate Stone           breakpoint_sp->FindLocationByID(break_loc_id));
22132c1f46dcSZachary Turner 
2214b9c1b51eSKate Stone       if (stop_frame_sp && bp_loc_sp) {
22152c1f46dcSZachary Turner         bool ret_val = true;
22162c1f46dcSZachary Turner         {
2217b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2218b9c1b51eSKate Stone                                                  Locker::InitSession |
2219b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
2220a69bbe02SLawrence D'Anna           Expected<bool> maybe_ret_val =
2221a69bbe02SLawrence D'Anna               LLDBSwigPythonBreakpointCallbackFunction(
2222b9c1b51eSKate Stone                   python_function_name,
2223b9c1b51eSKate Stone                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
222482de8df2SPavel Labath                   bp_loc_sp, bp_option_data->m_extra_args);
2225a69bbe02SLawrence D'Anna 
2226a69bbe02SLawrence D'Anna           if (!maybe_ret_val) {
2227a69bbe02SLawrence D'Anna 
2228a69bbe02SLawrence D'Anna             llvm::handleAllErrors(
2229a69bbe02SLawrence D'Anna                 maybe_ret_val.takeError(),
2230a69bbe02SLawrence D'Anna                 [&](PythonException &E) {
2231a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.ReadBacktrace();
2232a69bbe02SLawrence D'Anna                 },
2233a69bbe02SLawrence D'Anna                 [&](const llvm::ErrorInfoBase &E) {
2234a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.message();
2235a69bbe02SLawrence D'Anna                 });
2236a69bbe02SLawrence D'Anna 
2237a69bbe02SLawrence D'Anna           } else {
2238a69bbe02SLawrence D'Anna             ret_val = maybe_ret_val.get();
2239a69bbe02SLawrence D'Anna           }
22402c1f46dcSZachary Turner         }
22412c1f46dcSZachary Turner         return ret_val;
22422c1f46dcSZachary Turner       }
22432c1f46dcSZachary Turner     }
22442c1f46dcSZachary Turner   }
22452c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
22462c1f46dcSZachary Turner   // trying to call the script function
22472c1f46dcSZachary Turner   return true;
22482c1f46dcSZachary Turner }
22492c1f46dcSZachary Turner 
225063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2251b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2252b9c1b51eSKate Stone   WatchpointOptions::CommandData *wp_option_data =
2253b9c1b51eSKate Stone       (WatchpointOptions::CommandData *)baton;
22542c1f46dcSZachary Turner   const char *python_function_name = wp_option_data->script_source.c_str();
22552c1f46dcSZachary Turner 
22562c1f46dcSZachary Turner   if (!context)
22572c1f46dcSZachary Turner     return true;
22582c1f46dcSZachary Turner 
22592c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
22602c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
22612c1f46dcSZachary Turner 
22622c1f46dcSZachary Turner   if (!target)
22632c1f46dcSZachary Turner     return true;
22642c1f46dcSZachary Turner 
22652c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
226663dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2267d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
22682c1f46dcSZachary Turner 
2269d055e3a0SPedro Tammela   if (!python_interpreter)
22702c1f46dcSZachary Turner     return true;
22712c1f46dcSZachary Turner 
2272b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
22732c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22742c1f46dcSZachary Turner     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2275b9c1b51eSKate Stone     if (wp_sp) {
2276b9c1b51eSKate Stone       if (stop_frame_sp && wp_sp) {
22772c1f46dcSZachary Turner         bool ret_val = true;
22782c1f46dcSZachary Turner         {
2279b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2280b9c1b51eSKate Stone                                                  Locker::InitSession |
2281b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
228205495c5dSJonas Devlieghere           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2283b9c1b51eSKate Stone               python_function_name,
2284b9c1b51eSKate Stone               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
22852c1f46dcSZachary Turner               wp_sp);
22862c1f46dcSZachary Turner         }
22872c1f46dcSZachary Turner         return ret_val;
22882c1f46dcSZachary Turner       }
22892c1f46dcSZachary Turner     }
22902c1f46dcSZachary Turner   }
22912c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
22922c1f46dcSZachary Turner   // trying to call the script function
22932c1f46dcSZachary Turner   return true;
22942c1f46dcSZachary Turner }
22952c1f46dcSZachary Turner 
229663dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2297b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
22982c1f46dcSZachary Turner   if (!implementor_sp)
22992c1f46dcSZachary Turner     return 0;
23002c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23012c1f46dcSZachary Turner   if (!generic)
23022c1f46dcSZachary Turner     return 0;
23039a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23042c1f46dcSZachary Turner   if (!implementor)
23052c1f46dcSZachary Turner     return 0;
23062c1f46dcSZachary Turner 
23072c1f46dcSZachary Turner   size_t ret_val = 0;
23082c1f46dcSZachary Turner 
23092c1f46dcSZachary Turner   {
2310b9c1b51eSKate Stone     Locker py_lock(this,
2311b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
231205495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
23132c1f46dcSZachary Turner   }
23142c1f46dcSZachary Turner 
23152c1f46dcSZachary Turner   return ret_val;
23162c1f46dcSZachary Turner }
23172c1f46dcSZachary Turner 
231863dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2319b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
23202c1f46dcSZachary Turner   if (!implementor_sp)
23212c1f46dcSZachary Turner     return lldb::ValueObjectSP();
23222c1f46dcSZachary Turner 
23232c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23242c1f46dcSZachary Turner   if (!generic)
23252c1f46dcSZachary Turner     return lldb::ValueObjectSP();
23269a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23272c1f46dcSZachary Turner   if (!implementor)
23282c1f46dcSZachary Turner     return lldb::ValueObjectSP();
23292c1f46dcSZachary Turner 
23302c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val;
23312c1f46dcSZachary Turner   {
2332b9c1b51eSKate Stone     Locker py_lock(this,
2333b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23349a14adeaSPavel Labath     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2335b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2336b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
233705495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
23382c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
23392c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
23402c1f46dcSZachary Turner       else
234105495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2342b9c1b51eSKate Stone     } else {
23432c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
23442c1f46dcSZachary Turner     }
23452c1f46dcSZachary Turner   }
23462c1f46dcSZachary Turner 
23472c1f46dcSZachary Turner   return ret_val;
23482c1f46dcSZachary Turner }
23492c1f46dcSZachary Turner 
235063dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2351b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
23522c1f46dcSZachary Turner   if (!implementor_sp)
23532c1f46dcSZachary Turner     return UINT32_MAX;
23542c1f46dcSZachary Turner 
23552c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23562c1f46dcSZachary Turner   if (!generic)
23572c1f46dcSZachary Turner     return UINT32_MAX;
23589a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23592c1f46dcSZachary Turner   if (!implementor)
23602c1f46dcSZachary Turner     return UINT32_MAX;
23612c1f46dcSZachary Turner 
23622c1f46dcSZachary Turner   int ret_val = UINT32_MAX;
23632c1f46dcSZachary Turner 
23642c1f46dcSZachary Turner   {
2365b9c1b51eSKate Stone     Locker py_lock(this,
2366b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
236705495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
23682c1f46dcSZachary Turner   }
23692c1f46dcSZachary Turner 
23702c1f46dcSZachary Turner   return ret_val;
23712c1f46dcSZachary Turner }
23722c1f46dcSZachary Turner 
237363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2374b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
23752c1f46dcSZachary Turner   bool ret_val = false;
23762c1f46dcSZachary Turner 
23772c1f46dcSZachary Turner   if (!implementor_sp)
23782c1f46dcSZachary Turner     return ret_val;
23792c1f46dcSZachary Turner 
23802c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23812c1f46dcSZachary Turner   if (!generic)
23822c1f46dcSZachary Turner     return ret_val;
23839a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23842c1f46dcSZachary Turner   if (!implementor)
23852c1f46dcSZachary Turner     return ret_val;
23862c1f46dcSZachary Turner 
23872c1f46dcSZachary Turner   {
2388b9c1b51eSKate Stone     Locker py_lock(this,
2389b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
239005495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
23912c1f46dcSZachary Turner   }
23922c1f46dcSZachary Turner 
23932c1f46dcSZachary Turner   return ret_val;
23942c1f46dcSZachary Turner }
23952c1f46dcSZachary Turner 
239663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2397b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
23982c1f46dcSZachary Turner   bool ret_val = false;
23992c1f46dcSZachary Turner 
24002c1f46dcSZachary Turner   if (!implementor_sp)
24012c1f46dcSZachary Turner     return ret_val;
24022c1f46dcSZachary Turner 
24032c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24042c1f46dcSZachary Turner   if (!generic)
24052c1f46dcSZachary Turner     return ret_val;
24069a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
24072c1f46dcSZachary Turner   if (!implementor)
24082c1f46dcSZachary Turner     return ret_val;
24092c1f46dcSZachary Turner 
24102c1f46dcSZachary Turner   {
2411b9c1b51eSKate Stone     Locker py_lock(this,
2412b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
241305495c5dSJonas Devlieghere     ret_val =
241405495c5dSJonas Devlieghere         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
24152c1f46dcSZachary Turner   }
24162c1f46dcSZachary Turner 
24172c1f46dcSZachary Turner   return ret_val;
24182c1f46dcSZachary Turner }
24192c1f46dcSZachary Turner 
242063dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2421b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24222c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val(nullptr);
24232c1f46dcSZachary Turner 
24242c1f46dcSZachary Turner   if (!implementor_sp)
24252c1f46dcSZachary Turner     return ret_val;
24262c1f46dcSZachary Turner 
24272c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24282c1f46dcSZachary Turner   if (!generic)
24292c1f46dcSZachary Turner     return ret_val;
24309a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
24312c1f46dcSZachary Turner   if (!implementor)
24322c1f46dcSZachary Turner     return ret_val;
24332c1f46dcSZachary Turner 
24342c1f46dcSZachary Turner   {
2435b9c1b51eSKate Stone     Locker py_lock(this,
2436b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24379a14adeaSPavel Labath     PyObject *child_ptr =
24389a14adeaSPavel Labath         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2439b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2440b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
244105495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24422c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
24432c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
24442c1f46dcSZachary Turner       else
244505495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2446b9c1b51eSKate Stone     } else {
24472c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
24482c1f46dcSZachary Turner     }
24492c1f46dcSZachary Turner   }
24502c1f46dcSZachary Turner 
24512c1f46dcSZachary Turner   return ret_val;
24522c1f46dcSZachary Turner }
24532c1f46dcSZachary Turner 
245463dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2455b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
2456b9c1b51eSKate Stone   Locker py_lock(this,
2457b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24586eec8d6cSEnrico Granata 
24596eec8d6cSEnrico Granata   static char callee_name[] = "get_type_name";
24606eec8d6cSEnrico Granata 
24616eec8d6cSEnrico Granata   ConstString ret_val;
24626eec8d6cSEnrico Granata   bool got_string = false;
24636eec8d6cSEnrico Granata   std::string buffer;
24646eec8d6cSEnrico Granata 
24656eec8d6cSEnrico Granata   if (!implementor_sp)
24666eec8d6cSEnrico Granata     return ret_val;
24676eec8d6cSEnrico Granata 
24686eec8d6cSEnrico Granata   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24696eec8d6cSEnrico Granata   if (!generic)
24706eec8d6cSEnrico Granata     return ret_val;
2471b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2472b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
24736eec8d6cSEnrico Granata   if (!implementor.IsAllocated())
24746eec8d6cSEnrico Granata     return ret_val;
24756eec8d6cSEnrico Granata 
2476b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2477b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
24786eec8d6cSEnrico Granata 
24796eec8d6cSEnrico Granata   if (PyErr_Occurred())
24806eec8d6cSEnrico Granata     PyErr_Clear();
24816eec8d6cSEnrico Granata 
24826eec8d6cSEnrico Granata   if (!pmeth.IsAllocated())
24836eec8d6cSEnrico Granata     return ret_val;
24846eec8d6cSEnrico Granata 
2485b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
24866eec8d6cSEnrico Granata     if (PyErr_Occurred())
24876eec8d6cSEnrico Granata       PyErr_Clear();
24886eec8d6cSEnrico Granata     return ret_val;
24896eec8d6cSEnrico Granata   }
24906eec8d6cSEnrico Granata 
24916eec8d6cSEnrico Granata   if (PyErr_Occurred())
24926eec8d6cSEnrico Granata     PyErr_Clear();
24936eec8d6cSEnrico Granata 
24946eec8d6cSEnrico Granata   // right now we know this function exists and is callable..
2495b9c1b51eSKate Stone   PythonObject py_return(
2496b9c1b51eSKate Stone       PyRefType::Owned,
2497b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
24986eec8d6cSEnrico Granata 
24996eec8d6cSEnrico Granata   // if it fails, print the error but otherwise go on
2500b9c1b51eSKate Stone   if (PyErr_Occurred()) {
25016eec8d6cSEnrico Granata     PyErr_Print();
25026eec8d6cSEnrico Granata     PyErr_Clear();
25036eec8d6cSEnrico Granata   }
25046eec8d6cSEnrico Granata 
2505b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
25066eec8d6cSEnrico Granata     PythonString py_string(PyRefType::Borrowed, py_return.get());
25076eec8d6cSEnrico Granata     llvm::StringRef return_data(py_string.GetString());
2508b9c1b51eSKate Stone     if (!return_data.empty()) {
25096eec8d6cSEnrico Granata       buffer.assign(return_data.data(), return_data.size());
25106eec8d6cSEnrico Granata       got_string = true;
25116eec8d6cSEnrico Granata     }
25126eec8d6cSEnrico Granata   }
25136eec8d6cSEnrico Granata 
25146eec8d6cSEnrico Granata   if (got_string)
25156eec8d6cSEnrico Granata     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
25166eec8d6cSEnrico Granata 
25176eec8d6cSEnrico Granata   return ret_val;
25186eec8d6cSEnrico Granata }
25196eec8d6cSEnrico Granata 
252063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
252163dd5d25SJonas Devlieghere     const char *impl_function, Process *process, std::string &output,
252297206d57SZachary Turner     Status &error) {
25232c1f46dcSZachary Turner   bool ret_val;
2524b9c1b51eSKate Stone   if (!process) {
25252c1f46dcSZachary Turner     error.SetErrorString("no process");
25262c1f46dcSZachary Turner     return false;
25272c1f46dcSZachary Turner   }
2528b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25292c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25302c1f46dcSZachary Turner     return false;
25312c1f46dcSZachary Turner   }
253205495c5dSJonas Devlieghere 
25332c1f46dcSZachary Turner   {
2534b9c1b51eSKate Stone     Locker py_lock(this,
2535b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
253605495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
25377f09ab08SPavel Labath         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
25387f09ab08SPavel Labath         output);
25392c1f46dcSZachary Turner     if (!ret_val)
25402c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
25412c1f46dcSZachary Turner   }
25422c1f46dcSZachary Turner   return ret_val;
25432c1f46dcSZachary Turner }
25442c1f46dcSZachary Turner 
254563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
254663dd5d25SJonas Devlieghere     const char *impl_function, Thread *thread, std::string &output,
254797206d57SZachary Turner     Status &error) {
2548b9c1b51eSKate Stone   if (!thread) {
25492c1f46dcSZachary Turner     error.SetErrorString("no thread");
25502c1f46dcSZachary Turner     return false;
25512c1f46dcSZachary Turner   }
2552b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25532c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25542c1f46dcSZachary Turner     return false;
25552c1f46dcSZachary Turner   }
255605495c5dSJonas Devlieghere 
2557b9c1b51eSKate Stone   Locker py_lock(this,
2558b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25597406d236SPavel Labath   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
25607406d236SPavel Labath           impl_function, m_dictionary_name.c_str(),
25617406d236SPavel Labath           thread->shared_from_this())) {
25627406d236SPavel Labath     output = std::move(*result);
25637406d236SPavel Labath     return true;
25642c1f46dcSZachary Turner   }
25657406d236SPavel Labath   error.SetErrorString("python script evaluation failed");
25667406d236SPavel Labath   return false;
25672c1f46dcSZachary Turner }
25682c1f46dcSZachary Turner 
256963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
257063dd5d25SJonas Devlieghere     const char *impl_function, Target *target, std::string &output,
257197206d57SZachary Turner     Status &error) {
25722c1f46dcSZachary Turner   bool ret_val;
2573b9c1b51eSKate Stone   if (!target) {
25742c1f46dcSZachary Turner     error.SetErrorString("no thread");
25752c1f46dcSZachary Turner     return false;
25762c1f46dcSZachary Turner   }
2577b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25782c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25792c1f46dcSZachary Turner     return false;
25802c1f46dcSZachary Turner   }
258105495c5dSJonas Devlieghere 
25822c1f46dcSZachary Turner   {
25832c1f46dcSZachary Turner     TargetSP target_sp(target->shared_from_this());
2584b9c1b51eSKate Stone     Locker py_lock(this,
2585b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
258605495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2587b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), target_sp, output);
25882c1f46dcSZachary Turner     if (!ret_val)
25892c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
25902c1f46dcSZachary Turner   }
25912c1f46dcSZachary Turner   return ret_val;
25922c1f46dcSZachary Turner }
25932c1f46dcSZachary Turner 
259463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
259563dd5d25SJonas Devlieghere     const char *impl_function, StackFrame *frame, std::string &output,
259697206d57SZachary Turner     Status &error) {
2597b9c1b51eSKate Stone   if (!frame) {
25982c1f46dcSZachary Turner     error.SetErrorString("no frame");
25992c1f46dcSZachary Turner     return false;
26002c1f46dcSZachary Turner   }
2601b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26022c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26032c1f46dcSZachary Turner     return false;
26042c1f46dcSZachary Turner   }
260505495c5dSJonas Devlieghere 
2606b9c1b51eSKate Stone   Locker py_lock(this,
2607b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
26087406d236SPavel Labath   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
26097406d236SPavel Labath           impl_function, m_dictionary_name.c_str(),
26107406d236SPavel Labath           frame->shared_from_this())) {
26117406d236SPavel Labath     output = std::move(*result);
26127406d236SPavel Labath     return true;
26132c1f46dcSZachary Turner   }
26147406d236SPavel Labath   error.SetErrorString("python script evaluation failed");
26157406d236SPavel Labath   return false;
26162c1f46dcSZachary Turner }
26172c1f46dcSZachary Turner 
261863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
261963dd5d25SJonas Devlieghere     const char *impl_function, ValueObject *value, std::string &output,
262097206d57SZachary Turner     Status &error) {
26212c1f46dcSZachary Turner   bool ret_val;
2622b9c1b51eSKate Stone   if (!value) {
26232c1f46dcSZachary Turner     error.SetErrorString("no value");
26242c1f46dcSZachary Turner     return false;
26252c1f46dcSZachary Turner   }
2626b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26272c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26282c1f46dcSZachary Turner     return false;
26292c1f46dcSZachary Turner   }
263005495c5dSJonas Devlieghere 
26312c1f46dcSZachary Turner   {
2632b9c1b51eSKate Stone     Locker py_lock(this,
2633b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
263405495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
26357f09ab08SPavel Labath         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
26362c1f46dcSZachary Turner     if (!ret_val)
26372c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26382c1f46dcSZachary Turner   }
26392c1f46dcSZachary Turner   return ret_val;
26402c1f46dcSZachary Turner }
26412c1f46dcSZachary Turner 
2642b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2643b9c1b51eSKate Stone                      const std::string &newStr) {
26442c1f46dcSZachary Turner   size_t pos = 0;
26452c1f46dcSZachary Turner   uint64_t matches = 0;
2646b9c1b51eSKate Stone   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
26472c1f46dcSZachary Turner     matches++;
26482c1f46dcSZachary Turner     str.replace(pos, oldStr.length(), newStr);
26492c1f46dcSZachary Turner     pos += newStr.length();
26502c1f46dcSZachary Turner   }
26512c1f46dcSZachary Turner   return matches;
26522c1f46dcSZachary Turner }
26532c1f46dcSZachary Turner 
265463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2655f9517353SJonas Devlieghere     const char *pathname, const LoadScriptOptions &options,
2656f9517353SJonas Devlieghere     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2657f9517353SJonas Devlieghere     FileSpec extra_search_dir) {
26583b33b416SJonas Devlieghere   namespace fs = llvm::sys::fs;
265900bb397bSJonas Devlieghere   namespace path = llvm::sys::path;
26603b33b416SJonas Devlieghere 
2661f9517353SJonas Devlieghere   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2662f9517353SJonas Devlieghere                                          .SetEnableIO(!options.GetSilent())
2663f9517353SJonas Devlieghere                                          .SetSetLLDBGlobals(false);
2664f9517353SJonas Devlieghere 
2665b9c1b51eSKate Stone   if (!pathname || !pathname[0]) {
26662c1f46dcSZachary Turner     error.SetErrorString("invalid pathname");
26672c1f46dcSZachary Turner     return false;
26682c1f46dcSZachary Turner   }
26692c1f46dcSZachary Turner 
2670f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2671f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2672f9517353SJonas Devlieghere           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2673f9517353SJonas Devlieghere 
2674f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
2675f9517353SJonas Devlieghere     error = io_redirect_or_error.takeError();
2676f9517353SJonas Devlieghere     return false;
2677f9517353SJonas Devlieghere   }
2678f9517353SJonas Devlieghere 
2679f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
26802c1f46dcSZachary Turner 
2681f9f36097SAdrian McCarthy   // Before executing Python code, lock the GIL.
268220b52c33SJonas Devlieghere   Locker py_lock(this,
268320b52c33SJonas Devlieghere                  Locker::AcquireLock |
2684f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::InitSession : 0) |
2685f9517353SJonas Devlieghere                      Locker::NoSTDIN,
2686b9c1b51eSKate Stone                  Locker::FreeAcquiredLock |
2687f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2688f9517353SJonas Devlieghere                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2689f9517353SJonas Devlieghere                  io_redirect.GetErrorFile());
26902c1f46dcSZachary Turner 
2691f9517353SJonas Devlieghere   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
269200bb397bSJonas Devlieghere     if (directory.empty()) {
269300bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
269400bb397bSJonas Devlieghere           "invalid directory name", llvm::inconvertibleErrorCode());
269542a9da7bSStefan Granitz     }
269642a9da7bSStefan Granitz 
2697f9f36097SAdrian McCarthy     replace_all(directory, "\\", "\\\\");
26982c1f46dcSZachary Turner     replace_all(directory, "'", "\\'");
26992c1f46dcSZachary Turner 
270000bb397bSJonas Devlieghere     // Make sure that Python has "directory" in the search path.
27012c1f46dcSZachary Turner     StreamString command_stream;
2702b9c1b51eSKate Stone     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2703b9c1b51eSKate Stone                           "sys.path.insert(1,'%s');\n\n",
2704b9c1b51eSKate Stone                           directory.c_str(), directory.c_str());
2705b9c1b51eSKate Stone     bool syspath_retval =
2706f9517353SJonas Devlieghere         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2707b9c1b51eSKate Stone     if (!syspath_retval) {
270800bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
270900bb397bSJonas Devlieghere           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
27102c1f46dcSZachary Turner     }
27112c1f46dcSZachary Turner 
271200bb397bSJonas Devlieghere     return llvm::Error::success();
271300bb397bSJonas Devlieghere   };
271400bb397bSJonas Devlieghere 
271500bb397bSJonas Devlieghere   std::string module_name(pathname);
2716d6e80578SJonas Devlieghere   bool possible_package = false;
271700bb397bSJonas Devlieghere 
271800bb397bSJonas Devlieghere   if (extra_search_dir) {
271900bb397bSJonas Devlieghere     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
272000bb397bSJonas Devlieghere       error = std::move(e);
272100bb397bSJonas Devlieghere       return false;
272200bb397bSJonas Devlieghere     }
272300bb397bSJonas Devlieghere   } else {
272400bb397bSJonas Devlieghere     FileSpec module_file(pathname);
272500bb397bSJonas Devlieghere     FileSystem::Instance().Resolve(module_file);
272600bb397bSJonas Devlieghere     FileSystem::Instance().Collect(module_file);
272700bb397bSJonas Devlieghere 
272800bb397bSJonas Devlieghere     fs::file_status st;
272900bb397bSJonas Devlieghere     std::error_code ec = status(module_file.GetPath(), st);
273000bb397bSJonas Devlieghere 
273100bb397bSJonas Devlieghere     if (ec || st.type() == fs::file_type::status_error ||
273200bb397bSJonas Devlieghere         st.type() == fs::file_type::type_unknown ||
273300bb397bSJonas Devlieghere         st.type() == fs::file_type::file_not_found) {
273400bb397bSJonas Devlieghere       // if not a valid file of any sort, check if it might be a filename still
273500bb397bSJonas Devlieghere       // dot can't be used but / and \ can, and if either is found, reject
273600bb397bSJonas Devlieghere       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
273700bb397bSJonas Devlieghere         error.SetErrorString("invalid pathname");
273800bb397bSJonas Devlieghere         return false;
273900bb397bSJonas Devlieghere       }
274000bb397bSJonas Devlieghere       // Not a filename, probably a package of some sort, let it go through.
2741d6e80578SJonas Devlieghere       possible_package = true;
274200bb397bSJonas Devlieghere     } else if (is_directory(st) || is_regular_file(st)) {
274300bb397bSJonas Devlieghere       if (module_file.GetDirectory().IsEmpty()) {
274400bb397bSJonas Devlieghere         error.SetErrorString("invalid directory name");
274500bb397bSJonas Devlieghere         return false;
274600bb397bSJonas Devlieghere       }
274700bb397bSJonas Devlieghere       if (llvm::Error e =
274800bb397bSJonas Devlieghere               ExtendSysPath(module_file.GetDirectory().GetCString())) {
274900bb397bSJonas Devlieghere         error = std::move(e);
275000bb397bSJonas Devlieghere         return false;
275100bb397bSJonas Devlieghere       }
275200bb397bSJonas Devlieghere       module_name = module_file.GetFilename().GetCString();
2753b9c1b51eSKate Stone     } else {
27542c1f46dcSZachary Turner       error.SetErrorString("no known way to import this module specification");
27552c1f46dcSZachary Turner       return false;
27562c1f46dcSZachary Turner     }
275700bb397bSJonas Devlieghere   }
27582c1f46dcSZachary Turner 
27591197ee35SJonas Devlieghere   // Strip .py or .pyc extension
276000bb397bSJonas Devlieghere   llvm::StringRef extension = llvm::sys::path::extension(module_name);
27611197ee35SJonas Devlieghere   if (!extension.empty()) {
27621197ee35SJonas Devlieghere     if (extension == ".py")
276300bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 3);
27641197ee35SJonas Devlieghere     else if (extension == ".pyc")
276500bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 4);
27661197ee35SJonas Devlieghere   }
27671197ee35SJonas Devlieghere 
2768d6e80578SJonas Devlieghere   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2769d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2770d6e80578SJonas Devlieghere         "Python does not allow dots in module names: %s", module_name.c_str());
2771d6e80578SJonas Devlieghere     return false;
2772d6e80578SJonas Devlieghere   }
2773d6e80578SJonas Devlieghere 
2774d6e80578SJonas Devlieghere   if (module_name.find('-') != llvm::StringRef::npos) {
2775d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2776d6e80578SJonas Devlieghere         "Python discourages dashes in module names: %s", module_name.c_str());
2777d6e80578SJonas Devlieghere     return false;
2778d6e80578SJonas Devlieghere   }
2779d6e80578SJonas Devlieghere 
2780f9517353SJonas Devlieghere   // Check if the module is already imported.
278100bb397bSJonas Devlieghere   StreamString command_stream;
27822c1f46dcSZachary Turner   command_stream.Clear();
278300bb397bSJonas Devlieghere   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
27842c1f46dcSZachary Turner   bool does_contain = false;
2785f9517353SJonas Devlieghere   // This call will succeed if the module was ever imported in any Debugger in
2786f9517353SJonas Devlieghere   // the lifetime of the process in which this LLDB framework is living.
2787f9517353SJonas Devlieghere   const bool does_contain_executed = ExecuteOneLineWithReturn(
2788b9c1b51eSKate Stone       command_stream.GetData(),
2789f9517353SJonas Devlieghere       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2790f9517353SJonas Devlieghere 
2791f9517353SJonas Devlieghere   const bool was_imported_globally = does_contain_executed && does_contain;
2792612384f6SJonas Devlieghere   const bool was_imported_locally =
2793612384f6SJonas Devlieghere       GetSessionDictionary()
279400bb397bSJonas Devlieghere           .GetItemForKey(PythonString(module_name))
2795b9c1b51eSKate Stone           .IsAllocated();
27962c1f46dcSZachary Turner 
27972c1f46dcSZachary Turner   // now actually do the import
27982c1f46dcSZachary Turner   command_stream.Clear();
27992c1f46dcSZachary Turner 
2800612384f6SJonas Devlieghere   if (was_imported_globally || was_imported_locally) {
28012c1f46dcSZachary Turner     if (!was_imported_locally)
280200bb397bSJonas Devlieghere       command_stream.Printf("import %s ; reload_module(%s)",
280300bb397bSJonas Devlieghere                             module_name.c_str(), module_name.c_str());
28042c1f46dcSZachary Turner     else
280500bb397bSJonas Devlieghere       command_stream.Printf("reload_module(%s)", module_name.c_str());
2806b9c1b51eSKate Stone   } else
280700bb397bSJonas Devlieghere     command_stream.Printf("import %s", module_name.c_str());
28082c1f46dcSZachary Turner 
2809f9517353SJonas Devlieghere   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
28102c1f46dcSZachary Turner   if (error.Fail())
28112c1f46dcSZachary Turner     return false;
28122c1f46dcSZachary Turner 
28132c1f46dcSZachary Turner   // if we are here, everything worked
28142c1f46dcSZachary Turner   // call __lldb_init_module(debugger,dict)
281500bb397bSJonas Devlieghere   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
28167406d236SPavel Labath                                     m_dictionary_name.c_str(),
28177406d236SPavel Labath                                     m_debugger.shared_from_this())) {
28182c1f46dcSZachary Turner     error.SetErrorString("calling __lldb_init_module failed");
28192c1f46dcSZachary Turner     return false;
28202c1f46dcSZachary Turner   }
28212c1f46dcSZachary Turner 
2822b9c1b51eSKate Stone   if (module_sp) {
28232c1f46dcSZachary Turner     // everything went just great, now set the module object
28242c1f46dcSZachary Turner     command_stream.Clear();
282500bb397bSJonas Devlieghere     command_stream.Printf("%s", module_name.c_str());
28262c1f46dcSZachary Turner     void *module_pyobj = nullptr;
2827b9c1b51eSKate Stone     if (ExecuteOneLineWithReturn(
2828b9c1b51eSKate Stone             command_stream.GetData(),
2829f9517353SJonas Devlieghere             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2830f9517353SJonas Devlieghere             exc_options) &&
2831b9c1b51eSKate Stone         module_pyobj)
2832c154f397SPavel Labath       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2833c154f397SPavel Labath           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
28342c1f46dcSZachary Turner   }
28352c1f46dcSZachary Turner 
28362c1f46dcSZachary Turner   return true;
28372c1f46dcSZachary Turner }
28382c1f46dcSZachary Turner 
283963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
28402c1f46dcSZachary Turner   if (!word || !word[0])
28412c1f46dcSZachary Turner     return false;
28422c1f46dcSZachary Turner 
28432c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
28442c1f46dcSZachary Turner 
284505097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
284605097246SAdrian Prantl   // clearly not keyword material anyway
284710b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
284810b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
28492c1f46dcSZachary Turner     return false;
28502c1f46dcSZachary Turner 
28512c1f46dcSZachary Turner   StreamString command_stream;
28522c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
28532c1f46dcSZachary Turner   bool result;
28542c1f46dcSZachary Turner   ExecuteScriptOptions options;
28552c1f46dcSZachary Turner   options.SetEnableIO(false);
28562c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
28572c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2858b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2859b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2860b9c1b51eSKate Stone                                &result, options))
28612c1f46dcSZachary Turner     return result;
28622c1f46dcSZachary Turner   return false;
28632c1f46dcSZachary Turner }
28642c1f46dcSZachary Turner 
286563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2866b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2867b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2868b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
28692c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
28702c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
28712c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
28722c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
28732c1f46dcSZachary Turner }
28742c1f46dcSZachary Turner 
287563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
28762c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
28772c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
28782c1f46dcSZachary Turner }
28792c1f46dcSZachary Turner 
288063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28814d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
28822c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
288397206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2884b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2885b9c1b51eSKate Stone   if (!impl_function) {
28862c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
28872c1f46dcSZachary Turner     return false;
28882c1f46dcSZachary Turner   }
28892c1f46dcSZachary Turner 
28908d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28912c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28922c1f46dcSZachary Turner 
2893b9c1b51eSKate Stone   if (!debugger_sp.get()) {
28942c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
28952c1f46dcSZachary Turner     return false;
28962c1f46dcSZachary Turner   }
28972c1f46dcSZachary Turner 
28982c1f46dcSZachary Turner   bool ret_val = false;
28992c1f46dcSZachary Turner 
29002c1f46dcSZachary Turner   std::string err_msg;
29012c1f46dcSZachary Turner 
29022c1f46dcSZachary Turner   {
29032c1f46dcSZachary Turner     Locker py_lock(this,
2904b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2905b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29062c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29072c1f46dcSZachary Turner 
2908b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29092c1f46dcSZachary Turner 
29104d51a902SRaphael Isemann     std::string args_str = args.str();
291105495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
291205495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
291305495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
29142c1f46dcSZachary Turner   }
29152c1f46dcSZachary Turner 
29162c1f46dcSZachary Turner   if (!ret_val)
29172c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29182c1f46dcSZachary Turner   else
29192c1f46dcSZachary Turner     error.Clear();
29202c1f46dcSZachary Turner 
29212c1f46dcSZachary Turner   return ret_val;
29222c1f46dcSZachary Turner }
29232c1f46dcSZachary Turner 
292463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29254d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
29262c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
292797206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2928b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2929b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
29302c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29312c1f46dcSZachary Turner     return false;
29322c1f46dcSZachary Turner   }
29332c1f46dcSZachary Turner 
29348d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29352c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29362c1f46dcSZachary Turner 
2937b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29382c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
29392c1f46dcSZachary Turner     return false;
29402c1f46dcSZachary Turner   }
29412c1f46dcSZachary Turner 
29422c1f46dcSZachary Turner   bool ret_val = false;
29432c1f46dcSZachary Turner 
29442c1f46dcSZachary Turner   std::string err_msg;
29452c1f46dcSZachary Turner 
29462c1f46dcSZachary Turner   {
29472c1f46dcSZachary Turner     Locker py_lock(this,
2948b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2949b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29502c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29512c1f46dcSZachary Turner 
2952b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29532c1f46dcSZachary Turner 
29544d51a902SRaphael Isemann     std::string args_str = args.str();
29559a14adeaSPavel Labath     ret_val = LLDBSwigPythonCallCommandObject(
29569a14adeaSPavel Labath         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
29579a14adeaSPavel Labath         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
29582c1f46dcSZachary Turner   }
29592c1f46dcSZachary Turner 
29602c1f46dcSZachary Turner   if (!ret_val)
29612c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29622c1f46dcSZachary Turner   else
29632c1f46dcSZachary Turner     error.Clear();
29642c1f46dcSZachary Turner 
29652c1f46dcSZachary Turner   return ret_val;
29662c1f46dcSZachary Turner }
29672c1f46dcSZachary Turner 
296893571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
296993571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
297093571c3cSJonas Devlieghere /// value is None.
297163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2972b9c1b51eSKate Stone                                                           std::string &dest) {
29732c1f46dcSZachary Turner   dest.clear();
297493571c3cSJonas Devlieghere 
29752c1f46dcSZachary Turner   if (!item || !*item)
29762c1f46dcSZachary Turner     return false;
297793571c3cSJonas Devlieghere 
29782c1f46dcSZachary Turner   std::string command(item);
29792c1f46dcSZachary Turner   command += ".__doc__";
29802c1f46dcSZachary Turner 
298193571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
298293571c3cSJonas Devlieghere   // returns successfully.
298393571c3cSJonas Devlieghere   char *result_ptr = nullptr;
29842c1f46dcSZachary Turner 
2985b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
298693571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
29872c1f46dcSZachary Turner           &result_ptr,
2988fd2433e1SJonas Devlieghere           ExecuteScriptOptions().SetEnableIO(false))) {
29892c1f46dcSZachary Turner     if (result_ptr)
29902c1f46dcSZachary Turner       dest.assign(result_ptr);
29912c1f46dcSZachary Turner     return true;
29922c1f46dcSZachary Turner   }
299393571c3cSJonas Devlieghere 
299493571c3cSJonas Devlieghere   StreamString str_stream;
299593571c3cSJonas Devlieghere   str_stream << "Function " << item
299693571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
299793571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
299893571c3cSJonas Devlieghere 
299993571c3cSJonas Devlieghere   return false;
30002c1f46dcSZachary Turner }
30012c1f46dcSZachary Turner 
300263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3003b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30042c1f46dcSZachary Turner   dest.clear();
30052c1f46dcSZachary Turner 
3006b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30072c1f46dcSZachary Turner 
30082c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
30092c1f46dcSZachary Turner 
30102c1f46dcSZachary Turner   if (!cmd_obj_sp)
30112c1f46dcSZachary Turner     return false;
30122c1f46dcSZachary Turner 
3013b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3014b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30152c1f46dcSZachary Turner 
3016f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30172c1f46dcSZachary Turner     return false;
30182c1f46dcSZachary Turner 
3019b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3020b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30212c1f46dcSZachary Turner 
30222c1f46dcSZachary Turner   if (PyErr_Occurred())
30232c1f46dcSZachary Turner     PyErr_Clear();
30242c1f46dcSZachary Turner 
3025f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30262c1f46dcSZachary Turner     return false;
30272c1f46dcSZachary Turner 
3028b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30292c1f46dcSZachary Turner     if (PyErr_Occurred())
30302c1f46dcSZachary Turner       PyErr_Clear();
30312c1f46dcSZachary Turner     return false;
30322c1f46dcSZachary Turner   }
30332c1f46dcSZachary Turner 
30342c1f46dcSZachary Turner   if (PyErr_Occurred())
30352c1f46dcSZachary Turner     PyErr_Clear();
30362c1f46dcSZachary Turner 
303793571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3038b9c1b51eSKate Stone   PythonObject py_return(
3039b9c1b51eSKate Stone       PyRefType::Owned,
3040b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30412c1f46dcSZachary Turner 
304293571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3043b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30442c1f46dcSZachary Turner     PyErr_Print();
30452c1f46dcSZachary Turner     PyErr_Clear();
30462c1f46dcSZachary Turner   }
30472c1f46dcSZachary Turner 
3048b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3049f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
305022c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
305122c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
305293571c3cSJonas Devlieghere     return true;
30532c1f46dcSZachary Turner   }
305493571c3cSJonas Devlieghere 
305593571c3cSJonas Devlieghere   return false;
30562c1f46dcSZachary Turner }
30572c1f46dcSZachary Turner 
305863dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3059b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
30602c1f46dcSZachary Turner   uint32_t result = 0;
30612c1f46dcSZachary Turner 
3062b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30632c1f46dcSZachary Turner 
30642c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
30652c1f46dcSZachary Turner 
30662c1f46dcSZachary Turner   if (!cmd_obj_sp)
30672c1f46dcSZachary Turner     return result;
30682c1f46dcSZachary Turner 
3069b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3070b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30712c1f46dcSZachary Turner 
3072f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30732c1f46dcSZachary Turner     return result;
30742c1f46dcSZachary Turner 
3075b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3076b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30772c1f46dcSZachary Turner 
30782c1f46dcSZachary Turner   if (PyErr_Occurred())
30792c1f46dcSZachary Turner     PyErr_Clear();
30802c1f46dcSZachary Turner 
3081f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30822c1f46dcSZachary Turner     return result;
30832c1f46dcSZachary Turner 
3084b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30852c1f46dcSZachary Turner     if (PyErr_Occurred())
30862c1f46dcSZachary Turner       PyErr_Clear();
30872c1f46dcSZachary Turner     return result;
30882c1f46dcSZachary Turner   }
30892c1f46dcSZachary Turner 
30902c1f46dcSZachary Turner   if (PyErr_Occurred())
30912c1f46dcSZachary Turner     PyErr_Clear();
30922c1f46dcSZachary Turner 
309352712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
309452712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
30952c1f46dcSZachary Turner 
30962c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3097b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30982c1f46dcSZachary Turner     PyErr_Print();
30992c1f46dcSZachary Turner     PyErr_Clear();
310052712d3fSLawrence D'Anna   } else {
310152712d3fSLawrence D'Anna     result = py_return;
31022c1f46dcSZachary Turner   }
31032c1f46dcSZachary Turner 
31042c1f46dcSZachary Turner   return result;
31052c1f46dcSZachary Turner }
31062c1f46dcSZachary Turner 
310763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3108b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31092c1f46dcSZachary Turner   bool got_string = false;
31102c1f46dcSZachary Turner   dest.clear();
31112c1f46dcSZachary Turner 
3112b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31132c1f46dcSZachary Turner 
31142c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
31152c1f46dcSZachary Turner 
31162c1f46dcSZachary Turner   if (!cmd_obj_sp)
31172c1f46dcSZachary Turner     return false;
31182c1f46dcSZachary Turner 
3119b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3120b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31212c1f46dcSZachary Turner 
3122f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31232c1f46dcSZachary Turner     return false;
31242c1f46dcSZachary Turner 
3125b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3126b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31272c1f46dcSZachary Turner 
31282c1f46dcSZachary Turner   if (PyErr_Occurred())
31292c1f46dcSZachary Turner     PyErr_Clear();
31302c1f46dcSZachary Turner 
3131f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31322c1f46dcSZachary Turner     return false;
31332c1f46dcSZachary Turner 
3134b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31352c1f46dcSZachary Turner     if (PyErr_Occurred())
31362c1f46dcSZachary Turner       PyErr_Clear();
31372c1f46dcSZachary Turner 
31382c1f46dcSZachary Turner     return false;
31392c1f46dcSZachary Turner   }
31402c1f46dcSZachary Turner 
31412c1f46dcSZachary Turner   if (PyErr_Occurred())
31422c1f46dcSZachary Turner     PyErr_Clear();
31432c1f46dcSZachary Turner 
31442c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3145b9c1b51eSKate Stone   PythonObject py_return(
3146b9c1b51eSKate Stone       PyRefType::Owned,
3147b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31482c1f46dcSZachary Turner 
31492c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3150b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31512c1f46dcSZachary Turner     PyErr_Print();
31522c1f46dcSZachary Turner     PyErr_Clear();
31532c1f46dcSZachary Turner   }
31542c1f46dcSZachary Turner 
3155b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3156f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
315722c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
315822c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
31592c1f46dcSZachary Turner     got_string = true;
31602c1f46dcSZachary Turner   }
31612c1f46dcSZachary Turner 
31622c1f46dcSZachary Turner   return got_string;
31632c1f46dcSZachary Turner }
31642c1f46dcSZachary Turner 
31652c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
316663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3167b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3168b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
31692c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
31702c1f46dcSZachary Turner   return py_lock;
31712c1f46dcSZachary Turner }
31722c1f46dcSZachary Turner 
3173eb5c0ea6SJonas Devlieghere void ScriptInterpreterPythonImpl::Initialize() {
31745c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
31752c1f46dcSZachary Turner 
3176b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
317705097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
317805097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
317905097246SAdrian Prantl   // initialization.
3180079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
31812c1f46dcSZachary Turner 
318205495c5dSJonas Devlieghere   LLDBSwigPyInit();
31832c1f46dcSZachary Turner 
3184b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3185b9c1b51eSKate Stone   // directory.
31862c1f46dcSZachary Turner 
31872c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
31882c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
31892c1f46dcSZachary Turner 
3190b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
319105097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
319205097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
319305097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
31942df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
31952c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
319660f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
31972c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31982c1f46dcSZachary Turner 
3199b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3200b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3201b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3202b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
3203049ae930SJonas Devlieghere 
3204049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
3205049ae930SJonas Devlieghere   // Python will not just overwrite its internal SIGINT handler but also the
3206049ae930SJonas Devlieghere   // one from the process. Backup the current SIGINT handler to prevent that
3207049ae930SJonas Devlieghere   // Python deletes it.
3208049ae930SJonas Devlieghere   RestoreSignalHandlerScope save_sigint(SIGINT);
3209049ae930SJonas Devlieghere 
3210049ae930SJonas Devlieghere   // Setup a default SIGINT signal handler that works the same way as the
3211049ae930SJonas Devlieghere   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3212049ae930SJonas Devlieghere   // Also make sure to not pollute the user's REPL with the signal module nor
3213049ae930SJonas Devlieghere   // our utility function.
3214049ae930SJonas Devlieghere   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3215049ae930SJonas Devlieghere                      "  import signal;\n"
3216049ae930SJonas Devlieghere                      "  def signal_handler(sig, frame):\n"
3217049ae930SJonas Devlieghere                      "    raise KeyboardInterrupt()\n"
3218049ae930SJonas Devlieghere                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3219049ae930SJonas Devlieghere                      "lldb_setup_sigint_handler();\n"
3220049ae930SJonas Devlieghere                      "del lldb_setup_sigint_handler\n");
3221049ae930SJonas Devlieghere #endif
32222c1f46dcSZachary Turner }
32232c1f46dcSZachary Turner 
322463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3225b9c1b51eSKate Stone                                                std::string path) {
32262c1f46dcSZachary Turner   std::string path_copy;
32272c1f46dcSZachary Turner 
32282c1f46dcSZachary Turner   std::string statement;
3229b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
32302c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
32312c1f46dcSZachary Turner     statement.append(path);
32322c1f46dcSZachary Turner     statement.append("\")");
3233b9c1b51eSKate Stone   } else {
32342c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
32352c1f46dcSZachary Turner     statement.append(path);
32362c1f46dcSZachary Turner     statement.append("\")");
32372c1f46dcSZachary Turner   }
32382c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
32392c1f46dcSZachary Turner }
32402c1f46dcSZachary Turner 
3241bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3242bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3243bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3244bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3245bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3246bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3247bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
324863dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
324963dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
325063dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
325163dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3252bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3253bcadb5a3SPavel Labath // when the process exits).
3254bcadb5a3SPavel Labath //
325563dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3256d68983e3SPavel Labath 
32574e26cf2cSJonas Devlieghere #endif
3258